Presentation is loading. Please wait.

Presentation is loading. Please wait.

Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University Jan 25,2012.

Similar presentations


Presentation on theme: "Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University Jan 25,2012."— Presentation transcript:

1 Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University wanghj@zju.edu.cn Jan 25,2012

2 References Product help (F1) http://www.mathworks.cn/ac ademia/student_center/tutori als/launchpad.html

3 Main content I.introduction II.syntax and command III.M-file programming IV.Advanced programming

4 Chap1. introduction 1.1 Matlab 's history 1.2 Main features of Matlab 1.3 Programming environment 1.4 Matlab Desktop (V2011b)

5 1.1 Matlab 's history MATLAB = MATrix (Matrices) & LABoratory

6 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)

7 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®

8 8 1.3 Programming environment  Core functionality as compiled C-code, m-files  Additional functionality in Toolboxes (m-files)  Interactive operation

9 Start matlab and see(demo) 1.4 Matlab Desktop (V2011b)

10 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.

11 Chap2. syntax and command 2.1 Basic concept 2.2 Matrices & Arrays 2.3 Commonly used commands 2.4 Flow control 2.5 Graphics

12 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

13 2.1 Basic concept 2. Constant pi3.14159265... iImaginary unit jSame as i epsFloating-point relative precision RealminSmallest floating-point number RealmaxLargest floating-point number InfInfinity NaNNot-a-number

14 2.1 Basic concept 3.Variable Just for storage the data. 4.Functions Usually: the name of function is composed by small letters.

15 2.1 Basic concept 5. Order of identifier Searches a. variable in current workspace b. built-in variable c. built-in m-file d. m-file in current directory e. m-file on search path

16 2.1 Basic concept 6. Operators + - * / …… Relational operators ==(equal to)~= (not equal) (greater than)>= (greater than or equal to) Logical operators &(and) |(or) ~(not)

17 2.1 Basic concept 7. Expression Variables, constants and functions connected by the operator. a+b c*f(a)

18 2.1 Basic concept 8. Statement Value of the expression assigned to a variable called assign command statement; = a = zeros(2,2);

19 2.1 Basic concept 9. Comment & others % ; …

20 2.2 Matrices & Arrays 1.Matrices generate Colon(:) & Brackets([]) ones, zeros, sparse magic, randn linspace,logspace true,false

21 2.2 Matrices & Arrays 1.Matrices generate Colon(:) Brackets([]) a = [1,2,3;4,5,6;7,8,9] b = 1:2:10

22 2.2 Matrices & Arrays 2.Operators +Addition -Subtraction *Matrices Multiplication /Matrices Division \Matrices Left division ^Matrices Power 'Complex conjugate transpose ( )Specify evaluation order

23 2.2 Matrices & Arrays.* Element-by-element multiplication./ Element-by-element division.\ Element-by-element left division.^ Element-by-element power.' Unconjugated array transpose

24 2.2 Matrices & Arrays size,length isempty,any,all diag, triu, tril inv,det,svd, …… 3. Other operate

25 2.2 Matrices & Arrays 4.Example A=magic(3) X=[1 3 5]' b=A*X

26 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

27 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

28 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

29 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

30 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

31 2.4 Flow control 2.loop Control— for,while,continue, break 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 fibnacci

32 2.4 Flow control 3.error Control— try,throw catch try statement... statement catch exceptObj statement... statement end

33 2.4 Flow control 3.error Control— try,throw,catch try statement … statement catch err statement... statement end

34 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

35 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.

36 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

37 2.5 Graphics 2. Figure tool grid on, grid off title, xlabel, ylabel, zlabel, text axis ij, axis equal close

38 2.5 Graphics 3. 3D Graphics  plot3,pie3  mesh,meshc,meshz  surf,waterfall,surfc  contour,quiver,fill3  tem3,slice,scatter3 2D graphs:  3D graphs:

39 2.5 Graphics 3. 3D Graphics Dis3D_topo_demo 2D graphs:  3D graphs:

40 2.5 Graphics 4. Others plot Plot catalog select a variable from the workspace and see the graphics menu …

41 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

42 42 3.1 Scripts m-file 1. Just only composed by a bunch of instruction set (including the control flow of instructions including )

43 3.1 Scripts m-file 2. Variable storaged in the base workspace shared with the command window.

44 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');

45 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;

46 46 3.2 function m-file 2. Variable storaged in the function workspace separated with the command window.

47 47 3.2 function m-file 3. Primary and Subfunctions funciton a = prifun(x) ….. r=3; a = 2 + subfun(r); function b = subfun(r) …

48 48 3.2 function m-file 4. style Declare function line %Comment line %Help online zone (lookfor 、 help) %Edit record and copyright infomation Function body

49 49 3.3 Function calls and parameter passing 1. Local and global variable K = 1; ki = 105; f = anim(K,ki); image(f.cdata);

50 50 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;

51 51 3.3 Function calls and parameter passing 3. Parameter passing with adjustable parameters K = 1; ki = 105; f = anim(K,ki); image(f.cdata);

52 52 3.3 Function calls and parameter passing 3. Parameter passing with adjustable parameters argin argout

53 53 3.3 Function calls and parameter passing 4. Pass across the space variable x= evalin(‘base’, ‘K’)

54 54 3.4 Debug m-file 1. Two type errors Syntax variable name error … Run-time Algorithm error

55 55 3.4 Debug m-file 2. Using debug tools

56 Debug tool

57  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 。

58 Chap4. Advanced programming 4.1 File Operate 4.2 Graphice User Interface(GUI) 4.3 Application Programming Interface(API) 4.4 complier

59 59 4.1 File Operate 1.fopen,fclose 2.fread,fwirte 3.xlsread,xlswrite 4.getline 5.Fprintf

60 浙江大学地球科学系 王华军 60 ( 1 ) open &close fid=fopen(‘datafile’ , ‘r’) ‘r’ —— read ‘w’ —— write ‘a’ —— add ‘rt’ —— read &write

61 61 ( 1 ) open &close fclose(fid) close fid fclose(all) close all

62 浙江大学地球科学系 王华军 62 ( 1 ) open &close For spacial *.mat save load

63 63 ( 2 ) read &write fread fwrite

64 浙江大学地球科学系 王华军 64 ( 2 ) Example(Binary) %write a=1:50; fid=fopen('user.dat', 'w'); fwrite(fid,a); fclose(fid);

65 %read fid=fopen('user.dat','r'); a=fread(fid,50); fclose(fid); (2) Example(Binary)

66 (3) Examples 1.(newful) mrrDpro.m 2.(newfel) 2D visulization 3. actic em31 figure 4. 3dVisualize

67 67 4.2 Graphice User Interface(GUI)

68  MATLAB 能够以比较简单的方式实现一系列的图形界面功能。通过对控 件、菜单属性的设置和 Callback 的编写,就能够满足大多数用户的需求。  控件的 Callback 属性: Callback 属性的取值是字符串,可以是某个 M 文件名或一小段 MATLAB 语句。当用户激活控件对象(例如 :在控件对 象图标上单击鼠标左键 )时,应用程序就运行 Callback 属性定义的子程 序。 控件的 Callback 属性  菜单的 Callback 属性: Callback 属性的取值是字符串,可以是某个 M 文件名或一小段 MATLAB 语句。当用户激活菜单对象时,若没有子菜单 就运行 Callback 属性定义的子程序。若有,先运行 Callback 属性定义的 子程序,再显示子菜单。 菜单的 Callback 属性 Graphice User Interface(GUI) 68

69 69 4.3 Application Programming Interface Interface with C,fortran,excel

70 70 4.3 Application Programming Interface Example for C

71 71 4.4 complier 1.mcc mcc[-options] fun [fun2...] [mexfile1...] mlibfile1...] 2.Tools

72 72 4.4 complier 2.Tools Deployment project Code Generation Project

73 73 4.4 complier 2.Tools Deployment project Code Generation Project

74 一旦你学会了基本语法,设计程序的能力 取决于你的知识和掌握函数的多少及熟练 程度. 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. Practice and practice

75 Thanks!


Download ppt "Matlab Programming Huajun Wang Department of Earth Sciences, Zhejiang University Jan 25,2012."

Similar presentations


Ads by Google