结构化程序及自定义函数
杂记
注解与分块
Comment:%
Section:%%
逻辑运算符
Not equal to: ~=
And: &&
Or: ||
disp(variable):display the value of a variable(can be a string)
Pre-allocating
%A
for n = 1:10
a(n) = 2^n
end
disp(a)
%B
a = zeros(1,10)
for n = 1:10
a(n) = 2^n
end
disp(a)
In A example,we do not pre-allocate space to vector a rather than letting MATLAB resize it on every iteration.
B runs faster than A
计时
tic
commands
toc
其他
- clear variable/all : to remove variable(s)
- close all : to close all figures
- clc : 清空命令行窗口
- … : 换行
- ctrl + C : 强行停止程序运行
各种结构(加end)
if elseif else
if condition1
statement1
elseif condition2
statement2
else condition3
statement3
end
switch
switch expression
case value1
statement1
case value2
statement2
otherwise
statement
end
由expression得到的value对应一个case,运行那个case下的语句
while
while condition
statement
end
break continue
for
for variable=start:increment:end
commands
end
函数
内置函数
查看内置函数的代码
edit(which('function.m'))
nargin, nargout, varargin, varargout
- nargin/nargin(‘function name’):函数输入参数个数
- nargout/nargout(‘function name’):函数输出参数个数
详细介绍
自定义函数(脚本名要与函数名相同)
例:自由落体运动的路程
f
=
x
0
+
v
0
t
+
1
/
2
g
t
2
f = x_0+v_0t+1/2gt^2
f=x0+v0t+1/2gt2
function y = freebody(x0, v0, t) % 输出多个变量时:function [a f] = ...
% calculation of free falling
% x0: initial displacment in m
% ...
y = x0 + v0.*t + 1/2 *9.8 *t.*t;
% *,/必须用.*, ./在使用矩阵计算的时候会发挥用处
函数句柄(匿名函数)
f = @(x) exp(-2*x)