I've been building a program in MATLAB off of an excellent thread describing how to find the shortest distance between a point and a line segment in 2D (Shortest distance between a point and a line segment). I need a function that does essentially the same thing as this previously answered question but in 3D instead of 2D and in MATLAB.
None of the top comments for answers to this previous post are in MATLAB so I'm having some trouble understanding what's going on behind the scenes in this code. Maybe some of you smarter or more skilled out there can help me convert this to a 3D MATLAB code?
The line segment would be defined as two points S1 (x1,y1,z1) and S2 (x2,y2,z2) and the point is simply a single coordinate Pnt (x3,y3,z3).
EDIT: There seems to be a little confusion here. I really do mean line segments not an infinite line. I've attached the code that I'm working with. I'd like to add that this code which I've modified was originally written as part of a comment in the above linked thread and the original author Peter Karasev deserves credit for it. As is, the code works in 2D, and I've commented in 3 lines which are a start to make it 3D (vz, uz, and at lenSqr). My specific question is that I really don't understand what's going on mathematically with detP and how I can make detP and the subsequent if statements work in 3D.
The inputs are as defined above in the original question text.
function r = PointToLineSegment3D( S1, S2, Pnt )
% r = PointToLineSegment3D( S1, S2, Pnt )
vx = S1(1)-Pnt(1);
vy = S1(2)-Pnt(2);
% vz = S1(3)-Pnt(3);
ux = S2(1)-S1(1);
uy = S2(2)-S1(2);
% uz = S2(3)-S1(3);
lenSqr= (ux*ux+uy*uy); % +uz*uz
detP= -vx*ux + -vy*uy;
if( detP < 0 )
r = norm(S1-Pnt,2);
elseif( detP > lenSqr )
r = norm(S2-Pnt,2);
else
r = abs(ux*vy-uy*vx)/sqrt(lenSqr);
end
end
For future users who find this question, this is the code that I've made to work in 3D in MATLAB. This does not work for an infinite line only a line segment.
function r = PointToLineSegment3D( S1, S2, Pnt )
% r = PointToLineSegment3D( S1, S2, Pnt )
vx = S1(1)-Pnt(1);
vy = S1(2)-Pnt(2);
vz = S1(3)-Pnt(3);
ux = S2(1)-S1(1);
uy = S2(2)-S1(2);
uz = S2(3)-S1(3);
lenSqr= (ux*ux+uy*uy+uz*uz)
detP= -vx*ux + -vy*uy + -vz*uz;
if( detP < 0 )
r = norm(S1-Pnt,2);
elseif( detP > lenSqr )
r = norm(S2-Pnt,2);
else
r =norm( abs(cross((S2-S1),(S1-Pnt)))/sqrt(lenSqr));
end
end