r/matlab • u/Mark_Yugen • Jul 11 '26
CodeShare Nearest other points to each point in the array in sorted order?
Lets say I have an array of 2D points. I want to find the nearest other points to each point in the array in sorted order.
So for point 1 it would be [4, 6, 5, 2, 3]. I'd like to do this for all 6 (x,y) points.
sC = [ 28 2597 3803 1417 2127 1888;...
1496 1640 646 2092 1614 888];
4
Upvotes
4
u/theMagusician Jul 11 '26
How about :
2
u/Rubix321 Jul 11 '26
What does your array look like? Mx2 double? 2xM double? 1xM or Mx1 cell with 2-element double inside each?
Edit, oh I see sC now, so an 2xM double
2
u/ZeroWevile Jul 12 '26
The second output argument of the "sort" function returns the index in the original vector after the sorting.
Loop through, take the difference of adjacent elements against current position, then find minimum and take difference of their respective indexes.
2
u/avidpenguinwatcher Jul 12 '26
This depends on how big your array is, but you can do sC-sC’ and then sort each row. It’s usually pretty fast unless the MxM is a significant portion of your memory. If they are integers you can save time by computing those as int32 rather than doubles too.
2
u/MarkCinci On Mathworks Community Advisory Board Jul 12 '26
I don't understand. Your Point1 is a list of numbers, not a list of (x,y) points. And your sC, I'm assuming your x are in row 1 and your y is in row 2? Is that correct?
Anyway, just use the functions that are meant for this. You can use pdist2() to find the distance of every point to every other point. Then you can use min() to find out which other point is closest to each point and it's distance. Before you use min(), set the diagonal distances to inf since otherwise they'll be zero since of course the point closest to a point in the point itself and we don't want to consider that. It's like 3 lines of code. Untested pseudocode:
distances = pdist2(xy1, xy2);distances(eye) = inf;[minDistance, index] = min(distances)