Changing point coordinates in a file to closest ones in another file
5 views (last 30 days)
Show older comments
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?
0 Comments
Accepted Answer
Guillaume
on 27 Feb 2016
Edited: Guillaume
on 27 Feb 2016
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, :) = [];
More Answers (1)
See Also
Categories
Find more on Point Cloud Processing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!