Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University wanghj@zju.edu.cn Jan 25,2012 References • Product help (F1) • http://www.mathworks.cn/ac ademia/student_center/tutori als/launchpad.html Main content I. introduction II. syntax and command III.M-file programming IV. Advanced programming Chap1.introduction 1.1 1.2 1.3 1.4 Matlab 's history Main features of Matlab Programming environment Matlab Desktop (V2011b) 1.1 Matlab 's history MATLAB = MATrix (Matrices) & LABoratory 1.1 Matlab 's history December 1996 First printing For MATLAB 5 May 1997 Second printing For MATLAB 5.1 September 1998 Third printing For MATLAB 5.3 September 2000 Fourth printing Revised for MATLAB 6 (Release 12) June 2001 Online only Revised for MATLAB 6.1 (Release 12.1) July 2002 Online only Revised for MATLAB 6.5 (Release 13) August 2002 Fifth printing Revised for MATLAB 6.5 June 2004 Sixth printing Revised for MATLAB 7.0 (Release 14) October 2004 Online only Revised for MATLAB 7.0.1 (Release 14SP1) March 2005 Online only Revised for MATLAB 7.0.4 (Release 14SP2) June 2005 Seventh printing Minor revision for MATLAB 7.0.4 (Release 14SP2) September 2005 Online only Minor revision for MATLAB 7.1 (Release 14SP3) March 2006 Online only Minor revision for MATLAB 7.2 (Release 2006a) September 2006 Eighth printing Minor revision for MATLAB 7.3 (Release 2006b) March 2007 Ninth printing Minor revision for MATLAB 7.4 (Release 2007a) September 2007 Tenth printing Minor revision for MATLAB 7.5 (Release 2007b) March 2008 Eleventh printing Minor revision for MATLAB 7.6 (Release 2008a) October 2008 Twelfth printing Minor revision for MATLAB 7.7 (Release 2008b) March 2009 Thirteenth printing Minor revision for MATLAB 7.8 (Release 2009a) September 2009 Fourteenth printing Minor revision for MATLAB 7.9 (Release 2009b) March 2010 Fifteenth printing Minor revision for MATLAB 7.10 (Release 2010a) September 2010 Sixteenth printing Revised for MATLAB 7.11 (R2010b) April 2011 Online only Revised for MATLAB 7.12 (R2011a) September 2011 Seventeenth printingRevised for MATLAB 7.13 (R2011b) 1.2 Main features of Matlab High-level language for technical computing Development environment for managing code, files, and data Interactive tools for iterative exploration, design, and problem solving Mathematical functions for linear algebra, statistics, Fourier analysis, filtering, optimization, and numerical integration 2-D and 3-D graphics functions for visualizing data Tools for building custom graphical user interfaces Functions for integrating MATLAB based algorithms with external applications and languages, such as C, C++, Fortran, Java™, COM, and Microsoft® Excel® 1.3 Programming environment Core functionality as compiled C-code, m-files Additional functionality in Toolboxes (m-files) Interactive operation 8 1.4 Matlab Desktop(V2011b) Start matlab and see(demo) 1.4 Matlab Desktop(V2011b) Command History: View, search, copy, or execute statements you previously entered in the Command Window Command Window: Run MATLAB language statements. Current Folder Browser: Vinew, open, and find files and file content. Perform file management operations. Editor: Create, edit, debug, and analyze files containing MATLAB language statements. Figures: Create, modify, view, and print figures generated with MATLAB. Comparison Tool: View line-by-line differences between two files. Help Browser: View and search the documentation and demos for all your MathWorks products. Profiler: Improve the performance of your MATLAB code. Variable Editor: View array contents in a table format and edit the values. Web Browser: View HTML and related files produced by MATLAB. Workspace Browser: View and change the contents of the workspace. Chap2. syntax and command 2.1 2.2 2.3 2.4 2.5 Basic concept Matrices & Arrays Commonly used commands Flow control Graphics 2.1 Basic concept 1.Identifier Name of functions or variables. • Require Composed by letter, numerical and underline; Not more than 31 characters; Case sensitivity; Can not start by numerical; • Example A,b , c8, d_f 2g, h(k 2.1 Basic concept 2. Constant pi i j eps Realmin Realmax Inf NaN 3.14159265... Imaginary unit Same as i Floating-point relative precision Smallest floating-point number Largest floating-point number Infinity Not-a-number 2.1 Basic concept 3.Variable Just for storage the data. 4.Functions Usually: the name of function is composed by small letters. 2.1 Basic concept 5. Order of identifier Searches a. b. c. d. e. variable in current workspace built-in variable built-in m-file m-file in current directory m-file on search path 2.1 Basic concept 6. Operators + - * / Relational operators == (equal to) < (less than) > (greater than) to) Logical operators & (and) | (or) ~ (not) …… ~= <= >= (not equal) (less than or equal to) (greater than or equal 2.1 Basic concept 7. Expression Variables, constants and functions connected by the operator. a+b c*f(a) 2.1 Basic concept 8. Statement Value of the expression assigned to a variable called assign command statement; <variable> = <expression > a = zeros(2,2); 2.1 Basic concept 9. Comment & others % ; … 2.2 Matrices & Arrays 1.Matrices generate Colon(:) & Brackets([]) ones, zeros, sparse magic, randn linspace,logspace true,false 2.2 Matrices & Arrays 1.Matrices generate Colon(:) Brackets([]) a = [1,2,3;4,5,6;7,8,9] b = 1:2:10 2.2 Matrices & Arrays 2.Operators + * / \ ^ ' ( ) Addition Subtraction Matrices Multiplication Matrices Division Matrices Left division Matrices Power Complex conjugate transpose Specify evaluation order 2.2 Matrices & Arrays .* ./ .\ .^ .' Element-by-element Element-by-element Element-by-element Element-by-element Unconjugated array multiplication division left division power transpose 2.2 Matrices & Arrays 3. Other operate size,length isempty,any,all diag, triu, tril inv,det,svd, …… 2.2 Matrices & Arrays 4.Example A=magic(3) X=[1 3 5]' b=A*X 2.3 Commonly used commands 1.help, lookfor 2.Who,whos,disp 3.Save,load 4.clc, clear 5.cd,dir,pwd,path,!(system) 6.input,ginput 2.4 Flow control 1.Conditional Control if, else, switch % Generate a random number a = randi(100, 1); % If it is even, divide by 2 if rem(a, 2) == 0 disp('a is even') b = a/2; end 2.4 Flow control 1.Conditional Control if, else, switch a = randi(100, 1); if a < 30 disp('small') elseif a < 80 disp('medium') else disp('large') end 2.4 Flow control 1.Conditional Control if, else, switch [dayNum, dayString] = weekday(date, 'long', 'en_US'); witch dayString case 'Monday' disp('Start of the work week') case 'Tuesday' disp('Day 2') case 'Wednesday' disp('Day 3') case 'Thursday' disp('Day 4') case 'Friday' disp('Last day of the work week') otherwise disp('Weekend!') end 2.4 Flow control 2.loop Control— for,while,continue, break for n = 1:9 for m=1:n r(n,m)=m*n; end if n>5, continue; end end r 2.4 Flow control 2.loop Control— for,while,continue, break fibnacci f(1)=1; f(2)=1; n=1; while f(n)+f(n+1)<30 f(n+2)=f(n)+f(n+1); n=n+1; end f 2.4 Flow control 3.error Control— try,throw catch try statement ... statement catch exceptObj statement ... statement end 2.4 Flow control 3.error Control— try,throw,catch try statement … statement catch err statement ... statement end clear a=magic(4); b=eye(3); try c = a * b; [na,ma]=size(a); [nb,mb]=size(b); if (ma~=nb) error('afdas'); err = MException('whj:NotMatch','A=(%d,%d),B=(%d,%d)',na,ma,nb,mb); throw(err); end catch err c=a(1:3,1:3)*b if (strcmp(err.identifier,'whj:NotMatch')) err else rethrow(err); end end exception = MException(msgIdent, msgString, v1, v2, ...) exception = MException('AcctError:Incomplete', ... 'Field ''%s.%s'' is not defined.', ... 'Accounts', 'ClientName'); exception.message ans = Field 'Accounts.ClientName' is not defined. 2.5 Graphics 1. 2D Graphics plot, plotyy, subplot, loglog, semilogx,semilogy hist,histc,staris area, fill, pie, bar,barh, stem, errorbar, polar,rose, fplot,ezplot scatter, Image,imagesc, pcolor,imshow 2.5 Graphics 2. Figure tool grid on, grid off title, xlabel, ylabel, zlabel, text axis ij, axis equal close 2.5 Graphics 3. 3D Graphics plot3,pie3 mesh,meshc,meshz surf,waterfall,surfc contour,quiver,fill3 tem3,slice,scatter3 2.5 Graphics 3. 3D Graphics Dis3D_topo_demo 2.5 Graphics 4. Others plot Plot catalog select a variable from the workspace and see the graphics menu … Chap3. M-file programming 3.1 Scripts m-file 3.2 function m-file 3.3 Function calls and parameter passing 3.4 Debug m-file 3.1 Scripts m-file 1. Just only composed by a bunch of instruction set (including the control flow of instructions including ) 42 3.1 Scripts m-file 2. Variable storaged in the base workspace shared with the command window. 3.1 Scripts m-file 3. Example %circle.m clf; r=2; t=0:pi/100:2*pi; x=r*exp(i*t); plot(x,'r*'); axis('square'); 3.2 function m-file 1. Just only add a function declare line in the scripts m-file. function y = mean(x) % claculate the mean value % for vecter, mean(x) return the mean value % for matrices, MEAN(x) is a vecter, each element is the mean value of the Column vecter of matrces. % whi, 1/25/2012 [m,n]=size(x); if m==1 m=n; end y=sum(x)/m; 3.2 function m-file 2. Variable storaged in the function workspace separated with the command window. 46 3.2 function m-file 3. Primary and Subfunctions funciton a = prifun(x) ….. r=3; a = 2 + subfun(r); function b = subfun(r) … 47 3.2 function m-file 4. style Declare function line %Comment line %Help online zone (lookfor、help) %Edit record and copyright infomation Function body 48 3.3 Function calls and parameter passing 1. Local and global variable K = 1; ki = 105; f = anim(K,ki); image(f.cdata); 49 3.3 Function calls and parameter passing 2. Functions calls [out1,out2,~,out3] = fun(in1,in2,…); function [y1,y2,y3] = fun1(x1,x2,x3) % demo functions calls % x1,x2,x3: input argument parameters % y1,y2,y3: output argument parameters %{ [y1,~,y3] = fun1(1,2,4); %} % whj,1/25/2012 y1 = x1+x2; y2 = x2+x3; y3 = x3+x1; 50 3.3 Function calls and parameter passing 3. Parameter passing with adjustable parameters K = 1; ki = 105; f = anim(K,ki); image(f.cdata); 51 3.3 Function calls and parameter passing 3. Parameter passing with adjustable parameters argin argout 52 3.3 Function calls and parameter passing 4. Pass across the space variable x= evalin(‘base’, ‘K’) 53 3.4 Debug m-file 1. Two type errors Syntax variable name error … Run-time Algorithm error 54 3.4 Debug m-file 2. Using debug tools 55 Debug tool Debug menu Continue:恢复程序运行至结束或另一个断点 。 Single Step:单步执行函数。 Step In:深入下层局部工作区 。 Quit Debugging:退出调试状态。 Set/Clear Breakpoint:设置/清除光标处的断点 。 Clear All Breakpoints:清除程序中的所有断点 。 Stop if Error:运行至出错或结束。 Stop if Warning:运行至警告消息或结束。 Stop if NaN of Inf:运行至运算结果出现 NaN 或 Inf。 Chap4. Advanced programming 4.1 File Operate 4.2 Graphice User Interface(GUI) 4.3 Application Programming Interface(API) 4.4 complier 4.1 File Operate 1. 2. 3. 4. 5. fopen,fclose fread,fwirte xlsread,xlswrite getline Fprintf 59 (1)open &close fid=fopen(‘datafile’,‘r’) ‘r’ —— read ‘w’ —— write ‘a’ —— add ‘rt’ —— read &write 浙江大学地球科学系 王华军 60 (1)open &close fclose(fid) fclose(all) 61 close fid close all (1) open &close For spacial *.mat save load 浙江大学地球科学系 王华军 62 (2)read &write fread fwrite 63 (2)Example(Binary) %write a=1:50; fid=fopen('user.dat', 'w'); fwrite(fid,a); fclose(fid); 浙江大学地球科学系 王华军 64 (2) Example(Binary) %read fid=fopen('user.dat','r'); a=fread(fid,50); fclose(fid); (3) Examples 1.(newful) mrrDpro.m 2.(newfel) 2D visulization 3. actic em31 figure 4. 3dVisualize 4.2 Graphice User Interface(GUI) 67 Graphice User Interface(GUI) MATLAB能够以比较简单的方式实现一系列的图形界面功能。通过对控 件、菜单属性的设置和 Callback 的编写,就能够满足大多数用户的需 求。 控件的 Callback 属性: Callback 属性的取值是字符串,可以是某个 M文件名或一小段MATLAB语句。当用户激活控件对象(例如 :在控件对象 图标上单击鼠标左键 )时,应用程序就运行 Callback 属性定义的子程 序。 菜单的 Callback 属性: Callback 属性的取值是字符串,可以是某 个M文件名或一小段MATLAB语句。当用户激活菜单对象时,若没有子菜单 就运行 Callback 属性定义的子程序。若有,先运行 Callback 属性定 义的子程序,再显示子菜单。 68 4.3 Application Programming Interface Interface with C,fortran,excel 69 4.3 Application Programming Interface Example for C 70 4.4 complier 1.mcc mcc[-options] fun [fun2 ...] [mexfile1 ...] mlibfile1 ...] 2.Tools 71 4.4 complier 2.Tools • • Deployment project Code Generation Project 72 4.4 complier 2.Tools • • Deployment project Code Generation Project 73 Practice and practice 一旦你学会了基本语法,设计程序的能力 取决于你的知识和掌握函数的多少及熟练 程度. Once you learn the basic syntax, the ability of the program design depends on your knowledge and how many functions you have mastered and proficiency. Thanks!