'How to get the point to line segment distance in 2D? [closed]

I’m just wondering if there is a simple way to get the distance between a point and a line segment in 2D in Matlab?



Solution 1:[1]

x = [0,0]; %some point
a = [1,2]; %segment points a,b
b = [3,5];

d_ab = norm(a-b);
d_ax = norm(a-x);
d_bx = norm(b-x);

if dot(a-b,x-b)*dot(b-a,x-a)>=0
    A = [a,1;b,1;x,1];
    dist = abs(det(A))/d_ab;        
else
    dist = min(d_ax, d_bx);
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lanpa