Re: [運算] 怎算出兩條線有沒有交叉? 交點已回收
clear all
close all
clc
% ab為1線, cd為1線
a=[1 2] ;
b=[pi 7] ;
c=[2.7 11] ;
d=[1 12] ;
% 先求兩條線方程式的係數
% m*x -y=m*b(1)-b(2)
% Line1Coeff(1)*x+Line1Coeff(2)*y=Line1Coeff(3)
% 第1條線
Line1Coeff(1)=(a(2)-b(2))/(a(1)-b(1)) ;
Line1Coeff(2)=-1 ;
Line1Coeff(3)=Line1Coeff(1)*b(1)-b(2) ;
% 第2條線
Line2Coeff(1)=(c(2)-d(2))/(c(1)-d(1)) ;
Line2Coeff(2)=-1 ;
Line2Coeff(3)=Line2Coeff(1)*d(1)-d(2) ;
% 用行列式解兩條線交點
% 有交點必須滿足下式不等於0
Singularity=Line1Coeff(2)*Line2Coeff(1)-Line1Coeff(1)*Line2Coeff(2) ;
if Singularity==0
'no intersection'
else
IntersectX=(Line2Coeff(3)*Line1Coeff(2)-Line1Coeff(3)*Line2Coeff(2))/Singularity ;
IntersectY=(Line1Coeff(3)*Line2Coeff(1)-Line2Coeff(3)*Line1Coeff(1))/Singularity ;
end
% 兩條線的點
if a(1)<=b(1)
x1=a(1):0.01:b(1) ;
else
x1=b(1):0.01:a(1) ;
end
y1=Line1Coeff(1)*x1-Line1Coeff(3) ;
if c(1)<=d(1)
x2=c(1):0.01:d(1) ;
else
x2=d(1):0.01:c(1) ;
end
y2=Line2Coeff(1)*x2-Line2Coeff(3) ;
% 判斷交點是否在範圍內
if IntersectX>=min(x1) && IntersectX<=max(x1) &&...
IntersectY>=min(y1) && IntersectY<=max(y1) &&...
IntersectX>=min(x2) && IntersectX<=max(x2) &&...
IntersectY>=min(y2) && IntersectY<=max(y2)
'intersect'
else
'no intersection'
end
% 畫圖驗證
figure(1)
hold on
plot(x1,y1,'b')
plot(x2,y2,'r')
plot(IntersectX,IntersectY,'ko')
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.46.37
→
02/11 14:49, , 1F
02/11 14:49, 1F
→
02/11 14:49, , 2F
02/11 14:49, 2F
→
02/11 14:50, , 3F
02/11 14:50, 3F
→
02/11 14:54, , 4F
02/11 14:54, 4F
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 3 篇):