Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

MATLAB For Engineering Applications

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 208

MATLAB for Engineering Applications

Ashok Krishnamurthy
Siddharth Samsi
Ohio Supercomputer Center
1224 Kinnear Road
Columbus, OH 43212
http://www.osc.edu/
Table of Contents – Day One

• Overview
• Basic Interfaces
• Arrays, Matrices, Operators
• Programming
• Data I/O

Intro MATLAB

2
Table of Contents – Day Two

• Basic Data Analysis


• Numerical Analysis
• Graphics, Data Visualization, Movies
• Inter-language Programming

Intro MATLAB

3
Overview
MATLAB
• “MATrix LABoratory”

• Powerful, extensible, highly integrated


computation, programming, visualization, and
simulation package

• Widely used in engineering, mathematics, and


science

• Why?

Intro MATLAB

5
MATLAB’s Appeal

• Interactive code development proceeds


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

Intro MATLAB

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

Intro MATLAB

7
Toolboxes, Software, & Links

Intro MATLAB

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

Intro MATLAB

9
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

Intro MATLAB

10
References

Mastering MATLAB 7, D. Hanselman and B. Littlefield,


Prentice Hall, 2004

Getting Started with MATLAB 7: A Quick Introduction


for Scientists and Engineers, R. Pratap, Oxford University
Press, 2005.

Intro MATLAB

11
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

Intro MATLAB

12
Basic Interfaces
Main MATLAB Interface

Intro MATLAB

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

Intro MATLAB

15
MATLAB Editor Window

Intro MATLAB

16
MATLAB Help Window (Very Powerful)

Intro MATLAB

17
Command-Line Help : List of MATLAB Topics
>> help
HELP topics:

matlab\general - General purpose commands.


matlab\ops - Operators and special characters.
matlab\lang - Programming language constructs.
matlab\elmat - Elementary matrices and matrix manipulation.
matlab\elfun - Elementary math functions.
matlab\specfun - Specialized math functions.
matlab\matfun - Matrix functions - numerical linear algebra.
matlab\datafun - Data analysis and Fourier transforms.
matlab\polyfun - Interpolation and polynomials.
matlab\funfun - Function functions and ODE solvers.
matlab\sparfun - Sparse matrices.
matlab\scribe - Annotation and Plot Editing.
matlab\graph2d - Two dimensional graphs.
matlab\graph3d - Three dimensional graphs.
matlab\specgraph - Specialized graphs.
matlab\graphics - Handle Graphics.
…etc...

Intro MATLAB

18
Command-Line Help : List of Topic Functions
>> help matfun
Matrix functions - numerical linear algebra.

Matrix analysis.
norm - Matrix or vector norm.
normest - Estimate the matrix 2-norm.
rank - Matrix rank.
det - Determinant.
trace - Sum of diagonal elements.
null - Null space.
orth - Orthogonalization.
rref - Reduced row echelon form.
subspace - Angle between two subspaces.

Intro MATLAB

19
Command-Line Help : Function Help
>> help det
DET Determinant.
DET(X) is the determinant of the square matrix X.

Use COND instead of DET to test for matrix


singularity.

See also cond.

Overloaded functions or methods (ones with the same


name in other directories)
help laurmat/det.m

Reference page in Help browser


doc det

Intro MATLAB

20
Keyword Search of Help Entries
>> lookfor who
newton.m: % inputs: 'x' is the number whose
square root we seek
testNewton.m: % inputs: 'x' is the number whose
square root we seek
WHO List current variables.
WHOS List current variables, long form.
TIMESTWO S-function whose output is two times its
input.

>> whos
Name Size Bytes Class Attributes
ans 1x1 8 double
fid 1x1 8 double
i 1x1 8 double

Intro MATLAB

21
startup.m
• Customize MATLAB’s start-up behavior
• Create startup.m file and place in:

– Windows: $matlabroot\work
– UNIX: directory where matlab command is issued

My startup.m file:

addpath e:\download\MatlabMPI\src
addpath e:\download\MatlabMPI\examples
addpath .\MatMPI
format short g
format compact eliminates
eliminatesextra
extrablank
blanklines
linesin
inoutput
output

Intro MATLAB

22
Variables (Arrays) and Operators
Variable Basics
>> 16 + 24 no
nodeclarations
declarationsneeded
needed
ans =
40

>> product = 16 * 23.24 mixed


mixeddata
datatypes
types
product =
371.84
semi-colon
semi-colonsuppresses
suppressesoutput
outputof
of
>> product = 16 *555.24; the
thecalculation’s
calculation’sresult
result
>> product
product =
8883.8

Intro MATLAB

24
Variable Basics
>> clear
clearremoves
clear removesall allvariables;
variables;
>> product = 2 * 3^3;
clear xx yyremoves
>> comp_sum = (2 + 3i) + (2 - 3i); clear removesonly
onlyxxand
andyy
>> show_i = i^2;
complex
complexnumbers
numbers(i (ior j)require
orj) require
>> save three_things
no
nospecial
specialhandling
handling
>> clear
>> load three_things
>> who
Your variables are: save/loadare
save/load areused
usedtoto
comp_sum product show_i retain/restore
retain/restoreworkspace
workspacevariables
variables
>> product
product =
54
>> show_i use hometotoclear
usehome clearscreen
screenandandput
put
show_i = cursor
cursoratatthe
thetop
topofofthe
thescreen
screen
-1

Intro MATLAB

25
MATLAB Data

The basic data type used in MATLAB is the double precision array

• No declarations needed: MATLAB automatically allocates required memory

• Resize arrays dynamically

• To reuse a variable name, simply use it in the left hand side


of an assignment statement

• MATLAB displays results in scientific notation


o Use File/Preferences and/or format function to change default
 short (5 digits), long (16 digits)
 format short g; format compact (my preference)

Intro MATLAB

26
Variables Revisited
• Variable names are case sensitive and over-written when re-used

• Basic variable class: Auto-Indexed Array


– Allows use of entire arrays (scalar, 1-D, 2-D, etc…) as
operands
– Vectorization: Always use array operands to get best
performance (see next slide)

• Terminology: “scalar” (1 x 1 array), “vector” (1 x N array), “matrix”


(M x N array)

• Special variables/functions: ans, pi, eps, inf, NaN, i,


nargin, nargout, varargin, varargout, ...

• Commands who (terse output) and whos (verbose output) show


variables in Workspace

Intro MATLAB

27
Vectorization Example*

>> type slow.m >> type fast.m


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

Intro MATLAB

28
Matrices: Magic Squares

This
Thismatrix
matrixisiscalled
calledaa
“magic
“magicsquare”
square”

Interestingly,
Interestingly,
Durer
Dureralso
alsodated
dated
this
thisengraving
engravingby by
placing 15 and 14
placing 15 and 14
side-by-side
side-by-sideinin
the magic square.
the magic square.

Intro MATLAB

29
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

Intro MATLAB

30
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

Intro MATLAB

31
Multidimensional Arrays
>> r = randn(2,3,4) % create a 3 dimensional array filled with
normally distributed random numbers
r(:,:,1) = “%”
“%”sign
signprecedes
precedescomments,
comments,MATLAB
MATLAB
-0.6918 1.2540 -1.4410 ignores
ignoresthe
therest
restofofthe
theline
line
0.8580 -1.5937 0.5711
r(:,:,2) =
randn(2,3,4):33dimensions,
randn(2,3,4): dimensions,filled
filledwith
with
-0.3999 0.8156 1.2902 normally
normallydistributed
distributedrandom
randomnumbers
numbers
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

Intro MATLAB

32
Character Strings

>> hi = ' hello';


>> class = 'MATLAB';
>> hi
hi =
hello
>> class
class =
MATLAB
>> greetings = [hi class] concatenation
concatenationwith
withblank
blankor
orwith
with“,”
“,”
greetings =
helloMATLAB
>> vgreetings = [hi;class] semi-colon:
semi-colon:join
joinvertically
vertically
vgreetings =
hello
MATLAB

Intro MATLAB

33
Character Strings as Arrays
>> greetings
greetings =
helloMATLAB
>> vgreetings = [hi;class]
vgreetings =
hello
MATLAB
note
notedeleted
deletedspace
spaceatat
>> hi = 'hello'
beginning
beginningofofword;
word;
hi = results
resultsininerror
error
hello
>> vgreetings = [hi;class]
??? Error using ==> vertcat
CAT arguments dimensions are not consistent.

Intro MATLAB

34
String Functions
yo =
Hello
Class

>> ischar(yo)
ans = returns
returns11ififargument
argumentisisaacharacter
character
1 array
arrayand
and00otherwise
otherwise

>> strcmp(yo,yo)
ans =
1
returns
returns11ififstring
stringarguments
argumentsare
arethe
the
same
sameand
and00otherwise; strcmpiignores
otherwise;strcmpi ignorescase
case

Intro MATLAB

35
Set Functions
Arrays are ordered sets:

>> a = [1 2 3 4 5]
a =
1 2 3 4 5
>> b = [3 4 5 6 7]
b =
3 4 5 6 7
returns
returnstrue
true(1)
(1)ififarrays
arraysare
arethe
thesame
same
>> isequal(a,b) size
sizeand
andhave
havethe
thesame
samevalues
values
ans =
0 returns
returns11where
whereaaisisininbb
>> ismember(a,b) and
and00otherwise
otherwise
ans =
0 0 1 1 1

Intro MATLAB

36
Matrix Operations
>> durer = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]

durer = MATLAB
MATLABalso
alsohas
has
16 3 2 13 magic(N)
magic(N) (N (N >> 2)
2)
5 10 11 8 function
function
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

Intro MATLAB

37
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

Intro MATLAB

38
Diagonal Elements
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> diag(durer) % diag plucks out the diagonal elements


ans =
16
10
7
1

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

Intro MATLAB

39
The Other Diagonal…
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> fliplr(durer) % “flip left-right”


ans =
13 2 3 16
8 11 10 5
12 7 6 9
1 14 15 4
>> sum(diag(fliplr(durer)))
ans =
34

Intro MATLAB

40
Matrix Subscripting
>> durer
durer =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1

>> diag_sum = durer(1,1) + durer(2,2) + durer(3,3)


diag_sum =
33
>> durer(4,4) = pi
durer =
16.0000 3.0000 2.0000 13.0000
5.0000 10.0000 11.0000 8.0000
9.0000 6.0000 7.0000 12.0000
4.0000 15.0000 14.0000 3.1416

>> durer(4,4) = 1

Intro MATLAB

41
Colon Operator (Vector Creation)

>> 1:5 % use the colon operator to create row vectors


ans =
1 2 3 4 5

>> 1:0.9:6 % you can vary the increment (0.9 in this


case)
ans =
1.0000 1.9000 2.8000 3.7000 4.6000
5.5000

The last element is always less than or equal to the upper


limit

Intro MATLAB

42
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

Intro MATLAB

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

Intro MATLAB

44
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

Intro MATLAB

45
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

Intro MATLAB

46
Two Division Operators
• Right divide (familiar version) a/b
– What happens: a is divided by b
– Right operand “goes into” left operand
• Left divide a\b
– What happens: b is divided by a
– Left operand “goes into” right operand
– Behavior depends on operands (scalar vs. matrix)

• Both operators work with matrices (of course). More


later on what is actually calculated …
• Comparison of the use of / and \ on next slide

Intro MATLAB

47
Using the Division Operators
>> x = 53.0;
>> y = 22.5;

>> x/y

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

Intro MATLAB

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

Intro MATLAB

49
Adding Another Curve
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'),title('More complicated')

Line
Linecolor,
color,style,
style,marker
markertype,
type,
all
allwithin
withinsingle
singlequotes;
quotes;type
type
>>
>> doc
doc LineSpec
LineSpec
for
forall
allavailable
availableline
lineproperties
properties

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

52
Programming
Outline

• MATLAB m-file Editor


– To start: click icon or enter edit command in
Command Window, e.g., >> edit test.m
• Scripts and Functions
• Decision Making/Looping
– if/else
– switch
– for and while
• Running Operating System Commands

Intro MATLAB

54
m-file Editor Window

You
Youcancansave
saveand
andrun
runthe
the
file/function/script
file/function/scriptininone
one
step by clicking here
step by clicking here

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

Intro MATLAB

55
Scripts and Functions

• Scripts do not accept input arguments, nor do they


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

Intro MATLAB

56
Functions – First Example
function [a b c] = myfun(x, y) Write
Writethese
thesetwo
twolines
linesto
toaafile
filemyfun.m
myfun.m
b = x * y; a = 100; c = x.^2; and
andsave
saveititon
onMATLAB’s
MATLAB’spath path
>> myfun(2,3) % called with zero outputs
ans =
100
>> u = myfun(2,3) % called with one output
u =
100
>> [u v w] = myfun(2,3) % called with all outputs
u =
100
v = Any
Anyreturn
returnvalue
valuewhich
whichisisnot
notstored
storedin
in
6 an
anoutput
outputvariable
variableis
issimply
simplydiscarded
discarded
w =
4

Intro MATLAB

57
Example: deLaunay Triangulation
• Have a set of random (x,y) points and want to connect
them together to make a triangular grid

• The deLaunay algorithm creates a set of triangles such


that no (other) data points are contained within the area
or perimeter of any given triangle.
– Creates an “orthogonal” set of triangles
– The resulting grid is useful as a coordinate system

• Used in scatter pattern analysis:


– Position of debris resulting from an explosion
– Establish properties of the explosion: its original location,
strength, parts specifications, …

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

61
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 H1 (help 1) line displayed
% angle between b and c when using lookfor
% 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

Intro MATLAB

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

Intro MATLAB

63
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

Intro MATLAB

64
Getting ortho Function Help
>> help ortho
ortho function input: Three vectors each with 3 elements
The output is a 3-element array containing the angles
between each pair of input vectors. The output
elements are respectively:
angle between a and b
angle between b and c
angle between a and c
Typical use or ortho is to determine if a,b,c form an
orthogonal basis set that spans 3-D space.

>> help sin


SIN Sine.
SIN(X) is the sine of the elements of X.

See also asin, sind.

Intro MATLAB

65
Function Syntax Summary
• If the m-file name and function name differ, the file name
takes precedence

• Function names must begin with a letter

• First line must contain function followed by the most


general calling syntax

• Statements after initial contiguous comments (help lines) are


the body of the function

• Terminates on the last line or a return statement

Intro MATLAB

66
Function Syntax Summary (cont.)
• error and warning can be used to test and continue
execution (error-handling)

• Scripts called in m-file functions are evaluated in the


function workspace

• Additional functions (subfunctions) can be included in an


m-file

• Use which command to determine precedence, e.g.,

>> which title


C:\MATLAB71\toolbox\matlab\graph2d\title

Intro MATLAB

67
Variable Argument Lists

• varargin / varargout allow variable numbers of


input / output function arguments

• Used only inside function m-files

• Must be declared as the last input / output argument

• Declarations must be typed in lowercase

Intro MATLAB

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

Intro MATLAB

69
Variable Argument Lists (cont.)
• Consider the m-file:
function [s, varargout] = mysize(x)
nout = max(nargout,1) - 1; nargout:number
nargout: numberofofoutput
output
s = size(x); arguments
argumentsininfunction
functioncall
call
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
packall
alloutput
outputvalues
values
into varargoutcell
intovarargout cellarray
array

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

72
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

Intro MATLAB

73
while Loop

>> b = 4; a = 2.1; count = 0;


>> while b - a > 0.01
a = a + 0.001;
count = count + 1;
end
>> count
count =
1891

Intro MATLAB

74
A Performance Tip
Input variables are not copied into the function
workspace, unless

– If any input variables are changed, the variable will


be copied

– Avoid performance penalty when using large arrays


by extracting only those elements that will need
modification

Intro MATLAB

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

Intro MATLAB

76
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.
>> path >> addpath('c:\');
>> matlabpath
MATLABPATH
MATLABPATH
E:\MATLAB\R2006b\work c:\
E:\MATLAB\R2006b\work\f_funcs E:\MATLAB\R2006b\work
E:\MATLAB\R2006b\work\na_funcs E:\MATLAB\R2006b\work\f_funcs
E:\MATLAB\R2006b\work\na_scripts E:\MATLAB\R2006b\work\na_funcs
E:\MATLAB\R2006b\toolbox\matlab\general E:\MATLAB\R2006b\work\na_scripts
E:\MATLAB\R2006b\toolbox\matlab\ops E:\MATLAB\R2006b\toolbox\matlab\general
E:\MATLAB\R2006b\toolbox\matlab\ops

• rmpath is used to remove paths from the search path

Intro MATLAB

77
Common OS Commands
• ls / dir provide a directory listing of the current directory
>> ls

. .. sample.m

>>

• pwd shows the current directory


>> pwd
ans =
e:\Program Files\MATLAB\R2006b\work
>>

Intro MATLAB

78
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

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

81
Data I/O
Loading and Saving Workspace Variables
• MATLAB can load and save data in .MAT format

• .MAT files are binary files that can be transferred across platforms;
as much accuracy as possible is preserved.

• Load: load filename OR A = load(‘filename’)


loads all the variables in the specified file (the default name is
MATLAB.MAT)

• Save: save filename variables


saves the specified variables (all variables by default) in the
specified file (the default name is MATLAB.MAT)

Intro MATLAB

83
ASCII File Read/Write
load and save can also read and write ASCII files with
rows of space separated values:

• load test.dat –ascii

• save filename variables


(options are ascii, double, tabs, append)

• save example.dat myvar1 myvar2 -ascii -double

Intro MATLAB

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

range
rangeofofdata
datatotobe
beread
read
• dlmwrite
dlmwrite(filename,A,delimiter);
writes ASCII values in array A to file filename with values
separated by delimiter

• Useful with spreadsheet data

Intro MATLAB

85
More ASCII File Read
• textread
[A, B, C, ...] = textread[‘filename’, ‘format’];
[A, B, C, ...] = textread[‘filename’, ‘format’, N];
[...] = textread[..., ‘param’, ‘value’, ...];

• The type of each return argument is given by format (C-style


conversion specifiers: %d, %f, %c, %s, etc…)
• Number of return arguments must match number of conversion
specifiers in format
• format string is reused N times or entire file is read if N not given
• Using textread you can
– specify values for whitespace, delimiters and exponent characters
– specify a format string to skip over literals or ignore fields

Intro MATLAB

86
textread Example

• Data file,
tab delimited:

• MATLAB
m-file: ‘param’,’value’ pairs
use doc textread for
available param options
• Results:

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

89
Low-Level File I/O (cont.)
• File Positioning
– feof: Test for end-of-file
– ferror: Query MATLAB about errors in file input
or output
– frewind: Rewind an open file
– fseek: Set file position indicator
– ftell: Get file position indicator

• String Conversion
– sprintf: Write formatted data to a string
– sscanf: Read string under format control

Intro MATLAB

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

Permission
File Name of requested:
identifier file ‘r’, ’r+’
number ‘w’, ’w+’
‘a’, ’a+’
• status = fclose(fid);

0, if successful File identifier number


-1, otherwise or ‘all’ for all files

Intro MATLAB

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

Number File Format Amount of


Data successfully identifier specifier data to read:
array read number n, [n, m], Inf

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

Number File Format Data


successfully identifier specifier array(s) to
read number write

fscanf and fprintf are similar to C version but vectorized

Intro MATLAB

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

Intro MATLAB

93
Other Formatted I/O Commands
• fgetl: line = fgetl(fid);
reads next line from file without line terminator

• fgets: line = fgets(fid);


reads next line from file with line terminator

• textread: [A,B,C,...] = textread('filename','format',N)


reads N lines of formatted text from file filename

• sscanf: A = sscanf(s, format, size);


reads string under format control

• sprintf: s = sprintf(format, A);


writes formatted data to a string

Intro MATLAB

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

Data Number File Amount to read ‘int’, ‘double’, …


array successfully identifier n, [n, m],...
read number

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

Number File array to


successfully identifier ‘int’, ‘double’, …
write
written number

fread and fwrite are vectorized

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

97
File I/O Example (Alternative)
• Cell arrays (storage mechanism for dissimilar kinds of
data) offer a very flexible alternative
• Avoid the nuances and pitfalls of counting spaces and
tabs
• Create a cell array to store the field name by using curly
braces after variable name:

name{i} = fscanf(fid, ‘%s’, 1);

curly
curlybraces
bracesare
arecell
cellarray
array %s(string)
%s (string)format
formatspecifier
specifiercan
can
constructors
constructors be
beused
usedhere
herewith
withcell
cellarray
array

Intro MATLAB

98
Specialized File I/O Commands

• hdf: HDF interface


• imfinfo: Return information about a graphics file
• imread/imwrite: Read/Write image from graphics file
• wk1read/wk1write: Read/Write a Lotus123 WK1
spreadsheet file into a matrix
• xlsread/xlswrite: Read/Write a matrix to a Excel
spreadsheet file
• urlread: read data from a URL

Intro MATLAB

99
uigetfile: Interactively Get a Filename

• [filename, pathname, filterindex] =


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

Intro MATLAB

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

Intro MATLAB

101
Manipulating Structures
• Structures are arrays (no surprise)
• Fields can be added one at a time:

>> class(2).name = ‘MPI’;


>> class(2).day1 = ‘TBA’;
>> class(2).day2 = ‘TBA’;

• Can also use a single statement:

>> class(2) = struct(‘name’,‘MPI’,...


‘day1’,‘TBA’,‘day2’,‘TBA’)

Intro MATLAB

102
Manipulating Structures (cont.)
• Consider the simple structure

>> exam.name = ‘Jim Kirk’;


>> exam.score = 79;
>> exam(2).name = ‘Janice Lester’;
>> exam(2).score = 89;
>> [exam.score]
ans =
square
squarebrackets
bracketsproduce
produceaa
79 89 numeric row vector
numeric row vector

Intro MATLAB

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

>> {exam.name}
ans =
'Jim Kirk' 'Janice Lester'

Intro MATLAB

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

Intro MATLAB

105
Lab 2
• The data file DataIO_lab2.csv is an ASCII data file that consists of comma
separated real values. There are 3000 rows and 16 columns of data. The first
column corresponds to sampling instants and the next 15 columns correspond
to vibration data collected from a shaker table.

• Write a short m-file to read the data in the DataIO_lab2.csv file and assign it
to two variables: t which is a 3000 X 1 array containing the sampling instants
and x which is a 3000 X 15 array containing the data on all the channels. You
can use fscanf (in conjunction with fopen) or dlmread to read the data.

• Plot x(:,1) through x(:,15) against t.

• MATLAB provides another way of reading ASCII data files: textread. Use
textread to read the data in DataIO_lab2.csv and assign it to the
variables t and x.

Intro MATLAB

106
Basic Data Analysis
Basic Data Analysis

• Basic, and more advanced, statistical analysis is


easily accomplished in MATLAB.

• Remember that the MATLAB default is to


assume vectors are columnar.

• Each column is a variable, and each row is an


observation.

Intro MATLAB

108
Vibration Sensors Data

Each
Eachcolumn
columnisisthe
the
raw rpm sensor
raw rpm sensor
data
datafrom
fromaa
different
different sensor
sensor
used
usedininanan
instrumented
instrumented
engine
enginetest.
test.The
The
rows
rows representthe
represent the
times
timesreadings
readings
were
weremade.
made.

Intro MATLAB

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

Note
Notethat
that in
inthis
this
case
casethe
theplot
plot
command
command
generates
generatesoneone
time-series
time-seriesfor
for
each
eachcolumn
columnof of
the
thedata
datamatrix
matrix

Intro MATLAB

110
Average of the Data:
1
Applying >> mean(rpm_raw)
Applyingthe meanfunction
themean function
to
tothe
thedata
datamatrix
matrixyields
yieldsthe
the
mean
meanofofeach
eachcolumn
column ans =
1081.4 1082.8 1002.7
2
But
Butyou
youcan
caneasily
easilycompute
computethe the >> mean(mean(rpm_raw))
mean
meanof ofthe
theentire
entirematrix
matrix
(applying
(applyingaafunction
functiontotoeither
eitheraa
single ans =
singlerow
rowororaasingle
singlecolumn
column
results
resultsin
inthe
thefunction
functionapplied
applied 1055.6
to
tothe
thecolumn,
column,ororthe
therow,
row,i.e.,
i.e.,
in
inboth
bothcases,
cases,the
theapplication
applicationis is
to
tothe
thevector).
vector).

Intro MATLAB

111
The mean Function
>> help mean
MEAN Average or mean value.
For vectors, MEAN(X) is the mean value of the elements in X. For
matrices, MEAN(X) is a row vector containing the mean value of
each column. For N-D arrays, MEAN(X) is the mean value of the
elements along the first non-singleton dimension of X.

MEAN(X,DIM) takes the mean along the dimension DIM of X.


But
Butwe
wecan
canapply
applythe meanfunction
themean function
Example: If X = [0 1 2 along
3 4 5] alongany
anydimension
dimension

then mean(X,1) is [1.5 2.5 3.5] and mean(X,2) is [1


>> mean(rpm_raw, 2) 4]
ans =
1045.7
3
1064.7 So
Sowe
wecan
caneasily
easilyobtain
obtainthe
therow
row
1060.7 means
means
1055
1045

Intro MATLAB

112
max and its Index
1 MAX Largest component. 2
For vectors, MAX(X) is the largest
element in X. For matrices, MAX(X) >> max(rpm_raw)
is a row vector containing the ans =
maximum element from each column. 1115 1120 1043
For N-D arrays, MAX(X) operates along
the first non-singleton dimension.
>> max(max(rpm_raw))
[Y,I] = MAX(X) returns the indices of ans =
the maximum values in vector I. 1120
If the values along the first non-
singleton dimension contain more
>> [y,i] = max(rpm_raw)
than one maximal element, the index
of the first one is returned. y =
1115 1120 1043
We
Wecancancompute
computethethemax
max i =
of
ofthe
theentire
entirematrix,
matrix,or
orof
of 8 2 17
any
anydimension
dimension max
maxalong
alongthe
thecolumns
columns

Intro MATLAB

113
min
>> min(rpm_raw) min
minalong
alongeach
eachcolumn
column
ans =
1053 1053 961

>> min(min(rpm_raw)) min


minofofentire
entirematrix
matrix
ans =
961

>> [y,i] = min(rpm_raw)


y =
1053 1053 961
i =
22 1 22

Intro MATLAB

114
Standard Deviation, Median, Covariance
>> median(rpm_raw) % median along each column
ans =
1080 1083.5 1004
>> cov(rpm_raw) % covariance of the data
ans =
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 column
ans =
17.504 15.649 18.875
>> var(rpm_raw) % variance is the square of std
ans =
306.4 244.9 356.25

Intro MATLAB

115
Data Analysis: Histogram
HIST Histogram.
N = HIST(Y) bins the elements of Y into 10 equally spaced containers
and returns the number of elements in each container. If Y is a
matrix, HIST works down the columns.

N = HIST(Y,M), where M is a scalar, uses M bins.

N = HIST(Y,X), where X is a vector, returns the distribution of Y


among bins with centers specified by X. The first bin includes
data between -inf and the first center and the last bin
includes data between the last bin and inf. Note: Use HISTC if
it is more natural to specify bin edges instead.

...

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

119
Data Analysis: Sorting
>> help sort
SORT Sort in ascending or descending order.
For vectors, SORT(X) sorts the elements of X in ascending order.
For matrices, SORT(X) sorts each column of X in ascending order. 1
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) 2
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. 3


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

Intro MATLAB

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

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

Intro MATLAB

121
Sorting Data (cont.)
>> 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
2
>> sort(magic(4),1)
ans =
4 2 3 1
5 7 6 8
9 11 10 12
16 14 15 13

Intro MATLAB

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

>> [y i] = sort(magic(4)) 3
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

Intro MATLAB

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


This
Thisexample
exampleusesusesan an
ans = FIR
FIRfilter
filtertotocompute
computeaa
359 351 335.67 moving
movingaverage
averageusing
usingaa
719 724.33 667 window
windowsizesizeofof33
1088.3 1081.7 1001
1084 1091.7 1004.7
1081 1073 1006.7

Intro MATLAB

124
Filtered Data Plot

Intro MATLAB

125
Fast Fourier Transform (FFT)

• fft is one of the built-in functions in MATLAB

• The fft function can compute the discrete Fourier


transform of any arbitrary length sequence. fft
incorporates most known fast algorithms for
various lengths (e.g. power of 2)

• Not all lengths are equally fast

Intro MATLAB

126
Discrete Fourier Transform Definition

N 1 j 2 kn

X [k ]   x[n]e N

n 0
N 1 j 2 kn
1
x[n] 
N
 X [k ]e
k 0
N

Intro MATLAB

127
fft and fftshift
1 11
N=11

0  2
After fftshift

N=11

- 0 
Intro MATLAB

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

Intro MATLAB

129
Frequency Spectrum

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

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

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

Intro MATLAB

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

s E (11 bits) f (52 bits)

s
A numeric value is represented as: (-1)s (1.f) 2 (E-1023)
• 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.

Intro MATLAB

136
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
Existence
Existence
• consistent if rank(A) = rank([A b]) ofofsolution
solution
• independent if rank(A) = n Uniqueness
Uniqueness
ofofsolution
solution

Intro MATLAB

137
Linear Equations, n = m
>> A = [1 2 3; 4 5 6; 7 8 0]
• When A is square (i.e., A =
1 2 3
n = m) and the equations
4 5 6
are independent and 7 8 0
consistent, the unique >> b = [366; 804; 351]
b =
solution can be found using 366
the \ operator. 804
351
>> [rank(A) rank([A b])]
• MATLAB finds the solution ans =
3 3
using a LU decomposition >> x = A\b
of A. x =
25
22
99

Intro MATLAB

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

the solution with min ||x||.

Intro MATLAB

139
Example: Force Required to Move Object

Force, F

Unit mass, velocity at time t = 0 is 0. Force on object is F(t).

• F(t) = xj, j - 1 < t < j, j = 1, …, 10

• Want total distance moved in 10 s to be 1.

• Want velocity at t =10 s to be 0.

Intro MATLAB

140
Example (cont.)
• This leads to the underdetermined set of equations

Ax  b ,
 19 / 2 17 / 2 15 / 2  1/ 2 
A  ,
 1 1 1  1 
1
x   x1  x10  , b   
T

 0

Intro MATLAB

141
Example (cont.)
>> x1 = A\b >> x2 = pinv(A) >> [norm(x1) norm(x2)]
x1 = * b ans =
0.11111 x2 = 0.15713 0.1101
0 0.054545
0 0.042424
0 0.030303
0 0.018182
0 0.0060606
0 -0.0060606
0 -0.018182
0 -0.030303
-0.11111 -0.042424
-0.054545

Intro MATLAB

142
Linear Equations, n > m

• When there are more >> A = [2 -1; 1 1; 6 -1];


equations than >> b = [2; 5; -5];
unknowns (i.e.,
>> [rank(A) rank([A b])]
n > m), usually no
solution exists. ans =
• \ can be used to find 2 3
the least squares >> x = A\b
solution, i.e., the x that x =
minimizes ||Ax-b||2 -0.094595
2.4459

Intro MATLAB

143
Example: Fit Polynomial to Data
Assume we can model data as
y  a0  a1 x    a p x p  e
Assume e is measurement noise, and that we have n
measurements of x and y. This leads to an overdetermined
set of equations:

 1 x1  x   a0   y1 
1
p

    
         
 1 xn  xnp   a p   yn 
    

Intro MATLAB

144
Example (cont.)

yˆ  1.64 x 3  5.3x 2  7.69 x  3


Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

147
Matrix Factorizations: chol
chol: factors a >> A = [2 -1; 1 1; 6 -1];
symmetric, positive >> B = A'*A
B =
definite matrix A as
41 -7
RTR, where R is -7 3
upper triangular. >> R = chol(B)
R =
6.4031 -1.0932
Useful in solving least 0 1.3435
squares problems. >> R'*R
ans =
41 -7
-7 3

Intro MATLAB

148
Eigenvalues and Eigenvectors: eig
eig: computes the >> A = [1 -1 0; 0 1 1; 0 0 -2];
eigenvalues, i and >> [V, D] = eig(A)
eigenvectors, xi of a V =
square matrix A.. 1 1 -0.10483
0 0 -0.31449
0 0 0.94346
• i and xi satisfy D =
Axi = i xi 1 0 0
0 1 0
• [V,D] = eig(A) 0 0 -2
returns the eigenvectors >> [A*V(:,3) D(3,3)*V(:,3)]
of A in the columns of V, ans =
and the eigenvalues in 0.20966 0.20966
the diagonal elements of 0.62897 0.62897
D. -1.8869 -1.8869

Intro MATLAB

149
Singular Value Decomposition: svd
svd: factors an n x m >> A = [2 -1; 1 1; 6 -1];
matrix A as A = USVT, >> [U,S,V] = svd(A)
where U and V are U =
orthogonal matrices, -0.32993 0.47852 -0.81373
and S is a diagonal -0.12445 -0.87653 -0.46499
-0.93577 -0.052149 0.34874
matrix with singular
S =
values of A.
6.4999 0
0 1.3235
• Useful in solving least 0 0
squares problems. V =
-0.98447 -0.17558
0.17558 -0.98447

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

152
Ordinary Differential Equations
• MATLAB has a collection of m-files, called the ODE
suite to solve initial value problems of the form

M(t,y)dy/dt = f(t, y)
y(t0) = y0

where y is a vector.

• The ODE suite contains several procedures to solve


such coupled first order differential equations.

Intro MATLAB

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

Solution Initial
Time Solution ODE ODE file
time span conditions
index matrix solver for
derivatives [t0 tf]

Intro MATLAB

154
ODE Suite Solvers

Non-stiff equations Stiff equations


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

Intro MATLAB

155
Example : van der Pol Equation
• Equation is function dydt = vdpol(t,y)
%
d2x/dt2 - (1-x2)dx/dt + x = 0
% van der Pol equation

• Convert to first order ODEs mu = 2;


using dydt = [y(2);mu*(1- …
y1 = x, y2 = dx/dt y(1)^2)*y(2)-y(1)];

dy1/dt = y2
ODE File vdpol.m
dy2/dt=(1-y12)y2-y1

Intro MATLAB

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

Intro MATLAB

157
More on ODE Solvers
• There are a number of different options in specifying
the ODE file. Check HELP on odefile for details.

• odeset and odeget can be used to set and examine


the ODE solver options.

• Can find events (such as max/min/zero, crossings etc.)


in the solution.

Intro MATLAB

158
Numerical Integration
• trapz: Trapezoidal integration

• quad: Adaptive, recursive Simpson’s Rule for


quadrature

• quadl: Adaptive, recursive Newton-Coates


8-panel rule

• dblquad: Double integration using quad or


quadl

Intro MATLAB

159
Integration Example: humps Function
>> x = linspace(-1,2,150);
>> y = humps(x);
>> plot(x,y)
>> format long
>> trapz(x,y) % 5-digit accuracy
ans =
26.344859225225534

>> quad('humps', -1, 2) % 6-digit accuracy


ans =
26.344960501201232

>> quadl('humps', -1, 2) % 8-digit accuracy


ans =
26.344960471378968

Intro MATLAB

160
Root Finding and Minimization

• roots: finds roots of polynomials

• fzero: finds roots of a nonlinear function of one


variable

• fminbnd, fminsearch: finds maxima and


minima of functions of one and several variables

Intro MATLAB

161
Example of Polynomial Roots

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

Intro MATLAB

162
Example of Roots for Nonlinear Functions

Intro MATLAB

163
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

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

166
Graphics, Data Visualization & Movies
Overview
• Plots
– Simple plots
– Subplots (Multiple Axis Regions)
– Mesh plots (Colored wire-frame view of surface)
– Surface Plots
– Patches
– Contour Plots
– Visualization
• Images
– Indexed images
– Intensity images
– Truecolor images
– Reading and writing images
• Movies

Intro MATLAB

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

Intro MATLAB

169
Multiple Curve Plots
>> z = cos(x);
>> plot(x,y,'g.',x,z,'b-.'), title('More Complicated')

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

Intro MATLAB

170
Plot Power: Contour & 3-D Mesh
>> t = 0:pi/25:pi;
>> [x,y,z] = cylinder(4*cos(t));
>> subplot(2,1,1)
>> contour(y)
>> subplot(2,1,2)
>> mesh(x,y,z)
>> xlabel('x')
>> ylabel('this is the y axis')
>> text(1,-2,0.5,...
'\it{Note the gap!}')

To
Tosave:
save:
print
print -djpeg
-djpeg myfigure.jpg
myfigure.jpg
use
usehelp
help print
print for
for options
options

Intro MATLAB

171
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])
1 3

>> subplot(2,3,3)
2
>> 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

Intro MATLAB

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

Intro MATLAB

173
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); Default: shading faceted
>> [X,Y] = meshgrid(-16:1.0:16);
>> Z = sqrt(X.^2 + Y.^2 + 5000); >> shading flat
>> surf(Z) >> shading interp

Intro MATLAB

174
Surface Plots: Colormaps

>> colormap hot

>> colormap gray

>> colormap cool

>> colormap pink

Intro MATLAB

175
More Surface Plots

>> meshc(Z)

>> meshz(Z)

>> surfl(Z)

>> pcolor(Z)

Intro MATLAB

176
Patches
• A patch is a graphics object which contains one or more polygons.
• The polygons don’t have to be connected
• Useful for modeling real-world objects such as missiles and tanks
• Use the patch function to display a patch
• One way to define a patch is to specify Faces and Vertices
Vertices, v Faces, f
Vertex 1 0 0 0
Vertex 2 1 0 0 Face 1 1 2 3 4
Vertex 3 1 1 0 Face 2 5 6 7 8
Vertex 4 0 1 0 Face 3 1 2 6 5
Vertex 5 0.25 0.25 1 Face 4 2 3 7 6
Vertex 6 0.75 0.25 1 Face 5 3 4 8 7
Vertex 7 0.75 0.75 1 Face 6 4 1 5 8
Vertex 8 0.25 0.75 1

Intro MATLAB

177
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

Intro MATLAB

178
Contour Plots
• Use to create, display, and label isolines determined by one or more
matrices
• contour(Z) generates isolines from values given by a matrix Z and
displays it in 2-D
• contour3(Z) generates isolines from values given by a matrix Z and
displays it in 3-D

>> Z = peaks;
>> contour(Z,40)
>>

>> Z = peaks;
>> contour3(Z,40)
>>

Intro MATLAB

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

Intro MATLAB

180
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 >> set(L1, 'Color', 'g')
– Color
– Style
– Position

>> set(L1, 'Position', [-1, -1, 1]) >> set(L1, 'Style', 'local')

Intro MATLAB

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

Intro MATLAB

182
Visualization: Viewpoint
• Use view to specify the viewpoint by defining azimuth and elevation with
respect to the origin • MATLAB defaults
– For 2-D plots, azimuth = 0o elevation = 90o
– For 3-D plots, azimuth = -37.5o elevation = 30o

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


y

Elevation
x

Azimuth

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

Intro MATLAB

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

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

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

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

Intro MATLAB

184
Camera Default Properties
• MATLAB defaults:
– CameraPosition: Position adjusted such that the orientation
of the scene is the standard MATLAB 2-D or 3-D view

– CameraTarget: Center of plot box

– CameraUpVector: y-direction for 2-D views and z-direction for


3-D views

– CameraViewAngle: Angle adjusted such that scene fills the


position rectangle

– Projection: orthographic

Intro MATLAB

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

10 0.5 0.5 0.5 10

I C 1 0.35 0.25 m

Intro MATLAB

186
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);
Intro MATLAB

187
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 HumVee(:, :, 3)
– 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(:, :, 2)

HumVee(:, :, 1)

Intro MATLAB

188
Summary: Commands to Display Images

Use the following to display an Indexed image.


>> image(I); colormap(map)

Use the following to display an Intensity image


>> imagesc(I); colormap(map);

Use the following to display a Truecolor image


>> image(I);

Intro MATLAB

189
Reading Images

• MATLAB can read images of various


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

Intro MATLAB

190
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

Intro MATLAB

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

Use
imfinfo(filename)
to get information on
an image file

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

194
Movie Preparation & Play

Intro MATLAB

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

• M = aviread(FILENAME) reads the AVI movie FILENAME into a movie array M.

Intro MATLAB

196
Example that Illustrates the Use of Movies to Visualize the Various
Powers of the N-th Root of Unity, exp(2pi / n)

figure(1)
numframes=16;

% gca: “get current axis”; returns handle to the


% current axes for the current figure
set(gca, ‘NextPlot', 'replacechildren')
axis equal % fix the axes
for k=1:numframes
plot(fft(eye(k+16))); % eye: Identity matrix
A(k)=getframe;
end
movie(A)

Intro MATLAB

197
aviread
• Refer to Example 1 in movie documentation (doc
movie) to create frame array F using getframe then:

>> movie2avi(F, ‘wave.avi’)


>> M = aviread(‘wave.avi’)
>> movie(M)

•This can create some very large files!

•aviread can only read Type-2 Digital Video AVI files

Intro MATLAB

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

Intro MATLAB

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

Intro MATLAB

201
MEX Procedure
Procedures 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

Intro MATLAB

202
MEX Include File : mex.h

• Must be included in all MEX Files source code

• Defines the prototypes of all mex* API functions (e.g.


mexErrMsgTxt() in our example )

 mex* functions used to set up program tasks

• Includes matrix.h, which in turn defines the prototypes


of all mx* API functions (e.g. mxGetN() in our example)

 mx* functions used for data variables

Intro MATLAB

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

const mxArray *prhs[])


Pointer to array of
of RHS argument
pointers

Intro MATLAB

204
Sample Problem: Scaling
• Simple example: A C function that takes its input,
multiplies each element by 2, and then returns the
“scaled-up” values

• Straightforward C task chosen so that MEX


requirements can be emphasized

• Resulting C MEX file is general purpose in nature

• How the function might be used in MATLAB:


>> [a b] = timestwo(x,y);

Intro MATLAB

205
mexFunction in Scaling Example
In MATLAB: >> a = timestwo(x)

void mexFunction(
In timestwo.c: int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[])

nlhs = 1 nrhs = 1

plhs a prhs x (matrix)

Intro MATLAB

206
MEX Procedure
1. Compile timestwo.c using “mex” command in MATLAB
Compiling mex program,
>> mex timestwo.c
>> dir *.mexw32
timestwo.c

timestwo.mexw32
A platform-specific binary is
generated after compiling

2. Use timestwo.mexw32 like any MATLAB command


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

Intro MATLAB

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

Intro MATLAB

208

You might also like