How can i find the nearest neighbor of all indices of a matrix containing the coordinates

2 views (last 30 days)
Hello all,
I'm having trouble in finding a solution to my problem. I have a matrix containing coordinates or points in the xy plane like this: A = [X1 Y1;X2 Y2;...;Xn Yn];
Now I would like to find for every point its closest partner, for example point 1 ([X1 Y1]) could be closest to point 2 [X2 Y2], point 2 ([X2 Y2]) could be closest to point 3 [X3 Y3].
Point 3 ([X3 Y3]) could be closest to node 52 [X52 Y52] and to node 4 [X4 Y4].. etc
I would like to store this as NEAREST = [node#1 node#2] thus for this example NEAREST = [1 2; 2 3; 3 52; 3 4].
I can't figure this out yet, is there someone with a good idea?

Answers (1)

Walter Roberson
Walter Roberson on 25 Nov 2013
If you have the stats toolbox, use pdist2() to find the pairwise distances. Remove the diagonal 0 from the result. [mindist, minidx] = sort(ThatArray,2). Now the matching is 1:size(ThatArray,1) vs minidx

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!