1、第一,本文要求解的一元二次方程如下图,共三个。
2、第二,启动MATLAB,新建脚本(Ctrl+N),输入如下代码:function [x1,垓矗梅吒x2]=solve_equation(a,b,c)%so造婷用痃lve_equation,solve the quadratic equation with one unknowndelt=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)。
3、第三,保存上述函数文件。保存函数文件时,函数文件名必须与函数定义名相一致,所以本文的函数文竭惮蚕斗件保存为solve_髫潋啜缅equation.m。然后利用函数文件(solve_equation.m)求解第一步中的一元二次方程。先求第一个一元二次方程,在命令行窗口(Command Window)输入solve_equation(2,3,2),回车得到如下结果:ans =There is no answer!
4、第四,求解第二个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,2,1), 回车得到如下结果:ans =There is only one answer!ans = -1 -1x1 = -1x2 = -1
5、第五,求解第三个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,-5,6),回车得到如下结果:ans =There are two answers!ans = 3 2x1 = 3x2 = 2