Calculate and plot the shortest distance (norm) between a point and a line in 3D space

20 views (last 30 days)
I have a point P with coordinates [X Y Z] and a line AB (the coordinates of A and B are known)
I would like to calculate and to plot the segment representing the shortest distance between P and the line AB.
I am aware of matlab functions to calculate this distance (like this), but I do need to plot the segment in the 3D space.
I guess for this taks I need to find the coordinates of the point C along the line AB that is the end point of the segment connecting P to AB. How can I find these coordinates?
Thank you very much.

Accepted Answer

Matt J
Matt J on 21 Apr 2022
Edited: Matt J on 21 Apr 2022
A=A(:); B=B(:); P=P(:); %column vectors
C=A + (B-A)\(P-A)*(B-A); %nearest point
xyz=num2cell([P,C],2);
line(xyz{:})
  2 Comments
Giuseppe
Giuseppe on 21 Apr 2022
Edited: Giuseppe on 21 Apr 2022
Thank you for your help @Matt J.
Your code doesn't seem to work for me.
Considering the line AB and the point P, I have the following coordinates:
P = [203 149 167]
A = [202.8619 148.3503 167.2331]
B = [208.9890 151.9891 181.0078]
How can I plot the shortest line connecting the point P to the line AB? Thank you!
Bruno Luong
Bruno Luong on 21 Apr 2022
@Giuseppe Matt's formula is correct and he already shows you plot the shortest line P to C, a projection of P on the line AB (not a segment).

Sign in to comment.

More Answers (1)

KSSV
KSSV on 21 Apr 2022
It is an easy task to achieve. You can find the foot of the perpendicular. Refer this:
  1 Comment
Giuseppe
Giuseppe on 21 Apr 2022
Thank you @KSSV. Based on your reference, I wrote a code that seems to work when the coordinates of A and B along the line AB are integers:
P=[3 6 2];
A=[4 7 1];
B=[3 5 3];
a=A(1)-B(1);
b=A(2)-B(2);
c=A(3)-B(3);
k=(a*B(1)+b*B(2)+c*B(3))/(a^2+b^2+c^2);
Q=[B(1)+a*k B(2)+b*k B(3)+c*k];
hold on
plot3(P(1),P(2),P(3),'blacko')
plot3(A(1),A(2),A(3),'blacko')
plot3(B(1),B(2),B(3),'blacko')
plot3(Q(1),Q(2),Q(3),'blacko')
plot3([A(1) B(1)],[A(2) B(2)],[A(3) B(3)],'r')
plot3([P(1) Q(1)],[P(2) Q(2)],[P(3) Q(3)],'b')
axis equal
hold off
Doesn't seem to work when the coordinates of the points A and B of the line AB are not integers.
For example I have:
P = [203 149 167]
A = [202.8619 148.3503 167.2331]
B = [208.9890 151.9891 181.0078]
Any help is appreciated. Thank you!

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!