Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Coordinates Points in Matlab

Tags:

matlab

What I want to do is to sort these coordinates points:

Measured coordinates (x,y)= (2,2),(2,3),(1,2),(1,3),(2,1),(1,1),(3,2),(3,3),(3 ,1)

I need to get sequences or trajectories of this points to follow them by iteration.

like image 773
user1310873 Avatar asked Jan 16 '23 00:01

user1310873


1 Answers

data = [2,2 ; 2,3 ; 1,2 ; 1,3 ; 2,1 ; 1,1 ; 3,2 ; 3,3 ; 3 ,1]
% corresponding sort-value, pick one out or make one up yourself:
sortval = data(:,1); % the x-value
sortval = data(:,2); % y-value
sortval = (data(:,1)-x0).^2 + (data(:,2)-y0).^2; % distance form point (xo,y0)
sortval = ...

[~,sortorder] = sort(sortval);
sorted_data = data(sortorder,:);

But from you comment, I understand you actually need something to reconstruct a path and iteratively find the closest neighbour of the last found point (of the reconstructed path so far).

The following is how I would solve this problem (using pdist2 for calculating the distances between all the points for easiness):

data = [2,2 ; 2,3 ; 1,2 ; 1,3 ; 2,1 ; 1,1 ; 3,2 ; 3,3 ; 3 ,1];
dist = pdist2(data,data);

N = size(data,1);
result = NaN(1,N);
result(1) = 1; % first point is first row in data matrix

for ii=2:N
    dist(:,result(ii-1)) = Inf;
    [~, closest_idx] = min(dist(result(ii-1),:));
    result(ii) = closest_idx;
end

which results in:

result =
     1     2     4     3     6     5     9     7     8

being the indices to consecutive points on the curve. Here's a plot of this result:

enter image description here

As @mathematician1975 already mentioned, there can be equal distances to a point. This is solved here by using min which just finds the first occurrence of the minimum in an array. This means that if you order your input data differently, you can get different results of course, this is inherent to the equal-distance issue.

2nd remark: I don't know how this will behave when using large input data matrices, probably a bit slow because of the loop, which you can't avoid. I still see room for improvement, but that's up to you ;)

like image 64
Gunther Struyf Avatar answered Jan 24 '23 17:01

Gunther Struyf