1
$\begingroup$

I have a 2-dimensional list of data of $x$ and $y$ coordinates. I am looking for a way to get the element of the list which has the closest $y$ value to a given $y$ value. I tried using Nearest, but this only gives me the nearest $y$ value to the value that I am looking for, but not an element of the form {x, y}. I am sure this can't be a great problem, I just do not see how to solve it.

Thanks in advance!

$\endgroup$
  • 1
    $\begingroup$ could you add an example of your code and result? $\endgroup$ – Sumit Jul 12 '16 at 13:09
4
$\begingroup$

Your problem is much simpler than the title suggests

pts = RandomReal[1, {10, 2}]
y = RandomReal[]

Graphics[
 Point @ pts,
 GridLines -> {None, {y}}, 
 Epilog -> {Red, AbsolutePointSize@7, 
   Point@First@MinimalBy[pts, Abs[#[[2]] - y] &]}
]

enter image description here

$\endgroup$
1
$\begingroup$

A way to use Nearest:

Using @Kuba's setup:

SeedRandom[1]
pts = RandomReal[1, {10, 2}]
y = RandomReal[];

nF = Nearest[pts[[All, 2]] -> Automatic]; 
(* nF =  Nearest[pts[[All, 2]] -> "Index"] in versions 10+ *)
Graphics[{Point@pts, Red, AbsolutePointSize@7, Point[pts[[First @ nF @ y]]]}, 
 GridLines -> {None, {y}}]

enter image description here

$\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.