1 / 90

Short M ATLAB Tutorial

Short M ATLAB Tutorial. Covered by: Dan Negrut University of Wisconsin, Madison. Before getting started …. Acknowledgement: Almost entirely, this tutorial compiled from bits of information gathered from various internet sources

vian
Télécharger la présentation

Short M ATLAB Tutorial

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ShortMATLAB Tutorial Covered by: Dan Negrut University of Wisconsin, Madison

  2. Before getting started… • Acknowledgement: • Almost entirely, this tutorial compiled from bits of information gathered from various internet sources • It is available for download from SBEL website in PPT format for other to be able to save, edit, and distribute as they see fit • Please let me know of any mistakes you find • email me at my lastname@wisc.edu • The right frame of mind: • You will not be able to say at the end of workshop that you know MATLAB but rather that you have been exposed to MATLAB (I don’t know MATLAB myself, I’m just using it…) • Use MATLAB’s “help”, this is your first stop • Second stop: search the web for examples that come close to what you need • You learn how to use MATLAB by using it, that’s why the start might be slow and at times frustrating

  3. Contents – 1 • First hour of workshop • What is Matlab? • MATLAB Components • MATLAB Desktop • Matrices • Importing and Exporting Data • Elementary math with MATLAB

  4. Contents – 2 • 2. Second hour of workshop • M-file Programming • Functions vs. Scripts • Variable Type/Scope • Debugging MATLAB functions • Flow control in MATLAB • Other Tidbits • Function minimization • Root finding • Solving ODE’s • Graphics Fundamentals • Data Types most likely won’t have time for it

  5. What is MATLAB? • Integrated Development Environment (IDE) • Programming Language • Collection of Toolboxes • Excellent Linear Algebra support

  6. MATLAB as an IDE • Integrated development environment (IDE) • Write your own code for computation • Good visualization (plotting) tools • Easy-to-use environment • Command Window • Command History • Help Browser • Workspace Browser • Editor/Debugger

  7. MATLAB Desktop Tools

  8. MATLAB as Programming Language • High-level language • Data types • Functions • Control flow statements • Input/output • Graphics • Object-oriented programming capabilities

  9. Toolboxes • Collections of functions to solve problems from several application fields. • DSP (Digital Signal Processing) Toolbox • Image Toolbox • Wavelet Toolbox • Neural Network Toolbox • Fuzzy Logic Toolbox • Control Toolbox • Multibody Simulation Toolbox • And many many other… (Visit for instance http://www.tech.plym.ac.uk/spmc/links/matlab/matlab_toolbox.html, amazing number of toolboxes available: if you need something, it’s out there somewhere available for download)

  10. MATLAB for [Linear] Algebra

  11. Calculations at the Command Line Assigning Variables MATLAB as a calculator • -5/(4.8+5.32)^2 ans = -0.0488 • (3+4i)*(3-4i) ans = 25 • cos(pi/2) ans = 6.1230e-017 • exp(acos(0.3)) ans = 3.5470 • a = 2; • b = 5; • a^b • ans = • 32 • x = 5/2*pi; • y = sin(x) • y = • 1 • z = asin(y) • z = • 1.5708 Semicolon suppresses screen output Results assigned to “ans” if name not specified () parentheses for function inputs A Note about Workspace: Numbers stored in double-precision floating point format

  12. General Functions • whos: List current variables and their size • clear: Clear variables and functions from memory • cd: Change current working directory • dir:List files in directory • pwd:Tells you the current directory you work in • echo:Echo commands in M-files • format: Set output format (long, short, etc.) • diary(foo): Saves all the commands you type in in a file in the current directory called “foo”

  13. Getting help • help command (>>help) • lookfor command (>>lookfor) • Help Browser (>>doc) • helpwin command (>>helpwin) • Search Engine • Printable Documents • “Matlabroot\help\pdf_doc\” • Link to The MathWorks

  14. Handling Matrices in Matlab

  15. Matrices • Entering and Generating Matrices • Subscripts • Scalar Expansion • Concatenation • Deleting Rows and Columns • Array Extraction • Matrix and Array Multiplication • NOTE: we don’t have time to carefully look at all these topics. I want you to be aware that these facilities exist in MATLAB, and that you can access them when needed by first doing a “help” on that command

  16. Entering Numeric Arrays • a=[1 2;3 4] • a = • 1 2 • 3 4 • b=[-2.8, sqrt(-7), (3+5+6)*3/4] • b = • -2.8000 0 + 2.6458i 10.5000 • b(2,5) = 23 • b = • -2.8000 0 + 2.6458i 10.5000 0 0 • 0 0 0 0 23.0000 Use square brackets [ ] NOTE: 1) Row separator semicolon (;) 2) Column separator space OR comma (,) • Any MATLAB expression can be entered as a matrix element (internally, it is regarded as such) • In MATLAB, the arrays are always rectangular

  17. Columns (n) 1 2 3 4 5 A (2,4) 1 2 Rows (m) 3 4 5 A (17) The Matrix in MATLAB A = 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 4 10 1 6 2 8 1.2 9 4 25 7.2 5 7 1 11 0 0.5 4 5 56 23 83 13 0 10 Rectangular Matrix: Scalar: 1-by-1 array Vector: m-by-1 array 1-by-n array Matrix: m-by-n array

  18. Entering Numeric Arrays Scalar expansion • w=[1 2;3 4] + 5 • w = • 6 7 • 8 9 • x = 1:5 • x = • 1 2 3 4 5 • y = 2:-0.5:0 • y = • 2.0000 1.5000 1.0000 0.5000 0 • z = rand(2,4) • z = • 0.9501 0.6068 0.8913 0.4565 • 0.2311 0.4860 0.7621 0.0185 Creating sequences: colon operator (:) Utility functions for creating matrices.

  19. Numerical Array Concatenation(Tiling) Use [ ] to combine existing arrays as matrix “elements” Row separator: semicolon (;) Column separator: space / comma (,) • a=[1 2;3 4] • a = • 1 2 • 3 4 • cat_a=[a, 2*a; 3*a, 4*a; 5*a, 6*a] • cat_a = • 1 2 2 4 • 3 4 6 8 • 3 6 4 8 • 9 12 12 16 • 5 10 6 12 • 15 20 18 24 Use square brackets [ ] 4*a Note: The resulting matrix must be rectangular

  20. Array Subscripting / Indexing 1 2 3 4 5 A = 1 6 11 16 21 2 7 12 17 22 3 8 13 18 23 4 9 14 19 24 5 10 15 20 25 4 10 1 6 2 1 2 3 4 5 8 1.2 9 4 25 A(1:5,5) A(:,5) A(21:25) A(1:end,end) A(:,end) A(21:end)’ 7.2 5 7 1 11 0 0.5 4 5 56 A(3,1) A(3) 23 83 13 0 10 A(4:5,2:3) A([9 14;10 15])

  21. Deleting Rows and Columns • A=[1 5 9;4 3 2.5; 0.1 10 3i+1] • A = • 1.0000 5.0000 9.0000 • 4.0000 3.0000 2.5000 • 0.1000 10.0000 1.0000+3.0000i • A(:,2)=[] • A = • 1.0000 9.0000 • 4.0000 2.5000 • 0.1000 1.0000 + 3.0000i • A(2,2)=[] • ??? Indexed empty matrix assignment is not allowed. “:” is a VERY important construct in MATLAB

  22. [2x4]*[4x3] [2x3] c(2,4) = a(2,4)*b(2,4) Matrix Multiplication • a = [1 2 3 4; 5 6 7 8]; • b = ones(4,3); • c = a*b • c = • 10 10 10 • 26 26 26 [2x4] [4x3] a(2nd row).b(3rd column) Array Multiplication (componentwise operation) • a = [1 2 3 4; 5 6 7 8]; • b = [1:4; 1:4]; • c = a.*b • c = • 1 4 9 16 • 5 12 21 32

  23. Matrix Manipulation Functions • zeros: Create an array of all zeros • ones: Create an array of all ones • eye: Identity Matrix • rand: Uniformly distributed random numbers • diag: Diagonal matrices and diagonal of a matrix • size: Return array dimensions • fliplr: Flip matrices left-right • flipud: Flip matrices up and down • repmat: Replicate and tile a matrix

  24. Matrix Manipulation Functions • transpose (’): Transpose matrix • rot90: rotate matrix 90 • tril: Lower triangular part of a matrix • triu: Upper triangular part of a matrix • cross: Vector cross product • dot: Vector dot product • det: Matrix determinant • inv: Matrix inverse • eig: Evaluate eigenvalues and eigenvectors • rank: Rank of matrix

  25. Exercise 1 (10 minutes) Define a matrix A of dimension 2 by 4 whose (i,j) entry is A(i,j)=i+j Extract two 2 by 2 matrices A1 and A2 out of the matrix A. A1 contains the first two columns of A, A2 contains the last two columns of A Compute the matrix B to be the sum of A1 and A2 Compute the eigenvalues and eigenvectors of B Solve the linear system Bx=b, where b has all the entries equal to 1 Compute the determinant of B Compute the inverse of B Compute the condition number of B NOTE: Use only MATLAB native functions for all operations

  26. Elementary Math

  27. Elementary Math • Logical Operators • Math Functions • Polynomial and Interpolation

  28. = = equal to > greater than < less than >= Greater or equal <= less or equal ~ not & and | or isfinite(), etc. . . . all(), any() find Logical Operations • Mass = [-2 10 NaN 30 -11 Inf 31]; • each_pos = Mass>=0 each_pos = 0 1 0 1 0 1 1 • all_pos = all(Mass>=0) all_pos = 0 • all_pos = any(Mass>=0) all_pos = 1 • pos_fin = (Mass>=0)&(isfinite(Mass)) pos_fin = 0 1 0 1 0 0 1 • Note: • 1 = TRUE • 0 = FALSE

  29. Elementary Math Function • abs, sign: Absolute value and Signum Function • sin, cos, asin, acos…: Triangular functions • exp, log, log10: Exponential, Natural and Common (base 10) logarithm • ceil, floor: Round to integer, toward +/-infinity • fix: Round to integer, toward zero

  30. Elementary Math Function • round: Round to the nearest integer • gcd: Greatest common divisor • lcm: Least common multiple • sqrt: Square root function • real, imag: Real and Image part of complex • rem: Remainder after division

  31. Elementary Math Function Operating on Arrays • max, min: Maximum and Minimum of arrays • mean, median: Average and Median of arrays • std, var: Standard deviation and variance • sort: Sort elements in ascending order • sum, prod: Summation & Product of Elements • trapz: Trapezoidal numerical integration • cumsum, cumprod: Cumulative sum, product • diff, gradient: Differences and Numerical Gradient

  32. Polynomials and Interpolation • Polynomials • Representing • Roots (>>roots) • Evaluation (>>polyval) • Derivatives (>>polyder) • Curve Fitting (>>polyfit) • Partial Fraction Expansion (>>residue) • Interpolation • One-Dimensional (interp1) • Two-Dimensional (interp2)

  33. Example polysam=[1 0 0 8]; roots(polysam) ans = -2.0000 1.0000 + 1.7321i 1.0000 - 1.7321i polyval(polysam,[0 1 2.5 4 6.5]) ans = 8.0000 9.0000 23.6250 72.0000 282.6250 polyder(polysam) ans = 3 0 0 [r p k]=residue(polysam,[1 4 3]) r = 9.5 3.5 p = -3 -1 k = 1 -4

  34. Curve fitting polyfit(X,Y,N) - finds the coefficients of a polynomial P(X) of degree N that over the points X fits the data Y best in a least-squares sense x = [0: 0.1: 2.5]; y = erf(x); p = polyfit(x,y,6) p = 0.0084 -0.0983 0.4217 -0.7435 0.1471 1.1064 0.0004 interp1(x,y,[0.45 0.95 2.2 3.0]) ans = 0.4744 0.8198 0.9981 NaN

  35. Exercise 2 (10 minutes) • Let x be an array of values from 0 to 2, equally spaced by 0.01 • Compute the array of exponentials corresponding to the values stored in x • Find the polynomial p of degree 5 that is the best least square approximation to y on the given interval [0,2] • Evaluate the polynomial p at the values of x, and compute the error z with respect to the array y • Interpolate the (x,z) data to approximate the value of the error in interpolation at the point .9995

  36. ENDMATLAB for [Linear] Algebra

  37. Programming and Application Development

  38. Topics discussed… • The concept of m-file in MATLAB • Script versus function files • The concept of workspace • Variables in MATLAB • Type of a variable • Scope of a variable • Flow control in MATLAB • The Editor/Debugger

  39. Before Getting Lost in Details… • Obtaining User Input • “input” - Prompting the user for input >> apls = input( ‘How many apples? ‘ ) • “keyboard” - Pausing During Execution (when in M-file) • Shell Escape Functions (! Operator) • Optimizing MATLAB Code • Vectorizing loops • Preallocating Arrays

  40. Function M-file function r = ourrank(X,tol) % rank of a matrix s = svd(X); if (nargin == 1) tol = max(size(X)) * s(1)* eps; end r = sum(s > tol); Multiple Input Arguments use ( ) • r=ourrank(rand(5),.1); function [mean,stdev] = ourstat(x) [m,n] = size(x); if m == 1 m = n; end mean = sum(x)/m; stdev = sqrt(sum(x.^2)/m – mean.^2); Multiple Output Arguments, use [ ] • [m std]=ourstat(1:9);

  41. Input Arguments Output Arguments Function Name Online Help function y = mean (x) % MEAN Average or mean value. % For vectors, MEAN(x) returns the mean value. % For matrices, MEAN(x) is a row vector % containing the mean value of each column. [m,n] = size(x); if m == 1 m = n; end y = sum(x)/m; Function Code Basic Parts of a Function M-File

  42. Script and Function Files • Script Files • Work as though you typed commands into MATLAB prompt • Variable are stored in MATLABworkspace • 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

  43. The concept of Workspace • At any time in a MATLAB session, the code has a workspace associated with it • The workspace is like a sandbox in which you find yourself at a certain point of executing MATLAB • The “Base Workspace”: the workspace in which you live when you execute commands from prompt • Remarks: • Each MATLAB function has its own workspace (its own sandbox) • A function invoked from a calling function has its own and separate workspace (sandbox) • A script does not lead to a new workspace (unlike a function), but lives in the workspace from which it was invoked

  44. Variable Types in MATLAB • Local Variables • In general, a variable in MATLAB has local scope, that is, it’s only available in its workspace • The variable disappears when the workspace ceases to exist • Recall that a script does not define a new workspace – be careful, otherwise you can step on variables defined at the level where the script is invoked • Since a function defines its own workspace, a variable defined in a function is local to that function • Variables defined outside the function should be passed to function as arguments. Furthermore, the arguments are passed by value • Every variable defined in the subroutine, if to be used outside the body of the function, should be returned back to the calling workspace

  45. Variable Types in MATLAB • Global Variables • These are variables that are available in multiple workspaces • They have to be explicitly declared as being global • Not going to expand on this, since using global variables is a bad programming practice • A note on returning values from a function • Since all variables are local and input arguments are passed by value, when returning from a function a variable that is modified inside that function will not appear as modified in the calling workspace unless the variable is either global, or declared a return variable for that function

  46. Flow Control Statements if Statement if ((attendance >= 0.90) & (grade_average >= 60)) pass = 1; end; while Loops eps = 1; while (1+eps) > 1 eps = eps/2; end eps

  47. Flow Control Statements a = zeros(k,k) % Preallocate matrix for m = 1:k for n = 1:k a(m,n) = 1/(m+n -1); end end for Loop: method = 'Bilinear'; ... (some code here)... switch lower(method) case {'linear','bilinear'} disp('Method is linear') case 'cubic' disp('Method is cubic') otherwise disp('Unknown method.') end Method is linear switchStatement:

  48. Editing and Debugging M-Files • The Editor/Debugger • 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

  49. Debugging Select Workspace Set Auto- Breakpoints tips

  50. Importing and Exporting Data • Using the Import Wizard • Using Save and Load command save fname save fname x y z save fname -ascii save fname -mat load fname load fname x y z load fname -ascii load fname -mat

More Related