2
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ One way will be First@Sort[list, #1[[2]] > #2[[2]] &][[1]]. Where list = {{x1, y1}, {x2, y2}, ..., {xn, yn}} $\endgroup$ – RunnyKine Nov 22 '13 at 4:48
  • 1
    $\begingroup$ Look up Ordering. $\endgroup$ – Ray Koopman Nov 22 '13 at 6:38
5
$\begingroup$

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]]
$\endgroup$
3
$\begingroup$
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]]
$\endgroup$
  • $\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
3
$\begingroup$

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]
$\endgroup$
  • 1
    $\begingroup$ I don't understand why this had not been upvoted before. $\endgroup$ – Michael E2 Aug 28 '14 at 0:39
2
$\begingroup$

If speed is a concern for a large list, tryPickas 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.

$\endgroup$
0
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.