MATLAB Course - Part 3
MATLAB Course - Part 3
Topics in MATLAB
Hans-Petter Halvorsen
https://www.halvorsen.blog
Simulink and Advanced
Topics in MATLAB
University of South-Eastern Norway
MATLAB
Simulink and Advanced Topics
Hans-Petter Halvorsen, 2025.06.24
http://www.halvorsen.blog
Preface
Copyright You cannot distribute or copy this document without permission from the
author. You cannot copy or link to this document directly from other sources, web
pages, etc. You should always link to the proper web page where this document is
located, typically http://www.halvorsen.blog
In this MATLAB Course, you will learn basic MATLAB and how to use MATLAB in Control
and Simulation applications. An introduction to Simulink and other Tools will also be
given.
This is a self-paced course based on this document and some short videos on the way.
This document contains lots of examples and self-paced tasks that the users will go
through and solve on their own. The user may go through the tasks in this document in
their own pace and the instructor will be available for guidance throughout the course.
1. Introduction to MATLAB
2. Modelling, Simulation and Control
3. Simulink and Advanced Topics
In Part 3 of the course, you will learn how to use some of the more advanced features in
MATLAB. We will also take a closer look at Simulink, which is a Block Diagram
Simulation Tool used together with MATLAB. We will also give an overview to other tools
for numerical mathematics and simulation.
You must go through MATLAB Course – Part 1: Introduction to MATLAB before you start.
The course consists of lots of Tasks you should solve while reading this course manual
and watching the videos referred to in the text.
ii
Make sure to bring your headphones for the videos in this course. The
course consists of several short videos that will give you an introduction to the different
topics in the course.
What is MATLAB?
What is Simulink?
MATLAB offers lots of additional Toolboxes for different areas such as Control Design,
Image Processing, Digital Signal Processing, etc.
This training will give you the basic knowledge of Simulink and how you can use it
together with MATLAB.
http://www.halvorsen.blog/documents/teaching/courses/matlab.php
On these web pages you find video solutions, complete step by step solutions,
downloadable MATLAB code, additional resources, etc.
iii
Table of Contents
Preface ...................................................................................................................... ii
1 Introduction ........................................................................................................ 1
2 Simulink.............................................................................................................. 2
iv
v Table of Contents
9.5.6 Statistics............................................................................................. 60
http://www.halvorsen.blog/documents/programming/matlab
Part 3: Advanced Topics, Simulink and other Tools consists of the following topics:
• Introduction to Simulink
• Advanced Topics in MATLAB:
o Debugging in MATLAB
o More about functions
o More about Plots
o Using Cells in the MATLAB Editor
o Importing Data
o Structures and Cell Arrays
• Alternatives to MATLAB
1
2 Simulink
Simulink is an environment for simulation and model-based design for dynamic and
embedded systems. It provides an interactive graphical environment and a
customizable set of block libraries that let you design, simulate, implement, and test a
variety of time-varying systems, including communications, controls, signal processing,
video processing, and image processing.
Simulink offers:
• “Simulink Overview”
• “Getting Started with Simulink”
2
3 2 Simulink
The Simulink Library Browser is the library where you find all the blocks you may use in
Simulink. Simulink software includes an extensive library of functions commonly used
in modeling a system. These include:
You may now drag the blocks you want to use from the Simulink Library Browser to the
model surface (or right-click on a block and select “Add to…”).
Example:
In this example we place (drag and drop) to blocks, a Sine Wave and a Scope, on the
model surface:
When holding the mouse over an input or an output the mouse changes to the following
symbol.
Use the mouse, while holding the left button down, to drag wires from the input to the
output.
Another wiring technique is to select the source block, then hold down the Ctrl key
while left-clicking on the destination block.
If wire a connection from a wire to another block, like the example below, you need to
hold down the Ctrl key while left-clicking on the wire and then to the input of the desired
block.
All standard blocks in Simulink have detailed Help. Click the Help button in the Block
Parameter window for the specific block to get detailed help for that block.
The Help Window then appears with detailed information about the selected block:
2.4 Configuration
There are lots of parameters you may want to configure regarding your simulation.
Select “Configuration Parameters…” in the Simulation menu.
Note! Each of the controls on the Configuration Parameters dialog box corresponds to a
configuration parameter that you can set via the “sim” and “simset” commands. You
will learn more about these commands later.
Solvers are numerical integration algorithms that compute the system dynamics over
time using information contained in the model. Simulink provides solvers to support the
simulation of a broad range of systems, including continuous-time (analog), discrete-
time (digital), hybrid (mixed-signal), and multirate systems of any size.
2.5 Examples
Below we will go through some examples in order to illustrate how to create block
diagrams and related functionality.
Example:
Integrator with initial value
Create the following model (an integrator) and run the simulation:
Step 2: Configuration
Double-click on the Integrator block. The Parameter window for the Integrator block
appears:
Select “Initial condition source=external”. The Integrator block now looks like this:
Double-click on the Constant block. The Parameter window for the Constant block
appears:
In the Constant value field we type in the initial value for the integrator, e.g., type the
value 1.
Step 3: Wiring
Use the mouse to wire the inputs and outputs of the different blocks.
When holding the mouse over an input or an output the mouse change to the following
symbol.
Draw a wire between the output on the Constant block to the lower input in the
Integrator block, like this:
Wire the rest of the blocks together and you will get the following diagram:
Step 4: Simulation
Start the simulation by clicking the “Start Simulation” icon in the Toolbar:
Example:
Sine Wave
Example:
Using vectors
If you want to see the signal dimensions, select “Signal Dimensions” and “Wide
Nonscalar Lines” as shown here:
The thick lines indicate vectors, while the number (8) is the size of the vector.
As you see you may use standard MATLAB functions and syntax.
Run the simulation and see the results in the Scope block.
In this task we will simulate a simple model of a bacteria population in a jar (known from
a previous task).
birth rate = bx
𝑥̇ = 𝑏𝑥 − 𝑝𝑥 2
We will simulate the number of bacteria in the jar after 1 hour, assuming that initially
there are 100 bacteria present.
Procedure:
1. Create the block diagram for the system using “pen & paper”
2. Start Simulink and create a New Model
3. Drag in the necessary blocks from the Simulink Library Browser
4. Configure the different blocks (double-click/right-click depending on what you
need). Some blocks need to be “flipped” (Right-click → Format → Flip Block),
while in other blocks you need to set a value (double-click)
5. Draw lines between the different blocks using the mouse
6. Set Simulation Settings (Simulation → Configuration Parameters). The
simulation Time (Stop Time) should be set to 1 (hour)
7. Use a Scope to see the Simulated Result
• Sum block Note! One plus (+) must be changed to minus (-)
[End of Task]
You may use Simulink together with MATLAB to specify data and parameters to your
Simulink model. You may specify commands in the MATLAB Command Window or as
commands in an m-file. This is called data-driven modeling.
Double-click on the Scope and select the Parameters icon in the Toolbar:
You use the simset command to configure your simulation parameters and the sim
command to run the simulation.
The variables you refer to in the m-file is set in the Constant value field in the Parameter
window for each block.
• simset
• sim
Use these commands if you configure and run your Simulink model from a m-file.
Example:
%Simulator Settings
t_stop=100; %[s]
T_s=t_stop/1000; %[s]
options=simset('solver', 'ode5', 'fixedstep', T_s);
%Starting simulation
sim('mass_spring_damper', t_stop, options);
[End of Example]
In this exercise you will construct a simulation diagram that represents the behavior of a
dynamic system. You will simulate a spring-mass damper system.
where t is the simulation time, F(t) is an external force applied to the system, c is the
damping constant of the spring, k is the stiffness of the spring, m is a mass, and x(t) is
the position of the mass. 𝑥̇ is the first derivative of the position, which equals the
velocity of the mass. 𝑥̈ is the second derivative of the position, which equals the
acceleration of the mass.
The goal is to view the position x(t) of the mass m with respect to time t. You can
calculate the position by integrating the velocity of the mass. You can calculate the
velocity by integrating the acceleration of the mass. If you know the force and mass, you
can calculate this acceleration by using Newton's Second Law of Motion, given by the
following equation:
Therefore,
Substituting terms from the differential equation above yields the following equation:
1
𝑥̈ = (𝐹 − 𝑐𝑥̇ − 𝑘𝑥)
𝑚
You will construct a simulation diagram that iterates the following steps over a period of
time.
Instead of hard-coding the model parameters in the blocks you should refer to them as
variables set in an m-file.
• x_init
• dxdt_init
• m=
• c=
• k
• t_step_F
• F_O
• F_1
m-File
→ Create the model of the system in Simulink, and then create a m-file where you
specify model and simulation parameters. Then use the sim function in order to run the
simulation within the m-file.
[End of Task]
𝑥̇ = 𝑎𝑥
1
where 𝑎 = − ,where 𝑇 is the time constant
𝑇
𝑥(𝑡) = 𝑒 𝑎𝑡 𝑥0
Simulate the system in Simulink where we plot the solution 𝑥(𝑡) in the time interval
0 ≤ 𝑡 ≤ 25
[End of Task]
In all but the simplest programs, you are likely to encounter some type of unexpected
behavior when you run the program for the first time. Program defects can show up in
the form of warning or error messages displayed in the command window, programs
that hang (never terminate), inaccurate results, or some number of other symptoms.
It is difficult to write code without errors (bugs), but MATLAB have powerful Debugging
functionality, similar to other tools like, e.g., Visual Studio.
Why we call it debugging? They found a bug (actually a moth) inside a computer in 1947
that made the program not behaving as expected. This was the “first” real bug which
was debugged.
The first step in order to avoid errors is to remove all warnings and errors notifies by
MATLAB in the Editor. On the right side of the Editor there will be shown symbols to
illustrate that MATLAB have found potential errors in your code.
Warnings - Click the symbols to get more information about a specific warning
Example:
30
31 3 Debugging in MATLAB
Errors - Click the symbols to get more information about a specific error
Example:
In addition MATLAB have more sophisticated debugging tools we will learn more about
below. These are tools you use when your program is running.
The MATLAB Debugger enables you to examine the inner workings of your program while
you run it. You can stop the execution of your program at any point and then continue
from that point, stepping through the code line by line and examining the results of each
operation performed. You have the choice of operating the debugger from the Editor
window that displays your program, from the MATLAB command line, or both.
When the program is in debug-mode, the command prompt is changed to “K>>” and the
following message appears in the status bar:
A red circle indicates that you have set a breakpoint, which means your program
will stop at this place in your code and wait for further instructions from you.
The green arrow indicates at what line your program is at the moment.
Now you can use the “debugging toolbar” to step through your code:
Set/Clear Breakpoint
Continue
Task 4: Debugging
Set a Breakpoint inside the loop and use the Debugging functionality to step through the
program and watch the result in each iteration.
In addition you should open some of your previous programs you have made, and try the
debugging tools on them.
[End of Task]
Example:
We create the following function:
x = a + b;
y = a * b;
if nargin == 3
x = a + b + c;
y = a * b * c;
end
if nargin == 4
x = a + b + c + d;
y = a * b * c * d;
end
We test the function in the Command window with different inputs and outputs:
35
36 4 More about Functions
y =
6
>> [x, y] = myfunc(1,2,3,4)
x =
10
y =
24
>> [x] = myfunc(1,2)
x =
3
>> [x, y, z] = myfunc(1,2)
??? Error using ==> myfunc
Too many output arguments.
>> myfunc(1,2)
ans =
3
>>
Note! In newer versions of MATLAB, the error function is recommended instead of the
disp function, but both should work.
[End of Example]
You may have experienced standing on top of a hill or mountain, and it feels you can see
everything. How far can you really see? It depends on the height of the mountain and the
radius of the earth, as shown in the sketch below.
In this task we will create a function that finds the distance to the horizon 𝑥ℎ .
𝐷 is the diameter of the earth, 𝑅 is the radius of the earth, ℎ is your height above the
earth, where you are standing on a mountain. The radius on the earth is 𝑅 = 6378𝑘𝑚.
>>xh=horizon(h)
How far can you see if you are on top of the Mount Everest?
Make sure the function may handle vector inputs and create a help text for the function
that describes what the function is doing.
→ Create a script where you use the function to plot h vs. xh where h is a vector from 1 to
8000 meters. Create labels, title and a legend in the plot.
[End of Task]
The distance to the horizon is quite different on the moon than on the earth because the
radius is different for each.
→ Extend your function so that R could be an optional input to the function, e.g.:
>>xh=horizon(h,R)
→ Use nargin to solve the problem. Use also nargchk to validate the number of inputs.
How far could you see if the moon had a mountain similar to Mount Everest? The radius
on the moon is 𝑅 = 1737𝑘𝑚.
[End of Task]
Let say we also may want to find the angle (a) between radius to the horizon and the
observer (you are standing on top of the mountain). See the illustration above.
→ Extend your function so that the angle 𝒂 could be an optional output from the
function, e.g.:
>>[xh,a]=horizon(h,R)
→ Use nargout to solve the problem. Use also nargoutchk to validate the number of
outputs.
[End of Task]
Example:
The MATLAB code:
39
40 5 More about Plots
[End of Example]
[End of Task]
Task 9: 3D Plot
Use your xh=horizon(h,R) from a previous task to create a mesh plot where you
plot xh for different values of h and R respectively.
Tip! Call the function in nested For Loops for different values for h and R respectively.
[End of Task]
42
43 6 Using Cells in the MATLAB Editor
M-files often have a natural structure consisting of multiple sections. Especially for
larger files, you typically focus efforts on a single section at a time, working with the
code in just that section. Similarly, when conveying information about your M-files to
others, often you describe the sections of the code. To facilitate these processes, use
M-file cells, where cell means a section of code. Specifically, MATLAB uses cells for
Rapid code iteration in the Editor/Debugger — this makes the experimental phase of
your work with M-file scripts easier.
Use one of your previous scripts and divide your code into different cells. Run the
different Cells individually.
Use the Cells tools to browse between the different Cells in your script.
[End of Task]
44
45 7 Importing Data
Select, e.g., a Excel Spreadsheet File, and the Import Wizard appears:
Clicking Finish and the data from the Excel file will be available in MATLAB:
Before you start, you should watch the video “Importing Data from Files”.
Create a spreadsheet file with some data (or use an existing spreadsheet with data if
you have) and import the data into MATLAB.
[End of Task]
Before you start, you should watch the video “Introducing Structures and Cell
Arrays”
8.1 Structures
A structure is a data structure that can hold diverse data types, not necessarily
numbers, and with named data containers called fields, similar to a record with fields in
a database.
Example:
>>tank.height = 0.4;
>>tank.diameter = 0.5;
>>tank.type = 'cylinder';
>>tank
tank = height: 0.4000
diameter: 0.5000
type: 'cylinder'
[End of Example]
Create a function that calculates the volume of different objects, such as a cylinder, a
sphere, etc.
47
48 8 Structures and Cell Arrays
[End of Task]
• Python
• Octave
• Scilab and Scicos
• LabVIEW
9.1 Python
Python is a widely used high-level, general-purpose, interpreted, dynamic programming
language.
For more MATLAB look and feel the Anaconda Python distribution is recommended (with
all major Scientific packages included, such as NumPy, SciPy, Matplotlib...).
The Spyder IDE is also included (which has much more features than the basic IDE).
Python for Science and Engineering: This is a textbook in Python Programming with
lots of Examples, Exercises, and Practical Applications within Mathematics,
Simulations, etc. The focus is on numerical calculations in mathematics and
engineering. Necessary theory is presented in addition to many practical examples.
49
50 9 Alternatives to MATLAB
These textbooks can be downloaded for free. These textbooks have many of the same
examples and exercises you find in the MATLAB textbooks.
https://www.halvorsen.blog/documents/programming/python/
9.2 Octave
Octave is a free software tool for numerical analysis and visualization. The function and
command syntax are very similar to MATLAB. Many contributed functions packages (like
the toolboxes in MATLAB) are available. They cover control theory, signal processing,
simulation, statistics etc. They are installed automatically when you install Octave.
There is no SIMULINK-like tool in Octave, but there are many simulation functions (as in
Control System Toolbox in MATLAB).
Scilab is an open-source software. Since 1994 it has been distributed freely along with
the source code via the Internet. It is currently used in educational and industrial
environments around the world.
Scilab is quite like MATLAB, and the range of functions are comparable.
Octave is more like MATLAB than to Scilab. One problem with Octave has been that data
plotting is more cumbersome in Octave than in Scilab.
One nice thing about Scilab is that you get Scicos automatically installed when you
install Scilab. Scicos is a block-diagram based simulation tool like Simulink and
LabVIEW Simulation Module.
9.4 LabVIEW
LabVIEW is a graphical programming language, and it is well suited for Control and
Simulation applications.
In this chapter we will use LabVIEW to create a block diagram model and simulate it,
similar to what we have done in Simulink.
When opening LabVIEW, you first come to the “Getting Started” window.
In order to create a new VI, select “Blank VI” or in order to create a new LabVIEW
project, select “Empty project”.
When you open a blank VI, an untitled front panel window appears. This window
displays the front panel and is one of the two LabVIEW windows you use to build a VI.
The other window contains the block diagram. The sections below describe the front
panel and the block diagram.
In LabVIEW, you build a user interface, or front panel, with controls and indicators.
Controls are knobs, push buttons, dials, and other input devices. Indicators are graphs,
LEDs, and other displays.
You build the front panel with controls and indicators, which are the interactive input
and output terminals of the VI, respectively. Controls are knobs, push buttons, dials,
and other input devices. Indicators are graphs, LEDs, and other displays. Controls
simulate instrument input devices and supply data to the block diagram of the VI.
Indicators simulate instrument output devices and display data the block diagram
acquires or generates.
The difference between a “Numeric Control” and a “Numeric Indicator” is that for a
“Numeric Control” you may enter a value, while the “Numeric Indicator” is read-only,
i.e., you may only read the value, not change it.
The appearance is also slightly different, the “Numeric Control” has an increment and
an decrement button in front, while the “Numeric Indicator” has a darker background
color in order to indicate that its read-only.
After you build the front panel, you add code using graphical representations of
functions to control the front panel objects. The block diagram contains this graphical
source code. Front panel objects appear as terminals, on the block diagram. Block
diagram objects include terminals, subVIs, functions, constants, structures, and wires,
which transfer data among other block diagram objects.
Here we have basic math functions, such as Add, Subtract, Multiply, Divide, etc.
Example:
[End of Example]
LABVIEW have lots of VIs (functions) for Linear Algebra. Below we see the Linear Algebra
palette in LabVIEW:
9.5.4 Interpolation
LabVIEW offers lots of functionality for Interpolation.
9.5.6 Statistics
LabVIEW offers lots of functionality for Statistics, including basic functionality for
finding mean, median, standard deviation, etc.
9.5.7 Optimization
LabVIEW offers lots of functionality for Optimization.
9.5.9 Polynomials
LabVIEW offers lots of functionality for creating and manipulating Polynomials.
63
64 Appendix A – MathScript Functions
>SysClosed = feedback(SysIn_1,
feedback Connects two system models together to produce a
SysIn_2)
closed-loop model using negative or positive feedback
connections
>A = eye(2)
ss Constructs a model in state-space form. You also can use
>B = [0; 1]
this function to convert transfer function models to state- >C = B'
space form. >SysOutSS = ss(A, B, C)
>A = [1, 1; -1, 2]
ssinfo Returns information about a state-space system model.
>B = [1, 2]'
>C = [2, 1]
>D = 0
>SysInSS = ss(A, B, C, D)
>[A, B, C, D, Ts] =
ssinfo(SysInSS)
>[num, den] = pade(delay, order)
pade Incorporates time delays into a system model using the
>[A, B, C, D] = pade(delay,
Pade approximation method, which converts all order)
residuals. You must specify the delay using the set
function. You also can use this function to calculate
coefficients of numerator and denominator polynomial
functions with a specified delay.
>num=[4];
bode Creates the Bode magnitude and Bode phase plots of a
>den=[2, 1];
system model. You also can use this function to return the >H = tf(num, den)
magnitude and phase values of a model at frequencies >bode(H)
you specify. If you do not specify an output, this function
creates a plot.
>[mag, wout] = bodemag(SysIn)
bodemag Creates the Bode magnitude plot of a system model. If
>[mag, wout] = bodemag(SysIn,
you do not specify an output, this function creates a plot. [wmin wmax])
>[mag, wout] = bodemag(SysIn,
wlist)
>num = [1]
margin Calculates and/or plots the smallest gain and phase
>den = [1, 5, 6]
margins of a single-input single-output (SISO) system >H = tf(num, den)
model. The gain margin indicates where the frequency margin(H)
response crosses at 0 decibels. The phase margin
indicates where the frequency response crosses -180
degrees. Use the margins function to return all gain and
phase margins of a SISO model.
>[gmf, gm, pmf, pm] = margins(H)
margins Calculates all gain and phase margins of a single-input
single-output (SISO) system model. The gain margins
indicate where the frequency response crosses at 0
decibels. The phase margins indicate where the
frequency response crosses -180 degrees. Use the margin
function to return only the smallest gain and phase
margins of a SISO model.
For more details about these functions, type “help cdt” to get an overview of all the
functions used for Control Design and Simulation. For detailed help about one specific
function, type “help <function_name>”.
Plots functions: Here are some useful functions for creating plots: plot, figure, subplot,
grid, axis, title, xlabel, ylabel, semilogx – for more information about the plots
function, type “help plots”.
65
Hans-Petter Halvorsen
E-mail: [email protected]
Blog: http://www.halvorsen.blog