文章目录
02 结构化程序与自定义函数
- 编写脚本
- 结构化编程
- 自定义函数
编写脚本
- A file containing a series of MATLAB commands
MATLAB脚本是一个包含一系列MATLAB命令的文件 - Pretty much like a C/C++ program
与 C/C++ 程序类似 - Scripts need to be saved to a
<file>.mfile before they can be run
脚本运行前 需要保存为<file>.m文件
不需要编译 是解释型语言
Start UP

忘记函数名?

![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ptsN9kYt-1660124233889)(image/image-20211008163659762.png)]](https://i-blog.csdnimg.cn/blog_migrate/72df67a2b0d56ef13617bb8f99219b23.png)
需要调试程序?
-
MATLAB中的注释符号是
% -
如果使用
%%会将代码标记为section(区块) 可以将代码分块运行 -
选中多行后 单击右键 选择
Comment可注释多行 快捷键为Ctrl + R- 取消注释的快捷键为
Ctrl + T
- 取消注释的快捷键为
断点调试
单击行号 使用断点 breakpoint
关于断点测试
MATLAB 在执行到断点处时, 会暂停执行, 可以对前面已执行部分的变量进行检查

自动缩进
选中需要缩进的代码 点击右键 选择 smart indent 可以自动添加缩进

快捷键 : ctrl + I
结构化编程
使用循环结构, 条件结构 等 使程序更加简洁
if,elseif,else条件为真时执行代码块for多次执行代码块switch,case,otherwise分支语句,otherwise相当于defaulttry,catch异常处理while条件为真时重复执行代码块break终止当前(最近的)循环continue跳过当前循环end终止代码块 或 用于标明数组的最后一个下标pause暂停执行return返回到调用函数
if elseif else
if condition1
statement1
elseif condition2
statement2
else
statement3
end
elseif和else是可选的
示例程序
% 判断奇偶数
a = 3;
if rem(a,2) == 0
disp('a is even')
else
disp('a is odd')
end
rem(para1, para2)函数,用于求余数 余数(remainder)
第一个参数是除数, 第二个参数是被除数rem(para1, para2)相当于para1 % para2, 即para1对para2求模
switch
switch expression
case value1
statement1
case value2
statement2
.
.
.
otherwise
statement
end
将
expression与value进行逻辑比较, 如果结果为真, 则执行该分支下的语句当
otherwise分支存在时
会在所有value都与expression不匹配时, 执行otherwise分支下的语句相当于编程语言中的
default❗️注意 与编程语言不同的是
MATLAB中的switch语句不会出现case穿透现象, 不需要加break
示例程序
input_num = 1;
switch input_num
case -1
disp('negative 1');
case 0
disp('zere');
case 1
disp('positive 1');
while
while expression
statement
end
当
expression成立的时候, 执行statement, 直到expression不成立
示例程序
n = 1;
while prod(1:n) < 1e100
n = n + 1;
end
prod()表示乘积 (product)
1:n表示从1到n的向量
prod(1:n)表示n!阶乘
e100表示 1 0 100 10^{100} 10100
1e100表示 1 × 1 0 100 1\times 10^{100} 1×10100
for
for variable=start:increment:ending
commands
end
start是起始值,ending是结束值
increment是步长
1:10= [1,2,3,4,…,10]
1:2:10= [1,3,5,7,9]不指定步长时, 默认步长为 1
示例程序
for n=1:10
a(n)=2^n;
end
disp(a)
上式的
a是一个数组
为变量预分配空间
Pre-allocating Space to Variables
看下面两个示例程序
tic
for ii = 1:2000
for jj = 1:2000
A(ii,jj) = ii + jj;
end
end
toc
tic
A = zeros(2000,2000)
for ii = 1:size(A,1)
for jj = 1:size(A,2)
A(ii,jj) = ii + jj
end
end
toc
第一个程序没有预分配空间, 在对A矩阵进行赋值时, 会不断对A进行扩容
第二个程序对A预分配空间, 不需要扩容, 效率更高
tic开始计时
toc结束计时可以得到运行代码块的时间
逻辑运算符
| Operator | Meaning |
|---|---|
< | Less than |
<= | Less than or equal to |
> | Greater than |
>= | Greater than or equal to |
== | Equal to |
~= | Not equal to |
&& | And |
| ` | ` |
以上运算符的运算结果均是
boolean类型
Tips for Script Writing
-
在脚本的开始处
- 使用
clear all先前所有的变量 - 使用
close all关闭所有的图形
- 使用
-
在语句的结尾添加分号
;避免不需要的输出 -
使用换行号
...增加程序的可读性-
A = [1 2 3 4 5 6; ... 6 5 4 3 2 1];
-
-
遇到错误时(如死循环), 使用
ctrl + c终止程序的运行
函数
函数与脚本的区别
- 相同点
- 脚本和函数都是包含
MATLAB命令的.m文件 - 需要执行相同操作(routines) 时, 可以编写函数
- 脚本和函数都是包含
- 不同点
- 脚本
- 没有输入参数与返回参数
- Operate on data in the global workspace
操作全局工作区的数据
- 函数
- (可以)有输入参数与返回参数
- Operate on data in the local workspace
操作局部工作区的数据
- 脚本
MATLAB的内置函数
edit(which('mean.m'))
mean是计算平均值的函数使用:
a[10 16 27 64];
mean(a)可计算数组a的平均值

自定义函数
User Define Function
- 写一个可以计算给定初始位置
x
0
x_0
x0, 初速度
v
o
v_o
vo, 时间
t
t
t 内自由落体的函数:
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,vO,t)
% calculation of free falling
% 0: initial displacement in m
% vO: initial velocity in m/sec
% t: the elapsed time in sec
% x: the depth of falling in m
X = ×0 + v0.*t + 1/2*9.8*t.*t;
*是数字之间直接相乘
如果输入向量, 会将两个向量直接相乘
.*是元素之间相乘
如果输入向量, 是将向量的对应元素相乘
多个参数与返回值的函数
质点的加速度和受力如下:
a
=
v
2
−
v
1
t
2
−
t
1
F
=
m
a
\begin{aligned} a&=\frac{v_2-v_1}{t_2-t_1}\\ F&=ma \end{aligned}
aF=t2−t1v2−v1=ma
function [a F] = acc(v2,v1,t2,t1,m)
a = (v2-v1)./(t2-t1);
F = m.*a;
调用以上函数:
[Acc Force] = acc(20,10,5,4,1)
Exercise
- 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 number is provided to convert
- You may want to use these functions:
input,isempty,break,disp,num2str
函数的默认参数
在没有给出对应参数时, 函数应该使用默认参数进行运算
实现这样的功能, 会用到以下默认变量
inputnameVariable name of function input 参数名mfilenameFile name of currently running function 当前函数的文件名narginNumber of function input arguments 参数数量nargoutNumber of function output arguments 返回值数量vararginVariable length input argument list 参数长度(向量参数)varargoutVariable length output argument list 返回值长度(向量返回值)
function [volume] = pillar(Do, Di, height)
if nargin==2, % 如果输入的参数只有两个(没有输入 height)
height=1; % 默认 height 设为 1
end
volume=abs(Do.*2-Di.^2).*height*pi/4;
Function Handle
创建匿名函数的方法
一个曲线的表达式没必要创建一个 .m 文件来储存
f = @(x) exp(-2*x); %此行为 Function Handle
x = 0:0.1:2;
plot(x,f(x));
可以认为 f 是指向后面表达式 exp(-2*x) 的一个指针
本文介绍MATLAB编程的基础知识,包括脚本编写、结构化编程、自定义函数等内容,并通过实例讲解了条件语句、循环语句及逻辑运算符的使用方法。

6639

被折叠的 条评论
为什么被折叠?



