MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center...

208
MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212 http://www.osc.edu/

Transcript of MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center...

Page 1: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

MATLAB for Engineering ApplicationsAshok Krishnamurthy

Siddharth Samsi

Ohio Supercomputer Center

1224 Kinnear Road

Columbus, OH 43212

http://www.osc.edu/

Page 2: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

2

Intro MATLAB

Table of Contents – Day One

• Overview

• Basic Interfaces

• Arrays, Matrices, Operators

• Programming

• Data I/O

Page 3: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

3

Intro MATLAB

Table of Contents – Day Two

• Basic Data Analysis

• Numerical Analysis

• Graphics, Data Visualization, Movies

• Inter-language Programming

Page 4: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Overview

Page 5: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

5

Intro MATLAB

MATLAB

• “MATrix LABoratory”

• Powerful, extensible, highly integrated computation, programming, visualization, and simulation package

• Widely used in engineering, mathematics, and science

• Why?

Page 6: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 7: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 AnalysisOptimizationRequirements Management InterfaceStatisticsNeural NetworkSymbolic/Extended MathPartial Differential EquationsPLS ToolboxMappingSpline

Data Acquisition and ImportData AcquisitionInstrument ControlExcel LinkPortable Graph Object

Page 8: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

8

Intro MATLAB

Toolboxes, Software, & Links

Page 9: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 10: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 11: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

11

Intro MATLAB

References

Mastering MATLAB 7, D. Hanselman and B. Littlefield,Prentice Hall, 2004

Getting Started with MATLAB 7: A Quick Introductionfor Scientists and Engineers, R. Pratap, Oxford UniversityPress, 2005.

Page 12: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 13: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Basic Interfaces

Page 14: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

14

Intro MATLAB

Main MATLAB Interface

Page 15: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 (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”)

Page 16: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

16

Intro MATLAB

MATLAB Editor Window

Page 17: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

17

Intro MATLAB

MATLAB Help Window (Very Powerful)

Page 18: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

18

Intro MATLAB

Command-Line Help : List of MATLAB Topics

>> helpHELP 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...

Page 19: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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.

Page 20: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 21: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

21

Intro MATLAB

Keyword Search of Help Entries

>> lookfor whonewton.m: % inputs: 'x' is the number whose

square root we seektestNewton.m: % inputs: 'x' is the number whose

square root we seekWHO 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

Page 22: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

My startup.m file:

addpath e:\download\MatlabMPI\srcaddpath e:\download\MatlabMPI\examplesaddpath .\MatMPIformat short gformat compact eliminates extra blank lines in outputeliminates extra blank lines in output

Page 23: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Variables (Arrays) and Operators

Page 24: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

24

Intro MATLAB

Variable Basics

no declarations neededno declarations needed

mixed data typesmixed data types

semi-colon suppresses output of the calculation’s result

semi-colon suppresses output of the calculation’s result

>> 16 + 24ans = 40

>> product = 16 * 23.24product = 371.84

>> product = 16 *555.24;>> productproduct = 8883.8

Page 25: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

25

Intro MATLAB

Variable Basics

complex numbers (i or j) require no special handling

complex numbers (i or j) require no special handling

clear removes all variables;

clear x y removes only x and y

clear removes all variables;

clear x y removes only x and y

save/load are used to

retain/restore workspace variables

save/load are used to

retain/restore workspace variables

>> clear>> product = 2 * 3^3;>> comp_sum = (2 + 3i) + (2 - 3i);>> show_i = i^2;>> save three_things>> clear>> load three_things>> whoYour variables are:comp_sum product show_i >> productproduct = 54>> show_ishow_i = -1

use home to clear screen and put cursor at the top of the screen

use home to clear screen and put cursor at the top of the screen

Page 26: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 notationo Use File/Preferences and/or format function to change default

short (5 digits), long (16 digits) format short g; format compact (my preference)

Page 27: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 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

Page 28: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

28

Intro MATLAB

Vectorization Example*

>> type slow.mtic;x=0.1;for k=1:199901 y(k)=besselj(3,x) +

log(x); x=x+0.001;endtoc;>> slowElapsed time is 17.092999 seconds.

*times measured on this laptop

>> type fast.mtic;x=0.1:0.001:200;y=besselj(3,x) + log(x);toc;>> fastElapsed time is 0.551970 seconds.

Roughly 31 times faster without use of for loop

Page 29: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

29

Intro MATLAB

Matrices: Magic Squares

This matrix is called a “magic square”

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.

Interestingly, Durer also dated this engraving by placing 15 and 14 side-by-side in the magic square.

Page 30: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 31: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 32: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

randn(2,3,4): 3 dimensions, filled with normally distributed random numbers

randn(2,3,4): 3 dimensions, filled with normally distributed random numbers

“%” sign precedes comments, MATLAB ignores the rest of the line

“%” sign precedes comments, MATLAB ignores the rest of the line

Page 33: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

33

Intro MATLAB

Character Strings

>> hi = ' hello';>> class = 'MATLAB';>> hihi = hello>> classclass =MATLAB>> greetings = [hi class]greetings = helloMATLAB>> vgreetings = [hi;class]vgreetings = helloMATLAB

semi-colon: join verticallysemi-colon: join vertically

concatenation with blank or with “,”concatenation with blank or with “,”

Page 34: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 atbeginning of word;results in error

note deleted space atbeginning of word;results in error

Page 35: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

35

Intro MATLAB

yo =

Hello

Class

>> ischar(yo)

ans =

1

>> strcmp(yo,yo)

ans =

1

String Functions

returns 1 if argument is a characterarray and 0 otherwise

returns 1 if argument is a characterarray and 0 otherwise

returns 1 if string arguments are thesame and 0 otherwise; strcmpi ignores case

returns 1 if string arguments are thesame and 0 otherwise; strcmpi ignores case

Page 36: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

36

Intro MATLAB

Set FunctionsArrays 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 true (1) if arrays are the same size and have the same values

returns 1 where a is in b and 0 otherwise

returns 1 where a is in b and 0 otherwise

Page 37: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

37

Intro MATLAB

>> 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

Matrix Operations

MATLAB also hasmagic(N) (N > 2)function

MATLAB also hasmagic(N) (N > 2)function

Page 38: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 39: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

39

Intro MATLAB

Diagonal Elements

>> durerdurer = 16 3 2 13 5 10 11 8 9 6 7 12 4 15 14 1

>> diag(durer) % diag plucks out the diagonal elementsans = 16 10 7 1

>> sum(diag(durer))ans = 34

Page 40: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

40

Intro MATLAB

The Other Diagonal…>> durerdurer = 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

Page 41: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

41

Intro MATLAB

Matrix Subscripting>> durerdurer = 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) = pidurer = 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

Page 42: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

42

Intro MATLAB

Colon Operator (Vector Creation)

>> 1:5 % use the colon operator to create row vectorsans = 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

Page 43: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 44: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 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.

Page 45: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 46: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 47: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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 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

Page 48: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

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

Page 49: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

49

Intro MATLAB

Easy 2-D Graphics>> x = [0: pi/100: pi]; % [start: increment: end]

>> y = sin(x);

>> plot(x,y), title('Simple Plot')

Page 50: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

50

Intro MATLAB

Adding Another Curve

Line color, style, marker type, all within single quotes; type

>> doc LineSpec

for all available line properties

Line color, style, marker type, all within single quotes; type

>> doc LineSpec

for all available line properties

>> z = cos(x);

>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')

Page 51: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

51

Intro MATLAB

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:

15.6 17.5 36.6 43.8 58.2 61.6 64.2 70.4 98.8• 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)'

Page 52: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

52

Intro MATLAB

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.

Page 53: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Programming

Page 54: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

54

Intro MATLAB

• 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

Outline

Page 55: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

55

Intro MATLAB

You can save and run the file/function/script in one step by clicking here

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

Tip: semi-colons suppress printing, commas (and semi-colons) allow multiple commands on one line, and 3 dots (…) allow continuation of lines without execution

m-file Editor Window

Page 56: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

56

Intro MATLAB

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.

Page 57: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

57

Intro MATLAB

function [a b c] = myfun(x, y)b = x * y; a = 100; c = x.^2;

>> myfun(2,3) % called with zero outputsans = 100>> u = myfun(2,3) % called with one outputu = 100>> [u v w] = myfun(2,3) % called with all outputsu = 100v = 6w = 4

Functions – First Example

Write these two lines to a file myfun.m and save it on MATLAB’s path

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

Any return value which is not stored in an output variable is simply discarded

Page 58: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

58

Intro MATLAB

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, …

Page 59: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

59

Intro MATLAB

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')

Page 60: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

60

Intro MATLAB

MATLAB script: mydelaunay.m

% deLaunay triangulation% ----------------------% You must have variables x, y, and z instanced% in the workspaceplot(x,y,'o');tri = delaunay(x,y);hold on, trimesh(tri,x,y,z), hold off; % plot triangleshidden off % reveal all hidden points!title(‘deLaunay triangulation')

Page 61: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

61

Intro MATLAB

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

Page 62: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

62

Intro MATLAB

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

Page 63: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

63

Intro MATLAB

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

Page 64: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

64

Intro MATLAB

Using Your ortho Function

>> a = [1 2 3];>> b = [4 5 6];>> c = [7 8 9];>> ortho(a,b,c)ans = 12.9332 3.4470 16.3801>> a = [22 0 0];>> b = [0 5 0];>> c = [0 0 13];>> ortho(a,b,c)ans = 90 90 90

Page 65: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

65

Intro MATLAB

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.

Page 66: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

66

Intro MATLAB

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

Page 67: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

67

Intro MATLAB

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 titleC:\MATLAB71\toolbox\matlab\graph2d\title

Page 68: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

68

Intro MATLAB

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

Page 69: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

69

Intro MATLAB

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',[.5 .7 .3],'linestyle',‘o’)

results in varargin being a 1-by-4 cell array with the values ‘color’, [.5 .7 .3], ‘linestyle’ and ‘o’

Page 70: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

70

Intro MATLAB

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

pack all output valuesinto varargout cell array

pack all output valuesinto varargout cell array

nargout: number of outputarguments in function call

nargout: number of outputarguments in function call

Page 71: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

71

Intro MATLAB

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') endans =B is bigger

Page 72: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

72

Intro MATLAB

switch Statement

>> n = 8n = 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') endm =the remainder is two

Page 73: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

73

Intro MATLAB

for Loop>> for i = 2:5

for j = 3:6

a(i,j) = (i + j)^2

end

end

>> a

a =

0 0 0 0 0 0

0 0 25 36 49 64

0 0 36 49 64 81

0 0 49 64 81 100

0 0 64 81 100 121

Page 74: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

74

Intro MATLAB

while Loop

>> b = 4; a = 2.1; count = 0;>> while b - a > 0.01 a = a + 0.001; count = count + 1; end>> countcount = 1891

Page 75: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

75

Intro MATLAB

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

Page 76: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

76

Intro MATLAB

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, ...

Page 77: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

77

Intro MATLAB

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.

• rmpath is used to remove paths from the search path

>> path

MATLABPATH

E:\MATLAB\R2006b\workE:\MATLAB\R2006b\work\f_funcsE:\MATLAB\R2006b\work\na_funcsE:\MATLAB\R2006b\work\na_scriptsE:\MATLAB\R2006b\toolbox\matlab\generalE:\MATLAB\R2006b\toolbox\matlab\ops

>> addpath('c:\');>> matlabpath

MATLABPATH

c:\E:\MATLAB\R2006b\workE:\MATLAB\R2006b\work\f_funcsE:\MATLAB\R2006b\work\na_funcsE:\MATLAB\R2006b\work\na_scriptsE:\MATLAB\R2006b\toolbox\matlab\generalE:\MATLAB\R2006b\toolbox\matlab\ops

Page 78: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

78

Intro MATLAB

Common OS Commands

• ls / dir provide a directory listing of the current directory

• pwd shows the current directory

>> ls

. .. sample.m

>>

>> pwdans =e:\Program Files\MATLAB\R2006b\work>>

Page 79: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

79

Intro MATLAB

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 = 0

Page 80: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

80

Intro MATLAB

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.

Page 81: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

81

Intro MATLAB

Lab 2

• 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.

Page 82: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Data I/O

Page 83: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

83

Intro MATLAB

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)

Page 84: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

84

Intro MATLAB

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

Page 85: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

85

Intro MATLAB

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 readrange of data to be read

Page 86: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

86

Intro MATLAB

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

Page 87: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

87

Intro MATLAB

textread Example

• Data file, tab delimited:

• MATLAB m-file:

• Results:

‘param’,’value’ pairs

use doc textread for available param options

Page 88: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

88

Intro MATLAB

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.

Page 89: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

89

Intro MATLAB

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

Page 90: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

90

Intro MATLAB

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

Page 91: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

91

Intro MATLAB

File Open (fopen)/Close (fclose)• fid = fopen(‘filename’, ‘permission’);

• status = fclose(fid);

File identifiernumber

Name offile

Permissionrequested:‘r’, ’r+’‘w’, ’w+’‘a’, ’a+’

0, if successful-1, otherwise

File identifier numberor ‘all’ for all files

Page 92: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

92

Intro MATLAB

Formatted I/O• fscanf: [A, count] = fscanf(fid,format,size);

• fprintf: count = fprintf(fid, format, A,...);

Dataarray

Numbersuccessfully

read

Fileidentifiernumber

Amount of data to read:

n, [n, m], Inf

Formatspecifier

Numbersuccessfully

read

Fileidentifiernumber

Formatspecifier

Dataarray(s) to

write

fscanf and fprintf are similar to C version but vectorized

Page 93: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

93

Intro MATLAB

Format String Specification

%-12.5einitial %character width and

precision

conversionspecifier

alignment flag

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...

Page 94: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

94

Intro MATLAB

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

Page 95: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

95

Intro MATLAB

Binary File I/O• [data, count] = fread(fid, num, precision);

• count = fwrite(fid, data, precision);

Dataarray

Numbersuccessfully

read

Fileidentifiernumber

Amount to read n, [n, m],...

‘int’, ‘double’, …

array towrite

Numbersuccessfully

written

Fileidentifiernumber

‘int’, ‘double’, …

fread and fwrite are vectorized

Page 96: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

96

Intro MATLAB

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

Page 97: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

97

Intro MATLAB

File I/O Example

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;endfclose(fid);

Data file MATLAB m-file to read it

MATLAB outputSince 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...)

Page 98: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

98

Intro MATLAB

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);

%s (string) format specifier can be used here with cell array

%s (string) format specifier can be used here with cell array

curly braces are cell array constructors

curly braces are cell array constructors

Page 99: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

99

Intro MATLAB

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

Page 100: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

100

Intro MATLAB

uigetfile: Interactively Get a Filename

• [filename, pathname, filterindex] = uigetfile(‘Filterspec’, ‘DialogTitle’);

Example:>> f = uigetfile('*.jpg;*.bmp;*.gif;*.tif','Specify Graphics File:')

Page 101: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

101

Intro MATLAB

• 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’

Structures

Page 102: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

102

Intro MATLAB

• 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’)

Manipulating Structures

Page 103: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

103

Intro MATLAB

• Consider the simple structure

>> exam.name = ‘Jim Kirk’;

>> exam.score = 79;

>> exam(2).name = ‘Janice Lester’;

>> exam(2).score = 89;

>> [exam.score]

ans =

79 89

Manipulating Structures (cont.)

square brackets produce a numeric row vector

square brackets produce a numeric row vector

Page 104: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

104

Intro MATLAB

Manipulating Structures (cont.)• Can also create a cell array using curly braces:

>> {exam.name}

ans =

'Jim Kirk' 'Janice Lester'

Page 105: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

105

Intro MATLAB

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 …)

Page 106: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

106

Intro MATLAB

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.

Page 107: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Basic Data Analysis

Page 108: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

108

Intro MATLAB

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.

Page 109: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

109

Intro MATLAB

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.

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.

Page 110: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

110

Intro MATLAB

Plotting the Data

Note that in this case the plot command generates one time-series for each column of the data matrix

Note that in this case the plot command generates one time-series for each column of the data matrix

>> plot(rpm_raw)>> xlabel('sample number - during time slice');>> ylabel('Unfiltered RPM Data');>> title(‘3 sequences of samples from RPM sensor’)

Page 111: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

111

Intro MATLAB

Average of the Data:

Applying the mean function to the data matrix yields the mean of each column

Applying the mean function to the data matrix yields the mean of each column

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).

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).

1

2

>> mean(rpm_raw)

ans = 1081.4 1082.8 1002.7

>> mean(mean(rpm_raw))

ans = 1055.6

Page 112: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

112

Intro MATLAB

The mean Function

But we can apply the mean function along any dimension

But we can apply the mean function along any dimension

So we can easily obtain the row means

So we can easily obtain the row means

3

>> 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 [1.5 2.5 3.5] and mean(X,2) is [1 4]>> mean(rpm_raw, 2)

ans = 1045.7 1064.7 1060.7 1055 1045

Page 113: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

113

Intro MATLAB

max and its Index

We can compute the max of the entire matrix, or of any dimension

We can compute the max of the entire matrix, or of any dimension

1 2 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 = 1115 1120 1043

>> max(max(rpm_raw))ans = 1120

>> [y,i] = max(rpm_raw)y = 1115 1120 1043i = 8 2 17

max along the columnsmax along the columns

Page 114: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

114

Intro MATLAB

min

>> min(rpm_raw)ans = 1053 1053 961

>> min(min(rpm_raw))ans = 961

>> [y,i] = min(rpm_raw)y = 1053 1053 961i = 22 1 22

min along each columnmin along each column

min of entire matrixmin of entire matrix

Page 115: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

115

Intro MATLAB

Standard Deviation, Median, Covariance>> median(rpm_raw) % median along each columnans = 1080 1083.5 1004>> cov(rpm_raw) % covariance of the dataans = 306.4 -34.76 32.192 -34.76 244.9 -165.21 32.192 -165.21 356.25>> std(rpm_raw) % standard deviation along each columnans = 17.504 15.649 18.875>> var(rpm_raw) % variance is the square of stdans = 306.4 244.9 356.25

Page 116: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

116

Intro MATLAB

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.

. . .

Page 117: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

117

Intro MATLAB

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

Page 118: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

118

Intro MATLAB

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

Page 119: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

119

Intro MATLAB

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

Page 120: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

120

Intro MATLAB

Data Analysis: Sorting

1

2

3

>> 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

Page 121: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

121

Intro MATLAB

Sorting Data (cont.)

1

>> magic(4)ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

>> sort(magic(4))ans = 4 2 3 1 5 7 6 8 9 11 10 12 16 14 15 13

Page 122: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

122

Intro MATLAB

Sorting Data (cont.)

2

>> magic(4) >> sort(magic(4),2)ans = ans = 16 2 3 13 2 3 13 16

5 11 10 8 5 8 10 11 9 7 6 12 6 7 9 12 4 14 15 1 1 4 14 15

>> sort(magic(4),1)ans = 4 2 3 1 5 7 6 8 9 11 10 12 16 14 15 13

Page 123: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

123

Intro MATLAB

Sorting Data (cont.)

3

>> magic(4)ans = 16 2 3 13 5 11 10 8 9 7 6 12 4 14 15 1

>> [y i] = sort(magic(4))y = i = 4 2 3 1 4 1 1 4 5 7 6 8 2 3 3 2 9 11 10 12 3 2 2 3 16 14 15 13 1 4 4 1

Page 124: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

124

Intro MATLAB

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 = 359 351 335.67 719 724.33 667 1088.3 1081.7 1001 1084 1091.7 1004.7 1081 1073 1006.7

This example uses an FIR filter to compute a moving average using a window size of 3

This example uses an FIR filter to compute a moving average using a window size of 3

Page 125: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

125

Intro MATLAB

Filtered Data Plot

Page 126: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

126

Intro MATLAB

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

Page 127: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

127

Intro MATLAB

Discrete Fourier Transform Definition

21

0

21

0

[ ] [ ]

1[ ] [ ]

j knNN

n

j knNN

k

X k x n e

x n X k eN

Page 128: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

128

Intro MATLAB

fft and fftshift

0 2

N=11

-

1 11

0

N=11

After fftshift

Page 129: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

129

Intro MATLAB

Example: FFT of sine Wave in Noise

>> fs = 1000;>> 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)');

Page 130: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

130

Intro MATLAB

Frequency Spectrum

Page 131: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

131

Intro MATLAB

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.

Page 132: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

132

Intro MATLAB

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 1000 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);

Page 133: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

133

Intro MATLAB

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.

Page 134: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Numerical Analysis

Page 135: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

135

Intro MATLAB

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

Page 136: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

136

Intro MATLAB

• Fundamental data type in MATLAB is a double precision value in ANSI/IEEE Standard 754 format:

• Roundoff: eps = 2-52 ≈ 10-16

• Underflow: realmin = 2-1022 ≈ 10-308

• Overflow: realmax = (2 - eps) * 21023 ≈ 10308

• eps, realmin and realmax are built in variables in MATLAB.

IEEE Double Precision Numbers

s

s E (11 bits) f (52 bits)

A numeric value is represented as: (-1)s (1.f) 2 (E-1023)

Page 137: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

137

Intro MATLAB

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

Existence of solution

Uniqueness of solution

Uniqueness of solution

Page 138: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

138

Intro MATLAB

Linear Equations, n = m

• 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.

>> A = [1 2 3; 4 5 6; 7 8 0]A = 1 2 3 4 5 6 7 8 0>> b = [366; 804; 351]b = 366 804 351>> [rank(A) rank([A b])]ans = 3 3>> x = A\bx = 25 22 99

Page 139: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

139

Intro MATLAB

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\bx = 8 0 -3>> x1 = pinv(A)*bx1 = 7.1667 1.6667 -3.8333>> sqrt([sum(x.^2) sum(x1.^2)])ans = 8.544 8.2966

Page 140: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

140

Intro MATLAB

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.

Page 141: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

141

Intro MATLAB

Example (cont.)

• This leads to the underdetermined set of equations

1 10

,

19 / 2 17 / 2 15/ 2 1/ 2,

1 1 1 1

1,

0T

Ax b

A

x x x b

Page 142: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

142

Intro MATLAB

Example (cont.)

>> x1 = A\bx1 = 0.11111 0 0 0 0 0 0 0 0 -0.11111

>> x2 = pinv(A) * b

x2 = 0.054545 0.042424 0.030303 0.018182 0.0060606 -0.0060606 -0.018182 -0.030303 -0.042424 -0.054545

>> [norm(x1) norm(x2)]ans = 0.15713 0.1101

Page 143: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

143

Intro MATLAB

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 = 2 3>> x = A\bx = -0.094595 2.4459

Page 144: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

144

Intro MATLAB

Example: Fit Polynomial to Data

Assume e is measurement noise, and that we have nmeasurements of x and y. This leads to an overdeterminedset of equations:

Assume we can model data as

0 1p

py a a x a x e

1 1 0 11

1

p

pn n p n

x x a y

x x a y

Page 145: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

145

Intro MATLAB

Example (cont.)

3 2ˆ 1.64 5.3 7.69 3y x x x

Page 146: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

146

Intro MATLAB

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; 1 1.01]>> b = [2; 2.01];>> x = A\bx = 1 1>> A1 = [1 1.005; 1 1.01];>> x1 = A1\bx1 = -0.01 2>> cond(A)ans = 402.01

Page 147: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

147

Intro MATLAB

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; -1 2 1];

>> [L, U] = lu(A)L = 1 0 0 1 -0.5 1 -1 1 0U = 1 2 -1 0 4 0 0 0 2>> L * Uans = 1 2 -1 1 0 1 -1 2 1

Page 148: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

148

Intro MATLAB

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'*AB = 41 -7 -7 3>> R = chol(B)R = 6.4031 -1.0932 0 1.3435>> R'*Rans = 41 -7 -7 3

Page 149: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

149

Intro MATLAB

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; 0 0 -2];>> [V, D] = eig(A)V = 1 1 -0.10483 0 0 -0.31449 0 0 0.94346D = 1 0 0 0 1 0 0 0 -2>> [A*V(:,3) D(3,3)*V(:,3)]ans = 0.20966 0.20966 0.62897 0.62897 -1.8869 -1.8869

Page 150: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

150

Intro MATLAB

Singular Value Decomposition: svdsvd: 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 = -0.32993 0.47852 -0.81373 -0.12445 -0.87653 -0.46499 -0.93577 -0.052149 0.34874S = 6.4999 0 0 1.3235 0 0V = -0.98447 -0.17558 0.17558 -0.98447

Page 151: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

151

Intro MATLAB

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 = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514>> A*B*Aans = 2 -1 1 1 6 -1>> B*A*Bans = -0.013514 0.13514 0.14865 -0.36486 0.64865 0.013514

Page 152: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

152

Intro MATLAB

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

Page 153: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

153

Intro MATLAB

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.

Page 154: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

154

Intro MATLAB

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);

Timeindex

Solutionmatrix

ODEsolver

ODE filefor

derivatives

Solutiontime span

[t0 tf]

Initialconditions

Page 155: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

155

Intro MATLAB

ODE Suite Solvers

• 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

Non-stiff equations Stiff equations

Page 156: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

156

Intro MATLAB

Example : van der Pol Equation

• 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

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

Page 157: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

157

Intro MATLAB

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

Page 158: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

158

Intro MATLAB

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.

Page 159: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

159

Intro MATLAB

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

Page 160: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

160

Intro MATLAB

Integration Example: humps Function

>> x = linspace(-1,2,150);>> y = humps(x);>> plot(x,y)>> format long>> trapz(x,y) % 5-digit accuracyans = 26.344859225225534

>> quad('humps', -1, 2) % 6-digit accuracyans = 26.344960501201232

>> quadl('humps', -1, 2) % 8-digit accuracyans = 26.344960471378968

Page 161: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

161

Intro MATLAB

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

Page 162: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

162

Intro MATLAB

Example of Polynomial Roots

p(x)=x3+4x2-7x-10

Page 163: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

163

Intro MATLAB

Example of Roots for Nonlinear Functions

Page 164: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

164

Intro MATLAB

Example of Function Minimization

>> p = [1 0 -2 -5];>> 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)ans = -6.0887

Page 165: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

165

Intro MATLAB

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

Page 166: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

166

Intro MATLAB

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?

Page 167: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Graphics, Data Visualization & Movies

Page 168: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

168

Intro MATLAB

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

Page 169: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

169

Intro MATLAB

Basic XY Plot

>> x = [0:pi/100:pi];

>> y = sin(x);

>> plot(x,y), title('Simple Plot')

Page 170: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

170

Intro MATLAB

Multiple Curve Plots

Line color, style, marker type, all within single quotes

Line color, style, marker type, all within single quotes

>> z = cos(x);

>> plot(x,y,'g.',x,z,'b-.'), title('More Complicated')

Page 171: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

171

Intro MATLAB

Plot Power: Contour & 3-D Mesh

To save:

print -djpeg myfigure.jpg

use help print for options

To save:

print -djpeg myfigure.jpg

use help print for options

>> 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!}')

Page 172: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

172

Intro MATLAB

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-.')>> axis([-Inf,Inf,-Inf,Inf])

4 5 6

2

31

Page 173: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

173

Intro MATLAB

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

>> figure(2);>> [X,Y] = meshgrid(-16:1.0:16);>> Z = sqrt(X.^2 + Y.^2 + 5000);>> mesh(Z)

•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:

Page 174: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

174

Intro MATLAB

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.^2 + 5000);>> surf(Z)

>> shading flat

>> shading interp

Default: shading faceted

Page 175: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

175

Intro MATLAB

Surface Plots: Colormaps

>> colormap hot

>> colormap gray

>> colormap cool

>> colormap pink

Page 176: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

176

Intro MATLAB

More Surface Plots

>> meshc(Z)

>> meshz(Z)

>> surfl(Z)

>> pcolor(Z)

Page 177: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

177

Intro MATLAB

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

Vertex 1 0 0 0Vertex 2 1 0 0Vertex 3 1 1 0Vertex 4 0 1 0Vertex 5 0.25 0.25 1Vertex 6 0.75 0.25 1Vertex 7 0.75 0.75 1Vertex 8 0.25 0.75 1

Face 1 1 2 3 4Face 2 5 6 7 8Face 3 1 2 6 5Face 4 2 3 7 6Face 5 3 4 8 7Face 6 4 1 5 8

Vertices, v Faces, f

Page 178: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

178

Intro MATLAB

Patches: MATLAB code>> v = [0 0 0; 1 0 0 ; 1 1 0; 0 1 0; 0.25 0.25 1; 0.75 0.25 1;

0.75 0.75 1; 0.25 0.75 1];>> f = [1 2 3 4; 5 6 7 8; 1 2 6 5; 2 3 7 6; 3 4 8 7; 4 1 5 8];>> % 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’)>> view(3)>> axis square>> grid on

Page 179: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

179

Intro MATLAB

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)>>

Page 180: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

180

Intro MATLAB

More Contour Plots

>> Z = peaks;>> [C, h] = contour(Z, 10);>> clabel(C, h);>> title('Labeled Contour')

>> Z = peaks;>> [C, h] = contourf(Z, 10);>> title('Filled Contour')>>

Page 181: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

181

Intro MATLAB

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')

Page 182: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

182

Intro MATLAB

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);

Page 183: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

183

Intro MATLAB

Visualization: Viewpoint• Use view to specify the viewpoint by defining azimuth and elevation with

respect to the origin

x

-y

z

Azimuth

Elevation

y

• MATLAB defaults– For 2-D plots, azimuth = 0o elevation = 90o

– For 3-D plots, azimuth = -37.5o elevation = 30o

Default View >> view(-37.5, 60);

>> view(0, 90); >> view(-37.5, 90);

Page 184: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

184

Intro MATLAB

Visualization: Camera Properties

>> set(gca,'CameraPosition',[-800,-800,13])Default View

>> set(gca,'CameraTarget',[0,0,2])

>> set(gca,'CameraUpVector',[0,1,0])

>> set(gca,'CameraViewAngle',30) >> set(gca,'Projection','perspective')

• Use the set command to modify parameters associated with a graphics object. In this case, the Camera Properties

Page 185: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

185

Intro MATLAB

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

Page 186: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

186

Intro MATLAB

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 colormapR G B

0

1 0

C

12

m

10

I

0.5 0.5 0.5

1 0.35 0.25

10

1

1 0

Page 187: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

187

Intro MATLAB

Intensity Images• 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);

Page 188: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

188

Intro MATLAB

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(:, :, 1)

HumVee(:, :, 2)

HumVee(:, :, 3)

Page 189: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

189

Intro MATLAB

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);

Page 190: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

190

Intro MATLAB

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

Page 191: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

191

Intro MATLAB

MATLAB Code for Reading Images

>> Crusader = imread(’Crusader.jpg');

>> image(Crusader)

>> whos Crusader

Name Size Bytes Class

Crusader 186x250x3 139500 uint8 array

Grand total is 139500 elements using 139500 bytes

Page 192: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

192

Intro MATLAB

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

Page 193: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

193

Intro MATLAB

Writing Images: MATLAB code>> Abrams = imread(‘Abrams.jpg');

>> image(Abrams)

>> whos Abrams

Name Size Bytes Class

Abrams 511x640x3 981120 uint8 array

Grand total is 981120 elements using 981120 bytes

>> % Write out tank as gray image

>> AbramsGray = rgb2gray(Abrams);

>> colormap gray;

>> image(AbramsGray)

>> imwrite(AbramsGray, gray, 'Abrams.bmp');

Page 194: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

194

Intro MATLAB

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.

Page 195: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

195

Intro MATLAB

Movie Preparation & Play

Page 196: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

196

Intro MATLAB

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.

Page 197: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

197

Intro MATLAB

figure(1)numframes=16;

% gca: “get current axis”; returns handle to the% current axes for the current figureset(gca, ‘NextPlot', 'replacechildren')axis equal % fix the axes for k=1:numframes plot(fft(eye(k+16))); % eye: Identity matrix A(k)=getframe;endmovie(A)

Example that Illustrates the Use of Movies to Visualize the Various Powers of the N-th Root of

Unity, exp(2pi / n)

Page 198: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

198

Intro MATLAB

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

Page 199: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

199

Intro MATLAB

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.

Page 200: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

Inter-Language Programming

Page 201: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

201

Intro MATLAB

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

Page 202: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

202

Intro MATLAB

MEX ProcedureProcedures for working with MATLAB’s MEX mechanism

1. Prepare the C or Fortran MEX program according to MATLAB external interfacing rules

2. Compile the C or FORTRAN MEX program using MATLAB command “mex”

3. mex in turn makes use of external C or FORTRAN compilers

4. Call the compiled MEX function in the same way as calling any MATLAB function

Page 203: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

203

Intro MATLAB

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

Page 204: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

204

Intro MATLAB

Gateway Function : mexFunction()

void mexFunction (int nlhs,

mxArray *plhs[],

int nrhs,

const mxArray *prhs[])

• Equivalent to main() in C programs

• Has 4 arguments

Number of LHS arguments

Number of RHS arguments

Pointer to array of of LHS argument

pointers

Pointer to array of of RHS argument

pointers

Page 205: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

205

Intro MATLAB

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);

Page 206: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

206

Intro MATLAB

mexFunction in Scaling Example

>> a = timestwo(x)

nrhs = 1

prhs x (matrix)

nlhs = 1

plhs a

void mexFunction( int nlhs, mxArray *plhs[],int nrhs, const mxArray *prhs[])

In MATLAB:

In timestwo.c:

Page 207: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

207

Intro MATLAB

MEX Procedure1. Compile timestwo.c using “mex” command in MATLAB

2. Use timestwo.mexw32 like any MATLAB command

>> mex timestwo.c>> dir *.mexw32

timestwo.mexw32

Compiling mex program, timestwo.c

A platform-specific binary is generated after compiling

>> [a b] = timestwo(5,6)a = 10b = 12

Page 208: MATLAB for Engineering Applications Ashok Krishnamurthy Siddharth Samsi Ohio Supercomputer Center 1224 Kinnear Road Columbus, OH 43212

208

Intro MATLAB

timestwo.cinclude “mex.h”

Gateway function and

its 4 arguments

Processing the input

parameters

Dynamically allocate

memory for the output

array

#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];

}

}

}