MATLAB Course - Part 2
MATLAB Course - Part 2
MATLAB
HANS-PETTER HALVORSEN, 2012.08.20
Faculty of Technology, Postboks 203, Kjlnes 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. MATLAB is a tool for technical computing, computation and visualization in an integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem solving related to Linear Algebra, Modelling, Simulation and Control applications. 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. The MATLAB Course consists of 3 parts: MATLAB Course Part I: Introduction MATLAB Basics MATLAB Course Part II: Modelling, Simulation and Control MATLAB Course Part III: Advanced Topics, Simulink and other Tools
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. Course Homepage: http://home.hit.no/~hansha/?lab=matlab
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 a tool for technical computing, computation and visualization in an integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem solving related to Linear Algebra. 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 For more information about MATLAB, etc., please visit http://home.hit.no/~hansha/
iii
Table of Contents
Preface......................................................................................................................................................ii Table of Contents .................................................................................................................................... iv 1 2 Introduction .................................................................................................................................... 1 Differential Equations and ODE Solvers ......................................................................................... 2 2.1 3 ODE Solvers in MATLAB ........................................................................................................... 4
Numerical Techniques .................................................................................................................... 9 3.1 3.2 Interpolation............................................................................................................................ 9 Curve Fitting .......................................................................................................................... 12 Linear Regression .......................................................................................................... 12 Polynomial Regression .................................................................................................. 15
3.3.1 3.4
3.4.1 4 5 6
Optimization ................................................................................................................................. 27 Control System Toolbox................................................................................................................ 32 Transfer Functions ........................................................................................................................ 34 6.1 6.2 6.3 Introduction ........................................................................................................................... 34 Tasks ...................................................................................................................................... 36 Analysis of Standard Functions ............................................................................................. 38
v 8
Frequency Response ..................................................................................................................... 49 9.1 9.2 9.3 9.4 Introduction ........................................................................................................................... 49 Tasks ...................................................................................................................................... 51 Frequency response Analysis ................................................................................................ 53 Stability Analysis of Feedback Systems ................................................................................. 56
10
Appendix A MATLAB Functions .......................................................................................................... 63 Numerical Techniques....................................................................................................................... 63 Solving Ordinary Differential Equations ....................................................................................... 63 Interpolation ................................................................................................................................. 63 Curve Fitting.................................................................................................................................. 63 Numerical Differentiation ............................................................................................................. 64 Numerical Integration................................................................................................................... 64 Optimization...................................................................................................................................... 64 Control and Simulation ..................................................................................................................... 65
1 Introduction
This Lab Work has its own web page with additional resources, documents, web links, etc.:
http://home.hit.no/~hansha/?lab=matlab
Part 2: Modelling, Simulation and Control consists of the following topics: Differential Equations and ODE Solvers Numerical Techniques o Interpolation o Curve Fitting o Numerical Differentiation o Numerical Integration Optimization Control System Toolbox Transfer functions State-space models Frequency Response Discrete Systems Additional Tasks
Example:
Given the following differential equation: where Note! The solution for the differential equation is found to be: ( ) We shall plot the solution for this differential equation using MATLAB. Set and the initial condition ( ) . ,where is the time constant
We will create a script in MATLAB (.m file) where we plot the solution
The Code is as follows: T = 5; a = -1/T; x0 = 1; t = [0:1:25] x = exp(a*t)*x0; plot(t,x); grid This gives the following Results:
[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. There are different functions, such as ode23 and ode45.
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) Where @mydiff is defined as a function like this (mydiff.m):
MATLAB Course - Part II: Modelling, Simulation and Control
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]
Example:
Given the differential equations:
In MATLAB you define a function for these 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!!
5 Using the ode45 function gives the following code: [t,y] = ode45(@mydiff, [-1,1], [1,1]); plot(t,y) title('solution of dy/dt=x and dx/dt=-y') legend('y', 'x') The equations are solved in the time span This gives the following plot:
):
Note! The function mydiff must return a column vector, thats why we need to transpose it. Then we use the ode solver to solve the differential equations (run_mydiff.m):
6
tspan = [-1,1]; x0 = [1,1]; [t,x] = ode45(@mydiff, tspan, x0); plot (t,x) legend('x1', 'x2')
Task 1:
Bacteria Population
In this task we will simulate a simple model of a bacteria population in a jar. The model is as follows:
Task 2:
Given the following system: where ,where is the time constant and as parameters, to make it easy to be able to change values
The function for the differential equation is: function dx = mysimplediff(t,x,param) % My Simple Differential Equation a = param(1); b = param(2); dx = a*x+b; Then we solve and plot the equation using this code: tspan = [0 25]; x0 = 1; a = -1/5; b = 1; param = [a b]; [t,y] = ode45(@mysimplediff, tspan, x0,[], param); plot(t,y) By doing this, it is very easy to changes values for the parameters code for the differential equation. and without changing the
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. The result from the simulation is:
Read more about the different solvers that exists in the Help system in MATLAB [End of Task]
Task 3:
ODE Solvers
Use the ode23 function to solve and plot the results of the following differential equation in the interval : ( Note! [End of Task] ) ( )
Task 4:
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 1: Reformulate the differential equation so Tip 2: Set: is alone on the left side.
[End of Task]
3 Numerical Techniques
In the previous chapter we investigated how to solve differential equations numerically, in this chapter we will take a closer look at some other numerical techniques offered by MATLAB, such as interpolation, curve-fitting, numerical differentiations and integrations.
3.1 Interpolation
Interpolation is used to estimate data points between two known points. The most common interpolation technique is Linear Interpolation. In MATLAB we can use the interp1 function.
Example:
Given the following data: x 0 1 2 3 4 5 We will find the interpolated value for The following MATLAB code will do this: x=0:5; y=[15, 10, 9, 6, 2, 0];
plot(x,y ,'-o')
y 15 10 9 6 2 0
% Find interpolated value for x=3.5 new_x=3.5; new_y = interp1(x,y,new_x) The answer is 4, from the plot below we see this is a good guess:
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') plot(x,y, new_x, new_y, '-o') The result is as we plot both the original point and the interpolated points in the same graph:
11
Numerical Techniques
Task 5:
Interpolation
Given the following data: Temperature, T [ oC] 100 150 200 250 300 400 500 Energy, u [KJ/kg] 2506.7 2582.8 2658.1 2733.7 2810.4 2967.9 3131.6
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? What is the interpolated value for u=2680.78 KJ/kg? [End of Task]
12
Numerical Techniques
Example
>>polyfit(x,y,1)
polyval
These techniques use a polynomial of degree N that fits the data Y best in a least-squares sense. A polynomial is expressed as: ( ) where are the coefficients of the polynomial.
MATLAB represents polynomials as row arrays containing coefficients ordered by descending powers.
3.2.1
Linear Regression
Example:
Given the following data: x y 0 15
MATLAB Course - Part II: Modelling, Simulation and Control
Numerical Techniques
We will use the polyfit function in MATLAB. The following code will solve it: x=[0, 1, 2, 3, 4 ,5]; y=[15, 10, 9, 6, 2 ,0]; n=1; % 1.order polynomial p = polyfit(x,y,n) The answer is: 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) This gives the following plot:
14
Numerical Techniques
We see this gives a good model based on the data available. [End of Example]
Task 6:
Linear Regression
Given the following data: Temperature, T [ oC] 100 150 200 250 300 400 500 Plot u versus T. Find the linear regression model from the data Energy, u [KJ/kg] 2506.7 2582.8 2658.1 2733.7 2810.4 2967.9 3131.6
15
Numerical Techniques
3.2.2
Polynomial Regression
In the previous section we used linear regression which is a 1.order polynomial. In this section we will study higher order polynomials. In polynomial regression we will find the following model: ( )
Example:
Given the following data: x y 0 15 1 10 2 9 3 6 4 2 5 0 We will found the model of the form: ( ) 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. We use a For loop in order to create models of 2, 3, 4 and 5.order. The code is as follows: x=[0, 1, 2, 3, 4 ,5]; y=[15, 10, 9, 6, 2 ,0]; for n=2:5 %From order 2 to 5 p=polyfit(x,y,n) ymodel=polyval(p,x); subplot(2,2,n-1) plot(x,y,'o',x,ymodel) title(sprintf('Model of order %d', n)); end The polyfit gives the following polynomials:
MATLAB Course - Part II: Modelling, Simulation and Control
16
p = 0.0536 p = -0.0648 p = 0.1875 p = -0.0417 0.7083 -4.2083 10.2917 -11.7500 -1.9398 6.2986 -9.4272 14.9802 0.5397 -4.0701 14.6587 -3.1821 14.4643
Numerical Techniques
15.0000
Using the values, we get the following models: ( ) ( ) ( ) ( ) This gives the following results:
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]
Task 7:
Polynomial Regression
Numerical Techniques
Use the polyfit and polyval functions in MATLAB and compare the models using different orders of the polynomial. Use subplots and make sure to add titles, etc. [End of Task]
Task 8:
Model fitting
Given the following data: Height, h[ft] 0 1.7 1.95 2.60 2.92 4.04 5.24 Flow, f[ft^3/s] 0 2.6 3.6 4.03 6.45 11.22 30.61
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]
( ) is:
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:
We will use Numerical Differentiation to find on the following function:
19 First, we will plot the data points together with the real function x=-2:0.1:2; y=x.^2; plot(x,y) hold on x=-2:2; y=x.^2; plot(x,y, '-oc') This gives the following plot:
We will use this to compare the results from the numerical differentiation with the exact solution. The code is as follows: 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
MATLAB Course - Part II: Modelling, Simulation and Control
20 -1 1 3 NaN -2 0 2 4
Numerical Techniques
Note! NaN is added to the vector with numerical differentiation in order to get the same length of the vectors. If we plot the derivatives (numerical and exact), we get:
[End of Example]
21
Numerical Techniques
Task 9:
Numerical Differentiation
Find
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 same plot. Increase number of data point to see if there are any difference. Do the same for the following functions: ( ) and the approximation in the
[End of Task]
3.3.1
Differentiation on Polynomials
( )
where
Example
Given the polynomial ( ) We can rewrite the polynomial like this: ( ) The polynomial is defined in MATLAB as:
22 >> p=[1, 0, 0, 2] We know that: The code is as follows >> p=[1, 0, 0, 2] p = 1 0 0 >> polyder(p) ans = 3 0 0 Which is correct, because ( ) with the coefficients:
Numerical Techniques
in MATLAB.
Task 10:
Differentiation on Polynomials
Task 11:
Differentiation on Polynomials
Find the derivative for the product: ( Use the polyder(a,b) function. 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. Try both methods, to see if you get the same answer. [End of Task]
MATLAB Course - Part II: Modelling, Simulation and Control
)(
23
Numerical Techniques
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: ( This is known as the trapezoid rule. We approximate the integral by using n trapezoids formed by using straight line segments between the points ( ) and ( ) for as shown in the gure below: ) ( )
The area of a trapezoid is obtained by adding the area of a rectangle and a triangle:
24 MATLAB offers functions for numerical integration, such as: Function diff quad Description
Difference and approximate derivative. DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. Numerically evaluate integral, adaptive Simpson quadrature. Q = QUAD(FUN,A,B) tries to approximate the integral of calar-valued function FUN from A to B. FUN is a function handle. The function Y=FUN(X) should accept a vector argument X and return a vector result Y, the integrand evaluated at each element of X. Uses adaptive Simpson quadrature method Same as quad, but uses adaptive Lobatto quadrature method Integrate polynomial analytically. POLYINT(P,K) returns a polynomial representing the integral of polynomial P, using a scalar constant of integration K.
>>
Numerical Techniques
Example
>> dydx_num=diff(y)./diff(x);
quadl polyint
>>
Example:
Given the function:
We know that the exact solution is: The integral from 0 to 1 is:
25
Numerical Techniques
We will use the trapezoid rule and the diff function in MATLAB to solve the numerical integral of from 0 to 1. The MATLAB code for this is: x=0:0.1:1; y=x.^2; avg_y = y(1:length(x)-1) + diff(y)/2; A = sum(diff(x).*avg_y) Note! The following two lines of code avg_y = y(1:length(x)-1) + diff(y)/2; A = sum(diff(x).*avg_y) Implements this formula, known as the trapezoid rule: ( The result from the approximation is: A = 0.3350 If we use the functions quad we get: quad('x.^2', 0,1) ans = 0.3333 If we use the functions quadl we get: quadl('x.^2', 0,1) ans = 0.3333 [End of Example] ) ( )
Task 12:
Numerical Integration
26 Find the integral of y with respect to x, evaluated from -1 to 1 Compare the different methods. The exact solution is: ( ( Compare the result with the exact solution. ) ( ) ( ) ( )| )
Numerical Techniques
[End of Task]
3.4.1
Integration on Polynomials
( )
where
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.
Task 13:
Integration on Polynomials
with respect to
) using MATLAB.
4 Optimization
Optimization is important in control and simulation applications. Optimization is based on finding the minimum of a given criteria function. In MATLAB we can use the fminbnd and fminsearch functions. We will take a closer look of how to use these functions. Function fminbnd Description
X = FMINBND(FUN,x1,x2) attempts to find a local minimizer X of the function FUN in the interval x1 < X < x2. FUN is a function handle. FUN accepts scalar input X and returns a scalar function value F evaluated at X. FUN can be specified using @. FMINBND is a single-variable bounded nonlinear function minimization. X = FMINSEARCH(FUN,X0) starts at X0 and attempts to find a local minimizer X of the function FUN. FUN is a function handle. FUN accepts input X and returns a scalar function value F evaluated at X. X0 can be a scalar, vector or matrix. FUN can be specified using @. FMINSEARCH is a multidimensional unconstrained nonlinear function minimization.
Example
>> x = fminbnd(@cos,3,4) x = 3.1416
fminsearch
Example:
Given the following function: ( ) We will use fminbnd to find the minimum of the function. We plot the function:
27
28
Optimization
We write the following MATLAB Script: x = -5:1:5; f = mysimplefunc(x); plot(x, f) x_min = fminbnd(@mysimplefunc, -5, 5) where the function (mysimplefunc.m) is defined like this: 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: ( ) ( ) ( )
29 We will use fminsearch to find the minimum of the function. The MATLAB Code can be written like this: [x,fval] = fminsearch(@myfunc, [1;1]) where the function is defined like this: function f = myfunc(x) f = 2*(x(1)-1).^2 + x(1) - 2 + (x(2)-2).^2 + x(2); Note! The unknowns x and y is defined as a vector, i.e., [ ] If there is more than one variable, you have to do it this way. This gives: x = 0.7500 1.5000 fval = 0.6250 The minimum is of the function is given by We can also plot the function: clear,clc [x,y] = meshgrid(-2:0.1:2, -1:0.1:3); 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); For figure 3 we get: and . ( ) ( )
Optimization
30
Optimization
[End of Example]
Task 14:
Optimization
Given the following function: ( ) Plot the function Find the minimum for this function [End of Task]
Task 15:
Optimization
This function is known as Rosenbrock's banana function. The function looks like this:
31
Optimization
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. Lets see if MATLAB can do the job for us.
Plot the function Find the minimum for this function [End of Task]
Here we will take a closer look at the Control System Toolbox. 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
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 Transfer Functions
It is assumed you are familiar with basic control theory and transfer functions, if not you may skip this chapter.
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. A general transfer function is on the form: ( ) Where is the output and is the input. ( ) ( )
First order Transfer Function: A first order transfer function is given on the form: ( ) there is the Gain is the Time constant 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: ( ) Where is the time-delay. ( ) ( )
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: Function tf pole Description
Creates system model in transfer function form. You also can use this function to state-space models to transfer function form. Returns the locations of the closed-loop poles of a system model.
Example
>num=[1]; >den=[1, 1, 1]; >H = tf(num, den) >num=[1] >den=[1,1] >H=tf(num,den) >pole(H)
36 zero step
Find the zeros Creates a step response plot of the system model. You also can use this function to return the step response of the model outputs. If the model is in state-space form, you also can use this function to return the step response of the model states. This function assumes the initial model states are zero. If you do not specify an output, this function creates a plot. Creates the linear simulation plot of a system model. This function calculates the output of a system model when a set of inputs excite the model, using discrete simulation. If you do not specify an output, this function creates a plot. Computes the convolution of two vectors or matrices. Connects two system models in series to produce a model SysSer with input and output connections you specify Connects two system models together to produce a closed-loop model using negative or positive feedback connections Convert from continuous- to discrete-time models Convert from discrete- to continuous-time models
Transfer Functions
lsim
>C1 = [1, 2, 3]; >C2 = [3, 4]; >C = conv(C1, C2) >Hseries = series(H1,H2) >SysClosed = feedback(SysIn_1, SysIn_2)
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
Task 16: Transfer function
and .
Use the tf function in MATLAB to define the transfer function above. Set Type help tf in the Command window to see how you use this function. Example: % Transfer function H=1/(s+1) num = [1]; den = [1, 1]; H = tf(num, den) [End of Task]
Second order Transfer Function: A second order transfer function is given on the form: ( ) ( )
37 Where is the gain zeta is the relative damping factor [rad/s] is the undamped resonance frequency.
Transfer Functions
Task 17:
Define the transfer function using the tf function. Set Plot the step response (use the step function in MATLAB) for different values of follows: . Select as
38 [End of Task]
Transfer Functions
Task 18:
Time Response
Given the following system: ( ) 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]
Task 19:
Integrator
The transfer function for an Integrator is as follows: ( ) Find the pole(s) Plot the Step response: Use different values for MATLAB. [End of Task] , e.g., . Use the step function in
Task 20:
1. order system
39 ( ) Find the pole(s) Plot the Step response. Use the step function in MATLAB. Step response 1: Use different values for Step response 2: Use different values for , e.g., , e.g., . Set . Set
Transfer Functions
[End of Task]
Task 21:
2. order system
The transfer function for a 2. order system is as follows: ( ) ( Where is the gain zeta is the relative damping factor [rad/s] is the undamped resonance frequency. )
Find the pole(s) Plot the Step response: Use different values for the step function in MATLAB. Tip! From control theory we have the following: , e.g., . Set and K=1. Use
40
Transfer Functions
So you should get similar step responses as shown above. [End of Task]
Task 22:
2. order system
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 ( ) ( ) ( ) ( ) ( )( )
41
Transfer Functions
Plot the Step response. Set K=1. Set , , function in MATLAB. [End of Task]
, ,
7 State-space Models
It is assumed you are familiar with basic control theory and state-space models, if not you may skip this chapter.
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. We have the following equations:
][
][
][
][
This gives the following compact form of a general linear State-space model:
Example:
42
43 Given the following equations: These equations can be written on the compact state-space form: [ ] [ [End of Example] ][ ] [ ]
State-space Models
[ ]
MATLAB have several functions for creating and manipulation of State-space models: Function ss Description
Constructs a model in state-space form. You also can use this function to convert transfer function models to state-space form. Creates a step response plot of the system model. You also can use this function to return the step response of the model outputs. If the model is in state-space form, you also can use this function to return the step response of the model states. This function assumes the initial model states are zero. If you do not specify an output, this function creates a plot. Creates the linear simulation plot of a system model. This function calculates the output of a system model when a set of inputs excite the model, using discrete simulation. If you do not specify an output, this function creates a plot. Convert from continuous- to discrete-time models Convert from discrete- to continuous-time models
Example
>A = [1 3; 4 6]; >B = [0; 1]; >C = [1, 0]; >D = 0; >sysOutSS = ss(A, B, C, D) >num=[1,1]; >den=[1,-1,3]; >H=tf(num,den); >t=[0:0.01:10]; >step(H,t);
step
lsim
c2d d2c
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]
44
State-space Models
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
Task 23: State-space model
Find the Step Response Find the transfer function from the state-space model using MATLAB code. [End of Task]
Task 24:
Mass-spring-damper system
Where c=damping constant, m=mass, k=spring constant, F=u=force The state-space model for the system is: [ ] [ ][ ] [ ]
45 [ ] Define the state-space model above using the ss function in MATLAB. Set , , (try also with other values to see what happens).
State-space Models
Apply a step in F (u) and use the step function in MATLAB to simulate the result. Find the transfer function from the state-space model [End of Task]
Task 25:
Block Diagram
Find the state-space model from the block diagram below and implement it in MATLAB.
Set
And b=1, c=1 Simulate the system using the step function in MATLAB [End of Task]
8 Discrete systems
It is assumed you are familiar with basic control theory and discretization of continuous systems, if not you may skip this chapter. You should know about transfer functions and state-space models.
For Simulation and Control in computers discrete systems are very important. Given the continuous linear state space-model:
MATLAB has several functions for dealing with discrete systems: Function c2d d2c Description
Convert from continuous- to discrete-time models. You may specify which Discretization method to use Convert from discrete- to continuous- time models
>>
Example
>>c2d(sys,Ts) >>c2d(sys,Ts,tustin)
Before you start, you should use the Help system in MATLAB to read more about these functions. Type help <functionname> in the Command window.
Task 26:
Discretization
46
47 [ ] [ ][ ] [ ]
Discrete systems
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: where is the sampling time.
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.
Task 27:
Discrete Simulation
In this task we will simulate a simple model of a bacteria population in a jar. The model is as follows:
48
Discrete systems
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 Frequency Response
In this chapter we assume that you are familiar with basic control theory and frequency response from previous courses in control theory/process control/cybernetics. If not, you may skip this chapter.
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 ( ). If we have the input signal: ( ) The steady-state output signal will be: ( ) Where steady-state). ( )
is the ratio between the amplitudes of the output signal and the input signal (in
A and
( )
( )
49
50 ( ) We have that: ( ) | ( )|
( )
Frequency Response ( ) ( )
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 Gain function: ( ) The Phase function: ( ) The The ( ) | ( )|
( )-axis is in decibel (dB), where the decibel value of x is calculated as: ( )-axis is in degrees (not radians!)
MATLAB have several functions for frequency response: Function bode Description
Creates the Bode magnitude and Bode phase plots of a system model. You also can use this function to return the magnitude and phase values of a model at frequencies you specify. If you do not specify an output, this function creates a plot. Creates the Bode magnitude plot of a system model. If you do not specify an output, this function creates a plot. Calculates and/or plots the smallest gain and phase margins of a single-input single-output (SISO) system model. The gain margin indicates where the frequency response crosses at 0 decibels. 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.
Example
>num=[4]; >den=[2, 1]; >H = tf(num, den) >bode(H) >[mag, wout] = bodemag(SysIn) >[mag, wout] = bodemag(SysIn, [wmin wmax]) >[mag, wout] = bodemag(SysIn, wlist) >num = [1] >den = [1, 5, 6] >H = tf(num, den) margin(H)
bodemag
margin
Example: Here you will learn to plot the frequency response in a Bode diagram.
51 ( ) ( ) ( )
Frequency Response
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. % Transfer function H=1/(s+1) num=[1]; den=[1, 1]; H = tf(num, den) bode (H); The Bode 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
Task 28: 1. order system
52 What is the break frequency? Set up the mathematical expressions for Assignment. ( ) and
Frequency Response
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 Make sure ( ) is in dB. ( )( )
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]
Task 29:
Bode Diagram
We have the following transfer function: ( ) What is the break frequencies? Set up the mathematical expressions for Assignment. ( ) and ( ). Use Pen & Paper for this ( ( )( ) )
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]
53
Frequency Response
( ): ( ) is defined as follows: ( )
Where is the Controller transfer function is the Process transfer function is the Measurement (sensor) transfer function Note! Another notation for is
( ): ( ) is defined as follows: ( ) ( ) ( ) ( ) ( )
The Tracking Property is good if the tracking function T has value equal to or close to 1: | |
MATLAB Course - Part II: Modelling, Simulation and Control
Frequency Response
( )
The Compensation Property is good if the sensitivity function S has a small value close to zero: | | Note! ( ) ( ) ( ) ( ) | |
( )
Frequency Response Analysis of the Tracking Property: From the equations above we find: The Tracking Property is good if: | ( The Tracking Property is poor if: | ( )| )|
55
Frequency Response
are defined:
crossover-frequency the frequency where the gain of the Loop transfer function the value:
) has
- the frequency where the gain of the Sensitivity transfer function ( ) has the value:
Task 30:
Where
, where
Where
Set Kp = 1,5 og Ti = 1000 sec. Define the Loop transfer function function ( ) and in MATLAB. ( ), Sensitivity transfer function ( ) and Tracking transfer
56
Frequency Response
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. Find the bandwidths from the plot above.
Plot the step response for the Tracking transfer function [End of Task]
( )
The Phase Margin - PM ( ) is how much the phase lag function of the loop can be reduced before the loop becomes unstable.
57 Where:
Frequency Response
Note!
(gain margin frequency - gmf) is the gain margin frequency/frequencies, in radians/second. A gain margin frequency indicates where the model phase crosses -180 degrees. GM ( ) is the gain margin(s) of the system. (phase margin frequency - pmf) returns the phase margin frequency/frequencies, in radians/second. A phase margin frequency indicates where the model magnitude crosses 0 decibels. PM ( ) is the phase margin(s) of the system. and are called the crossover-frequencies
The definitions are as follows: Gain Crossover-frequency : | ( Phase Crossover-frequency : ( Gain Margin - GM ( ):
| ( )|
)|
or: | ( Phase margin PM ( ): ( We have that: Asymptotically stable system: Marginally stable system: Unstable system: ) )|
We use the following functions in MATLAB: tf, bode, margins and margin.
Task 31:
Stability Analysis
Frequency Response
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]
10 Additional Tasks
If you have time left or need more practice, solve the tasks below.
Task 32:
ODE Solvers
Use the ode45 function to solve and plot the results of the following differential equation in the interval : ( ) [End of Task]
Task 33:
Mass-spring-damper system
Where c=damping constant, m=mass, k=spring constant, F=u=force The state-space model for the system is: [ ] 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 [End of Task]
Additional Tasks
Task 34:
Numerical Integration
Find the work produced in a piston cylinder device by solving the equation: Assume the ideal gas low applies:
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]
61
Additional Tasks
Task 35:
State-space model
The following model of a pendulum is given: where m is the mass, r is the length of the arm of the pendulum, g is the gravity, b is a friction coefficient. Define the state-space model in MATLAB Solve the differential equations in MATLAB and plot the results. Use the following values [End of Task]
Task 36:
lsim
Where c=damping constant, m=mass, k=spring constant, F=u=force The state-space model for the system is: [ ] [ ][ ] [ ]
[ ] Simulate the system using the lsim function in the Control System Toolbox. Set c=1, m=1, k=50.
MATLAB Course - Part II: Modelling, Simulation and Control
62 [End of Task]
Additional Tasks
Interpolation
MATLAB offers functions for interpolation, e.g.: Function interp1 Description Example
Curve Fitting
Here are some of the functions available in MATLAB used for curve fitting: Function polyfit Description
P = POLYFIT(X,Y,N) finds the coefficients of a polynomial P(X) of degree N that fits the data Y best in a least-squares sense. P is a row vector of length N+1 containing the polynomial coefficients in descending powers, P(1)*X^N + P(2)*X^(N-1) +...+ P(N)*X + P(N+1). Evaluate polynomial. Y = POLYVAL(P,X) returns the value of a polynomial P evaluated at X. P is a vector of length N+1 whose elements are the coefficients of the polynomial in descending powers. Y = P(1)*X^N + P(2)*X^(N-1) + ... + P(N)*X + P(N+1)
Example
>>polyfit(x,y,1)
polyval
63
64
Numerical Differentiation
MATLAB offers functions for numerical differentiation, e.g.: Function diff polyder Description
Difference and approximate derivative. DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. Differentiate polynomial. POLYDER(P) returns the derivative of the polynomial whose coefficients are the elements of vector P. POLYDER(A,B) returns the derivative of polynomial A*B.
Example
>> dydx_num=diff(y)./diff(x); >>p=[1,2,3]; >>polyder(p)
Numerical Integration
MATLAB offers functions for numerical integration, such as: Function diff quad Description
Difference and approximate derivative. DIFF(X), for a vector X, is [X(2)-X(1) X(3)-X(2) ... X(n)-X(n-1)]. Numerically evaluate integral, adaptive Simpson quadrature. Q = QUAD(FUN,A,B) tries to approximate the integral of calar-valued function FUN from A to B. FUN is a function handle. The function Y=FUN(X) should accept a vector argument X and return a vector result Y, the integrand evaluated at each element of X. Uses adaptive Simpson quadrature method Same as quad, but uses adaptive Lobatto quadrature method Integrate polynomial analytically. POLYINT(P,K) returns a polynomial representing the integral of polynomial P, using a scalar constant of integration K.
>>
Example
>> dydx_num=diff(y)./diff(x);
quadl polyint
>>
Optimization
MATLAB offers functions for local minimum, such as: Function fminbnd Description
X = FMINBND(FUN,x1,x2) attempts to find a local minimizer X of the function FUN in the interval x1 < X < x2. FUN is a function handle. FUN accepts scalar input X and returns a scalar function value F evaluated at X. FUN can be specified using @. FMINBND is a single-variable bounded nonlinear function minimization. X = FMINSEARCH(FUN,X0) starts at X0 and attempts to find a local minimizer X of the function FUN. FUN is a function handle. FUN accepts input X and returns a scalar function value F evaluated at X. X0 can be a scalar, vector or matrix. FUN can be specified using @. FMINSEARCH is a multidimensional unconstrained nonlinear function minimization.
Example
>> x = fminbnd(@cos,3,4) x = 3.1416
fminsearch
65
Example
>X = [0:0.01:1]; >Y = X.*X; >plot(X, Y) >num=[1]; >den=[1, 1, 1]; >H = tf(num, den) >num=[1] >den=[1,1] >H=tf(num,den) >poles(H) >num=[1,1]; >den=[1,-1,3]; >H=tf(num,den); >t=[0:0.01:10]; >step(H,t);
lsim
>C1 = [1, 2, 3]; >C2 = [3, 4]; >C = conv(C1, C2) >Hseries = series(H1,H2) >SysClosed = feedback(SysIn_1, SysIn_2) >A = eye(2) >B = [0; 1] >C = B' >SysOutSS = ss(A, B, C) >num=[4]; >den=[2, 1]; >H = tf(num, den) >bode(H) >[mag, wout] = bodemag(SysIn) >[mag, wout] = bodemag(SysIn, [wmin wmax]) >[mag, wout] = bodemag(SysIn, wlist) >num = [1] >den = [1, 5, 6] >H = tf(num, den) margin(H)
bodemag
margin
margins
c2d d2c
Telemark University College Faculty of Technology Kjlnes Ring 56 N-3918 Porsgrunn, Norway www.hit.no
Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics