Re: [運算] 怎算出兩條線有沒有交叉? 交點已回收

看板MATLAB作者 ( )時間15年前 (2011/02/11 14:46), 編輯推噓0(004)
留言4則, 2人參與, 最新討論串1/3 (看更多)
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
複製貼上時記得處理一下換行 ptt一行的容許字數不夠多
02/11 14:49, 1F

02/11 14:49, , 2F
不管座標在哪個象限 是不是0都可以用
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
文章代碼(AID): #1DLDjV5P (MATLAB)
文章代碼(AID): #1DLDjV5P (MATLAB)