MATLAB判断两条直线平行

两条直线平行的判据比较简单,只要斜率相等就可以了。但也有特殊情况,比如平行于y轴的直线斜率没有定义。

综合考虑以上情形,就不难将程序写出来,具体如下:

函数 isparallellines.m

function flag = isparallellines(line1, line2)
% decide if two lines are parallel.
% Input:
% 	line1: [a1 b1 c1], equation coefficients of line1
%	line2: [a2 b2 c2], equation coefficients of line2
% Output:
%	flag=1: parallel
%	flag=0: not parallel
% Poweed by Xianbao Duan
% Email: xianbao.d@gmail.com
% Website: http://www.52souji.net/

a1 = line1(1);	b1 = line1(2);	c1 = line1(3);
a2 = line2(1);	b2 = line2(2);	c2 = line2(3);

if (a1==0 && b1==0) || (a2==0 && b2==0)
	% if a1,b1 = 0 or a2,b2 = 0, wrong line equation
	error('Wrong coefficents for line equations!');
end

if a1~=0 && a2~=0 && b1==0 && b2==0
	% for lines parallel to y-axis
	flag = 1;
else
	% for usual lines
	k1 = -a1/b1;
	k2 = -a2/b2;
	if k1 == k2 
		flag = 1;
	else
		flag = 0;
	end
end

我再提供一种想法,有兴趣的可以尝试编写一下:根据直线与坐标轴(比如x轴)的夹角进行判断。

标签: matlab

相关文章推荐

添加新评论 (无需注册,可直接评论)

仅有一条评论

  1. Poweed应该是Powered吧