How to calculate distance between 3D points ?

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

 Accepted 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.

2 Comments

Thank you, it worked !
Thanks !! this works perfectly .

Sign in to comment.

More Answers (2)

KSSV
KSSV on 12 Dec 2018
Read about knnsearch. This will help you more.
If you implement this it's enough no need loops :
sqrt(sum((pts1 - pts2 ) .^ 2))

5 Comments

Unfortunatly it doen't work
figure
scatter3(X1, Y1, Z1, 'filled')
title('CountingOverlay')
xlabel('X')
ylabel('Y')
zlabel('Z')
hold on
scatter3(X2, Y2, Z2, 'filled')
hold off
pts1 = [X1, Y1, Z1];
pts2 = [X2, Y2, Z2];
sqrt(sum((pts1 - pts2 ) .^ 2))
Unfortunatly it doen't work
Doesn't help , what error did you get ?? paste the complete error message and your datas to test
sqrt(sum((pts1 - pts2 ) .^ 2));
Matrix dimensions must agree.
Yes that's true, I don't have the same numbers of points ...
@Marine you need to know that you can't subtract unequal size dimensions first thing !
Second thing if one ask's you to post the datas - you should post it or the sample of it, instead of making the other to puzzle his/her mind!
As I said, I'm new to matlab.
Thanks for you help.

Sign in to comment.

Products

Release

R2018b

Community Treasure Hunt

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

Start Hunting!