I have a set of data like {{x1, y1},{x2, y2}, ...,{xn, yn}}
.
From this data can I find the value of x
for which y
is maximum.
Is it is possible using Mathemamtica 9.0?
Transpose[list][[2]]
contains all the y values in the list, so you can find the max of these and then locate where this occurs using Position
Position[y = Transpose[list][[2]], Max[y]]
Sort[list, #1[[2]] > #2[[2]] &][[1, 1]]
This will give you the value of x
for which y
is maximum. But if you also want the value of y
then do:
Sort[list, #1[[2]] > #2[[2]] &][[1]]
-
$\begingroup$ It's basically the same so I'm posting it here:
SortBy[list, Last][[-1, 1]]
$\endgroup$ – Kuba♦ Nov 22 '13 at 7:50
If you wish to allow for duplicate (repeated) maximum values this question is a duplicate of:
How to find rows that have maximum value?
Otherwise I suggest you use Ordering
as proposed by Ray Koopman:
SeedRandom[1]
data = RandomReal[{0, 100}, {50, 2}];
# ~Extract~ Ordering[#2, {-1}] & @@ Transpose[data]
-
1$\begingroup$ I don't understand why this had not been upvoted before. $\endgroup$ – Michael E2 Aug 28 '14 at 0:39
If speed is a concern for a large list, tryPick
as in
Pick[list[[All, 1]], list[[All, 2]], Max[list[[All, 2]]]]
That is, choose from the list of x values,list[[All,1]],
where in the list of y values,list[[All,2]],
y is maximum. I've found array subscripts like...[[All,...]]
to be fast compared toTranspose
.
Another fun alternative:
Fold[If[#1[[2]] > #2[[2]], #1, #2] &, First@list, Rest@list]
Roughly speaking, goes through the list element by element, comparing the best answer (i.e. the one with the largest y) found so far with every element in the list in turn. If on comparison, the element being compared to the best answer so far has a larger y, then that's made the new best answer.
First@Sort[list, #1[[2]] > #2[[2]] &][[1]]
. Wherelist = {{x1, y1}, {x2, y2}, ..., {xn, yn}}
$\endgroup$ – RunnyKine Nov 22 '13 at 4:48Ordering
. $\endgroup$ – Ray Koopman Nov 22 '13 at 6:38