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

• To: mathgroup at smc.vnet.net
• Subject: [mg72971] Re: [mg72958] Re: How to find the index of a maximal element in a list?
• From: János <janos.lobb at yale.edu>
• Date: Sat, 27 Jan 2007 05:33:36 -0500 (EST)
• References: <epa2rr\$iue\$1@smc.vnet.net> <200701261218.HAA09922@smc.vnet.net>

```On Jan 26, 2007, at 7:18 AM, Peter Pein wrote:

> 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

Now that begs the newbie question; if WRI should always probe what
parts of a program should be run as compiled.  I can imagine a "meta
parser" that invoked after you hit shift+command or select "evaluate
notebook" and wraps with Compile every part of the notebook that the
meta parser think it can be run as compiled.

Am I dreaming... or what ?

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: Different results for same integration
• Next by Date: Re: Different results for same integration
• 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?