Presentation is loading. Please wait.

Presentation is loading. Please wait.

MATLAB for Engineering Applications

Similar presentations


Presentation on theme: "MATLAB for Engineering Applications"— Presentation transcript:

1 MATLAB for Engineering Applications
Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH Basic Information: restrooms--through the hall to the right, found on the right sign the sheet by the door, get booklet, sign up for userid and password ask questions; will try to answer OSC--facilities for high performance computing STS Group: supports users; tests systems; develops courses; participates in national collaborations technical Web page:

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

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

4 Overview

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

6 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 Intro MATLAB

7 MATLAB Toolboxes 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 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 Intro MATLAB

8 Toolboxes, Software, & Links
Intro MATLAB

9 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 Intro MATLAB

10 Online MATLAB Resources
web.mit.edu/afs/athena.mit.edu/software/matlab/ www/home.html www-h.eng.cam.ac.uk/help/tpl/programs/matlab.html Intro MATLAB

11 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. Intro MATLAB

12 Some More Resources MATLAB Educational sites:
Yahoo! MATLAB Web site: dir.yahoo.com/Science/mathematics/software/matlab/ Newsgroup: comp.soft-sys.matlab Intro MATLAB

13 Basic Interfaces

14 Main MATLAB Interface Intro MATLAB

15 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 (openvar varname 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”) Intro MATLAB

16 MATLAB Editor Window Intro MATLAB

17 MATLAB Help Window (Very Powerful)
Intro MATLAB

18 Command-Line Help : List of MATLAB Topics
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... Intro MATLAB

19 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. Intro MATLAB

20 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 Intro MATLAB

21 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 1x double fid 1x double i x double Intro MATLAB

22 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 My startup.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 Intro MATLAB

23 Variables (Arrays) and Operators

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

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

26 The basic data type used in MATLAB is the double precision array
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/Preferences and/or format function to change default short (5 digits), long (16 digits) format short g; format compact (my preference) Intro MATLAB

27 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 use array 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 Intro MATLAB

28 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 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 seconds. Roughly 31 times faster without use of for loop Intro MATLAB

29 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. Intro MATLAB

30 Durer’s Matrix: Creation
» durer1N2row = [ ; ]; » durer3row = [ ]; » durer4row = [ ]; » durerBy4 = [durer1N2row;durer3row;durer4row]; » durerBy4 durerBy4 = Intro MATLAB

31 Easier Way... durerBy4 = » durerBy4r2 = [ ; ; ; ] durerBy4r2 = Intro MATLAB

32 Multidimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled with normally distributed random numbers r(:,:,1) = r(:,:,2) = r(:,:,3) = r(:,:,4) = “%” sign precedes comments, MATLAB ignores the rest of the line randn(2,3,4): 3 dimensions, filled with normally distributed random numbers Intro MATLAB

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

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

35 String Functions yo = Hello Class >> ischar(yo) ans = 1
>> strcmp(yo,yo) 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 Intro MATLAB

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

37 Matrix Operations >> durer = [ ; ; ; ] durer = >> % 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 = MATLAB also has magic(N) (N > 2) function Intro MATLAB

38 Transpose Operator >> % to get the row sums, we'll use the transpose operator >> % (an apostrophe) >> durer' ans = >> row_sums = sum(durer')' row_sums = 34 Intro MATLAB

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

40 The Other Diagonal… >> durer durer = 16 3 2 13 5 10 11 8
>> fliplr(durer) % “flip left-right” ans = >> sum(diag(fliplr(durer))) 34 Intro MATLAB

41 Matrix Subscripting >> durer durer = 16 3 2 13 5 10 11 8
>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3) diag_sum = 33 >> durer(4,4) = pi >> durer(4,4) = 1 Intro MATLAB

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

43 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 34 Intro MATLAB

44 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 scalar version 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. Intro MATLAB

45 Dot Operator Example >> A = [1 5 6; 11 9 8; 2 34 78] A = 1 5 6
>> B = [ ; ; ] B = Intro MATLAB

46 Dot Operator Example (cont.)
>> C = A * B % “normal” matrix multiply C = >> CDOT = A .* B % element-by-element CDOT = Intro MATLAB

47 Two Division Operators
Right divide (familiar version) a/b What happens: a is divided by b Right operand “goes into” left operand Left divide a\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 Intro MATLAB

48 Using the Division Operators
>> x = 53.0; >> y = 22.5; >> x/y ans = >> x\y ans = >> (x/y)^(-1) 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 Intro MATLAB

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

50 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 Intro MATLAB

51 Lab 1 Create a row vector called X whose elements are the integers 1 through 9. Create another row vector called Temp whose elements are: These data are the result of an experiment on heat conduction through an iron bar. The array X contains positions on the bar where temperature measurements were made. The array Temp contains the corresponding temperatures. Make a 2-D plot with temperature on the y-axis and position on the x-axis. The data shown in your plot should lie along a straight line (according to physics) but don’t because of measurement errors. Use the MATLAB polyfit function to fit the best line to the data (use >> hold on; for multiple plots in same figure). In other words use polyfit to determine the coefficients a and b of the equation T = ax + b Lastly, we can calculate a parameter called chi-square (χ2) that is a measure of how well the data fits the line. Calculate chi-square by running the MATLAB command that does the following matrix multiplication: >> (Temp-b-a*X)*(Temp-b-a*X)' Intro MATLAB

52 Lab 2 Write a MATLAB command that will generate a column vector called theta. theta should have values from –2π to 2π in steps of π/100. Generate a matrix F that contains values of the following functions in the columns indicated: Column 1: cos(θ) Column 2: cos(2θ)(1 + sin(θ2) Column 3: e -0.1|θ| Evaluate each of the above functions for the θ values in the theta vector from above. Plot each of the columns of F against theta. Overlay the three plots, using a different color for each. Create a new column vector called maxVect that contains the largest of the three functions above for each theta. Plot maxVect against theta. Create a column vector called maxIndex that has the column number of the maximum value in that row. Intro MATLAB

53 Programming

54 Outline MATLAB m-file Editor
To start: click icon or enter edit command in Command Window, e.g., >> edit test.m Scripts and Functions Decision Making/Looping if/else switch for and while Running Operating System Commands Intro MATLAB

55 m-file Editor Window You can save and run the file/function/script in one step by clicking here Tip: semi-colons suppress printing, commas (and semi- colons) allow multiple commands on one line, and 3 dots (…) allow continuation of lines without execution Intro MATLAB

56 Scripts and Functions Scripts do not accept input arguments, nor do they produce output arguments. Scripts are simply MATLAB commands written into a file. They operate on the existing workspace. Functions accept input arguments and produce output variables. All internal variables are local to the function and commands operate on the function workspace. A file containing a script or function is called an m-file If duplicate functions (names) exist, the first in the search path (from path command) is executed. Intro MATLAB

57 Functions – First Example
function [a b c] = myfun(x, y) b = x * y; a = 100; c = x.^2; >> myfun(2,3) % called with zero outputs ans = 100 >> u = myfun(2,3) % called with one output u = >> [u v w] = myfun(2,3) % called with all outputs v = 6 w = 4 Write these two lines to a file myfun.m and save it on MATLAB’s path Any return value which is not stored in an output variable is simply discarded Intro MATLAB

58 Example: deLaunay Triangulation
Have a set of random (x,y) points and want to connect them together to make a triangular grid The deLaunay algorithm creates a set of triangles such that no (other) data points are contained within the area or perimeter of any given triangle. Creates an “orthogonal” set of triangles The resulting grid is useful as a coordinate system Used in scatter pattern analysis: Position of debris resulting from an explosion Establish properties of the explosion: its original location, strength, parts specifications, … Intro MATLAB

59 Interactive Session >> x = randn(1,12); % generates 12 normally distributed numbers >> y = randn(1,12); >> z = zeros(1,12); % trimesh (used below) needs three arguments >> plot(x,y,'o'); >> tri = delaunay(x,y); >> hold on, trimesh(tri,x,y,z), hold off; % plot triangles >> hidden off %reveal all hidden points >> title(‘deLaunay Triangulation') Intro MATLAB

60 MATLAB script: mydelaunay.m
% deLaunay triangulation % % You must have variables x, y, and z instanced % in the workspace plot(x,y,'o'); tri = delaunay(x,y); hold on, trimesh(tri,x,y,z), hold off; % plot triangles hidden off % reveal all hidden points! title(‘deLaunay triangulation') Intro MATLAB

61 Using the mydelaunay script
>> x = randn(1,12); % generates 12 normally distributed numbers >> y = randn(1,12); >> z = zeros(1,12); % trimesh (used below) needs three arguments >> mydelaunay Intro MATLAB

62 Function: Header/Help Comments
function angles = ortho(a,b,c) %ortho function input: Three vectors each with 3 elements % The output is a 3-element array containing the % angles between each pair of input vectors. The % output elements are respectively: % angle between a and b % angle between b and c % angle between a and c % Typical use or ortho is to determine if a,b,c form an % orthogonal basis set that spans 3-D space. All initial comment lines are displayed when help is used on a function NOTE: This function should be saved in a file named ortho.m H1 (help 1) line displayed when using lookfor Intro MATLAB

63 Function: Body anorm = norm(a); % Local Variables
bnorm = norm(b); % Calculate vector lengths cnorm = norm(c); ab = dot(a,b); % Calculate Dot Products bc = dot(b,c); ac = dot(a,c); cosy_ab = ab/(anorm*bnorm); % Calculate cosine of cosy_bc = bc/(bnorm*cnorm); % included angles cosy_ac = ac/(anorm*cnorm); angles(1) = convert2deg(acos(cosy_ab)); % Create output angles(2) = convert2deg(acos(cosy_bc)); angles(3) = convert2deg(acos(cosy_ac)); return Intro MATLAB

64 Using Your ortho Function
>> a = [1 2 3]; >> b = [4 5 6]; >> c = [7 8 9]; >> ortho(a,b,c) ans = >> a = [22 0 0]; >> b = [0 5 0]; >> c = [0 0 13]; Intro MATLAB

65 Getting ortho Function Help
>> help ortho ortho function input: Three vectors each with 3 elements The output is a 3-element array containing the angles between each pair of input vectors. The output elements are respectively: angle between a and b angle between b and c angle between a and c Typical use or ortho is to determine if a,b,c form an orthogonal basis set that spans 3-D space. >> help sin SIN Sine. SIN(X) is the sine of the elements of X. See also asin, sind. Intro MATLAB

66 Function Syntax Summary
If the m-file name and function name differ, the file name takes precedence Function names must begin with a letter First line must contain function followed by the most general calling syntax Statements after initial contiguous comments (help lines) are the body of the function Terminates on the last line or a return statement Intro MATLAB

67 Function Syntax Summary (cont.)
error and warning can be used to test and continue execution (error-handling) Scripts called in m-file functions are evaluated in the function workspace Additional functions (subfunctions) can be included in an m-file Use which command to determine precedence, e.g., >> which title C:\MATLAB71\toolbox\matlab\graph2d\title Intro MATLAB

68 Variable Argument Lists
varargin / varargout allow variable numbers of input / output function arguments Used only inside function m-files Must be declared as the last input / output argument Declarations must be typed in lowercase Intro MATLAB

69 Variable Argument Lists (cont.)
Consider the following function m-file: function myplot(x, varargin) plot(x, varargin{:}) All input arguments beginning with the second one are collected into the variable varargin so the function call: myplot(x.^2,'color',[ ],'linestyle',‘o’) results in varargin being a 1-by-4 cell array with the values ‘color’, [ ], ‘linestyle’ and ‘o’ Intro MATLAB

70 Variable Argument Lists (cont.)
Consider the m-file: function [s, varargout] = mysize(x) nout = max(nargout,1) - 1; s = size(x); for k = 1:nout, varargout(k) = {s(k)}; end The following >> [s,rows,cols] = mysize(rand(4,5)) returns s = [4 5], rows = 4, cols = 5 nargout: number of output arguments in function call pack all output values into varargout cell array Intro MATLAB

71 if/elseif/else Statement
>> A = 2; B = 3; >> if A > B 'A is bigger' elseif A < B 'B is bigger' elseif A == B 'A equals B' else error('Something odd is happening') end ans = B is bigger Intro MATLAB

72 switch Statement >> n = 8 n = 8 >> switch(rem(n,3)) case 0
m = 'no remainder' case 1 m = ‘the remainder is one' case 2 m = ‘the remainder is two' otherwise error('not possible') end m = the remainder is two Intro MATLAB

73 for Loop >> for i = 2:5 for j = 3:6 a(i,j) = (i + j)^2 end
Intro MATLAB

74 while Loop >> b = 4; a = 2.1; count = 0;
>> while b - a > 0.01 a = a ; count = count + 1; end >> count count = 1891 Intro MATLAB

75 A Performance Tip Input variables are not copied into the function
workspace, unless If any input variables are changed, the variable will be copied Avoid performance penalty when using large arrays by extracting only those elements that will need modification Intro MATLAB

76 MATLAB’s Search Path Is name a variable? Is name a built-in function?
Does name exist in the current directory? Does name exist anywhere in the search path? “Discovery functions”: who, whos, what, which, exist, help, doc, lookfor, dir, ls, ... Intro MATLAB

77 Changing the Search Path
The addpath command adds directories to the MATLAB search path. The specified directories are added to the beginning of the search path. >> addpath('c:\'); >> matlabpath MATLABPATH c:\ E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops >> path MATLABPATH E:\MATLAB\R2006b\work E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\toolbox\matlab\ops rmpath is used to remove paths from the search path Intro MATLAB

78 Common OS Commands ls / dir provide a directory listing of the current directory >> ls sample.m >> pwd shows the current directory >> pwd ans = e:\Program Files\MATLAB\R2006b\work >> Intro MATLAB

79 Running OS Commands The system command can be used to run OS commands
On Unix systems, the unix command can be used as well On DOS systems, the corresponding command is dos >> dos('date') The current date is: Thu 01/04/2007 Enter the new date: (mm-dd-yy) ans = Intro MATLAB

80 Lab 1 Create, perhaps using for-loops, a synthetic “image” that has a 1 in the (1,1) location, and a 255 in the (128,128) location, and i + j - 1 in the i, j location. This we'll refer to as the ”diagonal gray'' image. Can you manage to do this without using for-loops? Display the image using (we’ll assume you placed your image in a matrix named a) image(a); colormap(gray). (Don’t worry if this doesn’t work exactly the way you expect. Colormaps can be tricky!) Now convert your code to a MATLAB script Test your script to insure that it produces the same results as the ones obtained interactively. Intro MATLAB

81 Lab 2 next = 0.5(last +(x/last))
Write a MATLAB function that implements Newton’s iterative algorithm for approximating the square root of a number. The core of Newton’s algorithm is that if last is the last approximation calculated, the next (improved) approximation is given by next = 0.5(last +(x/last)) where x is the number whose square root you seek. Two other pieces of information are needed to implement the algorithm. The first is an initial guess at the square root. (A typical starting value might be 1.0, say). The second is the accuracy required for the approximation. You might specify you want to keep iterating until you get an approximation that is good to 5 decimal places for example. Your MATLAB function should have three input arguments: x, the initial guess, and the accuracy desired. It should have one output, the approximate square root of x to the desired accuracy. Intro MATLAB

82 Data I/O

83 Loading and Saving Workspace Variables
MATLAB can load and save data in .MAT format .MAT files are binary files that can be transferred across platforms; as much accuracy as possible is preserved. Load: load filename OR A = load(‘filename’) loads all the variables in the specified file (the default name is MATLAB.MAT) Save: save filename variables saves the specified variables (all variables by default) in the specified file (the default name is MATLAB.MAT) Intro MATLAB

84 ASCII File Read/Write load and save can also read and write ASCII files with rows of space separated values: load test.dat –ascii save filename variables (options are ascii, double, tabs, append) save example.dat myvar1 myvar2 -ascii -double Intro MATLAB

85 ASCII File Read/Write (cont.)
dlmread M = dlmread(filename,delimiter,range); reads ASCII values in file filename that are separated by delimiter into variable M; most useful for numerical values. The last value in a line need not have the delimiter following it. range = [R1 C1 R2 C2] (upper-left to lower-right corner) dlmwrite dlmwrite(filename,A,delimiter); writes ASCII values in array A to file filename with values separated by delimiter Useful with spreadsheet data range of data to be read Intro MATLAB

86 More ASCII File Read textread
[A, B, C, ...] = textread[‘filename’, ‘format’]; [A, B, C, ...] = textread[‘filename’, ‘format’, N]; [...] = textread[..., ‘param’, ‘value’, ...]; The type of each return argument is given by format (C-style conversion specifiers: %d, %f, %c, %s, etc…) Number of return arguments must match number of conversion specifiers in format format string is reused N times or entire file is read if N not given Using textread you can specify values for whitespace, delimiters and exponent characters specify a format string to skip over literals or ignore fields Intro MATLAB

87 textread Example Data file, tab delimited: MATLAB m-file: Results:
‘param’,’value’ pairs use doc textread for available param options Results: Intro MATLAB

88 Import Wizard Import ASCII and binary files using the Import Wizard. Type uiimport at the Command line or choose Import Data from the File menu. Intro MATLAB

89 Low-Level File I/O Functions
File Opening and Closing fclose: Close one or more open files fopen: Open a file or obtain information about open files Unformatted I/O fread: Read binary data from file fwrite: Write binary data to a file Formatted I/O fgetl: Return the next line of a file as a string without line terminator(s) fgets: Return the next line of a file as a string with line terminator(s) fprintf: Write formatted data to file fscanf: Read formatted data from file Intro MATLAB

90 Low-Level File I/O (cont.)
File Positioning feof: Test for end-of-file ferror: Query MATLAB about errors in file input or output frewind: Rewind an open file fseek: Set file position indicator ftell: Get file position indicator String Conversion sprintf: Write formatted data to a string sscanf: Read string under format control Intro MATLAB

91 File Open (fopen)/Close (fclose)
fid = fopen(‘filename’, ‘permission’); status = fclose(fid); Permission requested: ‘r’, ’r+’ ‘w’, ’w+’ ‘a’, ’a+’ File identifier number Name of file 0, if successful -1, otherwise File identifier number or ‘all’ for all files Intro MATLAB

92 fscanf and fprintf are similar to C version but vectorized
Formatted I/O fscanf: [A, count] = fscanf(fid,format,size); fprintf: count = fprintf(fid, format, A,...); Data array File identifier number Format specifier Number successfully read Amount of data to read: n, [n, m], Inf Number successfully read File identifier number Format specifier Data array(s) to write fscanf and fprintf are similar to C version but vectorized Intro MATLAB

93 Format String Specification
alignment flag conversion specifier initial % character width and precision Specifier Description %c Single character %d Decimal notation (signed) %e Exponential notation %f Fixed-point notation %g The more compact of %e or %f %o Octal notation (unsigned) %s String of characters %u Decimal notation (unsigned) %x Hexadecimal notation ...others... Intro MATLAB

94 Other Formatted I/O Commands
fgetl: line = fgetl(fid); reads next line from file without line terminator fgets: line = fgets(fid); reads next line from file with line terminator textread: [A,B,C,...] = textread('filename','format',N) reads N lines of formatted text from file filename sscanf: A = sscanf(s, format, size); reads string under format control sprintf: s = sprintf(format, A); writes formatted data to a string Intro MATLAB

95 fread and fwrite are vectorized
Binary File I/O [data, count] = fread(fid, num, precision); count = fwrite(fid, data, precision); Data array Number successfully read File identifier number Amount to read n, [n, m],... ‘int’, ‘double’, … ‘int’, ‘double’, … Number successfully written File identifier number array to write fread and fwrite are vectorized Intro MATLAB

96 File Position Commands
feof: tf = feof(fid); tests for end of file fseek: status = fseek(fid, offset, origin); sets the file position ftell: position = ftell(fid); gets the file position frewind: frewind(fid); rewinds the file ferror: message = ferror(fid); inquire about file I/O status Intro MATLAB

97 MATLAB m-file to read it
File I/O Example Data file MATLAB m-file to read it fid = fopen('asciiData.txt','r'); i = 1; while ~feof(fid) name(i,:) = fscanf(fid,'%5c',1); year(i) = fscanf(fid,'%d',1); no1(i) = fscanf(fid,'%d',1); no2(i)=fscanf(fid,'%d',1); no3(i)=fscanf(fid,'%g',1); no4(i)=fscanf(fid,'%g\n'); i=i+1; end fclose(fid); MATLAB output Since a tab counts as one character in MATLAB, you must use spaces after the name field in the data file (else get “Tom 1” in name output, etc...) Intro MATLAB

98 File I/O Example (Alternative)
Cell arrays (storage mechanism for dissimilar kinds of data) offer a very flexible alternative Avoid the nuances and pitfalls of counting spaces and tabs Create a cell array to store the field name by using curly braces after variable name: name{i} = fscanf(fid, ‘%s’, 1); curly braces are cell array constructors %s (string) format specifier can be used here with cell array Intro MATLAB

99 Specialized File I/O Commands
hdf: HDF interface imfinfo: Return information about a graphics file imread/imwrite: Read/Write image from graphics file wk1read/wk1write: Read/Write a Lotus123 WK1 spreadsheet file into a matrix xlsread/xlswrite: Read/Write a matrix to a Excel spreadsheet file urlread: read data from a URL Intro MATLAB

100 uigetfile: Interactively Get a Filename
[filename, pathname, filterindex] = uigetfile(‘Filterspec’, ‘DialogTitle’); Example: >> f = uigetfile('*.jpg;*.bmp;*.gif;*.tif','Specify Graphics File:') Intro MATLAB

101 Structures Multidimensional MATLAB arrays
Access elements using textual field designators Create structures by using periods (.): >> class.name = ‘MATLAB’; >> class.day1 = ‘2/27/07’; >> class.day2 = ‘2/28/07’; >> class class = name: ‘MATLAB’ day1: ‘2/27/07’ day2: ‘2/28/07’ Intro MATLAB

102 Manipulating Structures
Structures are arrays (no surprise) Fields can be added one at a time: >> class(2).name = ‘MPI’; >> class(2).day1 = ‘TBA’; >> class(2).day2 = ‘TBA’; Can also use a single statement: >> class(2) = struct(‘name’,‘MPI’,... ‘day1’,‘TBA’,‘day2’,‘TBA’) Intro MATLAB

103 Manipulating Structures (cont.)
Consider the simple structure >> exam.name = ‘Jim Kirk’; >> exam.score = 79; >> exam(2).name = ‘Janice Lester’; >> exam(2).score = 89; >> [exam.score] ans = square brackets produce a numeric row vector Intro MATLAB

104 Manipulating Structures (cont.)
Can also create a cell array using curly braces: >> {exam.name} ans = 'Jim Kirk' 'Janice Lester' Intro MATLAB

105 Lab 1 The data file DataIO_lab1.dat is a binary data file containing a 256 X 256 image. The data is stored in row order with each pixel value being a double value. Read the data in DataIO_lab1.dat into a 256 X 256 real array, and display it as a gray scale image. Here are some suggestions to help you: Preallocate the array that will hold the image data. Use the function fopen to open the file and get a file handle. Since the data is binary, use the function fread to read the data; if you want you can read it 256 values at a time. To display the data array as an image, use the MATLAB command image If the resulting image is rotated, you can use the transpose operator to take care of that. Close the file using fclose. Scale the array so that all pixel values are between 1 and 64 What are you looking at? (FUN: experiment with non-gray colormaps …) Intro MATLAB

106 Lab 2 The data file DataIO_lab2.csv is an ASCII data file that consists of comma separated real values. There are 3000 rows and 16 columns of data. The first column corresponds to sampling instants and the next 15 columns correspond to vibration data collected from a shaker table. Write a short m-file to read the data in the DataIO_lab2.csv file and assign it to two variables: t which is a 3000 X 1 array containing the sampling instants and x which is a 3000 X 15 array containing the data on all the channels. You can use fscanf (in conjunction with fopen) or dlmread to read the data. Plot x(:,1) through x(:,15) against t. MATLAB provides another way of reading ASCII data files: textread. Use textread to read the data in DataIO_lab2.csv and assign it to the variables t and x. Intro MATLAB

107 Basic Data Analysis 107

108 Basic Data Analysis Basic, and more advanced, statistical analysis is easily accomplished in MATLAB. Remember that the MATLAB default is to assume vectors are columnar. Each column is a variable, and each row is an observation. Intro MATLAB

109 Vibration Sensors Data
Each column is the raw rpm sensor data from a different sensor used in an instrumented engine test. The rows represent the times readings were made. Intro MATLAB

110 Plotting the Data >> plot(rpm_raw) >> xlabel('sample number - during time slice'); >> ylabel('Unfiltered RPM Data'); >> title(‘3 sequences of samples from RPM sensor’) Note that in this case the plot command generates one time-series for each column of the data matrix Intro MATLAB

111 Average of the Data: 1 2 >> mean(rpm_raw)
ans = >> mean(mean(rpm_raw)) 1055.6 Applying the mean function to the data matrix yields the mean of each column 2 But you can easily compute the mean of the entire matrix (applying a function to either a single row or a single column results in the function applied to the column, or the row, i.e., in both cases, the application is to the vector). Intro MATLAB

112 The mean Function >> help mean MEAN Average or mean value. For vectors, MEAN(X) is the mean value of the elements in X. For matrices, MEAN(X) is a row vector containing the mean value of each column. For N-D arrays, MEAN(X) is the mean value of the elements along the first non-singleton dimension of X. MEAN(X,DIM) takes the mean along the dimension DIM of X. Example: If X = [0 1 2 3 4 5] then mean(X,1) is [ ] and mean(X,2) is [1 4] But we can apply the mean function along any dimension >> mean(rpm_raw, 2) ans = 1045.7 1064.7 1060.7 1055 1045 3 So we can easily obtain the row means Intro MATLAB

113 max and its Index 2 1 MAX Largest component. For vectors, MAX(X) is the largest element in X. For matrices, MAX(X) is a row vector containing the maximum element from each column. For N-D arrays, MAX(X) operates along the first non-singleton dimension. [Y,I] = MAX(X) returns the indices of the maximum values in vector I. If the values along the first non- singleton dimension contain more than one maximal element, the index of the first one is returned. >> max(rpm_raw) ans = >> max(max(rpm_raw)) 1120 >> [y,i] = max(rpm_raw) y = i = We can compute the max of the entire matrix, or of any dimension max along the columns Intro MATLAB

114 min >> min(rpm_raw) ans = 1053 1053 961
>> min(min(rpm_raw)) 961 >> [y,i] = min(rpm_raw) y = i = min along each column min of entire matrix Intro MATLAB

115 Standard Deviation, Median, Covariance
>> median(rpm_raw) % median along each column ans = >> cov(rpm_raw) % covariance of the data >> std(rpm_raw) % standard deviation along each column >> var(rpm_raw) % variance is the square of std Intro MATLAB

116 Data Analysis: Histogram
HIST Histogram. N = HIST(Y) bins the elements of Y into 10 equally spaced containers and returns the number of elements in each container. If Y is a matrix, HIST works down the columns. N = HIST(Y,M), where M is a scalar, uses M bins. N = HIST(Y,X), where X is a vector, returns the distribution of Y among bins with centers specified by X. The first bin includes data between -inf and the first center and the last bin includes data between the last bin and inf. Note: Use HISTC if it is more natural to specify bin edges instead. . . . Intro MATLAB

117 Histogram (cont.) >> hist(rpm_raw) %histogram of the data
Intro MATLAB

118 Histogram (cont.) >> hist(rpm_raw, 20) %histogram of the data
Intro MATLAB

119 Histogram (cont.) >> hist(rpm_raw, 100) %histogram of the data
Intro MATLAB

120 Data Analysis: Sorting
>> help sort SORT Sort in ascending or descending order. For vectors, SORT(X) sorts the elements of X in ascending order. For matrices, SORT(X) sorts each column of X in ascending order. For N-D arrays, SORT(X) sorts the along the first non-singleton dimension of X. When X is a cell array of strings, SORT(X) sorts the strings in ASCII dictionary order. Y = SORT(X,DIM,MODE) has two optional parameters. DIM selects a dimension along which to sort. MODE selects the direction of the sort 'ascend' results in ascending order 'descend' results in descending order The result is in Y which has the same shape and type as X. [Y,I] = SORT(X,DIM,MODE) also returns an index matrix I. If X is a vector, then Y = X(I). If X is an m-by-n matrix and DIM=1, then for j = 1:n, Y(:,j) = X(I(:,j),j); end 1 2 3 Intro MATLAB

121 Sorting Data (cont.) 1 >> magic(4) ans = 16 2 3 13 5 11 10 8
>> sort(magic(4)) 1 Intro MATLAB

122 Sorting Data (cont.) 2 >> magic(4) >> sort(magic(4),2)
ans = ans = >> sort(magic(4),1) ans = 2 Intro MATLAB

123 Sorting Data (cont.) 3 >> magic(4) ans = 16 2 3 13 5 11 10 8
>> [y i] = sort(magic(4)) y = i = 3 Intro MATLAB

124 Bin Average Filtering FILTER One-dimensional digital filter. Y = FILTER(B,A,X) filters the data in vector X with the filter described by vectors A and B to create the filtered data Y. The filter is a "Direct Form II Transposed" implementation of the standard difference equation: a(1)*y(n) = b(1)*x(n) + b(2)*x(n-1) b(nb+1)*x(n-nb) - a(2)*y(n-1) a(na+1)*y(n-na) >> filter(ones(1,3), 3, rpm_raw) ans = This example uses an FIR filter to compute a moving average using a window size of 3 Intro MATLAB

125 Filtered Data Plot Intro MATLAB

126 Fast Fourier Transform (FFT)
fft is one of the built-in functions in MATLAB The fft function can compute the discrete Fourier transform of any arbitrary length sequence. fft incorporates most known fast algorithms for various lengths (e.g. power of 2) Not all lengths are equally fast Intro MATLAB

127 Discrete Fourier Transform Definition
Intro MATLAB

128 fft and fftshift 1 11 N=11 2 After fftshift N=11 - Intro MATLAB

129 Example: FFT of sine Wave in Noise
>> t = [0:999]*(1/fs); >> x = sin(2*pi*250*t); >> X = fft(x(1:512)); >> noise = 0.8*randn(size(x)); >> xn = x + noise; >> XnMag = fftshift(20*log10(abs(fft(xn(1:512))))); >> XnMagPf = XnMag(256:512); >> frq = [0:length(XnMagPf) - 1]'*(fs/length(XnMag)); >> plot(frq, XnMagPf) >> xlabel('freq. (Hz)'); >> ylabel('Mag. (db)'); Intro MATLAB

130 Frequency Spectrum Intro MATLAB

131 Lab 1 Load the data_analysis_lab1.mat file into the MATLAB workspace. This will produce an array variable called grades containing grades on an exam between 0 and 100. Calculate the average and standard deviation of the grades. Plot a histogram of the grades using 100 bins. We want to compare the histogram with a Gaussian distribution. Write you own MATLAB Gaussian function M-file which returns a value y using the following formula y=exp(-[x-m]2/2σ2) where m is the average and σ is the standard deviation of the distribution. Your function should have input arguments x,m, and σ. On the histogram plot also plot a Gaussian distribution of the grades using the calculated average and standard deviation. Intro MATLAB

132 Lab 2 Load the file data_analysis_lab2.mat. Since this is a .mat file, you should be able to load it easily using the load command. Your workspace should now contain a single variable x. x is 3000 points long and consists of the sum of 3 sine waves. The sampling frequency is Hz. Plot the first 0.33 seconds of x. You may find it convenient to create a second array (say called time) that has the time values corresponding to the samples in x. >> Fs = 1000; %Sampling frequency >> time = [0:length(x)-1]’*(1/Fs); % time index fft is a built-in function in MATLAB. We can compute and plot the magnitude of the FFT of x to identify the frequencies of the sine waves. >> X = fft(x); X is a complex valued array that is the FFT of x. We can compute the magnitude of the FFT by taking the absolute value of X. >> Xmag = abs(X); >> plot(Xmag); Intro MATLAB

133 Lab 2 (cont.) The plot of Xmag shows 6 components, and also we have only index values not real frequency values along the abscissa. Six components show up because the FFT is evaluated over positive and negative frequencies. Also, the frequencies are “wrapped around”. We can take care of the wrap around using the fftshift function. >> Xmag = fftshift(Xmag); Next, we can generate a suitable frequency axis for plotting Xmag. >> frq = [0:length(Xmag)-1]’*(Fs/length(Xmag)) – (Fs/2); >> plot(frq, Xmag); Can you see the 3 frequency components (in the positive freq. part of the axis)? Zoom into the plot either using the axis command or the interactive zoom button on the figure’s toolbar and determine the frequencies of the 3 components. Intro MATLAB

134 Numerical Analysis 134

135 Overview IEEE double precision numbers Numerical Linear Algebra
Solving linear equations (Ax  b) Condition number Matrix factorizations Eigenvalues and eigenvectors Singular value decomposition Solving ODE’s Numerical integration Root finding Nonlinear optimization Intro MATLAB

136 IEEE Double Precision Numbers
Fundamental data type in MATLAB is a double precision value in ANSI/IEEE Standard 754 format: Roundoff: eps = 2-52 ≈ 10-16 Underflow: realmin = ≈ Overflow: realmax = (2 - eps) * ≈ 10308 eps, realmin and realmax are built in variables in MATLAB. E (11 bits) s f (52 bits) A numeric value is represented as: (-1)s (1.f) 2 (E-1023) s Intro MATLAB

137 Solving Linear Equations
Consider the set of equations Ax = b A is an n x m matrix, x is an m x 1 vector and b is an n x 1 vector The rank of a matrix is the number of independent rows (or columns). Rank can be checked using the MATLAB command rank Equations are consistent if rank(A) = rank([A b]) independent if rank(A) = n Existence of solution Uniqueness of solution Intro MATLAB

138 Linear Equations, n = m When A is square (i.e.,
>> b = [366; 804; 351] b = 366 804 351 >> [rank(A) rank([A b])] ans = >> x = A\b x = 25 22 99 When A is square (i.e., n = m) and the equations are independent and consistent, the unique solution can be found using the \ operator. MATLAB finds the solution using a LU decomposition of A. Intro MATLAB

139 Linear Equations, n < m
When the number of equations is less than the number of unknowns (i.e., n < m), usually an infinite number of solutions exist. \ finds the solution with no more than rank(A) non- zero elements. pinv can be used to find the solution with min ||x||. >> A = [2 3 4; 1 1 1]; b = [4;5]; >> x = A\b x = 8 -3 >> x1 = pinv(A)*b x1 = 7.1667 1.6667 >> sqrt([sum(x.^2) sum(x1.^2)]) ans = Intro MATLAB

140 Example: Force Required to Move Object
Force, F Unit mass, velocity at time t = 0 is 0. Force on object is F(t). F(t) = xj, j - 1 < t < j, j = 1, …, 10 Want total distance moved in 10 s to be 1. Want velocity at t =10 s to be 0. Intro MATLAB

141 Example (cont.) This leads to the underdetermined set of equations
Intro MATLAB

142 Example (cont.) >> x1 = A\b x1 = 0.11111 -0.11111
>> x2 = pinv(A) * b x2 = >> [norm(x1) norm(x2)] ans = Intro MATLAB

143 Linear Equations, n > m
When there are more equations than unknowns (i.e., n > m), usually no solution exists. \ can be used to find the least squares solution, i.e., the x that minimizes ||Ax-b||2 >> A = [2 -1; 1 1; 6 -1]; >> b = [2; 5; -5]; >> [rank(A) rank([A b])] ans = >> x = A\b x = 2.4459 Intro MATLAB

144 Example: Fit Polynomial to Data
Assume we can model data as Assume e is measurement noise, and that we have n measurements of x and y. This leads to an overdetermined set of equations: Intro MATLAB

145 Example (cont.) Intro MATLAB

146 Condition of a Matrix Consider Ax = b. If A changes by a small amount A, how large is the change in the solution x? ||x||/||x|| < k(A) ||A||/||A|| (A) is the condition number of A (A) is calculated using the MATLAB command cond(A) Consider A essentially singular if (A) > 1/eps >> A = [1 1; ] >> b = [2; 2.01]; >> x = A\b x = 1 >> A1 = [ ; ]; >> x1 = A1\b x1 = -0.01 2 >> cond(A) ans = 402.01 Intro MATLAB

147 Matrix Factorizations: lu
lu: factors a square matrix A into the product of a permuted lower triangular matrix L and an upper triangular matrix U such that A = LU. Useful in computing inverses, Gaussian elimination. >> A = [1 2 -1; 1 0 1; ]; >> [L, U] = lu(A) L = U = >> L * U ans = Intro MATLAB

148 Matrix Factorizations: chol
chol: factors a symmetric, positive definite matrix A as RTR, where R is upper triangular. Useful in solving least squares problems. >> A = [2 -1; 1 1; 6 -1]; >> B = A'*A B = >> R = chol(B) R = >> R'*R ans = Intro MATLAB

149 Eigenvalues and Eigenvectors: eig
eig: computes the eigenvalues, i and eigenvectors, xi of a square matrix A.. i and xi satisfy Axi = i xi [V,D] = eig(A) returns the eigenvectors of A in the columns of V, and the eigenvalues in the diagonal elements of D. >> A = [1 -1 0; 0 1 1; ]; >> [V, D] = eig(A) V = D = >> [A*V(:,3) D(3,3)*V(:,3)] ans = Intro MATLAB

150 Singular Value Decomposition: svd
svd: factors an n x m matrix A as A = USVT, where U and V are orthogonal matrices, and S is a diagonal matrix with singular values of A. Useful in solving least squares problems. >> A = [2 -1; 1 1; 6 -1]; >> [U,S,V] = svd(A) U = S = V = Intro MATLAB

151 Pseudoinverse: pinv pinv: The pseudoinverse of an n x m matrix A is a matrix B such that BAB = B and ABA = A MATLAB uses the SVD of A to compute pinv. Useful in solving least squares problems. >> A = [2 -1; 1 1; 6 -1]; >> B = pinv(A) B = >> A*B*A ans = >> B*A*B Intro MATLAB

152 More Matrix Math in MATLAB
det(A): computes determinant inv(A): computes inverse expm(A),logm(A), sqrtm(A): computes exponential, logarithm and square root of A polyvalm(p,A): evaluate matrix polynomial, p(A). lscov(A, b, V): computes least square solution with known covariance lsqnonneg(A,b): non-negative least squares norm(A): computes matrix norm orth(A), null(A): finds a basis for the range and null space of A qr(A): orthogonal-triangular decomposition of A subspace(A,B): computes angle between subspaces defined by A and B Intro MATLAB

153 Ordinary Differential Equations
MATLAB has a collection of m-files, called the ODE suite to solve initial value problems of the form M(t,y)dy/dt = f(t, y) y(t0) = y0 where y is a vector. The ODE suite contains several procedures to solve such coupled first order differential equations. Intro MATLAB

154 Steps in ODE Solution Using MATLAB
Express the differential equation as a set of first-order ODEs M(t,y)dy/dt = f(t,y) Write an m-file to compute the state derivative function dydt = myprob(t, y) Use one of the ODE solvers to solve the equations [t, y] = ode_solver(‘myprob’, tspan, y0); Initial conditions Solution time span [t0 tf] Time index Solution matrix ODE solver ODE file for derivatives Intro MATLAB

155 ODE Suite Solvers Non-stiff equations Stiff equations
ode23: explicit, one-step Runge-Kutta low-order solver ode45: explicit, one-step Runge-Kutta medium order solver. First solver to try on a new problem ode113: multi-step Adams-Bashforth-Moulton solver of varying order ode23s: implicit, one- step modified Rosenbrock solver of order 2 ode15s: implicit, multi- step numerical differentiation solver of varying order. Solver to try if ode45 fails or is too inefficient Intro MATLAB

156 Example : van der Pol Equation
function dydt = vdpol(t,y) % % van der Pol equation mu = 2; dydt = [y(2);mu*(1- … y(1)^2)*y(2)-y(1)]; ODE File vdpol.m Equation is d2x/dt2 - (1-x2)dx/dt + x = 0 Convert to first order ODEs using y1 = x, y2 = dx/dt dy1/dt = y2 dy2/dt=(1-y12)y2-y1 Intro MATLAB

157 van der Pol Equation Solution
>> tspan = [0 20]; >> y0 = [2; 0]; >> [t, y] = ode45('vdpol', tspan, y0); >> plot(t, y(:,1), t, y(:,2), '--'); Intro MATLAB

158 More on ODE Solvers There are a number of different options in specifying the ODE file. Check HELP on odefile for details. odeset and odeget can be used to set and examine the ODE solver options. Can find events (such as max/min/zero, crossings etc.) in the solution. Intro MATLAB

159 Numerical Integration
trapz: Trapezoidal integration quad: Adaptive, recursive Simpson’s Rule for quadrature quadl: Adaptive, recursive Newton-Coates 8-panel rule dblquad: Double integration using quad or quadl Intro MATLAB

160 Integration Example: humps Function
>> x = linspace(-1,2,150); >> y = humps(x); >> plot(x,y) >> format long >> trapz(x,y) % 5-digit accuracy ans = >> quad('humps', -1, 2) % 6-digit accuracy >> quadl('humps', -1, 2) % 8-digit accuracy Intro MATLAB

161 Root Finding and Minimization
roots: finds roots of polynomials fzero: finds roots of a nonlinear function of one variable fminbnd, fminsearch: finds maxima and minima of functions of one and several variables Intro MATLAB

162 Example of Polynomial Roots
p(x)=x3+4x2-7x-10 Intro MATLAB

163 Example of Roots for Nonlinear Functions
Intro MATLAB

164 Example of Function Minimization
>> x = linspace(0,2,100); >> y = polyval(p,x); >> plot(x,y) >> fminbnd('x.^3-2*x-5',0,2) ans = 0.8165 >> polyval(p,ans) Intro MATLAB

165 Lab 1 Consider the set of equations Ax=b where A is an 8x8 matrix given by A(i,j)=1.0+(|i-j|/8.0)½ and b is a 8x1 array given by b(i)=i Solve for x using: The \ operator The MATLAB pinv function The MATLAB inv function LU Decomposition How do your answers compare? For best performance, evaluate the matrix A without using any for loops Intro MATLAB

166 Lab 2 Use numerical integration to integrate 1/(1+x2) from 0 to 1. The result is analytically calculated to be /4. Use the following three MATLAB functions: trap() quad() quadl() and compare the accuracy of your numerical result with the exact value. Use quad or quadl to get the most accurate result possible with MATLAB. How accurate is it? Intro MATLAB

167 Graphics, Data Visualization & Movies

168 Overview Plots Simple plots Subplots (Multiple Axis Regions)
Mesh plots (Colored wire-frame view of surface) Surface Plots Patches Contour Plots Visualization Images Indexed images Intensity images Truecolor images Reading and writing images Movies Intro MATLAB

169 Basic XY Plot >> x = [0:pi/100:pi]; >> y = sin(x);
>> plot(x,y), title('Simple Plot') Intro MATLAB

170 Multiple Curve Plots >> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'), title('More Complicated') Line color, style, marker type, all within single quotes Intro MATLAB

171 Plot Power: Contour & 3-D Mesh
>> t = 0:pi/25:pi; >> [x,y,z] = cylinder(4*cos(t)); >> subplot(2,1,1) >> contour(y) >> subplot(2,1,2) >> mesh(x,y,z) >> xlabel('x') >> ylabel('this is the y axis') >> text(1,-2,0.5,... '\it{Note the gap!}') To save: print -djpeg myfigure.jpg use help print for options Intro MATLAB

172 Subplots Used to display multiple plots in the same figure window,
subplot(m,n,i) subdivides the window into m-by-n subregions (subplots) and makes the ith subplot active for the current plot >> subplot(2,3,1) >> plot(t, sin(t), 'r:square') >> axis([-Inf,Inf,-Inf,Inf]) >> subplot(2,3,3) >> plot(t, cos(t), 'g') >> axis([-Inf,Inf,-1,1]) >> subplot(2,3,5) >> plot(t, sin(t).*cos(t), 'b-.') 3 1 2 4 5 6 Intro MATLAB

173 Mesh Plots MATLAB defines a surface by the z-coordinates of points above a rectangular grid in the x-y plane Plot is formed by joining adjacent defining points with straight lines Surface plots are used when matrices are too large to visualize numerically, and also to graph functions of two variables Use to generate a colored wire-frame view of a surface displayed in a 3-D view Only the lines connecting the defining points are colored mesh(Z) generates a wireframe view of matrix Z, where Z(i,j) define the height of a surface over the rectangular x-y grid: >> figure(2); >> [X,Y] = meshgrid(-16:1.0:16); >> Z = sqrt(X.^2 + Y.^ ); >> mesh(Z) Intro MATLAB

174 Surface Plots surf(Z) generates a colored faceted 3-D view of the surface. By default, the faces are quadrilaterals, each of constant color, with black mesh lines The shading command allows you to control the view >> figure(2); >> [X,Y] = meshgrid(-16:1.0:16); >> Z = sqrt(X.^2 + Y.^ ); >> surf(Z) Default: shading faceted >> shading flat >> shading interp Intro MATLAB

175 Surface Plots: Colormaps
>> colormap hot >> colormap gray >> colormap cool >> colormap pink Intro MATLAB

176 More Surface Plots >> meshc(Z) >> meshz(Z)
>> surfl(Z) >> pcolor(Z) Intro MATLAB

177 Patches A patch is a graphics object which contains one or more polygons. The polygons don’t have to be connected Useful for modeling real-world objects such as missiles and tanks Use the patch function to display a patch One way to define a patch is to specify Faces and Vertices Vertices, v Faces, f Vertex Vertex Vertex Vertex Vertex Vertex Vertex Vertex Face Face Face Face Face Face Intro MATLAB

178 Patches: MATLAB code >> v = [0 0 0; ; 1 1 0; 0 1 0; ; ; ; ]; >> f = [ ; ; ; ; ; ]; >> % Code to make top figure on previous slide >> patch('Vertices', v, 'Faces', f, 'FaceVertexCData', hsv(6), 'FaceColor', 'flat') >> view(3) >> axis square >> grid on >> clf >> % Code to make bottom figure on previous slide >> patch('Vertices', v, 'Faces', f, 'FaceVertexCData', hsv(8), 'FaceColor', ‘interp’) Intro MATLAB

179 Contour Plots Use to create, display, and label isolines determined by one or more matrices contour(Z) generates isolines from values given by a matrix Z and displays it in 2-D contour3(Z) generates isolines from values given by a matrix Z and displays it in 3-D >> Z = peaks; >> contour(Z,40) >> >> Z = peaks; >> contour3(Z,40) >> Intro MATLAB

180 More Contour Plots >> Z = peaks; >> Z = peaks;
>> [C, h] = contour(Z, 10); >> clabel(C, h); >> title('Labeled Contour') >> Z = peaks; >> [C, h] = contourf(Z, 10); >> title('Filled Contour') >> Intro MATLAB

181 Visualization: Light Technique for adding photo-realistic appearance to a graphical scene Use light to create lighting effects in MATLAB in conjunction with the following three important properties Color Style Position >> set(L1, 'Color', 'g') >> set(L1, 'Position', [-1, -1, 1]) >> set(L1, 'Style', 'local') Intro MATLAB

182 MATLAB Lighting Code >> % This code creates the upper left figure on previous slide >> [X, Y, Z] = sphere(64); >> h = surf(X, Y, Z); >> axis square >> reds = zeros(256, 3); >> for i=1:256 reds(i, 1) = (i-1)/255; end >> colormap(reds) >> shading interp >> L1 = light('Position', [-1, -1, -1]); >> lighting phong >> set(h, 'AmbientStrength', 0.75); >> set(h, 'DiffuseStrength', 0.5); Intro MATLAB

183 Visualization: Viewpoint
Use view to specify the viewpoint by defining azimuth and elevation with respect to the origin MATLAB defaults For 2-D plots, azimuth = 0o elevation = 90o For 3-D plots, azimuth = -37.5o elevation = 30o z y Default View >> view(-37.5, 60); Elevation x Azimuth -y >> view(0, 90); >> view(-37.5, 90); Intro MATLAB

184 Visualization: Camera Properties
Use the set command to modify parameters associated with a graphics object. In this case, the Camera Properties >> set(gca,'CameraTarget',[0,0,2]) >> set(gca,'CameraPosition',[-800,-800,13]) Default View >> set(gca,'CameraViewAngle',30) >> set(gca,'Projection','perspective') >> set(gca,'CameraUpVector',[0,1,0]) Intro MATLAB

185 Camera Default Properties
MATLAB defaults: CameraPosition: Position adjusted such that the orientation of the scene is the standard MATLAB 2-D or 3-D view CameraTarget: Center of plot box CameraUpVector: y-direction for 2-D views and z-direction for 3-D views CameraViewAngle: Angle adjusted such that scene fills the position rectangle Projection: orthographic Intro MATLAB

186 Indexed Images Consists of a data matrix, I and a colormap matrix, C C is an m-by-3 matrix, with each row specifying the R, G, and B components of a single color Values in C are floating point numbers in the range [0, 1] Color of each pixel is determined by using the corresponding value of I as an index into the colormap R G B 1 1 2 1 1 10 0.5 0.5 0.5 10 I C 1 0.35 0.25 m Intro MATLAB

187 Intensity Images >> imagesc(I); colormap(gray);
Consists of a data matrix, I, whose values represent intensities within some range. For double-precision data, the intensity values are in the range [0, 1], where 0 represents black, and 1 represents white. Values in between 0 and 1 represent shades of gray Use the following to display intensity images. >> imagesc(I, [0, 1]); colormap(gray); The second input argument [0, 1] to imagesc specifies the desired intensity range. I is displayed by first mapping the first value in the range to the first colormap entry, and second value in the range to the last colormap entry. Values in between are mapped linearly. To automatically map the minimum value in I to the first colormap entry, and the maximum value in I to the last colormap entry, do the following. >> imagesc(I); colormap(gray); Intro MATLAB

188 Truecolor Images (RGB Images)
Consist of a m-by-n-by-3 data array, I, containing the R, G, and B components for each individual pixel I(:, :, 1) is the red component of the image I(:, :, 2) is the green component of the image I(:, :, 3) is the blue component of the image To display a truecolor image, do the following >> image(I) Truecolor images do not use colormaps HumVee(:, :, 3) HumVee(:, :, 2) HumVee(:, :, 1) Intro MATLAB

189 Summary: Commands to Display Images
Use the following to display an Indexed image. >> image(I); colormap(map) Use the following to display an Intensity image >> imagesc(I); colormap(map); Use the following to display a Truecolor image >> image(I); Intro MATLAB

190 Reading Images MATLAB can read images of various formats including
BMP, HDF, JPEG, PCX, TIFF, XWD Use function imread to read image files imread reads indexed, intensity, and truecolor images Images are read into a uint8 matrix of appropriate size imread automatically determines the format of the image based on information in the header You can specify a format as an optional second argument Intro MATLAB

191 MATLAB Code for Reading Images
>> Crusader = imread(’Crusader.jpg'); >> image(Crusader) >> whos Crusader Name Size Bytes Class Crusader 186x250x uint8 array Grand total is elements using bytes Intro MATLAB

192 Writing Images MATLAB can write images of various formats including the following BMP, HDF, JPEG, PCX, TIFF, XWD Use function imwrite to write image files imwrite writes indexed, intensity, and truecolor images Images are written as a uint8 matrix (converted if necessary) of appropriate size along with colormaps (if necessary) and headers imwrite determines the format from extension of filename. You can specify an optional format if extension is absent or to force a particular format Use imfinfo(filename) to get information on an image file Intro MATLAB

193 Writing Images: MATLAB code
>> Abrams = imread(‘Abrams.jpg'); >> image(Abrams) >> whos Abrams Name Size Bytes Class Abrams x640x uint8 array Grand total is elements using bytes >> % Write out tank as gray image >> AbramsGray = rgb2gray(Abrams); >> colormap gray; >> image(AbramsGray) >> imwrite(AbramsGray, gray, 'Abrams.bmp'); Intro MATLAB

194 Creating Movies in MATLAB
MATLAB movies are stored in an array of movie frames. For example, in a movie array M, the ith frame is M(i). A movie frame is a structure having the fields "cdata" and "colormap" which contain the image data in a uint8 matrix and the colormap in a double matrix. Movie frames can be created by following commands getframe returns a movie frame by taking a snapshot of the current axis. For example, F=getframe; im2frame converts an indexed image into movie format. For example, F=im2frame(A,MAP) returns the frame as an indexed image matrix A and a colormap MAP. A MATLAB movie array can be played back by the movie command. movie(M,N,FPS) plays the movie M for N times at FPS frames per second. The default if FPS is omitted is 12 fps. Intro MATLAB

195 Movie Preparation & Play
Intro MATLAB

196 MATLAB movie ↔ AVI format
movie2avi(M,FILENAME,PARAM,VALUE,PARAM,VALUE...) creates an AVI file from the MATLAB movie M using the specified parameter settings. Available parameters are FPS - The frames per second for the AVI movie. The default is 15 fps. COMPRESSION - A string indicating the compressor to use. For example, ‘Indeo3’, ‘Indeo5’, ‘Cinepak’, ‘MSVC’, or ‘None’. QUALITY - A number between 0 and 100. Higher quality numbers result in higher video quality and larger file sizes. The default is 75. KEYFRAME - For compressors that support temporal compression, this is the number of key frames per second. The default is 2 key frames per second. COLORMAP - An M-by-3 matrix defining the colormap to be used for indexed AVI movies. VIDEONAME - A descriptive name for the video stream. This parameter must be no greater than 64 characters long. The default name is the filename. M = aviread(FILENAME) reads the AVI movie FILENAME into a movie array M. Intro MATLAB

197 Example that Illustrates the Use of Movies to Visualize the Various Powers of the N-th Root of Unity, exp(2pi / n) figure(1) numframes=16; % gca: “get current axis”; returns handle to the % current axes for the current figure set(gca, ‘NextPlot', 'replacechildren') axis equal % fix the axes for k=1:numframes plot(fft(eye(k+16))); % eye: Identity matrix A(k)=getframe; end movie(A) Intro MATLAB

198 aviread Refer to Example 1 in movie documentation (doc
movie) to create frame array F using getframe then: >> movie2avi(F, ‘wave.avi’) >> M = aviread(‘wave.avi’) >> movie(M) This can create some very large files! aviread can only read Type-2 Digital Video AVI files Intro MATLAB

199 Lab 1 Show views from various angles of the surface defined by the following function: z = |x| * exp(-x2-y2) * y in MATLAB, use: Z = abs(X) .* exp(-X .^ 2 – Y .^ 2) .* Y; Define an x-y grid with x and y in [-2, 2] with increments of 0.2. Show a total of 6 views in the same figure. Camera parameters for each view should appear in the title for the sub-image. Detailed Instructions Use meshgrid to define the grid ([X, Y] = meshgrid(-2:0.2:2, -2:0.2:2);) Use “subplot” to get multiple plots in the same figure Use surfc for the first three plots, and surf for the remaining three plots Use the “shading” and “view” functions to achieve desired appearance and view Set the title for each view using the “title” function Use “axis tight” to make the surface fill the extent of the axes for each view Use “axis vis3d” to preserve aspect ratio for different views Set the size and position of the figure window using the “set” function. Intro MATLAB

200 Inter-Language Programming
200

201 MEX Basics MEX stands for MATLAB EXecutable
MEX files are C and FORTRAN programs that are callable from MATLAB after compiling Why? Pre-existing C/FORTRAN programs can be called from MATLAB without rewriting codes in MATLAB Computations that do not run fast enough in MATLAB, such as for loops, can be coded in C or FORTRAN for efficient implementation. Access to hardware such as A/D, D/A converters, GPIB hardware, serial/parallel port, etc. Protect intellectual property Intro MATLAB

202 MEX Procedure Procedures for working with MATLAB’s MEX mechanism
Prepare the C or Fortran MEX program according to MATLAB external interfacing rules Compile the C or FORTRAN MEX program using MATLAB command “mex” mex in turn makes use of external C or FORTRAN compilers Call the compiled MEX function in the same way as calling any MATLAB function Intro MATLAB

203 MEX Include File : mex.h Must be included in all MEX Files source code
Defines the prototypes of all mex* API functions (e.g. mexErrMsgTxt() in our example ) mex* functions used to set up program tasks Includes matrix.h, which in turn defines the prototypes of all mx* API functions (e.g. mxGetN() in our example) mx* functions used for data variables Intro MATLAB

204 Gateway Function : mexFunction()
Equivalent to main() in C programs Has 4 arguments void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) Number of LHS arguments Pointer to array of of LHS argument pointers Number of RHS arguments Pointer to array of of RHS argument pointers Intro MATLAB

205 Sample Problem: Scaling
Simple example: A C function that takes its input, multiplies each element by 2, and then returns the “scaled-up” values Straightforward C task chosen so that MEX requirements can be emphasized Resulting C MEX file is general purpose in nature How the function might be used in MATLAB: >> [a b] = timestwo(x,y); Intro MATLAB

206 mexFunction in Scaling Example
In MATLAB: >> a = timestwo(x) void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) In timestwo.c: nlhs = 1 nrhs = 1 a plhs x (matrix) prhs Intro MATLAB

207 A platform-specific binary is generated after compiling
MEX Procedure 1. Compile timestwo.c using “mex” command in MATLAB Compiling mex program, timestwo.c >> mex timestwo.c >> dir *.mexw32 timestwo.mexw32 A platform-specific binary is generated after compiling 2. Use timestwo.mexw32 like any MATLAB command >> [a b] = timestwo(5,6) a = 10 b = 12 Intro MATLAB

208 timestwo.c include “mex.h” Gateway function and its 4 arguments
#include “mex.h” // do not forget this void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *p,*n; // pointers to output and input arrays int i,j,m,n; // indices and dimension variables if (nrhs != nlhs) // Error Check mexErrMsgTxt(“Number of input and output args differ"); for(i = 0; i < nrhs; i++) { m = mxGetM(prhs[i]); n = mxGetM(prhs[i]); // get dims plhs[i] = mxCreateDoubleMatrix(m,n,mxREAL); data1 = mxGetPr(prhs[i]); // retrieve input data2 = mxGetPr(plhs[i]); // create pointer to output for(j = 0; j < m*n; j++ { data2[j] = 2 * data1[j]; } Gateway function and its 4 arguments Dynamically allocate memory for the output array Processing the input parameters Intro MATLAB


Download ppt "MATLAB for Engineering Applications"

Similar presentations


Ads by Google