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

作者:流年 | 创建时间: 2023-05-29
MATLAB函数文件是指可以定义输入参数和返回输出变量的M文件。本文介绍通过建立函数文件(Function)来求解一元二次方程的方法。...
MATLAB函数文件(Function)和求解一元二次方程

操作方法

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

第二,启动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

温馨提示

函数文件与脚本文件相比,都是.M文件,只是函数文件开头多了函数声明行(Function Declaration Line)。
点击展开全文

更多推荐