此函数返回从3D点P到由两个3D点A和B定义的线段的最短距离,它将P投影到直线上,然后检查这个投影点是否在A和B之间。如果是,则使用这个投影点计算距离。
如果投影在线段之外,则计算到A点或B点的距离,这取决于哪一点更近。
我想得到反馈,如果这是一个干净的解决方案的问题。
function d = point_seg_dist(P, A, B)
% Returns distance from a 3D point to a line segment
%
% Inputs
%
% P : vector
% Position in space
%
% A : vector
% Position of line segment endpoint
%
% B : vector
% Position of other line segment endpoint
%
% Outputs
%
% d : double
% Distance from point to line segment
AP = P - A; % Vector from A to point
AB = B - A; % Vector from A to B
% Project point onto line
P_line = A + dot(AP, AB) / dot(AB, AB) * AB;
if all(A < P_line) && all(P_line < B)
% The point projected onto the line is in between A and B
% Projection of point onto segment is the same
% as projection of point onto line
P_seg = P_line;
else
% The point projected onto the line is outside of A and B
if all(P_line <= A)
% The projected point is closer to A
P_seg = A;
else
% The projected point is closer to B
P_seg = B;
end
end
d = norm(P - P_seg); % Distance to line segment
end发布于 2018-03-12 12:37:40
下面是沃尔夫拉姆阿尔法提供的解决方案的实现,正如OP的评论中所建议的那样。
已执行的公式是:
哪里
是直线上的两点,x_0是第三个点。
function d = point_seg_dist(x0, x1, x2)
% Make sure we are in 3D
if length(x0) == 2
x1(3) = 0;
x2(3) = 0;
x0(3) = 0;
end
% We want column arrays
if size(x0,1) < size(x0,2)
x0 = P';
x1 = x1';
x2 = x2';
end
d = norm(cross(x2-x1 , x1-x0)) / norm(x2-x1);除了对输入进行几次检查外,计算是在一条线上进行的,它不需要投影或检查投影点的位置。
https://codereview.stackexchange.com/questions/162447
复制相似问题