7
$\begingroup$

Suppose I have the following list of $x,y$ coordinates:

A = {{-5, 0.508928}, {-4, 0.516564}, {-3, 0.523614}, {-2, 0.523574}, {-1, 0.520759}, {0, 0.519357}, {1, 0.502434}, {2, 0.505553}, {3, 0.510231}, {4, 0.515214}, {5, 0.517549}}

Now, I wish to find the $x,y$ coordinate, where $y$ is largest. I have tried:

A // MatrixForm
Max /@ Transpose[A]

But this returns the combination of maximum in each column.

$\endgroup$
12
$\begingroup$
MaximalBy[A, Last]

{{-3, 0.523614}}

$\endgroup$
6
$\begingroup$
A[[Ordering[A[[All, -1]], -1]]]

{{-3, 0.523614}}

Note: Ordering typically is faster than alternatives for large lists.

SeedRandom[1]
a = RandomReal[1, {100000, 2}];
r1 = a[[Ordering[a[[All, -1]], -1]]]; // RepeatedTiming // First

0.0017

r2 = First[SortBy[a, -Last@#&]];// RepeatedTiming// First

0.017

r3 = TakeLargestBy[a, Last,1]; // RepeatedTiming // First

0.039

r4 = MaximalBy[a, Last]; // RepeatedTiming // First

0.065

r5 = First[Sort[a, #1[[2]] > #2[[2]] &]];// RepeatedTiming// First

1.88

r1 == {r2} == r3 == r4 =={r5}

True

$\endgroup$
  • $\begingroup$ Thinking about this, I am somewhat shocked how ineffcient MaximalBy is. $\endgroup$ – Henrik Schumacher Jun 2 at 16:44
  • $\begingroup$ @Henrik, me too. $\endgroup$ – kglr Jun 2 at 17:18
2
$\begingroup$
First[Sort[A, #1[[2]] > #2[[2]] &]]

{-3, 0.523614}

$\endgroup$
2
$\begingroup$

Another simpler one:

(sort the list by last element of each sublist and then pick the last element)

SortBy[A, Last][[-1]]  

Which gives {-3, 0.523614}

$\endgroup$
  • 1
    $\begingroup$ You mean SortBy[A, Last][[Length[A]]]? How about SortBy[A, Last][[-1]] or Last@SortBy[A, Last] $\endgroup$ – OkkesDulgerci Jun 2 at 14:58
  • $\begingroup$ Oh!, yes! Thanks, included yours!. $\endgroup$ – math Jun 2 at 16:37

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.