How to find the closest rows (positions/entities) in two mby3 matrixes?
2 次查看(过去 30 天)
显示 更早的评论
Hi all,
I have 2 matrices both with 3 columns as the x, y, and z positions. My question is how can I find the row numbers which are closest to each other? I was thinking of: min(abs(Matrix_A - matrix_B)
but this does not give me the row number. Any ideas on how to find the row number?
for simplicity consider row number 5 from matrix_A is to be matched with the closest row on matrix_B.
Thanks!
A = rand(10 , 3) % find the closest row in B to the 5th row in A
B = rand(10 , 3)
closest = min(abs(A(5 , :) - B))
回答(1 个)
Image Analyst
2023-4-28
Try this. Adapt as needed:
% Create sample data.
xyz1 = rand(4, 3);
xyz2 = rand(4, 3) + 1.5;
plot3(xyz1(:, 1), xyz1(:, 2), xyz1(:, 3), 'b.', 'MarkerSize',20);
grid on;
hold on;
plot3(xyz2(:, 1), xyz2(:, 2), xyz2(:, 3), 'r.', 'MarkerSize',20);
% Find distance between every point and every other point.
distances = pdist2(xyz1, xyz2)
% Find minimum distance
minDistance = min(distances(:))
% Find index
[row1, row2] = find(distances == minDistance)
% Draw a line between the two closest (x,y,z) points
p1 = xyz1(row1, :)
p2 = xyz2(row2, :)
plot3([p1(1), p2(1)], [p1(2), p2(2)], [p1(3), p2(3)], 'g-', 'LineWidth', 4);
1 个评论
dpb
2023-4-28
Only recast to use the optional alternate input parameter of pdist2 to return N 'smallest' or 'largest' values; and an index array into the output distances of the locations of the other array. That's a little confusing in that it doesn't return the one overall global minimum as one might think, but studying the outuput a little will clarify what it actually does return. Overall, there's not much real difference other than the potential size of the output returned; I don't know that it can save any compute time; it might even be something more internally because it's also got to do the calculation to find the minimal ones...and that just might be more than simply computing them all and then doing the global search. I've not tried timing it on large problems to explore...
% Create sample data.
xyz1 = rand(4, 3);
xyz2 = rand(4, 3) + 1.5;
plot3(xyz1(:, 1), xyz1(:, 2), xyz1(:, 3), 'b.', 'MarkerSize',20);
grid on;
hold on;
plot3(xyz2(:, 1), xyz2(:, 2), xyz2(:, 3), 'r.', 'MarkerSize',20);
% Find distance between every point and every other point.
[distances,index] = pdist2(xyz1, xyz2,'euclidean','smallest',1)
% Find minimum distance
% Draw a line between the two closest (x,y,z) points
[~,row2]=min(distances);
row1=index(row2);
p1 = xyz1(row1, :)
p2 = xyz2(row2, :)
plot3([p1(1), p2(1)], [p1(2), p2(2)], [p1(3), p2(3)], 'g-', 'LineWidth', 4);
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!