Lecture Notes Computermath
Lecture Notes Computermath
COMPUTERMATH
Content
1. Introduction .......................................................................................................... 3
4. Plots .................................................................................................................... 13
krj/04.09.19 2
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
1. Introduction
its main way of calculation. Nearly all mathematical operations are executed as matrix
MATLAB has been first introduced by Cleve Moler in the late 1970s and is distributed
containing basic methods and functions and can be extended by various so called “Add-
Ons” which extend the method library by special functionalities like curve fitting,
Due to this high customizability, it is a popular choice in the scientific world for all
The following pages should give a basic introduction in how to handle MATLAB and
its implemented methods and how to use it in a scientific background. Even as this
most effective when used in combination with the lecture and the practical sessions
held therein.
introductory interactive online lecture. Please feel free to check out those links:
MATLAB Academy (The Onramp course is free, you need to register for the other
krj/04.09.19 3
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
2. MATLAB desktop
The figure below gives an introductory overview of the MATLAB desktop. You can
change the desktop arrangement to meet your needs, including resizing, moving, and
closing tools.
2 3
2) Home tab – create new scripts, open files, import data, set preferences etc.
3) Current directory – View files, perform file operations such as open, find files and
5) Command history – View a log of or search for the statements you entered in the
krj/04.09.19 4
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
except that the user does not necessarily need to specify the data type. So by typing:
X = 45;
we define a variable named X of type double with a value of 45. Initially we would
guess that MATLAB would create a variable of type integer, as our numerical value
does not contain any decimals. However, in MATLAB every numerical value is saved
Y = uint8(30);
we create a variable named Y and force its type to be of integer (unsigned 8 Bit, i.e.
only positive values can be stored in Y, otherwise the value becomes 0) with a value of
Z = true;
Using a semicolon at the end of our command suppresses screen output for this
operation. If we omit it, we receive the following screen output for the above command
X=45:
X =
45
X = [1 2 3 4 5];
X = [1;2;3;4;5];
krj/04.09.19 5
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
The above vectors can also be created with the automatic spacing. Here, we define the
min and max values of vector and the increment between each value. The following
example creates a vector 𝑋 = [1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0]:
X = 1.1:0.1:2;
X = 1:5;
X =
1 2 3 4 5
If you want to create a vector with a specific number of elements, use the implemented
linspace function. linspace requires three arguments: the value of the first
element, the value of the last elements and the number of elements in the vector. So
using
X = linspace(1,10,21);
Combining the commands to create a line vector and a column vector allows us to
create a matrix:
M = [1 2; 3 4]
M =
1 2
3 4
Indexing in vectors and matrices is done differently from other programming languages.
The first index in a vector or matrix in MATLAB is 1! Thus, to access the 3rd element
Y = X(3)
Y =
2
krj/04.09.19 6
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
To access more than one element in a vector, you need to use a vector of indexes. So
X([3 4 5])
ans =
2 8 9
X(3:5)
X(3:end)
Note that end can be used, if you do not know the length of the vector, or if your
You can use indexing to overwrite a specific element in a vector with a new value:
1 2 89 4 34
MATLAB is also quite flexible when it comes to vector size, so unlike other
programming languages where the size of an array is fixed, in MATLAB you can always
add elements to a vector. To add a new element to the end of the vector above, use:
X(end+1) = 21
X =
1 2 89 4 34 21
page 6 would be 2. To access more than one element or even complete rows or columns,
M = [1 2 3 ; 4 5 6; 7 8 9]
M(1:2,1) %show all elements of row 1-2, column 1
ans =
1
4
krj/04.09.19 7
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
To transpose a vector or matrix, you can simply put ' at the end of the variable name:
M = [1 2; 3 4]
M =
1 2
3 4
M = M'
M =
1 3
2 4
X = [ 1 2 3 ; 4 5 6];
Y = [ 1 2 ; 3 4 ; 5 6];
Z = X*Y;
22 28
The result of this multiplication is: 𝑍 = 3 4. For those, who do not remember
49 64
how to calculate the product of two matrices, the detailed calculation is shown here:
1 2
5 3 4 6
5 6
1 2 3 1∙1+2∙3+3∙5 1∙2+2∙4+3∙6
7 8
4 5 6 4∙1+5∙3+6∙5 4∙2+5∙4+6∙6
The above example also explains, why matrices can only be multiplied if the number
of rows and columns of the first matrix match with the number columns and rows of
the other matrix (Matrix 1 = M1xN1, Matrix 2 = M2xN2; M1=N2, N1=M2). If you try
to multiply two matrices which violate this rule, you will get the following output:
krj/04.09.19 8
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
X = [1 2 3 ; 4 5 6];
Y = [1 2 3 ; 4 5 6];
Z = X.*Y
Z =
1 4 9
16 25 36
As you can see, all matrix elements of X were multiplied with their corresponding
Element-wise matrix division is done similarly; however, direction of the division mark
division of Y by X!
Normal matrix division shows to be more complex. Mathematically this is not defined,
1 2 2 4
𝑋=3 4,𝑌 = 3 4
4 6 8 10
ans =
0.5000 0
0.6667 0.3333
𝑎𝑑𝑗(𝑌)
𝑌 >? =
det (𝑌)
N
det (𝑦?? ) −det (𝑦?K ) det (𝑦?L )
𝑎𝑑𝑗(𝑌) = H−det (𝑦K? ) det (𝑦KK ) −det (𝑦KL )M
det (𝑦L? ) −det (𝑦LK ) det (𝑦LL )
krj/04.09.19 9
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
1 2 3
𝑌 = O4 5 6 P
7 8 10
N
5 6 4 6 4 5
𝑑𝑒𝑡 V W −𝑑𝑒𝑡 V W 𝑑𝑒𝑡 V W
8 10 7 10 7 8
⎛ 2 3 1 3 1 2 ⎞
𝑎𝑑𝑗(𝑌) = ⎜−𝑑𝑒𝑡 V W 𝑑𝑒𝑡 V W −𝑑𝑒𝑡 V W =
8 10 7 10 7 8 ⎟
2 3 1 3 1 2
⎝ 𝑑𝑒𝑡 V5 6
W −𝑑𝑒𝑡 V
4 6
W 𝑑𝑒𝑡 V
4
W
5 ⎠
2 2 −3 N 2 4 −3
O 4 −11 6 P = O 2 −11 6 P
−3 6 −3 −3 6 −3
2 1
− −1 1
⎛ 3 3 ⎞
𝑌 >? =⎜ 2 2
− 3 −2⎟
3 3
⎝ 1 −2 1⎠
== equal to
~= not equal to
> greater than
< less than
>= greater than or equal to
<= less than or equal to
If you compare two vectors or matrices by using a relational operator, the result is a
A = [1 2 5 10 -5];
B = [3 5 -7 2 -1];
A>B
ans = 0 0 1 1 0
krj/04.09.19 10
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
The result contains only 0 and 1 which refer to true (1) and false (0), i.e. at which
index the value in A is larger than in B. These operations can be exploited easily for
all values in B that are smaller than 0. Therefore, we first have to create a vector
containing only 0. This can be achieved easily by applying the function zeros:
Now we compare B and C by applying the relational operator > and save the results
in D:
D = B>C
D = 1 1 0 1 0
Using results vector D as an indexing vector, we can eliminate all values in B that are
smaller than 0, i.e. we overwrite B with a vector that only contains the values greater
zero in B:
B = B(D)
B = 3 5 2
As you can see above, B now only contains positive values, all other have been
eliminated. The whole process can also be achieved in just one statement:
B = B(B>0)
This method provides a fast and computationally cheap way of selecting certain values
inside a vector or matrix without using any loops. It can be applied with any relational
operator.
In order to combine multiple conditions, we need to connect each of the conditions with
& AND
| OR
~ Negation
krj/04.09.19 11
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Example:
We extract all values in vector A that are greater than 1 and are not equal to 8.
A = [2 5 -7 2 8 1];
B = A>1 %Condition1: All values in A that a greater than 1
C = A~=8 %Condition2: All values that are not equal to 8
B = 1 1 0 1 1 1
C = 1 1 1 1 0 1
D = B&C %Combine condition1 and condition2
D = 1 1 0 1 0 1
A(D) %Apply the Boolean vector to A
ans = 2 5 2
A(A>1&A~=8)
The conditions used as index do not necessarily need to refer to the same vector that
Example:
We have recorded some data and saved the data in two vectors. Vector pressure
temperatures at the same time points. Now we would like to create a vector
temperature was between 10°C and 20°C. Thus, we apply a conditional index on
pressureTempSorted = pressure(temperature>=10&temperature<=20)
krj/04.09.19 12
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
4. Plots
One major application field for MATLAB is data processing, so plots are a fundamental
piece of this programming language. They are easy to create and include a wide variety
chapter.
Basic plots
The plot command in MATLAB requires at least one argument, i.e. the vector of values
you want to display. However, the most common way to use the plot command is to
provide two arguments: a vector containing the values to display (ydata), and a vector
with the respective x-values (xdata), e.g. a time vector. The time vector does not have
to be equally spaced, but vector length of both vectors has to be equal. Thus, the
plot(xdata,ydata)
Example:
t = (0:0.01:2);
sinfkt = sin(10*pi*t); %Calculate sinus of 10*pi*t.
plot(t,sinfkt);
krj/04.09.19 13
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Apart from the line plot shown above, other plot formats are possible:
Examples:
t = 0:0.1:4;
y = sin(t.^2).*exp(-t);
stem(t,y)
krj/04.09.19 14
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
figure;
stairs(t,y)
If you want to show only details of your plots, you can limit the axes by using the
axis command. The command shown below limits the visible plot from 2 to 4 on the
Providing a title for your figure as well as labeling the plot axes helps in understanding
the figure. MATLAB provides functions for both; in the example below, we are plotting
plot(t,data);
xlabel('time[s]')
ylabel('pressure[mbar]')
title('Experiment 1')
krj/04.09.19 15
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Line specifications
To set a specific color in your plot, you can add an argument in the plot command.
plot(xdata,ydata,'COLOR');
Color Command
red r
green g
blue b
cyan c
magenta m
yellow y
black k
white w
The line specifications can also be further extended by information about the line style
and marker type. It is not necessary to provide all three options, omitting one leads to
MATLAB using the default option, i.e. blue color, solid line or no markers, respectively.
The general form of using a combination of color, line style and marker style is:
plot(xdata,ydata,'ColorLinestyleMarkerstyle');
cross x
square s
diamond d
upwards triangle ^
downwards triangle v
triangle to the left <
triangle to the right >
pentragram p
hexagram h
Example:
x = -10:10;
plot(x,x.^2,'r:*');
Additional options are available by adding parameters to the function call of plot. The
Option Command
color Color
line style LineStyle
line width LineWidth
marker style Marker
size of markers MarkerSize
marker color MarkerEdgeColor
Each parameter needs to be paired with the desired value (so called “name-value” pairs).
This way colors other than the above can be specified by entering the RBG values of
krj/04.09.19 17
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
the desired color, normalized to 1. To draw the example below with an orange solid
line of width 5 and black hexagram markers of size 9 you need to use:
krj/04.09.19 18
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Multiple plots
If you need to plot more than one plot in one figure, there are two ways to do it:
t = (0:0.01:2);
sinfkt = sin(2*pi*5*t);
cosfkt = 2*cos(2*pi*3*t);
expfkt = exp(-2*t);
Example 1:
Example 2:
plot(t,sinfkt);
hold on; %this command tells MATLAB not to overwrite
%the figure when using the next plot command
plot(t,cosfkt,'g'); %'g' is used to make the cos-plot
%appear in green
plot(t,expfkt,'r'); %plot in red
Examples 1 & 2 result in the same figure and may be used depending on which version
suits best for the actual code you are planning to write:
krj/04.09.19 19
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Here, the sinus function is plotted in black with “+” as markers, the cosinus function is
plotted in blue with broken lines and no markers and the exponential function is plotted
To add a legend describing your plot as well as a grid to make reading the graph easier,
you can use the following commands. For each line plotted, the legend shows a sample
of the line type, marker symbol, and color beside the text label you specify.
Using legend you have to respect the order in which you have plotted the different
A wide variety of additional properties can be accessed and changed using the handles
to both the axes object (showing the plot) and the figure object (housing the axes
object). To change properties in those objects you need to use set. Some examples are
shown below:
krj/04.09.19 20
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
t = 0:0.01:15;
x = sin(t*7).*sin(t/2);
plot(t,x,'m','linewidth',2)
grid on
set(gca,'YTick',[-1:0.1:1]) % Sets the ticks on the y-axis to
% -1,-0.9,-0.8...0.9,1
set(gca,'YMinorGrid','on') % Enables an additional minor grid
% pattern on the y-axis
set(gca,'GridColor','r') % Sets the color of grid lines to red
set(gca,'MinorGridColor','g') % Sets the color of the minor grid
% lines to green
% Sets the position of the figure to 440 pixels away from the left
% screen edge and 380 pixels from the bottom edge with a size of
% 840x420 pixels.
set(gcf,'Position',[440 380 840 420])
Multiple plots do not necessarily have to be plotted together into one figure window,
MATLAB also provides the opportunity to distribute them onto multiple plots in one
subplot(m,n,p);
Using this function you have to provide three arguments: arguments m and n provide
information about the size of the mxn-matrix the figure window is segmented into, p is
the number of the axis object you want to use for your actual plot. The axis objects
are numbered along the top row of the figure window, then the second row, etc.
krj/04.09.19 21
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Example:
t = (0:0.01:2);
sinfkt = sin(2*pi*5*t);
cosfkt = 2*cos(2*pi*3*t);
expfkt = exp(-2*t);
subplot(2,2,1) % Applying a 2x2 plot-matrix and selecting
% axis object 1 (upper left corner)
plot(t,sinfkt,'Linewidth',2);
title('Sinus plot')
xlabel('time [s]')
ylabel('amplitude')
subplot(2,2,2);
plot(t,cosfkt,'linewidth',2);
title('Cosinus plot')
xlabel('time [s]')
ylabel('amplitude')
subplot(2,2,[3 4]); % Place this plot along axis objects 3 and 4
plot(t,expfkt,'linewidth',2);
title('Exponential plot')
xlabel('time [s]')
ylabel('amplitude')
krj/04.09.19 22
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
3-Dimensional plots
Besides 2-D plots MATLAB also offers the tools to build 3-dimensional plots. The
previously used command plot is not applicable for 3-dimensional plots. In the following
example we will use mesh to create a mesh representation of our 2-dimensional data Z.
x = (-3:0.1:3);
y = (-3:0.1:3);
v = ones(length(x),1); %Create a column vector v with the
%same length as x
X = v*x; %Create a matrix X with structure:
%-3 -2.9 -2.8 ... 3
%-3 -2.9 -2.8 ... 3
%... ... ... ... ...
%-3 -2.9 -2.8 ... 3
krj/04.09.19 23
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
5. Data I/O
As mentioned above, MATLAB is widely used in data analysis. Therefore, data I/O is
an important function in MATLAB. You can save and load data in several formats,
with simple text files (*.txt) and Microsoft Excel files (*.xlsx and *.csv) being the ones
Data saved in ASCII format text files can be imported by using the load command,
saving data is done by using save. load only requires the filename, or the full file
path if the file is not located in the current working directory. If no variable is specified,
MATLAB creates a new variable named after the filename containing the imported
values. save requires the file path as well as the data vector or matrix that contains
the data to be saved. If no file with the given name exists, a new file will be created.
In the following example we are importing data from a file Data.txt in the current
directory. Afterwards we are multiplying every data point by the factor 4 and save the
X = load('Data.txt');
NewX = X*4;
save('NewData.txt','NewX','-ascii') %Save new data in ASCII format
MATLAB provides special functions to read and write *.xlsx files. xlsread opens a
Microsoft Excel file and imports the data into MATLAB. If only the filename is
provided, the function will only read data from the first worksheet. Additional
parameters like worksheet and range can be assigned. When saving the data into an
Excel file using xlswrite the user has to provide a filename and the data that has to
Measurement1, range B3:B67. Afterwards we are extracting some data and save it to
krj/04.09.19 24
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Using xlsread and xlswrite is valid if you are importing data from files that only
contain numeric values (apart from an optional header line). If you want to import a
file that contains data of different data types, using readtable is a better option.
readtable automatically creates a variable of type table that contains the different
Example:
The file patientinfo.xlsx contains info such as last name (text), height (numeric) and
Pinfo = readtable('patientinfo.xlsx')
Columns Lastname, Firstname, Gender and Treatment_group are now of type cell
array (i.e. a vector containing values of type String with different lengths), columns
krj/04.09.19 25
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Age and Height are of type numeric, and Day_admitted is a datetime array. Each
column of the table can be accessed by using the dot operator, single values by using
an index:
pinfo.Gender(2)
ans =
{'female'}
pinfo.Day_admitted(2:4)
ans =
16-Sep-2017
19-Oct-2017
23-Oct-2017
If you want to write code that allows the user to select a file to be opened at runtime,
you can provide a graphical dialog by using uigetfile. uigetfile lets you specify
filters so that only a certain file type is visible, a dialog title that appears in the top
row of the file dialog and a default folder in which the dialog starts. In the following
opened. It allows the user to open files with formats *.txt, *.xlsx and *.mat.
[filename,pathname] = uigetfile({'*.txt;*.xlsx;*.mat'},...
'Select Measurement file')
krj/04.09.19 26
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
uigetfile returns two variables: filename and pathname. To create a full filepath
(i.e. recompose the separated parts filename and pathname to a filepath), you can use
fullfile:
filepath = fullfile(pathname,filename);
To open a similar dialog to select a file to save to, you can use uiputfile. It has the
krj/04.09.19 27
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
So far, we have only used the MATLAB command window for executing our
and execute it from the MATLAB command history. Additionally, entering extensive
code into the command window can be an annoying task when there is still debugging
to be done.
MATLAB offers the opportunity to save code into MATLAB executable files, so called
m-files (derived from their file extension *.m). New m-files are created by clicking
New®Script or using WIN+S (⌘+S for mac). MATLAB differentiates between two
types of m-files: m-scripts and m-functions. M-scripts only contain a sequence of code
and are mainly used to execute commands that are needed on a regular basis. They
can be executed from the m-file editor (using the Run button or F5) or the MATLAB
command window (by typing the filename of the m-script). In contrast to that, m-
functions provide code that can be executed from other m-functions or m-scripts. M-
functions can receive parameters and return values to the calling function. The syntax
for creating an m-function is (in the first code line of the file):
whereas myfun is the name of your function; in and out are the input and output
In the example shown above, mean and stdev are the return or output parameters.
They need to be defined in the code, otherwise the function will not execute. After all
krj/04.09.19 28
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
statements are executed, the actual values of mean and stdev are returned. The function
While m-scripts access the normal MATLAB workspace, each m-function has their own
workspace. So every value, vector or matrix that is required in the function must be
passed as a parameter. In the above example, only one input (i.e. a vector of numbers
of which the mean and standard deviation is calculated) is required. After execution of
the function is finished, that particular workspace is deleted, i.e in the above example
previously done in a graphical user interface. That allows you to automate workflows
without having to code a single line. Below are examples how to generate code from a
Plots
Plots can be modified graphically, i.e. using the Edit Plot button and then double-
click in the figure opens a user interface that allows to modify all properties (line styles,
markers, legends, grid lines, etc.) of the plot. After setting all properties to the desired
values, the styling of the plot can be exported as a function (File®Generate Code),
allowing the recreation of that same plot using different data. The exported function
can also be modified to tune for different usages. Below, you can see the GUI to modify
the plot along with parts of the generated code. The generated function is called
createfigure and requires two inputs: the vector of x-values and a matrix of y-
values.
krj/04.09.19 29
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
% Create figure
figure1 = figure;
% Create axes
axes1 = axes('Parent',figure1);
hold(axes1,'on');
krj/04.09.19 30
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Data import
Right-clicking on data files (e.g. .xslx, .xls, .txt,...) opens the Import dialog. MATLAB
automatically selects the optimal output type (e.g. table, numeric matrix, ...). You
can select the range of data to be imported and change the output type to your own
preference. Using Import Selection imports the selected data naming the variable
containing data the same as the file name. To generate a code that allows you to repeat
and modify that import use the drop-down menu below Import Selection and select
Generate Script or Generate Function. A script uses a fixed file path to import
from while a function allows you to hand over the file path and other parameters (e.g.
worksheet, range, etc.) at runtime. The available choice for output types in the user
interface depend on the type of the selected file while the selected output type affects
krj/04.09.19 31
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
%% Create table
bacteriagrowth = table;
krj/04.09.19 32
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
As in any other high-level programming language, loops and conditions can be used to
control program flow. Below, both methods and exemplary application will be shown.
Loops
Consider the following case: we need to compute the amount of a decaying radioactive
element over time. So if the element has an initial amount (t=0) of R(0) = 20kg and
it loses adecay=17% of its mass each year, than the remaining amount after one year is:
alpha_decay = 0.17;
R(1) = 20; %[kg] In MATLAB index starts at 1, so year 0 is index 1
R(2) = R(1)-R(1)*alpha_decay;
R(3) = R(2)-R(2)*alpha_decay;
R(4) = R(3)-R(3)*alpha_decay
R =
Thus, 11.4 kg of our element remain after three years. Now, if you need to make that
calculation for a timespan of 50 years, copying and adjusting all that code would be
both time-consuming and error-prone. Computers are made to repeatedly execute the
same tasks. So what we need to do to make the code more efficient is using a loop.
krj/04.09.19 33
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
for-loops
For-loops are the choice when you know the number of iterations that need to be
executed (e.g. the number of years we want to calculate the radioactive decay for).
They need to be given a counter variable that can be used inside the loop to get the
current number of iterations. Below is the same calculation as above but using a for-
loop:
alpha_decay = 0.17;
R(1) = 20;
Note, that the definition of the counter above is basically a vector i=[2,3,4].
Multiple loops can be nested within each other. So, if you nest two loops, for every
iteration of the outer loop, the inner will run through all defined counter steps. Below,
we are using nested for-loops to create a so-called Hilbert matrix of size 5. The element
in the mth row and nth column in a Hilbert matrix is defined as:
1
𝐻(𝑚, 𝑛) =
𝑚+𝑛−1
Thus, to create a Hilbert matrix of size, we need a loop to cycle through m={1,2,…,5}
krj/04.09.19 34
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
a Hilbert matrix of size 3000 using the above code takes about 0.072s on a normal PC,
however if you do not pre-allocate matrix H, its memory size changes with each
iteration, slowing down the code considerably. Running the same code with no pre-
allocation therefore takes 0.76s, more than a tenfold increase of computing costs.
MATLAB does its calculations in vectors and matrices, thus some calculations that
require loops in other programming languages, can be done in MATLAB without loops,
using only vector operations. The example above can thus be rewritten to:
Using that code results in a computing time for H of 0.0067s, so less than a tenth of
krj/04.09.19 35
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
while-loops
Unlike for-loops, while-loops continue iteration as long as a predefined condition
statement is true. Therefore, they are best used in situations where the required number
of iterations is unknown. All conditional and Boolean operators can be applied to define
the condition statement. In case of AND (&), OR (|) and EQUAL (=), you have to
use double notation (&&,||,==). The following example transfers a given number from
decimal to binary system. As the number of loops depends on the input, a while loop
fits perfectly:
y = 25;
result=[];
while y > 0
remainder = mod(y,2);%mod calculates the remainder of a
%division, here it is the remainder of
y/2
result(end+1)=remainder;
y = floor(y/2); %calculate y/2 and round off result
end
result = fliplr(result) %flip result vector left to right
result =
1 1 0 0 1
Conditions
Conditions are used to control the execution of certain commands. The basic use of
respective code is executed; if the condition is not met, the respective code is skipped.
code if the given condition is not true. elseif allows application of a separate condition
to the else clause. To create if-else statements you can use all conditional and Boolean
operators. In case of AND (&), OR (|) and EQUAL (=), you have to use double
notation (&&,||,==). The following example evaluates if a given year is a leap year.
A leap year is defined as a year where its remainder of the division by 4 is 0 and the
remainder of the division by 100 is not 0. Additionally, all years with a remainder of 0
krj/04.09.19 36
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
years = [2000;2002;2004];
for k = 1:length(years)
rem4 = mod(years(k),4);
rem100 = mod(years(k),100);
rem400 = mod(years(k),400);
if (rem4 == 0 && rem100 ~= 0)||(rem400 == 0)
fprintf('%i is a leap year\n',years(k));
else
fprintf('%i is not a leap year\n',years(k));
end
end
Above, the command fprintf is used to prompt text on the command window. “%i”,
the so-called conversion character that indicates, that at this position a variable should
be prompted in integer format. The variable is defined at the end of the statement, i.e.
years(k). \n, a so-called escape character is used to jump to a new line afterwards.
fprintf offers a wide variety of output options. To limit the number of decimal places
when printing floating points, you can add field width and precision information to the
conversion character. Thus, using %5.3f would print a floating number with a
Example:
y = 107784.7843;
fprintf('y = %5.3f',y);
y = 107784.784
Switch
Using if-else-statements for multiple distinct cases is not applicable due to the complex
structure a program can become in this instance. Here, a switch-structure can be very
helpful. Switch executes one set of statements selected from an arbitrary number of
alternatives. The following example allows conversion of a given number from decimal
to hexadecimal system. As results can be both numeric and characters (A-F), the code
krj/04.09.19 37
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
needs to distinguish between remainders that are 0-9 and the remainders 10-15. In the
latter case the respective hexadecimal character has to be selected for the current
remainder.
y = 307292;
result=''; %result has to be vector of chars
while y > 0
remainder = mod(y,16);
if remainder < 10
%convert the numerical remainder into a char
result(end+1)=num2str(remainder);
else %if remainder >9, than select respective character
switch(remainder) %return the character that resembles
%that remainder in the hexadecimal
%system
case(10)
remainder = 'A';
case(11)
remainder = 'B';
case(12)
remainder = 'C';
case(13)
remainder = 'D';
case(14)
remainder = 'E';
case(15)
remainder = 'F';
otherwise
error('remainder >15!'); %stop the program and
%show an error
end
result(end+1)=remainder;
end
y = floor(y/16); %calculate y/16 and round off result
end
applicable. Here, the code is stopped and an error is shown in the command window.
krj/04.09.19 38
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Consider the following situation: you have recorded some data with a measurement
x_data = load('Interp_data_x.txt');
y_data = load('Interp_data_y.txt');
plot(x_data,y_data,'r+','linewidth',1.5,'Markersize',9)
title('Measurement 1')
xlabel('time [s]')
ylabel('amplitude')
Now we would like to obtain the value at 8 seconds. However, there is no measurement
at that time point. To at least get an estimated value, we can interpolate between the
value at 7.2s and 8.4s. The simplest way here is linear interpolation:
𝑓? − 𝑓k
𝑓(𝑥) = 𝑓k + ∙ (𝑥 − 𝑥k )
𝑥? − 𝑥k
Here, f(x) is the value at 8s that we want to find, f0 is the value at x0 (i.e. 7.2s), while
f1 is the value at x1 (i.e. 8.4s). To use linear interpolation, we use the interp1 method
krj/04.09.19 39
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Now, we have found a value at 8s, but is it the right one? If you look at the data it
looks like some polynomial of certain degree, so the interpolated value at 8s seems a
little off. As mentioned above, we used linear interpolation (the default setting in
interp1) to find the value at 8s, using the information of its closest neighbors at 7.4s
and 8.2s. A more realistic interpolation can be done using spline-interpolation. A spline
interpolation uses low-degree polynomials in each of the intervals, i.e. between two
points, and aims at smoothly fitting the separate polynomial pieces together. The
following code compares a linear interpolation of the measured data with a spline
%Interpolate the whole data set using the denser x_new vector as
%the base
y_new = interp1(x_data,y_data,x_new);
plot(x_new,y_new,'Color',[1 0.3 0.3],'Linestyle',...
'--','linewidth',1.5);
%Spline interpolation
y_new_spline = interp1(x_data,y_data,x_new,'spline');
y_8_spline = interp1(x_data,y_data,8,'spline'); %the value at 8s
%using spline
fprintf('Value at 8s (spline): %1.3f\n',y_8_spline)
plot(x_new,y_new_spline,'Color',[0.5 0.5 0.5],'Linestyle',...
'--','linewidth',1.5);
krj/04.09.19 40
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Even though we now have a reasonable estimate of the value at 8s, we still do not
know the polynomial behavior the measured data was following. Thus, we have to fit
a polynomial to the data above. The data looks like a polynomial of at least 3rd degree,
krj/04.09.19 41
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
the polynomial coefficients in a vector p, which has a length of n+1. polyval allows
the above example we evaluate a vector of x-values (x_test) to see the polynomial as
a curve. The result is not yet satisfying, so we might try using a higher degree
polynomial:
We now have a perfect fit and we can evaluate the polynomial at x = 8s:
y_8 = polyval(p5,8);
fprintf('Value at 8s: %1.3f\n',y_8)
Value at 8s: -15.021
Using polyval always bears the risk of overfitting, i.e. using a polynomial of a degree
that is much higher than the one defining the measured data. The higher the select
degree of the fitted polynomial, the more unstable the result becomes. In the following
krj/04.09.19 42
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
The fit to the data is still perfect, but using this polynomial to extrapolate would result
in incorrect values. The same effect can be seen in noisy data. In the example below,
some noisy data is fitted using a polynomial of 1st degree (i.e. a line of best fit) and a
While the 10th degree polynomial provides a better fit to the data, the 1st order
polynomial provides a better generalization and is influenced less by the noise. Thus,
using the linear function would provide better results when extrapolating. Parameter
identification
krj/04.09.19 43
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
9. Parameter identification
In the previous chapter we have used interpolation and polynomial fitting to receive
information that was initially missing in recorded data. While that approach is feasible
Now we would like to know the expected saturation at 200mmHg PaO2. That we can
K L s
100 ∙ n𝑎? ∙ 𝑃𝑎𝑂K(pqr) + 𝑎K ∙ 𝑃𝑎𝑂K(pqr) + 𝑎L ∙ 𝑃𝑎𝑂K(pqr) + 𝑃𝑎𝑂K(pqr) t
𝑆𝑎𝑂K = K L s
𝑎s + 𝑎u ∙ 𝑃𝑎𝑂K(pqr) + 𝑎v ∙ 𝑃𝑎𝑂K(pqr) + 𝑎w ∙ 𝑃𝑎𝑂K(pqr) + 𝑃𝑎𝑂K(pqr)
𝑎? = −8,5322289 ∙ 10L
𝑎K = 2,1214010 ∙ 10L
𝑎L = −67,073989
1
Kelman GR (1966) Digital computer subroutine for the conversion of oxygen tension into saturation. J Appl Physiol 21:1375-1376
krj/04.09.19 44
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
𝑎s = 9,3596087 ∙ 10u
𝑎u = −3,1346258 ∙ 10s
𝑎v = 2,3961674 ∙ 10L
𝑎w = −67,104406
As you can see, we also need PaCO2, body temperature (T) and blood pH at the time
of measurement. Now, what if we have not recorded T and pH? Kelman’s equations
shown above are a model of the human oxygen dissociation. If we consider T and pH
the values of T and pH that existed during the measurement. To do so, we need to
find the values of T and pH that lead to a minimal difference between the recorded
data (i.e. SaO2) and the modelled values (using Kelman’s equations). In general, we
minimize the difference between the recorded data ydata (i.e. SaO2) and the calculated
results of a function F(x, xdata), where xdata is the input to the function (i.e. PaO2)
and x are the parameters that need to be identified (i.e. T and pH). To compensate for
positive and negative differences between ydata and F(x, xdata) usually the sum of
2
min‖𝐹(𝑥, 𝑥𝑑𝑎𝑡𝑎) − 𝑦𝑑𝑎𝑡𝑎‖ = min ˆ(𝐹(𝑥q , 𝑥𝑑𝑎𝑡𝑎q ) − 𝑦𝑑𝑎𝑡𝑎q )K
… 2 …
q
optimization tasks in the curve fitting and the optimization toolbox. A less
sophisticated but still applicable algorithm for us is fminsearch, which is part of the
MATLAB core library. Here, the user itself has to calculate the difference between the
measured data and the calculated results and return some error value. fminsearch
only tries to minimize this error by alternating the parameter values. Thus, the user is
krj/04.09.19 45
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
First, we need to create a function containing the above model oxygen dissociation:
% Compute saturation
a1 = -8.5322289*10^3;
a2 = 2.1214010*10^3;
a3 = -6.7073989*10^1;
a4 = 9.3596087*10^5;
a5 = -3.1346258*10^4;
a6 = 2.3961674*10^3;
a7 = -6.7104406*10^1;
SaO2 = 100*(a1*vPO2+a2*vPO2.^2+a3*vPO2.^3+vPO2.^4)./...
(a4+a5*vPO2+a6*vPO2.^2+a7*vPO2.^3+vPO2.^4);
Next, we require a function that calculates and returns an error value that
because the objective of fminsearch is to minimize the output of that function. That
(here: T and pH) and all other information and data that is required to calculate the
Temp = x(1);
pH = x(2);
SaO2_m = zeros(1,length(PaO2_r));
Above, the deviation between desired output (i.e. the measured values) and the
predicted output is calculated as summed squared difference. The user can influence
krj/04.09.19 46
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
the fitting process by applying alternate methods for error calculation (e.g. weighing
factors, etc.). Finally, we require a script that imports the recorded data and starts
fminsearch:
PaO2_r = load('measured_PaO2.txt');
SaO2_r = load('measured_SaO2.txt');
figure
plot(PaO2_r,SaO2_r,'rx','linewidth',2','markersize',9);
xlabel('PaO_2 [mmHg]');
ylabel('SaO_2 [%]');
title('Measured oxygen saturation')
set(gca,'Xgrid','on','Ygrid','on');
x = fminsearch(@(x) obj_func_GasDissO2(x,PaO2_r,SaO2_r,PaCO2),...
initial_guess);
Temp = x(1);
pH = x(2);
fprintf('Temperature: %2.1f\n',Temp);
fprintf('pH: %1.2f\n',pH);
Temperature: 36.5
pH: 7.51
contain the fitted parameters. The identification results in a pH of 7.51 and a body
temperature of 36.5 °C. To evaluate the identification result and compare it with the
recorded data, we create a new vector of PaO2 values and calculate the model result
for SaO2 using the model with its newly identified parameters:
PaO2 = PaO2_r(1):10:PaO2_r(end);
SaO2 = zeros(1,length(PaO2));
for i = 1:length(SaO2)
SaO2(i) = GasDissociation(PaO2(i),Temp,pH,PaCO2);
end
hold on
plot(PaO2,SaO2,'Color',[0.5 0.5 0.5],...
'linestyle','--','linewidth',1.5);
krj/04.09.19 47
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Now, we can use the identified model to calculate the expected SaO2 at other PaO2.
The example below computes the expected SaO2 at 200mmHg PaO2. Because %
indicates a numeric value or string is going to be inserted into the text at that point,
we need to insert the % character for the saturation output as a separate string to
SaO2_200 = GasDissociation(200,Temp,pH,PaCO2);
fprintf('SaO2 @200mmHg PaO2: %2.2f%s',SaO2_200,'%');
SaO2 @200mmHg PaO2: 99.52%
As default settings, fminsearch evaluates the given objective function 200 times for
each variable provided or until the error value that is returned is below 10-4 (i.e. the
termination tolerance). If you need to have a more accurate fit than that or if the
evaluations is not sufficient to reach an acceptable result, you can modify those options
modified and the value that you want to set for it. Thus, to set a maximum limit for
the function evaluations of 10000 and a termination tolerance of 10-6 you would call
krj/04.09.19 48
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
...
opt = optimset('MaxFunEvals',10000,'TolFun',1e-6);
x = fminsearch(@(x) obj_func_GasDissO2(x,PaO2_r,SaO2_r,PaCO2),...
initial_guess, opt);
...
In the above example, we have used initial values of T=37, pH=7.45, i.e. the standard
values for a healthy human. In our case, those were fairly close to the correct values,
allowing the algorithm behind fminsearch to rapidly converge to the correct results.
or if the initial values are chosen far away from the correct values, the algorithm might
fail to find appropriate values reproducing the measured data and instead terminate
without returning optimal parameter values or with values that are unrealistic (e.g.
negative body temperature). The figure below schematically shows the error surface of
global minimum
local minimum
Here, we find two minima, one being the lowest point in a local area (i.e. the local
minimum) and one being the lowest value overall (i.e. the global minimum). We require
the algorithm to find the global minimum; there, the corresponding values of the
parameters 𝑥⃗ are the closest value to the correct parameter values. However, if we
would set the initial guess for 𝑥⃗ close to or even left of the local minimum, chances are
krj/04.09.19 49
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
high that the algorithm would end up there, providing us with a false result. As an
example, we run the above script again, using 𝑥⃗ = {1 1} for 𝑥⃗ = {𝑇 𝑝𝐻}. The result
Temperature: -3.8
pH: 5.09
As the correct parameter values are unknown to us upon starting the parameter
data to find appropriate initial conditions or at least set plausible initial guesses.
krj/04.09.19 50
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
approximations of the solution are still feasible. MATLAB provides tools to numerically
solve ordinary (and partial) differential equations. The solver algorithms differ in their
application field, i.e. some are specialized for stiff systems whereas others are best to
be used for computationally intensive problems. For example, algorithm ode45 (ODE
stands for Ordinary Differential Equation) is a variable step solver using the 4th and
5th order Runge-Kutta solutions to approximate the numerical error for step size
𝑦 = 𝑦?
𝑑𝑦?
𝑦̇ = = 𝑦K
𝑑𝑡
𝑑𝑦K
𝑦̈ = = 𝑦L
𝑑𝑡
When solving the system, MATLAB calculates 𝑦? , 𝑦K and 𝑦L for every simulation time
step, while we have to provide 𝑦̇ ? , 𝑦̇ K and 𝑦̇ L . The m-function containing our set of
differential equation has to receive the current simulation time 𝑡 and the vector of
krj/04.09.19 51
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
function dy = my_ode(t,y)
%y(1) = y1
%y(2) = y2
%y(3) = y3
%dy(1) = dy1 = y2
%dy(2) = dy2 = y3
%dy(3) = dy3 = (20-1/2*y1+y2)/5
dy(1) = y(2);
dy(2) = y(3);
dy(3) = (20-0.2*y(1)-1.7*y(2)-y(3))/5;
To start the simulation we execute the following statement in the MATLAB command
window or in a script:
The function parameters are from left to right: the inputs to our ODE function that
the solver is allowed to change, the name of the function containing the system of
ODEs, the simulation time vector, i.e. the time steps we want MATLAB to calculate
values at, and the initial values. The output vector t contains the timesteps at which
MATLAB solved the ODE, while the output matrix y contains 𝑦? , 𝑦K and 𝑦L i.e. 𝑦, 𝑦̇
and 𝑦̈ as separate columns (i.e. y1 in the 1st column, y2 in the second column, etc.).
figure
plot(t,y(:,1),'linewidth',1.5); %y1
hold on
plot(t,y(:,2),'linewidth',1.5); %y2
plot(t,y(:,3),'linewidth',1.5); %y3
xlabel('time[s]')
ylabel('amplitude')
legend('y1=y','y2=y''','y3=y''''');
krj/04.09.19 52
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
To be able to pass parameters to our ODE system, e.g. computing the more general
function dy = my_ode(t,y,params)
a = params(1);
b = params(2);
c = params(3);
d = params(4);
e = params(5);
dy = zeros(length(y),1);
dy(1) = y(2);
dy(2) = y(3);
dy(3) = (e-d*y(1)-c*y(2)-b*y(3))/a;
krj/04.09.19 53
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
𝑑𝑥
= 2𝑥 − 3𝑦
𝑑𝑡
𝑑𝑦
= 3𝑥 − 𝑦
𝑑𝑡
To solve such a system in MATLAB, we simply need to rewrite the above system to:
𝑑𝑦?
= 2𝑦? − 3𝑦K
𝑑𝑡
𝑑𝑦K
= 3𝑦? − 𝑦K
𝑑𝑡
function dy = my_ode_system(t,y)
% x = y1 = y(1)
% y = y2 = y(2)
dy = zeros(length(y),1);
dy(1) = 2*y(1)-3*y(2);
dy(2) = 3*y(1)-y(2);
krj/04.09.19 54
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
MATLAB offers the possibility of creating apps to allow other users to easily start
functions that you have created or visualize their results. MATLAB provides a toolbox
– App Designer – that provides a graphical interface to create apps. Using the App
Designer, we can place components like buttons, sliders, checkboxes or pop-up menus
on a canvas and then define the code that is executed when a user interacts with those
components.
The following example is meant to introduce the basic steps in creating apps in
import data and display it on the screen. The figure below shows a rough sketch of
krj/04.09.19 55
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
• A small plot that shows the imported data with the current plot settings
• Three dropdown menus to select the color the plots should appear in
We expect the data to be saved as a comma separated file (.csv) where the first column
contains the time, the second column the pressure, the third column the flow and the
Upon starting the App Designer (using the command appdesigner in the command
krj/04.09.19 56
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
1. The component library: Here you will find all component types that you can
2. The canvas: Here you will place the components to define the graphical layout
of your app.
3. The component browser: Lists the components currently on your app canvas.
Here you can add new callbacks that define the behavior of your components.
5. Switch to select the current view (Design view: your current app layout / Code
First, place the following components on your canvas (using drag-and-drop) to replicate
• An axes component
• A button
• A slider
• A table
• Three checkboxes
You should now see the components listed in the component browser on the right.
Now, we are going to set the properties for all those components. By clicking on a
component in the component browser, you can inspect its properties. Do the following:
• Set the Text property of the button component to “Import data”. Notice that
• Set the Title and the X and Y labels of the axes component
krj/04.09.19 57
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
• Set the Label of the slider component to “time [s]”. The name of each component
is always derived from the label, therefore this component is named timesSlider,
including the s from the unit [s]. That name is not intuitive, therefore we need
to timeSlider.
• Set the Label of the three dropdown menus to “pressure”, “flow” and
“temperature”.
• Rename the options of the dropdown menus and delete the fourth option (using
o For the temperature menu use options: rose, dark green, grey
• Set the Label of the edit field to “linewidth” and set the maximum to 8.
• Set all three check boxes to Selected and delete the Text. Now, the check boxes
are hard to identify in the component browser and later in your code. Thus,
right-click on each of them in the component browser and select Rename. Set
• Deselect the Enable options for the slider, the dropdown menus and the edit
field. Now, the user has to import data first before those options become
available.
Now you can switch to the code view. Here, MATLAB automatically creates all code
that is required to create your app the way you defined it in the design view. You will
notice that all code is greyed out. That means, that you are not allowed to change any
of that code to prevent you from crashing your app. To add callbacks (i.e. functions
that are executed when the user interacts with any of the components) right-click on
the respective component, go to callbacks and select a callback. Now, follow these steps:
krj/04.09.19 58
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
your app code. Thus, we need to create a Property. Those are passed to every
functions along with the components as part of the app parameter (Notice the
a new property, select the Properties tab in the code browser and click on the
• To open a file dialog and to import the data, add the following code to the
created property) now contains a matrix with four columns (time, pressure, flow,
• Now, add code to enable all the disabled components and to show the data in
app.pressureDropDown.Enable = 'on';
app.flowDropDown.Enable= 'on';
app.temperatureDropDown.Enable = 'on';
app.linewidthEditField.Enable = 'on';
app.timeSlider.Enable = 'on';
app.UITable.Data = app.data;
• Finally, add code to set the current position of the time slider to the last value
of the time vector and set the maximum slider position to that same value.
The plotdata function is supposed to be a function that plots your imported data
using the current user settings in the app. As we need to update the plot every time
krj/04.09.19 59
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
new data is imported, or if any of the component values are changed, it is wise to write
a separate function that does that instead of having the same code in every component
callback. The plotdata function we are about to create requires only one input – app
– which contains both the information and access to all our components and the
imported data.
To create a new function in the code view, you need to go to Functions in the code
browser and add a new function using the + sign. Rename the new function to
• First, we need to define colors that are not part of the standard plot colors:
• Next, the last plot in the UIAxes component has to be cleared and the figure
cla(app.UIAxes);
hold(app.UIAxes,'on');
• Now, depending on if the respective check box is checked, pressure, flow and
temperature should be plotted using the currently selected color, which can be
krj/04.09.19 60
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
switch app.temperatureDropDown.Value
case "rose" %Temperature colors are not
Color = ROSE; %standard, so we need to check
case "dark green" %and set separately
Color = DARK_GREEN;
otherwise %there is only one option left
Color = GREY;
end
plot(app.UIAxes,app.data(:,1),app.data(:,4) ,...
'Color',Color,'linewidth',app.linewidthEditField.Value);
end
• Finally, set the x-axis limits to the value set by the slider and the y-axis limits
to the minimum and maximum values in the data matrix (using min or max on
Therefore, we need to use another min or max on that vector to get the minimum
set(app.UIAxes,'XLim',[0 app.timeSlider.Value]);
set(app.UIAxes,'YLim',[min(min(app.data(:,2:4)))...
max(max(app.data(:,2:4)))]);
set(app.UIAxes,'box','on');
set(app.UIAxes,'XGrid','on');
set(app.UIAxes,'YGrid','on');
plotdata can now be used in every component callback. Add callbacks to the slider,
the dropdown menus, the edit field and the checkboxes. Add the plotdata(app) call
Your app should be finished now. You can start it by clicking on the green Run button.
Test your app with the provided GUI_Data.csv in FELIX. The result should look like
this:
krj/04.09.19 61
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
krj/04.09.19 62
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
12. SIMULINK
systems. The primary interface is a graphical block diagramming tool with a set of
block libraries. Through its tight connection with MATLAB it can either drive
MATLAB or be scripted from it. It also uses the MATLAB workspace, so results in
You can select objects from the Simulink object browser and drag them to your model
editor canvas. The following figure shows the object browser and the model editor with
You can connect the blocks to define the data flow. To create dynamic systems with
SIMULINK, all differential equations need be of first order, i.e. differential equations
of higher order need to be broken down to first order. Imagine the following initial
value problem:
krj/04.09.19 63
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
of third order into three equations of first order by reversing the causality:
𝑦(𝑡) = ’ 𝑦̇ (𝑡)𝑑𝑡
𝑦̇ (𝑡) = ’ 𝑦̈ (𝑡)𝑑𝑡
The following figure shows the final block set in the model editor. You can rotate blocks
and add text fields to improve understandability of your SIMULINK model. We have
used integrators (Continuous → Integrator) to integrate the signal 𝑦⃛(𝑡) to get 𝑦̈ (𝑡),
divide block (Math Operations ® Divide) and an add block (Math Operations ® Add).
In the add block, you need to modify the list of signs to +---. Initial conditions can be
visualize the simulation results we have added a scope (Sinks → Scope) and a workspace
output (Sinks → To Workspace), which saves the results in the MATLAB workspace
(Here, you would find a vector tout containing the simulation time, and simout
krj/04.09.19 64
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
containing the simulation result, i.e. y). Here, parameters should be set to “array” as
the save format to allow easy data access. To start the simulation, set the simulation
time to e.g. 100s in the toolbar and click on the play button. When opening the scope,
to derive state space description and transfer function of the following system:
Transferring this equation into two equations of first order leads to:
𝑥(𝑡) = ’ 𝑥̇ (𝑡)
krj/04.09.19 65
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
When simulating the step response (Sources ® Step) of the system, we get the
following result:
To be able to use MATLAB to derive the state space description, we have to replace
the step generator and the scope by input and output blocks:
krj/04.09.19 66
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Now we can linearize our system (“Test1.mdl”) in MATLAB and generate the state
space description:
[A,B,C,D] = linmod('Test1')
A =
0 1
-100 -5
B =
0
1
C =
1 0
D =
0
𝑥̇ 0 1 𝑥? 0
” ?• = V W ∙ V𝑥 W + V W ∙ 𝑢(𝑡)
𝑥̇ K −100 −5 K 1
𝑥?
𝑦 = (1 0) ∙ V𝑥 W
K
Using this information, we can again use MATLAB to generate the transfer function:
[num,den]=ss2tf(A,B,C,D)
num =
0 -0.0000 1.0000
den =
1.0000 5.0000 100.0000
krj/04.09.19 67
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
1
𝐺(𝑠) =
𝑠K + 5𝑠 + 100
We can validate this result by replacing our SIMULINK system with a transfer function
krj/04.09.19 68
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
SIMULINK is saving simulation results in the MATLAB workspace or getting the state
sometimes it is also helpful to use m-functions in SIMULINK, e.g. some commands are
In the following example we want to solve the initial value problem below:
use the m-function in SIMULINK directly. First, we need to place the necessary blocks
on the model canvas. In addition to the already known integrator and scope, we need
a clock (Sources ® Clock) to get the current simulation time t and a MATLAB
We can open the MATLAB Function block with a double-click to access and change
its code:
xdot = 3*sin(x)*exp(-x*t)+2*cos(exp(x)*t);
The number of inputs and the input and output names of the function block change
krj/04.09.19 69
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
If you need to create a model with a large number of constants and gains, it gets
SIMULINK offers the possibility to use the MATLAB workspace in this case. Instead
of using a fixed value in the constant blocks or gain blocks we can enter a variable
name from the MATLAB workspace. Now, SIMULINK reads the corresponding value
krj/04.09.19 70
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Also, a full remote start of SIMULINK model in MATLAB is possible. In the following
example, we have reused the dynamic system above and have exchanged all gain values
by variables. Moreover, we have connected the time block to another “To workspace”
Now we can run multiple simulations of our system Oscillator.slx with different
figure;
hold on
a_test = [1 0.8 0.6];
b_test = [1.2 1.4 1.6];
for i = 1:length(a_test)
A = a_test(i);
B = b_test(i);
sim('Oscillator.slx',0:0.01:10);
hold on
plot([0; tout],result,'linewidth',2);
end
krj/04.09.19 71
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
xlabel('time [s]');
ylabel('x');
legend('Test 1','Test 2','Test 3','location','southeast');
set(gca,'XGrid','on','YGrid','on','XMinorGrid','on',...
'YMinorgrid','on');
krj/04.09.19 72
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Controller
This chapter should give an overview on how to implement controllers in dynamic
We want to implement a cruise control in a simple car model. The car model is defined
Thus, the problem can be reduced to the fact, that we have two opposing forces: engine
force (𝑢) and friction force (𝑏 ∙ 𝑣). The differential equation defining our system is:
𝑑𝑣
𝐹 =𝑚∙𝑎 =𝑚∙ =𝑢−𝑏∙𝑣
𝑑𝑡
In SIMULINK the system looks as follows (the step input for the engine force is set to
krj/04.09.19 73
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
•∙ž
If we use a mass of 1000 kg, a friction coefficient of 50 Ÿ
and a step input u of 500 N,
figure;
hold on
m = 1000; %[kg] mass
b = 50; %[N*s/m] firction coefficient
u = 500; %[N] engine force
sim('Car_model.slx',0:0.01:120);
hold on
plot(tout,velocity,'lin ewidth',2);
xlabel('time [s]');
ylabel('velocity [m/s]');
set(gca,'XGrid','on','YGrid','on','XMinorGrid','on',...
'YMinorgrid','on');
As you can see above, the friction is limiting the speed we can achieve, when applying
an engine force of 500 N. Thus, instead of having to test different engine forces to
achieve a certain velocity, we want to implement a simple cruise control that achieves
P-Controller
When applying a P-Controller to a system, the rise time to a stable state (i.e. a final
velocity) will decrease, the steady state error will decrease (i.e. the difference
between the desired velocity and the achieved velocity) but never be eliminated and
krj/04.09.19 74
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
noticeable in systems of 2nd or higher order. Our system is of 1st order. To implement a
controller into our system, we first form a subsystem containing our motor model. This
is done by selecting all elements of our model and then choosing Create Subsystem from
Selection from the context menu. Now we need to replace the step input and the scope
Now we create the controller (Note that the input to the controller is now the desired
As you can see above, we calculate the difference between the actual velocity and the
desired velocity (from the step input). This feedback is multiplied by the P-controller
parameter kp and supplied to the car model as the engine force. The step input is set
to 20, i.e. the desired velocity. The result of our simulation is:
krj/04.09.19 75
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
As you can see, the P-controller was not able to eliminate the steady state error, i.e.
we did not reach the desired 20 m/s. To this extend we need to apply an additional
PI-controller
Applying an additional integral control will lead to elimination of the steady state
error, i.e. we will reach the desired velocity. Unfortunately, this also increases the
eventual overshoot further and leads to an increase of the settling time. Our system
As you can see above, we have now integrated the feedback signal and multiplied it
with the integral control parameter ki. The result of our simulation is now:
krj/04.09.19 76
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
PID-Controller
visible in systems of 2nd and higher order when applying a PI-control. It also decreases
settling time, i.e. the system reaches a stable state faster. Because the car model above
is of 1st order only, we cannot show the overshoot effect when using a PI-control. Thus,
krj/04.09.19 77
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
To extend the PI-control to a PID-control, we need to add another gain and a derivative
krj/04.09.19 78
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
Now the system shows no more overshoot and reaches the stable state faster. We can
also test its reaction to a step disturbance, i.e. a change in some external input:
krj/04.09.19 79
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
In the following test, the disturbance step input was set to a step time of 120s (i.e.
after the system has settled from the first control action) with a step value of -10. The
All of the shown controller elements (P, I, D) can also be inserted by using the PID-
the above system using the PID-controller block. By setting individual parameters to
krj/04.09.19 80
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
krj/04.09.19 81
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer
krj/04.09.19 82