MathGroup Archive 2007

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: How to find the index of a maximal element in a list?


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


  • Prev by Date: Re: How to find the index of a maximal element in a list?
  • Next by Date: Re: 2D interpolation
  • Previous by thread: Re: How to find the index of a maximal element in a list?
  • Next by thread: Re: How to find the index of a maximal element in a list?