1 / 208

MATLAB for Engineering Applications

MATLAB for Engineering Applications. Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212 http://www.osc.edu/. Table of Contents – Day One. Overview Basic Interfaces Arrays, Matrices, Operators Programming Data I/O.

Télécharger la présentation

MATLAB for Engineering Applications

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. MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212 http://www.osc.edu/

  2. Intro MATLAB Table of Contents – Day One • Overview • Basic Interfaces • Arrays, Matrices, Operators • Programming • Data I/O

  3. Intro MATLAB Table of Contents – Day Two • Basic Data Analysis • Numerical Analysis • Graphics, Data Visualization, Movies • Inter-language Programming

  4. Overview

  5. Intro MATLAB MATLAB • “MATrix LABoratory” • Powerful, extensible, highly integrated computation, programming, visualization, and simulation package • Widely used in engineering, mathematics, and science • Why?

  6. Intro MATLAB MATLAB’s Appeal • Interactive code development proceeds incrementally; excellent development and rapid prototyping environment • Basic data element is the auto-indexed array • This allows quick solutions to problems that can be formulated in vector or matrix form • Powerful GUI tools • Large collection of toolboxes: collections of topic-related MATLAB functions that extend the core functionality significantly

  7. Intro MATLAB MATLAB Toolboxes Signal & Image Processing Signal Processing Image Processing Communications Frequency Domain System Identification Higher-Order Spectral Analysis System Identification Wavelet Filter Design Control Design  Control System Fuzzy Logic Robust Control μ-Analysis and Synthesis Model Predictive Control Math and Analysis Optimization Requirements Management Interface Statistics Neural Network Symbolic/Extended Math Partial Differential Equations PLS Toolbox Mapping Spline Data Acquisition and Import Data Acquisition Instrument Control Excel Link Portable Graph Object

  8. Intro MATLAB Toolboxes, Software, & Links

  9. Intro MATLAB MATLAB System • Language: arrays and matrices, control flow, I/O, data structures, user-defined functions and scripts • Working Environment: editing, variable management, importing and exporting data, debugging, profiling • Graphics system: 2D and 3D data visualization, animation and custom GUI development • Mathematical Functions: basic (sum, sin,…) to advanced (fft, inv, Bessel functions, …) • API: can use MATLAB with C, Fortran, and Java, in either direction

  10. Intro MATLAB Online MATLAB Resources • www.mathworks.com/ • www.mathtools.net/MATLAB • www.math.utah.edu/lab/ms/matlab/matlab.html • web.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.html • www.utexas.edu/its/rc/tutorials/matlab/ • www.math.ufl.edu/help/matlab-tutorial/ • www.indiana.edu/~statmath/math/matlab/links.html • www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html

  11. Intro MATLAB References Mastering MATLAB 7, D. Hanselman and B. Littlefield, Prentice Hall, 2004 Getting Started with MATLAB 7: A Quick Introduction for Scientists and Engineers, R. Pratap, Oxford University Press, 2005.

  12. Intro MATLAB Some More Resources MATLAB Educational sites: http://www.eece.maine.edu/mm/matweb.html Yahoo! MATLAB Web site: dir.yahoo.com/Science/mathematics/software/matlab/ Newsgroup: comp.soft-sys.matlab

  13. Basic Interfaces

  14. Intro MATLAB Main MATLAB Interface

  15. Intro MATLAB Some MATLAB Development Windows • Command Window: where you enter commands • Command History: running history of commands which is preserved across MATLAB sessions • Current directory: Default is $matlabroot/work • Workspace: GUI for viewing, loading and saving MATLAB variables • Array Editor: GUI for viewing and/or modifying contents of MATLAB variables (openvarvarname or double-click the array’s name in the Workspace) • Editor/Debugger: text editor, debugger; editor works with file types in addition to .m (MATLAB “m-files”)

  16. Intro MATLAB MATLAB Editor Window

  17. Intro MATLAB MATLAB Help Window (Very Powerful)

  18. Intro MATLAB Command-Line Help: List of MATLAB Topics >> help HELP topics: matlab\general - General purpose commands. matlab\ops - Operators and special characters. matlab\lang - Programming language constructs. matlab\elmat - Elementary matrices and matrix manipulation. matlab\elfun - Elementary math functions. matlab\specfun - Specialized math functions. matlab\matfun - Matrix functions - numerical linear algebra. matlab\datafun - Data analysis and Fourier transforms. matlab\polyfun - Interpolation and polynomials. matlab\funfun - Function functions and ODE solvers. matlab\sparfun - Sparse matrices. matlab\scribe - Annotation and Plot Editing. matlab\graph2d - Two dimensional graphs. matlab\graph3d - Three dimensional graphs. matlab\specgraph - Specialized graphs. matlab\graphics - Handle Graphics. …etc...

  19. Intro MATLAB Command-Line Help: List of Topic Functions >> help matfun Matrix functions - numerical linear algebra. Matrix analysis. norm - Matrix or vector norm. normest - Estimate the matrix 2-norm. rank - Matrix rank. det - Determinant. trace - Sum of diagonal elements. null - Null space. orth - Orthogonalization. rref - Reduced row echelon form. subspace - Angle between two subspaces. …

  20. Intro MATLAB Command-Line Help: Function Help >> help det DET Determinant. DET(X) is the determinant of the square matrix X. Use COND instead of DET to test for matrix singularity. See also cond. Overloaded functions or methods (ones with the same name in other directories) help laurmat/det.m Reference page in Help browser doc det

  21. Intro MATLAB Keyword Search of Help Entries >> lookfor who newton.m: % inputs: 'x' is the number whose square root we seek testNewton.m: % inputs: 'x' is the number whose square root we seek WHO List current variables. WHOS List current variables, long form. TIMESTWO S-function whose output is two times its input. >> whos Name Size Bytes Class Attributes ans 1x1 8 double fid 1x1 8 double i 1x1 8 double

  22. Intro MATLAB startup.m • Customize MATLAB’s start-up behavior • Create startup.m file and place in: • Windows: $matlabroot\work • UNIX: directory where matlab command is issued Mystartup.m file: addpath e:\download\MatlabMPI\src addpath e:\download\MatlabMPI\examples addpath .\MatMPI format short g format compact eliminates extra blank lines in output

  23. Variables (Arrays) and Operators

  24. Intro MATLAB Variable Basics >> 16 + 24 ans = 40 >> product = 16 * 23.24 product = 371.84 >> product = 16 *555.24; >> product product = 8883.8 no declarations needed mixed data types semi-colon suppresses output of the calculation’s result

  25. Intro MATLAB Variable Basics >> clear >> product = 2 * 3^3; >> comp_sum = (2 + 3i) + (2 - 3i); >> show_i = i^2; >> save three_things >> clear >> load three_things >> who Your variables are: comp_sum product show_i >> product product = 54 >> show_i show_i = -1 clearremoves all variables; clear x y removes only x and y complex numbers (ior j) require no special handling save/loadare used to retain/restore workspace variables use home to clear screen and put cursor at the top of the screen

  26. Intro MATLAB MATLAB Data The basic data type used in MATLAB is the double precision array • No declarations needed: MATLAB automatically allocates required memory • Resize arrays dynamically • To reuse a variable name, simply use it in the left hand side of an assignment statement • MATLAB displays results in scientific notation • Use File/Preferencesand/or format function to change default • short (5 digits), long (16 digits) • format short g; format compact (my preference)

  27. Intro MATLAB Variables Revisited • Variable names are case sensitive and over-written when re-used • Basic variable class:Auto-Indexed Array • Allows use of entire arrays (scalar, 1-D, 2-D, etc…) as operands • Vectorization:Always usearray operands to get best performance (see next slide) • Terminology: “scalar” (1 x 1 array), “vector” (1 x N array), “matrix” (M x N array) • Special variables/functions:ans, pi, eps, inf, NaN, i, nargin, nargout, varargin, varargout, ... • Commands who (terse output) and whos (verbose output) show variables in Workspace

  28. Intro MATLAB Vectorization Example* >> type slow.m tic; x=0.1; for k=1:199901 y(k)=besselj(3,x) + log(x); x=x+0.001; end toc; >> slow Elapsed time is 17.092999 seconds. *times measured on this laptop >> type fast.m tic; x=0.1:0.001:200; y=besselj(3,x) + log(x); toc; >> fast Elapsed time is 0.551970 seconds. Roughly 31 times faster without use of for loop

  29. Intro MATLAB Matrices: Magic Squares This matrix is called a “magic square” Interestingly, Durer also dated this engraving by placing 15 and 14 side-by-side in the magic square.

  30. Intro MATLAB Durer’s Matrix: Creation » durer1N2row = [16 3 2 13; 5 10 11 8]; » durer3row = [9 6 7 12]; » durer4row = [4 15 14 1]; » durerBy4 = [durer1N2row;durer3row;durer4row]; » durerBy4 durerBy4 = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1

  31. Intro MATLAB Easier Way... durerBy4 = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 » durerBy4r2 = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] durerBy4r2 = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1

  32. Intro MATLAB Multidimensional Arrays >> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) = -0.6918 1.2540 -1.4410 0.8580 -1.5937 0.5711 r(:,:,2) = -0.3999 0.8156 1.2902 0.6900 0.7119 0.6686 r(:,:,3) = 1.1908 -0.0198 -1.6041 -1.2025 -0.1567 0.2573 r(:,:,4) = -1.0565 -0.8051 0.2193 1.4151 0.5287 -0.9219 “%” sign precedes comments, MATLAB ignores the rest of the line randn(2,3,4): 3 dimensions, filled with normally distributed random numbers

  33. Intro MATLAB Character Strings >> hi = ' hello'; >> class = 'MATLAB'; >> hi hi = hello >> class class = MATLAB >> greetings = [hi class] greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB concatenation with blank or with “,” semi-colon: join vertically

  34. Intro MATLAB Character Strings as Arrays >> greetings greetings = helloMATLAB >> vgreetings = [hi;class] vgreetings = hello MATLAB >> hi = 'hello' hi = hello >> vgreetings = [hi;class] ??? Error using ==> vertcat CAT arguments dimensions are not consistent. note deleted space at beginning of word; results in error

  35. Intro MATLAB String Functions yo = Hello Class >> ischar(yo) ans = 1 >> strcmp(yo,yo) ans = 1 returns 1 if argument is a character array and 0 otherwise returns 1 if string arguments are the same and 0 otherwise; strcmpi ignores case

  36. Intro MATLAB Set Functions Arrays are ordered sets: >> a = [1 2 3 4 5] a = 1 2 3 4 5 >> b = [3 4 5 6 7] b = 3 4 5 6 7 >> isequal(a,b) ans = 0 >> ismember(a,b) ans = 0 0 1 1 1 returns true (1) if arrays are the same size and have the same values returns 1 where a is in b and 0 otherwise

  37. Intro MATLAB Matrix Operations >> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] durer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> % durer's matrix is "magic" in that all rows, columns, >> % and main diagonals sum to the same number >> column_sum = sum(durer) % MATLAB operates column-wise column_sum = 34 34 34 34 MATLAB also has magic(N) (N > 2) function

  38. Intro MATLAB Transpose Operator >> % to get the row sums, we'll use the transpose operator >> % (an apostrophe) >> durer' ans = 16 5 9 4 3 10 6 15 2 11 7 14 13 8 12 1 >> row_sums = sum(durer')' row_sums = 34 34 34 34

  39. Intro MATLAB Diagonal Elements >> durer durer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> diag(durer) % diag plucks out the diagonal elements ans = 16 10 7 1 >> sum(diag(durer)) ans = 34

  40. Intro MATLAB The Other Diagonal… >> durer durer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> fliplr(durer) % “flip left-right” ans = 13 2 3 16 8 11 10 5 12 7 6 9 1 14 15 4 >> sum(diag(fliplr(durer))) ans = 34

  41. Intro MATLAB Matrix Subscripting >> durer durer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1 >> diag_sum = durer(1,1) + durer(2,2) + durer(3,3) diag_sum = 33 >> durer(4,4) = pi durer = 16.0000 3.0000 2.0000 13.0000 5.0000 10.0000 11.0000 8.0000 9.0000 6.0000 7.0000 12.0000 4.0000 15.0000 14.0000 3.1416 >> durer(4,4) = 1

  42. Intro MATLAB Colon Operator (Vector Creation) >> 1:5 % use the colon operator to create row vectors ans = 1 2 3 4 5 >> 1:0.9:6 % you can vary the increment (0.9 in this case) ans = 1.0000 1.9000 2.8000 3.7000 4.6000 5.5000 The last element is always less than or equal to the upper limit

  43. Intro MATLAB Colon Operator (Indexing) >> sum(durer(1:3,4)) % sums first three % elements of column 4 ans = 33 >> sum(durer(:,end)) % a lone colon is ALL % elements, end is % the last element ans = 34

  44. Intro MATLAB The “Dot Operator” • By default and whenever possible MATLAB will perform true matrix operations (+-*). The operands in every arithmetic expression are considered to be matrices. • If, on the other hand, the user wants the scalarversion of an operation a “dot” must be put in front of the operator, e.g., .*. Matrices can still be the operands but the mathematical calculations will be performed element-by-element. • A comparison of matrix multiplication and scalar multiplication is shown on the next slide.

  45. Intro MATLAB Dot Operator Example >> A = [1 5 6; 11 9 8; 2 34 78] A = 1 5 6 11 9 8 2 34 78 >> B = [16 4 23; 8 123 86; 67 259 5] B = 16 4 23 8 123 86 67 259 5

  46. Intro MATLAB Dot Operator Example (cont.) >> C = A * B % “normal” matrix multiply C = 458 2173 483 784 3223 1067 5530 24392 3360 >> CDOT =A.*B% element-by-element CDOT = 16 20 138 88 1107 688 134 8806 390

  47. Intro MATLAB Two Division Operators • Right divide (familiar version) a/b • What happens: a is divided by b • Right operand “goes into” left operand • Left dividea\b • What happens: b is divided by a • Left operand “goes into” right operand • Behavior depends on operands (scalar vs. matrix) • Both operators work with matrices (of course). More later on what is actually calculated … • Comparison of the use of / and \ on next slide

  48. Intro MATLAB Using the Division Operators >> x = 53.0; >> y = 22.5; >> x/y ans = 2.3556 >> x\y ans = 0.4245 >> (x/y)^(-1) ans = 0.4245 For matrix operands, A\B is the solution to Ax = B obtained by Gaussian elimination. Read “Arithmetic Operators + - * / \ ^ ’ ” in “MATLAB Function Reference”: HelpSearch for:division

  49. Intro MATLAB Easy 2-D Graphics >> x = [0: pi/100: pi]; % [start: increment: end] >> y = sin(x); >> plot(x,y), title('Simple Plot')

  50. Intro MATLAB Adding Another Curve >> z = cos(x); >> plot(x,y,'g.',x,z,'b-.'),title('More complicated') Line color, style, marker type, all within single quotes; type >> doc LineSpec for all available line properties

More Related