MATLAB Script
%:注解
%%:分节符
Relational Operators
< <= > >= == ~=(not equal to) &&(and) ||(or)
Script Flow
if elseif else
if condition1
statement1
elseif condition2
statement2
else
statement3
end %每一个区块都需要一个end
%ram(a,2)取余,a/2的余数
%disp('')输出语句,disp()输出变量
switch
switch expression
case value1
statement1
case value2
statement2
…………
otherwise
statement
end
while
while expression
statement
end
EG:
n = 1;
while prod(1:n) < 1e100 %prod累积
n = n+1;
end
for
for variable=start:increment:end
commands
end
EG:
for n=1:10 %1:2:10
a(n) = 2^n;
end
disp(a) %disp(find(a))
Pre - allocationg(节约时间)
Not pre-allocating
tic
for ii = 1:2000
for jj = 1:2000
A(ii,jj) = ii+jj;
end
end
toc
Pre-allocating
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
%tic---toc为计时组件
break ==> while
x = 2; k = 0; error = inf;
error_threshold = 1e-32;
while error_threshold
if k>100
break
end
x = x-sin(x)/cos(x);
error = abs(x-pi);
k = k+1;
end
注:clear all:清楚变量
close all:关闭图形
Ctrl + C:避免宕机,跳出程序
Function
edit(which('mean.m')) %进入一个mean function的源码
function y = mean()
%……
%……
%……
if nargin == 1 || (nargin == 2 && isDimSet)
……………………
Default Variables
nargin:Number of function input arguments
function [volume] = pillar(Do, di ,height)
if nargin == 2
haight = 1;
nargout:Number of function output arguments
varargin、varargout:Variable length input/output argument list
inputname:Variable name of function input
mfilename:File name of currently running function
Handles
f = @(x) exp(-2*x); %f指向后面的exp(……),@(x)是f的input
x = 0:0.1:2;
plot(x,f(x)); %画图
%将X于f(x)绑定,将x放入对应法则中