MATLAB交互式输入(input)和调用函数文件
来源:网络收集 点击: 时间:2024-07-20第一,编写求解一元二次方程的函数文件。启动MATLAB,新建脚本(Ctrl+N),输入如下代码:
function =solve_equation(a,b,c)
%solve_equation,solve the quadratic equation with one unknown
delt=b^2-4*a*c;
if delt0
There is no answer!
elseif delt==0
There is only one answer!
x1=-b/(2*a);x2=x1;
ans=
else
There are two answers!
x1=(-b+sqrt(delt))/(2*a);
x2=(-b-sqrt(delt))/(2*a);
ans=
end
保存上述函数文件(函数文件第一行是function引导的函数声明行),命名为solve_equation.m(函数文件名要与函数声明行中的函数定义名一致)。

第二,编写交互式输入脚本。新建脚本(Ctrl+N),输入如下代码:
close all; clear all; clc
prompt1=Please input a\n;
a=input(prompt1)
prompt2=Please input b\n;
b=input(prompt2)
prompt3=Please input c\n;
c=input(prompt3)
solve_equation(a,b,c)
上述脚本通过input( )提示输入变量a,b,c(即一元二次方程的系数),然后调用函数文件solve_equation.m,进而求解一元二次方程的根。

第三,保存和运行上述交互式输入脚本,在命令行窗口(Command Window)输入以下a,b,c的值。
Please input a
1
a =
1
Please input b
2
b =
2
Please input c
1
c =
1

第四,a,b,c输入完毕后,在命令行窗口(Command Window)返回如下结果:
There is only one answer!
ans =
-1 -1

第五,如果输入a=2,b=-5,c=3(即求2x^2-5x+3=0的根),在命令行窗口(Command Window)返回如下结果:
There are two answers!
ans =
1.5000 1.0000

版权声明:
1、本文系转载,版权归原作者所有,旨在传递信息,不代表看本站的观点和立场。
2、本站仅提供信息发布平台,不承担相关法律责任。
3、若侵犯您的版权或隐私,请联系本站管理员删除。
4、文章链接:http://www.1haoku.cn/art_975254.html