x=input('请输入x的值:');
if rem(x,2)==1
y=sqrt(x);
else
y=x^(1/3);
end
y
多分支if语句
c=input('请输入一个字符:','s');
if c>='A' && c<='Z'
disp(lower(c))
elseif c>='a' && c<='z'
disp(upper(c))
elseif c>='0' && c<='9'
disp(str2double(c)^2)
else
disp(c)
end
用switch实现选择结构
语句格式
c=input('请输入一个单词:','s');
switch c(1)
case {'A','E','I','O','U','a','e','i','o','u'}
disp([c,'以元音字母开头']);
otherwise
disp([c,'以辅音字母开头']);
end
g=input('请输入PM2.5值:');
switch fix(g)
case num2cell(0:34)
disp('空气质量优');
case num2cell(35:74)
disp('空气质量良好');
case num2cell(75:114)
disp('空气质量轻度污染');
case num2cell(115:149)
disp('空气质量中度污染');
case num2cell(150:249)
disp('空气质量重度污染');
otherwise
disp('空气质量严重污染');
end
用for语句实现循环结构
什么是循环结构?
for语句
y=0;
g=-1;
n=input('n=?');
for i=1:n
g=-g;
y=y+g/(2*i-1);
end
pai=4*y
a=0;
b=1;
n=input('n=?');
h=(b-a)/n;
x=a:h:b;
f=sqrt(1-x.*x);
s=[];
for k=1:n
s1=(f(k)+f(k+1))*h/2;
s=[s,s1];
end
pai=4*sum(s)
s=0;
n=input('n=?');
for i=1:n
x=rand(1);
y=rand(1);
if x*x+y*y<=1
s=s+1;
end
end
pai=s/n*4
用while语句实现循环
while语句
msum=0;
n=0;
x=input('Enter a number (end in 0):');
while x~=0
msum=msum+x;
n=n+1;
x=input('Enter a number (end in 0):');
end
if n>0
msum
mean=msum/n
end
break语句和continue语句
for n=100:200
if rem(n,21)~=0
continue
end
n
break
end
循环的嵌套
m=input('m=');
p=1:m;
p(1)=0;
for i=2:sqrt(m)
for j=2*i:i:m
p(j)=0;
end
end
n=find(p~=0);
p(n)
函数文件的定义与调用
函数文件的基本结构
function [s,p]=fcircle(r)
s=pi*r*r;
p=2*pi*r;
函数调用
匿名函数
# f2.m
function f=f2(n)
f=0;
for k=1:n
f=f+k*(k+1);
end