calculate distance matrix for 3D points

24 views (last 30 days)
EXIT_FAILURE
EXIT_FAILURE on 12 Mar 2022
Answered: Matt J on 16 Mar 2022
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?

Answers (2)

Prahlad Gowtham Katte
Prahlad Gowtham Katte on 16 Mar 2022
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 on 16 Mar 2022
Assuming xA, yA, zA, xB, yB, zB are column vectors,
D=pdist2([ xA, yA, zA],[xB, yB, zB])

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!