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!