
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
1.7.1 选择结构
MATLAB的选择结构有if语句和switch语句两种形式。if语句最为常用,switch语句适用于选择分支比较整齐、分支较多、没有优先关系的场合。对if语句来说,只有一种选择是其中最简单的一种,其格式如下:

当expression为真(true或1)时,就执行if与end之间的语句。
当有两种选择时,格式如下:

如果expression为真(true或1),则执行statements1;否则执行statements2。
如果程序需要有3个或3个以上的选择分支,则可使用如下语句格式:

在这种格式的语句中,else语句可有可无,当程序遇到某个表达式为真时,即执行对应的程序语句,其他的分支将被跳过。
if语句是可以嵌套的,如:

选择结构也可以由switch语句实现,在多选择分支时使用switch语句更为方便,其语句格式如下:

如果switch_expression等于case中的某一个表达式,则执行相应的程序语句。当switch_expression与所有表达式都不相等时,就执行otherwise对应的程序语句,但otherwise语句并不是必需的。
【例1-5】利用if语句遍历一个矩阵,并赋予对应的新值。

运行程序,输出如下:

【例1-6】利用switch语句,根据在命令提示符处输入的值,有条件地显示不同的文本。

运行程序,输出如下:
