【matlab】已知两线段的端点,求线段之间最短距离

数据说明:

      线段: points=[x1 y1 x2 y2]

程序说明:

      通过线段两端点,写成参数函数(考虑了斜率不存在的问题)

程序:

function practice(points1,points2)
g=points1(2)-points1(4);
h=points1(1)-points1(3);
if g<0|h<0
    t1=-1:0.1:0;
else
    t1=0:0.1:1;
end
x1=points1(1)+h*t1;
y1=points1(2)+g*t1;


g1=points2(2)-points2(4);
h1=points2(1)-points2(3);
if g1<0 | h1<0
    t2=-1:0.1:0;
else
    t2=0:0.1:1;
end
x2=points2(1)+h1*t2;
y2=points2(2)+g1*t2;

n=length(t1);
m=length(t2);

juli=zeros(n,m);
for i=1:n
    juli(i,:)=sqrt((x2-x1(i)).^2+(y2-y1(i)).^2);%
end%获得每两个点之间的距离
[mina,mini]=min(juli(:));%找出距离中的最小值,及其单下标
j0=fix(mini/n)+1;
i0=mod(mini,n);%将单下标转化为双下标
x0=t1(i0);y0=2*t2(i0);
x3=t2(j0);y3=2*t2(j0);
disp('为最短距离=')
disp(mina)%输出两点坐标,及最短距离
plot(x1,y1,'r',x2,y2,'r',x0,y0,'b*',x3,y3,'b*');
axis([0 20 0 20]);
grid on%画出来
end

测试:

       1.测试数据

        points1=[2 2 2 6]; 

        points2=[12 8 14 10];

       2.测试结果

最短距离为10.1980

说明

matlab新手,如有不对,请各位豪杰指点

参考来源:https://zhidao.baidu.com/question/268795945.html

猜你喜欢

转载自blog.csdn.net/heni6560/article/details/83185768