You are on page 1of 19

MatLab Tutorial

Introduction to Control Systems


MAEG3050
Patricia Piroska Grof

22/09/2014

Email: ppgrof@mae.cuhk.edu.hk

Contents
1 What is MATLAB? 2

2 How to obtain MATLAB? 2

3 The main parts of MatLab 2

4 Data structures 3
4.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Vectors and Arrays . . . . . . . . . . . . . . . . . . . . . . . . 4
4.3 Character string . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.4 Matrix arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
4.5 Element-by-element matrix operations . . . . . . . . . . . . . 5
4.6 Cell arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.7 Complex numbers . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.8 Checking existing variables . . . . . . . . . . . . . . . . . . . 6

5 Functions 7
5.1 Built-in functions . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.2 User-defined functions . . . . . . . . . . . . . . . . . . . . . . 7

6 Graphs 8
6.1 Basic plotting . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.2 Multiple plot . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

7 Help and supporting toolboxes 10

1
8 Control system toolbox 10
8.1 Transfer function . . . . . . . . . . . . . . . . . . . . . . . . . 10
8.2 Control systems and their design . . . . . . . . . . . . . . . . 11

9 Simulink 13
9.1 Block diagramm . . . . . . . . . . . . . . . . . . . . . . . . . 13
9.2 Example: simulating the motion of a pendulum . . . . . . . . 14

10 Conclusion 18

1 What is MATLAB?
The meaning of the word MATLAB is Matrix Laboratory, as it sup-
ports array (matrix) type data structures. MATLAB is a high-level language
and interactive environment for numerical computation, visualization, and
programming. Using MATLAB, you can analyze data, develop algorithms,
create models and applications. In this way it is suitable to write user defined
functions using the the built-in functions for solving complex mathematical
problems such us numerical simulations of ordinary differential equations or
operations with big data and so on. The aim of this tutorial to introduce
the basic concept and application possibilities of this program via various
examples.

2 How to obtain MATLAB?


You may download the trial version or purchase the student version from
the official website of MATLAB: www.mathworks.com. First, registration is
necessary to create an account. MATLAB is available on Windows, Mac OS
X and Linux. You are welcome to use it for free at ERB 218.

3 The main parts of MatLab


Start the program by clicking on the MATLAB icon. Now you may see
the following parts:

– Command Window
We can write here commands (in the command line), define variables,
or call any of the existing functions

– Editor
We can write here a whole script or create our own functions using
various built-in functions and save it in a ’.m’ file.

2
Figure 1: Command Window

– Current Folder
Inform us about the content of the folder where we are working in.
Before we start writing the script, we need to make sure we are in the
right folder to save the files. Best way is to create a working folder
we start to work, set this folder as Current Folder, so we save here
everything immediately.

– Command History
Stores all commands we typed in the Command Window. We recall the
these commands by pressing the ’up’ button on the keyboard while the
cursor is in the command line.

– Workspace or Workspace Editor


We can see or edit the existing variables defined by us. Variables can
be saved in a ’.dat’ file.

4 Data structures
MATLAB supports array structures, it stores the elements automatically
in double precision floating points (double), however the user can define other
data types:

help datatypes

3
Figure 2: Editor

4.1 Variables
We can define the variables as follows:
a=.132456;
b=1e5;
b
b=
100000
When we type without ’;’, MATLAB lists the variable name and its value in
Command Window.

4.2 Vectors and Arrays


Examples for creating variables:
A=[1 2 3]
A=
1 2 3 A’
creates the transpose of A.
A(3)
shows the 3rd element of A.
Try the following commands:
t1=0:10:100
t2=linspace(0,100,11)
length(t1)
length(t2)

4
4.3 Character string
We can store characters in variables:
S= ’I am a student in CUHK’
S=
I am a student in CUHK
S(4)
lists the 4th character, which is m in our case.

4.4 Matrix arrays


We enter the matrices denoting with operator ’;’, if a new row starts:
B=[1 2 3; 4 5 6; 7 8 9]
B=
1 2 3
4 5 6
7 8 9
Indexing matrices: (n,m)
where n = the index number of nth row and m = the index number of mth
column.
For example, try the following codes:
B(2,2)
B(:,2)
B(1:2,1:2)
B(2:3,:)
Please note that the operator ’:’ is suitable for referring multiple elements,
or the whole row, or the whole column.
B(2,:)=[ ];
This command deletes the 2nd row of matrix B. You may check the size of
the matrix, B:
size(B)
Here are some examples for special matrices:
Z=zeros(1,2)
E=eye(5)
O=ones(3)
D=diag([3,2,1])

4.5 Element-by-element matrix operations


• Addition +

• Subtraction −

5
• Multiplication .*

• Division ./

• Exponentiation .∧

4.6 Cell arrays


We may use cell arrays, to store data having different types. We can store
string type data as well in this type of array.

C1={a}

C1 =

[0.1325]

C2=cell(1,3)

creates a 1 x 3 size cell array.

C2{1}=S
C2 =

[1x22 char] [] []

4.7 Complex numbers



In MATLAB both "i" and "j" is available for representing −1. Type
the folliwngs:

c1=1+2i;

c2=(1+2i)*(3+4j)

c2 =

-5.0000 +10.0000i

4.8 Checking existing variables


We may check our variables in use in Workspace, however we can use
following commands to list them in the Command Window:
who
whos

6
The last one lists also the properties of the used variables.
clear all
clears all the variables which are in use.
clc
clears the command window.

5 Functions
Arithmetic expressions often require computations other than addition,
subtraction, multiplication, division, and exponentiation, e.g., many expres-
sions require the use of logarithms, exponentials, and trigonometric func-
tions.

5.1 Built-in functions


MATLAB has several built-in functions, for example:
• abs(x) - absolute value of variable x
• sqrt(x) - square root of variable x
• round(x) - rounded value of of variable x
• sign(x) - signum function x
• exp(x) - ex
• log(x) and log10(x) - is the natural and the base 10 logarithm of variable
x
• sin(x) - sinus function
• cos(x) - cos function
• dot(X,Y) - dot product of X and Y matrix also: sum(X.*Y)

5.2 User-defined functions


We do have the opportunity to create custom functions. First, we have
to write the script in a ’.m’ file in the Editor, then we can call it in the
Command Window.
Let us write a function, which calculates the roots of the quadratic function
with well known formula (1).

−b ± b2 − 4 · a · c
(1)
2·a
The file, which has to hold the name ’quad’ (because we name the function
quad as well) is as follows:

7
function [root1,root2]=quad(a,b,c)
D = b2 -4*a*c;
root1 = (-b+sqrt(D))/2/a;
root2 = (-b-sqrt(D))/2/a;
where a,b,c are coefficients of the quadratic function, root1 and root2 are the
solutions of the function. ’sqrt’ calculates the square root.
Let us solve the following qudratic function:
x2 + 3x + 2 = 0 (2)
Type to the Command Window:

a=1; b=3; c=2;


[root1,root2]=quad(a,b,c)

Our function ’quad’ gives us the solution of (2). The roots are -1 and -2.

6 Graphs
We can plot nice figures in MATLAB. We use the ’plot’ function to create
the plot. In this section we deal with 2D plotting, but MATLAB can plot
3D figures, too.

6.1 Basic plotting


Let us plot the Eq. (2):

figure(1)

The figure will appear in a new window called Figure.

x=linspace(-4,1,50);

We create a 50 element vector from -4 to 1.

y=a* x .2 +b*x+c;

We calculate the y value in every point.

If there is a ’.’ before the sign of the operation, it means the operation is
going to be executed element-by-element.

plot(x,y)
We call the ’plot’ function. The elements of x concern the horizontal axis,
the elements of y concern the vertical axis.

8
6.2 Multiple plot
xlabel(’x’)
ylabel(’y’)
title(’Multiple plot’)
Let us give the label ’x’ for the horisontal, and ’y’ for the vertical one, and let
us give the name ’Multiple plot’ for the whole figure utilizing ’title’ command.
grid on
We turn the grid lines on in the figure.
hold on
We keep the figure window switched on to plot there more functions in the
following way:
plot(x,sin(x),’mx-’,x,cos(x),’co-’)
We call the functions ’sin’ and ’cos’ to calculate sine and cosine of x in every
point. We can define different line colors, different markers and different line
types as well. For further information, please browse Help menu for Line
Properties.
hold off
We finished plotting in the figure window.
The three figures can be seen now in one figure, see Figure 3.
Multiple plot
6

3
y

−1
−4 −3 −2 −1 0 1
x

Figure 3: The three functions

9
7 Help and supporting toolboxes
MATLAB has a so called in-screen help system. If we type

help

it lists the available toolboxes in the Command Window. A toolbox con-


tains a set of pre-written functions to use them for different purposes. For
example:

help control

lists the existing functions in control system toolbox.

help tf

gives us information about creating transfer functions via tf function. We


can also browse the Help menu online.

8 Control system toolbox


We will use frequently the functions defined in this toolbox. Let us see
some example of the possible applications.

8.1 Transfer function


We can represent polynomials, by typing their coefficients. For example:

s2 + 2s + 3 (3)

s+1 (4)
A1=[1, 2, 3];
B1=[1, 1];
Let us name A1 and B1 the two vectors of coefficients ot the two polynomi-
als.
C1=conv(A1,B1);
printsys(B1,C1)
num/den =
s+1
———————
s3 + 3 s2 + 5 s + 3
We can easily expand the polynomial by taking convolution between the vec-
tors representing the 2 polynomial (3) and (4) factors, using the command
’conv’. The other command, ’printsys’ prints the system with numerator B1

10
and denumerator C1.
We can create directly transfer functions with the ’tf’ function:
num=1;
den=[1 1 1];
sys=tf(num,den);
[r,p,k]=residue(num,den)
r=
0 - 0.5774i
0 + 0.5774i
p=
-0.5000 + 0.8660i
-0.5000 - 0.8660i
k=
[]
The ’residue’ function calculates the residues ’r’, the poles ’p’ and the direct
term ’k’.
From the transfer function we can formulate the State Space (SS) model (5):

ẋ(t) = Ax(t) + Bu(t) (5)


y(t) = Cx(t) + Du(t)
[A B C D]=tf2ss(num,den)
eig(A)
ans =
-0.5000 + 0.8660i
-0.5000 - 0.8660i
The expression ’eig(A)’ calculates the poles of the system. We can compare
easily that we have now the same poles, like we calculated them before using
’residue’ function.

8.2 Control systems and their design


We can calculate and plot the step response of our system by the function
called ’step’:
[y,t] = step(sys);
figure(2)
plot(t,y)
axis tight
xlabel(’t’)
ylabel(’y(t)’)
grid on
The variable ’t’ denotes the time, and ’y’ contains the response values of
the system in every time point. The trajectory of system is shown in Figure

11
1

0.8

0.6
y(t)

0.4

0.2

0
0 2 4 6 8 10
t

Figure 4: Step response

4. The function ’impulse’ works similarly.

Finally, let us print the Bode (’bode’) diagram, see Figure 5, and the
Nyquist (’nyquist’) diagram, see Figure 6, and calculate the gain (’Gm’) and
phase (’Pm’) margin and the corresponding frequencies. For this purpose, we
use the ’margin’ function:
figure(3)
bode(sys)
grid on
figure(4)
nyquist(sys)
grid on

[Gm,Pm,Wcg,Wcp] = margin(sys)
Gm =
Inf
Pm =
90
Wcg =
Inf
Wcp =
1.0000

12
Bode Diagram
20

0
Magnitude (dB)

−20

−40

−60

−80
0

−45
Phase (deg)

−90

−135

−180
−2 −1 0 1 2
10 10 10 10 10
Frequency (rad/s)

Figure 5: Bode diagram

The term ’Inf’ means that the value is infinite. That is because the phase
curve never will reach the value -180 degree. See Figure 5. Sometimes the
resulting value is ’NaN’, which means the calculated value is Not a Number.

9 Simulink
Simulink is an extension to MATLAB that allows engineers to rapidly
and accurately build computer models of dynamic physical systems using
block diagram notation. We may simulate linear and nonlinear systems,
continuous-time and discrete-time components furthermore graphical ani-
mations are possible to create.

9.1 Block diagramm


• A block diagram of a system is a pictorial representation of the func-
tions performed by each component and of the flow of signals. It de-
scribes a set of relationships that hold simultaneously.

• A block diagram contains information concerning dynamic behavior,


but it does not include any information on the physical construction
of the system.

13
Nyquist Diagram
1.5
2 dB 0 dB −2 dB

−4 dB
1
4 dB
−6 dB
6 dB
0.5
10 dB −10 dB
Imaginary Axis

20 dB −20 dB
0

−0.5

−1

−1.5
−1 −0.5 0 0.5 1 1.5
Real Axis

Figure 6: Nyquist diagram

• Many dissimilar and unrelated systems can be represented by the same


block diagram.

• A block diagram of a given system is not unique.

9.2 Example: simulating the motion of a pendulum

Figure 7: The diagram of the simple pendulum system

In this section we build the block diagram step by step of a pendulum

14
according to [1]. The scheme of the model is as follows (Figure 7):
d2 φ
mR2 + mgR sin φ = 0
dt2
Let us recall the dynamics of a simple pendulum with length R and mass m.
The equation of mottion is as follows:
d2 φ dφ
mR2 +η + mgR sin φ = 0 (6)
dt2 dt
If a torque N is applied on a stacionary pendulum it will swing out
through the angle φ. The damping force Fdamp = ηω. To overwrite the dif-
ferential equation above, we add the damping torques. Where η is a damping
ratio.
Data:
m = 0.07 kg,
R = 0.3 m,
η = 0.003.
1. Launch Simulink. See Figure 1 and click on Simunlink Library icon
on the middle-top.

Figure 8: Simulink Library Browser

2. Create a new model. There is a new model icon in the left-top of


Figure 8.

15
Figure 9: New Simulink model

3. Insert and wire blocks. From Simulink library browser (Figure 8)


pull blocks to the workspace (Figure 9).
• Fcn Block from the Simulink/User-Defined Functions library and
define the function (Figure 10) using Eq. (6)

Figure 10: Fcn Block settings

• two Integrator blocks from the Simulink/Continuous library


• Scope block from Simulink/Sinks
• MUX block from Simulink/Commonly used blocks library
IMPORTANT: Do not forget to save your file! If you are working
with multible files, always save them to the same folder.

16
Figure 11: Block diagram of the pendulum

4. Double check if every block is set. Make sure that the initial
condition of the 2 integrator is set, like in Figure 12:

Figure 12: Two Integrator block settings

5. Add pendulum animation function. Simulink comes with a pen-


dulum animation function called pndanim1.m. S- Function blocks al-
low you to call a Matlab function from your model. So let?s bring
an S-Function block into our workspace (located under User-Defined

17
Functions). Double click on the block and enter in pndanim1 in the
S-Function Name box. Also enter in ts for the S-Function parameter
(ts, or the sampling time, is the argument taken by the pndanim1
function) and hit OK. Highlight the S-Function block and create a
subsystem (Ctrl + G). Double-click on the subsystem and delete the
Out1 block since we will not need it. Then right click and Add Mask.
Add ts parameter: Double-click on the subsystem block and enter in a

Figure 13: Adding ts parameter to Mask settings

sampling time of 0.005 seconds. The subsystem takes a vector input.


To create a vector input, we need to Mux the two signals. Bring Con-
stant and MUX blocks into the workspace. Route the signals so your
model looks like the one in Figure 11.

6. Set simulation parameters. Click Simulation/Model configuration


parameters, and make sure the values are the same like in Figure 14.

7. Run simulation. Check the Scope for the trajectory.

10 Conclusion
This is a very brief introduction to MATLAB. You may be interested in
learning more, please check http://www.mathworks.com/academia/students.
html?s_tid=acmain_sp_gw_bod, http://ctms.engin.umich.edu/CTMS/index.
php?aux=Home and https://www.facebook.com/MATLAB

18
Figure 14: Configuration of parameters

References
[1] Herbert Goldstein. Classical mechanics, volume 4. Pearson Education
India, 1962.

19

You might also like