1. 程式人生 > >【matlab】已知兩線段的端點,求線段之間最短距離

【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新手,如有不對,請各位豪傑指點