Introduction To MATLAB Simulink
Introduction To MATLAB Simulink
HT2022
Preface
This text began as a handful of pages, highlighting a few useful commands for system
modelling and control design in Matlab. Since then, it has grown several times its original
size, with several additional chapters on advanced topics, and the language gradually
taking on a tone suitable for a comprehensive tutorial.
Despite this, the purpose of this document has remained the same – to serve as a handbook
to getting started with Matlab, understanding core concepts, producing high-quality fig-
ures, using the numeric LTI models included in the Control System Toolbox, and graphical
programming in Simulink. The idea is to serve as a tutorial on using the above mentioned
tools within the scope of simulation and control of dynamic systems. Small stand-alone
exercises are integrated into the reading material to assist the learning process.
This text has been tailored to support the courses given by the Department of Machine
Design at KTH Royal Institute of Technology, but will likely be useful in a larger scope, and
can be distributed freely without the author’s consent.
Prerequisites: This is not meant to be an introduction to programming, it is assumed
that the reader has knowledge in basic programming and computer science, numerical
methods, and algebra. For the chapters on dynamic systems modelling, basic knowledge in
automatic control (sometimes designated “signals and systems”) is strongly recommended.
Having worked in Matlab previously is not a requirement, but will be beneficial, in which
case the first chapters may be repetition.
ii
Acknowledgements
Some sections of this text are based on the tutorials Einführung in MATLAB and Einführung in
Simulink, originally written for the course Regelungstechnisches Labor, held by the Institute
of Automatic Control (IRT) at RWTH Aachen University in Aachen, Germany during the
summer of 2017. The author of this document would like to thank Prof. Dirk Abel and his
staff at the IRT for providing such excellent tutorials in the German language.
The opening sections on Simulink, including the material on running a demo model are
adapted from an older text from the Department of Machine Design.
Finally, the author would like to express heartfelt gratitude to all the people who helped
test the material, and gave their feedback and support.
iii
Contents
1 Introduction 1
2 Fundamentals 2
2.1 Introducing the desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 The command line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.1 Suppressing output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.2 Input history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.3 Auto-completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2.4 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.5 Aborting commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.6 Unquoted strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2.7 Housekeeping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.1 Creating new scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.2 Sectioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3.3 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
iv
3.6 Structure arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.6.1 Dot-notation and nested structures . . . . . . . . . . . . . . . . . . . . 16
3.6.2 Indexing structure arrays . . . . . . . . . . . . . . . . . . . . . . . . . 16
4 Structured programming 17
4.1 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
4.1.1 Writing your own functions . . . . . . . . . . . . . . . . . . . . . . . . 17
4.1.2 Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.2 Conditional statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.2.1 if, elseif, else . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
4.2.2 switch, case, otherwise . . . . . . . . . . . . . . . . . . . . . . . . 19
4.2.3 try, catch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.3 Loops and iterations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
4.3.1 while . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.3.2 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
4.4 Control statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
v
7.1.2 Zero-pole-gain models . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
7.1.3 State-space models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
7.1.4 PID controller models . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7.2 Interconnecting dynamic systems . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.2.1 Parallel connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.2.2 Series connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
7.2.3 Feedback connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.3 Linear analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
7.3.1 Time-domain analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7.3.2 Frequency-domain analysis . . . . . . . . . . . . . . . . . . . . . . . . 39
7.3.3 Pole-zero analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
9 Simulink 50
9.1 Motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.2 Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
9.2.1 Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
9.2.2 Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
9.2.3 Running a simple example . . . . . . . . . . . . . . . . . . . . . . . . 53
9.3 Solver configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
9.3.1 Fixed-step methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
9.3.2 Variable-step methods . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
9.3.3 Stiff systems of equations . . . . . . . . . . . . . . . . . . . . . . . . . 55
9.3.4 Discrete solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
9.3.5 Automatic selection by Simulink . . . . . . . . . . . . . . . . . . . . . 56
9.4 Studying a demo model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
9.4.1 Coordinate transforms . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
9.4.2 Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
9.4.3 Simulation resuls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
9.5 Creating your first dynamic model . . . . . . . . . . . . . . . . . . . . . . . . 61
9.5.1 Walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
9.5.2 Partitioning the Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
vi
9.6 Matlab integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
9.6.1 Exporting outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
9.6.2 To Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
9.6.3 Running simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
9.6.4 Single simulation output . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
9.7 Dynamic system models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.7.1 The Transfer Fcn block . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
9.8 Closing words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Solutions to exercises 72
Elementary mathematics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Vectors and matrices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
The Control System Toolbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Discrete-time systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Simulink-Matlab integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Appendix 80
Creating a publication-quality Figure . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Custom linear analysis plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
vii
1 Introduction
Matlab is one of the most widely used languages for scientific programming and numerical
computation, with over 3 million users worldwide. Typical applications include, but are not
limited to data analytics, deep learning, signal processing, robotics, and control systems.
It is an interactive language, meaning that it will execute commands directly, without
first being compiled into machine code. The fundamental datatypes are double-precision
floating point matrices (Matlab stands for MATrix LABoratory). This is one of the reasons
that it performs so well in the domain of numerical computing.
“Matlab” also refers to the application itself, which is required to run code written in the
language. It is an Integrated Development Environment (IDE) that can handle all necessary
aspects of developing sophisticated applications in the Matlab language. In addition to
the interactive command line, it provides tools for graphical drawing and writing your own
scripts and functions, to name a few features. This tutorial will focus on both the language,
regarding syntax and semantics, and the IDE itself.
Simulink is a graphical user interface that sits on top of the Matlab engine and simplifies the
modeling and simulation of complex dynamical systems. The necessary matrix calculations
are performed by Matlab in the background, automatically. Both products are proprietary
(non-free) and are developed and maintained by the US-based company MathWorks, Inc.
Please note: The tutorial is written with MATLAB R2021a in mind. In the case that you
are working with another version, some functions may behave differently, and some menus
and dialogues might have a different appearance.
In addition to the core packages Matlab and Simulink, you will need to have the following
packages installed for this tutorial
• Control System Toolbox (Chapters 7+)
• System Identification Toolbox (Chapter 8)
When installing Matlab, it is suggested that you include all packages, if you have the
capacity.
1
2 Fundamentals
• Current Folder – Access the files and folders in the current working directory
• Command Window – Enter commands at the command line, more on this later
• Workspace – Explore variables and data that you create or import
2
2 Fundamentals
The last line will trigger one of the most common error messages:
Error: Invalid expression ...
Matlab will sometimes try to help you find the cause of your problems. Try correcting the
command according to the advice you get, and see if you eliminate the error.
2.2.3 Auto-completion
Finally, to speed things up in the future, it is convenient to use Tab to auto-complete
your typed commands. Test this by creating a variable that shares your name, and is equal
to your age (in years). Now start typing the first 2-3 letters of your name in the command
line, then press to complete the rest. Depending on your name, it may prove more
or less useful, but for structured variable names such as motorModelLinearSimplified it
may help. Note that it will look for completions among the default functions and variable
names, including other toolboxes that are installed on your system.
3
2 Fundamentals
2.2.4 Documentation
Oftentimes, you will need to look up a function to see exactly what syntax it uses, which
input arguments are needed, or what to expect it to return. To facilitate this, the documen-
tation for functions can be accessed through the command line directly. Try the following
commands
>> help cos
>> help linspace
>> doc linspace
>> lookfor cosine
The command lookfor searches through the first line of all documentation contained in
the search path, to try to find any and all matches for the query. Searching through the
documentation may sometimes take longer than you wish for, and the Matlab window
will be unresponsive while this happens.
Based on the error message you receive, you might be able to deduce what is happening.
If you write unquoted strings in Matlab, it will parse the first word as the function, and
any additional words separated by spaces as separate input arguments. By using single
apostrophes, you can forcefully tie together strings of letters.
It should be said that when writing scripts, it is considered good practice to explicitly use
brackets when calling functions to improve readability.
2.2.7 Housekeeping
You can tidy up in Matlab using the following commands
>> clear all % Clear all variables from the Workspace
>> clc % Clear the Command Window
4
2 Fundamentals
2.3 Scripts
When you wish for several commands to be performed successively, you can write your
Script, also sometimes called M-Files because of their “.m” ending.
When running a script, all variables defined in the (base) Workspace will be available to
it, and conversely, all new data created by your script will be stored there as well. These
variables are said to be in the global scope. This is a significant difference when compared
to Matlab functions, which are addressed in Section 4.1. Functions, unlike scripts, each
have their own scope and are not able to access the Workspace directly.
This will open the Editor window, which will appear above the Command Window. The
Editor has syntax highlighting, supports debugging, and enables formatting code using
the right-click context menu.
Observe that the Toolstrip now has a new tab, labeled “EDITOR”, providing additional
tools for code formatting. Once you have populated your script with the command you
want to run, you can click “Run” in the Toolstrip, or F5 . This will prompt you to save your
script somewhere, and the file is saved every time you run it this way.
Create a new script, and write the following in the Editor
% My first script
cd
disp('This is my first script ')
a = 6*7
b = 6*7;
Save it as “myScript1.m”.
Then try the following commands in the command line
>> myScript1
>> help myScript1
2.3.2 Sectioning
For long scripts, it can sometimes be efficient to divide the code into Sections, which helps
break down the code both visually but also enables running parts of it at a time.
This is done by inserting Cell Dividers (%%) above the parts you want to section. The section
where the line marker is currently in will also be highlighted in yellow. Sectioning allows
for quick traversal through your code by using the keyboard combinations Ctrl + and
Ctrl + .
5
2 Fundamentals
You can run the current section (without saving) with Ctrl + . This will also ignore any
Breakpoints in the code, which will be explained in the next section.
2.3.3 Debugging
When you want to assure yourself of what is happening in the code, you can place Break-
points in the code, by clicking the line number in the Editor. A red circle will show itself,
which represents a breakpoint in the code. Every time the execution encounters this line,
it will pause there, and the Workspace will reflect the state it was in at that time.
When the script has stopped for a breakpoint, you will see the message “Paused in debug-
ger” in the bottom left, and the command line will look like
K>>
You can use the command line during this state to manipulate the Workspace, to test the
behavior in the code. To stop debugging, click “Quit Debugging” in the Toolstrip, or use
+ F5 .
6
3 Basic functions and datatypes
This chapter aims to introduce some of the building blocks of writing code in Matlab, and
we will begin by introducing some of the built-in functions for mathematical operations.
After this, you will be introduced to the two most important datatypes in Matlab – the
numeric and the logical, and the notion that everything is a matrix. Finally, we will look at
the structure array, which allows you to create your own data structures.
ans Contains the result returned from the most recent command
pi An approximation of the number 𝜋
eps Machine epsilon, floating-point relative accuracy, 2−52
Inf Infinity, represents 1/(+0)
NaN Not-a-Number, represents 0/0
√
i, j The imaginary unit, −1
7
3 Basic functions and datatypes
Exercise
Create a new script, and save it as EulersFormula.m and write the following code
𝑓1 = cos 𝑥 + 𝑖 sin 𝑥 𝑓2 = 𝑒 𝑖 𝑥
3. Show that the answers of the two expressions are equal for 𝑥 = 𝜋, by showing that
the difference is zero
4. Try some other values of 𝑥, run the script, and see what happens
3. Show that the answers of the two expressions are equal for 𝑥 = 1
4. Try the following values: 0, −1, 2, 𝑖 + 2 and try to explain what you are seeing
8
3 Basic functions and datatypes
To see a more comprehensive list of elementary functions for declaring and manipulating
matrices, type
help elmat
1 Starting in R2017a, you can create strings using double quotes, which provide a set of functions for working
with text as data. Read more on the Mathworks homepage
9
3 Basic functions and datatypes
You can specify which diagonal using an extra integer argument. Giving no argument is
implicitly zero, and refers to the main diagonal.
>> g0 = 2* ones (1 ,4); % The main diagonal
>> g1 = 3* ones (1 ,3); % The first upper diagonal
>> G = diag(g0 ,0) + diag(g1 ,1);
It should be mentioned that you can freely convert between sparse and full representa-
tions; numerically there is no difference between the two.
10
3 Basic functions and datatypes
Note that Matlab uses one-based indexing, unlike some languages that start counting at
zero. For vectors, you can drop the second index, which is then implicitly 1. You can also
use the reserved keyword end to access the last entry in a matrix.
>> b = 1:1:6
>> b(end -1) % Second -to -last element
>> b(4: end) % Last three elements
>> b(end +1) = 7 % You can also add elements like this
>> b(3) = [] % And remove elements with an empty matrix
You can also return the dimensions of declared matrices using the functions size and
length, try the following commands
>> size(A)
>> length (A)
>> size(b)
>> length (b)
Table 3.3 shows a list of some of the commonly used arithmetic operations for matrices and
their corresponding operator.
mtimes * Multiplication
mpower ^ Power
mldivide \ Left division, backslash
mrdivide / Right division, slash
11
3 Basic functions and datatypes
plus + Addition
minus - Subtraction
times .* Element-wise multiplication
power .^ Element-wise power
ldivide .\ Element-wise left division
rdivide ./ Element-wise right division
transpose .’ Transpose
To get a feeling for the difference between the two kinds of operators, try the following
>> A = [1 ,2 ,3; 4 ,5 ,6; 7 ,8 ,9] % Declare a 3x3 matrix
>> b = [5 ,6 ,7] % Declare a 1x3 vector
>> b = b.' % Transpose to a 3x1 vector
>> b + b % Vector addition
>> b.' * b % Scalar (dot) product
>> b * b % Error : Incorrect dimensions !
>> b .* b % Element -wise multiplication
>> A * A % Matrix multiplication
>> A ^ 2 % This gives the same result
>> A .^ 2 % But not this!
>> A \ b % Backslash division
You can see a comprehensive list of all the arithmetic operations, and more, if you type
>> help ops
12
3 Basic functions and datatypes
Exercise
Very rarely will you declare matrices by hand; oftentimes, you will want to build your
matrices dynamically, varying only a few parameters to shape the outcome. To wrap up
this section, you will try your hand at creating an automatic build script for a generic matrix.
For this exercise, you will create the following sparse, diagonal, 𝑚 × 𝑛 rectangular matrix.
𝑎0 𝑎1 · · · 𝑎𝑘
𝑎0 𝑎1 · · · 𝑎𝑘
𝐴 =
.. .. .. ..
. . . .
𝑎0 𝑎1 ··· 𝑎 𝑘
The goal is to automate all the work, without using any “hard-coded” constants. The user
need only provide the vector to be repeated along the diagonal, and the number of rows.
Do the following in a new Matlab script.
1. Declare the vector 𝑎 = [1, 2, 3] and choose 𝑚 = 3.
2. Find a way to automatically determine 𝑛, the number of columns of the matrix 𝐴.
3. Using 𝑎 and 𝑚, create a matrix whose columns represent each non-zero diagonal.
Hint: To repeat a matrix several times and concatenate the result, check out
>> help repmat
4. Next, declare the appropriately sized index vector for the diagonals.
5. Finally, create the sparse diagonal matrix 𝐴 using spdiags. You should convert it to
its full form to more easily see if it looks correct.
6. Now try to change 𝑚 to some other positive integer and run the script again. If you
have done it correctly, the script should produce a new, appropriately sized matrix –
without any complaints.
7. Then, change the vector 𝑎 to some other, non-empty row vector of any size. Again, if
the process is automated properly, there should be no error.
8. The “trivial” case where 𝑎 = 𝑚 = 1 should also work.
13
3 Basic functions and datatypes
For example
>> A = [5 ,7 ,0; 0 ,2 ,9; 5 ,0 ,0]
>> B = logical ([1 ,1 ,0; 1 ,0 ,1; 1 ,0 ,0])
>> A & B % All true or non -zero elements in A AND B
>> A | B % All true or non -zero elements in A OR B
>> ~B % All false elements in B
>> ~(A | ~B) % you can also write compound expressions
14
3 Basic functions and datatypes
eq == Determine equality
ge >= Determine greater than or equal to
gt > Determine greater than
le <= Determine less than or equal to
lt < Determine less than
ne ~= Determine inequality
Note that when accessing multiple elements contained inside cells, the output is returned
individually, not as a matrix. Cells are often used to store text strings, since storing them in
the same matrix would require vertical concatenation (stacking them on top of each other),
and so they would need to have the same length.
15
3 Basic functions and datatypes
Now assume we also want to keep track of the point’s velocity, [𝑥,
¤ 𝑦,
¤ 𝑧¤ ]. Let’s give it an
impulse along the 𝑧-axis. One way to add this new information is to use the setfield
command, as follows
>> p = setfield (p, 'vel ', [0 ,0 ,1])
Now if you double-click the variable p in the Workspace, it will bring up the Variables
window, and show the fields contained inside it.
As can be seen, the dot-notation can be used even if the field does not yet exist, upon which
it will be created. It can also be used multiple times to go deeper into the data structure;
for instance, you can access the name of the point using
>> p. header .name
Usually, a header comes first, so let’s sort the order of the fields using
>> p = orderfields (p) % No extra arguments -> sort alphabetically
Note that it does not matter in which order fields are specified.
16
4 Structured programming
This chapter covers some advanced techniques and constructs that, while they are useful
when developing code, lie outside the scope of modeling mechatronic systems. The reason
this chapter is included is more for the sake of completeness.
4.1 Functions
One way to help structure your program is to separate the project code into functions, which
also allows for reusing functionality instead of re-writing it.
Another benefit is that the code becomes easier to document for the developer and easier
to read for an external user. Note that this could be you in a few years, re-visiting an old
project.
...
return
end
First, note the signature in the first line of code, which lets Matlab know to treat the file
as a function definition, and how to handle the ingoing and outgoing values. Next, the
function definition makes use of the reserved keyword return, which stops the execution
of the function and returns control to the place where it was invoked. Finally, the block of
code is enclosed by the keyword end, which marks the end of the function definition.
Create a new (empty) M-file, and add the following lines of code.
17
4 Structured programming
Save it as add.m. Observe that it will appear in the Current Window with a slightly different
icon (“fx”) to let you know it’s a function definition.
Now try the following commands
>> help add
>> add (2 ,2)
4.1.2 Scope
Note that in the previous example, no variables called a or b ever appeared in the base
workspace. An important aspect of functions is that they have their own private workspace,
which is destroyed at the end of the function call. This also means that a function cannot
directly access the base workspace, unless specified explicitly using the global keyword,
both inside the function definition, and in the scope of the invoking function.
18
4 Structured programming
19
4 Structured programming
4.3.1 while
In a while-loop, the specified statements will be continuously executed until the condition
resolves to a logical zero. In the case where the condition resolves to false the first time, the
loop will not be entered, and the statements will never be executed.
while <condition>
% Do something repeatedly , while the condition holds
end
If the logical value of the condition is not altered by any commands inside the loop, the
program can get stuck in an infinite loop. Such a loop can be created intentionally with the
condition while true, which will never be exited unless a control statement is used, see
Section 4.4
4.3.2 for
The for-statement is suited for cases where the number of iterations is defined beforehand.
The index variable will sequentially assume each defined value, and the code will be
executed once per iteration. When all values have been used, the program will break out
of the loop, and keep executing.
for <index> = <values>
% Do something iteratively , for each specified value
end
• break can be used to immediately break the program out of the current loop and
execute commands defined after the end of the loop.
• continue is used to immediately go to the next iteration of the loop.
• return can be used to exit the current function, and return control to the invoking
function. If this is used outside of a function it will return control to the command
prompt, causing the program to terminate.
20
5 Basic graphics functions
One of the things that makes Matlab so useful is its rich library for graphical representation
of data, which helps to visualize data and communicate results. The built-in graphics
functions include plotting functions in 2D and 3D, animating objects, applying lighting or
transparency effects, and adding user interface elements and callbacks.
This chapter will show how to create graphical representations of data interactively, using
higher-abstraction functions that simplify some of the features behind the scenes. It will
cover some 2D plotting functions, modifying and working with multiple figures, and
exporting to vector graphics formats. If a larger amount of control is desired, it is possible
to use the lower-level functions to build up graphical objects from the start, which will be
elaborated on in Chapter 6.
As you can see, the default behavior of the plot command is to open a new figure, populate
it with axes, scale them accordingly, and draw lines onto it, making the first line blue, then
red, etc. Sometimes this is sufficient, but it is also possible to control the appearance, as
will be shown in the coming sections.
21
5 Basic graphics functions
can set some basic Axes properties using the keywords 'on' or 'off', try the following
commands
>> grid on % Show grid lines
>> box on % Enclose the Axes in ruler lines
The strings should be provided in the order that the lines were added.
22
5 Basic graphics functions
The .fig format is used for saving the Figure as-is, so that it can be loaded at some later
stage and further manipulated inside Matlab. The other formats involve an element of
rendering, in which an image is produced, which is meant to capture what is displayed on
the screen. The image formats can be divided into two categories; namely raster (also called
bitmap), or vector graphics.
23
5 Basic graphics functions
Trigonometric functions
1
0.8
0.6
0.4
0.2
Amplitude
0
-0.2
-0.4
-0.6
-0.8
0 1 2 3 4 5 6
Angle (rad)
(a) JPEG: Compressed bitmap (20 KB) (b) EPS: Vector graphics (18 KB)
Figure 5.1: Comparison between a compressed bitmap and a vector graphics print
provide less destructive compression, it helps to illustrate one of the potential issues. It
should be said that there are a few use cases where raster graphics is preferred, most
commonly when plotting 3D surfaces, or colors with transparency.
If your vector graphics file still appears pixellated, make sure you are using the painters
renderer. You can configure this under “Export Setup...” in the Figure window. Go to the
“Renderer” tab and change the “Custom renderer” option.
24
5 Basic graphics functions
25
6 Advanced graphics programming
This chapter will focus on the hierarchical make-up of graphical objects, handles, and
manual construction of Figures. This chapter also introduces the concept of object proper-
ties and ways to configure them. This notion applies to other complex data structures in
Matlab, like the Dynamic System Models, which will be introduced in Chapter 7.
Root
Figure
Illustration
Axes
Objects
Chart Primitive
Objects Objects
Figure 6.1: The parent-child relationship between some graphics objects in Matlab1
You can control the behavior and appearance of a particular graphics object by setting its
properties, which will be shown how to do later. First, a brief walkthrough of the important
graphics objects. This list only contains a subset of the most important objects. You can see
the complete list on the Mathworks homepage.
26
6 Advanced graphics programming
The variable p now contains a way to access the Chart Line object created by plot. Using
this handle, you can now directly access the properties of the chart.
The handle only points to the Line object, but as shown in the tree in Figure 6.1, the actual
data representation consists of several other objects. As we have already seen, when calling
plot directly, it will implicitly set up a Figure and an Axes in which to place the Line. It
is still possible to access these directly, but to do so we first need to produce a handle for
them as well.
27
6 Advanced graphics programming
Check the Workspace and you will see that you now have three graphics objects available
as variables.
to get a list of some of the properties available. You should see something like this
p =
28
6 Advanced graphics programming
Figure 6.2: Vector image created using LATEX interpreting for text fields
29
6 Advanced graphics programming
Preamble
The first thing is to create some data to plot. As the Figure suggests, we are looking at
an exponential smoothing curve and its derivative. We also take the time to define some
custom colors, these are borrowed from the Python package matplotlib.
clear all , close all , clc % Clean slate
% Custom colors
c1 = [31 , 119 , 180]/255; % #1 f77b4
c2 = [255 , 127 , 14]/255; % # ff7f0e
% Data to plot
T = 1; % Time constant (sec)
t0 = 0; tf = 6*T;
t = linspace (t0 ,tf ,50); % Time vector for simulation
f1 = 1 - exp(-t./T); % Exponential smoothing
f2 = exp(-t./T)/T; % Exponential decay
tT = [t0 ,t0+T]; yT = [0 ,1]; % Help - lines for gradient at t=0
% Screen placement
set(groot ,'Units ','centimeters ')
scrn = get(groot ,'ScreenSize ') - pos;
pos (1:2) = scrn (3:4) /2;
30
6 Advanced graphics programming
Observe that the Text objects, such as the labels, line numbering, and the legend are
instructed to use the LATEX interpreter. This is what makes it possible to typeset equations
in the text fields.
% Create Figure
fig = figure ('Units ','centimeters ','Position ',pos);
% Add Axes
ax = axes('Parent ',fig ,...
'XGrid ','on ','YGrid ','on ','XColor ','k','YColor ','k',...
'XMinorTick ','on ','YMinorTick ','on ','YLim ' ,[0 ,1.2] ,...
'TickLabelInterpreter ','latex ','FontSize ' ,10);
% Add Lines
ln (1) = line(ax ,t,f1 ,'Color ',c1 ,'LineWidth ' ,1.0,'LineStyle ','-');
ln (2) = line(ax ,t,f2 ,'Color ',c2 ,'LineWidth ' ,1.0,'LineStyle ','-');
ln (3) = line(ax ,tT ,yT ,'Color ','k','LineStyle ','--');
% Add Legend
leg = legend ('Parent ',fig ,...
'String ',{'$f(x) = 1-e^{-t/T}$','$f''(x) = 1/T\,e^{-t/T}$'},...
'Interpreter ','latex ','FontSize ' ,10,'Location ','southeast ');
31
7 The Control System Toolbox
The Matlab IDE is designed with high extensibility, and additional features come bundled
in “toolboxes” that can be installed alongside the core system. Up until now, we have been
only using functionality contained in the core toolbox. This chapter focuses on some of the
functions, data structures, and apps contained in the Control System Toolbox. In particular,
only continuous-time, single-input-single-output systems will be addressed in this chapter.
For more advanced topics, see Chapter 8.
Before you continue, make sure you have the Control System Toolbox installed. You can
list all installed toolboxes with the following command
>> ver
Now would be a good time to also check for the other packages listed in Chapter1.
Table 7.1: Some of the LTI models in the Control System Toolbox
These numeric LTI models belong to the class of objects known as dynamic system models.
Let’s look at how to create these datatypes, some of their properties, and how to transform
between them. Please note that this chapter will only cover parametric, continuous-time
system models.
Before we continue, let’s wipe the slate clean.
>> clear all , close all , clc
32
7 The Control System Toolbox
Alternatively, you can define the Laplace variable 𝑠 using a reserved keyword, and use this
to construct the rational expression in a (sometimes) more intuitive way.
>> s = tf('s'); % Laplace variable
>> tf2 = (2*s + 6) /(s^2 + 8*s + 15) % Transfer function
For this purpose, the zpk model can be used. Such a model can be created by specifying
the appropriate arguments, but it is also possible to transform between representations by
using a system model as the input instead. This is the simplest way to transform between
representations and works for all dynamic system models (if such a transform exists). This
method of converting between datatypes will be referred to in this text as casting.
33
7 The Control System Toolbox
The same system can be constructed by specifying the poles and zeros explicitly as vectors.
>> z = -3; % Zero at s = -3
>> p = [-3, -5]; % Poles at s = -3, -5
>> k = 2; % Gain of 2
>> zpk2 = zpk(z,p,k) % Explicitly create ZPK model
With real numbers, a term that appears in both the numerator and denominator in the
fraction can be simplified away. This is also true when considering transfer functions,
and the resulting simplified model is the minimal realization of the original system. In our
example, minreal will perform the pole-zero pair cancellation at 𝑠 = −3.
>> zpk3 = minreal (zpk2) % Minimal realisation
When working with transfer functions, it is often a good habit to always apply a minreal
to the result before studying it further.
𝑥(𝑡)
¤ = 𝐴 𝑥(𝑡) + 𝐵 𝑢(𝑡)
𝑦(𝑡) = 𝐶 𝑥(𝑡) + 𝐷 𝑢(𝑡),
where 𝑡 is the independent variable (time), and the dependent, vector-valued functions 𝑥(𝑡)
and 𝑢(𝑡) are denoted the state and input vectors, respectively. The vector field 𝑥(𝑡)
¤ defines
the gradient of the state vector at each point in the controlled state-space. In this particular
class of ODEs, the vector field is linear and time-invariant, and so can be represented by
the multiplications with the system (or state) matrix 𝐴, and control (or input) matrix 𝐵.
The function 𝑦(𝑡) defines the output of the system, as some linear function of the state
and input vectors. This is written as the multiplication with the output matrix 𝐶, and
the feedthrough matrix 𝐷 (seldom present). This chapter covers only SISO systems, so the
input and output matrices are vectors. For details on the general MIMO case, see Chapter 8.
A state-space model can be created in Matlab with the ss command. We can cast any of
the models we have seen to a state-space representation, just like earlier. You can specify
additional keywords as strings to elicit desired behavior—see the documentation. Try the
following examples
>> ss1 = ss(tf1) % Cast TF to SS model
>> ss2 = ss(tf1 ,'minimal ') % Minimal realisation
34
7 The Control System Toolbox
Let’s consider another system, shown below. For the sake of simplifying the notation, the
dependent variable 𝑡 is dropped from future examples.
0 1 0
𝑥¤ = 𝑥+ 𝑢
−1 −1 1
𝑦= 1 0 𝑥
You can create a state-space model of this by explicitly defining the numerical matrices,
and passing them in as individual arguments.
>> A = [0 ,1; -1 , -1]; % System matrix
>> B = [0;1]; % Control matrix
>> C = [1 ,0]; % Output matrix
>> D = 0; % Feedthrough matrix
>> ss3 = ss(A,B,C,D) % Create SS model
where the control parameters are related through 𝐾 i = 𝐾 p /𝑇i , 𝐾d = 𝐾 p 𝑇d and 𝑇f = 𝑇d /𝑁.
While the parallel form is more general and easier to grasp, it should be pointed out
that in the standard form, each control parameter has a clear physical interpretation and
well-defined unit of measurement.
PID controller models can be created with the commands pid and pidstd, depending
on what representation you would like. It is possible to cast existing dynamic system
models to PID form, if such a representation is possible. Any PID model can be cast to the
representations presented earlier.
When creating new models, the trailing arguments can be omitted to create simple P or PI
controllers.
35
7 The Control System Toolbox
They won’t be elaborated on further in this text, but 2 degrees-of-freedom (2-DOF) PID
controllers are also present in the Control System Toolbox, available with the commands
pid2 and pidstd2.
Figure 7.1 shows three possible ways to connect systems. There are commands in Matlab
for this, but it is also possible to perform arithmetic operations, such as the addition and
multiplication of dynamic system models.
sys1 Σ sys1
−
Σ sys1 sys2
sys2 sys2
Note: The order of the multiplication is important in the multi-variable cases since matrix
multiplication is not commutative in general! The correct order is determined by the reverse
order in which the blocks appear in the diagram.
36
7 The Control System Toolbox
It should be mentioned that while not as simple, it is possible to arrive at the same result
with arithmetic operations.
>> one = eye(size(sys1*sys2)); % Identity matrix
>> sys_fb3 = (one+sys1*sys2) \ sys1 % Equivalent equation
To generalize the arithmetic expression for multi-variable systems, the identity matrix is
used instead of just the scalar 1. Also, note the backslash division!
Table 7.2: Plot commands for linear analysis of dynamic system models
We can divide the analysis into three domains of study, but it should be stressed that they
are simply different viewpoints of the same fundamental question; “How can we expect
the modeled system to respond to inputs?”
For the sake of the coming analysis, let’s consider the second-order transfer function
37
7 The Control System Toolbox
Step Response
Bode Diagram
1.6
10
1.4 5
0
1.2
-5
1
Magnitude (dB)
Amplitude
-10
0.8
-15
0.6 -20
-25
0.4
-30
0.2
-35
0
0 5 10 15 20 25 30 -40
10-1 100 101
Time (seconds)
Frequency (rad/s)
Nyquist Diagram
Pole-Zero Map
3
1.5
0 dB 0.72 0.58 0.44 0.32 0.22 0.1
-2 dB
2 2 dB
1 0.86
Imaginary Axis (seconds-1 )
4 dB -4 dB
1
6 dB -6 dB 0.5 0.96
Imaginary Axis
10 dB -10 dB
20 dB -20 dB
0 1.6 1.4 1.2 1 0.8 0.6 0.4 0.2
0
-1
-0.5 0.96
-2
-1 0.86
Figure 7.2: Example of some of the graphical linear analysis tools in Matlab
The resulting system response is called the step response, see Figure 7.2a. You can simulate
and plot the step response for any dynamic system model with the step command. If you
38
7 The Control System Toolbox
ignore the output, it will plot the response in the most recent Axes, otherwise, it will just
save the vector containing the time and outputs, to the Workspace.
>> step(sys) % Step response plot
>> [y,t] = step(sys) % Returns the output and time vectors
For stable LTI systems, the overall behavior is a fast initial rise, followed by convergence
towards some final steady-state value. In the case of our oscillating systems, there is also
some overshoot present. You can extract system characteristics such as rise time, overshoot
in percent, and settling time, by using
>> stepinfo (sys) % Computes step response characteristics
Another common system response is the impulse response, where the input is a unit impulse
at 𝑡 = 0. This can be thought of as an instantaneous transfer of energy into the dynamic
system. Just like the step response, you can choose to produce the plot or to save the output
as vectors.
>> impulse (sys) % Impulse response plot
Additionally, you can test any input signal of your choice by creating the necessary time
and input vectors, and exciting the linear system using lsim.
>> t = 0:0.1:30; % Time from 0 to 30 sec
>> u = asin(sin(t)); % Saw -wave with period 2 PI
>> lsim(sys ,u,t) % Linear simulation plot
𝑠 = 𝑗 𝜔 + 𝜎,
where the imaginary part contains some frequency 𝜔, and the real part corresponds to
some factor of decay 𝜎. By letting the real part be zero, we can study how the system
behaves when excited with undamped oscillations at various frequencies. This is called the
frequency response.
The most useful plot for studying the frequency response is the Bode diagram, which shows
the magnitude (dB) and phase shift (degrees) of the system, as a function of the input
frequency (rad/sec). Similar to the previous graphical commands, you can either return
the output vectors to the Workspace or show the plot window.
>> bode(sys) % Bode diagram
Oftentimes, it is sufficient to only show the magnitude plot, like in Figure 7.2b.
>> bodemag (sys) % Only show the magnitude plot
39
7 The Control System Toolbox
Another way to represent the frequency response is the Nyquist diagram, which plots the
system magnitude and phase shift in the complex number plane, using polar coordinates
and extending the range of frequencies to include negative numbers.
>> nyquist (sys) % Nyquist diagram
An example of the resulting parametric curve can be seen in Figure 7.2c, and is a common
tool for analyzing the robustness of linear control systems.
Lastly, it is possible to extract important numeric values relating to the frequency response
of a system, by using the commands below. The steady-state gain of a system is defined as
the magnitude of the system when excited with a frequency of zero, hence why it’s also
referred to as the DC gain, from the field of electrical engineering.
It is equivalent to setting 𝑠 = 0 in the transfer function and can be found with the command
>> K0 = dcgain (sys) % Steady - state gain
Another important system characteristic is the bandwidth, which is the frequency where the
gain drops below =3 dB of its steady-state value.
>> B = bandwidth (sys) % Bandwidth of the system
Any frequencies above the bandwidth are commonly considered strongly attenuated.
Re (𝑝 𝑖 ) < 0, 𝑖 = 1, 2, . . . , 𝑛.
You can determine the pole and zero locations of a SISO system model using the commands
>> p = pole(sys) % Poles of the system
>> z = zero(sys) % Zeros of the system
A useful way to graphically represent the poles and zeros of a transfer function is by
plotting their locations on the complex 𝑠-plane, whose 𝑥 and 𝑦-axes represent the real and
imaginary parts, respectively. It is common to mark a zero location with a circle (◦), and a
pole location with a cross (×). Such a figure is known as pole-zero map, see Figure 7.2d.
>> pzmap (sys) % Pole -zero map
40
7 The Control System Toolbox
To ensure system stability, no poles can be to the right of the line drawn by the imaginary
axis. Additionally, other conclusions regarding the dynamics of a stable system model can
be drawn by studying the pole locations more carefully. Since all the coefficients of the
transfer function polynomials are real, the poles and zeros must be either purely real or
appear in complex conjugate pairs.
• A purely real pole corresponds to an asymptote in the time domain, where the system
output converges exponentially to some steady-state value. The rate is determined
by the time constant, which is the inverse of the real pole.
• Complex-conjugated pole pairs represent oscillations in the time-domain behavior.
The magnitude and angle of the complex phasor can tell you about the natural frequency
of the oscillations, as well as the damping ratio.
You can determine the numerical values using the following command
>> damp(sys) % Natural frequency and damping of the system
For more theory regarding conjugated poles and oscillations, consult the literature from
your basic control theory course.
Exercise
Consider the stable transfer function 𝐺(𝑠) in a feedback control-loop with the controller
𝐶(𝑠) shown in Figure 7.3.
𝑟(𝑡) 𝑦(𝑡)
Σ 𝐶(𝑠) 𝐺(𝑠)
−
100 4 𝑠 2 + 40 𝑠 + 400
𝐺(𝑠) = 𝐶(𝑠) =
𝑠 + 10 𝑠 + 100
2 𝑠 2 + 40 𝑠
Do the following in a new Matlab script, and try to answer the questions below.
1. Create the transfer function models for 𝐺(𝑠) and 𝐶(𝑠).
2. Create the resulting closed-loop system from 𝑟(𝑡) to 𝑦(𝑡), shown in Figure 7.3.
3. Investigate the closed-loop system poles and zeros. Notice anything particular?
Hint: It might be more clear if you represent it as a zero-pole-gain model.
4. Now try to determine the minimal realization of the closed-loop system. What
changed?
41
7 The Control System Toolbox
5. The controller is actually just a PID controller. What are its parameters?
6. Compare the time-domain properties of the controlled system (such as rise time,
overshoot, etc.) of the uncontrolled system 𝐺(𝑠). Can you see some correlation if you
then compare the frequency-domain properties such as poles, damping, etc.?
42
8 Dynamic systems – Advanced topics
This chapter covers some of the more advanced aspects of modeling dynamic systems in
Matlab. In particular, this chapter serves to extend some of the definitions provided in
the previous chapter, to cover more advanced topics such as multi-variable, and discrete-
time systems. Lastly, it will present alternative commands for working further with the
graphical representations shown in the previous chapter.
To provide a preface, the first section covers how to manipulate dynamic system models,
and access their internal properties. For this reason, it is suggested that you first work
through Chapter 6, if you have not already.
Please note that this chapter involves some minor abuse of notation, where time-domain
signals and their transformed counterpart are used interchangeably. For convenience, the
time dependency and the Laplace variable may also be dropped from the notation.
The simplest way to access the properties is by using the dot-notation. First, we give our
model a name.
>> [Link] = 'Low -pass filter ';
Alternatively, you we use the set and get commands. We can define the polynomials by
setting the name-value pair explicitly.
>> set(tf1 , 'Numerator ', 10, 'Denominator ', [1, 10]);
The default time unit is seconds. Confirm that with the appropriate get command.
>> get(tf1 ,'TimeUnit ') % Read the time unit
43
8 Dynamic systems – Advanced topics
The raw numeric representations can also be extracted from LTI models with the commands
tfdata, ssdata, etc. depending on the type of model.
>> [num , den] = tfdata (tf1) % Get the polynomial coefficients
𝑥 : 𝑝×1 𝐴:𝑝×𝑝
𝑥¤ : 𝑝 × 1 𝐵:𝑝×𝑞
𝑢 : 𝑞×1 𝐶 :𝑟×𝑝
𝑦 : 𝑟×1 𝐷:𝑟×𝑞
Physical systems rarely have feedthrough characteristics, so very often the 𝐷-matrix is just
a zero matrix. In newer versions of Matlab you can simply specify 0 and the size will be
determined automatically. For older versions, the following dynamic sizing can be used
D = zeros (size(C ,1) , size(B ,2));
Let’s re-consider the system model from Chapter 7, but as a multi-variable system.
>> A = [0 ,1; -1 , -1]; % System matrix
>> B = [0;1]; % Control matrix
>> C = [1 ,0;0 ,1]; % Output matrix
>> ss1 = ss(A,B,C ,0) % Create SS model
44
8 Dynamic systems – Advanced topics
Setting the identity matrix as the output matrix ensures that the entire state vector is
returned as the output (𝑦 = 𝑥) since a vector multiplied by the identity matrix is unchanged.
By specifying the index in Matlab, you can specify which output you want, try
>> ss1 (1) % Model of the dynamics from u to y1
>> pole(ss1 (2)) % Poles of the model from u to y2
>> step(ss1) % Step response from both outputs
Next, let’s make the system multi-input as well. We can change the control matrix 𝐵 to be
multi-variable without re-initializing the model, but this requires setting the 𝐷 matrix too,
to avoid matrix inconsistencies
>> set(ss1 , 'B', eye (2) , 'D', zeros (2)) % Vector - valued input
Setting the control matrix 𝐵 to the identity matrix means that the system now takes the
vector-valued input 𝑢 = [𝑢1 , 𝑢2 ]T , where 𝑢1 acts directly on the state 𝑥1 , and 𝑢2 on 𝑥 2 .
When working with a MIMO system, you can choose to study individual input-output
dynamics by providing two indices, the first for the output, and the second for the input.
This ordering is no coincidence, as will be shown in the next section. The syntax for
indexing is just like with regular matrices, see Section 3.3.4.
>> ss1 (1 ,1) % Model of the dynamics from u1 to y1
>> step(ss1 (: ,2)) % Unit step at u2 , show both outputs
>> step(ss1) % Unit step at each input , respectively
By providing the signals for both inputs explicitly, it is possible to simulate inputs from
both inputs simultaneously
>> t = linspace (0 ,10 ,10000) % Time vector
>> u = ones (2 ,10000); % Unit step at both inputs
>> lsim(ss1 ,u,t) % Linear simulation
𝑦 = 𝐺 𝑢,
where 𝑦 is the output vector, and 𝑢 is the input vector. The transfer matrix 𝐺 assumes the
dimensions 𝑟 × 𝑞, and the form
45
8 Dynamic systems – Advanced topics
It becomes clear that the transfer function from input 𝑢 𝑗 to output 𝑦 𝑖 is given by 𝑔 𝑖,𝑗 , which
denotes the entry in the 𝑖 th row and the 𝑗 th column of the transfer matrix. For this reason,
it becomes natural to index all MIMO systems in Matlab this way, which is why indexing
for state-space systems follows this convention too.
You can cast a state-space model to a transfer matrix just like with scalar systems
>> tf1 = tf(ss1) % Cast to transfer matrix
>> zp1 = zpk(ss1) % Also works in ZPK form
You will see that you can do the same things with the transfer matrix, as with the state-space
model.
>> tf1 (1 ,1) % Transfer function from u1 to y1
>> step(tf1 (: ,2)) % Unit step at u2 , show both outputs
>> step(zp1) % Unit step at each input , respectively
The discrete state-space equation describes the value of the state vector at sample 𝑘 + 1 as a
linear function of the state and input vectors of the previous sample 𝑘, defined by its four
system matrices, which take on a form very familiar to that we have already seen.
Similarly, the discrete-time transfer function also closely resembles its continuous counter-
part; a fraction of two polynomials of a complex variable, written as
𝐵(𝑧) 𝑏 𝑚 𝑧 𝑚 + 𝑏 𝑚−1 𝑧 𝑚−1 + · · · + 𝑏1 𝑧 + 𝑏0
𝐺(𝑧) = = .
𝐴(𝑧) 𝑎 𝑛 𝑧 𝑛 + 𝑎 𝑛−1 𝑧 𝑛−1 + · · · + 𝑎1 𝑧 + 𝑎 0
46
8 Dynamic systems – Advanced topics
Analogously, a discrete transfer matrix describes the transfer from the sequence of inputs
to the sequence of outputs. Note that the complex variable is 𝑧 instead of 𝑠, which serves
as a reminder that discrete-time system models are functions with a different domain.
There are several ways of transforming between the domains, most of which involve some
degree of approximation, where models may lose some of their original expressiveness.
This text is not going to cover any in-depth theory on discretization or 𝑧-transform, for that
purpose, see a textbook in digital control theory1 .
It is important to note that in the discrete-time, different rules apply. For instance, a pole in
the right-half plane will produce a stable system, as long as its magnitude is less than one.
>> z = 0; % Zeros
>> p = 0.5; % Poles
>> k = 0.5; % Gain
>> Ts = 0.01; % Sample time
>> zpkd = zpk(z, p, k, Ts) % Discrete transfer function
The default method for discretization method provides an exact discretization in the time
domain, given ZOH acting on the inputs. Another common method is Tustin’s approximation,
which provides a good match in the frequency domain, and allows for frequency pre-
warping to preserve important dynamics at certain frequencies.
>> tfd3 = c2d(tfc , Ts , 'tustin ') % Tustin 's approximation
Finally, it should be mentioned that it is also possible to apply the reverse transformations
to the methods mentioned above, using the c2d command.
>> tfc1 = d2c(tfd1)
1 For a complete overview, see Computer-Controlled Systems: Theory and Design by Åström and Wittenmark.
47
8 Dynamic systems – Advanced topics
Exercise
Consider the continuous state-space model
0 1 0
𝑥(𝑡)
¤ = 𝑥(𝑡) + 𝑢(𝑡),
−1 −1 1
| {z } |{z}
𝐴 𝐵
𝑦(𝑡) = 1 0 𝑥(𝑡).
| {z }
𝐶
Do the following in a new Matlab script, and try to answer the questions below.
1. Create a continuous state-space model of the original system.
2. Create a discrete state-space model of the approximated system with 𝑇s = 0.5 sec.
3. Discretise the original model using c2d with ZOH and the same 𝑇s .
4. Compare the step responses of the three systems, in the same Axes. How good are
they at capturing the model dynamics?
5. Repeat the above for 𝑇s = 0.1 and 𝑇s = 1, what can you observe?
6. Run the script and answer the same questions using the approximation
1
Φ ≈ 𝐼 + 𝐴 𝑇s + (𝐴 𝑇s )2 Γ = 𝐴−1 (Φ − 𝐼) 𝐵
2
7. Optional: You might recognize the approximation as the first two terms in the Maclau-
rin series expansion of a certain function 𝑓 (𝐴 𝑇s ). Use that function instead to deter-
mine Φ (and thus Γ). How does the approximation compare to ZOH now?
Hint: For performing this function on matrices, check
>> help matfun
48
8 Dynamic systems – Advanced topics
Once you have the handle, it becomes possible to exercise a high level of control over the
plot’s appearance. It should be mentioned that these plots are specializations of the more
graphical objects shown in Chapter 6, so in addition to modifying the underlying objects
such as the Axes, you may also provide options specific for that particular plot.
For instance, Figure 7.2b can be produced with the following code snippet
sys = tf(1, [1 ,0.4 ,1]); % Transfer function
handle = bodeplot (sys); % Get plot handle
setoptions (handle , 'Grid ','on ', 'PhaseVisible ','off '); % Options
In this case, disabling the PhaseVisible option is used to show only the magnitude, not the
phase shift. For the available arguments, you should consult the MathWorks documentation
for the command in question.
For the actual code used to produce the plots in Figure 7.2, see Appendix 9.8.
49
9 Simulink
Simulink provides a graphical user interface (GUI) for building dynamic system models
as block diagrams, using click-and-drag mouse operations. With this interface, you can
draw the models just as you would with pencil and paper (or as most textbooks depict
them). This chapter explains some of the basic features of the Simulink software package,
examples on how to build a model from scratch, and the integration with the Matlab
engine, including some of the toolboxes and techniques seen in previous chapters.
9.1 Motivation
Simulink encourages you to try things out. You can easily take an existing model and add
to it, or build models from scratch, as will be shown in Section 9.5. Using scopes and
other display blocks, you can see the simulation results while the simulation is running. In
addition, you can change many parameters and see what happens for “what if” exploration.
After you define a model, you can simulate it using a choice of integration methods, either
from the Simulink menus or by entering commands in the Matlab Command Window.
With Simulink, it becomes easier to move beyond idealized linear models, to explore more
realistic nonlinear models, factoring in friction, air resistance, gear slippage, hard stops, and
the other things that describe real-world phenomena. The Simulink modeling environment
supports nonlinear and discontinuous dynamics, modeled in continuous time, discrete
time, or a hybrid of the two. Systems can even be multi-rate, i.e. have different parts that
are sampled or updated at different rates.
9.2 Fundamentals
All models in Simulink are made up of blocks, which may have any number of inputs and/or
outputs. A block can represent a physical component, a small system, or a function.
Additionally, Simulink handles data in three categories, listed below.
• Signals – Block inputs and outputs, computed during simulation.
• States – Internal values, representing the dynamics of the block, computed during
simulation.
• Parameters – Values that affect the behavior of a block, controlled by the user.
50
9 Simulink
In short, signals represent the connection between blocks’ output(s) and input(s). It is
possible to create a branch in a signal so that the output from one block serves as the
input to several blocks. Signals can be vectors of arbitrary length, and Simulink supports
numerical and logical values.
Similar to Matlab, signal types and dimensions are inferred automatically unless defined
explicitly. When a model is run for the first time it is compiled into executable code, upon
which all parameters and signals are validated. Any mismatched parameter or signal
properties will cause errors, and prevent the simulation from running.
When working in Simulink, there are a few things to keep in mind to try to maintain a
logical and systematic structure to your models:
• Try to work from left to right, with inputs at the very left and outputs at the very
right.
• Label your signals using some consistent convention that is easy to follow.
• Refrain from using hard-coded values in your blocks, use variables defined in the
Matlab workspace.
• Use Subsystems to group blocks, which increases readability and reduces the com-
plexity of your models.
On the Simulink start page, choose a new “Blank Model”. You should see a blank canvas,
with a Toolstrip at the top, similar to that of Matlab. You will also see that Matlab is still
open, and closing it will prompt Simulink to also close since Simulink is not a standalone
environment.
The canvas can be populated with any number of blocks to create a model. When working
on the canvas, you can use the mouse to
• move blocks by holding the left mouse button,
• copy blocks by holding the right mouse button,
• open block parameters by double-clicking with the left mouse button,
• connect an input and output by holding the left mouse button,
• create a new branch on a signal by holding the right mouse button,
• label existing signals by double-clicking with the left mouse button,
• zoom in/out in the model using the mouse wheel,
• move the canvas by holding the middle mouse button,
51
9 Simulink
52
9 Simulink
• Sources – contains blocks with no input of their own, which provide signal generation
functionality, such as the Pulse Generator, Step, and Sine Wave blocks.
In the Simulation Toolstrip, in the “Simulate” section, set the Stop Time to 5, and click the
Run button to simulate the model. The progress is shown in the status bar at the bottom
of the window. In this case, the model is not particularly complex and should compile and
execute within a few seconds. Once the execution finishes (and if no errors occurred), the
status will return to Ready, and you may hear a system notification sound. The simulation
results can be seen in the Scope block by double-clicking it; you should see something like
Figure 9.3.
53
9 Simulink
The Sine Wave output is displayed in an oscilloscope-style grid, with time along the 𝑥-
axis. It is more than likely that the result does not exactly reflect your expectations. For
instance, the amplitude of the signal never reaches 1, and the curve appears to have several
discontinuous breaks. This will be addressed in the coming section.
1 For a good summary of key concepts, see Chapters 5 and 6 of Numerical Analysis (2nd ed.) by Timothy Sauer.
54
9 Simulink
Table 9.1: General guidelines on when to use each of the different solvers
2 For more details, see the article Stiff Differential Equations by Cleve Moler on the MathWorks homepage.
3 Adopted from the page Choose an ODE Solver on the MathWorks homepage.
55
9 Simulink
is nonstiff is stiff
Variable-step VariableStepDiscrete ode23t
ode45 ode15s
This also brings us back to the original issue, the poor resolution of the Sine Wave model.
If you go back to your model, you will likely see that the status bar is displaying
auto(VariableStepDiscrete)
in the bottom right. Knowing what we know now, it makes sense that this is the solver it
chose – the Sine Wave has no continuous states since it is just a Source.
If you click the text, you will also see that it has automatically determined the Max step size
to be 0.1, which explains why the curve has such low resolution. Click the cogwheel icon
(see Figure 9.4), and it will take you to the solver settings. Alternatively, you can get there
from the Modeling Toolstrip, under the Setup tab.
Figure 9.4: Bringing up the solver settings from the status bar
4 Adopted from the page Choose a Fixed-Step Solver on the MathWorks homepage.
56
9 Simulink
If you expand the Solver details you will get access to all the solver parameters. Try setting
the Max step size to 0.001 and running the simulation again. Hopefully, the curve should
look more like a sinusoidal wave than before.
Hint: You can run the simulation directly from the Scope, by opening it again and using
the Run button in the Scope toolbar.
This will start a new instance of Simulink and open the system model shown in Figure 9.5.
blower
Terr cmd
On/Off
HeatFlow 1/s
Fahrenheit HeatCost
Thermostat Troom
to Celsius Cost
Set Point
Calculator PlotResults
Heater
F2C
C2F
House
F2C Tindoors
Tout
Avg Outdoor
Temp
Daily Temp
Variation Toutdoors
Temperatures
The demo models the (simplified) thermodynamics of a house, and the overall dynamics
can be described as follows.
1. The Thermostat controls the Heater, which is switched on or off based on the difference
between the reference (Set Point) and measured temperature.
2. The temperature of the House is affected by the output from the Heater, as well as
the outside temperature, which fluctuates over the course of a day. This is simulated
as a sine wave superimposed on a daily average temperature.
3. Finally, the temperature of the House is measured and fed back into the Thermostat,
which closes the loop on this simplified feedback control system.
57
9 Simulink
9.4.2 Subsystems
The model uses subsystems to simplify the model diagram and create reusable systems. A
subsystem is a grouping of blocks, implemented by the Subsystem block. If you double-
click a Subsystem block it will show the contents of the underlying blocks. The oval blocks
represent the input and output signals, and the number inside the block indicates the port
number of that signal.
This model contains three main subsystems, shown in Figure 9.6; representing the Ther-
mostat (9.6a), Heater (9.6b) and House (9.6c), respectively.
1
Thermostat Command (On/Off)
On/Off
1 1 1
2
HeatFlow
Terr Blower Troom Heater Switch
switch HeatGain
(a) Thermostat Subsystem
Heater Air Temperature
1 1/s 1
Heater Room Temp
QDot Troom
In 1/Mc
Heat Losses
2
Outdoor Temp
Tout
The Thermostat subsystem models the operation of a thermostat, determining when the
heating system is turned on and off. It can be seen that it is modeled by a single discon-
tinuous Relay block, and outputs either a numerical one or zero, based on the temperature
58
9 Simulink
error. It is configured to keep the temperature bounded within a specified range from the
set point.
Next, let’s turn our attention to the Heater subsystem which contains some of the most
commonly used blocks. The circular block is a Sum block, which outputs the signed sum
of the input signals. The triangular block is a Gain block, which outputs the product of the
input and the constant defined in the block. The square block with a cross (×) outputs the
product of the two input signals at each instance of time. In the case where one signal is a
constant, it is equivalent to the Gain block.
Interpreting the blocks as an equation, we see that the Heater is modeled as a discontinuous
but static (memoryless) system. The instantaneous heat transfer rate is given by the product
¤ heat capacity 𝑐, and the on/off signal from
of the temperature difference, air flow rate 𝑀,
the Thermostat;
(
𝑀¤ 𝑐 (𝑇Heater − 𝑇room ) , when on
𝑄¤ Heater =
0, when off.
A small comment on the static property of the subsystem — it is assumed that the heating
element reaches the temperature 𝑇Heater immediately when turned on (regardless of the
ambient temperature) and that all heat transfer stops immediately when turned off. This
approximation makes sense when considering that the time unit used in the model is hours
and that the time constant of a conventional heater is likely to be orders of magnitude
smaller — minutes or even seconds.
Finally, the House is modeled as a dynamical system, meaning that the output is determined
not only by the instantaneous input but the entire history of inputs, as well as the initial
conditions. This is achieved using the square Integrator ( 1𝑠 ) block, where 𝑠 is the Laplace
variable. The Integrator is the backbone for building differential equations using block
diagrams, which is how all dynamic systems are modeled in Simulink.
Reading the block diagram as a differential equation, we see that the rate of increase in
temperature of a mass 𝑀 with heat capacity 𝑐 is determined by the heat from the Heater,
and losses – defined by the quotient of the temperature difference inside and outside, and
the equivalent thermal resistance for the whole house 𝑅 eq ;
𝑇room − 𝑇out
𝑀 𝑐 𝑇¤room = 𝑄¤ Heater − .
𝑅 eq
As an optional exercise, you are encouraged to derive this equation, on your own, from the
block diagram representation in Figure 9.6c.
59
9 Simulink
Exercise
Here are a few things to try to see how the model responds to different parameters.
• Open the Constant block labeled Set Point and set the value to some other value.
Rerun the simulation to see how the indoor temperature and heating costs change.
• Adjust the outside temperature (the Avg Outdoor Temp block) and rerun the simula-
tion to see how it affects the indoor temperature.
60
9 Simulink
• Adjust the daily temperature variation by opening the Sine Wave block labeled Daily
Temp Variation and changing the Amplitude parameter, then re-run the simulation.
• Restore the model to its original state. Then replace the Relay block in the Thermostat
subsystem with a Saturation block, with limits (1,0). The thermostat control signal is
now proportional to the error, and can now assume values between zero (off) and one
(full power). How does this affect the temperature of the house?
• If you zoom in on the curve of the indoor temperature, you may see some small
high-frequency oscillations superimposed on the output. What phenomenon do you
think this is? Try to change the model configuration to remove the oscillations.
Hint: There are nonlinear dynamics! Try a solver which is better at DAEs, see Table 9.1.
𝐹 = 𝑚 𝑥¥ + 𝑑 𝑥¤ + 𝑘 𝑥,
where the force 𝐹 is the input to the system, and the deflection 𝑥 is the output.
9.5.1 Walkthrough
Using the rules of thumb listed above, we can identify that we will need one sum block and
two integrators. The next step is to factor the highest-order term. We get
𝑚 𝑥¥ = 𝐹 − 𝑑 𝑥¤ − 𝑘 𝑥,
which tells us that three (not yet present) forces are acting on the oscillator. To get the
acceleration, we need to divide away the mass.
Let’s begin by expressing this using a sum block and a gain block, respectively. Open the
Library Browser, navigate to the Commonly Used Blocks, then drag and drop a Sum and a
Gain block into your blank model.
We can ignore the settings of the Sum block for now, but you should change the Gain value
to 1/m. If the block lights up red, don’t worry about that yet – it is simply a warning that the
61
9 Simulink
variable m is undefined. Finally, connect the output of the Sum with the input of the Gain
and double-click on the newly created connection to label the signal something appropriate
like mx”. You should have something that looks like Figure 9.8.
mx''
The output signal from the Gain is now the acceleration of the oscillator. To get the
velocity, we should use an Integrator. Instead of using the Library Browser, we will use a
different method. Single-click anywhere in the empty space of the model and begin typing
“integrator”. You should see an auto-completion list appear where you clicked. You can
click the name of the block you want (or hit if it appears at the top of the list) to insert
it. This is the fastest way to insert blocks that you know the name of. Once you have added
the integrator, you can copy ( Ctrl + C ) and paste ( Ctrl + V ) it to get another one. Connect
them in series with the Gain and label the intermediate signals x” and x’, like in Figure 9.9.
Now that we have defined the output signal, we can connect it to a sink. For this example,
visualizing the signal with a Scope will be enough. A Scope can be found under Sinks in
the Library Browser; connect it to the output of the second Integrator, and label the signal
x, see Figure 9.10.
The block diagram is not yet finished. Next, we need to feed back the spring and damper
forces, and then add the input force 𝐹. Let’s turn our attention to the Sum block. By
double-clicking it you can edit the List of signs. The signs are defined counter-clockwise
from the top and can be either plus (+), minus (-), or blank (|). Change it to “-+-”.
Now let’s feed the spring force back onto the mass. We know that the spring force is the
product of the stiffness 𝑘 and the deflection 𝑥, so we need another Gain block. To make
it easy, right-click and hold the 1/m Gain, then drag it somewhere to create a new copy,
Gain1. Change the gain value to k. Then right-click on it and choose Rotate & Flip Flip Block
(or use Ctrl + I ). Place it above the old Gain block and connect the input of the Sum with
the output of Gain1, then connect the input of Gain1 with the signal labeled x. If done
correctly, a branch should be created for you. Rename the signal to kx. You should have
something like in Figure 9.11.
62
9 Simulink
kx
For the damping force, we will do something much faster. Right-click and hold the signal
labeled x’ to branch a new arrow, then drag it directly to the lower input of the Sum block.
Now right-click and drag one of the old Gain blocks so that the new copy ends up on top
of the newly created line. If done correctly, it should connect itself so that the signal passes
through it. Change the gain value to d and rename the signal, see Figure 9.12.
kx
dx'
Finally, let’s add an input signal. You can find a Step block under the Sources tab in the
Library Browser. Set the Step time to 0, and the Final value to F. The final block diagram
can be seen in Figure 9.13.
kx
dx'
The last thing to do before we can run the model is to define the parameters. There are a
few ways to do this, the simplest way is to define them through the Command Window so
that they are temporarily saved in the Workspace.
63
9 Simulink
Finally, you can test the simulation by running it. The output should look like Figure 9.14.
If the model appears correct, you can save it as [Link] – it will be used for
the following sections.
64
9 Simulink
kx
x
F mx'' x'' 1 x' 1
s s
dx'
Finally, open the scope, click the cogwheel in the toolbar to bring up the Configuration
Properties, and click Layout. Choose the 2 × 1 grid configuration (Figure 9.16), then accept
the changes and close the configuration window.
After running the simulation again, the Scope should look like Figure 9.17.
For more practice on building a block diagram based on a system of differential equations,
see this tutorial from the Control Tutorials for MATLAB and Simulink.
65
9 Simulink
Figure 9.17: Step response of the damped oscillator, showing both deflection and velocity
66
9 Simulink
Figure 9.18: Data export configuration for the damped oscillator model
67
9 Simulink
Subsequently, we need to add some outputs. Add two Out1 (sink) blocks, using any method
you prefer, and connect them to signals x and x’, so that the deflection has number 1 and
the velocity has number 2, see Figure 9.19.
kx
1
x
F mx'' x'' 1 x' 1
s s
dx'
2
Finally, run the simulation again and wait until it finishes. Check the Matlab Workspace.
There should be two vectors named tout and yout, which are the time and output vectors,
respectively. Each column in yout corresponds to an Out1 block, with the ordering given
by the respective port numbers.
You can try the following commands to plot the signals using Matlab.
>> subplot (2 ,1 ,1) , plot(tout , yout (: ,1)) % Plot deflection
>> subplot (2 ,1 ,2) , plot(tout , yout (: ,2)) % Plot velocity
9.6.2 To Workspace
Furthermore, there is another sink called To Workspace, which allows you to export in-
dividual signals as various data types. This allows greater flexibility when you have a
large model and may want to export internal signals, such as controller logic, which aren’t
considered model outputs. In the case where the Single simulation output option is on, the
saved variables will appear inside the output structure.
This command is equivalent to clicking the Run button of the model, and will save the out-
puts in the Workspace as specified in the Configuration Parameters previously. However,
it is also possible to specify the variables in which to save the outputs.
68
9 Simulink
Note that when using this syntax, the returned data is not determined by the data export
configuration, and you have to make sure that you are saving the correct signals!
For example, you can save the time vector, internal states, and output matrix as t, x and y
respectively, using
>> [t,x,y] = sim('DampedOscillator ') % Run Simulink model
You will need to use dot-notation to access the exported data, and keep in mind that like
most things in Matlab, the output structure can be indexed. For a review of structures,
see Section 3.6.
Exercise
In this exercise, you will try your hand at running the damped oscillator model with varying
model parameters, and plotting the results within the Matlab IDE.
Create a new Matlab script, and add the following model parameter initialization
clear all , close all , clc
% Constant parameters
F = 1; % Force
m = 1; % Mass
k = 1; % Stiffness
d = 1; % Damping
1. Add the command to run the damped oscillator model, saving the output structure.
2. Plot the deflection in a Figure in Matlab, and make sure it is correct.
3. Now, change the code so that the model is simulated four times, each time with a
different damping value. You can try 𝑑vec = [2.0, 1.0, 0.5, 0.2] for instance.
Hint: You may want to consider using iterations, see Section 4.3.
4. Plot the results in four separate Figures.
5. Label the plots accordingly—-so that it becomes clear which damping values were
used.
Hint: You can read more about formatting text on the MathWorks homepage.
6. Optional: Export the Figures as separate vector graphics files, see Section Section 6.4.
69
9 Simulink
𝑋(𝑠) 1
𝐺(𝑠) = = .
𝐹(𝑠) 𝑚𝑠 +𝑑𝑠+𝑘
2
Open the damped oscillator model, and add a Transfer Fcn block to the model, using some
method you prefer. Upon adding the block, open the parameters and specify the following
• Numerator coefficients: [1]
• Denominator coefficients: [m, d, k]
Next, add a new Scope, and make sure it has 2 inputs and is partitioned like in Section 9.5.2
– if you create a copy of the previous Scope, the settings will carry over. Finally, connect
it to both the output of the Transfer Fcn and the deflection signal x, and connect the input
of the Transfer Fcn to the Step output by creating a new branch. Your model should look
something like Figure 9.20.
kx
1
x
F mx'' x'' 1 x' 1
s s x
dx'
2
Figure 9.20: Comparing the output of a Transfer Fcn to the block diagram
70
9 Simulink
Upon running the simulation, you should be able to convince yourself that the two models
produce “the same” (sufficiently similar) outputs. As an optional exercise, modify the
Simulink model so that the new Scope displays the difference between the two outputs in
a third subplot. What is the order of magnitude of the difference?
71
Solutions to exercises
Elementary mathematics
clear all , close all , clc
% Variable x
x = pi;
% Test equality
diff_f = f1 - f2
diff_g = g1 - g2
Comments
Even though the functions ( 𝑓1 (𝑥), 𝑓2 (𝑥)) and (𝑔1 (𝑥), 𝑔2 (𝑥)) are in fact equivalent, and thus
should be equal for all values 𝑥 ∈ ℂ, there are some values for which the difference is
non-zero. One such case is for 𝑥 → −1, for which 𝑔1,2 (𝑥) → ∞. Matlab solves the equation
as
Inf − Inf = NaN (not a number).
Additionally, you will encounter cases where the answer is in the order of magnitude
1×10=16 . This is a numerical residual, and in most cases can be considered zero.
72
Solutions to exercises
% Number of columns
r = size(a ,2) - 1;
n = m + r;
% Diagonal columns
D = repmat (a, m, 1);
% Index vector
R = 0:r;
% Sparse diagonal
A = spdiags (D, R, m, n);
full(A)
73
Solutions to exercises
% Minimal realisation
G_cl = minreal (G_cl);
% PID controller
C = pid(C)
% Linear analysis
damp(G), stepinfo (G)
damp(G_cl), stepinfo (G_cl)
% Figures
figure ; step(G,G_cl);
legend ('Uncontrolled ','Closed -loop ')
print('ExerciseDynamicSystemStep .eps ','-depsc ','-painters ','-loose
')
Comments
In the uncontrolled system, the damping ratio of 0.5 gives rise to oscillations, with a
maximum overshoot of 16.29 %. In the controlled system, the two poles are moved onto
the real axis, which corresponds to a damping of 1, and so no oscillations or overshoot is
present. This, paired with the fact that the poles lie further to the left, gives a faster settling
time. The resulting plots can be seen in Figure 1.
74
Solutions to exercises
Step Response
Pole-Zero Map
1.2
10
Uncontrolled
Closed-loop 8
1
6
Imaginary Axis (seconds-1 )
0.8 4
Amplitude
2
0.6
0
-2
0.4
-4
0.2 -6
-8
0
0 0.2 0.4 0.6 0.8 1 1.2 -10
-25 -20 -15 -10 -5 0
Time (seconds)
Real Axis (seconds -1 )
75
Solutions to exercises
Discrete-time systems
clear 'all ', close 'all ', clc
% Comparison
figure ('Name ',sprintf ('N = %d, Ts = %1.1f', N, Ts));
step(sysC ,sysD ,sysA);
legend ('Continuous ','Discretisation ','Approximation ')
print ( sprintf ('ExerciseDiscretisation -N%d-T%[Link] ',N,Ts),
'-depsc ','-painters ','-loose ');
end
end
76
Solutions to exercises
Comments
As can be seen in Figure 2, the “accuracy” of the approximation is generally more important
than the step size. For the first-order approximation, choosing a sample-time of 1 sec
will make the system unstable, whereas using the same sample time in the second-order
approximation captures the dynamics quite well.
We can identify the approximation as the truncated Taylor expansion for the exponential
function
1 1
exp(𝑥) = 1 + 𝑥 + 𝑥 2 + 𝑥 3 + . . .
2! 3!
Using the matrix exponential command expm, we see that ZOH is equivalent to taking the
matrix exponential of the system matrix multiplied with the sample time.
Step Response
Step Response
1.5
1.2
Continuous
Continuous
Discretisation
Discretisation
Approximation
1 Approximation
1
0.8
Amplitude
Amplitude
0.6
0.5
0.4
0.2
0
0 5 10 15 20 25 0
0 2 4 6 8 10 12 14 16 18 20
Time (seconds)
Time (seconds)
77
Solutions to exercises
Simulink-Matlab integration
clear 'all ', close 'all ', clc
% Constant parameters
F = 1; % Force
m = 1; % Mass
k = 1; % Stiffness
% Plot results
figure (n);
plot(out(n).tout ,out(n).yout (: ,1))
grid on; set(gca ,'YLim ' ,[0 ,2]);
Comments
We can see that the system becomes critically damped at 𝑑 = 2, and decreasing the damping
further introduces oscillations in the system, see Figure 3. It follows that a system with no
damping (𝑑 = 0) will not display any attenuation in the amplitude of the oscillations.
78
Solutions to exercises
1.2
Amplitude
1
1
0.8
0.8
0.6
0.6
0.4
0.4
0.2
0.2
0
0 1 2 3 4 5 6 7 8 9 10 0
0 1 2 3 4 5 6 7 8 9 10
Time (seconds)
Time (seconds)
1.8 1.8
1.6 1.6
1.4 1.4
1.2 1.2
Amplitude
Amplitude
1 1
0.8 0.8
0.6 0.6
0.4 0.4
0.2 0.2
0 0
0 1 2 3 4 5 6 7 8 9 10 0 1 2 3 4 5 6 7 8 9 10
Time (seconds) Time (seconds)
Figure 3: Running the damped oscillator model with different damping values
79
Appendix
% Custom colors
c1 = [31 , 119 , 180]/255; % #1 f77b4
c2 = [255 , 127 , 14]/255; % # ff7f0e
% Data to plot
T = 1; % Time constant (sec)
t0 = 0; tf = 6*T;
t = linspace (t0 ,tf ,50); % Time vector for simulation
f1 = 1 - exp(-t./T); % Exponential smoothing
f2 = exp(-t./T)/T; % Exponential decay
tT = [t0 ,t0+T]; yT = [0 ,1]; % Help - lines for gradient at t=0
% Screen placement
set(groot ,'Units ','centimeters ')
scrn = get(groot ,'ScreenSize ') - pos;
pos (1:2) = scrn (3:4) /2;
% Add Axes
ax = axes('Parent ',fig ,...
'XGrid ','on ','YGrid ','on ','XColor ','k','YColor ','k',...
80
Appendix
% Add Lines
ln (1) = line(ax ,t,f1 ,'Color ',c1 ,'LineWidth ' ,1.0,'LineStyle ','-');
ln (2) = line(ax ,t,f2 ,'Color ',c2 ,'LineWidth ' ,1.0,'LineStyle ','-');
ln (3) = line(ax ,tT ,yT ,'Color ','k','LineStyle ','--');
% Add Legend
leg = legend ('Parent ',fig ,...
'String ',{'$f(x) = 1-e^{-t/T}$','$f''(x) = 1/T\cdot e^{-t/T}$'},
...
'Interpreter ','latex ','FontSize ' ,10,'Location ','southeast ');
81
Appendix
for i=1:4
switch i
case 1
% Step response
obj(i) = stepplot (sys);
case 2
% Pole -zero map
obj(i) = pzplot (sys);
setoptions (obj(i), 'Grid ','on ',...
'XLim ' ,[ -1.8 ,0] , 'YLim ' ,1.5*[ -1 ,1]);
case 3
% Bode diagram ( magnitude only)
obj(i) = bodeplot (sys);
setoptions (obj(i), 'Grid ','on ', 'PhaseVisible ','off ');
case 4
% Nyquist diagram
obj(i) = nyquistplot (sys);
setoptions (obj(i), 'Grid ','on ');
end
end
82