Changing point coordinates in a file to closest ones in another file

5 views (last 30 days)
I have a file M1 containing a matrix from this form, for example
1 10 45
2 32 56
3 12 50
4 28 67
The second and third column are x and y coordinates of nodes and the first column is the id of the node. And another one M2 containing another matrix, for example
10 50
30 60
These columns are coordinates of, let's say, reference nodes
What I want to do is to change the coordinates in the first file to the closest one to them in the second file. So my result, will be something like this:
1 10 50
2 30 60
3 10 50
4 30 60
Any hints or ideas how to do it?

Accepted Answer

Guillaume
Guillaume on 27 Feb 2016
Edited: Guillaume on 27 Feb 2016
If you have the statistics toolbox, you can use pdist2 to calculate your distance matrix:
Dist = pdist2(M1(:, [2 3]), M2, 'cityblock'); %You used the cityblock distance in your code. Wouldn't 'euclidean' be better?
If not, you can still avoid the loops with:
Dist = abs(bsxfun(@minus, M1(:, 2), M2(:, 1).')) + abs(bsxfun(@minus, M1(:, 3), M2(:, 2).')); %for cityblock
DistSquared = abs(bsxfun(@minus, M1(:, 2), M2(:, 1).').^2) + abs(bsxfun(@minus, M1(:, 3), M2(:, 2).').^2); %for euclidean
You also don't need a loop to create your final matrix:
[~, closestidx] = min(Dist, [], 2);
M3 = [M1(:, 1), M2(closestidx, [1 2])];
To find the rows of M2 that do not appear in M3:
notpresent = ~ismember(M2, M3(:, [2 3]), 'rows');
To remove these rows from M2:
M2(notpresent, :) = [];
  1 Comment
etudiant_is
etudiant_is on 27 Feb 2016
Thanks a lot for your answer. For the distance, yes i used the Manhattan distance which is what i need in my problem.

Sign in to comment.

More Answers (1)

etudiant_is
etudiant_is on 27 Feb 2016
I did it like this
[rows1, ~] = size(M1);
[rows2 , ~] = size(M2);
for i=1:rows1
for j=1:rows2
Dist (i,j) = abs(M1 (i,2) - M2 (j,1)) + abs(M1 (i,3) - M2 (j,2));
end
end
[MinDist, MinDistInd]= min(Dist');
for i=1:rows1
M3(i,1)=i;
M3(i,2)=M2 (MinDistInd(i),1);
M3(i,3)=M2 (MinDistInd(i),2);
end
I get the result I want, but then I notice that some reference points are not picked at all, so how can I remove them from M2 and keep only those which were used? Besides, is there a shorted way to do it because my first matrices has like 10000 elements inside of it?

Community Treasure Hunt

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

Start Hunting!