-
How to find the matrix location of the nearest point?
Nearest[{{2,1},{2,3},{3,4},{4,5},{5,6}…{4,9}},{3,5}]
2)if I have a original set of points
ospts={{2,1},{2,3},{3,4},{4,5},{5,6}.......{4,9}},
and a target set of points tspts={{1,2}…{3,5}}. For each target point I like to find the nearest original point and its position within the ospts. How should I do it?
Thanks.
Xiaxing
Hi Xiaxing,
Here is one way to do it
SeedRandom[123];
ospts = RandomInteger[25, {10, 2}];
tspts = RandomInteger[25, {10, 2}];
closest = tspts // Map[First@Nearest[ospts, #] &];
ListPlot[{ospts, tspts},
PlotLegends -> {"ospts", "tspts"},
Epilog -> {Red, Transpose[{closest, tspts}] // Map[Line]},
ImageSize -> Large]
Positions of the closest points
positions = closest // Map[Position[ospts, #] &] // Flatten
(* {1, 8, 1, 7, 1, 7, 2, 4, 4, 9} *)
Mathematica’s Help for Nearest shows examples of nearly the same thing. I’m unsure why you are asking how to find the nearest.
If you want the nearest to a set of points you could say “at the center of a set” or “on the boundary of a set”.
but you appear to be asking for merely the nearest of each of one to the other which can be done by List[] operation.
Apply[ (Nearest[ opt, #])&, tpt]
a statistical approach might also be interesting
Hi John,
What do you mean by
List[] operation
Your proposed solution
Apply[(Nearest[opt, #])&, tpt]
will just return a single point. How does it answer the first question or the second question?