点到空间直线的距离

计算已知空间点P到已知直线L的距离:

已知两点确定了一条空间直线,求出直线的方向向量。计算P点与直线L上其中一点的空间向量,然后计算它与直线方向向量的外积。则点到空间直线的距离就是外积的模与空间直线方向向量的模相除。

以下为简单的MATLAB代码,输入为空间点P,和直线上的两点:

function [ d ] = DisPtToLine( P, CorPts ) %UNTITLED Summary of this function goes here % Detailed explanation goes here l = [ CorPts(1) - CorPts(4), CorPts(2) - CorPts(5), CorPts(3) - CorPts(6) ]; pl = [ P(1) - CorPts(1), P(2) - CorPts(2), P(3) - CorPts(3) ]; tem = cross(pl, l); d = norm( tem ) / norm( l ); end

通常要计算点到多条直线的距离,或要计算其中的最小值,则用MATLAB的最优化函数:

fminunc

function [ x, y, z ] = GetIntersection( p1, ps1, p2, ps2 ) %UNTITLED Summary of this function goes here % Detailed explanation goes here global p1x p1y p1z ps1x ps1y ps1z p2x p2y p2z ps2x ps2y ps2z p1x = p1(1); p1y = p1(2); p1z = p1(3); ps1x = ps1(1); ps1y = ps1(2); ps1z = ps1(3); p2x = p2(1); p2y = p2(2); p2z = p2(3); ps2x = ps2(1); ps2y = ps2(2); ps2z = ps2(3); P = [0 0 0]'; [intP] = fminunc(@MinDis, P); x = intP(1); y = intP(2); z = intP(3); end function f = MinDis( P ) global p1x p1y p1z ps1x ps1y ps1z p2x p2y p2z ps2x ps2y ps2z p1 = [ p1x p1y p1z ]'; ps1 = [ ps1x ps1y ps1z ]'; p2 = [ p2x p2y p2z ]'; ps2 = [ ps2x ps2y ps2z ]'; d1 = DisPtToLine( P, [p1(1), p1(2), p1(3), ps1(1), ps1(2), ps1(3)]' ); d2 = DisPtToLine( P, [p2(1), p2(2), p2(3), ps2(1), ps2(2), ps2(3)]' ); f = d1 + d2; end function [ d ] = DisPtToLine( P, CorPts ) %UNTITLED Summary of this function goes here % Detailed explanation goes here l = [ CorPts(1) - CorPts(4), CorPts(2) - CorPts(5), CorPts(3) - CorPts(6) ]'; pl = [ P(1) - CorPts(1), P(2) - CorPts(2), P(3) - CorPts(3) ]'; tem = cross(pl, l); d = norm( tem ) / norm( l ); end

你可能感兴趣的:(点到空间直线的距离)