1、Script Editor
use command clear all to remove privious variables
use command clear all to close all figures
use semicolon ; at the end of commands to inhibit unwanted output
use ellipsis … to make scripts more readable: A = [1 3 2 4 5 9 ;
… 8 6 5 9 2 7]
use ctrl+c to terminate the script
2、Structure Programing
Flow Control:if,elseif,else,for,switch,case,otherwise,try,catch,while,
break,continue,end,pause,return
if(条件1)
语句1
elseif(条件2)
语句2
......
else
语句n
end
while(条件)
语句
end
switch 开关
case (开关1)
语句1
case(开关2)
语句2
......
case(开关n)
语句n
otherwise
语句
end
i=1;
for n=1:2:10
a(i) = 2^n;
i=i+1;
end
disp(a);
Logical Operators:< <= > >= == ~=(不等于) && ||
pre-allocating:
A
tic
for(ii = 1:2000)
for(jj = 1:2000)
end
end
toc
B
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
B比A快
把A矩阵copy到B,并把A中的负数改为正数:
A=([0 -1 4;9 -14 25;-34 49 64]);
B=zeros(3,3);
for ii=1:3
for jj=1:3
if(A(ii,jj)>0)
B(ii,jj) = A(ii,jj);
else
B(ii,jj) = -A(ii,jj);
end
end
end
disp(B);
3.Functions
function x = freebody(x0,v0,t)
x = x0 +v0*t + 1/2*9.8*t.*t; %注意是点乘.*
end
function [a , F] = acc(v2,v1,t2,t1,m)
a = (v2-v1) ./ (t2-t1);
F = m.*a;
end
华氏度转摄氏度
function C = F2C
prompt = 'Temperature in F = ';
F = input(prompt);
while(~isempty(F))
C = (F-32).*(5/9);
C = num2str(C);
D = ['==>Temperature in C = ' C];
disp(D)
prompt = 'Temperature in F = ';
F = input(prompt);
end
函数默认变量:
inputname(argNumber):返回函数输入的第argNumber个变量名
mfilename:返回正在运行函数的文件名
nargin:返回函数输入参数个数
nargout:返回函数输出参数个数
varargin(variable argument in):返回输入参数表的变量个数
varargout(variable argument out):输出参数表的变量个数
function [volume] = pillar(Do,Di,height)
if nargin == 2 %若只输入两个参数,则需定义height的默认值
height = 1;
end
volume = abs(Do.^2-Di.^2).*height*pi/4;
Function Handles
一种定义无名函数的方法,比如,一条曲线方程,不必定义为函数。
f = @(x) exp(-2*x);
x = 0:0.1:2;
plot(x,f(x));