Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
2007
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

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?

  • To: mathgroup at smc.vnet.net
  • Subject: [mg72947] Re: [mg72911] How to find the index of a maximal element in a list?
  • From: János <janos.lobb at yale.edu>
  • Date: Fri, 26 Jan 2007 06:34:29 -0500 (EST)
  • References: <200701251119.GAA19752@smc.vnet.net>

On Jan 25, 2007, at 6:19 AM, 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.

Well, my newbie instinct says that

Ordering[listName,-1]

might be your best bet.

In[1]:=
lst = Table[Random[Integer,
      {1, 10^7}], {i, 1,
      10^6}];

In[2]:=
Timing[Position[lst,
    Max[lst]]]
Out[2]=
{0.4704309999999996*Second,
   {{653015}}}

In[3]:=
Timing[Last[Last[First[
      Last[Reap[a = -1; i = 1;
         Scan[(If[#1 >= a,
           a = #1; Sow[{a,
           i}], Null];
           i++; ) & ,
          lst]; ]]]]]]
Out[3]=
{8.194379000000001*Second,
   653015}

In[4]:=
Timing[Ordering[lst, -1]]
Out[4]=
{0.02305199999999985*Second,
   {653015}}



János


----------------------------------------------
Trying to argue with a politician is like lifting up the head of a  
corpse.
(S. Lem: His Master Voice)


  • Prev by Date: Re: 2D interpolation
  • Next by Date: can't InstallJava[] on Linux-x86-64 to Import an xls file
  • 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?