I have a list of point2d coordinate {x,y}. I would like to find the point where x is the smallest. How can I do it in Mathematica?
1 Answer
Initializing some test data:
pts = RandomReal[100, {10, 2}];
Kuba's suggestion in the comments is this:
MinimalBy[pts, First]
{{31.2859, 50.9165}}
and here is a piece of code that captures the idea of Henrik's suggestion:
First@SortBy[pts, First]
{31.2859, 50.9165}
In other programming languages, we might have written a for loop and made a variable keep track of the smallest x coordinate so far. In Mathematica, we can also use loops but we try to stay away from it. If we were to implement that kind of solution in Mathematica, it would look like this instead:
min[pt1_, pt2_] := If[First[pt1] < First[pt2], pt1, pt2]
Fold[min, pts]
{31.2859, 50.9165}
Another pattern that one can see sometimes is to get the smallest value, get the position of the smallest value, and then extract that position from the original list:
minVal = pts[[All, 1]] // Min;
pos = Position[pts, {minVal, _}];
Extract[pts, pos]
{{31.2859, 50.9165}}
Note that I use Extract
instead of Part
to get the element, it's useful to remember that Extract
works well with the type of output that Position
gives. We could not have used Part
to extract this information without first transforming the expression that Position
gave.
I recommend the simplest approaches, i.e. one of the first two presented above. Most of all I recommend MinimalBy
.
point2d[[Ordering[point2d, 1][[1]]]]
$\endgroup$First@Sort@point2d
$\endgroup$