[討論] 找出兩條直線的交點
小弟因為有需要
可是爬過文發現沒有人有這樣的問題
於是自己寫了一個 也順便分享出來
希望各位前輩也可以幫小弟找看看有沒有錯誤
還是說有更好的寫法
以下是code
function [x y] = crosspoint(line1,line2)
% This function can find the cross point with two straight lines
% Input matrix : line1 = [line1(x1),line1(y1) ; line1(x2),line1(y2)]
% line2 = [line2(x1),line2(y1) ; line2(x2),line2(y2)]
% x1,y1 and x2,y2 is the two end points of lines
% [x y] is the cross point of two straight lines
%%%%%%% test %%%%%%%%
line1 = [0.8,2.6 ; 6,9.4];
line2 = [5,-2 ; 2.55,8.45];
%%%%%%% test %%%%%%%%
x11 = line1(1,1); y11 = line1(1,2);
x21 = line1(2,1); y21 = line1(2,2);
x12 = line2(1,1); y12 = line2(1,2);
x22 = line2(2,1); y22 = line2(2,2);
%%%%%%% test %%%%%%%%
plot([x11 x21] ,[y11 y21]);hold on;plot([x12 x22] ,[y12 y22]);
%%%%%%% test %%%%%%%%
seta = 0; setb = 0;
% line1
if x11 == x21
% for x = a y + b
str1 = [num2str(x11) '=a*(' num2str(y11) ')+b'];
str2 = [num2str(x21) '=a*(' num2str(y21) ')+b'];
[aa1,bb1] = solve(str1,str2,'a','b');
a1 = subs(aa1) ; b1 = subs(bb1) ; seta = 1;
else % y11 == y21 or other
% for y = a x + b
str1 = [num2str(y11) '=a*(' num2str(x11) ')+b'];
str2 = [num2str(y21) '=a*(' num2str(x21) ')+b'];
[aa1,bb1] = solve(str1,str2,'a','b');
a1 = subs(aa1) ; b1 = subs(bb1) ;
end
% line2
if x12 == x22
% for x = a y + b
str1 = [num2str(x12) '=a*(' num2str(y12) ')+b'];
str2 = [num2str(x22) '=a*(' num2str(y22) ')+b'];
[aa2,bb2] = solve(str1,str2,'a','b');
a2 = subs(aa2) ; b2 = subs(bb2) ; setb = 1;
else % y12 == y22 or other
% for y = a x + b
str1 = [num2str(y12) '=a*(' num2str(x12) ')+b'];
str2 = [num2str(y22) '=a*(' num2str(x22) ')+b'];
[aa2,bb2] = solve(str1,str2,'a','b');
a2 = subs(aa2) ; b2 = subs(bb2) ;
end
% solve y = a*x + b
if seta == 1
st1 = ['x=' num2str(a1) '*y+(' num2str(b1) ')'];
else
st1 = ['y=' num2str(a1) '*x+(' num2str(b1) ')'];
end
if setb == 1
st2 = ['x=' num2str(a2) '*y+(' num2str(b2) ')'];
else
st2 = ['y=' num2str(a2) '*x+(' num2str(b2) ')'];
end
[xx,yy] = solve(st1,st2,'x','y');
x = subs(xx);
y = subs(yy);
%%%%%%% test %%%%%%%%
plot(x,y,'o','MarkerSize',3,'LineWidth',2);
%%%%%%% test %%%%%%%%
% program end
謝謝大家
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.116.71.95
推
04/13 00:05, , 1F
04/13 00:05, 1F
推
04/14 16:09, , 2F
04/14 16:09, 2F
推
04/15 11:06, , 3F
04/15 11:06, 3F
推
04/15 22:15, , 4F
04/15 22:15, 4F
推
01/08 22:18, , 5F
01/08 22:18, 5F
MATLAB 近期熱門文章
PTT數位生活區 即時熱門文章