calculate distance matrix for 3D points

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?

답변 (2개)

Prahlad Gowtham Katte
Prahlad Gowtham Katte 2022년 3월 16일

0 개 추천

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.
Matt J
Matt J 2022년 3월 16일

0 개 추천

Assuming xA, yA, zA, xB, yB, zB are column vectors,
D=pdist2([ xA, yA, zA],[xB, yB, zB])

카테고리

도움말 센터File Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

제품

릴리스

R2021b

질문:

2022년 3월 12일

답변:

2022년 3월 16일

Community Treasure Hunt

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

Start Hunting!

Translated by