Contents MATLAB Tutorial Based on IPLab@SUT Matlab Tutorial What Matlab? Matrices Numerical Arrays String Arrays Elementary Math Logical Operators Math Functions Importing and Exporting Data 2 Contents Graphics Fundamentals 2D plotting Subplots 3D plotting Editing and Debugging M-files Script and Function Files Basic Parts of an M-file Flow Control Statements M-file Programming Data Types Continued What MATLAB? high-performance software Computation Vualization Easy-to-use environment. high-level language Data types Functions Control flow statements Input/output Graphics Object-oriented programming capabilities 3 5 Calculations at the Command Line General Functions 9 MATLAB as a calculator Assigning Variables» -5/(4.8+5.32)^2 ans» a 2; ans 2; -.488» b 5; -.488 5;» (3+4i)*(3-4i)» a^b a^b ans ans ans ans 25 25 32 32» cos(pi/2)» x 5/2*pi; 5/2*pi; ans ans» y sin(x) 6.23e-7 sin(x) y» exp(acos(.3)) ans ans 3.547» z asin(y) 3.547 asin(y) z.578.578 A Note about Workspace: Numbers stored in double-precion floating point format Semicolon suppresses screen output Results assigned to ans if name not specified () parentheses for function inputs whos: Lt current variables clear: Clear variables and functions from memory cd: Change current working directory ls: Lt files in directory
Getting help help command lookfor command Printable Documents Matlabroot\help\pdf_doc\ (>>help) (>>lookfor) Matrices Entering and Generating Matrices Subscripts Scalar Expansion Concatenation Deleting Rows and Columns Array Extraction Matrix and Array Multiplication 2 Entering Numeric Arrays The Matrix in MATLAB 3 Row separator semicolon (;) Column separator space / comma (,)» a[ a[ 2;3 2;3 4] 4] a Use square 2 brackets [ ] 3 4» b[-2.8, b[-2.8, sqrt(-7), sqrt(-7), (3+5+6)*3/4] (3+5+6)*3/4] b -2.8-2.8 + 2.6458i 2.6458i.5.5» b(2,5) b(2,5) 23 23 b -2.8-2.8 + 2.6458i 2.6458i.5.5 23. 23. Any MATLAB expression can be entered as a matrix element Matrices must be rectangular. (Set undefined elements to zero) 4 A 2 Rows (m) 3 4 5 Columns (n) 2 3 4 5 4 6 2 6 6 2 8.2 9 4 25 2 7 2 7 22 7.2 5 7 3 8 3 8 23.5 4 5 56 4 9 4 9 24 23 83 3 5 5 2 25 A (2,4) A (7) Rectangular Matrix: Scalar: -by- array Vector: m-by- array -by-n array Matrix: m-by-n array Entering Numeric Arrays Numerical Array Concatenation 5 Scalar expansion Creating sequences: colon operator (:) Utility functions for creating matrices.» w[ w[ 2;3 2;3 4] 4] + 5 w 6 7 8 9» x :5 :5 x 2 3 4 5» y 2:-.5: 2:-.5: y 2. 2..5.5...5.5» z rand(2,4) rand(2,4) z.95.95.668.668.893.893.4565.4565.23.23.486.486.762.762.85.85 6 Use [ ] to combine exting arrays as matrix elements Row separator: semicolon (;) Column separator: space / comma (,)» a[ a[ 2;3 2;3 4] 4] a Use square 2 brackets [ ] 3 4» cat_a[a, cat_a[a, 2*a; 2*a; 3*a, 3*a, 4*a; 4*a; 5*a, 5*a, 6*a] 6*a] cat_a cat_a 2 2 4 3 4 6 8 3 6 4 8 9 2 2 2 2 6 6 4*a 5 6 2 2 5 5 2 2 8 8 24 24 Note: The resulting matrix must be rectangular
Deleting Rows and Columns Array Subscripting / Indexing» A[ A[ 5 9;4 9;4 3 2.5; 2.5;.. 3i+] 3i+] A.. 5. 5. 9. 9. 4. 4. 3. 3. 2.5 2.5.....+3.i.+3.i» A(:,2)[] A(:,2)[] A.. 9. 9. 4. 4. 2.5 2.5.... + 3.i 3.i» A(2,2)[] A(2,2)[]?????? Indexed Indexed empty empty matrix matrix assignment assignment not not allowed. allowed. A A(3,) A(3) 2 3 4 5 2 3 4 5 4 6 2 6 6 2 8.2 9 4 25 2 7 2 7 22 7.2 5 7 3 8 3 8 23.5 4 5 56 4 9 4 9 24 23 83 3 5 5 2 25 A(:5,5) A(:,) A(:,5) A(:,) A(2:25) A(2:) A(4:5,2:3) A([9 4; 5]) 7 8 9 Matrix Multiplication» a [ [ 2 3 4; 4; 5 6 7 8]; 8];» b ones(4,3); ones(4,3);» c a*b a*b c 26 26 26 26 26 26 Array Multiplication [2x4]*[4x3] [2x4] [4x3] [2x3] a(2nd row).b(3rd column)» a [ [ 2 3 4; 4; 5 6 7 8]; 8];» b [:4; [:4; :4]; :4];» c a.*b a.*b c 4 9 6 6 5 2 2 2 2 32 32 c(2,4) a(2,4)*b(2,4) 2 Matrix Manipulation Functions zeros: Create an array of all zeros ones: Create an array of all ones eye: Identity Matrix rand: Uniformly dtributed random numbers diag: Diagonal matrices and diagonal of a matrix size: Return array dimensions repmat: Replicate and tile a matrix Matrix Manipulation Functions Elementary Math det: Matrix determinant inv: Matrix inverse eig: Evaluate eigenvalues and eigenvectors rank: Rank of matrix Logical Operators Math Functions Polynomial and Interpolation 2 25
Logical Operations Elementary Math Function 26 equal to > greater than < less than > Greater or equal < less or equal ~ not & and or finite(), etc.... all(), any() find» Mass Mass [-2 [-2 NaN NaN 3 3 - - Inf Inf 3]; 3];» each_pos each_pos Mass> Mass> each_pos each_pos» all(mass>) all(mass>)» any(mass>) any(mass>)» pos_fin pos_fin (Mass>)&(finite(Mass)) (Mass>)&(finite(Mass)) pos_fin pos_fin Note: TRUE FALSE 27 abs, sign: Absolute value and Signum Function sin, cos, asin, acos : Triangular functions exp, log, log: Exponential, Natural and Common (base ) logarithm ceil, floor: Round toward infinities fix: Round toward zero Elementary Math Function round: Round to the nearest integer sqrt: Square root function real, imag: Real and Image part of complex rem: Remainder after divion Elementary Math Function max, min: Maximum and Minimum of arrays mean, median: Average and Median of arrays std, var: Standard deviation and variance sort: Sort elements in ascing order sum, prod: Summation & Product of Elements 28 Importing and Exporting Data Using the Import Wizard Using Save and Load command Input/Output for Text File Read formatted data, reusing the format string N times.»[a An]textread(filename,format,N) save save fname fname save save fname fname x y z save save fname fname -ascii save save fname fname -mat -mat load load fname fname load load fname fname x y z load load fname fname -ascii load load fname fname -mat -mat Import and Exporting Numeric Data with General ASCII delimited files» M dlmread(filename,delimiter,range) 32 33
Graphics Fundamentals Graphics Basic Plotting plot, title, xlabel, grid, leg, hold, ax Editing Plots Property Editor Mesh and Surface Plots meshgrid, mesh, surf, colorbar, patch, hidden Handle Graphics 35 36 2-D Plotting Sample Plot Syntax: Title plot(x, y, y, 'clm', x2, x2, y2, y2, 'clm2',...)...) Example: 37 x[:.:2*pi]; ysin(x); zcos(x); plot(x,y,x,z,'linewidth',2) title('sample Plot','fontsize',4); xlabel('x values','fontsize',4); ylabel('y values','fontsize',4); leg('y data','z data') grid grid on on 38 Ylabel Leg Xlabel Grid Subplots Syntax: subplot(rows,cols,index)»subplot(2,2,);»»subplot(2,2,2)»...... Surface Plot Example x :.:2; :.:2; y :.:2; :.:2; [xx, [xx, yy] yy] meshgrid(x,y); meshgrid(x,y); zzsin(xx.^2+yy.^2); surf(xx,yy,zz) surf(xx,yy,zz) xlabel('x xlabel('x axes') axes') ylabel('y ylabel('y axes') axes')»subplot(2,2,3)»......»subplot(2,2,4)»...... 39 4
3-D Surface Plotting contourf-colorbar-plot3-waterfall-contour3-mesh-surf Specialized Plotting Routines bar-bar3h-ht-area-pie3-rose 4 42 Editing and Debugging M-Files Debugging 43 What an M-File? The Editor/Debugger Search Path Debugging M-Files Types of Errors (Syntax Error and Runtime Error) Using keyboard and ; statement Setting Breakpoints Stepping Through Continue, Go Until Cursor, Step, Step In, Step Out Examining Values Selecting the Workspace Viewing Datatips in the Editor/Debugger Evaluating a Selection 44 Select Workspace Set Auto- Breakpoints tips Script and Function Files Programming and Dubugging Script Files Work as though you typed commands into MATLAB prompt Variable are stored in MATLAB workspace 45 46 Function Files Let you make your own MATLAB Functions All variables within a function are local All information must be passed to functions as parameters Subfunctions are supported
Basic Parts of a Function M-File Flow Control Statements 47 Output Arguments Function Name Input Arguments Online Help function y mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) a row vector % containing the mean value of each column. [m,n] size(x); if m Function Code m n; y sum(x)/m; 48 if Statement if if ((attance ((attance > >.9).9) & (grade_average (grade_average > > 6)) 6)) pass pass ; ; ; ; while Loops eps eps ; ; while while (+eps) (+eps) > eps eps eps/2; eps/2; eps eps eps*2 eps*2 49 Flow Control Statements for Loop a a zeros(k,k) zeros(k,k) % % Preallocate Preallocate matrix matrix for for m m :k :k for for n n :k :k a(m,n) a(m,n) /(m+n /(m+n -); -); switch Statement method method 'Bilinear'; 'Bilinear'; switch switch lower(method) lower(method) case case {'linear','bilinear'} {'linear','bilinear'} dp('method dp('method linear') linear') case case 'cubic' 'cubic' dp('method dp('method cubic') cubic') otherwe otherwe dp('unknown dp('unknown method.') method.') Method Method linear linear 5 M-file Programming Features SubFunctions Varying number of input/output arguments Local and Global Variables Obtaining User Input Prompting for Keyboard Input Pausing During Execution Errors and Warnings Dplaying error and warning Messages Shell Escape Functions (! Operator) Optimizing MATLAB Code Vectorizing loops Preallocating Arrays Function M-file Data Types function function r ourrank(x,tol) ourrank(x,tol) % rank rank of of a matrix matrix s svd(x); svd(x); if if (nargin (nargin ) ) tol tol max(size(x)) max(size(x)) * s()* s()* eps; eps; r sum(s sum(s > tol); tol); Multiple Input Arguments use ( )»rourrank(rand(5),.); 5 function function [mean,stdev] [mean,stdev] ourstat(x) ourstat(x) [m,n] [m,n] size(x); Multiple Output size(x); if if m Arguments, use [ ] m n; n;»[m std]ourstat(:9); mean mean sum(x)/m; sum(x)/m; stdev stdev sqrt(sum(x.^2)/m sqrt(sum(x.^2)/m mean.^2); mean.^2); 52 Numeric Arrays Multidimensional Arrays Structures and Cell Arrays
Multidimensional Arrays Structures 53 The first references array dimension, the row. The second references dimension 2, the column. The third references dimension 3, The page. 2 3 3 6 8 5 7 6 2 9 2 3 4 4 4 5 3 6 4 2 Page Page N» A pascal(4);» A(:,:,2) A(:,:,2) magic(4) magic(4) A(:,:,) A(:,:,) 2 3 4 3 6 4 2 2 A(:,:,2) A(:,:,2) 6 6 2 3 3 3 5 8 9 7 6 2 2 4 4 4 5 5» A(:,:,9) A(:,:,9) diag(ones(,4)); 54 Arrays with named data containers called fields.» patient.name'john Doe'; Doe';» patient.billing 27.;» patient.test [79 [79 75 75 73; 73; 8 8 78 78 77.5; 22 22 2 2 25]; 25]; Also, Build structure arrays using the struct function. Array of structures» patient(2).name'katty Thomson';» Patient(2).billing.;» Patient(2).test [69 [69 25 25 33; 33; 2 2 28 28 77.5; 22 22 2 2 25]; 25]; Cell Arrays Array for which the elements are cells and can hold other MATLAB arrays of different types.» A(,) {[ {[ 4 3; 3; 5 8; 8; 7 2 9]}; 9]};» A(,2) {'Anne Smith'};» A(2,) {3+7i};» A(2,2) {-pi:pi/:pi}; Next Tutorial Session Image Processing Toolbox Movie Making Problem Set 55 Using braces {} to point to elements of cell array Using celldp function to dplay cell array Getting more help Contact http://www.mathworks.com/support You can find more help and FAQ about mathworks products on th page. Getting started with Matlab http://www.indiana.edu/~statmath/math/matlab/gettings tarted/index.html Matlab Primer http://math.ucsd.edu/~driver/2d-s99/matlabprimer.html Questions?? 69 7