I have data1 and a target point targetPts, and want to find the closest point from the data. As you can see from below, the 29th point from the data is the closest point and thus the value of data1[[29]] is same as the desired value, which is {0.67033, 0.84245}.

data1 = BlockRandom[SeedRandom[7]; RandomReal[1, {30, 2}]];
targetPts = {0.68, 0.75};
Flatten@Nearest[data1, targetPts]

Now my problem changed a bit. I was given data1data2 and I need to use it as the input. My desired output for this case is {0.67033, 0.84245, 0.177696, 0.49873}. The first 2 elements are used in the Nearest searching, while all 4 elements are the desired output. It just like a lookup function.

data2 = BlockRandom[SeedRandom[8]; RandomReal[1, {30, 2}]];
data1data2 = ArrayFlatten[{{data1, data2}}];

How can I get it done? Many thanks!

First @ Nearest[data1data2[[All, ;; 2]] -> "Index", targetPts] 


data1data2[[First @ Nearest[data1data2[[All, ;; 2]] -> "Index", targetPts]]]  

 {0.67033, 0.84245, 0.177696, 0.49873}

For versions prior to version 11.1 replace "Index" above with Automatic (thanks: Henrik Schumacher).

  • $\begingroup$ And in older versions (pre 11.1 or 11.2, Automatic instead of "Index" is the only way to get the indices. $\endgroup$ – Henrik Schumacher Jun 18 '18 at 15:22
  • $\begingroup$ Thanks for all of you. I recorded the time and noted that the "Index" approach is much faster than First[Nearest[data1 -> data1data2, targetPts, 1]] approach for large data size. $\endgroup$ – H42 Jun 18 '18 at 15:58

You could pass a Rule to Nearest:

First[Nearest[data1 -> data1data2, targetPts, 1]]

{0.67032993, 0.84245042, 0.17769644, 0.49872995}


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.