Re: How to find the index of a maximal element in a list?
- To: mathgroup at smc.vnet.net
- Subject: [mg72977] Re: How to find the index of a maximal element in a list?
- From: Peter Pein <petsie at dordos.net>
- Date: Sat, 27 Jan 2007 05:57:41 -0500 (EST)
- References: <epa2rr$iue$1@smc.vnet.net> <epco7n$8cr$1@smc.vnet.net>
Peter Pein schrieb:
> 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:
well due to the limited capacity of my mind, I didn't remember the form
Ordering[list,-1]...
>
> testit[Last[Ordering[#]]&]
>
> {{0. Second, 243},
> {0. Second, 5935},
> {0.046 Second, 72435},
> {0.625 Second, 238526},
> {9.172 Second, 5922868}}
>
...
testit[First[Ordering[#,-1]]&]
{{0. Second, 243},
{0. Second, 5935},
{0. Second, 72435},
{0.015 Second, 238526},
{0.109 Second, 5922868}}
is of course the fastest known way so far to get the desired result until Carl
Woll finds a better one ;-)
P²