MATLAB Introduction to MATLAB Matlab 3 Mat Lab
MATLAB 简介 Introduction to MATLAB 门爱东教授
Matlab 开始 3
Mat. Lab 开始:窗 (Windows) n 命令窗 Command Window ³ MATLAB 解释器,即时计算/反馈/评价 » 3. 5*6. 2 » exp(1 j*3*pi/4) ans = 21. 7000 » -0. 7071 + 0. 7071 i » 7
Matlab 基础:矩阵数据结构 n 作空间 (Workspace) clear 函 数 从 作空间中清除 变量(函数) clear t=0: 5; T=0: 0. 5: 5; who » Your variables are: T t » whos Name T t Size 1 x 11 1 x 6 Bytes 88 48 Class double array Grand total is 17 elements using 136 bytes n 非常快速的键入; » a=exp(1 j*t); whos 16
Mat. Lab 基础:命令行编辑器 n Single-Stroke Editing Capabilities ³ ³ ³ Up-Arrow, Ctrl-P Recall previous line Down-Arrow, Ctrl-N Recall next line Left-Arrow, Ctrl-B Move back (left) one character Right-Arrow, Ctrl-F Move forward (right) one character Ctrl-Left-Arrow, Ctrl-L Move left one word Ctrl-Right-Arrow, Ctrl-R Move right one word Home, Ctrl-A Move to beginning of command line End, Ctrl-E Move to end of command line Esc, Ctrl-U Clear command line Del, Ctrl-D Delete character at cursor Backspace Delete character left of cursor Ctrl-K Delete to end of line n “Smart Recall” also available n Can modify editor behavior via the command cedit 18
Mat. Lab 基础:获得帮助 n 几种方法 ³命令行 » help HELP topics: matlabgeneral : matlabfunfun : toolboxsignal - - General purpose commands. - Function functions and ODE solvers. Signal Processing Toolbox. For more help on directory/topic, type "help topic". ³下拉菜单 Help ±注意: 多种方式,包括 HTML and PDF 25
Mat. Lab 基础:获得帮助 n lookfor 命令将在大多数 help 主题中进行关键词 搜索 (用 Ctrl-C 终止搜索,可能需要一定时间) n 注意在命令行 help 描述中命令 都采用大写字母 » help eps EPS Floating point relative accuracy. EPS returns the distance from 1. 0 to the next largest floating point number. EPS is used as a default tolerance by PINV and RANK, as well as several other MATLAB functions. See also REALMAX, REALMIN. » EPS ? ? ? Undefined variable or capitalized internal function EPS; Caps Lock may be on. » eps = 2. 2204 e-016 26
Matlab 基础:举例 n MATrix LABoratory » a=[1 2 3]; a*a' ans = 14 » a=[1 2 3]; a*a ? ? ? Error using ==> * Inner matrix dimensions must agree. 基于矩阵的有效的计算 » a=[1 2 3]; a. *a ans = 1 4 9 » sum(a) ans = 6 » b=a. *exp(a. ^2) b = 1. 0 e+004 * 0. 0003 0. 0109 » b(1) ans = 2. 7183 2. 4309 27
MATLAB 程序:简单的变量分配 n 标量 Scalars » clear; a=1; b=2. 0; c=1+j*2; d='Hello'; whos Name Size Bytes Class a b c d 1 x 1 1 x 5 8 8 16 10 double array char array (complex) Grand total is 8 elements using 42 bytes 35
MATLAB 程序:简单的变量分配 n 阵列 Arrays (实数、复数、字符)==>(double, complex, char) » clear; a=0: 0. 1: 1; b=[0: 0. 1: 1]; c=[0: 0. 1: 1]'; » d=[0 j 1]; e=[1 'abc' 3]; whos Name Size Bytes Class a b c d e 1 x 11 11 x 1 1 x 3 1 x 5 88 88 88 48 10 double array char array (complex) Grand total is 41 elements using 322 bytes What is the content of variable e ? 36
MATLAB 程序:简单的变量分配 n 矩阵 (实数、复数) » clear; a=[0 1; 5 9]; b=[j 1; 0 2]; » c=[a b]; d=[a; b]; e=[]; whos Name Size Bytes Class a b c d e 2 x 2 2 x 4 4 x 2 0 x 0 32 64 128 0 double double array (complex) array Grand total is 24 elements using 352 bytes 利用 “空矩阵 [ ]” 分配,例如上述的 e 变量,用于 各种初始化任务,例如预先分配内存空间。 37
MATLAB 程序:简单的变量分配 n 矩阵 (稀疏和字符) » clear; a=[1 0; 0 1]; b=sparse(a); » c=['who' 'is'; 'that? ']; whos Name Size Bytes Class a b c 2 x 2 2 x 5 32 36 20 double array sparse array char array Grand total is 16 elements using 88 bytes » c c = whois that? » c=['who' 'is'; 'there? '] ? ? ? All rows in the bracketed expression must have the same number of columns. 38
MATLAB 程序:变量分配 n 多维阵列 ³范例:“same-size 矩阵的集合” » clear; A=zeros(2, 2, 3); whos Name Size Bytes Class A 2 x 2 x 3 96 double array Grand total is 12 elements using 96 bytes » A(: , 2)=eye(2) A(: , 1) = 0 0 A(: , 2) = 1 0 0 1 A(: , 3) = 0 0 39
MATLAB 程序:变量分配 n 单元阵列 Cell Arrays ³范例: “various elements 各种元素的集合” » clear; A={'stuff' [1 2; 3 4] [0: 4]}; whos Name Size Bytes Class A 1 x 3 358 cell array Grand total is 17 elements using 358 bytes » A A = 'stuff' » A(2) [2 x 2 double] [1 x 5 double] % The parentheses provide a cell ans = [2 x 2 double] » A{2} A = 1 3 % Curly brackets extract what’s underneath 2 4 The use of curly brackets { } is new in Version 5. 40
MATLAB 程序:变量分配 n 结构 Structures ³范例: “结构化的数据集合” » mystuff. name='Jerry'; mystuff. age=35; » mystuff. family={'Chris' 'Margo' 'Max'} mystuff = name: 'Jerry' age: 34 family: {1 x 3 cell} » whos Name Size Bytes Class mystuff 1 x 1 692 struct array Grand total is 25 elements using 692 bytes » help struct STRUCT Create or convert to structure array. . See also CLASS, CELL, GETFIELD, SETFIELD, RMFIELD, FIELDNAMES. 也能产生结构“阵列” 注意: MATLAB Objects are structures with methods! 41
MATLAB 函数:阵列运算 n 阵列运算:两个相同大小的矩阵的元素对元素运算 n 特别注意:阵列(Array)运算和矩阵(Matrix)运算不相同! a= 3 2 4 1 2 5 b= 5 8 6 9 7 10 a. *b = 15 16 24 9 14 50 » x=0: 1: 5; pofx=x^2+2*x+1 ? ? ? Error using ==> ^ Matrix must be square. » pofx=x. ^2+2*x+1 pofx = 1 4 9 16 25 36 44
MATLAB 函数:阵列运算 n 关键是 “. ” 和非矩阵函数 » t=linspace(0, 2*pi, 5) t = 0 1. 5708 3. 1416 » cos(t). ^2+sin(t). ^2 ans = 1 1 4. 712 6. 2832 1 45
MATLAB 函数:矩阵运算 n 行/列 内部维数必须一致 » a=[2 3; 5 1]; b=[1 2]; c=a*b ? ? ? Error using ==> * Inner matrix dimensions must agree. » c=a*b' c = 8 7 n 选择合适的 MATLAB 函数! (“m” suffix) » a=[2 0; 0 3]; exp(a), expm(a) ans = 7. 38905609893065 1. 00000000000000 20. 08553692318767 ans = 7. 38905609893065 0 0 20. 08553692318770 47
MATLAB 函数:数据分析函数 n 更多…. . ³ ³ ³ ³ chol cond det eig expm inv logm lu norm null poly rank rref Cholesky 因数分解 矩阵制约数 行列式 特征值和特征向量 Eigenvalues and eigenvectors 矩阵指数 逆矩阵 矩阵对数 LU 因子 矩阵和向量范数 Null space 特征多项式 矩阵秩 Reduced row echelon form ³ and many, many more 53
MATLAB 绘图:简单的 2 D 绘图 n 2 D 绘图举例 » t=[0: 0. 1: 2*pi]; plot(t, cos(t)) 1 0. 8 0. 6 0. 4 0. 2 0 -0. 2 -0. 4 -0. 6 -0. 8 -1 0 1 2 3 4 5 6 7 58
MATLAB 绘图:简单的 2 D 绘图 n 2 D 基本绘图的扩展. . . Example Plot 1 0. 8 t=0: 0. 01: 10; p 1=cos(t); p 2=sin(t); p 3=p 1. *p 2; plot(t, p 1, t, p 2, t, p 3) title('Example Plot') xlabel('t (seconds)') 0. 6 0. 4 0. 2 0 -0. 2 -0. 4 -0. 6 -0. 8 -1 0 2 4 6 t (seconds) 8 10 59
MATLAB 绘图:专业 2 D 绘图 n 对于离散系统研究:stem n=0: 20; xn=(0. 7. ^n). *cos(2*pi*n/6); stem(n, xn) title('Discrete Sequence') xlabel('n (sample number)') ylabel('x(n)') axis([-2 22 -0. 4 1. 2]) Discrete Sequence 1 0. 8 0. 6 0. 4 x(n) 0. 2 0 -0. 2 -0. 4 0 5 10 15 20 n (sample number) 60
MATLAB 绘图:专业 2 D 绘图 n 极线图 polar n 直方图 hist theta=linspace(0, 6*pi, 300); rho=2+exp(-0. 2*theta). *cos(5*theta); polar(theta, rho) x=randn(1, 1000); hist(x, 10) 250 90 120 60 2 200 150 30 1 150 180 0 100 330 210 50 240 0 -3 -2 -1 0 1 2 3 4 300 270 61
MATLAB 绘图: 3 D 绘图 n 3 D 线和点 ³ plot 3 comet 3 and others n 等高线(轮廓) ³ contour 3 and others n 表面和网孔 Surfaces and Meshes ³ mesh ³ surf ³ slice meshc meshz surfc surfl waterfall and others n 色度映射、光和阴影 具,以及许多专门的图象显示和 分析 具 62
MATLAB 绘图: 3 D 绘图 n 交互式 3 D 绘图 z=[0: 0. 1: 5*(2*pi)]; f=exp(j*z); x=real(f); y=imag(f); plot 3(x, y, z) 40 30 20 10 figure(1) comet 3(x, y, z) 0 1 0. 5 0 0 -0. 5 -1 -1 63
MATLAB 绘图: 3 D 绘图 n 基本的 Setup 建立:meshgrid clear, x=-2: 0. 1: 2; y=-1: 0. 1: 1; Z=X. *exp(-X. ^2 -Y. ^2); whos Name Size Bytes X 21 x 41 6888 Y 21 x 41 6888 Z 21 x 41 6888 x 1 x 41 328 y 1 x 21 168 [X, Y]=meshgrid(x, y); Class double double array array n 对矩阵 z 应用绘图程序 64
MATLAB 绘图: 3 D 绘图 0. 5 meshc(Z) 0 -0. 5 30 20 10 0 0 10 20 30 40 50 注意: 使用 meshc(x, y, Z) 能提供更针对性的坐标轴 65
MATLAB 绘图: 3 D 绘图 mesh(x, y, Z), view(-15, 40) 0. 5 0 -0. 5 1 0. 5 0 -0. 5 -1 -2 -1 0 1 2 66
Matlab 程序流程控制:逻辑运算 n 更多……. . (参见 help ) ³ exist determine if variable/dir/file exists ³ isa determine type of data element ³ ischar determine if char/string ³ isfinite determine if value is finite ³ isglobal determine if variable global ³ isinf determine if value is IEEE infinity ³ isobject determine if user-defined object type ³ issparse determine if sparse matrix ³ isstr determine if string variable ³ etc. 72
Matlab 程序流程控制:if、else 和 end n 多项式求和的例子 p 1=[1 5 4]; p 2=[1 6 11 6]; n 1=length(p 1); n 2=length(p 2); if n 1<n 2, p 1=[zeros(1, n 2 -n 1) p 1]; else p 2=[zeros(1, n 1 -n 2) p 2]; end psum=p 1+p 2 psum = 1 7 16 10 n 注意. . . MATLAB 命令 break 允许提早终止 IF 结构。 77
Matlab 程序文本:脚本文件 n 通过传统文本编辑器生成 n 通过在提示符处简单地键入 polysum. m。 文件名 polysum 来“运行” % POLYSUM Sums p 1 and p 2 % with result in psum n 1=length(p 1); n 2=length(p 2); if n 1<n 2, p 1=[zeros(1, n 2 -n 1) p 1]; else p 2=[zeros(1, n 1 -n 2) p 2]; end psum=p 1+p 2 % Last line of file polysum. m 事先输入变 量的数值 » p 1=[1 2]; p 2=[1 3 2]; » polysum psum = 1 4 4 » p 1=[1 6 9 3]; p 2=[1 4 2]; » polysum psum = 1 7 13 5 » help polysum POLYSUM Sums p 1 and p 2 with result in psum » which polysum f: matlab 5classpolysum. m 80
Matlab 程序文本:函数文本 n 在提示符处简单地键入文件名 和所需参数来“运行”函数 n 通过传统文本编辑器生成 function [psum]=plysum(p 1, p 2) % PLYSUM Sum of two polys % p 1 and p 2 in the % command plysumf(p 1, p 2) n 1=length(p 1); n 2=length(p 2); if n 1<n 2, p 1=[zeros(1, n 2 -n 1) p 1]; else p 2=[zeros(1, n 1 -n 2) p 2]; end psum=p 1+p 2; % Last line of file plysum. m » a=[1 2]; b=[1 -1 3]; » plysum(a, b) ans = 1 0 5 » a a = 1 2 » help plysum PLYSUM Sum of two polys p 1 and p 2 in the command plysum(p 1, p 2) » which plysum f: matlab 5classplysum. m 82
MATLAB 程序:练习 n linspace 的使用是可预测的,但 logspace 稍微有点不同,请比较下列绘图结果 … t=logspace(0, 2, 30); plot(t, t, '*'); pause; semilogx(t, t, '*'); pause; loglog(t, t, '*') n 更深入一点研究字符串变量,请考虑下述结果… a='Hello'; abs(a) dec 2 hex(abs(a)) b=sqrt(2); c=rats(b) length(c) 84
主题概述 1 Matlab 开始 2 Matlab 基础 3 Matlab 程序 4 Matlab 扩展 ³Toolbox 概念 ³MATLABPATH 和 M-file 结构 ³Matlab 路径 ³SIMULINK 5 Matlab 进阶 87
Matlab 扩展:Toolbox 概念 n Toolbox: ³完成特定 作的 Tools (M-files) ³各领域的专家编写 ³Demo 演示了 Tools 应用 n Math. Works, Inc. (NOT FREE!!!!) ³Signal Processing ³Image Processing ³Communications ³Filter Design ³Wavelet ³ Neural Network ³ Optimization ³ ………. . . 88
Matlab 扩展: MATLABPATH n 当启动 Matlab 时,它需要知道到何处寻找 M-files,关键 点是 MATLABPATH ,可以通过下述命令浏览和修改路 径: path、 addpath、 rmpath etc. 或者 File/Set path…. 下拉菜单。 » path MATLABPATH c: matlab 5toolboxmatlabgeneral c: matlab 5toolboxmatlabops c: matlab 5toolboxmatlablang c: matlab 5toolboxmatlabelmat : c: matlab 5toolboxmatlabgraph 2 d : c: matlab 5toolboxmatlabdemos c: matlab 5toolboxcomm c: matlab 5toolboxsimulink : 90
Matlab 扩展:SIMULINK n 什么是 SIMULINK? ³ 动态系统仿真软件 “Dynamic System Simulation Software” n 换言之. . . 一种图形用户接口:以框图的形式定义动态系统。 数字仿 真结果由 Matlab 后台计算得到。 SIMULINK is a registered trademark of The Math. Works, Inc. 93
Matlab 进阶:更高效率,减少循环 n “无论什么情况下,都把 for 和 while 循环转换为阵 列和矩阵运算” (120 MHz Pentium) » tic; x=0; for i=1: 100000, x=x+i; end, x, toc x = 5. 0000 e+009 elapsed_time = 4. 1200 » tic; x=sum([1: 100000]), toc x = 5. 0000 e+009 elapsed_time = 0. 1700 » tic; x=zeros(1, 1000); for i=1: 1000, x(i)=sin(2*pi*i/1000); end, toc elapsed_time = 0. 2700 » tic; x=sin(2*pi*[1: 1000]/1000); toc elapsed_time = 0 ç Note: this was all executed on one line, only written on two to fit this slide! Your "mileage" may vary. "clear" before test. 98
Matlab 进阶:输入输出数据 n 注意: . m M-files 是简单的文本,因此, 它们能够在不同 MATLAB 间传递和利用。 而且,. mat 文件可在不同平台间传递。 n 输入. . . ³ load ³ fread ³ MEX ³ MAT 来自 “flat” ASCII file 对 non-flat, non-ASCII 文件的低级访问 External interface, 使用 C 或 FORTRAN I/O 格式化数据,形如 MATLAB. mat 文件 n 输出. . . ³ diary ³ save ³ fwrite ³ MEX ³ MAT 从日志 logfile 中剪贴 存为 “flat” ASCII file 存为低级的 non-flat, non-ASCII 文件 External interface, 用于 C or FORTRAN 接口 使用 save without ASCII, 存为. mat 文件 100
Matlab 进阶:输入输出数据 n 输入举例 ³外部程序 (Text 编辑器) 写下列文件 mydat. dat 1. 0 2. 0 3. 5 12. 3 5. 1 44. 7 4. 2 -1. 56 2. 0 ³读入为 MATLAB 变量. . . » load mydat. dat » mydat = 1. 0000 12. 3000 2. 0000 44. 7000 3. 5000 -1. 5600 5. 1000 4. 2000 2. 0000 101
MATLAB 进阶:调试命令 MATLAB 调试举例 » dbclear all » dbtype t 1 1 function [res 1]=t 1(c 1) 2 % T 1 Simple test function [res 1]=t 1(c 1) a 1=20; % T 1 Simple test function 3 4 b 1=t 2(a 1); a 1=20; 5 res 1=b 1*c 1; b 1=t 2(a 1); 6 % Last line of t 1. m res 1=b 1*c 1; » dbstop t 1 % Last line of t 1. m » dbstop in t 1 at 5 » dbstop in t 2 at 4 » t 1(5) function [res 2]=t 2(c 2) …. . debug window opens t 1. m …. . % T 2 Another test function K» who a 2=40; Your variables are: res 2=a 2*c 2; % Last line of t 2. m c 1 Continued. . 104
MATLAB 进阶:调试命令 K» dbcont K» who Your variables are: a 2 c 2 K» dbstack In c: . . . . t 2. m at line 4 In c: . . . . t 1. m at line 4 K» dbup In workspace belonging to c: . . . . t 1. m. K» who Your variables are: a 1 c 1 K» dbdown In workspace belonging to c: . . . . t 2. m. Continued. . 105
参考资料 n USENET NEWS Forum for MATLAB Users ³Read the group comp. soft-sys. matlab n Math. Works 教育网站 ³http: //www. mathworks. com/education/ n Anonymous FTP Archive ³FTP to ftp. mathworks. com n The Math. Works Newsletter ³ Quarterly publication, subscribe to newsletter@mathworks. com n Textbooks Incorporating MATLAB ³ http: //www. mathworks. com/education/books. sh tml 108
谢谢! menad@bupt. edu. cn
- Slides: 109