A MATLAB tutorial.ppt

上传人:livefirmly316 文档编号:377840 上传时间:2018-10-09 格式:PPT 页数:74 大小:166KB
下载 相关 举报
A MATLAB tutorial.ppt_第1页
第1页 / 共74页
A MATLAB tutorial.ppt_第2页
第2页 / 共74页
A MATLAB tutorial.ppt_第3页
第3页 / 共74页
A MATLAB tutorial.ppt_第4页
第4页 / 共74页
A MATLAB tutorial.ppt_第5页
第5页 / 共74页
亲,该文档总共74页,到这儿已超出免费预览范围,如果喜欢就下载吧!
资源描述

1、A MATLAB tutorial,Bjrn K. Alsberg Department of Computer Science University of Wales Aberystwyth,Introduction,What is MATLAB? General info. Manipulation of vectors and matrices String manipulation Plotting Programming (script and function files) Simple file input/output Some important mathematical f

2、unctions Management of MATLAB projects,What is MATLAB?,MATLAB (MATrix LABoratory) is a language for manipulation of vector and matrix expressions. MATLAB interprets code and is not compiled (valid for earlier versions than 5.0 only) MATLAB provides a powerful on-line graphical interface to explore t

3、he results from calculations.,Starting MATLAB,Find the MATLAB icon and double click You will see something like:,Commands to get started: intro, demo, help help Commands for more information: help, whatsnew, info, subscribe,MATLAB is an interpreter,This means you are performing a dialogue with MATLA

4、B: (2+5)*10/2 what you type in ans =35 what MATLAB answers you ,MATLAB as a calculator,All usual numerical operators available: elementary operators: + - / * e.g899 - 7.88 * 0.123 math functions: abs, cos, acos, sin, asin, tan, atan, exp, asinh, cosh, log, log10, sqrt, tanh, conj e.g. abs(-34.5) , c

5、os(0.7887) (assumes radians), exp(2.989),Variables,In MATLAB you dont declare variables. In general: variable_name = value Variables cant start with a number or names assigned to the MATLAB language. a = 12; c = a - 5 c =7,“Who” and “whos” (1),who/whos are used to display variables and information a

6、bout variables currently in working memory. example: qr = 99.9; f = -190; X = 12;12;89;90; who Your variables are:X f qr,“Who” and “whos” (2),whos Name Size Elements Bytes Density ComplexX 4 by 1 4 32 Full No f 1 by 1 1 8 Full No qr 1 by 1 1 8 Full No Grand total is 6 elements using 48 bytes,“clear”

7、 and “clc”,clear removes all variables from current memory clc clears the screen and sets the cursor to the upper left corner of the working window.,Function calls,Most of MATLABs commands are like functions:OUT = function_name(INPUT);The ; means that the contents in OUT are not written to screen.,V

8、ectors - transposing,a1 = 1 2 3 produce a ROW vector a2 = 1;2;3 produce a COLUMN vector is used to TRANSPOSE: b1 = a1 b1 is now:123,Vectors -merging,We can merge vectors. Let a = 2 7 5 8 and b = 1 1 2. Then c = a b will bec = 2 7 6 8 1 1 2The transposed: d = a ; b ( here d = c).d = a; b or a;b is no

9、t allowed,Vectors -indexing (0),Individual elements in a vector are extracted as follows, e.g.:a(1) - the first element in a a(5) - the fifth element in aWithin the parentheses we have a number (or numbers) that indicate(s) the element(s) we want to extract.NOTE! All vector/matrix indicies start wit

10、h 1 (not 0)!,Vectors -indexing (1),The “:”-notation:from:step:to6.7:-1.56:-0.11ans =6.7000 5.1400 3.5800 2.0200 0.4600,Vectors -indexing (2),a = 5 6 10 11 4. We want to construct a new vector from the 3 first elements in a:b = a(1:3)If we want the three last elements we need to know the size of a fi

11、rst:n = length(a) b = a(n-2:n),Matrix - intro,A matrix contains ROWS and COLUMNS:2 5 2 7 7X = 1 3 8 9 34 1 5 2 4 The dimensions or size of X is 3 ROWS and 5 COLUMNS, i.e. n,m=size(X) n = 3 m = 5,Matrix multiplication (1),Multiplication between vectors and matrices:A = 1 2 1; 2 9 0; 4 0 3; v = 0 1 3;

12、 y = A*vy =599,A =1 2 12 9 04 0 3,Matrix multiplication (2),We could also have written:y = v*Ay =14 9 9,It is very useful to remember that in general a matrix product has dimensions:p x q = p x n*n x q,Matrix multiplication (3),Let us multiply two matrices A and B:A = 0.5 3.4 0.1 2.2; 4.1 1.2 0.1 0.

13、1;A =0.5000 3.4000 0.1000 2.20004.1000 1.2000 0.1000 0.1000size(A) ans =2 4,Matrix multiplication (4),B is a matrix of random numbers:B = rand(4,2) B =0.2190 0.93470.0470 0.38350.6789 0.51940.6793 0.8310,Matrix multiplication (5),Now performing the matrix multiplication:C = A*B C =1.8318 3.65131.090

14、0 4.4275,Matrix - indexing (0),A matrix element is extracted by indicating ROW and COLUMN number(s), e.g.:C(1,2) - first row, second column C(4,4) - fourth row, fourth column,Matrix - indexing (1),The indexing for vector can be extended to matrices:k = C(:,2) k =3.65134.4275is the second column in C

15、. The : symbol means all elements in that index. The second row in C is:r = C(2,:) r =1.0900 4.4275,Matrix - indexing (2),The indexing in MATLAB is very powerful. The general syntax is:Y = X(vec1,vec2)where vec1 and vec2 are vectors containing the the indices we want to extract from the matrix X. Ex

16、ample:Y = X(12 8 1,10 1 2 80 40) size(Y)4 5,Matrix - indexing (3),If you happen to use decimal numbers in the index vectors, MATLAB automatically performs a rounding:X(1 9,:) = X(1.2 8.99,:)(may not be true for future versions of MATLAB),Matrix - addition,Adding and subtracting matrices and vectors

17、is easy:C = A + Bor C = A - Bas long as A and B have the same size. Another example:C = 12.4*A - 4*B + 100*D,Matrix - folding/unfolding (1),Unfolding and folding:X = 1 6 109 10 451 1 185 7 0;X unfolded into a vector:xv = (X(:)1 9 1 85 6 10 1 7 10 45 1 0The unfolding process operates COLUMNWISE,Matri

18、x - folding/unfolding (2),FOLDING A VECTOR BACK TO A MATRIX:Xh = reshape(xv,4,3)1 6 109 10 451 1 185 7 0,Special matrices (1),X = ones(2,3) X =1 1 11 1 1 Y = zeros(2,3) Y = 0 0 00 0 0,H = eye(4) H =1 0 0 00 1 0 00 0 1 00 0 0 1,Special matrices (2),Q = hankel(1 2 3 4) Q =1 2 3 42 3 4 03 4 0 04 0 0 0,

19、Q = toeplitz(1 2 3 4) Q = 1 2 3 42 1 2 33 2 1 24 3 2 1,Matrix operators (1),A =3 5 101 0 7 B = fliplr(A) B =10 5 37 0 1,D = diag(1 2 3) D = 1 0 00 2 00 0 3 v = diag(D) v = 1 2 3 v = diag(D,1) v = 0 0 ,Matrix operators (2),A =3 5 101 0 7 B = flipud(A) B =7 0 110 5 3,B = rot90(A) B =10 75 03 1,rot90 i

20、s NOT the same as transposed: B = A B =3 15 010 7,Matrix operators (3),B =A.2 B =9 25 1001 0 49 or C = A.*B C =27 125 10001 0 343,The dot notation means every element is subjected to a certain operator. Is valid for matrices and vectors: matrix .operator (matrix),Strings - intro,A string is containe

21、d within characters:q = This is a string vector! ; Each element in q contains a character: q(1:4) ans = This,Strings - concatenation,a = First part ; b = Second part; c = a b c = First part Second part;d = The ,a,of this string and the ,b; d = The First part of this string and the Second part,String

22、s - conversion (1),Converting from integers to strings:i = 25;str = She is ,int2str(i),years oldConverting from real numbers to strings:k = 12.778str =The road is ,num2str(k), miles long,Strings - conversion (2),Converting from strings to MATLAB commands:str = Q = A*B; eval(str)Very useful for e.g.

23、multiple matrices:i = 12 str = Q,int2str(i),= A,int2str(i-1),*B; eval(str)Q12 = A11*B;,Strings - conversion (3),How do I create a in a string when the string is defined by ?Define the string: fn = str = We can now create ,fn, in a string! We can now create in a string!,Plots - 2D basic,For simple 2-

24、D plot we use:plot(x) or plot(x,y)example: y = 5 3 6 5 4 3;plot(x) which here is the same as plot(1:6,y);,Plots - 2D symbols,Scatter 2D plot with various symbols:plot(x,y,xw)x = symbol w = white Possible symbols in MATLAB 4.2: . point o circle x x-mark + plus - solid * star : dotted -. dashdot - das

25、hed,Plots - 2D colours,There are several possible colours that can be used in the plot command: y yellow m magenta c cyan r red g green b blue w white k black,Plots - multiple plots,You can plot all the COLUMNS in a matrix X by:X =0.2190 0.04700.3835 0.51940.5297 0.67110.4175 0.68680.5269 0.09200.91

26、03 0.76220.3282 0.6326;plot(X),Plot - 3D lines,3D plots:plot3(x,y,z)The command “grid” is also used,Plot - 3D surface,Mesh and contour plots:mesh(X)view(angle,elevation)is used to adjust the viewpoint, or combined:mesh(X,angle,elevation),Plot - 3D contour,Mesh and contour plots:contour(X,no_lev)no_l

27、ev specifies the number of contour levels,Script and function files (1),Let us say we wrote the following in MATLAB: load data plot(X(1,:) A,D,B= svd(X); and wanted to use these commands often. We can write the same commands in a any ASCII editor but without the prompt character. Call this ASCII fil

28、e e.g. prog1.m (the extension .m must be included). Typing prog1 will execute the program,Script and function files (2),Let us include some comment in out program. A comment line starts with a percentage character: % This file describes my experiment load data plot(X(1,:) A,D,B= svd(X); - Typing hel

29、p prog1 will produce the n first comment lines in the program: % This file describes my experiment,Script and function files (3),Functions are declared as follows: function A,Q = myfunc(vec1, s,t) % A,Q = myfunc(vec1, s,t) % This function has inputs vec1, s and t % The output of this function is A a

30、nd QThe help command in MATLAB will produce the n first comment lines after the function declaration for functions also.,Script and function files (4),Remember: For MATLAB to recognize your program, you have to be either- In the current directory where the function or script is located - or you must

31、 have the home directory of the function/script in your MATLABPATH. The MATLABPATH is set by changing a file called MATLABRC.M in your /MATLAB directory.,Programming - conditional statements (1),IF I = JA(I,J) = 2; ELSEIF ABS(I-J) = 1 A(I,J) = -1; ELSEA(I,J) = 0; END,NOTE that comparison is =, not =

32、. Other comparison operators are = greater than or equal = less than or equal = if different from NOTE that IF has no BEGIN statement only END,Programming - logical operators (1),AND, OR and NOT operators : & = AND | = OR = NOT,IF (A 0),disp( A is between 0 and 1); ELSEdisp( A is outside 0,1 ); END;

33、,Programming - logical operators (2),The powerful FIND command: x = 10 7 1 2 0 990; idx = find(x 0) idx = 3 4 idx = find(x = 1 | x =7) idx = 2 3,x = 10 7 1 2 0 990; y = x1 y = 0 1 0 1 0 0 x(y)7 2,Programming - FOR loops,The general syntax for FOR loops FOR variable = expr, statement, ., statement EN

34、D Double loop example: FOR i = 1:N,FOR j = 1:M,Q(i,j) = 1/(i+j-1);END END,Programming - WHILE loops,The general form of a WHILE statement is:WHILE variable, statement, ., statement, END Example: WHILE norm(E) 0,E = E.*F;F = A + F/n;n = n + 1;END,Debugging,There is a debugger in MATLAB, but the two f

35、unctions KEYBOARD PAUSE are just as useful. KEYBOARD stops the program at the location of the word “keyboard”. All local variables are accessible. Type RETURN to get back and run the program. PAUSE creates a halt in the program; pressing a key will start the program again. PAUSE(n) pauses the progra

36、m for n seconds before continuing.,Save (1),The command SAVE saves the current working memory to a file. save wille save everything in memory to a file names matlab.mat All mat files have a special binary format. save mywork will create a file names mywork.mat,Save (2),It is possible to save just se

37、lected variables in memory save filename variable1 variable2 Example: save mywork X y u1 u2 wxy will create a file names mywork.mat with the variables X,y, u1.u2 and wxy only.,Save (3),SAVE can also be used to store in ASCII format: SAVE fname X Y Z -ascii uses 8-digit ASCII form instead of binary.

38、SAVE fname X Y Z -ascii -double uses 16-digit ASCII form. SAVE fname X Y Z -ascii -double -tabs delimits with tabs.,load (1),The command LOAD inserts into memory both MAT-files and ASCII files (with restrictions to format) load will load in everything to memory stored in matlab.mat load mywork will

39、load file mywork.mat. The inclusion of the .mat extension is optional.,load (2),Load can also read ASCII files if they just contain numbers load tst.dat will create a variable names “tst” containing the information stored in tst. If data is in matrix form (rows followed by return), the load command

40、will reconstruct the correct matrix.For more advanced input/output see: fopen, fprintf, fread etc./ which are C-like commands.,Some useful linear algebra commands,Eigenvalue decomposition: U,D = eig(X) Singular value decomposition: U,S,V = svd(X) Inverse of full rank matrices: Y = inv(X) Orthogonali

41、zation of a basis set: Q = orth(A) The determinant of a basis set: a = det(X) Pseudoinverse: X = pinv(A) Sum of diagonal elements: a = trace(X) Factors from Gaussian elimination: L,U = lu(X) Generalized eigenvalues: AA,BB,Q,Z,V = qz(A,B) Characteristic polynomial: v = poly(A),Some useful signal proc

42、essing commands,Fourier transform: f = fft(x) Inverse Fourier transform: x = ifft(f) 2D Fourier transform: F = fft2(X) Inverse 2D Fourier transform: X = ifft2(F) Convolution: c = CONV(a,b) 2D convolution: C = CONV(A,B) Deconvolution: q,r = deconv(b,a),Various numerical methods,Minimize function one

43、variable: a=fmin(func,x1,x2) Minimize function of several variables:a=fmins(func,x0) Find zero of function in one variable: a=fzero(func,x) Solving ordinary differential equations: t,y = ode45(yprime, t0, tfinal,y0) Numerically evaluate integral: q = quad8(func,a,b) Fitting polynomials to data: p =

44、polyfit(x,y,n) Evaluate polynomial: y = polyval(p,x) Convert matrix to sparse: A = sparse(A),Management of MATLAB projects,Commenting your code Directories Systematic script files HTML toolbox,MATLAB management - minimum comments,Minimum comment lines describe the INPUT/OUT parameters:function A,B,C

45、 = boink(Q,a,name) % A,B,C = boink(Q,a,name)The n first lines containing the % character will be visible when we type help boink,MATLAB management - improved comments,function A,B,C = boink(Q,a,name) % A,B,C = boink(Q,a,name) % INPUT PARAMETERS % Q = matrix with values % a = vector with values % nam

46、e = a string containing a file name %OUTPUT PARAMETERS % A = this is the first matrix % B = this is the second matrix % C = this is the third matrix,MATLAB management - directories,If you make general programs - put them in your own toolbox directories Keep project specific m-files in directories re

47、lated to the project,Management of MATLAB - suggested directory structure,MATLAB management - systematic script files,Use scripts for experiments (they are usually unique - not general) Use a systematic name - youll run out of sensible names Keep track of systematic script files (“doit”-files) by a

48、“how”-file.,MATLAB management - A “how” file example,HOW FILE FOR WAVELET REGRESSIONDOIT FILES - 1 Wavelet regression of Data set 1 2 Plotting from doit1 (Data set 1) 3 Program for constructing closed concentration system 4 Here we make concentration matrix 5 Optimization of the contribution from wa

49、velet scales in wavelet regression 6 Separate prediction using doit5 results 7 Systematic denoising + regression (Data set 1) 8 Plots from doit7 (Data set 1) 9 Dataset2: systematic PLS regression 10 Plots from doit9 (Data set 2) 11 Testing the scale contribution to the y-prediction 12 DS2: Multiresolution loading/score plots for selected threshold,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 教学课件 > 大学教育

copyright@ 2008-2019 麦多课文库(www.mydoc123.com)网站版权所有
备案/许可证编号:苏ICP备17064731号-1