操作方法
第一,本文要求解的一元二次方程如下图,共三个。
第二,启动MATLAB,新建脚本(Ctrl+N),输入如下代码: function [x1,x2]=solve_equation(a,b,c) %solve_equation,solve the quadratic equation with one unknown delt=b^2-4*a*c; if delt<0 'There is no answer!' elseif delt==0 'There is only one answer!' x1=-b/(2*a);x2=x1; ans=[x1,x2] else 'There are two answers!' x1=(-b+sqrt(delt))/(2*a); x2=(-b-sqrt(delt))/(2*a); ans=[x1,x2] end 其中,函数文件的第一行是function引导的函数声明行(Function Declaration Line)。
第三,保存上述函数文件。保存函数文件时,函数文件名必须与函数定义名相一致,所以本文的函数文件保存为solve_equation.m。然后利用函数文件(solve_equation.m)求解第一步中的一元二次方程。 先求第一个一元二次方程,在命令行窗口(Command Window)输入solve_equation(2,3,2),回车得到如下结果: ans = There is no answer!
第四,求解第二个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,2,1), 回车得到如下结果: ans = There is only one answer! ans = -1 -1 x1 = -1 x2 = -1
第五,求解第三个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,-5,6),回车得到如下结果: ans = There are two answers! ans = 3 2 x1 = 3 x2 = 2