MATLAB函数文件(Function)和求解一元二次方程

2025-10-03 20:40:09

1、第一,本文要求解的一元二次方程如下图,共三个。

MATLAB函数文件(Function)和求解一元二次方程

2、第二,启动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)。

MATLAB函数文件(Function)和求解一元二次方程

3、第三,保存上述函数文件。保存函数文件时,函数文件名必须与函数定义名相一致,冲陕羞所以本文的函数文件保存为solve_equation.m。然后利用函数文件(solve_equation.m)求解第一步中的一元二次方程。

先求第一个一元二次方程,在命令行窗边舍口(Command Window)输入solve_equation(2,3,2),回车得到如下结果:

ans =

There is no answer!

MATLAB函数文件(Function)和求解一元二次方程

4、第四,求解第二个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,2,1), 回车得到如下结果:

ans =

There is only one answer!

ans =

    -1  良牺  -1

x1 =

    -1

x2 =

    -1

MATLAB函数文件(Function)和求解一元二次方程

5、第五,求解第三个一元二次方程,在命令行窗口(Command Window)输入[x1,x2]=solve_equation(1,-5,6),回车得到如下结果:

ans =

There are two answers!

ans =

     3     2

x1 =

     3

x2 =

     2

MATLAB函数文件(Function)和求解一元二次方程

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢