Matlab Simulink
Matlab Simulink
Matlab Simulink
WS 2002/2003
email: pkrauss@mathworks.de
Contents
0 Introduction 6
0.1 The MATLAB Product Family . . . . . . . . . . . . . . . . . . 7
1 MATLAB interactively 9
1.1 Calculation with MATLAB . . . . . . . . . . . . . . . . . . . . 10
1.1.1 Integrated Development Environment (IDE) . . . . . . . 10
1.1.2 The MATLAB Command Window . . . . . . . . . . . . 11
1.1.3 The Data Types . . . . . . . . . . . . . . . . . . . . . . 12
1.1.4 The MATLAB Workspace . . . . . . . . . . . . . . . . 14
1.1.5 MATLAB Notation . . . . . . . . . . . . . . . . . . . . 16
1.1.6 Arithmetic Operators . . . . . . . . . . . . . . . . . . . 17
1.1.7 Relational and logical operators . . . . . . . . . . . . . 18
1.1.8 Elementary mathematical functions . . . . . . . . . . . 19
1.1.9 The output display format . . . . . . . . . . . . . . . . 19
1.1.10 Help and Online Documentation . . . . . . . . . . . . . 20
1.2 Manipulation of Vectors and Matrices . . . . . . . . . . . . . . 21
1.2.1 The Assignment of Vectores and Matrices . . . . . . . . 21
1.2.2 Special matrices . . . . . . . . . . . . . . . . . . . . . 22
1.2.3 Submatrices, Matrix-Indexing . . . . . . . . . . . . . . 23
1.2.4 Multidimensional matrices . . . . . . . . . . . . . . . . 24
1.3 Polynomials und matrices . . . . . . . . . . . . . . . . . . . . . 25
1.3.1 Description of differential equation systems . . . . . . . 25
1.3.2 Polynomial functions . . . . . . . . . . . . . . . . . . . 26
1.4 Exercises for Chapter 1 . . . . . . . . . . . . . . . . . . . . . . 27
1
CONTENTS CONTENTS
3 MATLAB Graphics 45
3.1 2-Dimensional Graphics . . . . . . . . . . . . . . . . . . . . . 46
3.1.1 Plot of Vectors and Matrices . . . . . . . . . . . . . . . 46
3.1.2 Labelling of Diagrams . . . . . . . . . . . . . . . . . . 48
3.1.3 Colors, Markers, Line Types, Axes Range, Grids . . . . 49
3.1.4 Windows with several Graphics . . . . . . . . . . . . . 50
3.2 3-dimensional Graphics . . . . . . . . . . . . . . . . . . . . . . 51
3.2.1 Line graphic . . . . . . . . . . . . . . . . . . . . . . . 51
3.2.2 Point of View . . . . . . . . . . . . . . . . . . . . . . . 52
3.2.3 Point of View of -dimensional Graphics . . . . . . . . 54
3.2.4 Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
3.3 Handle Graphics . . . . . . . . . . . . . . . . . . . . . . . . . 56
3.3.1 Object-Hierarchy . . . . . . . . . . . . . . . . . . . . . 56
3.3.2 Handle the Objects . . . . . . . . . . . . . . . . . . . . 57
3.3.3 Properties of Objects . . . . . . . . . . . . . . . . . . . 58
3.3.4 Example Paraboloid . . . . . . . . . . . . . . . . . . . 61
3.3.5 Properties Changing with the Graphical Interface . . . . 65
3.4 Exercises for Chapter 3 . . . . . . . . . . . . . . . . . . . . . . 67
2
CONTENTS CONTENTS
5 Modelling in SIMULINK 77
5.1 Model of an analog voltmeter . . . . . . . . . . . . . . . . . . . 78
5.1.1 Mechanical and electrical model . . . . . . . . . . . . . 78
5.1.2 Governing equations . . . . . . . . . . . . . . . . . . . 78
5.1.3 Block diagrams . . . . . . . . . . . . . . . . . . . . . . 79
5.2 Grafical editing . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.2.1 To start SIMULINK . . . . . . . . . . . . . . . . . . . 80
5.2.2 Editing block diagrams . . . . . . . . . . . . . . . . . . 82
5.2.3 Properties of blocks and signals . . . . . . . . . . . . . 86
5.2.4 Some cosmetic changes . . . . . . . . . . . . . . . . . 88
5.2.5 Starting a Simulation . . . . . . . . . . . . . . . . . . . 90
5.3 MATLAB interfaces . . . . . . . . . . . . . . . . . . . . . . . 91
5.3.1 Save block diagram . . . . . . . . . . . . . . . . . . . . 91
5.3.2 Using the MATLAB workspace . . . . . . . . . . . . . 93
5.4 Excercises for chapter 5 . . . . . . . . . . . . . . . . . . . . . . 98
3
CONTENTS CONTENTS
8 STATEFLOW 141
8.1 Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
8.1.1 STATEFLOW Objects . . . . . . . . . . . . . . . . . . 144
8.1.2 The STATEFLOW Editor . . . . . . . . . . . . . . . . 151
8.1.3 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 157
8.2 Some items of STATEFLOW . . . . . . . . . . . . . . . . . . . 158
8.2.1 Hierarchy by means of Subcharts . . . . . . . . . . . . 158
8.2.2 Graphical Functions . . . . . . . . . . . . . . . . . . . 159
8.2.3 Temporal Logic . . . . . . . . . . . . . . . . . . . . . . 160
8.3 STATEFLOW Tools . . . . . . . . . . . . . . . . . . . . . . . . 161
8.3.1 The Explorer . . . . . . . . . . . . . . . . . . . . . . . 161
8.3.2 The Editor – Additional Properties . . . . . . . . . . . . 162
8.3.3 The Debugger . . . . . . . . . . . . . . . . . . . . . . . 163
8.3.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . 164
4
CONTENTS CONTENTS
5
Chapter 0
Introduction
Inhaltsverzeichnis
6
CHAPTER 0. INTRODUCTION 0.1. THE MATLAB PRODUCT FAMILY
SIMULINK
BLOCK-
SETS
MATLAB
STATEFLOW
TOOL-
BOXES
C-CODE
HARDWARE
DATA
STAND-ALONE
APPLICATION
What is MATLAB?
7
CHAPTER 0. INTRODUCTION 0.1. THE MATLAB PRODUCT FAMILY
There are various software tools featured by MATLAB. They belong to the MAT-
LAB Product Family.
SIMULINK is a graphical development tool for
modelling,
simulation and
analysis
of linear and nonlinear dynamic systems. SIMULINK-models are developed and
parametrized as block diagramms.
8
Chapter 1
Inhaltsverzeichnis
9
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
The Launch Pad shows Tools, Helpdesks and Demos of all installed
products.
All Variables stored in memory are shown in Workspace.
In Command History the last MATLAB commands can be revisited.
File and directory browsing as well as searching capabilities can be done
by using Current Directory.
New commands are processed in the Command Window.
10
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
>> 1 + 2
ans = 3
Data types of variables are selected by the assignment of a value (no ex-
plicit declaration).
11
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
>> A = [1 2 3 4
5 6 7 8]
A =
1 2 3 4
5 6 7 8
Strings
12
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
Cells
>> SomeCell(1)= A ;
or
Structures
>> struct.numbers=A;
>> struct.characters=SomeString;
– Like cell arrays, structures also collect related data and information
together.
– The elements of the structure have field names (after the dot).
– Elements of structures are accessed by the name and the field name.
– Commands: fields, getfield, rmfield, setfield, struct,
struct2cell.
13
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
>>who
A struct
SomeString SomeCell
or
>> whos
Name Size Bytes Class
A
14
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
In addition to the interactive mode for managing the MATLAB workspace there
is the Workspace Browser.
Double arrays and character arrays may be viewed and manipulated using
a special Array Editor.
Furthermore, variables can be deleted and variables or the complete workspace
can be saved.
15
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
= Assignment A=B;
i=i+1;
. Decimal point 1.2
Elementwise mathematical operation A.*B;
Structures struct.number=A
Parent directory cd ..
Continuation a = bˆ 2 ...
+ 2*b*c + cˆ 2
, Separation of matrix subscripts [1,2,3,4]
Separation of function arguments zeros(2,5);
Multi statement lines if i==1,i, end
; End of row in matrices [1;2;3;4]
Supresses the display of results [1;2;3;4];
% Comment; rest of the line is not executed %Comment line
! Command to the operating system !dir
: Generation of vectors A=1:.1:5;
Submatrices A(:,2)
Loop variables for i=1:10,..
’ Encloses strings string=’Hello’
Transpose of vectors and matrices B=A’
16
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
>> B=A;
>> C=A*B
C =
7 10
15 22
>> D=A.*B
D =
1 4
9 16
17
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
Examples:
ans =
0 0 1
>> A|B
ans =
0 1 1
Logic functions:
all, any, exist, find, finite, isempty, isieee, isinf, isnan,
issparse, isstr, iscell, isequal, isfinite, islogical, isnu-
meric, isprime, isspace, isstruct, logical, cellfun
18
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
Special functions:
acos, acosh, asin, asinh, atan2, atanh, cosh, sinh, bessel, besselh,
beta, betainc, betaln, ellipj, ellipke, erf, erfc, erfcx, erfinv,
gamma, gammainc, gammaln, log2, pow2, rat, rats
3.14159265358979
The format command changes only the display format not the computional
accuracy.
Other options: format long e, format short e, format compact
19
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB
20
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES
or using the colon operator and other funtions for matrix manipulation
Manipulation of matrices:
rot90, fliplr, flipud, diag, tril, triu, reshape
Analyse matrices:
cond, det, norm, null, orth, rcond, rank, rref, trace
Linear algebra:
chol, inv, lscov, lu, nnls, pinv, qr , /, \
Eigenvalues and singular values:
balance, cdf2rdf, eig, hess, poly, qz, rsf2csf, schur, svd
21
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES
0 0 0
Matrix of ones
1 1 1
Identity matrix
>> A=eye(3,3)
A =
1 0 0
0 1 0
0 0 1
Empty matrix
>> A=[]
A =
[]
22
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES
Columns: A(:,4)
Rows: A(3,:)
Blocks: A(1:2,2:4)
23
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES
>> C(:,:,1)
>> A = [1 2;3 4];
ans =
>> B = [5 6;7 8];
1 2
>> C = cat(3,A,B);
3 4
>> D = zeros(5,4,3,2);
>> whos C D
Name Size Bytes Class
24
CHAPTER 1. MATLAB INTERACTIVELY 1.3. POLYNOMIALS UND MATRICES
State space description (matrix-oriented)
e.g. for a second order System
B =
0
2
D =
0
>> b = K*w0ˆ2
b =
2
1 1 1
25
CHAPTER 1. MATLAB INTERACTIVELY 1.3. POLYNOMIALS UND MATRICES
26
CHAPTER 1. MATLAB INTERACTIVELY 1.4. EXERCISES FOR CHAPTER 1
1. Generate the matrices and vectors A, b, M and D.
2. Linear algebra
Determine the rank of the matrix A.
Determine the eigenvalues and eigenvectors of the matrix A.
4. Polynomial functions
Determine the roots of the polynomial
.
.
Determine the extreme values of
27
CHAPTER 1. MATLAB INTERACTIVELY 1.4. EXERCISES FOR CHAPTER 1
5. Logical operators
.
Verify the equality of following expression :
.
Determine the maximal deviation of
und
7. Matrix manipulation
Cut out the 3rd row of A and write this vector into a new variable.
Now replace the 2nd column of D with the 3rd row of A.
28
Chapter 2
Inhaltsverzeichnis
29
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE
2.1. FLOW CONTROL STRUCTURES IN MATLAB
Example (ematrix.m):
ok=0;
while ˜ ok
n=input(’Dimension of identity matrix = ’);
if n>=0 & rem(n,1)==0
ok=1;
end
end
E=zeros(n,n)
for i=1:n
for j=1:n
if i==j, E(i,j)=1; end
end
end
0 0 1
30
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
K =
2;
D =
.5;
w0 =
1;
w =
sqrt(1-Dˆ2);
t =
[0:.1:10]’;
h =
K*(1-exp(-D*w0*t).*(cos(w*t) + ...
D/sqrt(1-Dˆ 2)*sin(w*t)));
plot(t,h)
M–scripts can be called from the MATLAB Command Window (filename with-
out extension!).
>> pt2s
2.5
1.5
0.5
0
0 1 2 3 4 5 6 7 8 9 10
31
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
2.2.2 Functions
Example of a function (nueberk.m)
function bk=nueberk(n,k)
% bk = nueberk(n,k)
% computes the binomial coefficient:
% n!/k!/(n-k)!
% mit n! = prod(1:n)
if k>=0 & k<=n
bk=prod(1:n)/prod(1:k)/prod(1:n-k);
elseif k>=0 & n<=k
bk=0;
end
At the top of the file must be a line that contains the syntax definition
function for the new function, the output variables (here only bk) in
[ ], the name of the function nueberk and the input variable n und k in
().
The variables in the function, here n, k and bk, are local variables and not
visible outside the function.
To see the result of a function you have to assign it to a variable, e.g.,
>> lotto=nueberk(49,6)
lotto =
13983816
32
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
We describe the following differential equation (pt1 dgl ss.m)
resp.
function dy = pt1_dgl_ss(t,y,flag,K,T,u)
% PT1_DGL_SS differential equation for
% first order systems.
% Formulation in state space description.
dy = -y/T + K/T*u;
Then
ode45(’pt1_dgl_ss’,tend,y0,[],K,T,u);
0.8
0.6
0.4
0.2
0
0 1 2 3 4 5 6 7 8 9 10
Other function–functions:
fminsearch,fzero,fminbnd,ode*,quad,dblquad
33
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
>> global K D w0 2
>> plot(t,x(:,1))
0
0 1 2 3 4 5 6 7 8 9 10
34
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
MATLAB uses it’s own search path for the access to M–files. The path can be
displayed by the command path.
>> path
MATLABPATH
C:\MATLABR11\toolbox\matlab\general
C:\MATLABR11\toolbox\matlab\ops
.
.
.
>> bsp
1
c:\kurs
35
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
36
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
You can use m-functions as well as operating system commands to handle the
directories (change, show, make). You have to put the symbol ! before the oper-
ating system commands to execute them
>> cd
ans =
c:\kurs\matlab
37
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS
%Vectorization
tic
x=pi/50:pi/50:5*pi;
y=sin(x)./x;
tv=toc;
%As a loop
tic
for l=1:length(x)
xl(l)=l*pi/50;
yl(l)=sin(xl(l))/xl(l);
end
ts=toc;
computing_time=struct(’vectorization’,tv,...
’as a loop’,ts)
38
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS
For programming in MATLAB you can use any ASCII-text editor. In the MAT-
LAB environment the MATLAB-Editor/Debugger is available as default.
>> edit
% extension .dat
39
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS
40
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS
2.3.2 Debugging
To find errors in MATLAB programs you can use several methods:
Not typing the ”;” on the end of a command displays intermediate results
in the workspace.
With the command keyboard you can interrupt the program sequence to
check the variables in the local workspace. The command return contin-
ues the program.
Using a sequence of MATLAB statements (scripts), instead of subfunctions,
enables you to display all variables.
The MATLAB Debugger
41
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS
mit n! = prod(1:n)
.
42
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.4. EXERCISES FOR CHAPTER 2
in the intervall
and compute .
.
mial
Save the structure into a mat-File. Use the structure to plot
Note: The command date creates today’s date.
2. String operations
Write an M–script that executes the following:
Output of the current directory and assignment to a character variable
Generation of a character variable dir destination with the con-
tent ”c:\temp”
change the directory to dir destination using the eval function.
Output of the dir destination directory and assignment to a cell
variable
43
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.4. EXERCISES FOR CHAPTER 2
3. The coefficients of the binomial formular
(Pascals’s Triangle)
can be calculated by nueberk. Write a program which computes the co-
efficients for
.
4. function – functions
Solve the differential equation
In order to do this you need the state space description.
Initial condition:
Parameters:
Input signal:
Time of simulation:
44
Chapter 3
MATLAB Graphics
Inhaltsverzeichnis
45
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS
>> U=1;
>> x=0:pi/20:2*pi;
>> u=U*sin(x);
>> plot(u)
0.5
−0.5
−1
0 5 10 15 20 25 30 35 40 45 50
If the plot–command is called with only one input parameter, the vector
is plotted versus its indices.
>> plot(x,u)
0.5
−0.5
−1
0 1 2 3 4 5 6 7
Using two vectors as input parameters the second vector is plotted versus
the first vector.
46
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS
>> u1=U*sin(x+pi/4);
>> plot(x,u,x,u1) % or
>> plot(x,[u’,u1’]) % or
>> plot(x,u)
>> hold on
>> plot(x,u1)
0.5
−0.5
−1
0 1 2 3 4 5 6 7
For the graphical presentation of several curves there are several possibli-
ties:
– Input by pairs of the presented curve vectors in the parameter block of
the plot-command.
– plot works with matrices as well
– with the help of the hold-command
47
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS
harmonische Signale
1
0.5
u = sin(x(t))
0 u1(t) u(t)
−0.5
−1
0 1 2 3 4 5 6 7
x(t)
You can use greek and mathmatical symbols for labelling diagrams.
48
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS
>> plot(x,u,’r+-’,x,u1,’b*--’)
>> range = [0 2*pi -1 1];
>> axis(range)
>> grid
>> legend(’u(t)’,’u1(t)’)
harmonische Signale
1
u(t)
u1(t)
0.5
u = sin(x(t))
−0.5
−1
0 1 2 3 4 5 6
x(t)
49
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS
>> axis(range)
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
0 2 4 6 0 2 4 6
1 1
0.5 0.5
0 0
−0.5 −0.5
−1 −1
0 2 4 6 0 2 4 6
50
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS
2
>> xlabel(’x’)
0
>> ylabel(’y’) 1
0.5 1
>> zlabel(’z’)
0
0.5
0
−0.5
−0.5
−1 −1
y
x
plot3 works like the plot command regarding the input parameters, only
with an additional dimension, i.e.,
>> plot3(x1,y1,z1,s1,x2,y2,z2,s2,...)
mand: zlabel
The axis scaling can be defined with
axis([xmin,xmax,ymin,ymax,zmin,zmax]).
51
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS
Elevation
-y y
Azimuth
x
azimuth is the angle in the -plane.
elevation is the vertical elevation of the -plane.
52
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS
Example:
subplot(2,2,1), plot3(x,y,z)
title(’azimuth = -37.5; elevation = 30’)
xlabel(’x’), ylabel(’y’), zlabel(’z’)
subplot(2,2,2), plot3(x,y,z)
view(0,0)
title(’azimuth = 0; elevation = 0’)
xlabel(’x’), ylabel(’y’), zlabel(’z’)
subplot(2,2,3), plot3(x,y,z)
view(90,0)
title(’azimuth = 90; elevation = 0’)
xlabel(’x’), ylabel(’y’), zlabel(’z’)
subplot(2,2,4), plot3(x,y,z)
view(0,90)
title(’azimuth = 0; elevation = 90’)
xlabel(’x’), ylabel(’y’), zlabel(’z’)
2
1.5
1
z
1
z
0 0.5
1
1
0
0
0
y −1 −1 x −1 −0.5 0 0.5 1
x
1.5 0.5
1 0
z
0.5 −0.5
0 −1
−1 −0.5 0 0.5 1 −1 −0.5 0 0.5 1
y x
The command rotate3d enables the user to interactively rotate the view
of a -D graphic
53
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS
-D mesh surface
>> mesh(X,Y,Z)
1.5
0.5
0
1
0.5 1
0.5
0
0
−0.5
−0.5
−1 −1
-D contour plot
>> contour3(X,Y,Z)
1.8
1.6
1.4
1.2
0.8
0.6
0.4
0.2
1
0.5 1
0.5
0
0
−0.5
−0.5
−1 −1
54
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS
3.2.4 Colors
A color map matrix may have any number of rows, but it must have ex-
actly 3 columns. Each row is interpreted as a color, with the first element
specifying the intensity of red, the second green, and the third blue.
55
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
root
figure
The root-object is the computer monitor. All following objects are subor-
dinate to the root-object.
The next level contains the figure-objects. figure-objects are windows
which can be placed on any desired position on the screen.
In the windows you can create axes-, uicontextmenu-, uicontrol-
and uimenu- objects. The axes-objects are coordiniate systems which
can be located and sized in the window. If there is no window open the
creation of axes-object will create automatically a window. The uicon-
textmenu–object is a menu that is attached to a certain object and is acti-
vated by a right-button click.
The objects uicontrol and uimenu are described in chapter ??.
Within the coordinate systems (axes) you can use line-,
patch-, surface-, image-, text-, light-, rectangle-objects which
are on the lowest level. Generating one of these objects with no axes and
figure objects available these higher objects are createt automatically.
56
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
>> fh=figure
fh =
1
>> ah=axes
ah =
1.00378
1.00378,
57
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
58
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
...
59
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
>> set(fh,’NumberTitle’,’off’,...
’Name’,’Beispielfenster’,...
’Color’,[0 0 1])
switch off the default title of the window “Figure No. 1”, gives the window
the new name “Beispielfenster” and changes the background color.
– The first parameter of the set-function identifies the working object.
– All the other parameters are set with (multiple) property/value string
pairs.
– Properties can be switches (’on’/’off’), strings (’Beispielfenster’)
or numerical values ([0 0 1]).
You can find a description of all object properties in the Help Desk under
Handle Graphics Objects.
60
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
>> [X,Y,Z]=parabol(1,1);
>> mesh(X,Y,Z)
61
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
If you want to display the paraboloid (coordinate system) smaller and in the
middle of the window you have to use the commands:
>> mesh(X,Y,Z)
62
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
The Axis scaling is automatically adjusted on the new format. You can
change the axis scaling by:
>> set(gca,’XTick’,[-1:.5:1],...
’YTick’,[-1:.5:1],...
’Ztick’,[0:.5:2])
63
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
It is possible to save graphics for later use. The menu File Save As
generates a binary file <name>.fig, e.g., par fig.fig.
>> open(’par_fig.fig’)
The command print can also be used for saving and exporting graphics.
64
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
>> propedit
65
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS
This editor consists of the right buttons of the button bar and the menu Tools.
With the help of the first 4 buttons of the button bar you can
select objects,
write text objects (title, xlabel, ylabel, . . . )
draw arrows and
put lines.
The last buttons of the button bar replace the commands axis and ro-
tate3d, respectively.
66
CHAPTER 3. MATLAB GRAPHICS 3.4. EXERCISES FOR CHAPTER 3
>> mesh(X,Y,Z)
67
CHAPTER 3. MATLAB GRAPHICS 3.4. EXERCISES FOR CHAPTER 3
68
Chapter 4
Inhaltsverzeichnis
69
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
cess_mode)
>> fclose(’all’)
70
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
>> S = load(’mydata’)
>> x=[1:10]’;
The command load loads data in ascii–format if the file only contains numbers
and the numbers are seperated by the space character. The data will be loaded in
a variable whose name is identical with the file name.
General ascii files include data tables which are designed user dependent and use
different seperators between the data values, e.g., the ” ; ”.
;2163.690 ;1030.312 ;851.492 ;854.431
;2214.200 ;1017.779 ;842.111 ;844.042
;2256.701 ;959.704 ;832.543 ;823.110
;2328.647 ;986.154 ;822.486 ;807.683
;2334.473 ;985.780 ;810.127 ;799.802
You can easily load them into the MATLAB-workspace with the command dlm-
read.
71
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
>> dlmwrite(’my_mldata.dat’,A,’;’)
More difficult is the conversion of special kind of formats like for example
"Time " "CA1 " "CA2 " "CA3 " "CA9 " ...
"10:59:18" 2163.690 1030.312 851.492 854.431 ...
"10:59:19" 2214.200 1017.779 842.111 844.042 ...
"10:59:20" 2256.701 959.704 832.543 823.110 ...
"10:59:21" 2328.647 986.154 822.486 807.683 ...
"10:59:22" 2334.473 985.780 810.127 799.802 ...
"10:59:23" 2348.700 939.031 795.598 765.771 ...
.
.
.
If you would load this file directly to MATLAB, MATLAB would interprete sev-
eral of the seperators as MATLAB operators, e.g.,
10:59:18 as a vector,
To avoid this you have to delete the header line and the seperators, which can be
easily acchieved by an M-file (conti change.m).
72
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
fid=fopen(’conti.dat’);
if fid==-1 %fid>0 if successfull
disp(’File could not be opened!’)
else
headline=fgetl(fid);
line=fgetl(fid);
i=1;
while line˜=-1 %end of file
ind=find(line==’"’ | line==’:’);
line(ind)=[];
data(i,:)=sscanf(line,’%g’,7)’;
i=i+1;
line = fgetl(fid);
end
end
fclose(fid);
The input routine reads the data from the file conti.dat into the variable
data.
A MATLAB-compatible ascii-file can be generated by the command save.
saves the matrix data into a 16 bit ascii format with tabulator as separator. The
new data file only contains space characters as seperators. The file myfname.txt
can be loaded by the command load.
73
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
For the formatted input and output of data use the commands fscanf, fprintf,
fgetl and fgets.
For the positioning of file pointers you have the commands ftell, fseek,
feof, ferror, frewind.
The main difference between the general binary–format and the binary Mat–
format lies in the possiblity to save variables separated in the file.
With the help of the command fwrite you write the content of only one(!)
variable in form of a number column in a file.
The mat–format does not save only the content of a variable but, its name too.
You can save several variables in one file and you can load the file and its vari-
ables with the original names.
74
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT
First of all start with the menu File Import Data. After selecting a file
the MATLAB Import Wizard is started. The wizard tries to read the data
and presents a preview. For textdata a delimiter is suggested.
75
CHAPTER 4. MATLAB DATA INTERFACES 4.2. EXERCISE FOR CHAPTER 4
76
Chapter 5
Modelling in SIMULINK
Inhaltsverzeichnis
77
CHAPTER 5. MODELLING IN SIMULINK 5.1. MODEL OF AN ANALOG VOLTMETER
5.1.2 Governing equations
Equilibrium of moment
mit
Torque of current
mit
Spring retraction
mit
!
Kirchhoff law
mit
Induction
mit
#"
78
CHAPTER 5. MODELLING IN SIMULINK 5.1. MODEL OF AN ANALOG VOLTMETER
79
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
>> simulink
and
>> simulink3
80
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
First of all, to design a new model, an empty model must be opened using the
menu. File New Model. The icon displaying an empty page in the library
browser also opens a new model.
81
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
A double click with the left mouse button on a symbol opens the library or
82
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
There exist several possibilities to copy the needed blocks to the work
space:
83
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
With the blocks in the work space the model can be edited corresponding to the
block diagram of our example.
84
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
The block diagram has an open inport an no output port. For simulations there
must be at least one input signal (source) and an output (sink).
85
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
Blocks are opened using double clicks with the left button.
Now we can edit all fields by writing the individual block parameters in-
stead of the default values. The values are stored using the OK-button.
The Help-button calls the online help corresponding to this block.
86
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
A double click on the line opens a field for editing the signal name.
Another way is to use the context menu Properties by pressing the
right button. Signal names and a description can be given. In addition, the
signal may be marked as a test signal (useful for floating scopes, see below).
Signal names are not compulsory, but has some advantages:
– The block diagram is better readable.
– The correspondence between equations and the diagram is clear.
– The name is tied to the signal. This is also true for submodels, so the
signal is easily identified also in complex simulations covering several
layers of hierarchy. The character < may be used as a place holder and
is replaced with the signal name by SIMULINK after the simulation.
87
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
All blocks have names, which may be edited after a mouse click. Names
within a block diagram must be unique.
The menu Format (menu bar or right click on a block) allowes several
adjustments.
– Size and type of a font is modified by Font.
– The default position of a name is below its block, but may be changed
by Flip Name oder by draging the name with the mouse.
– You can hide the name using Hide Name.
– The menues Flip Block und Rotate Block change the orienta-
tion of a block.
– You can add a drop shadow using Show drop shadow. The menu
Format can be used to display vector signals with thicker lines.
To add arbitrary text within the work space position the mouse and click the
left button, and you can enter the desired text.
Different possibilities for zooming are given using the menu View.
88
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
Manipulation of blocks
Rotate Menu: Mark, Format Flip Block or For-
mat Rotate Block
Add Mouse: Drag&Drop onto connected signal
Size Mouse: Mark, click on handle an drag
Copy Mouse: Drag&Drop with right button
Menu: Mark, Edit Copy and Edit Paste
Delete Menu: Mark, Edit Clear
Keyboard: Mark, del-key
Name Mouse: Click and edit
Open Mouse: Double click
Drag Mouse: Drag&Drop with left button
Menu: Mark, Edit Cut and Edit Paste
Manipulation of signals
Branch Mouse: Right click and drag
Position Mouse: Click on corner or line and drag
Generate Mouse: Click on inport or outport and drag or mark
first block ctrl-click on second block
Delete Menu: Mark, Edit Clear
Keyboard: Mark, del-key
Mark Mouse: Click with left button
Segments Mouse: Mark, Shift-click and drag
Angle Mouse: Click and drag to destiny (multiple of 90);
Shift-click and drag (arbitrary angle)
Most of the operations can be done using menues, context menues (right button)
or using the keyboard.
89
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING
The diagram displays the deflection of the hand (angle) when changing the
voltage by 1 V after one second.
The Scope block displays the result of the simulation graphically. It can be
opened using a double click.
The scales of the axes can be changed using a context menu (right button).
Several kinds of zooming are possible.
90
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
>> example
Furthermore, simulations can be started directly from the command prompt, e.g.,
>> sim(’example’)
produces the same results as a simulation started with the menu Simulation from
the block diagram example. The model need not be open to start sim. Calling
sim without further parameters uses the options given in the menu Simula-
tion Parameters.
There is no automatic saving in SIMULINK.
91
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
The mdl-file of a model only stores the simulation parameters and the block
diagram. For the simulation an internal model is used. The mdl-file ist an ascii
file, as shown in the following excerpt of example.mdl:
Model
Name "example"
Version 4.00
SimParamPage "Solver"
SampleTimeColors off
InvariantConstants off
WideVectorLines off
ShowLineWidths off
ShowPortDataTypes off
StartTime "0.0"
StopTime "5.0"
SolverMode "Auto"
Solver "ode45"
RelTol "1e-3"
AbsTol "auto"
Refine "1"
MaxStep "auto"
InitialStep "auto"
FixedStep "auto"
MaxOrder 5
OutputOption "RefineOutputTimes"
OutputTimes "[]"
LoadExternalInput off
ExternalInput "[t, u]"
SaveTime on
...
92
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
>> J = 0.64e-6;
>> R = 2e3;
>> C_F = 16e-6;
>> K_I = 8e-2;
>> K_phi = 8e-2;
The data must be read before starting the simulation. They are evaluated at each
simulation start. All SIMULINK variables reside in the MATLAB workspace.
>> sim(’example’)
93
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
Another possibility is to create all data using a MATLAB script, which must be
called before starting a simulation (example data.m).
The user has the ability to specify for each block diagram MATLAB commands
which are evaluated at certain events, so called Callbacks. This is especially
useful for the initialization of a simulation. Callbacks can be entered using the
menu File Model Properties Callbacks.
The commands of the field Model pre-load function are executed before the block
diagram is opened, here the script example data.m is executed.
94
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
The command line version of using callbacks is given by the command set param
>>set_param(’example’,’PreLoadFcn’,’example_data’)
Using the option Callback tracing from the menu File Preferences Simulink
displays all executed callbacks in the command window.
95
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
The results of a simulation can also be stored. To this end, we introduce some
new blocks in our diagram and save it as example new.
K_I alpha
u_I dalpha Winkel
K_I
Mux
m_F
t C_F
Zeit C_F
96
CHAPTER 5. MODELLING IN SIMULINK 5.3. MATLAB INTERFACES
After the first simulation the MATLAB workspace contains the following vari-
ables:
>> whos
Name Size Bytes Class
C_F 1x1 8 double array
J 1x1 8 double array
K_I 1x1 8 double array
K_phi 1x1 8 double array
R 1x1 8 double array
alpha 52x2 832 double array
t 52x1 416 double array
tout 52x1 416 double array
The variable yout is generated only if the diagram has a block Out from the
library Sinks.
The workspace can be written to a file for later use, e.g., for a plot of the angle
and the angle velocity.
Sprungantwort Spannungsmessgeraet
7
−1
−2
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
The data format Structure allows to generate graphics using the command simplot.
97
CHAPTER 5. MODELLING IN SIMULINK 5.4. EXCERCISES FOR CHAPTER 5
(b) Compute the step response using the Transfer Function block. The
transfer function of the ODE is given by
and . This file
.
(c) Implement a m–file defining the variables ,
should be executed when opening the model using the callback PreLoadFcn.
Tip: The MATLAB-Editor is opened using the command edit. A m–
file is executed by calling the name (without extension!) at the MAT-
LAB command prompt.
(d) Save the results in a mat–file.
3. Construct an allpass filter using Gain, Integrator and Sum blocks. This
element is described by the following two ODE:
mit
98
Chapter 6
Inhaltsverzeichnis
99
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
100
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
1−u*u dx
1 1/s 1/s
Funktion ddx x
mu erste zweite
Integration Integration
dx dx Anzeige
The simulation parameters of a model can be retrieved from the MATLAB prompt,
e.g.,
>> options=simget(’vdp_bsp’)
options =
AbsTol: ’auto’
Debug: ’off’
Decimation: 1
DstWorkspace: ’current’
FinalStateName: ’’
FixedStep: ’auto’ % 1/50 Time interval
InitialState: [1 1]
InitialStep: ’auto’
MaxOrder: 5
SaveFormat: ’Array’
MaxRows: 0
MaxStep: ’auto’
MinStep: []
OutputPoints: ’all’
OutputVariables: ’ty’
Refine: 1
RelTol: 0.0010
Solver: ’ode45’
SrcWorkspace: ’base’
Trace: ’’
ZeroCross: ’on’
101
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
The command simset is used to change simulation parameters from the com-
mand prompt. A simulation is started using sim
>> plot(t, y)
vdp_bsp: Referenzloesung x
3
1
Zustand x
−1
−2
−3
0 1 2 3 4 5 6 7 8 9 10
Zeit [s]
The command line driven simulation is especially useful for parameter studies.
See, e.g., the file vdp sim.m.
options = simget(’vdp_bsp’);
T = 10;
% Reference solution:
% ...with Runge-Kutta 4,5
% ...with relative error tolerance 10ˆ(-6)
options=simset(options,...
’Solver’,’ode45’,...
% use Runge-Kutta 4,5 solver
’RelTol’,1e-6)
% use rel. tolerance 10ˆ(-6)
[t,x]=sim(’vdp_bsp’,T,options);
% Show results
%...
102
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
% Show results
%...
1
Zustand x
−1
−2
−3
0 1 2 3 4 5 6 7 8 9 10
Zeit [s]
103
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
% Show results
%...
1
Zustand x
−1
−2
−3
0 1 2 3 4 5 6 7 8 9 10
Zeit [s]
104
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
Scope
Mux
PT_1
1
Outport
% numerical solution
options = simget(’hff’); T = 25;
105
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS
0.9
0.8
0.7
0.6
Ausgangsgröße
0.5
0.4
0.3
0.2 analytisch
mit zero crossing
ohne zero crossing
0.1
0
0 5 10 15 20 25
Zeit [s]
The library Signals&Systems contains the block Hit Crossing. This block
is useful to emit an event signal if a defined state change occurs.
The menu Simulation Simulation parameters Advanced contains
the option to activate or deactivate zero crossing detection.
106
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
Block_4 Block_3
107
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
Block_4 Block_3
trouble solving.
108
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
We compare the simulation time for simulation steps (loop sim.m)
tfinal=10;
options=simget(’loop_1’);
options=simset(options,’Solver’,’ode4’,...
’FixedStep’,1.0e-3);
factor = time_w/time_wo
gives
factor =
5.8348
To break up algebraic loops use the Memory block from the library Conti-
nous.
The block IC (Initial Condition) from the library Signals & Systems may
help to speed up the computation of algebraic loops.
To solve differential algebraic systems of equations the block Algebraic
Constraint from the library Math can be used.
109
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
diskreter kontinuierliche
Regler Strecke
Step Scope
regler_d strecke_c
Each SIMULINK block has a sampler for the inport and a zero order hold
for the outport.
This enables SIMULINK to have different sample times for every discrete
block.
The time stepping algorithm generates time steps in sich a way, that every
sample time of every block is included. Therefore simulations of systems
with continous and discrete as well as different sample times are possible.
The following figure displays the time steps generated using the same solver but
for different systems; a continous, a hybrid and a discrete system.
Zeitstützstellen
1
Regler und Strecke kontinuierlich
0.5
−0.5
−1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
1
Regler diskret, Strecke kontinuierlich
0.5
−0.5
−1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
1
Regler und Strecke diskret
0.5
−0.5
−1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
110
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
Independantly of the time steps given by the ODE–solver the discrete block is
computed only every 0.5 sec and holds its signal in between. The sample time
of the discrete block forces the solver at least to time steps every 0.5 sec.
Ausgangssignal Regler
20
Regler diskret, Strecke kontinuierlich
15
10
−5
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
Ausgangssignal Strecke
1
kontinuierlich
hybrid
0.8 diskret
0.6
0.4
0.2
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
111
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
u_I
K_I dalpha
alpha
Momentengleichgewicht Mux
Zeit C_F
m_F alpha
Blocks can be grouped to subsystems using the menu Edit Create Sub-
system (or using the corresponding menu entry for the right button). Those
blocks to be grouped must be marked before, most easily using the marking
window.
A double click on the subsystem block opens a new window containing the
subsystem.
112
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
113
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
The library Signals&Systems contains all those blocks nessessary for manipu-
lating signals, like vectorization, converting data types or to access shared mem-
ory.
Bus Creator, Bus Selector, Selector:
Select/change vector signals
Mux, Demux: Vectorization / Devector-
ization of signals
Assignment Assign signals to components
of another signal.
Matrix Concatenation: Concatenate
matrix or vector signals
Merge: Choose the last updated signal
(useful for conditionally executed subsys-
tems)
From, Goto: Signals without physical
connection
Goto Tag Visibility: Choose the scope of From blocks
Data Store Read, Memory, Write: Read/Write shared memory
Reshape: Change matrix dimensions
Data Type Conversion: Change signal to another data type
Hit Crossing: Detection of specific events
IC: Define initial conditions
Width: Width of a signal (number of channels)
Model Info: Displays specific information (e.g., last save)
Signal Specification: Change attributes of a signal
Probe: Displays width, sampe time and whether a signal is complex
114
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION
In the example hff new.mdl discontinuities are detected. The results are used
for further processing.
Sum
PT_1
Hit
Crossing OR [Enable]
Goto
[Enable]
Hit
From
Crossing1 Logical
Operator
[Visualization] In
From1 [Visualization]
Subsystem
Goto1
115
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.3. EXERCISES FOR CHAPTER 6
1 1 1 1 5 1
Enable In1 Out1 Enable In1 Out1
Gain Gain
SubSystem1 SubSystem2
116
Chapter 7
Advanced techniques
Inhaltsverzeichnis
117
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
>> rt_blocks
All blocks are standard SIMULINK blocks with a new look and functionality
using masked subsystems.
118
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
7.1.1 Example
We want to generate a block with the dynamical properties of a
-element.
For a better usability the step response should be displayed on the block. The
-element has the transfer function
The -element is described using the block Transfer Function from the
library Continuous.
After opening the block, numerator and denominator polynoms are entered.
The menu Edit Mask Subsystem converts a subsystem to a masked subsys-
tem, so before we need to make the block Transfer Function a subsystem (see
p. 112).
119
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
120
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
121
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
122
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS
123
CHAPTER 7. ADVANCED TECHNIQUES 7.2. DEE
u_i K_I
dalpha
Sum
m_phi 1 1 alpha
1 1/R K_phi 1/J 1
u i ddalpha s s
In Out
m_F C_F
124
CHAPTER 7. ADVANCED TECHNIQUES 7.2. DEE
>> dee
Since the block DEE is not write protected one should first copy it to the workspace.
The opened block can then be edited by entering the differential equation in state-
space form.
125
CHAPTER 7. ADVANCED TECHNIQUES 7.2. DEE
The block can now be used in arbitrary simulations. We now want to use it as
an alternative to the structured block diagram sfun bd. Therefore we add an
inport and an outport and save it as sfun dee.mdl.
u(3) 1/s
1
x1 Integ1
SysInport1
f(u) 1/s
x2 Integ2
Mux
SysMux
u(2) 1
y1 Port1
126
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
Here we need to know something about the simulation technique used by SIMULINK.
127
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
>> sizes=sfun_bd([],[],[],0)
sizes =
2 % Num. of cont. states
0 % Num. of diskr. states
1 % Num. of outport
1 % Num. of inports
0 % reserved, always 0
1 % with/without direct feedthrough (1/0)
128
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
M-files
Self written MATLAB functions may also serve as S-functions. To this end there
exists a template file sfuntmpl.m in <MATLAB>\toolbox\simulink\
blocks, that can be edited and saved with a new name (m sfun.m).
Not only the fixed parameters t, x, u, flag are used but also user specified
parameters.
129
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
C or Fortran programs
C or Fortran programs can be used for S-functions as well, using so-called MEX-
files (MATLAB executable files). Again, a specific structure must be used.
/*
* MEX_SFUN Example mex file S-function
*
*
* Use this as a template
* for other MEX-file systems.
*
* Syntax [sys, x0] = ...
* mex_sfun(t,x,u,flag,C_F,K_phi,K_I,R,J)
*/
The most simple way to generate MEX-files is again to open the template
file <MATLAB>\simulink\src\sfuntmpl_basic.c with an edi-
tor, modify the corresponding functions and save it with a new name. A
more elaborate template file is sfuntmpl doc.c in the same directory.
Using the MATLAB program mex the source file must be compiled to an
executable MEX-file ((.dll).
130
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
S-function Builder
131
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
The S-function block can be used like every other SIMULINK block in a
block diagram.
Here we used the S-function mex sfun.dll in the model mex sfun.dll.
The S-function block can be used with functions programed in any of the
three languages Matlab, C and Fortran.
In the mask of the S-function block the name of the function and their pa-
rameters must be entered.
132
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
2.5
1.5
Simulink Modell
0.5 DEE Modell
.m S−Funktion
.mex S−Funktion
0
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
133
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
options=simset(options,’Solver’,’ode4’,...
’FixedStep’,1e-3);
% SIMULINK block diagram
tic
[t,x,y]=sim(’sfun_bd’,5,options,u);
rz=toc;
% Block diagram generated with DEE
tic
[tdee,xdee,ydee]=sim(’sfun_dee’,5,options,u);
rzdee=toc;
% Block diagram using a M-file S-function
tic
[tm,xm,ym]=sim(’sfun_m’,5,options,u);
rzm=toc;
% Block diagram using a C-file S-function
tic
[tmex,xmex,ymex]=sim(’sfun_mex’,5,options,u);
rzmex=toc;
...
>> sfun_sim
result =
’SIMULINK’ [0.0600]
’DEE’ [0.1300]
’m-Datei’ [4.7970]
’C-Datei’ [0.2700]
So, programing S-functions in C is especially suited for using existing code or for
programing functionality that is not possible using standard SIMULINK blocks.
134
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS
7.3.5 MaskS
We now continue working with the S-function written in C.
After converting the S-function block to a subsystem we used the menu Edit
Mask s-function to generate a new mask for this block.
With its new appearance we again include it in a model (sfun mex new.mdl).
135
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES
136
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES
>> set_param(’mymainlib/Messfuehler’,...
’OpenFcn’,’fuehler’)
137
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES
After saving the library mymainlib it can be used in its modified version.
Self written libraries can be included in the Simulink Library Browser as
well as the library Blocksets & Toolboxes by
1. adding the directory where the library resides to the MATLAB path
2. and by creating a file called slblocks.m. In this file a variable
named blkStruct must be defined. Any file of the SIMULINK li-
braries may serve as an example.
138
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES
Browser(1).Library = ’mymainlib’;
Browser(1).Name = sprintf(’Eigene Bibliotheken’);
blkStruct.Browser = Browser;
% End of slblocks
139
CHAPTER 7. ADVANCED TECHNIQUES 7.5. EXERCISES FOR CHAPTER 7
To compute
the step response for the icon use the equation
.
2. Realise the all-pass filter with the Differential Equation Editors. Verify
your new block with SIMULINK by some simulations. The state space
equations of the all-pass filter are given by
3. Program a S-function as a M-file for simulating the all-pass filter; use the
file m sfun.m as a starting point.
4. Create a new library with the all-pass filter as its content.
140
Chapter 8
STATEFLOW
Inhaltsverzeichnis
141
CHAPTER 8. STATEFLOW 8.1. BASICS
8.1 Basics
STATEFLOW is a SIMULINK Blockset for the graphical development and sim-
ulation of finite state machines.
This class of models serves for modeling of complex control and monitoring
problems.
>> sfnew
Alternatively:
via the SIMULINK Block Library Signals & Toolboxes, SF
142
CHAPTER 8. STATEFLOW 8.1. BASICS
STATEFLOW Commands
sfnew generates a SIMULINK model with an empty
STATEFLOW block
sfexit closes all models with STATEFLOW blocks and
clears STATEFLOW from the memory
sfsave saves state charts and their SIMULINK models
stateflow, sflib opens the STATEFLOW Library SF
sfprint prints a STATEFLOW chart (format eligible)
sfhelp opens the STATEFLOW Online Help (HTML)
143
CHAPTER 8. STATEFLOW 8.1. BASICS
B C
B 1 C 2
144
CHAPTER 8. STATEFLOW 8.1. BASICS
On/
entry: i=0;
during: i=i+1;
exit: function_call();
state names are separated from their actions by slash (/) or carriage return.
Types of actions are:
en(try) Action is executed, when the state is activated.
du(ring) Action is executed, when an event occurs, if the state has been
active and is not exited.
ex(it) Action is executed, when the state is deactivated.
Actions can be:
– calculations,
– function calls,
– sending of events.
145
CHAPTER 8. STATEFLOW 8.1. BASICS
Transitions
On
Off
On [Condition]
Off
– The chart switches from state On to the junction and from there to state
Off, if the Condition is true. If not it switches back to state On.
146
CHAPTER 8. STATEFLOW 8.1. BASICS
[Condition]
On
Off
– In the example above the state Off is chosen as the initial state.
A
[Condition] H
On
Off
– When State A is activated for the first time, state A.Off is set active as
well due to the default transition.
When it is activated next time, the chart reactivates the substate active
last.
147
CHAPTER 8. STATEFLOW 8.1. BASICS
A
H
[B1]
On
E1
Off
E2[B2]{CA}/TA
On is active. When the event E1 occurs, the transition segment to the junc-
tion becomes valid and switches at first.
If the Condition B1 is true state Off becomes active, if not the non labeled
transition switches to state On.
State Off is active. The chart switches to state On, if event E2 occurs and
condition B2 is true. The Condition Action CA and the Transition Action
TA are executed.
A non labeled transition switches at any event, provided that its source state
is active.
148
CHAPTER 8. STATEFLOW 8.1. BASICS
IF THEN
Moore Mealy
entry transition action of the transition to the destination state
state
149
CHAPTER 8. STATEFLOW 8.1. BASICS
Events
On
switch_off
Off
switch_on
Data
Data are variables within a state chart. They have numerical values.
On
switch_off/off_count++
Off
switch_on/on_count++
Data access and data flow can be organized in several manners, e.g.:
Input from SIMULINK Data import from SIMULINK.
Output to SIMULINK Data export to SIMULINK
Workspace Variables have to be assigned in the MATLAB Workspace.
150
CHAPTER 8. STATEFLOW 8.1. BASICS
In the following example we develop the state chart of an over head projector.
Main part of the projector is the light source which is switched on or off.
Graphical objects are generated by clicking on an icon of the icon bar and
a second click on the workspace.
A double click on an icon causes the generation of as many objects as de-
sired until it is ended by ESC or a click on the right mouse button.
Drag & Drop with the left mouse button shifts graphical objekts. Drag &
Drop with the right mouse key copies them.
the default name of a state is ?. We edit it by clicking on it.
The size of a state object can be changed by clicking on the rounded corners
and pulling.
In order to build up a state hierarchy we enlarge a certain state and place
substates inside it.
151
CHAPTER 8. STATEFLOW 8.1. BASICS
The light source is turned on and off by the events light on and light off.
The state Light.Off is the initial state.
152
CHAPTER 8. STATEFLOW 8.1. BASICS
Beside the light source a projector has got a fan which works at the same time,
so that the device will not overheat.
To speed up the process we copy the entire superstate Light and change
the labeling. The superstate including all children can be selected as fol-
lows:
– either using a bounding box
– or grouping it (double click or short cut menu).
The states Light und Fan have to work parallelly.
In order to assign this property we click with the right mouse button on the
area outside the states and choose the option Decomposition Parallel
from the menu.
153
CHAPTER 8. STATEFLOW 8.1. BASICS
Both superstates, Light and Fan, have to be combined to guaranty the cooling
whenever the light source is turned on.
Therefore we add the transition actions fan on bzw. fan off to the transition
lables in superstate Light. Thus the event fan on is send simultanous to the
switching on of the light source.
154
CHAPTER 8. STATEFLOW 8.1. BASICS
– The STATEFLOW block proki fsm has got a (symbolic) trigger in-
put as a result of defining the input events. If there are more than one
input event, the signals have to be vectorised by a Mux.
– Each output data creates an output port of it’s own.
155
CHAPTER 8. STATEFLOW 8.1. BASICS
The Pulse Generator generates a rectangular signal. The state chart proki fsm
is triggered by the rising and falling edge.
The variable run reflects the state of the light source (0 or 1) and count
the number of switching operations in SIMULINK.
The first pulse has no effect on the light source, because this event is used
for initialization only.
The second event is light off. So the third event turns on the light.
156
CHAPTER 8. STATEFLOW 8.1. BASICS
8.1.3 Exercises
1. Complete the STATEFLOW block, so that the simulation stops at the stop
time required!
2. Add a switch that models the power supply to the projector model. Realize
this switch within the STATEFLOW-model by adding states on a certain
hierarchy level.
power off: nothing works.
power on: The light can be turned on and off by a separate switch as
before.
Add a second input event to the state chart and realize the acoording signal
in SIMULINK by a manual switch.
Set the simulation time to infinitve: inf.
Subchart the superstates on the higher hierarchy level.
157
CHAPTER 8. STATEFLOW 8.2. SOME ITEMS OF STATEFLOW
Subcharts can be created from a superstate using the context menu Make
contents Subcharted (right mouse key).
The transitions out of and into subcharts are called supertransitions.
They can be generated by pulling a transition from a source state within a
subchart towards the border of this subchart. There a wormwhole occurs
and the transition is pulled towards its center. This way the transition leads
to the upper level of the chart which might contain the destination state.
If the destination state is situated within another chart, the transition is
pulled toward the center of that subchart where another wormhole occurs.
158
CHAPTER 8. STATEFLOW 8.2. SOME ITEMS OF STATEFLOW
Graphical functions are created the just like subcharts from a state and con-
verted into a function using the context menu Type Function (right
mouse key).
Functions contain Flowcharts. these are charts which consist of junctions
and transitions only. States are not allowed in graphical functions.
The following rules are valid for the parameters of graphical functions:
– They may have one return parameter only.
– Arrays are not allowed as arguments or return values.
– Arguments have no initial values.
– Return parameters have always a scope Output, arguments have a
scope Input.
Additional data can be declared as Local, Temporary and Constant.
159
CHAPTER 8. STATEFLOW 8.2. SOME ITEMS OF STATEFLOW
Light 1
On light_off Off
en: light_out=1; en: light_out=0;
on after(5,T_eve):fan_off;
light_on
Fan fan_off 2
On Off
en: fan_out=1; en: fan_out=0;
exit(Light.Off)
Timer every(10,T_eve)/light_off; 3
On Off
every(10,T_eve)/light_on;
160
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS
On the left hand side of the window above there is a browser for the entire
object hierarchie of all state charts open .
On the right hand side we find all events and data of proki new.proki fsm.
With the menu Add of the explorer we can add new objects as well as with
the menu Add of the editor.
Note: Exclusive within the explorer it is possible:
1. to delete objets: select and key Del or menu Edit Cut.
2. to shift objects between hierarchy levels: Drag & Drop.
3. to change the sequence of objects: Drag & Drop.
4. to change properties of non graphical objects: double click on the ob-
ject opens the property mask.
161
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS
Properties of charts
162
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS
Breakpoints: sets global breakpoints Local breakpoints are set at the prop-
erty mask of an object.
Display in output window:
– Call Stack: Displays the future steps of the programm execution.
– Coverage: Displays the rate of the executed programm code.
– Browse Data: Displays the value of variables (only those variables,
where the option Watch in Debugger was selected in the mask).
163
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS
8.3.4 Exercises
1. Test the functionality of the various STATEFLOW-Tools, using them on the
examples developed.
2. Design a controller in STATEFLOW for switching a compressor on and off
using the temporal logic operators:
Function:
If there is a request ”Kompressor on”, from a superordinated controller
the compressor should be switched on immediately.
If there is no request for the compressor anymore the compressor shouldn’t
be switched off imediately. A ventilation valve is opened and the com-
pressor keeps running for another 4 seconds. After the compressor is
switched off the ventilation valve remains open 4 more seconds before
it is closed.
After closing the valve the compressor is ready for a new request. This
process of switching off the compressor lasts altogether 8 seconds.
If there is a new request within these 8 seconds it should work as follows:
If the request occurs during the first 4 seconds (when the compressor
isstill running) the ventilation valve is closed and the compressor keeps
running.
If the request occurs during the next 4 seconds after switching off the
compressor, the process of ventilation should be finished (4 seconds
waiting), before the compressor can be switched on again (if there is
still the request for it).
8 Bedarf
Kompressor
Ventil
6
0
0 2 4 6 8 10 12 14 16 18 20
164
Chapter 9
Inhaltsverzeichnis
165
CHAPTER 9. EXECUTION ORDER 9.1. THE SIMULINK EXECUTION ORDER
Subsystem1
In1 Out1
1 res
source sink
In1 Out1
Subsystem2
1 1
1
1 In1 z z Out1
z1 z2
Note: The sldebug command slist shows all executable (basic) blocks, but
not always in the calculation order of SIMULINK. (This is a bug!)
166
CHAPTER 9. EXECUTION ORDER 9.2. CONDITIONALLY EXECUTED SUBSYSTEMS
f()
fcn_call 1 1 trigger 1 1
1 1
1 In1 z z Out1 1 In1 z z Out1
z1 z2 z1 z2
167
CHAPTER 9. EXECUTION ORDER 9.2. CONDITIONALLY EXECUTED SUBSYSTEMS
There are two different types of conditions you can use to determine, if a sub-
system shall be executed:
1. function calls: function call control inputs can only come from
a STATEFLOW block (library sflib) or a
Function-Call Generator (library Signals & Systems).
trigger_2 0
chart
Note: Both control signal types differ concerning the execution order of the
calling and called system.
168
CHAPTER 9. EXECUTION ORDER 9.2. CONDITIONALLY EXECUTED SUBSYSTEMS
The block sending out a function call is the master (main). It controls the execu-
tion order.
When a function call is sent by a master block the calculation of the master stops
immediately. The called subsystem is computed and afterwards the master sub-
system continues.
fcn_call_1 fcn_call_1
Demux function call()
Demux function call()
fcn_call_2 In1 Out1 fcn_call_2 In1 Out1
Selector Selector
Scheduler Scheduler
1 Subsystem1 res 1 Subsystem1 res
source Subsystem2 sink source Subsystem2 sink
( ’ex21/source’): ( ’ex22/source’):
( ’ex21/Scheduler’): ( ’ex22/Scheduler’):
( ’ex21/Subsystem1/z1’): ( ’ex22/Subsystem2/z3’):
( ’ex21/Subsystem1/z2’): ( ’ex22/Subsystem2/z4’):
( ’ex21/Subsystem2/z3’): ( ’ex22/Subsystem1/z1’):
( ’ex21/Subsystem2/z4’): ( ’ex22/Subsystem1/z2’):
( ’ex21/sink’):
( ’ex22/sink’):
169
CHAPTER 9. EXECUTION ORDER 9.2. CONDITIONALLY EXECUTED SUBSYSTEMS
9.2.2 Triggers
A trigger signal produced by a certain block is an event which triggers a sub-
system so that its execution condition is true. But in this case SIMULINK itself
remains the master and manages the control flow.
Thus a triggered subsystem comes into operation during the current time step,
if the trigger is generated before the triggered subsystem in the calculation se-
quence. It is computed at the next time step, if the internal calculation order is
vice versa.
Example: The only difference between the two systems below is the control
condition of the subsystems.
Triggered Subsystems:
Subsystem1
0
1 In1 Out1
sub1
subout Merge
sub2
1 In1 Out1
Constant Subsystem2
switch/sub1
A B
subout subout
switch/sub2
Transiting from state A to state B the call to Subsystem 1 (/sub1) is sent out.
Switching back to A Subsystem 2 (/sub2) is called.
170
CHAPTER 9. EXECUTION ORDER 9.2. CONDITIONALLY EXECUTED SUBSYSTEMS
The output of the subsystem calculated most recently is put through to the state-
flow block and mapped to the stateflow variable subout.
We assume subsystem 2 has been calculated most recently and state A is active.
Now the event switch occures so the transition from A to B is executed.
Subsystem1
0
1 In1 Out1
Trigger()
sub1 Merge
subout
sub2
Trigger()
1 In1 Out1
Constant Subsystem2
The output of the subsystem calculated most recently is put through to the state-
flow block and mapped to the stateflow variable subout.
We assume subsystem 2 has been calculated most recently and state A is active.
Now the event switch occures so the transition from A to B is executed.
171
CHAPTER 9. EXECUTION ORDER 9.3. EXERCISE FOR CHAPTER 9
Change the setting of the first output of the STATEFLOW block to Func-
tion Call. Match the setting of the subsystem called by his signal!
172