文档介绍:MATLAB2009从入门到精通
Date
1
课程主要内容
第1章 MATLAB简介
第2章 数值运算
第3章 单元数组和结构
第4章 字符串
第5章 符号运算
第6章 MATLAB绘图基础
第7章 程序设计
第8章 计算方法 6 10 15 15
1 4 10 10 15 15
1 5 15 15 15 15
1 6 15 15 15 15
Date
15
用for循环语句需要注意以下事项:
(1)不能在for循环体内重新对循环变量n赋值来终止循环的执行。
(2)for循环可以进行嵌套循环。
(3)循环语句内的“;”可防止中间变量的输出。
Date
16
2、while循环
与for循环固定的次数求一组命令的值相反,while循环以不定的次数来求一组命令的值。while循环的一般形式如下:
while 表达式
循环体();
n+1;(自增)
end
只要表达式中的元素为真,就执行while和end语句之间的命令。通常,表达式给出的是一个标量值,但数组(或矩阵)同样有效。若为数组(或矩阵),则要求所有的元素都必须为真。
例:
Date
17
程序结果
>> while1
a =
Date
18
程序实例
问题描述:根据统计学的基础知识分析样本的平均值和标准差。
例:
Date
19
程序结果
>> for2
Enter the number of the points:6
Enter the value:1
Enter the value:3
Enter the value:5
Enter the value:7
Enter the value:9
Enter the value:0
The mean of this data set is:
The standard deviation is:
The number of data is:6
Date
20
>> while2
Enter the first value:1
Enter the first value:3
Enter the first value:5
Enter the first value:7
Enter the first value:9
Enter the first value:0
Enter the first value:-1
The mean of this data set is:
The standard deviation is:
The number of data is:6
Date
21
分支结构
在程序设计中,经常要根据一定的条件来执行不同的语句。当某些条件满足时,只执行其中的某个语句或某些语句。在这种情况下,分支结构就会是很好的选择了。在MATLAB中的分支结构语句包括if-else-end语句与switch-case-otherwise语句。
Date
22
1、if-else-end选择语句
if-else-end选择语句的结构如下所示:
if条件式1
表达式1;
elseif条件式2
表达式2;
...
else
表达式n;
end
哪一个if后的表达式中值为真,就执行该if后的表达式,否则跳过该表达式进行其它判断。
例:
Date
23
程序结果
>> ff(-1)
ans =
1
>> ff(2)
ans =
>> ff(8)
ans =
>> ff(16)
ans =
4
Date
24
采用plot(x,ff(x))绘分段函数图。
x1=-2::0;
x2=::5;
x3=::10;
x4=::12;
plot(x1,ff(x1))
hold on
plot(x2,ff(x2))
hold on
plot(x3,ff(x3))
hold on
plot(x4,ff(x4))
grid on
Date
25
程序结果
Date
26
MATLAB中的选择语句switch-case-otherwise,是特别让熟悉C等高级语言的用户方便地编写M文件而专门添加的。switch-case-otherwise语句的通用格式如下:
swith expression
case value1
statemen