例子来源于网络:关键是看disp函数怎么把字符和数字在一起进行显示。
两点生成直线程序
%%以下是一个通过给定两点显示直线方程的程序,
%%该程序需要给出两个点的坐标,结果返回为y=kx+b的格式,且求得斜率
function [k,a1,b,type]=straight_line(A,B) % 输入,A,B两点坐标
V=B-A;
a=inf;
b=inf;
type=\'undefined\';
if A==B
\'The two points are the same\'
return
end
if V(1)==0 && V(2)==0
disp(\'Enter two distinct points next time\')
return
end
if V(1)==0
type=\'vertical\';
elseif V(2)==0
type=\'horizontal\';
else
type=\'oblique\';
slope=atan2(V(2),V(1));
s=inv([A(1) 1;B(1) 1])*[A(2) B(2)]\';
a=s(1);
b=s(2);
end
switch type
case \'vertical\'
disp(\'经过这两个点的直线方程为::\');
disp([\'x = \',num2str(A(1))]);
case \'horizontal\'
disp(\' 经过这两个点的直线方程为:: \');
disp([\'y =\',num2str(A(2))]) ;
case \'oblique\'
disp(\' 经过这两个点的直线方程为:\') ;
disp([\'y = \',num2str(a) ,\' *x +\',num2str(b)]);
disp(\'斜率为:\')
k=num2str(a);%将符号数值化
end