How to calculate distance between 3D points ?

16 views (last 30 days)
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

Guillaume
Guillaume on 12 Dec 2018
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.

More Answers (2)

KSSV
KSSV on 12 Dec 2018
Read about knnsearch. This will help you more.

madhan ravi
madhan ravi on 12 Dec 2018
If you implement this it's enough no need loops :
sqrt(sum((pts1 - pts2 ) .^ 2))
  5 Comments
madhan ravi
madhan ravi on 12 Dec 2018
Edited: madhan ravi on 12 Dec 2018
@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!
Marine Bertschy
Marine Bertschy on 12 Dec 2018
As I said, I'm new to matlab.
Thanks for you help.

Sign in to comment.

Categories

Find more on MathWorks Cloud Center in Help Center and File Exchange

Products


Release

R2018b

Community Treasure Hunt

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

Start Hunting!