MATLAB基础知识学习笔记
02 结构化程序与自定义函数
2.1 撰写MATLAB的脚本
首先需要了解MATLAB脚本:
- 一个MATLAB脚本包括了一串的MATLAB指令
- 脚本在运行前需要保存在
.m
文件中
2.1.1 创建脚本
点击HOME中的New Script按钮
此时便出现Script的编辑框,如下所示:
这里我们输入以下代码
for i = 1:10
x = linspace(0, 10, 101);
plot(x, sin(x+i))
print(gcf, '-deps', strcat('plot', num2str(i), '.ps'));
end
点击Run运行程序
这里进行命名保存
然后就会呈现以下运行结果
注:
- 选中代码段,使用智能缩进(Smart Indent)
- 使用%可进行每一行的注释
- 使用%%将代码段分成区块
- 选中某一区块,运行节(Run section),只执行该区块代码
- 运行(Run),执行所有代码
2.1.2 编写脚本常用快捷键
Ctrl + R
:注释选中行Ctrl + T
:对选中行取消注释Ctrl + I
:对选中行进行智能缩进
2.2 结构化程序设计
2.2.1 逻辑运算符
运算符 | 说明 |
---|---|
< | 小于 |
<= | 小于等于 |
> | 大于 |
>= | 大于等于 |
== | 判断左右两边是否相等 |
~= | 判断左右两边是否不相等 |
&& | 且 |
|| | 或 |
与其他语言不同的是:MATLAB的不等于用
~=
表示
2.2.2控制流语句
MATLAB的代码执行顺序是从上到下的,如果要实现一些非顺序结构,则需要控制流语句
控制流语句 | 说明 |
---|---|
if ,elseif ,else | 条件为 true 时执行语句 |
for | 循环特定次数,并通过递增的索引变量跟踪每次迭代 |
switch ,case ,otherwise | 执行多组语句中的一组 |
try ,catch | 执行语句并捕获产生的错误 |
while | 循环语句,条件仍然为 true 就进行循环 |
break | 终止执行 for 或 while 循环,结束整个循环迭代 |
continue | 结束本轮循环迭代,下一次正常进行 |
end | 结束语句块,形成一个区块,与其他区块区分开来 |
pause | 暂停程序执行 |
return | 返回至调用脚本或函数处 |
if elseif else
语法格式:
if 条件1
语句1
elseif 条件2
语句2
else
语句3
end
举例:
%%
a = 3;
if rem(a, 2) == 0
disp('a is even');
else
disp('a is odd');
end
其中,rem(a, 2)
所表示的含义为a除以2的余数
switch
语法格式:
switch 表达式(可能有很多种变化的数值变量)
case 值1
语句1
case 值2
语句2
...
otherwise
语句n
end
举例:
%%
input_num = 5;
switch input_num
case -1
disp('negative one');
case 0
disp('zero');
case 1
disp('one')
otherwise
disp('other value');
end
while
语法格式:
while 表达式
语句
end
举例:
%%
n = 1;
while prod(1:n) < 1e100 % prod函数:连乘操作 n!<= 10的100次方
n = n + 1;
end
disp(n)
练习
使用代码实现下面公式
∑
n
=
1
999
n
\sum_{n=1}^{999}n
n=1∑999n
%% Use while loop to calculate the summation of the series 1+2+3+...+999
sum = 0;
n = 1;
while n < 1000
sum = sum + n;
n = n + 1;
end
disp(sum)
for
语法格式:
for 变量名=start:increment(增量;步长):end
语句
end
举例:
%%
for n = 1:10
a(n) = 2^n;
end
disp(a)
注意
我们的变量此时工作空间的情况,直接改变某些代码并不能改变原来变量的数据,它会保存原来旧的数据,我们必须要使用
clear
指令清除变量的旧数据,才能得到修改代码后更新的结果。
练习
求2的奇数次方
%%
for n = 1:2:10
a((n+1)/2) = 2^n;
end
disp(a)
Pre-allocation
预先声明需要的变量所占的内存空间大小
在使用循环语句时,可以尽量预先分配内存空间,这样的话会提升效率,如下图所示
2.2.3 练习
Use structured programming to:
-
Copy entries in matrix A to matrix B
-
Change the values in matrix B if their corresponding entries in matrix A is negative
A = [ 0 − 1 4 9 − 14 25 − 34 49 64 ] A = \begin{bmatrix} 0 & -1 & 4\\ 9 & -14 & 25\\ -34 & 49 & 64 \end{bmatrix} A=⎣⎡09−34−1−144942564⎦⎤
代码
%%
A = [0 -1 4; 9 -14 25; -34 49 64];
B=A;
for i = 1:3
for j = 1:3
if A(i,j) < 0
B(i,j) = -B(i,j);
end
end
end
disp(A)
disp(B)
2.2.4 代码小技巧
-
对于一行语句过长的情况,使用
...
可以进行换行操作,如A = [1 2 3 4 5; ... 6 7 8 9 10];
-
使用
Ctrl + C
可以在程序宕机 / 循环进行时,跳出循环
2.3 函数
2.3.1 脚本与函数的区别
脚本(Script) | 函数(Function) |
---|---|
不需要输入 | 需要输入 |
不需要输出 | 需要输出 |
保存在全局工作空间中 | 保存在局部工作空间中 |
2.3.2 查看内建函数
使用指令edit(which(‘函数名.m’))
如,查看内建函数mean()
2.3.3 用户自定义函数
单个输出的函数
【例1】编写一个用于计算自由落体位移的函数,给定初始位移
x
0
x_0
x0,初始速度
v
0
v_0
v0以及下落时间
t
0
t_0
t0,公式如下:
x
=
x
0
+
v
0
t
+
1
2
g
t
2
x = x_0 + v_0t + \frac{1}{2}gt^2
x=x0+v0t+21gt2
function x = freebody(x0, v0, t)
x = x0 + v0 .* t + 1/2 * 9.8 * t .* t;
注意使用点乘
.*
进行计算,涉及到多维乘法操作时,如果不使用点乘,会无法计算向量或矩阵
具有多个输入和输出的函数
【例2】粒子的加速度和作用力公式如下:
a
=
v
2
−
v
1
t
2
−
t
1
a = \frac{v_2 - v_1}{t_2 - t_1}
a=t2−t1v2−v1
F = m a F = ma F=ma
function [a, F] = acc(v2, v1, t2, t1, m)
a = (v2 - v1)/(t2 - t1);
F = m * a;
2.3.4 练习
-
Write a function that asks for a temperature in degrees Fahrenheit
-
Compute the equivalent temperature in degrees Celsius
-
Show the converted temperature in degrees Celsius
-
The function should keep running until no numberis provided to convert
-
You may want to use these functions:
input, isempty, break, disp, num2str
function C = F2C()
while 1
prompt = 'Please input the temperature in F:';
F = input(prompt);
if isempty(F)
break
end
C = (F - 32) .* (5 / 9);
disp(['Temperature in C: ' num2str(C)]);
end
2.3.5 函数默认变量(Function Default Variables)
自定义函数时,会遇到某些输入变量个数变化的情况,需要我们去进行定义,从而使用者在使用函数时,对于不同的输入形式能得到相应不同的结果:
参数 | 说明 |
---|---|
nargin | 函数输入参数数目 |
nargout | 函数输出参数数目 |
varargin | 可变长度输入参数列表 |
varargout | 可变长度的输出参数列表 |
详情见文档:输入输出参数
2.3.6 函数句柄(Function Handles)
%%
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x,f(x));