# Nearest numbers in the list

I am just curious that there is any better way to write the code to search the nearest value than what I wrote below

peaks={{127, 1}, {133, 0.992}, {139, 1}, {1762, 0.984}};

DeleteDuplicates[
Table[
Select[peaks,
(peaks[[i, 2]] - 0.1 <= #[] <= peaks[[i, 2]] + 0.1) &&
(peaks[[i, 1]] - 20 <= #[] <= peaks[[i, 1]] + 20)
&]
, {i, 1, Length[peaks]}]]

(*Output*)
{{{127, 1}, {133, 0.992}, {139, 1}}, {{1762, 0.984}}}


I think there will be much simpler and easier way to write in mathematica... Any help?

Edit

I try to gather the value by the near position You can see that three points are All in blue point, and one point is at yellow dot. I just want to find this cluster

• Nearest. But please describe what you want the code to do. Oct 4 '16 at 15:30
• A slight tweak to your code: Gather[peaks, And[Abs[#1[] - #2[]] < 20, Abs[#1[] - #2[]] < 0.1] &], assuming I understand your question. But I echo @corey979: Can you explain what it is you're trying to do? Oct 4 '16 at 15:32
• Thank you for the comment, I add the edit below Oct 4 '16 at 15:44

peaks={{127, 1}, {133, 0.992}, {139, 1}, {1762, 0.984}};

1. FindClusters[peaks, Method -> "Agglomerate"]

{{{127, 1}, {133, 0.992}, {139, 1}}, {{1762, 0.984}}}

2. cc = ClusterClassify[peaks, Method -> "DBSCAN"]; GatherBy[peaks, cc]

{{{127, 1}, {133, 0.992}, {139, 1}}, {{1762, 0.984}}}

This should be exactly reproducing the OP code, using Nearest :

 Sort /@ (Nearest[peaks, #, {Infinity, 1.},
DistanceFunction -> (Max[Abs[Subtract@##/{20, .1}]] &)
] & /@ peaks) // DeleteDuplicates


and you might also consider DistanceFunction -> (Norm[Subtract@##/{20, .1}] &)

• DistanceFunction -> EuclideanDistance?
– yode
Oct 4 '16 at 17:36
• @yode you could also use EuclideanDistance but you still need to apply the scale {20,.1} , so like EuclideanDistance[#1/{20, .1}, #2/{20, .1}] & Oct 4 '16 at 17:42
• @george2079 I think this code was what I asked on question, but sorry that I did not accept your post. Oct 4 '16 at 19:21