作者middle1023 (米豆)
看板MATLAB
标题[讨论] 找出两条直线的交点
时间Thu Apr 12 18:53:31 2007
小弟因为有需要
可是爬过文发现没有人有这样的问题
於是自己写了一个 也顺便分享出来
希望各位前辈也可以帮小弟找看看有没有错误
还是说有更好的写法
以下是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
1F:推 sunev:为什麽不用determinant的方式求解? 04/13 00:05
2F:推 middle1023:直觉只有想到这方法...就写下去了 04/14 16:09
3F:推 yimean:程式本是抛砖引玉,一山自有一山高,分享的精神是值得鼓励ꨠ 04/15 11:06
4F:推 middle1023:也是希望有更好的方式出现 04/15 22:15
5F:推 RainyBreeze:为什麽我用这个函式解出来的点只有X座标 没Y座标呢 01/08 22:18