MATLAB—求直线或者线段之间的交点坐标
1 function CrossPoint( ) 2 %% 求两条直线的交点坐标 3 x1 = [7.8 8]; 4 y1 = [0.96 0.94]; 5 %line2 6 x2 = [8.25 8.25]; 7 y2 = [0 0.99]; 8 %fit linear polynomial 9 p1 = polyfit(x1,y1,1); 10 p2 = polyfit(x2,y2,1); 11 %calculate intersection 12 x_intersect = fzero(@(x) polyval(p1-p2,x),3); 13 y_intersect = polyval(p1,x_intersect); 14 line(x1,y1); 15 hold on; 16 line(x2,y2); 17 plot(x_intersect,y_intersect,'r*') 18 axis([5,10,0,2]); 19 20 21 %% 求线段的交点坐标 22 n=20; 23 p=rand(n,4); %(x1,y1,x2,y2)线段两端点 24 25 for i=1:n 26 pbar=p(i,:); 27 pbar=reshape(pbar,[2,2]); 28 line(pbar(1,:),pbar(2,:)); 29 end 30 31 hold on; 32 for i=1:n-1 33 p1=p(i,:); 34 k1=(p1(2)-p1(4))/(p1(1)-p1(3)); 35 b1=p1(2)-k1*p1(1); 36 for j=i+1:n 37 p2=p(j,:); 38 k2=(p2(2)-p2(4))/(p2(1)-p2(3)); 39 b2=p2(2)-k2*p2(1); 40 41 x=-(b1-b2)/(k1-k2); %求两直线交点 42 y=-(-b2*k1+b1*k2)/(k1-k2); 43 %判断交点是否在两线段上 44 if min(p1(1),p1(3))<=x && x<=max(p1(1),p1(3)) && ... 45 min(p1(2),p1(4))<=y && y<=max(p1(2),p1(4)) && ... 46 min(p2(1),p2(3))<=x && x<=max(p2(1),p2(3)) && ... 47 min(p2(2),p2(4))<=y && y<=max(p2(2),p2(4)) 48 plot(x,y,'r.'); 49 end 50 end 51 end 52 end