MATLAB Course - Part 2
MATLAB Course - Part 2
MATLAB Course - Part 2
MATLAB
HANS-PETTER HALVORSEN, 2012.08.20
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
Preface
In this MATLAB Course you will learn basic MATLAB and how to use MATLAB in Control and
Simulation applications. An introduction to Simulink and other Tools will also be given.
This is a self-paced course based on this document and some short videos on the way. This document
contains lots of examples and self-paced tasks that the users will go through and solve on their own.
The user may go through the tasks in this document in their own pace and the instructor will be
available for guidance throughout the course.
In Part II of the course (Part II: Modelling, Control and Simulation) you will learn how to use MATLAB
in Modelling, Control and Simulation.
You must go through MATLAB Course – Part I: Introduction – MATLAB Basics before you start.
The course consists of lots of Tasks you should solve while reading this course manual and watching
the videos referred to in the text.
Make sure to bring your headphones for the videos in this course. The course consists of
several short videos that will give you an introduction to the different topics in the course.
Prerequisites
You should be familiar with undergraduate-level mathematics and have experience with basic
computer operations.
ii
What is MATLAB?
MATLAB is developed by The MathWorks. MATLAB is a short-term for MATrix LABoratory. MATLAB is
in use world-wide by researchers and universities. For more information, see www.mathworks.com
iii
Table of Contents
Preface......................................................................................................................................................ii
1 Introduction .................................................................................................................................... 1
3.1 Interpolation............................................................................................................................ 9
4 Optimization ................................................................................................................................. 27
iv
v Table of Contents
Numerical Techniques....................................................................................................................... 63
Interpolation ................................................................................................................................. 63
Curve Fitting.................................................................................................................................. 63
Numerical Integration................................................................................................................... 64
Optimization...................................................................................................................................... 64
http://home.hit.no/~hansha/?lab=matlab
Part 2: “Modelling, Simulation and Control” consists of the following topics:
1
2 Differential Equations and
ODE Solvers
MATLAB have lots of built-in functionality for solving differential equations. MATLAB includes
functions that solve ordinary differential equations (ODE) of the form:
( ) ( )
Higher order differential equations must be reformulated into a system of first order differential
equations.
Not all differential equations can be solved by the same technique, so MATLAB offers lots of different
ODE solvers for solving differential equations, such as ode45, ode23, ode113, etc.
Example:
Given the following differential equation:
Note! ̇
( )
We shall plot the solution for this differential equation using MATLAB.
2
3 Differential Equations and ODE Solvers
We will create a script in MATLAB (.m file) where we plot the solution ( ) in the time interval
T = 5;
a = -1/T;
x0 = 1;
t = [0:1:25]
x = exp(a*t)*x0;
plot(t,x);
grid
[End of Example]
This works fine, but the problem is that we first have to find the solution to the differential equation
– instead we can use one of the built-in solvers for Ordinary Differential Equations (ODE) in MATLAB.
Example:
We use the ode23 solver in MATLAB for solving the differential equation (“runmydiff.m”):
tspan = [0 25];
x0 = 1;
[t,x] = ode23(@mydiff,tspan,x0);
plot(t,x)
function dx = mydiff(t,x)
a = -1/5;
dx = a*x;
This gives the same results as shown in the plot above and MATLAB have solved the differential
equation for us (numerically).
Note! You have to implement it in 2 different m. files, one m. file where you define the differential
equation you are solving, and another .m file where you solve the equation using the ode23 solver.
[End of Example]
[t,y] = solver(odefun,tspan,y0,options,…)
where “solver” is one of the ODE solver functions (ode23, ode45, etc.).
Note! If you don’t specify the resulting array [t, y], the function create a plot of the result.
‘odefun’ is the function handler, which is a “nickname” for your function that contains the
differential equations.
Example:
Given the differential equations:
function dy=mydiff(t,y)
dy(1) = y(2);
dy(2) = -y(1);
dy = [dy(1); dy(2)];
Note! Since numbers of equations is more than one, we need to use vectors!!
plot(t,y)
title('solution of dy/dt=x and dx/dt=-y')
legend('y', 'x')
The equations are solved in the time span with initial values .
dxdt(1) = -x(2);
dxdt(2) = x(1);
dxdt = dxdt';
Note! The function mydiff must return a column vector, that’s why we need to transpose it.
Then we use the ode solver to solve the differential equations (“run_mydiff.m”):
tspan = [-1,1];
x0 = [1,1];
plot (t,x)
legend('x1', 'x2')
[End of Example]
birth rate=bx
Note! ̇
→ Simulate (i.e., create a plot) the number of bacteria in the jar after 1 hour, assuming that initially
there are 100 bacteria present.
[End of Task]
In this case we want to pass and as parameters, to make it easy to be able to change values
for these parameters.
function dx = mysimplediff(t,x,param)
% My Simple Differential Equation
a = param(1);
b = param(2);
dx = a*x+b;
tspan = [0 25];
x0 = 1;
a = -1/5;
b = 1;
param = [a b];
By doing this, it is very easy to changes values for the parameters and without changing the
code for the differential equation.
Note! We need to use the 5.argument in the ODE solver function for this. The 4.argument is for
special options and is normally set to “[]”, i.e., no options.
Read more about the different solvers that exists in the Help system in MATLAB
[End of Task]
Use the ode23 function to solve and plot the results of the following differential equation in the
interval :
( ) ( )
Note!
[End of Task]
Use the ode23/ode45 function to solve and plot the results of the following differential equation in
the interval :
( ) ̈ ̇ ( ) ̇( )
Note! ̈
Note! Higher order differential equations must be reformulated into a system of first order
differential equations.
Tip 2: Set:
[End of Task]
3.1 Interpolation
Interpolation is used to estimate data points between two known points. The most common
interpolation technique is Linear Interpolation.
Example:
Given the following data:
x y
0 15
1 10
2 9
3 6
4 2
5 0
x=0:5;
y=[15, 10, 9, 6, 2, 0];
plot(x,y ,'-o')
The answer is 4, from the plot below we see this is a good guess:
9
10 Numerical Techniques
[End of Example]
The default is linear interpolation, but there are other types available, such as:
linear
nearest
spline
cubic
etc.
Type “help interp1” in order to read more about the different options.
Example:
In this example we will use a spline interpolation on the same data as in the example above.
x=0:5;
y=[15, 10, 9,6, 2, 0];
new_x=0:0.2:5;
new_y=interp1(x,y,new_x, 'spline')
The result is as we plot both the original point and the interpolated points in the same graph:
[End of Example]
Task 5: Interpolation
Plot u versus T. Find the interpolated data and plot it in the same graph. Test out different
interpolation types. Discuss the results. What kind of interpolation is best in this case?
[End of Task]
MATLAB has built-in curve fitting functions that allows us to create empiric data model. It is
important to have in mind that these models are good only in the region we have collected data.
Here are some of the functions available in MATLAB used for curve fitting:
These techniques use a polynomial of degree N that fits the data Y best in a least-squares sense.
( )
Example:
Given the following data:
x y
0 15
1 10
2 9
3 6
4 2
5 0
x=[0, 1, 2, 3, 4 ,5];
y=[15, 10, 9, 6, 2 ,0];
n=1; % 1.order polynomial
p = polyfit(x,y,n)
ans =
-2.9143 14.2857
We can also plot the measured data and the model in the same plot:
x=[0, 1, 2, 3, 4 ,5];
y=[15, 10, 9, 6, 2 ,0];
n=1; % 1.order polynomial
p=polyfit(x,y,n);
a=p(1);
b=p(2);
ymodel=a*x+b;
plot(x,y,'o',x,ymodel)
[End of Example]
Plot u versus T.
[End of Task]
( )
Example:
Given the following data:
x y
0 15
1 10
2 9
3 6
4 2
5 0
( )
We will use the polyfit and polyval functions in MATLAB and compare the models using different
orders of the polynomial.
We will investigate models of 2.order, 3.order, 4.order and 5.order. We have only 6 data points, so a
model with order higher than 5 will make no sense.
x=[0, 1, 2, 3, 4 ,5];
y=[15, 10, 9, 6, 2 ,0];
ymodel=polyval(p,x);
subplot(2,2,n-1)
plot(x,y,'o',x,ymodel)
title(sprintf('Model of order %d', n));
end
p =
0.0536 -3.1821 14.4643
p =
-0.0648 0.5397 -4.0701 14.6587
p =
0.1875 -1.9398 6.2986 -9.4272 14.9802
p =
-0.0417 0.7083 -4.2083 10.2917 -11.7500 15.0000
( )
( )
( )
( )
As expected, the higher order models match the data better and better.
Note! The fifth order model matches exactly because there were only six data points available.
[End of Example]
x y
10 23
20 45
30 60
40 82
50 111
60 140
70 167
80 198
90 200
100 220
→ Use the polyfit and polyval functions in MATLAB and compare the models using different orders
of the polynomial.
[End of Task]
→ Create a 1. (linear), 2. (quadratic) and 3.order (cubic) model. Which gives the best model? Plot the
result in the same plot and compare them. Add xlabel, ylabel, title and a legend to the plot and use
different line styles so the user can easily see the difference.
[End of Task]
This approximation of the derivative corresponds to the slope of each line segment used to connect
each data point that exists. An example is shown below:
Example:
x y
-2 4
-1 1
0 0
1 1
2 4
First, we will plot the data points together with the real function using the following code:
x=-2:0.1:2;
y=x.^2;
plot(x,y)
hold on
x=-2:2;
y=x.^2;
plot(x,y, '-oc')
We will use this to compare the results from the numerical differentiation with the exact solution.
x=-2:2;
y=x.^2;
dydx_num=diff(y)./diff(x);
dydx_exact=2*x;
dydx=[[dydx_num, NaN]', dydx_exact']
This gives the following results (left column is from the numerical derivation, while the right column
is from the exact derivation):
dydx =
-3 -4
-1 -2
1 0
3 2
NaN 4
Note! NaN is added to the vector with numerical differentiation in order to get the same length of
the vectors.
[End of Example]
Define a vector x from -5 to +5 and use the diff function to approximate the derivative y with respect
to x ( ).
Compare the data in a 2D array and/or plot both the exact value of and the approximation in the
same plot.
( )
[End of Task]
( )
( ) ( )
Example
Given the polynomial
( )
( )
>> p=[1, 0, 0, 2]
We know that:
>> p=[1, 0, 0, 2]
p =
1 0 0 2
>> polyder(p)
ans =
3 0 0
( )
[End of Example]
[End of Task]
( )( )
Another approach is to use define is to first use the conv(a,b) function to find the total polynomial,
and then use polyder(p) function.
[End of Task]
∫ ( )
An integral can be seen as the area under a curve. Given ( ) the approximation of the Area
(A) under the curve can be found dividing the area up into rectangles and then summing the
contribution from all the rectangles:
∑( ) ( )
We approximate the integral by using n trapezoids formed by using straight line segments between
the points ( ) and ( ) for as shown in the figure below:
The area of a trapezoid is obtained by adding the area of a rectangle and a triangle:
Example:
Given the function:
We will use the trapezoid rule and the diff function in MATLAB to solve the numerical integral of
from 0 to 1.
x=0:0.1:1;
y=x.^2;
Note!
A = sum(diff(x).*avg_y)
∑( ) ( )
A =
0.3350
quad('x.^2', 0,1)
ans =
0.3333
quadl('x.^2', 0,1)
ans =
0.3333
[End of Example]
∫ ( ) ( )|
( ) ( ) ( ) ( )
( )
[End of Task]
( )
In MATLAB we can use the polyint function to perform integration on polynomials. This function
works the same way as the polyder function which performs differentiation on polynomials.
[End of Task]
In MATLAB we can use the fminbnd and fminsearch functions. We will take a closer look of how to
use these functions.
Example:
Given the following function:
( )
27
28 Optimization
x = -5:1:5;
f = mysimplefunc(x);
plot(x, f)
function f = mysimplefunc(x)
f = x.^2 + 2.*x + 1;
This gives:
x_min =
-1
→ The minimum of the function is -1. This can also be shown from the plot.
[End of Example]
Note! If a function has more than one variable, we need to use the fminsearch function.
Example:
Given the following function:
( ) ( ) ( )
function f = myfunc(x)
[ ]
This gives:
x =
0.7500
1.5000
fval =
0.6250
clear,clc
f = 2.*(x-1).^2 + x - 2 + (y-2).^2 + y;
figure(1)
surf(x,y,f)
figure(2)
mesh(x,y,f)
figure(3)
surfl(x,y,f)
shading interp;
colormap(hot);
[End of Example]
( )
[End of Task]
( ) ( ) ( )
The global minimum is inside a long, narrow, parabolic shaped flat valley. To find the valley is trivial.
To converge to the global minimum, however, is difficult. But MATLAB will hopefully do the job for
us.
[End of Task]
Control System Toolbox builds on the foundations of MATLAB to provide functions designed for
control engineering. Control System Toolbox is a collection of algorithms, written mostly as M-files,
that implements common control system design, analysis, and modeling techniques. Convenient
graphical user interfaces (GUIs) simplify typical control engineering tasks. Control systems can be
modeled as transfer functions, in zero-pole-gain or state-space form, allowing you to use both
classical and modern control techniques. You can manipulate both continuous-time and
discrete-time systems. Conversions between various model representations are provided. Time
responses, frequency responses can be computed and graphed. Other functions allow pole
32
33 Control System Toolbox
placement, optimal control, and estimation. Finally, Control System Toolbox is open and extensible.
You can create custom M-files to suit your particular application.
6.1 Introduction
Transfer functions are a model form based on the Laplace transform. Transfer functions are very
useful in analysis and design of linear dynamic systems.
( )
( )
( )
( )
( )
( )
there
is the Gain
A 1.order transfer function with time-delay has the following characteristic step response:
34
35 Transfer Functions
A first order transfer function with time-delay has the following transfer function:
( )
( )
( )
A 1.order transfer function with time-delay has the following characteristic step response:
MATLAB have several functions for creating and manipulation of transfer functions:
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type “help <functionname>” in the Command window.
6.2 Tasks
Use the tf function in MATLAB to define the transfer function above. Set and .
Type “help tf” in the Command window to see how you use this function.
Example:
[End of Task]
( )
( )
Where
is the gain
Set
→ Plot the step response (use the step function in MATLAB) for different values of . Select as
follows:
[End of Task]
( )
Plot the time response for the transfer function using the step function. Let the time-interval be from
0 to 10 seconds, e.g., define the time vector like this:
t=[0:0.01:10]
[End of Task]
Integrator
1. Order system
2. Order system
( )
→ Plot the Step response: Use different values for , e.g., . Use the step function in
MATLAB.
[End of Task]
( )
[End of Task]
( )
( )
Where
is the gain
zeta is the relative damping factor
[rad/s] is the undamped resonance frequency.
→ Plot the Step response: Use different values for , e.g., . Set and K=1. Use
the step function in MATLAB.
[End of Task]
Special case: When and the poles are real and distinct we have:
( )
( )( )
We see that this system can be considered as two 1.order systems in series.
( ) ( ) ( )
( ) ( ) ( )( )
Set and
[End of Task]
7.1 Introduction
A state-space model is a structured form or representation of a set of differential equations.
State-space models are very useful in Control theory and design. The differential equations are
converted in matrices and vectors, which is the basic elements in MATLAB.
̇
̇
[ ] [ ][ ] [ ][ ]
⏟ ⏟
̇
⏟ ⏟ ⏟
̇
[ ] [ ][ ] [ ][ ]
⏟ ⏟
⏟ ⏟ ⏟
This gives the following compact form of a general linear State-space model:
Example:
42
43 State-space Models
̇
[ ] [ ][ ] [ ]
̇
⏟ ⏟
⏟ [ ]
[End of Example]
MATLAB have several functions for creating and manipulation of State-space models:
Example:
% Creates a state-space model
A = [1 3; 4 6];
B = [0; 1];
C = [1, 0];
D = 0;
SysOutSS = ss(A, B, C, D)
[End of Example]
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type “help <functionname>” in the Command window.
7.2 Tasks
→ Find the transfer function from the state-space model using MATLAB code.
[End of Task]
̇
[ ] [ ][ ] [ ]
̇
[ ]
→Apply a step in F (u) and use the step function in MATLAB to simulate the result.
[End of Task]
Find the state-space model from the block diagram below and implement it in MATLAB.
Set
[End of Task]
For Simulation and Control in computers discrete systems are very important.
But the matrices is of course not the same as in the continuous system.
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type “help <functionname>” in the Command window.
46
47 Discrete systems
̇
[ ] [ ][ ] [ ]
̇
[ ]
[End of Task]
8.1 Discretization
In order to discretizate a continuous model there are lots of different methods to use. One of the
simplest is Euler Forward method:
As shown in a previous chapter, MATLAB have lots of built-in functions for solving differential
equations numerically, but here we will create our own discrete model.
birth rate=bx
We will simulate the number of bacteria in the jar after 1 hour, assuming that initially there are 100
bacteria present.
→ Find the discrete model using the Euler Forward method by hand and implement and simulate the
system in MATLAB using a For Loop.
[End of Task]
9.1 Introduction
The frequency response of a system is a frequency dependent function which expresses how a
sinusoidal signal of a given frequency on the system input is transferred through the system. Each
frequency component is a sinusoidal signal having a certain amplitude and a certain frequency.
The frequency response is an important tool for analysis and design of signal filters and for analysis
and design of control systems. The frequency response can be found experimentally or from a
transfer function model.
We can find the frequency response of a system by exciting the system with a sinusoidal signal of
amplitude A and frequency ω [rad/s] (Note: ) and observing the response in the output
variable of the system.
The frequency response of a system is defined as the steady-state response of the system to a
sinusoidal input signal. When the system is in steady-state it differs from the input signal only in
amplitude/gain (A) and phase lag ( ).
( )
( ) ⏟ ( )
Where is the ratio between the amplitudes of the output signal and the input signal (in
steady-state).
49
50 Frequency Response
( )
( )
( )
We have that:
( ) | ( ( )
)|
Where ( ) is the frequency response of the system, i.e., we may find the frequency response by
setting in the transfer function. Bode diagrams are useful in frequency response analysis.
The Bode diagram consists of 2 diagrams, the Bode magnitude diagram, ( ) and the Bode phase
diagram, ( ).
( ) | ( )|
( ) ( )
The ( )-axis is in decibel (dB), where the decibel value of x is calculated as:
Example:
Here you will learn to plot the frequency response in a Bode diagram.
( )
( )
( )
Below we see the script for creating the frequency response of the system in a bode plot using the
bode function in MATLAB. Use the grid function to apply a grid to the plot.
[End of Example]
Before you start, you should use the Help system in MATLAB to read more about these functions.
Type “help <functionname>” in the Command window.
9.2 Tasks
( )
→ Set up the mathematical expressions for ( ) and ( ). Use “Pen & Paper” for this
Assignment.
→ Plot the frequency response of the system in a bode plot using the bode function in MATLAB.
Discuss the results.
→ Find ( ) and ( ) for the following frequencies using MATLAB code (use the bode function):
( ) ( )( )
0.1
0.16
0.25
0.4
0.625
2.5
→ Find ( ) and ( ) for the same frequencies above using the mathematical expressions for
( ) and ( ). Tip: Use a For Loop or define a vector w=[0.1, 0.16, 0.25, 0.4, 0.625, 2.5].
[End of Task]
( )
( )
( )( )
→ Set up the mathematical expressions for ( ) and ( ). Use “Pen & Paper” for this
Assignment.
→ Plot the frequency response of the system in a bode plot using the bode function in MATLAB.
Discuss the results.
→ Find ( ) and ( ) for some given frequencies using MATLAB code (use the bode function).
→ Find ( ) and ( ) for the same frequencies above using the mathematical expressions for
( ) and ( ). Tip: use a For Loop or define a vector w=[0.01, 0.1, …].
[End of Task]
( )
Where
( ) ( )
( ) ( )
( ) ( )
The Tracking Property is good if the tracking function T has value equal to or close to 1:
| |
( )
( ) ( )
( ) ( )
The Compensation Property is good if the sensitivity function S has a small value close to zero:
| | | |
Note!
( )
( ) ( )
( ) ( )
| ( )|
| ( )|
– crossover-frequency – the frequency where the gain of the Loop transfer function ( ) has
the value:
– the frequency where the gain of the Tracking function ( ) has the value:
- the frequency where the gain of the Sensitivity transfer function ( ) has the value:
Where , where , ,
Where .
→ Define the Loop transfer function ( ), Sensitivity transfer function ( ) and Tracking transfer
function ( ) and in MATLAB.
→ Plot the Loop transfer function ( ), the Tracking transfer function ( ) and the Sensitivity
transfer function ( ) in the same Bode diagram. Use, e.g., the bodemag function in MATLAB.
[End of Task]
The Gain Margin – GM ( ) is how much the loop gain can increase before the system become
unstable.
The Phase Margin - PM ( ) is how much the phase lag function of the loop can be reduced before
the loop becomes unstable.
Where:
Gain Crossover-frequency - :
| ( )|
Phase Crossover-frequency - :
( )
Gain Margin - GM ( ):
| ( )|
or:
| ( )|
Phase margin PM ( ):
( )
We have that:
We use the following functions in MATLAB: tf, bode, margins and margin.
( )
( )
We will find the crossover-frequencies for the system using MATLAB. We will also find also the gain
margins and phase margins for the system.
Plot a bode diagram where the crossover-frequencies, GM and PM are illustrated. Tip! Use the
margin function in MATLAB.
[End of Task]
Use the ode45 function to solve and plot the results of the following differential equation in the
interval :
( )
[End of Task]
̇
[ ] [ ][ ] [ ]
̇
Set .
→ Solve and Plot the system using one or more of the built-in solvers (use, e.g., ode32) in MATLAB.
Apply a step in (which is the control signal ).
59
60 Additional Tasks
[End of Task]
→ Find the work produced in a piston cylinder device by solving the equation:
where
P= pressure
V=volume, m3
n=number of moles, kmol
R=universal gas constant, 8.314 kJ/kmol K
T=Temperature, K
We also assume that the piston contains 1 mol of gas at 300K and that the temperature is constant
during the process.
Use both the quad and quadl functions. Compare with the exact solution by solving the integral
analytically.
[End of Task]
where m is the mass, r is the length of the arm of the pendulum, g is the gravity, b is a friction
coefficient.
[End of Task]
̇
[ ] [ ][ ] [ ]
̇
[ ]
→ Simulate the system using the lsim function in the Control System Toolbox.
[End of Task]
Interpolation
MATLAB offers functions for interpolation, e.g.:
Curve Fitting
Here are some of the functions available in MATLAB used for curve fitting:
63
64 Appendix A – MATLAB Functions
Numerical Differentiation
MATLAB offers functions for numerical differentiation, e.g.:
Numerical Integration
MATLAB offers functions for numerical integration, such as:
Optimization
MATLAB offers functions for local minimum, such as:
bode Creates the Bode magnitude and Bode phase plots of a system >num=[4];
>den=[2, 1];
model. You also can use this function to return the magnitude >H = tf(num, den)
and phase values of a model at frequencies you specify. If you >bode(H)
do not specify an output, this function creates a plot.
bodemag Creates the Bode magnitude plot of a system model. If you do >[mag, wout] = bodemag(SysIn)
>[mag, wout] = bodemag(SysIn, [wmin
not specify an output, this function creates a plot. wmax])
>[mag, wout] = bodemag(SysIn,
wlist)
margin Calculates and/or plots the smallest gain and phase margins of a >num = [1]
>den = [1, 5, 6]
single-input single-output (SISO) system model. The gain margin >H = tf(num, den)
indicates where the frequency response crosses at 0 decibels. margin(H)
The phase margin indicates where the frequency response
crosses -180 degrees. Use the margins function to return all gain
and phase margins of a SISO model.
margins Calculates all gain and phase margins of a single-input >[gmf, gm, pmf, pm] = margins(H)
single-output (SISO) system model. The gain margins indicate
where the frequency response crosses at 0 decibels. The phase
margins indicate where the frequency response crosses -180
degrees. Use the margin function to return only the smallest
gain and phase margins of a SISO model.
c2d Convert from continuous- to discrete-time models
d2c Convert from discrete- to continuous-time models
Faculty of Technology
Kjølnes Ring 56
www.hit.no
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a