You are on page 1of 82

Lecture notes

COMPUTERMATH

Dr. Jörn Kretschmer


COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

Content

1. Introduction .......................................................................................................... 3

2. MATLAB desktop ................................................................................................ 4

3. Basic matrix operations ........................................................................................ 5

4. Plots .................................................................................................................... 13

5. Data I/O ............................................................................................................. 24

6. M-Scripts and M-Functions ................................................................................ 28

7. Conditions and loops .......................................................................................... 33

8. Interpolation and polynomial fitting ................................................................... 39

9. Parameter identification ..................................................................................... 44

10. Solving differential equations .............................................................................. 51

11. MATLAB Apps .................................................................................................. 55

12. SIMULINK ......................................................................................................... 63

13. Additional literature ........................................................................................... 82

krj/04.09.19 2
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

1. Introduction

MATLAB is the acronym for „MATRIX LABORATORY“, which already explains

its main way of calculation. Nearly all mathematical operations are executed as matrix

operations, which gives MATLAB a unique behavior and programming style.

MATLAB has been first introduced by Cleve Moler in the late 1970s and is distributed

by The Mathworks Inc. in Natick, Massachusetts, USA. It consists of a core part

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,

aerospace equations, bioinformatics and even financial calculations.

Due to this high customizability, it is a popular choice in the scientific world for all

data handling operations, modeling (numerical solving of differential equations),

machine learning and basic programming.

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

script contains detailed description of most important MATLAB features, it is still

most effective when used in combination with the lecture and the practical sessions

held therein.

Mathworks provides additional courseware about their products including a 2-hour

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

course, please contact me for details): https://matlabacademy.mathworks.com/

MATLAB courseware: https://www.mathworks.com/academia/courseware.html

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

1) Current folder – shows the files in the currently selected folder.

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

file content, and manage and tune your files

4) Workspace – View and make changes to the contents of the workspace

5) Command history – View a log of or search for the statements you entered in the

command window, copy them or execute them

6) Command window – Run MATLAB language statements

krj/04.09.19 4
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

3. Basic matrix operations

Variables, Scalars and Matrices


Allocation of values to variables is done similarly to any other programming languages,

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

in double format unless we define it else wise. So by typing:

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

30. If we e.g. want to create Boolean variables, we can type:

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

To create vectors we need to use square brackets:

X = [1 2 3 4 5];

This creates a line vector 𝑋 = [1 2 3 4 5]. To create column vectors we have to

use semicolons in between the numbers to start new lines:

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;

Omitting the increment argument leads to a vector with an increment of 1:

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);

creates a vector 𝑋 = [1 1.45 1.9 … 9.55 10] that has 21 elements.

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

in a vector 𝑋 = [1 5 2 8 9] and to copy it into a variable Y we need to use:

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

to access elements 3, 4 and 5 in the above vector, we use:

X([3 4 5])
ans =
2 8 9

Alternative commands with the same result are:

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

command should be applicable to vectors of different lengths.

You can use indexing to overwrite a specific element in a vector with a new value:

X([3 5]) = [89 34]


X =

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

In a matrix, row is indexed before column, so element X(1,2) of the matrix M on

page 6 would be 2. To access more than one element or even complete rows or columns,

see the following examples:

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

M(2,:) %show complete 2nd row


ans =
4 5 6

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

Multiplication and Division


Matrix multiplication (and vector multiplication analogously) is done as follows:

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:

??? Error using ==> mtimes


Inner matrix dimensions must agree.

Another way of multiplying two matrices is element-wise multiplication. This is done

by using a dot together with the multiplication mark:

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 (i.e. same index) in matrix Y.

Element-wise matrix division is done similarly; however, direction of the division mark

is important. Using X./Y results in a division of X by Y, using X.\Y results in a

division of Y by X!

Normal matrix division shows to be more complex. Mathematically this is not defined,

but if using a command like X/Y with

1 2 2 4
𝑋=3 4,𝑌 = 3 4
4 6 8 10

You would get the following result:

ans =
0.5000 0
0.6667 0.3333

So what happened here?

When using matrix division, MATLAB is executing the following operation:

𝑋/𝑌 = 𝑋 ∙ 𝑌 >? i.e. a matrix multiplication with inversed matrix Y.

Matrix inversion is done as follows:

𝑎𝑑𝑗(𝑌)
𝑌 >? =
det (𝑌)

whereas adj(Y) is the classical adjoint of Y:

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

One exemplary calculation is shown below:

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

with det(𝑌) = −3, 𝑌 >? is finally calculated as:

2 1
− −1 1
⎛ 3 3 ⎞
𝑌 >? =⎜ 2 2
− 3 −2⎟
3 3
⎝ 1 −2 1⎠

Relational operators / Boolean operators


Relational and Boolean operators are also applicable to vectors and matrices in

MATLAB. The following relational operators are applicable:

== 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

Boolean vector or matrix, respectively:

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

indexing a vector based on conditions. As an example, we are now trying to eliminate

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:

C = zeros(1,5) %Create a 1-line vector with 5 columns


C = 0 0 0 0 0

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

a Boolean operator. The following Boolean operators are applicable:

& 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

The short form of the above is:

A(A>1&A~=8)

The conditions used as index do not necessarily need to refer to the same vector that

we apply the index to.

Example:

We have recorded some data and saved the data in two vectors. Vector pressure

contains the measured pressures, vector temperature contains the measured

temperatures at the same time points. Now we would like to create a vector

pressureTempSorted which only contains pressures where the respective

temperature was between 10°C and 20°C. Thus, we apply a conditional index on

pressure but using conditions applied to temperature:

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

of individualization options. The basic functionality of plots will be shown in this

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

general form of using plot is:

plot(xdata,ydata)

Example:

t = (0:0.01:2);
sinfkt = sin(10*pi*t); %Calculate sinus of 10*pi*t.
plot(t,sinfkt);

Here we get the following plot:

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)

figure; %creates a new figure to plot in


bar(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

x-axis and between -0.15 and 0.1 on the y-axis:

axis([ 2, 4, -0.15, 0.1])

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

some measured data and provide axes labels and a title:

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.

The general form is:

plot(xdata,ydata,'COLOR');

MATLAB provides a number of predefined colors that can be applied:

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');

The following line styles and marker styles are available:

Line style Command


solid line -
dashed line --
dotted line :
dash-dotted line -.

Marker style Command


plus +
circle o
asterisk *
dot .
krj/04.09.19 16
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

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

following list gives an overview of the options available:

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:

plot(x,x.^2,'Color',[240/255 90/255 10/255],...


'LineWidth',5,'Marker','hexagram','MarkerEdgeColor','k',...
'MarkerFaceColor','k','MarkerSize',18);

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:

plot(t,[sinfkt; cosfkt; expfkt]);

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

Line specifications are also applicable to multiple plots:

plot(t, sinfkt, 'k-+', t, cosfkt, 'b--', t, expfkt, 'mo');

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

in magenta with “o” as markers and no line.

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.

legend('Sinus','Cosinus','Exponential'); % Place a legend


% on your figure
grid on % Place a grid texture on your figure

The resulting plot (excerpt) is shown below:

Using legend you have to respect the order in which you have plotted the different

graphs. The legend is then adjusted automatically.

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

figure by using the subplot command:

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

Y = y'*v'; %Create a matrix Y with structure:


%-3 -3 -3 ... -3
%-2.9 -2.9 -2.9 ... -2.9
%... ... ... ... ...
%3 3 3 ... 3

Z = (X.^2+Y.^2).*(X.^2+Y.^2); %Now we have created a 2-


%dimensional data set Z
mesh(x,y,Z);

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

used most frequently.

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

new data in “NewData.txt”.

X = load('Data.txt');
NewX = X*4;
save('NewData.txt','NewX','-ascii') %Save new data in ASCII format

In many situations, data might be available in Microsoft Excel format. Therefore

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

be written. Again, worksheet and range can be provided as additional parameters. In

the following example we are reading data from ExcelDataExample.xlsx, worksheet

Measurement1, range B3:B67. Afterwards we are extracting some data and save it to

NewExcelData.xlsx, worksheet NewData.

krj/04.09.19 24
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

Excelmat = xlsread('ExcelDataExample', 'Measurement1', 'B3:B67');


Index = Excelmat>0;
Meas1 = Excelmat(Index); %Get all data that is >0
xlswrite('NewExcelData.xls',Meas1,'NewData');

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

columns of the imported data.

Example:

The file patientinfo.xlsx contains info such as last name (text), height (numeric) and

admission date (date):

Using readtable and saving in a variable ptinfo leads to this:

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 =

1×1 cell array

{'female'}

pinfo.Day_admitted(2:4)
ans =

3×1 datetime array

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

example, a dialog is opened prompting the user to select a measurement file to be

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

same parameters as uigetfile.

krj/04.09.19 27
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

6. M-Scripts and M-Functions

So far, we have only used the MATLAB command window for executing our

commands. When repeating previous statements, we either have to re-type it or select

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):

function [out1, out2, ...] = myfun(in1, in2, ...)

whereas myfun is the name of your function; in and out are the input and output

parameters, respectively. In the following example we are creating an m-function to

calculate the mean and standard deviation of a data-vector of arbitrary length:

function [mean,stdev] = stat(x)


n = length(x); % length, sum and sqrt are m-functions
% provided by MATLAB
mean = sum(x)/n;
stdev = sqrt(sum((x-mean).^2/n));

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

shown above can be executed by the following command:

[mean stdev] = stat([12.7 45.4 98.9 26.6 53])


mean =
47.3200
stdev =
29.4085

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

variable n ceases to exist.

Automated code generation


MATLAB allows to automatically generate code for operations that you have

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

plot and from data import.

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

function createfigure(X1, YMatrix1)


%CREATEFIGURE(X1, YMatrix1)
% X1: vector of x data
% YMATRIX1: matrix of y data

% Auto-generated by MATLAB on 27-Sep-2018 11:16:44

% Create figure
figure1 = figure;

% Create axes
axes1 = axes('Parent',figure1);
hold(axes1,'on');

% Create multiple lines using matrix input to plot


plot1 =
plot(X1,YMatrix1,'MarkerSize',8,'Marker','o','LineWidth',2,...
'Parent',axes1);
...

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

the code that is generated.

krj/04.09.19 31
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

%% Import data from spreadsheet


% Script for importing data from the following spreadsheet:
%
% Workbook: C:\Users\Kretschmer\Documents\bacteria_growth.xlsx
% Worksheet: January
%
% To extend the code for use with different selected data or a
% different spreadsheet, generate a function instead of a script.

% Auto-generated by MATLAB on 2018/09/27 13:45:08

%% Import the data


[~, ~, raw] =
xlsread('C:\Users\Kretschmer\Documents\bacteria_growth.xlsx',...
'January','A2:B502');

%% Create output variable


bacteriagrowth = reshape([raw{:}],size(raw));

%% Create table
bacteriagrowth = table;

%% Allocate imported array to column variable names


bacteriagrowth.Time = data(:,1);
bacteriagrowth.Bacteriapopulation = data(:,2);

%% Clear temporary variables


clearvars data raw;

krj/04.09.19 32
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

7. Conditions and loops

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:

𝑅(1) = 𝑅(0) − 𝑅(0) ∙ 𝑎𝑙𝑝ℎ𝑎_𝑑𝑒𝑐𝑎𝑦

The amount in the subsequent years then is:

𝑅(2) = 𝑅(1) − 𝑅(1) ∙ 𝑎𝑙𝑝ℎ𝑎abcde

𝑅(3) = 𝑅(2) − 𝑅(2) ∙ 𝑎𝑙𝑝ℎ𝑎abcde

𝑅(4) = 𝑅(3) − 𝑅(3) ∙ 𝑎𝑙𝑝ℎ𝑎abcde …

In MATLAB code that would like:

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 =

20.0000 16.6000 13.7780 11.4357

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.

MATLAB provides count-controlled loops (for-loops) and condition-controlled loops

(while-loops). Below, both types of loops are introduced.

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;

for i = 2:4 %set the counter i to run from 2 to 4


%in increments of 1
R(i) = R(i-1)-R(i-1)*alpha_decay;
end

Note, that the definition of the counter above is basically a vector i=[2,3,4].

Consequently, the same annotation as in vectors is possible. The shortest annotation

startvalue:endvalue is automatically using an increment of 1 (see above code). Definition

of other increments can be done by using startvalue:increment:endvalue (e.g. 1:0.1:5 or

10:-0.2:2). Even particular steps can be defined by applying a vector:

c = []; %Create an empty vector c


for i = [2,5,7,10] %Steps will be 2,5,7,10
c(end+1)=i*i; %Calculate i^2 and append to the end of the
%vector
end

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}

and n={1,2,…,5}. The result will be saved in variable H, which is pre-allocated to

decrease computation time.

krj/04.09.19 34
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

k = 5; %Desired matrix size


H = zeros(k,k); %Pre-allocate matrix
for m = 1:k %Run loop from m = 1 to m = k in steps of 1
for n = 1:k %For every iteration of m, run loop from n = 1 to
%n = k in steps of 1
H(m,n) = 1/(m+n -1); %Save the current result in matrix
%H, row m, column n.
end
end

Pre-allocation of variables is important to make your code run efficiently. Computing

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:

k = 3000; %Desired matrix size


m = 1:k; %Create a vector m = 1,2,3,...k
n = 1:k; %Create a vector n = 1,2,3,...k
v = ones(length(m),1); %Create a vector v of containing ones
M = v*m; %Create a matrix M with structure:
%1 2 3 ... 3000
%1 2 3 ... 3000
%... ... ... ... ...
%1 2 3 ... 3000

N = n'*v'; %Create a matrix N with structure:


%1 1 1 ... 1
%2 2 2 ... 2
%... ... ... ... ...
%3000 ... ... 3000

H = 1./(M+N-1); %Matrices M and N overlap in a way that covers


%all combinations of m and n that would exist
%when using the nested loops

Using that code results in a computing time for H of 0.0067s, so less than a tenth of

the version with nested loops and pre-allocation!

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

conditions is the application of an if-statement. If the given condition is met, the

respective code is executed; if the condition is not met, the respective code is skipped.

Usage of an else-statement is not compulsory, but it can be used to offer an alternative

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

at the division by 400 are leap years, too.

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.

Therefore, command window output would look like the following:

2000 is a leap year


2002 is not a leap year
2004 is a leap year

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

minimum field width of 5 and a precision of 3.

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

result = fliplr(result) %flip result vector left to right


4B05C

The use of otherwise is optional. It provides an alternative statement if no case

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

8. Interpolation and polynomial fitting

Consider the following situation: you have recorded some data with a measurement

frequency of 0.8 Hz.

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

(1D interpolation) in MATLAB:

y_8 = interp1(x_data,y_data,8); %find the value at 8s given


%the known data points
hold on
plot(8,y_8,'b+','linewidth',1.5,'Markersize',9);
fprintf('Value at 8s: %1.3f',y_8)
Value at 8s: -13.714

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

interpolation by interpolating the whole data set. Additionally, a better estimation of

the point at 8s is calculated with spline interpolation.

%Create a denser x_data grid. Here, increment is 0.1s (i.e. 10Hz)


x_new = x_data(1):0.1:x_data(end);

%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

plot(8,y_8_spline,'x','Color',[0.57 0.67 0.4],...


'linewidth',2.5,'Markersize',12);
legend('linear interpolation','spline interpolation',...
'measured data','y@8s (linear)','y@8s (spline)');
Value at 8s (spline): -15.040

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,

so in a first attempt we fit a polynomial of 3rd degree to the data:


p3 = polyfit(x_data,y_data,3); %Fit polynomial of 3rd degree
fprintf('%1.3fx^3+%1.3fx^2+%1.3fx+%1.3f\n',p3);
x_test = x_data(1):0.01:x_data(end); %Create denser x_data vector
y_test3 = polyval(p3,x_test);
plot(x_test,y_test3,'Color',[0.5 0.5 1],...
'linestyle','-.','linewidth',1);
0.548x^3+-8.481x^2+33.107x+-18.279

krj/04.09.19 41
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

polyfit(x,y,n) fits a polynomial of nth degree to data defined by x and y. It returns

the polynomial coefficients in a vector p, which has a length of n+1. polyval allows

to calculate the polynomial at specific x-values using the polynomial coefficients p. In

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:

p5 = polyfit(x_data,y_data,5); %Fit polynomial of 5th degree


fprintf('%1.3fx^5+%1.3fx^4+%1.3fx^3+%1.3fx^2+%1.3fx+%1.3f\n',p5);
y_test5 = polyval(p5,x_test);
plot(x_test,y_test5,'Color',[0.5 0.5 0.5],'linestyle',...
'--','linewidth',1);
0.003x^5+-0.085x^4+1.400x^3+-12.010x^2+38.225x+-19.125

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

example we fit a polynomial of 10th degree to the data:

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

polynomial of 10th degree.

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

for linear problems, it gets difficult in nonlinear situations.

As an example we have recorded the arterial oxygen saturation (SaO2) of a patient at

different arterial oxygen partial pressures (PaO2).

Now we would like to know the expected saturation at 200mmHg PaO2. That we can

do using Kelmans1 model of the oxygen dissociation curve:

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)

𝑃𝑎𝑂K(pqr) = 𝑃𝑎𝑂K ∙ 10k.kKs∙(Lw>N)xk.s∙(yz>w.s)xk.kv({|}sk>{|}~d•€• )

𝑎? = −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

to be parameters of that model, we can use methods of parameter identification to find

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

squared errors is used. Thus the optimization problem is given as:

2
min‖𝐹(𝑥, 𝑥𝑑𝑎𝑡𝑎) − 𝑦𝑑𝑎𝑡𝑎‖ = min ˆ(𝐹(𝑥q , 𝑥𝑑𝑎𝑡𝑎q ) − 𝑦𝑑𝑎𝑡𝑎q )K
… 2 …
q

MATLAB provides special tools for parameter identification as well as general

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

able to manage the fitting process more directly.

krj/04.09.19 45
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

First, we need to create a function containing the above model oxygen dissociation:

function SaO2 = GasDissociation(PaO2,Temp,pH,PaCO2)

%Compute virtual PO2


vPO2 = PaO2.*10.^(0.024*(37-Temp)+0.4*(pH-7.4)+...
0.06*(log10(40)-log10(PaCO2)));

% 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

fminsearch can attempt to minimize. That function is called an objective function,

because the objective of fminsearch is to minimize the output of that function. That

function needs to receive the parameters that fminsearch is allowed to optimize

(here: T and pH) and all other information and data that is required to calculate the

model output using the function above.

function SSE = obj_func_GasDissO2(x,PaO2_r,SaO2_r,PaCO2)

% PaO2_r - recorded PaO2 values


% SaO2_r - recorded SaO2 values
% SaO2_m - modelled SaO2 values using the
currently evaluated Temp and pH

Temp = x(1);
pH = x(2);

SaO2_m = zeros(1,length(PaO2_r));

for i = 1:length(PaO2_r) %Calculate SaO2 for every recorded PaO2


SaO2_m(i) = GasDissociation(PaO2_r(i),Temp,pH,PaCO2);
end

%Calculate summed squared error (SSE)


SSE = sum((SaO2_m-SaO2_r).^2);

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');

initial_guess = [37 7.45]; %fminsearch requires an initial guess


for each parameter to start the optimization there
PaCO2 = 45; %[mmHg]

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

@(x) tells fminsearch which of the three inputs of obj_func_GasDissO2 should

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);

legend('measured data','fitted model','location','southeast');

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

avoid misinterpretation by MATLAB.

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

system that needs to be identified is so complex, that the number of function

evaluations is not sufficient to reach an acceptable result, you can modify those options

with optimset. optimset requires name-value pairs, defining the option to be

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

fminsearch the following way (based on the above example):

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);
...

For more options, please refer to the optimset help in MATLAB.

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.

However, in high-dimensional problems (a high number of parameters to be identified)

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

an arbitrary one-dimensional problem to explain the problem at hand.


Difference between ydata and F(x,xdata)

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

is not very realistic:

Temperature: -3.8
pH: 5.09

As the correct parameter values are unknown to us upon starting the parameter

identification, we need to gather as much information as possible from the measured

data to find appropriate initial conditions or at least set plausible initial guesses.

krj/04.09.19 50
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

10. Solving differential equations

Many differential equations cannot be solved analytically. In practical use however,

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

control. It can be applied as a first try.

Solving ODEs of higher order


When using MATLAB to solve ODEs, the ODEs have to be of first order, i.e.

differential equations of higher order need to be converted to systems of first order.

Imagine the following initial value problem:

5𝑦⃛ + 𝑦̈ + 1.7𝑦̇ + 0.2𝑦 = 20 with 𝑦(0) = 1, 𝑦̇ (0) = 0, 𝑦̈ (0) = 2

To calculate the solution numerically, we need to transform our differential equation

of third order into three equations of first order:

𝑦 = 𝑦?

𝑑𝑦?
𝑦̇ = = 𝑦K
𝑑𝑡

𝑑𝑦K
𝑦̈ = = 𝑦L
𝑑𝑡

𝑑𝑦L 20 − 0.2𝑦 − 1.7𝑦̇ − 𝑦̈ 20 − 0.2𝑦? − 1.7𝑦K − 𝑦L


𝑦⃛ = = =
𝑑𝑡 5 5

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

solutions 𝑦⃗ = {𝑦? , 𝑦K , 𝑦L } and return a column vector of differentials ••••⃗


𝑑𝑦 = {𝑦̇ ? , 𝑦̇ K , 𝑦̇ L }:

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 = zeros(length(y),1); %pre-allocate dy as a column vector

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:

[t,y] = ode45(@(t,y) my_ode(t,y),0:0.01:100,[1 0 2]);

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.).

Plotting this matrix results in the following graph:

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

form of our differential equation above:

𝑎𝑦⃛ + 𝑏𝑦̈ + 𝑐𝑦̇ + 𝑑𝑦 = 𝑒

the m-function containing the ODEs can be modified as follows:

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;

To start the simulation, the MATLAB statement is then:

params = [5 1 1.7 0.2 20];


[t,y] = ode45(@(t,y) my_ode(t,y,params),0:0.01:100,[1 0 2]);

krj/04.09.19 53
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

Solving ODE systems


ODE systems might contain variables and derivatives of different names:

𝑑𝑥
= 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

11. MATLAB Apps

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

MATLAB. It shows step-by-step instructions to create an app that allows a user to

import data and display it on the screen. The figure below shows a rough sketch of

what we intend to create:

krj/04.09.19 55
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

We want the following functionalities in our app:

• A small plot that shows the imported data with the current plot settings

• A button to import new data

• Three dropdown menus to select the color the plots should appear in

• A slider to set the time range to be shown on the plot

• A numeric input to set the line width of the plot

• A table showing the currently imported data

• Three checkboxes to select the data to be shown on the plot

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

fourth column the temperature.

Upon starting the App Designer (using the command appdesigner in the command

window) you will see a new window with an empty canvas:

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

choose from (buttons, check boxes, sliders, etc.)

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.

4. Component properties: Each of the app components has a number of properties.

Those properties can be set as default settings in the component properties

browser or can be changed at runtime by defining it in the app code.

5. Switch to select the current view (Design view: your current app layout / Code

view: the code defining your app behavior).

First, place the following components on your canvas (using drag-and-drop) to replicate

the sketch above:

• An axes component

• A button

• A slider

• Three dropdown menus

• An edit field (numeric)

• 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

the component name automatically changes to ImportdataButton

• 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 rename it (right-click on the respective component in the component browser)

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

the minus button):

o For the pressure menu use options: red, black, green

o For the flow menu use options: blue, magenta, yellow

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

the names to “pressureCheckBox”, “flowCheckBox” and “temperatureCheckBox”.

• 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:

• Create a new ButtonPushedFcn callback for the “Import data” button.

krj/04.09.19 58
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

• The data that is imported needs to be available across different functions in

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

naming of all the components: app.UIAxes, app.ImportdataButton,...). To add

a new property, select the Properties tab in the code browser and click on the

+ sign. Rename the new property to app.data.

• To open a file dialog and to import the data, add the following code to the

ImportdataButtonPushed function you have created before:

[filename,pathname] = uigetfile('.csv','Select data file');


filepath = fullfile(pathname,filename);
app.data = csvread(filepath);

csvread imports .csv-files as matrices. Thus, app.data (our previously

created property) now contains a matrix with four columns (time, pressure, flow,

temperature) and n rows.

• Now, add code to enable all the disabled components and to show the data in

your table component:

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.

Afterwards, the data should be plotted.

app.timeSlider.Value = app.data(end,1); %Last value in time vector


app.timeSlider.Limits = [0 app.data(end,1)];
plotdata(app);

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

“plotdata” and then follow these steps:

• First, we need to define colors that are not part of the standard plot colors:

ROSE = [206/255 136/255 164/255];


DARK_GREEN = [58/255 111/255 72/255];
GREY = [0.5 0.5 0.5];

• Next, the last plot in the UIAxes component has to be cleared and the figure

put on hold for the plots:

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

accessed from app.pressureDropDown.Value (...flowDropDown...

and ...temperatureDropDown... respectively) and the currently selected

linewidth, which can be accessed from app.linewidthEditField.Value):

if (app.pressureCheckBox.Value) %Check if pressure is selected


plot(app.UIAxes,app.data(:,1),app.data(:,2), ...
'Color',app.pressureDropDown.Value,...
'linewidth',app.linewidthEditField.Value);
end

if (app.flowCheckBox.Value) %Check if flow is selected


plot(app.UIAxes,app.data(:,1),app.data(:,3), ...
'Color',app.flowDropDown.Value,...
'linewidth',app.linewidthEditField.Value);
end

if (app.temperatureCheckBox.Value) %Check if temp. is selected

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

a matrix leads to a vector containing the minimum or maximum of each column.

Therefore, we need to use another min or max on that vector to get the minimum

or maximum of the whole matrix):

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

in all of those callbacks.

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

Simulating dynamic systems


SIMULINK is a MATLAB tool for modeling, simulating and analyzing dynamic

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

SIMULINK can be process further in MATLAB.

SIMULINK can be started by typing simulink in the MATLAB command window.

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

different blocks placed on the canvas.

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

5𝑦⃛ + 𝑦̈ + 1.7𝑦̇ + 0.2𝑦 = 20 with 𝑦(0) = 1, 𝑦̇ (0) = 0, 𝑦̈ (0) = 2

To calculate the solution numerically, we need to transform our differential equation

of third order into three equations of first order by reversing the causality:

𝑦(𝑡) = ’ 𝑦̇ (𝑡)𝑑𝑡

𝑦̇ (𝑡) = ’ 𝑦̈ (𝑡)𝑑𝑡

20 − 𝑦̈ (𝑡) − 1.7𝑦̇ (𝑡) − 0.2𝑦(𝑡)


𝑦̈ (𝑡) = ’ 𝑦⃛(𝑡)𝑑𝑡 = ’
5

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 𝑦̈ (𝑡),

signal 𝑦̈ (𝑡) to get 𝑦̇ (𝑡) and signal 𝑦̇ (𝑡) to get 𝑦(𝑡).

We also need constants (Sources ® Constant), gains (Math Operations ® Gain), a

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

set by accessing the integrator parameters (double-click on the respective block). To

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,

you should see the following result:

State space description and transfer functions


SIMULINK can be used to analyze dynamic systems. In the following example we want

to derive state space description and transfer function of the following system:

𝑥̈ (𝑡) = −100𝑥(𝑡) − 5𝑥̇ (𝑡) + 𝑢(𝑡)

Transferring this equation into two equations of first order leads to:

𝑥̇ (𝑡) = ’ 𝑥̈ (𝑡) = ’ −100𝑥(𝑡) − 5𝑥̇ (𝑡) + 𝑢(𝑡)

𝑥(𝑡) = ’ 𝑥̇ (𝑡)

In SIMULINK this systems looks as follows:

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

So the state space description of our system is:

𝑥̇ 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

So, the transfer function of our system is:

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

block (Continuous → Transfer Fcn):

The result is the same as of our system above:

krj/04.09.19 68
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

Using m-functions in SIMULINK / Starting SIMULINK models in MATLAB


So far, the only way we have used the interconnection between MATLAB and

SIMULINK is saving simulation results in the MATLAB workspace or getting the state

space description of a SIMULINK model with the help of MATLAB. However,

sometimes it is also helpful to use m-functions in SIMULINK, e.g. some commands are

easier to realize in MATLAB than with the graphical interface in SIMULINK.

Therefore, we are able to implement m-functions directly to the SIMULINK interface.

In the following example we want to solve the initial value problem below:

𝑥̇ = 3 ∙ sin(𝑥) ∙ 𝑒 >…™ + 2 ∙ cos(𝑒 … ∙ 𝑡) with 𝑥(0) = 10

Creating these equations in SIMULINK can be an annoying task; it is much faster to

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

Function (User-Defined Functions ® MATLAB Function):

We can open the MATLAB Function block with a double-click to access and change

its code:

function xdot = fcn_xdot(t,x)

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

accordingly. Now, the missing connections can be made:

krj/04.09.19 69
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

The result of the simulation is:

If you need to create a model with a large number of constants and gains, it gets

difficult to manage all of them if different parameter settings need to be tested.

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

from the workspace before simulation start.

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”

function to transfer the values to the MATLAB workspace.

Now we can run multiple simulations of our system Oscillator.slx with different

parameter settings in MATLAB:

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

system using SIMULINK. Imagine the following example:

We want to implement a cruise control in a simple car model. The car model is defined

as (inertia of the wheel is neglected):

m – car mass v – velocity b – friction coefficient

u – engine force a – acceleration

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

use the value in variable u as the Final value):

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,

the output of our system is as follows:

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

a desired velocity, e.g. 20 m/s. To this extend we apply a simple P-Controller.

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

an eventual overshoot will increase. The overshoot problem however is mostly

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

by input and output blocks (Ports & Subsystems → In/Out):

Now we create the controller (Note that the input to the controller is now the desired

velocity, the output of the controller is the engine force):

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

integral control, i.e. the applied controller becomes a PI-controller.

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

comprising a PI-control now looks as follows:

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

Applying an additional derivative control helps to decrease the overshoot that is

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,

we use a dynamic system of 3rd order:

When applying a PI-control with a reference value of 20 and PI parameters of kp =

300 and ki = 20.7 we get the following step response:

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

block (Continuous ® Derivative):

We choose kd = 550 and simulate again:

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

following graphs show the reaction of PI- and PID-control:

All of the shown controller elements (P, I, D) can also be inserted by using the PID-

controller block (SIMULINK Extras → PID-Controller). The following figure shows

the above system using the PID-controller block. By setting individual parameters to

0 you can also use different combinations of P I and D.

krj/04.09.19 80
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

krj/04.09.19 81
COMPUTERMATH
DDr.
Dr. Jörn Kretschmer

13. Additional literature

[1] Ottmar Beucher: “MATLAB und Simulink: Grundlegende Einführung für


Studenten und Ingenieure in der Praxis“, Vol. 4, Pearson Studium, 2008

[2] Cleve Moler: „Experiments with MATLAB“


https://de.mathworks.com/moler/exm.html

[3] MATLAB Appdesigner tutorial:


https://de.mathworks.com/help/matlab/app-designer.html?s_tid=srchtitle

[4] MATLAB student resources:


https://de.mathworks.com/academia/students.html?s_tid=acmain_sp_gw_bo
d

krj/04.09.19 82

You might also like