We can use Max[exampleList] or Min[exampleList] to find the maxima and minima of exampleList, however, is there a similar standalone function that returns something like {position in array, maximum value in the array} or {position in array, minimum value in the array}, i.e. both the position and value of the maximum or minimum element in exampleList? It seems awkward to have to write Position[exampleList,Max[exampleList]] or Position[exampleList,Min[exampleList]]?
Asked
Active
Viewed 4.5k times
21
Geof
- 221
- 1
- 2
- 4
-
2Take a look at http://reference.wolfram.com/mathematica/ref/Ordering.html for the position. – dr.blochwave Apr 09 '14 at 08:55
-
@blochwave Yes, thank you, that's what I was looking for. – Geof Apr 09 '14 at 09:00
-
Related: (900), (1342), (2177) – Mr.Wizard Apr 09 '14 at 09:57
1 Answers
32
Position[list,_?(#==Max[list]&)]
or shorter (per your comment...)
Position[list,Max[list]]
will do the trick, obviously change Max to Min for minimum...
Or, as suggested in comments
Ordering[list,1]
Ordering[list,-1]
Will give positions of minimum and maximum, respectively.
Computation times
order[n_] := Block[{},
list = RandomReal[1, n];
t1 = (Position[list, Min@list]; // RepeatedTiming // First);
t2 = (Ordering[list, 1]; // RepeatedTiming // First);
{{n, t1}, {n, t2}}]
tab = ParallelTable[order[Floor[1.1^n]], {n, 1, 100, 1}];
ListLogLogPlot[{tab[[All, 1]], tab[[All, 2]]}]
Ordering is much faster.
-
Why can't we just write
Position[exampleList,Max[exampleList]]? Sorry, I wrote that just as you were posting this answer. – Geof Apr 09 '14 at 08:56 -
@Geof: Well, for one thing, that's incomplete. The first argument to
Positionis the target list, andMaxdoes not return a list... – ciao Apr 09 '14 at 08:57 -
-
Sorry, that was a typo, I fixed the comment. I meant, why can't "(#==Max[list]&)" just be "Max[exampleList]"? – Geof Apr 09 '14 at 08:58
-
@geof: you can, I'm just in the habit of having complex functions there... – ciao Apr 09 '14 at 08:59
-
-
This solution does not seem to work correctly when precision numbers are involved, see my question https://mathematica.stackexchange.com/q/265106/45020. Any thoughts? – Kvothe Mar 14 '22 at 11:13
