matlab笔记(4)----程序流程语句

来源:互联网 发布:网络防攻击软件 编辑:程序博客网 时间:2024/06/08 18:42

if语句
if 表达式
     语句组
end


示例:


n = input('enter a number ,n= ');
if n<5
    n
end


运行M文件
>> Untitled
enter a number ,n= 4


n =


     4
再次运行M文件,输入9,无输出
>> Untitled
enter a number ,n= 9
>> 


双分支if语句
if 表达式
     语句组1
else
     语句组2
end


示例:
clear
clc
a=input('enter a number ,a= ');
b=input('enter a number ,b= ');
if a>b
    max=a;
else
    max=b;
end
max


结果:
enter a number ,a= 5
enter a number ,b= 4


max =


     5




多分支if语句


if 表达式
     语句组1
     elseif 表达式2
       语句组2
       ...
     elseif 表达式n
       语句组n
     else
       语句组n+1
end
示例:
clear
clc
score=input('enter the score of student,score= ');
if score>=90
    score='A'
elseif score>=80
    score='B'
elseif score>=70
    score='C'
elseif score>=60
    score='D'
else
    score='E'
end


结果:
enter the score of student,score= 78


score =


C

switch语句
switch 表达式
     case 数组1
          语句组1
     case 数组2
          语句组2
           ...
     case 数组n
          语句组n
otherwise
     语句组n+1
end

示例:

price=input('enter the price,price= ')
switch fix(price/100)
   case {0,1}
     rate=0;
   case {2,3,4}
     rate=3/100;
   case num2cell (5:9)
     rate=5/100;
   case num2cell (10:24)
     rate=8/100;
   case num2cell (25:49)
     rate=10/100;
   otherwise
     rate=14/100;
end
price=price*(1-rate)     


结果:
enter the price,price= 2000

price =

        2000


price =

        1840

while语句
while 表达式
     语句体
end

示例:求1+2+3+...+100的和。

i=0;
s=0;
while i<=100
    s=s+i;
    i=i+1;
end
s

结果:

s =

        5050

for语句

for 循环变量名=表达式1:表达式2:表达式3
      语句体
end

示例:求1+2+3+...+100的和。

clear
clc
s=0;
for i=1:100
    s=s+i;
end
s

结果:

s =

        5050

循环的嵌套

求这些项的和 1^1+1^2+1^3+...+2^1+2^2+2^3+...+3^1+3^2+3^3
示例:
clear
clc
s=0;
for i=1:3
    for j=1:10
        s=s+i^j;
    end
end
s

结果:
s =

       90628

continue语句
跳出循环体中所有剩余的语句,继续下一次循环,即结束本次循环

示例:把100~120之间的能被7整除的整数输出,

clear
clc
for i=100:120
    if rem(i,7)~=0  %rem为求余函数
        continue
    end
    i
end

结果:
i =

   105


i =

   112


i =

   119

break语句
退出循环体,继续执行循环体外的下一个语句
示例:把100~120之间的能被7整除的第一个整数输出

clear
clc
for i=100:120
    if rem(i,7)==0
        break
    end
end
i

结果:

i =

   105


try语句

try
   语句组1
catch
   语句组2
end

示例:矩阵乘法运算要求矩阵的维数相容,否则会出错,先求两矩阵的乘积,若出错,则自动会转去乘两矩阵的点成

clear
clc
A=[1 2 3;4 5 6];
B=[7 8 9; 10 11 12];
try
    C=A*B
catch
    C=A.*B
end
lasterr
C
结果:
ans =

Error using ==> mtimes
Inner matrix dimensions must agree.


C =                     %结果为数组乘法

     7    16    27
    40    55    72

将上例程序改为:

clear
clc
A=[1 2; 3 4;5 6];
B=[7 8;9 10; 11 12];
try
    C=A*B
catch
    C=A.*B
end
lasterr
C

结果:
ans =

Error using ==> mtimes
Inner matrix dimensions must agree.


C =                     %结果为矩阵乘法

     7    16
    27    40
    55    72




原创粉丝点击