您的位置:首页 > 编程语言 > MATLAB

MATLAB程序流程控制

2018-02-24 22:49 288 查看

1.条件结构

输入一个百分制成绩,输出成绩等级A、B、C、D、E。其中90~100分为A,80~89分为B,70~79分为C,60~69分为D,60分以下为E。

e.g. if语句

a=input('分数:');
if a>100
disp('出错!')
4000

elseif a>=90
disp('A')
elseif a>=80
disp('B')
elseif a>=70
disp('C')
elseif a>=60
disp('D')
elseif a>=0
disp('E')
else
disp('出错!')
end


e.g. switch语句

a=input('分数:');
switch fix(a)
case num2cell(0:59)
disp('E');
case num2cell(60:69)
disp('D');
case num2cell(70:79)
disp('C');
case num2cell(80:89)
disp('B');
case num2cell(90:100)
disp('A');
otherwise
disp('出错!');
end


2. 循环结构

输入n,求下式的值。



e.g. 循环结构

n=input('n=');
s=1;
while(n)
a=(2*n*2*n)/((2*n-1)*(2*n+1));
s=s*a;
n=n-1;
end
disp(s)


e.g. 向量运算

n=input('n=');
i=1:n;
A=[2*i (2*i-1);2*i (2*i+1)];
B=prod(A);  %每个因子分子和分母分别相乘
C=reshape(B,n,2);  %将分子和分母分成两列
D=prod(C);  %所有分子相乘、分母相乘
x=D(1,1);   %分子的最终结果
y=D(1,2);   %分母的最终结果
disp(x/y)  %最终结果


or

n=input('n=');
i=1:n;
A=(2*i).^2./((2*i-1).*(2*i+1));
s=prod(A)


3. 函数调用




编写一个函数文件f.m,使得调用f时,x可为矩阵,得出的f(x)为同阶矩阵。

function y=f(x)
y=(1./(((x-2)^2+0.1))+(1./((x-3)^4+0.01)));


注:x可为矩阵,除号要用‘ ./ ’ 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息