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: [mg72958] Re: How to find the index of a maximal element in a list?
  • From: Peter Pein <petsie at dordos.net>
  • Date: Fri, 26 Jan 2007 07:18:37 -0500 (EST)
  • References: <epa2rr$iue$1@smc.vnet.net>

Valter Sorana schrieb:
> 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,

if your data is in the range which can be handled by compiled functions, you
might want to try a compiled Scan[].

testit[f_, r_: {3,7}]:=
(SeedRandom[13];
((data=Table[Random[],{10^#1}];Timing[f[data]])&)/@(Range@@r));

testit[Position[#,Max[#],1,1][[1,1]]&]
Out[2]=
{{0.    Second, 243},
 {0.    Second, 5935},
 {0.062 Second, 72435},
 {0.312 Second, 238526},
 {6.797 Second, 5922868}}

This came to my mind, but it sorts the indices of the list and runs longer:

testit[Last[Ordering[#]]&]

{{0.    Second, 243},
 {0.    Second, 5935},
 {0.046 Second, 72435},
 {0.625 Second, 238526},
 {9.172 Second, 5922868}}

My suggestion:

testit[Compile[{{lst,_Real,1}},
  Module[{mx=First[lst],ix=0,n=1},
    Scan[(If[#>mx,mx=#;ix=n];n++)&,Rest[lst]];
  ix],
 {{mx,_Real},{ix|n,_Integer}}]]

{{0.    Second, 242},
 {0.    Second, 5934},
 {0.031 Second, 72434},
 {0.281 Second, 238525},
 {2.828 Second, 5922867}}

But do not try it uncompiled:

testit[Module[{mx=First[#],ix=1,n=1},
 Scan[(If[#>mx,mx=#;ix=n];n++)&,Rest[#]]; ix]&]

{{ 0.015 Second, 242},
 { 0.047 Second, 5934},
 { 0.453 Second, 72434},
 { 4.469 Second, 238525},
 {45.484 Second, 5922867}}

hth,
Peter


  • Prev by Date: Re: Re: pdf
  • Next by Date: Re: NDSolve EventLocator Method question about the Event option
  • Previous by thread: Re: How to find the index of a maximal element in a list?
  • Next by thread: Re: Re: How to find the index of a maximal element in a list?