点到线段的最短距离
程序员文章站
2022-03-02 10:57:36
...
function dist = PointToSegDist(x,y,x1,y1,x2,y2)
%POINTTOSEGDIST 此处显示有关此函数的摘要
% public static double PointToSegDist(double x, double y, double x1, double y1, double x2, double y2)
% {
% double cross = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
% if (cross <= 0) return Math.Sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
% double d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
% if (cross >= d2) return Math.Sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
% double r = cross / d2;
% double px = x1 + (x2 - x1) * r;
% double py = y1 + (y2 - y1) * r;
% return Math.Sqrt((x - px) * (x - px) + (y - py) * (y - py));
% }
dotProduct = (x2 - x1) * (x - x1) + (y2 - y1) * (y - y1);
if dotProduct<=0
dist = sqrt((x-x1)^2+(y-y1)^2);
else
d2 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
if dotProduct>=d2
dist = sqrt((x - x2) * (x - x2) + (y - y2) * (y - y2));
else
r=dotProduct/d2;
px = x1+(x2-x1)*r;
py = y1+(y2-y1)*r;
dist = sqrt((x - px) * (x - px) + (y - py) * (y - py));
end
end
end