首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >三维点到线段的最短距离

三维点到线段的最短距离
EN

Code Review用户
提问于 2017-05-03 23:20:41
回答 1查看 1.7K关注 0票数 5

此函数返回从3D点P到由两个3D点A和B定义的线段的最短距离,它将P投影到直线上,然后检查这个投影点是否在A和B之间。如果是,则使用这个投影点计算距离。

如果投影在线段之外,则计算到A点或B点的距离,这取决于哪一点更近。

我想得到反馈,如果这是一个干净的解决方案的问题。

代码语言:javascript
复制
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
EN

回答 1

Code Review用户

发布于 2018-03-12 12:37:40

下面是沃尔夫拉姆阿尔法提供的解决方案的实现,正如OP的评论中所建议的那样。

已执行的公式是:

d=\frac{|(\mathbf{x}_2-\mathbf{x}_1)\times(\mathbf{x}_1-\mathbf{x}_0)|}{|\mathbf{x}_2-\mathbf{x}_1|}

哪里

x_1=(x_1,y_1,z_1)
x_2=(x_2,y_2,z_2)

是直线上的两点,x_0是第三个点。

代码语言:javascript
复制
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);

除了对输入进行几次检查外,计算是在一条线上进行的,它不需要投影或检查投影点的位置。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/162447

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档