calculate distance matrix for 3D points
23 次查看(过去 30 天)
显示 更早的评论
I have the lists xA, yA, zA and the lists xB, yB, zB. The contain the the x,y and z coordinates of points of type A and type B. There may be different numbers of type A and type B points.
I would like to calculate a matrix containing the Euclidean distances between points of type A and type B. Of course, I only need to calculate one half of the matrix, since the other half contains duplicate data.
What is the most efficient way to do that?
When I'm done with that, I want to find the points of type B that are closest to one point of type A. How do I then find the coordinates the closest, second closes, third closest and so on points of type B?
0 个评论
回答(2 个)
Prahlad Gowtham Katte
2022-3-16
Hello
As per my understanding, you want to create a distance matrix between points of type A and type B. You can do that by creating a matrix and initializing all entries to 0 and using a for loop you can find the distances and update the matrix accordingly. After generating the matrix, you can select a row where all distances would be there from a point in type A and sorting it can give the points with least distance, etc. The following code is just a small illustration for the same.
%Taking values for xA,yA,zA and xB,yB,zB
xA=[1 2 3 4 5];
yA=[1 2 3 4 5];
zA=[1 2 3 4 5];
xB=[5 4 3 2 1];
yB=[5 4 3 2 1];
zB=[5 4 3 2 1];
%Rows and columns of the matrix
M=length(xA);
N=length(xB);
distance_matrix=zeros(M,N);%Initializing the matrix
for i=1:M
for j=1:N
d=sqrt((xA(i)-xB(j)).^2+(yA(i)-yB(j)).^2+(zA(i)-zB(j)).^2);
distance_matrix(i,j)=d;%Updating the distances
end
end
For more information on how to use sortrows please refer to the following link
Hope it helps.
0 个评论
Matt J
2022-3-16
Assuming xA, yA, zA, xB, yB, zB are column vectors,
D=pdist2([ xA, yA, zA],[xB, yB, zB])
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Statistics and Machine Learning Toolbox 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!