Matlab Overview
Matlab Overview
What is MATLAB?
MATLAB = Matrix (or) Mathwork Laboratory
MATLAB is a High Level Language
MATLAB is a software environment for interactive numerical computation
MATLAB is a powerful general purpose system for doing Mathematics,
Scientific and Engineering calculations
Matlab
High Level
Languages such as
C, Pascal etc.
Assembly
MATLAB Background
1970 – Cleve Moler, chairman of CS dept, at university of Mexico
• Designed to provide student access to LINPACK and EISPACK
without learning FORTRAN
1984 – Jack Little joined Cleve and Steve Bangert found the
Mathwork and developed C rewrite of MATLAB
• Adopted by control design engineers, in education for teaching of
linear algebra and numerical analysis and for Scientist involved
with image processing
FORTRAN TO MATLAB
FORTRAN:
real*8 A(10,10), B(10,10), C(10,10)
do i=1,10
do j=1,10
C(i,j) = A(i,j) + B(i,j)
10 continue
20 continue
MATLAB:
C=A+B
LINPACK AND EISPACK
MATLAB
Series of
Matlab
commands
Command
m-files mat-files
Line
functions
Input Command Data
Output execution like DOS storage/
capability command window loading
MATLAB System
MATLAB System consists of 5 main parts
• MATLAB Language
High level matrix or array language with control flow
statements
• MATLAB Working environment
Tools for developing, managing, debugging and profiling
m-files
• Handle Graphics
Includes 2D, 3D and GUI
• MATLAB Mathematical Function Libraries
Computation algorithms like sine, cosine, transforms,etc
• MATLAB Application Program Interface(API)
For reading and writing MAT files and for dynamic linking
APPLICATION
• Communication signals
• DC current analysis
• Image processing Application
• Engineering and scientific calculation
• Filtering
• Image Processing with GUI (Graphical User Interface)
Application
• Fuzzy Logic Applications
• Neural Network Applications
• Signal processing application
• Electrical Engineering simulation
• Control system application
MATLAB FOR ENGINEERS
int a;
double b;
float c;
x=
1 2 5 1
• a matrix x = [1 2 3; 5 1 4; 3 2 -1]
x=
1 2 3
5 1 4
3 2 -1
• transpose y = x’ y=
1
2
5
1
Long array
• t =1:10
t=
1 2 3 4 5 6 7 8 9 10
• k =2:-0.5:-1
k=
2 1.5 1 0.5 0 -0.5 -1
• B = [1:4; 5:8]
x=
1 2 3 4
5 6 7 8
Cell arrays
Cells: Initialization
Function Purpose
length Length of vector or largest array dimension
ndims Number of array dimensions
numel Number of array elements
size Array dimensions
iscolumn Determine whether input is column vector
isempty Determine whether array is empty
ismatrix Determine whether input is matrix
isrow Determine whether input is row vector
isscalar Determine whether input is scalar
isvector Determine whether input is vector
blkdiag Construct block diagonal matrix from input arguments
circshift Shift array circularly
ctranspose Complex conjugate transpose
diag Diagonal matrices and diagonals of matrix
flipdim Flip array along specified dimension
fliplr Flip matrix left to right
flipud Flip matrix up to down
ipermute Inverse permute dimensions of N-D array
permute Rearrange dimensions of N-D array
repmat Replicate and tile array
reshape Reshape array
rot90 Rotate matrix 90 degrees
shiftdim Shift dimensions
issorted Determine whether set elements are in sorted order
sort Sort array elements in ascending or descending order
sortrows Sort rows in ascending order
squeeze Remove singleton dimensions
transpose Transpose
vectorize Vectorize expression
MATLAB FILE TYPES
Associate Files
File Result
Extension
.fig Opens file in figure window
.m Opens file in Editor
.mat Opens Import Wizard to load the data into the MATLAB
workspace.
.slx, .mdl Opens file in a Simulink® model window
.mex[a] Displays icon for MATLAB in Windows Explorer tool
.p Displays icon for MATLAB in Windows Explorer tool
[a]
MEX-file extensions are platform-specific. See Using MEX-Files.
To associate a different file type with MATLAB, use the Windows Default
Programs control panel. On Windows 7 systems:
blockdiag(A,B,C)=
Matrix Manipulation
• MATLAB treats all variables as matrices.
• Vectors are special forms of matrices and contain only one row OR one
column.
• Scalars are matrices with only one row AND one column
Given:
Working with Matrices
MATLAB provides five functions that generate basic matrices:
• Zeros: all zeros. A = zeros(1,3)
• Ones: all ones. A = ones(2,4)
• eye(3,3)?
• rand: uniformly distributed random elements.
A = rand(3,5)
• randn: normally distributed random elements.
A = randn(2,5)
Set the state of the random number generator
rand(‘state’,2); randn(‘state’,2);
Single (closing) quotes act as string delimiters, so 'state' is a string. Many
MATLAB functions take string arguments.
Data Import and Export
Import Wizard
• Import wizard provides flexible data possibilities
• File -> Import data
• Provides working directory and various file format
• importdata – Load data from file
• uiimport – import data interactively
File Formats for Import and Export
FILE CONTENT EXTENSION IMPORT EXPORT
FUNCTION FUNCTION
MATLAB formatted MAT Load save
data
Text TXT csvread csvwrite
Spreadsheet XLS xlsread xlswrite
Extensible Markup XML xmlread xmlwrite
Language
Data acquisition DAQ Dadread none
Toolbox
Image BMP,JPEG,TIFF,GI imread imwrite
F
Audio MP4,M4A,WAV audioread Audiowrite
Video MPEG,M4V,MOV Videoreader videowriter
M-files :
Script and function files
When problems become complicated and require re–evaluation,
entering command at MATLAB prompt is not practical
Script Function
Collections of commands User defined commands
INPUT OUTPUT
FUNCTION
– Commands
– Functions
– Intermediate variables
Every function must begin with a header:
function output=function_name(inputs)
Output variable
Must match the file input variable
name
• Functions are M-files that can accept input arguments and return output
arguments. The names of the M-file and of the function should be the
same.
• Example
Task:
Usage example: To evaluate the area of a triangle with side of length 10, 15, 20:
Ax = b
Solutions to Systems of Linear Equations
(con’t…)
• Solution by Matrix Inverse: • Solution by Matrix Division:
Ax = b The solution to the equation
A-1Ax = A-1b Ax = b
x = A-1b can be computed using left division.
• MATLAB: MATLAB:
>> A = [ 3 2 -1; -1 3 2; 1 -1 -1]; >> A = [ 3 2 -1; -1 3 2; 1 -1 -1];
>> b = [ 10; 5; -1]; >> b = [ 10; 5; -1];
>> x = inv(A)*b >> x = A\b
x= x=
-2.0000 -2.0000
5.0000 5.0000
-6.0000 -6.0000
Answer: Answer:
x1 = -2, x2 = 5, x3 = -6 x1 = -2, x2 = 5, x3 = -6
NOTE:
left division: A\b b A right division: x/y x y
Solution of Differential Equations with
MATLAB
53
Symbolic Differential Equation Terms
y •y
dy •Dy
dt
2
d y
•D2y
2
dt
n
d y
n
•Dny
dt
54
Representative CCLODE Form
2
d y dy
b2 2 b1 b0 y A sin at
dt dt
y (0) C1 and y '(0) C2
•>> y = dsolve(‘b2*D2y+b1*D1y+b0*y=A*sin(a*t)’,
• ‘y(0)=C1’, ‘Dy(0)=C2’)
55
Example 1. Solve DE below with MATLAB.
dy y (0) 10
2 y 12
dt
•>> y = dsolve('Dy + 2*y = 12', 'y(0)=10')
•y =
•6+4*exp(-2*t)
58
59
Example 3. Solve DE below with MATLAB.
2
d y dy
2
3 2 y 24
dt dt
y (0) 10 y '(0) 0
•>> y = dsolve('D2y + 3*Dy + 2*y = 24',
'y(0)=10', 'Dy(0)=0')
•y =
•12+2*exp(-2*t)-4*exp(-t)
60
61
Example 4. Solve
2
DE below with MATLAB.
d y dy
2
2 5 y 20
dt dt
y (0) 0 y '(0) 10
•>>ezplot(y, [0 5]}
62
63
STRUCTURES IN MATLAB
STANDARD MATHEMATICAL FUNCTION
PLOT THE SINE, COSINE FUNCTION
Title Adding
Indefinite Integrals
DEFINITE INTEGRAL
TRANSFORMS
Symbolic Laplace Transform
•>> F = laplace(f)
•F =
• 5/s^2
81
Example 6. Determine the Laplace transform of
the function below using MATLAB.
2t 2t
v(t ) 3e sin 5t 4e cos 5t
•>> syms t s
•>> v = 3*exp(-2*t)*sin(5*t)
• + 4*exp(-2*t)*cos(5*t)
•v =
•3*exp(-2*t)*sin(5*t)+4*exp(-2*t)*cos(5*t)
82
Example 6. Continuation.
•>> V = laplace(v)
•V =
•15/((s+2)^2+25)+4*(s+2)/((s+2)^2+25)
•>> V=simplify(V)
•V =
• (23+4*s)/(s^2+4*s+29)
•
83
Example 7. Determine the inverse transform
of the function below using MATLAB.
100( s 3)
F (s) 2
( s 1)( s 2)( s 2 s 5)
•>> syms t s
•>> F=100*(s+3)/((s+1)*(s+2)*(s^2+2*s+5))
•F =
•(100*s+300)/(s+1)/(s+2)/(s^2+2*s+5)
84
Example 11-7. Continuation.
•>> f = ilaplace(F)
•f =
• 50*exp(-t)-20*exp(-2*t)-30*exp(-t)*cos(2*t)-10*exp(-
t)*sin(2*t)
•>> pretty(f)
• 50 exp(-t) - 20 exp(-2 t) - 30 exp(-t) cos(2 t) - 10 exp(-t) sin(2
t)
85
Example 11-8. Determine the inverse transform
of the function below using MATLAB.
10 48
Y (s) 2
s 2 ( s 2)( s 16)
•>> syms t s
•>> Y = 10/(s+2) + 48/((s+2)*(s^2+16))
•Y =
•10/(s+2)+48/(s+2)/(s^2+16)
86
Example 8. Continuation.
•>> y = ilaplace(Y)
•y =
•62/5*exp(-2*t)-12/5*cos(16^(1/2)*t)
+3/10*16^(1/2)*sin(16^(1/2)*t)
•>> y=simplify(y)
•y =
•62/5*exp(-2*t)-12/5*cos(4*t)+6/5*sin(4*t)
87
Two Dimensional Plots
Topics Covered:
1. Plotting basic 2-D plots.
MATLAB has many functions and commands that can be used to create various
types of plots.
label 1000
Text
Tick-mark
800
INTENSITY (lux)
600
400
Data symbol
200
0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
TWO-DIMENSIONAL plot() COMMAND
The basic 2-D plot command is:
plot(x,y)
x 1 2 3 5 7 7.5 8 10
y 2 6.5 7 7 5.5 4 6 8
A plot can be created by the commands shown below. This can be done in the
Command Window, or by writing and then running a script file.
Once the plot command is executed, the Figure Window opens with the following
plot.
PLOT OF GIVEN DATA
LINE SPECIFIERS IN THE plot() COMMAND
plot(x,y,’line specifiers’)
LINE SPECIFIERS IN THE plot() COMMAND
plot(x,y,‘line specifiers’)
LINE SPECIFIERS IN THE plot() COMMAND
The specifiers are typed inside the plot() command as strings.
The specifiers are optional. This means that none, one, two, or all the three
can be included in a command.
EXAMPLES:
Line Specifiers:
dashed red line and
asterisk markers.
PLOT OF GIVEN DATA USING LINE SPECIFIERS IN
THE plot() COMMAND
0 .5 x
Consider: y 3.5 cos(6 x) for 2 x 4
A script file for plotting the function is:
Once the plot command is executed, the Figure Window opens with the following
plot.
A PLOT OF A FUNCTION
0 .5 x
y 3.5 cos(6 x) for 2 x 4
CREATING A PLOT OF A FUNCTION
If the vector x is created with large spacing, the graph is not accurate.
Below is the previous plot with spacing of 0.3.
x = [-2:0.3:4];
y = 3.5.^(-0.5*x).*cos(6*x);
plot(x,y)
THE fplot COMMAND
fplot(‘function’,limits)
The limits is a vector with the domain of x, and optionally with limits of the y
axis:
[xmin,xmax] or [xmin,xmax,ymin,ymax]
Line specifiers can be added.
PLOT OF A FUNCTION WITH THE fplot() COMMAND
A plot of: y x 2 4 sin( 2 x) 1 for 3 x 3
plot(x,y,u,v,t,h)
plot(x,y,’-b’,u,v,’—r’,t,h,’g:’)
USING THE plot() COMMAND TO PLOT
MULTIPLE GRAPHS IN THE SAME PLOT
120
100
80
60
40
20
-20
-40
-2 -1 0 1 2 3 4
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
hold on Holds the current plot and all axis properties so that subsequent
plot commands add to the existing plot.
hold off Returns to the default mode whereby plot commands erase the
previous plots and reset all axis properties before drawing new
plots.
This method is useful when all the information (vectors) used for the plotting
is not available a the same time.
USING THE hold on, hold off, COMMANDS
TO PLOT MULTIPLE GRAPHS IN THE SAME PLOT
Plot of the function, y 3 x 3 26 x 10 and its first and second
derivatives, for 2 x 4 all in the same plot.
x = [-2:0.01:4];
y = 3*x.^3-26*x+6;
yd = 9*x.^2-26;
ydd = 18*x;
plot(x,y,'-b')
First graph is created.
hold on
plot(x,yd,'--r')
plot(x,ydd,':k') Two more graphs are created.
hold off
EXAMPLE OF A FORMATTED 2-D PLOT
Plot title
Light Intensity as a Function of Distance
1200 Legend
Theory
y axis Experiment
label 1000
Text
800
Tick-mark
INTENSITY (lux)
600
400
Data symbol
200
0
8 10 12 14 16 18 20 22 24
DISTANCE (cm)
x axis Tick-mark label
label
FORMATTING PLOTS
1. Formatting commands.
In this method commands, that make changes or additions to the plot, are
entered after the plot() command. This can be done in the Command
Window, or as part of a program in a script file.
title(‘string’)
Adds the string as a title at the top of the plot.
xlabel(‘string’)
Adds the string as a label to the x-axis.
ylabel(‘string’)
Adds the string as a label to the y-axis.
legend(‘string1’,’string2’,’string3’)
Creates a legend using the strings to label various curves (when several
curves are in one plot). The location of the legend is specified by the mouse.
text(x,y,’string’)
Places the string (text) on the plot at coordinate x,y relative to the plot axes.
gtext(‘string’)
Places the string (text) on the plot. When the command executes the figure
window pops and the text location is clicked with the mouse.
EXAMPLE OF A FORMATTED PLOT
Below is a script file of the formatted light intensity plot (2nd slide).
(Some of the formatting options were not covered in the lectures, but are
described in the book)
xlabel('DISTANCE (cm)')
Labels for the axes.
ylabel('INTENSITY (lux)')
Title for the plot.
title('\fontname{Arial}Light Intensity as a Function of Distance','FontSize',14)
axis([8 24 0 1200])
text(14,700,'Comparison between theory and
Setting limits of the axes.
experiment.','EdgeColor','r','LineWidth',2)
legend('Theory','Experiment',0) Creating text.
Creating a legend.
0.6
0.5
• plot(.) 0.4
0.3
0.2
Example: 0.1
>>x=linspace(0,4*pi,100); 0
>>y=sin(x); -0.1
>>plot(y) -0.2
>>plot(x,y) -0.3
0 10 20 30 40 50 60 70 80 90 100
0.7
• stem(.) 0.6
0.5
0.4
0.3
0.2
Example: 0.1
>>stem(y) 0
>>stem(x,y) -0.1
-0.2
-0.3
0 10 20 30 40 50 60 70 80 90 100
• title(.)
This is the sinus function
1
>>title(‘This is the sinus function’)
0.8
0.6
• xlabel(.)
0.4
0.2
sin(x)
>>xlabel(‘x (secs)’)
-0.2
-0.4
-0.6
• ylabel(.) -0.8
-1
0 10 20 30 40 50 60 70 80 90 100
>>ylabel(‘sin(x)’) x (secs)
A simple example:
a=1
while length(a) < 10
which prints out Pascal’s triangle:
a = [0 a] + [a 0]
end
1
11
121
1331
14641
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
• Why model?
- Represent
- Analyze
124
Model representations
125
Transfer Function representation
Given: G(s ) Y (s ) 25
U (s ) s 2 4s 25
Matlab function: tf
126
Zero-Pole-Gain representation
Given: H (s ) Y (s ) 3(s 1)
U (s ) (s 2 i )(s 2 i )
zeros = [1];
poles = [2-i 2+i];
gain = 3;
H = zpk(zeros,poles,gain)
127
State Space representation
1 0 1
Given: x Ax Bu, A B
2 1 0
y Cx Du
C 3 2 D 0
Matlab function: ss
A = [1 0 ; -2 1];
B = [1 0]’;
C = [3 -2];
D = [0];
sys = ss(A,B,C,D)
128
System analysis
129
Stability analysis
Is the system stable?
Recall: All poles of the system must be on the right hand side of the S plain
for continuous LTI systems to be stable.
In Matlab:
pole(sys)
130
Time domain analysis
Once a model has been inserted in Matlab, the step response can be
obtained directly from: step(sys)
0.8
0.6
• Impulse response
impulse(sys)
• Response to an arbitrary input
e.g.
t = [0:0.01:10];
u = cos(t);
lsim(sys,u,t)
133
Frequency domain analysis
For a pole and zero plot: pzmap(sys)
Pole-Zero Map
4
1
Imaginary Axis
-1
-2
-3
-4
-2 -1.8 -1.6 -1.4 -1.2 -1 -0.8 -0.6 -0.4 -0.2 0
Real Axis
134
Extra: partial fraction expansion
Given: 2s 2 3s 2
G ( s) 2
s 3s 2
num=[2 3 2];
den=[1 3 2];
[r,p,k] = residue(num,den)
r= Answer:
-4
1 r (1) r ( n)
p= G ( s) k ( s)
-2
-1 0
s p(1)
4 1
s p ( n)
k= 2s
2 s ( 2) s ( 1)
135