3

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?

Artes
  • 57,212
  • 12
  • 157
  • 245
NRS
  • 61
  • 1
  • 5

6 Answers6

5

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]]
bill s
  • 68,936
  • 4
  • 101
  • 191
3

There is a much neater way of doing this in Mathematica v10 onwards, using MaximalBy. Example:

lis = { {x1, 10}, {x2, 3}, {x3, 50}, {x4, 20} };

MaximalBy[lis, Last]

returns:

{{x3, 50}}
wolfies
  • 8,722
  • 1
  • 25
  • 54
3
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]]
RunnyKine
  • 33,088
  • 3
  • 109
  • 176
3

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]
Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
2

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.

KennyColnago
  • 15,209
  • 26
  • 62
1

Another fun alternative:

list = {{x1, 10}, {x2, 3}, {x3, 50}, {x4, 20}};

Fold[If[#1[[2]] > #2[[2]], #1, #2] &, First@list, Rest@list]

A shorter version of the same can be:

Fold[If[#1[[2]] > #2[[2]], #1, #2] &, list]

{x3, 50}


Explanation

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.

Syed
  • 52,495
  • 4
  • 30
  • 85
Aky
  • 2,719
  • 12
  • 19