Re: How to find the index of a maximal element in a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg72944] Re: How to find the index of a maximal element in a list?
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Fri, 26 Jan 2007 06:22:27 -0500 (EST)
- Organization: The Open University, Milton Keynes, UK
- References: <epa2rr$iue$1@smc.vnet.net>
Valter Sorana wrote:
> I may have a mental block, but I cannot find anything better than
>
> Position[listName,Max[listName]]
>
> that traverses the list twice - once to find the maximum and once to find where it is.
>
> Isn't there a way to get both the index and the max value in one go?
>
> (of course one could write a loop that does this, but I want to avoid loops)
>
> Thanks,
>
> Valter.
>
Hi Valter,
You could use the function Ordering [1] with its last argument set to
-1. (Ordering[list, -n] gives the positions of the last n elements of
Sort[list]; consequently, Ordering[list, -1] gives the position of the
largest element in list.)
In[1]:=
lst=Table[Random[], {10^7}];
In[2]:=
Position[lst,Max[lst]]//Timing
Out[2]=
{13.266 Second,{{8204211}}}
In[3]:=
Ordering[lst,-1]//Timing
Out[3]=
{0.125 Second,{8204211}}
Regards,
Jean-Marc
[1] http://documents.wolfram.com/mathematica/functions/Ordering