MATLAB: How to calculate distance between 3D points

3ddistancefor loopMATLABpointspoints cloud

Hello everyone,
I have two 3D points clouds and that are visually mostly overlaying. So far I have this code :
figure
scatter3(X1, Y1, Z1, 'filled')
title('CountingOverlay')
xlabel('X')
ylabel('Y')
zlabel('Z')
hold on
scatter3(X2, Y2, Z2, 'filled')
hold off
But what I would like to calculate now, are the distances between each points and eachother points to quantify how much they are overlaying.
So I think I will need to use pythogoras to calculate it, maybe using on of the following functions :
pts1 = [X1, Y1, Z1];
pts2 = [X2, Y2, Z2];
sqrt(sum((pts1 - pts2 ) .^ 2))
or:
norm(pts1 - pts2)
Can it works ?
Also my main problem is about the for loop part.
How can I use for loop to make it work here? I mean to make it calculate the distance between each points for the first cloud and each points of the 2nd cloud. This is the second time that I'm using Matlab and I'm a little bit lost with it.
Thank you in advance

Best Answer

Assuming you're on R2016b or later,
distance = sqrt(sum((permute(pts1, [1 3 2]) - permute(pts2, [3 1 2])) .^ 2, 3))
Rows of distance correspond to pts1, columns to pts2. Certainly as Madhan said, no need for loop.
If you have the stats toolbox, pdist2 does the same calculation.