
1.3.2 程序设计
与其他高级语言一样,MATLAB由顺序、条件和循环这三种基本控制结构组成,任何复杂的程序都可以由这三种基本结构构成。
1.顺序结构
顺序结构是指程序按照顺序依次执行各条指令,直到程序的最后一条语句为止,不需要任何特殊的流程控制。程序一般包括数据输入、数据处理和数据输出三个步骤。例如:

2.条件结构
条件结构又称为选择结构或分支结构,程序根据给定的条件是否成立来执行不同的操作。MATLAB中有if-else-end、switch-case-otherwise和try-catch-end三种条件结构程序语句。
(1)if-else-end语句
当有真和假两种条件时,if-else-end语句的结构为:

当需要多种条件执行不同的操作时,if-else-end语句的结构为:

【例1-5】判断输入数是否为正。

(2)switch-case-otherwise语句
switch-case-otherwise语句的格式为:

switch语句和if语句类似。switch语句根据变量或表达式的取值不同分别执行不同的命令。
【例1-6】根据菜单选择显示不同的函数。

(3)try-catch-end语句
MATLAB还提供了一种试探性执行语句try-catch-end,其格式为:

try-catch-end语句结构首先试探性地执行语句1,如果在此语句执行过程中出现错误,则将错误信息赋给保留的lasterr变量,并终止这段语句的执行,转而执行语句段2中的语句。如果不出错,则转去执行end后面的语句。
3.循环结构
循环执行是计算机运行的重要特点,MATLAB提供了两种实现循环结构的语句:for循环语句和while循环语句。
(1)for循环语句
for循环语句调用格式为:

执行时,先将初始值赋值给循环变量,执行循环体语句,执行完一次循环后,循环变量增加一个步长的值,然后判断循环变量的值是否处于初始值和终止值之间,如果满足条件则继续执行循环体语句,如果不满足条件则跳出循环。
【例1-7】已知,当n=100时,求x的值。程序如下:


程序运行结果如下:

(2)while循环语句
while循环语句调用格式为:

while循环语句是通过判断循环条件是否满足来决定是否继续循环的一种循环控制语句,也称为条件循环语句。它的特点是先判断循环条件,条件满足时执行循环。其执行过程为,如果条件成立,则执行循环体语句,执行后再判断条件是否成立,如果不成立则跳出循环。
【例1-8】利用while循环语句实现对的求解。

disp(sum)运行结果如下:
