You are on page 1of 173

Mechatronic Systems Simulation

Part B: Integrated System Simulation

Dr.-Ing. Peter Krauss

MATLAB / SIMULINK / STATEFLOW

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

2 MATLAB as a Programming language 29


2.1 Flow Control Structures in MATLAB . . . . . . . . . . . . . . 30
2.2 MATLAB – Programs . . . . . . . . . . . . . . . . . . . . . . . 31
2.2.1 Command sequences – (MATLAB Scripts) . . . . . . . 31
2.2.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.2.3 function–functions . . . . . . . . . . . . . . . . . . . . 33
2.2.4 Local, global and persistent variables . . . . . . . . . . 34
2.2.5 Program Structures . . . . . . . . . . . . . . . . . . . . 35
2.3 Programming Tools . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3.1 The Editor / Debugger . . . . . . . . . . . . . . . . . . 39
2.3.2 Debugging . . . . . . . . . . . . . . . . . . . . . . . . 41
2.3.3 Online-Help . . . . . . . . . . . . . . . . . . . . . . . . 42
2.4 Exercises for Chapter 2 . . . . . . . . . . . . . . . . . . . . . . 43

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

4 MATLAB Data Interfaces 69


4.1 General Data Format . . . . . . . . . . . . . . . . . . . . . . . 70

2
CONTENTS CONTENTS

4.1.1 Open and Close Files . . . . . . . . . . . . . . . . . . . 70


4.1.2 The MATLAB Data Format (.mat) . . . . . . . . . . . . 70
4.1.3 Processing of ASCII-Files . . . . . . . . . . . . . . . . 71
4.1.4 Processing of Binary Data . . . . . . . . . . . . . . . . 74
4.1.5 MATLAB Import Wizard . . . . . . . . . . . . . . . . . 75
4.2 Exercise for Chapter 4 . . . . . . . . . . . . . . . . . . . . . . 76

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

6 Basic simulation techniques 99


6.1 Simulation parameters . . . . . . . . . . . . . . . . . . . . . . 100
6.1.1 Parameter studies . . . . . . . . . . . . . . . . . . . . . 101
6.2 Blockoriented simulation . . . . . . . . . . . . . . . . . . . . . 107
6.2.1 Execution order . . . . . . . . . . . . . . . . . . . . . . 107
6.2.2 Algebraic loops . . . . . . . . . . . . . . . . . . . . . . 108
6.2.3 Discrete and continous blocks . . . . . . . . . . . . . . 110
6.2.4 Hierarchical models . . . . . . . . . . . . . . . . . . . 112
6.2.5 Complex simulation models . . . . . . . . . . . . . . . 113
6.3 Exercises for chapter 6 . . . . . . . . . . . . . . . . . . . . . . 116

3
CONTENTS CONTENTS

7 Advanced techniques 117


7.1 Masked subsystems . . . . . . . . . . . . . . . . . . . . . . . . 118
7.1.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.2 DEE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
7.2.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . 124
7.2.2 Differential Equation Editor (DEE) . . . . . . . . . . . 125
7.3 S-functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
7.3.1 S-functions . . . . . . . . . . . . . . . . . . . . . . . . 127
7.3.2 Type of S-functions . . . . . . . . . . . . . . . . . . . . 128
7.3.3 Integration in a block diagram . . . . . . . . . . . . . . 132
7.3.4 Comparison of different realizations . . . . . . . . . . 133
7.3.5 MaskS . . . . . . . . . . . . . . . . . . . . . . . . . . 135
7.4 Creating new libraries . . . . . . . . . . . . . . . . . . . . . . . 136
7.5 Exercises for chapter 7 . . . . . . . . . . . . . . . . . . . . . . 140

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

9 Execution Order 165


9.1 The SIMULINK Execution Order . . . . . . . . . . . . . . . . 166
9.2 Conditionally Executed Subsystems . . . . . . . . . . . . . . . 167
9.2.1 Function Calls . . . . . . . . . . . . . . . . . . . . . . 169
9.2.2 Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . 170

4
CONTENTS CONTENTS

9.3 Exercise for chapter 9 . . . . . . . . . . . . . . . . . . . . . . . 172

5
Chapter 0

Introduction

Inhaltsverzeichnis

0.1 The MATLAB Product Family . . . . . . . . . . . . . . . . . . . . . . . . . 7

6
CHAPTER 0. INTRODUCTION 0.1. THE MATLAB PRODUCT FAMILY

0.1 The MATLAB Product Family

SIMULINK
BLOCK-
SETS

MATLAB
STATEFLOW

TOOL-
BOXES

C-CODE
HARDWARE
DATA

STAND-ALONE
APPLICATION

What is MATLAB?

MATLAB is the abbreviated form of Matrix Laboratory. It has been developed


for technical Computing.
MATLAB is
an interactive programming environment,
a high level language,
a development tool,
a library of mathematical functions
and very easy to use.

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.

STATEFLOW is a special Blockset of SIMULINK for the design of


complex control structures,
i.e. for event driven systems,
for their simulation and
analysis.
STATEFLOW-models are developed and programmed as state machines.

MATLAB-Toolboxes are application-specific libraries of MATLAB functions


that customize MATLAB for solving particular classes of problems.

SIMULINK-Blocksets are application-specific libraries for SIMULINK-modells.

8
Chapter 1

MATLAB as an Interactive Programming


Environment

Inhaltsverzeichnis

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

9
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB

1.1 Calculation with MATLAB


1.1.1 Integrated Development Environment (IDE)

The default behaviour of MATLAB is to start as Integrated Development Envi-


ronment (IDE). Five windows are open, which may be seperated from the IDE:

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.1.2 The MATLAB Command Window

The menu View controls the appearance of the MATLAB Development


Environment.
The Command Window is the main window of MATLAB. It is the interface
for communication withe MATLAB in the interactive mode.
With the cursor keys and  former commands can be revisited.
clc clear the Command Window.
ans means answer and is the default-variable for calculation without as-
signment (pocket calculator mode), e.g.,
 

>> 1 + 2

ans = 3 

Data types of variables are selected by the assignment of a value (no ex-
plicit declaration).

Names of variables and constants


– may contain alphanumerical characters and the ”‘ ”’ (alltogether 31
characters, first character must be a letter),
– with capital and small letters are distinguished by MATLAB.

11
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB

1.1.3 The Data Types


Numerical notation of matrices:
 

>> A = [1 2 3 4
5 6 7 8]
A =
1 2 3 4


5 6 7 8 

– Matrices are generally placed within brackets.


– The access to matrix elements is possible via the indices of rows and
columns.
– Commands for the determination of the matrix dimension are: size,
length;
– Each element of a matrix requires Byte of memory.
– Complex Matrices require the double size of memory, because MAT-
LAB holds real and imaginary part separately.
– Sparse matrices are matrices with only few nonzero entries. MATLAB
provides special routines for these kind of matrices.
– There are routines for image processing operating on data of one Byte
length.

Strings
 

>> SomeString = ’Hello World.’;


 

– Strings are enclosed in single quotation marks.


– Strings are character matrices. The access to their elements is possible
via indices.
– Each element of a character matrix requires Byte of memory.


– conversion commands are: str2num, int2str, num2str, str2mat,


mat2str, str2double.

12
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB

Cells
 

>> SomeCell(1)= A ; 

>> SomeCell(2)= SomeString ; 

 

or
 

>> SomeCell 1 =A; 

>> SomeCell 2 =SomeString;




 

– Elements of cell arrays contain variables of different types, for instance


matrices of different size.
– To access the data use subscripts in curly braces or parentheses, resp.
– The curly braces are used to identify cell arrays.
– Commands: cell, cell2struct, celldisp, cellplot, num2-
cell, [var : ]. 

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

1.1.4 The MATLAB Workspace


The content:
The current content of the MATLAB workspace can be displayed by the
commands
 

>>who

Your variables are:

A struct


SomeString SomeCell 

or
 

>> whos
Name Size Bytes Class

A 2x4 64 double array


SomeCell 1x2 272 cell array
SomeString 1x12 24 char array
struct 1x1 336 struct array

Grand total is 64 elements using 696 bytes 

Clearing of the workspace:


We can clear the workspace with the command clear, e.g.,
 

>> clear SomeString struct SomeCell


>> who

Your variables are:




A 

14
CHAPTER 1. MATLAB INTERACTIVELY 1.1. CALCULATION WITH MATLAB

Load and Save:


For loading and saving the current content of the workspace we use the
commands load and save, resp. For example we save workspace data
into the file example.mat as follows:
 

>> save example 

The content of example.mat can be reloaded using


 

>> load example 

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

1.1.5 MATLAB Notation


[ ] Enclose vectors and matrices A = [ 1 2;3 4]
Enclose output parameters of functions [V,D]=eig(A);
( ) Indices of matrix or vector elements A(3);
Nesting of mathematical calculations (a+b)*c
Input parameters of functions plot(x,y)
 Representation of cells cell(1)= A ; 

= 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

1.1.6 Arithmetic Operators


matrix operation field operation
addition + +
subtraction - -
multiplication * .*
division right / ./
division left \ .\
power ˆ .ˆ
transpose (conj. complex) ’
transpose .’
 

>> A=[1 2;3 4]


A=
1 2
3 4

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

1.1.7 Relational and logical operators


< less than a<b
<= less than or equal a<=b
> greater than a>b
>= greater than or a>=b
equal
== equal a==b
& and a&b
| or a|b
˜ not ˜a
˜= not equal a˜=b

Examples:
 

>> A=[0 1 2];


>> B=[0 1 4];
>> A˜=B

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

1.1.8 Elementary mathematical functions


log10 Common (base 10)
abs Absolute Value
logarithm
angle Phase angle
real Complex real part
atan Inverse tangent
ceil Round towards
 rem Remainder after division
round Round towards nearest
conj Complex conjugate integer
cos Cosine sign Signum function
exp Exponential sin Sine
fix Round towards zero sqrt Square root
floor Round towards 
 tan Tangent
imag Complex imaginary part tanh Hyperbolic tangent

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

1.1.9 The output display format


MATLAB performs all computations in double precision. The format com-
mand changes the display format of the Command Window. In standard display
format the constant pi
looks like: in opposition to:
 

 

>> pi >> format long


ans = >> pi
3.1416 ans =


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

1.1.10 Help and Online Documentation


The easiest way to get help is the help command, e.g.,
 

>> help sqrt

SQRT Square root.


SQRT(X) is the square root of the
elements of X. Complex results are
produced if X is not positive.
 

For navigation through help to different routines a separate window can


be launched (menu Help, commands helpwin or for further information
helpdesk and doc, resp.

A complete MATLAB documentation is available in the Adobe Portable


Document Format (PDF) on te MATLAB Documentation CD.

20
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES

1.2 Manipulation of Vectors and Matrices


1.2.1 The Assignment of Vectores and Matrices
The matrix 





can be generated either by elementwise assignment


 

>> A(1,1)=1; A(1,2)=4; A(1,3)=7;


>> A(2,1)=2; A(2,2)=5; A(2,3)=8;
>> A(3,1)=3; A(3,2)=6; A(3,3)=9;
 

or in one piece, using MATLAB notation.


 

>> A=[1 4 7;2 5 8;3 6 9];


 

or using the colon operator and other funtions for matrix manipulation
 

>> A=1:9; A=reshape(A,3,3);


 

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

1.2.2 Special matrices


Matrix of zeros
 

>> A=zeros(3,3) % or: A=zeros(3)


A =
0 0 0
0 0 0


0 0 0 

Matrix of ones
 

>> A=ones(3,3) % or: A=ones(3)


A =
1 1 1
1 1 1


1 1 1 

Identity matrix
 

>> A=eye(3,3)
A =
1 0 0
0 1 0


0 0 1 

Empty matrix
 

>> A=[]
A =


[] 

Special matrices and vectors: rand, randn, linspace,


logspace, meshgrid, compan, diag, gallery, hadamard, han-
kel, hilbert, invhilb, kron, magic, pascal, toeplitz, van-
der, wilkinson

22
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES

1.2.3 Submatrices, Matrix-Indexing


Single elements: A(2,3)

Columns: A(:,4)

Rows: A(3,:)

Blocks: A(1:2,2:4)

Several elements: A([3 4 13])

23
CHAPTER 1. MATLAB INTERACTIVELY 1.2. MANIPULATION OF VECTORS AND MATRICES

1.2.4 Multidimensional matrices


MATLAB works with multidimensional matrices.
 

 

>> C(:,:,1)
>> A = [1 2;3 4];
ans =
>> B = [5 6;7 8];
1 2


>> C = cat(3,A,B); 

3 4 

The function CAT(DIM,A,B) concatenates the input matrices (here A and


B) along the dimension.
The conventions and notations are adjusted only in the dimension.
   

 

>> cat(1,A,B) >> cat(2,A,B) >> cat(3,A,B)




>> % => [A;B]


 

>> % => [A,B] 


 

Special multidimensional matrices can be generated resp. initialilized with


the functions zeros, ones, rand or randn, e.g., the command
 

>> D = zeros(5,4,3,2);
>> whos C D
Name Size Bytes Class

C 2x2x2 64 double array




D 4-D 960 double array 

generates a 4-dimensional matrix of zeros.


Functions to manipulate multidimensional matrices are cat, flipdim,
ind2sub, ipermute, ndgrid, ndims, permute, reshape, shift-
dim, squeeze, sub2ind

24
CHAPTER 1. MATLAB INTERACTIVELY 1.3. POLYNOMIALS UND MATRICES

1.3 Polynomials und matrices


1.3.1 Description of differential equation systems

   
State space description (matrix-oriented)

  
 e.g. for a second order System
 

>> K=2; d=0.5; w0=1;


>> A=[0 1;-w0ˆ2 -2*d*w0], B=[0;K*w0ˆ2]
A =
0 1
-1 -1

B =
0
2

>> C=[1 0], D=0


C =
1 0

D =


0 

               


Transfer function (polynomial description)
  

  e.g. for the second order system


>> b = K*w0ˆ2
b =
2

>> a =[1 2*d*w0 w0ˆ2]


a =


1 1 1 

25
CHAPTER 1. MATLAB INTERACTIVELY 1.3. POLYNOMIALS UND MATRICES

1.3.2 Polynomial functions


poly characteristic p=poly(A)
polynomial p =
1.0000 1.0000 1.0000
roots roots of the r=roots(p)
polynomial r =
-0.5000 + 0.8660i
-0.5000 - 0.8660i
polyval evaluate GZ=polyval(p, x);
polynomial
polyvalm evaluate polynomial
with matrix argument
conv polynomial p=conv([1 -r(1)],
multiplication [1 -r(2)])
p =
1.0000 1.0000 1.0000
deconv polynomial division deconv(p ,[1 -r(2)])
ans =
1.0000 0.5000-0.8660i
residue partial-fraction residue(b,a)
expansion ans =
0 - 1.1547i
0 + 1.1547i
polyder differentiate polyder(a)
polynomial ans =
2 1
polyfit fit polynomial to data in p=polyfit(a,p,3)
a least-squares sense
p =
1.0000 0 0 0

26
CHAPTER 1. MATLAB INTERACTIVELY 1.4. EXERCISES FOR CHAPTER 1

1.4 Exercises for Chapter 1


Some hints:
To reach the Online Help please use the command doc.
Useful commands are rank, eig, roots, polyder, polyval, max,
clear, load, save.
You can find a suggested solution in the file solution chap1.m.

      
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.

3. Solve the system of equations  .  


Try to use a numerical better algorithm (not inv).

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

6. Saving and loading Data:


Save the variable A into a *.mat-file.
Clear A from the MATLAB–workspace.
Load A from the *.mat-file into the MATLAB–workspace.

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

MATLAB as a Programming language

Inhaltsverzeichnis

2.1 Flow Control Structures in MATLAB . . . . . . . . . . . . . . . . . . . . . 30


2.2 MATLAB – Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
2.2.1 Command sequences – (MATLAB Scripts) . . . . . . . . . . . . . . . 31
2.2.2 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
2.2.3 function–functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
2.2.4 Local, global and persistent variables . . . . . . . . . . . . . . . . . . 34
2.2.5 Program Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2.3 Programming Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3.1 The Editor / Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . 39
2.3.2 Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
2.3.3 Online-Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
2.4 Exercises for Chapter 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

29
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE
2.1. FLOW CONTROL STRUCTURES IN MATLAB

2.1 Flow Control Structures in MATLAB


break break of a loop
end end of a loop or an if-structure
error output an error message and stop execution
for for loop (counting)
if, else, elseif conditional program flow
return return to the calling function
switch, case, otherwise decision between several cases
while while loop (condition)

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
 

>> n=3; ematrix; E % see eye(3,3)


E =
1 0 0
0 1 0


0 0 1 

30
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

2.2 MATLAB – Programs


2.2.1 Command sequences – (MATLAB Scripts)
An M–Script is the most simple form of a MATLAB program. Instead of typing
your MATLAB commands at the Command Window you write them into a file
with the extension *.m and save it under a specific name.
Example: Calculation of unit step response of a second order system (pt2s.m)

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

% is for Comment lines.


In command sequences the variables, e.g. K, D, w0, w, t, h are held in the
MATLAB workspace.

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 

A function has its own local workspace.


MATLAB parses the function and stores it in memory after the function
call.
The arguments varargin and varargout allows you to write functions
with a variable number of arguments.
The optional comment in the header of the function are used for the online
help.

32
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

2.2.3 function–functions in MATLAB


function functions are functions that have a function as input parameter. An
example is the solver of differential equations. The function, which is the input
variable of the solver function, describes the differential equation.


  
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
 

>> K=1; T=1; u=1;


>> tend=10; y0=0;
>> [t_ss,y_ss]= ...


ode45(’pt1_dgl_ss’,tend,y0,[],K,T,u); 

DGL−Loesung fuer PT1 Bauteil


1

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

2.2.4 Local, global and persistent variables


Each M-file function has an area of memory, separate from MATLABs base
workspace, in which it operates. This area is called the function workspace, with
each function having its own workspace context. Variables are local, i.e., they
are only visible within the function workspace. To use them globally you have
to declare them as global variables e.g.,
function xp=pt2zrd(t,x)
%PT2ZRD state space model
%of second order system
global K D w0
xp=[x(2); -w0ˆ2*x(1) - 2*D*w0*x(2) + K*w0ˆ2];
Commands in MATLAB workspace
2.5

 

>> global K D w0 2

>> K = 2; D = .5; w0 = 1; 1.5

>> T = 10, x0 = [0;0]; 1

>> [t,x] = ode45(’pt2zrd’,T,x0); 0.5

>> plot(t,x(:,1))
 

0
0 1 2 3 4 5 6 7 8 9 10

The variables K, D and w0 are in the global workspace.

Since the MATLAB-Version 5.3 it is possible to use persistent variables. They


can be defined by:
persistent myvar

Persistent variables are only usable in functions.


They are cleared when the M-file is cleared from memory with the com-
mand clear or when the M-file is changed.
Persistent variables maintain their values from one function call to the next
as opposed to local variables.
The functions mlock, munlock and mislocked support the usage of
persistent variables.

34
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

2.2.5 Program Structures in MATLAB


File and Variable Names in the MATLAB Search Path

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


. 

When MATLAB comes upon a new name, e.g.


 

>> bsp 

it follows these steps, in order: MATLAB


1. checks to see if bsp is a variable in workspace,
2. checks to see if bsp is a MATLAB built-in function,
3. checks to see if bsp is a file in the current directory,
4. checks to see if bsp is a file in the directory ”private”,
5. checks to see if bsp is a file in the MATLAB-Path and execute the first
file which is found.
Attention: MATLAB doesn’t warn you if you overload a function name with a
variable name. It will use the function or variable with highest MATLAB calling
priority.
For example
 

 

>> cd=1; cd >> clear cd


cd = >> cd


1 


c:\kurs 

overwrites the command cd. repairs it again

35
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

User-created functions can be administrated without a risk of duplicated desig-


nation:
when using the special directory private (a directory accessible only to M-
files in the directory immediately above it).
when using subfunctions in a function. These subfunctions are only acces-
sible in the function where they are declared.
To make user directories accessible to MATLAB there are the following possi-
bilities:
With path, addpath and rmpath we can manipulate the search path.
Extensions to the search path can be defined in the file startup.m in
order to make user specific updates to the path at each start of MATLAB.
Additionally there is the Path Browser for path management (File Set
Path).

36
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

Administration of User-created M-scripts and M-functions

For the administration of M-files the following recommendations are useful:


Do not put own created M-files in the original-MATLAB-Path because they
could be overwritten when you install an update of MATLAB.
User-created applications should use a special directory <user dir>. If
you want to use these functions in other directories you have to add this
path to the MATLAB-Path.
M-functions, which are used only in one function (primary function), should
be subfunctions. That means these subfunctions are declared in the same file
as the primary function.
Functions which are used only for a special application should be put in the
private-directory. The private-directory should created under the <user dir>.

The current directory

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

MATLAB Commands Windows UNIX


dir oder ls !dir !ls
type !type !cat
delete !del oder !erase !rm
mkdir !mkdir !mkdir
cd !chdir oder !cd !cd
pwd — !pwd
.. / .. oder ..\.. — !.. / ..
 

>> cd
ans =


c:\kurs\matlab 

37
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.2. MATLAB – PROGRAMS

Code Optimization for MATLAB

Notice following points:


Vectorization: Try to avoid loops. Many loops can be substituted using
array operations (.*,.\,./,.ˆ).
Example:

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

Preallocation: Matrices should be preallocated. Pre-allocating variables


creates a contigous memory space, e.g.:

y = zeros(1,100); % produces 1x100 matrix


A = ones(100) % produces 100x100 matrix

pack performs memory garbage collection.

38
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS

2.3 Programming Tools


2.3.1 The Editor / Debugger

For programming in MATLAB you can use any ASCII-text editor. In the MAT-
LAB environment the MATLAB-Editor/Debugger is available as default.

To start the editor from the MATLAB Command Window we type


 

>> edit 

for editing a new file.

Alternatively you can call the editor with a file name:


 

>> edit ematrix % opens ematrix.m

>> edit conti.dat % opens a file with the




% extension .dat 

39
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS

The MATLAB-Editor is a Debugging Tool as well, which can be activated dur-


ing the execution of MATLAB programs.

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

– Using breakpoints you can interrupt any program sequence to display


the current memory contents without changing anything in the func-
tions.
– In the popup–menue stack it is possible to switch between all workspace
levels.
– Activating the option Enable datatips in edit mode in File Preferences
Editor/Debugger Display enables to display the variable mem-
ory content in the debugger.
– Further debugger commands: dbclear, dbcont, dbdown, dbquit,
dbstack, dbstatus, dbstep, dbstop, dbtype, dbup.

41
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.3. PROGRAMMING TOOLS

2.3.3 Online-Help for User-created Functions and Directories


The header comments of user-created functions are automatically displayed by
the MATLAB-help function help, e.g.:
 

>> help nueberk


bk = nueberk(n,k)
computes the binomial coefficient:
n!/k!/(n-k)!


mit n! = prod(1:n) 

In MATLAB-directories exists a file contents.m, which lists detailed infor-


mation of the files in the directory. In user-created directories you have to create
the file contents.m on your own. If these directories are included in the MAT-
LAB path, you can then use the help function with
 

>> help c:\kurs\matlab

% Files for MATLAB training


% Version 2 (c) The MathWorks GmbH 2001
%
% MATLAB interactiv
%
% MATLAB Programming
% code_opt - example for code optimization
% ematrix - loop programming
% nueberk - subroutine example
.
.


. 

42
CHAPTER 2. MATLAB AS A PROGRAMMING LANGUAGE 2.4. EXERCISES FOR CHAPTER 2

2.4 Exercises for Chapter 2


Recommendation for all exercises:
Please write an M–file to solve the exercises. Use the MATLAB Editor/Debugger
(to be called with the command edit). Save your file with the extension ”.m”
and call it without extension at the MATLAB Command Window in order to
execute it.

1. Write an M–Script to solve the following problem:


Calculate the value of this function
      
   


 . Generate a vector  for it with a spacing of  


in the intervall 
and compute  .
 
 
 

Plot  versus  (plot(x,y)).


Create a structure with the elements:
polykoeff x dat y dat date name
The elements contain:
coefficients of vector  vector
   Today’s person
the polyno- date

 .
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

Return to the source directory


Usefull commands: eval, cat, pwd, cd, dir

   
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

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

45
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS

3.1 2-Dimensional Graphics


Example: harmonic signals
       mit   
 
3.1.1 Plot of Vectors and Matrices
 

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


>> hold off 

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

3.1.2 Labelling of Diagrams


 

>> title(’harmonische Signale’)


>> % adds text at the top
>> xlabel(’x(t)’)
>> % adds text beside the X-axis
>> ylabel(’u = sin(x(t))’)
>> % adds text beside the Y-axis
>> text(2.5,0,’u(t)’)
>> % adds the text
>> text(3.5,0,’u1(t)’)


>> % adds the text 

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

3.1.3 Colors, Markers, Line Types, Axes Range, Grids


 

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

We can assign plot properties to a line by using a third (string) parameter to


define color, marker and line type of the corresponding curve.
Symbol Color Symbol Marker Symbol Line Type
y yellow . dots - solid
m magenta o circle : dotted
c cyan x cross -. dash-dot
r red + plus sign -- dashed
g green * asterisk
b blue s square
w white d diamond
k black p pentagram
We can scale the axes using the command axis.
grid on and grid off are switches for the grid lines.
The function legend generates a legend.
More graphic commands: semilogx, semilogy, loglog, plotyy,
area, bar, barh, gplot, pie, stem.

49
CHAPTER 3. MATLAB GRAPHICS 3.1. 2-DIMENSIONAL GRAPHICS

3.1.4 Windows with several Graphics


 

>> grid off


>> subplot(2,2,1)
>> plot(x,u,’r-’)
>> axis(range)
>> subplot(2,2,2)
>> plot(x,sin(x+pi/4),’b--’)
>> axis(range)
>> subplot(2,2,3)
>> plot(x,sin(x+pi/2),’g:’)
>> axis(range)
>> subplot(2,2,4)
>> plot(x,sin(x+pi),’y-.’)


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

subplot(m,n,nr) breaks the figure window into an m by n matrix of


small axes, selects the nr axes for the current plot (counted rowwise).
Parameters of plot-command could be functions. The function output has
to be a vector or a matrix with a corresponding size.

50
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS

3.2 3-dimensional Graphics


Example: elliptical paraboloid
  
3.2.1 Line graphic

 
2

>> a=1; b=1;


1.5
>> x=-1:.1:1; y=x;
>> z=a*x.ˆ2+b*y.ˆ2; 1
z

>> plot3(x,y,z) 0.5

>> 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(x,y,z) % mit Vektoren


>> plot3(X,Y,Z) % mit Matrizen
>> plot3(x,y,z,s) % mit Linientyp


>> plot3(x1,y1,z1,s1,x2,y2,z2,s2,...) 

The labelling works analogously to the -dimensional case; additional com-




mand: zlabel
The axis scaling can be defined with

axis([xmin,xmax,ymin,ymax,zmin,zmax]).

The command grid produces grid lines.

51
CHAPTER 3. MATLAB GRAPHICS 3.2. 3-DIMENSIONAL GRAPHICS

3.2.2 Point of View


Using the command
view(azimuth,elevation)
changes the point of view of a 3-dimensional graphic.
z

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

azimuth = −37.5; elevation = 30 azimuth = 0; elevation = 0


2

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

azimuth = 90; elevation = 0 azimuth = 0; elevation = 90


2 1

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

3.2.3 Point of View of -dimensional Graphics


Creation of a -dimensional array
 

>> [X,Y] = meshgrid(x,y);




>> Z = a*X.ˆ2 + b*Y.ˆ2; 

-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

Selection of -D graphic commands: pcolor, meshc, meshz, surf,


surfc, surfl, image, bar3, bar3h, pie3, stem3, quiver3, rib-
bon, rotate3d.

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.

red green blue Farbe



 
 
 black
  white
 
 yellow

  magenta


  cyan
grey

The command colormap enables you to choose the color distribution of


a -D graphic. The command colormap(jet) sets the current figure’s
colormap to the root’s default. Other color distributions are hsv, hot,
cool, pink, gray, copper, flag, autumn, colorcube, lines,
spring, summer, winter.
The maximum value of a graphic correspond to the first color of the col-
ormap. The minimum value correspond to the last color of the colormap.
The values in between correspond to the colors between the first and the
last color of the colormap.
Background color and the color of the coordinate system and the labels
can be changed by the command colordef. Standard color is col-
ordef(’white’), possible are colordef(’black’) or the MAT-
LAB 4 setting colordef(’none’).

55
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

3.3 Handle Graphics


3.3.1 Object-Hierarchy

root

figure

axes uicontextmenu uicontrol uimenu

image light line patch rectangle surface text

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

3.3.2 Handle the Objects


Objects can be generated by functions, e.g. figure opens a window, axes
creates a coordinate system, line draws a line etc.
With the object handles you can identify and handle the objects. The ob-
ject handles are numbers which MATLAB uses for managing the objects.
– The root-object has the identificationnumber (object handle)  .
– Every figure-object is assigned with an ascending integer number,
e.g.,
 

>> fh=figure
fh =


1 

– Any other objects is assigned a real number, e.g.,


 

>> ah=axes
ah =


1.00378 

– The handling of objects are supported by the functions


 

>> gcf % get current figure


ans =
1

>> gca % get current axes


ans =


1.00378, 

which denote the current figure and axes object, respectively.

57
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

3.3.3 Properties of Objects


Every different object has several object properties, which have certain de-
fault values. To generate individual graphics you can change the object
properties.
The command get displays the current object properties, e.g.,
 

>> get(fh) % get(gcf) is doing the same 

returns a list of property/value pairs:

58
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

 

Alphamap = [ (1 by 64) double array]


BackingStore = on
CloseRequestFcn = closereq
Color = [0.8 0.8 0.8]
Colormap = [ (64 by 3) double array]
CurrentAxes = [99.0021]
CurrentCharacter =
CurrentObject = []
CurrentPoint = [0 0]
Dithermap = [ (64 by 3) double array]
DithermapMode = manual
DoubleBuffer = off
FileName =
FixedColors = [ (10 by 3) double array]
IntegerHandle = on
InvertHardcopy = on
KeyPressFcn =
MenuBar = figure
MinColormap = [64]
Name =
NextPlot = add
NumberTitle = on
PaperUnits = inches
PaperOrientation = portrait
PaperPosition = [0.25 2.5 8 6]
PaperPositionMode = manual
PaperSize = [8.5 11]
PaperType = usletter
Pointer = arrow
PointerShapeCData = [ (16 by 16) double array]
PointerShapeHotSpot = [1 1]
Position = [296 354 560 420]
Renderer = painters
RendererMode = auto


... 

59
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

The function set changes the object properties.


 

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

3.3.4 Example Paraboloid


 

>> [X,Y,Z]=parabol(1,1);


>> mesh(X,Y,Z) 

The displayed graphic contains objects:


1 figure
1 axes
1 surface

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:
 

>> clf %clear figure


>> axes(’Position’,[.3 .3 .4 .4]);


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

recreates the saved graphic.


The menu File Export allows one to save a MATLAB graphic in various
graphic formats.

The command print can also be used for saving and exporting graphics.

64
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

3.3.5 Properties Changing with the Graphical Interface


MATLAB has graphical user interface design environment tools that allow Han-
dle Graphics objects to be manipulated interactively. The command guide
opens the control panel. Part of the control panel is an Editor which can change
object properties. The Editor can be called from MATLAB workspace with the
command
 

>> propedit 

65
CHAPTER 3. MATLAB GRAPHICS 3.3. HANDLE GRAPHICS

In addition every figure–object has a plot editor.


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.

Many properties can be changed by the shortcut–menu (right-button click of the


mouse) or using the menu Tools. For example, with the shortcut–menu you can
create a legend for an axes–object.

66
CHAPTER 3. MATLAB GRAPHICS 3.4. EXERCISES FOR CHAPTER 3

3.4 Exercises for Chapter 3


1. Practice the handling of the plot-function:
Generate any signal, e.g. use the sin-function.
Plot a signal.
Plot several signals in one diagram.
Title the diagram, label the axis and the curve, and generate a legend.
Change colors, types of lines and axis coordinates of the diagram.
Create a window with several graphics and label the subplots.
Prove the functioning of the plot editor with the example.
Test the possiblities to save graphics.
2. With the command
 

>> [X,Y,Z] = parabol(a,b)




>> mesh(X,Y,Z) 

you can generate the paraboloid as a mesh graphic.


Try also the graphic commands meshc, meshz, surf, surfc,
surfl. Change the colormap with the commands colormap and
colordef.
Change several properties of the graphic, e.g. name, position, color,
scaling of the axis etc., with the command set.
Enter the command propedit and change some properties of the
graphic through the use of the graphical interface.

67
CHAPTER 3. MATLAB GRAPHICS 3.4. EXERCISES FOR CHAPTER 3

3. Presentation of measuring data


Read a file of measuring data(e.g. conti.dat using the M–script conti change.m
Calculate the number of measured vectors in the file.
Formulate a program to display each measured vector in one axes–
object. All axes–objects should be positioned in one figure–object.
(E.g. ”two side by side”)
Create the labelling of each channel automatically. The label should be
called channel number , or the channel name of the file header.


68
Chapter 4

MATLAB Data Interfaces

Inhaltsverzeichnis

4.1 General Data Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70


4.1.1 Open and Close Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
4.1.2 The MATLAB Data Format (.mat) . . . . . . . . . . . . . . . . . . . . 70
4.1.3 Processing of ASCII-Files . . . . . . . . . . . . . . . . . . . . . . . . 71
4.1.4 Processing of Binary Data . . . . . . . . . . . . . . . . . . . . . . . . 74
4.1.5 MATLAB Import Wizard . . . . . . . . . . . . . . . . . . . . . . . . . 75
4.2 Exercise for Chapter 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

69
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT

4.1 General Data Format


4.1.1 Open and Close Files
You can open and close any type of file with the commands fopen and fclose.
 

>> [fid, meldung]=fopen(myfile.dat, ac-




cess_mode) 

The functions returns a file-ident-number and a system dependent error message


if the open is not successful (see also example conti_change.m in section
4.1.3).
For the second input parameter you can choose between the following access
modes:
’r’ read (default)
’w’ write
’a’ append
 

>> fclose(’all’) 

closes all open files.


With further MATLAB-I/O-functions you can administrate binary-, ascii- or for-
mated text-files.
The MATLAB-I/O-functions are based on the ANSI C standard. But there are
some minor differences. The command fscanf for example returns a matrix as
output argument.

4.1.2 The MATLAB Data Format (.mat)


MAT-files are MATLAB-data-files, which are saved in a MATLABspecific
binaryformat. This format is platform independent.
 

>> save mydata 

saves all existing variables of the workspace in the file mydata.mat,


 

>> save mysuperdata X Y Z 

70
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT

saves the matrices X, Y, Z in the in the file mysuperdata.mat


 

>> load mysuperdata X 

loads only the matrix X in the in the workspace and


 

>> S = load(’mydata’) 

loads the data of the File mydata.mat into the structure S.

4.1.3 Processing of ASCII-Files


With the command save you can also save data in ascii–format.
 

>> x=[1:10]’;


>> save mytextdata.txt x -ascii 

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.
 

>> load mytextdata.txt -ascii 

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.
 

>> A = dlmread(’my_userdata.dat’, ’;’)


A =
1.0e+003 *
0 2.1637 1.0303 0.8515 0.8544


0 2.2142 1.0178 0.8421 0.8440 

71
CHAPTER 4. MATLAB DATA INTERFACES 4.1. GENERAL DATA FORMAT

It is important that you use the decimal point (not a comma).


The first column is interpreted by MATLAB as a zero column vector because of
the semicolon who is put in front.
Price quotations of the type 440.000,00 provoke error messages (because of
the comma) or wrong interpretation (without the comma).
On the other hand, you can save a MATLAB-matrix in a formatted ascii-format
with the function dlmwrite:
 

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

in which all none numerical characters like the


" "
and the header line are interpreted as errors.

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.
 

>> save myfname.txt data -ascii -double -tabs 

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

4.1.4 Processing of Binary Data


Binary data can be accessed by the functions fopen, fclose (with the access
mode ’rb’ or ’wb’ under MS Windows). With fread and fwrite you can
read or manipulate the data. For the correct reading of a binary file you have to
know the saved data type.
Example: read bindat.m

% Read binary data


fid = fopen(’yourdata.bin’,’rb’);
A = fread(fid, [100 2], ’double’);
r_status = fclose(fid);
% Write binary data
other_fid = fopen(’newdata.bin’,’wb’);
count = fwrite(other_fid, 1:10,’int32’);
w_status = fclose(other_fid);

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

4.1.5 MATLAB Import Wizard


The MATLAB Import Wizard is a GUI for easy input of text and binary data.

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.

In the following step the data is read.

75
CHAPTER 4. MATLAB DATA INTERFACES 4.2. EXERCISE FOR CHAPTER 4

4.2 Exercise for Chapter 4


1. You should analyse the data in the file conti.dat. Change the file conti.dat
with an editor: Load the data, create a time vector and plot several curves.
Check the function conti change2. Expand the function to create a
MATLAB readable time vector; replace the time vector and save the data
in a file (Note: Use the functions fopen, fprintf and fclose).
2. Save the data from the file conti.dat as a MATLAB–compatible ascii
file and binary file. Compare the reading time of both files with the help of
the commands tic,toc.
3. Try out the MATLAB Import Wizard.

76
Chapter 5

Modelling in SIMULINK

Inhaltsverzeichnis

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

77
CHAPTER 5. MODELLING IN SIMULINK 5.1. MODEL OF AN ANALOG VOLTMETER

5.1 Model of an analog voltmeter


5.1.1 Mechanical and electrical model


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

5.1.3 Block diagrams




 
 
  




 

 






A block diagram displays graphically the correspondence of signals.


Signals indicate the value of a physical quantity; in block diagrams signals
they are shown as arrows.
Every block of a diagram is a weighted operation for changing signals:
– Signal branches are indicated by branches of lines.
– Signals can be connected with e.g., sums or products,
– and modified by transfer blocks.
The dynamical behaviour of the system can be identified by the behaviour
of the transfer blocks. Therefore, they are labelled by their characteristic
step response. In addition, charakteristic parameters are given.

79
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING

5.2 Grafical editing of block diagrams


5.2.1 To start SIMULINK
SIMULINK is started using the corresponding icon or from the MATLAB Com-
mand Window with the commands
 

>> simulink 

and
 

>> simulink3 

respectively. simulink opens the ”‘Block Library Browser”’, containing all


blocks as leafs of a tree whereas simulink3 opens a new window with all
block libraries as blocks.

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

5.2.2 Editing block diagrams


For our example we need the blocks Sum, Integrator and Gain). These blocks
are in the libraries Continuous and Math.

A double click with the left mouse button on a symbol opens the library or

a right click on the correponding branch of the library browser.

82
CHAPTER 5. MODELLING IN SIMULINK 5.2. GRAFICAL EDITING

There exist several possibilities to copy the needed blocks to the work
space:

– Single blocks by simple Drag & Drop.


– Multiple blocks by marking several blocks (see below) followed by a
single Drag & Drop,
– or by using the menues Edit Copy and Edit Paste in library and
work space.

To mark a block, use either


– a mouse click for a single block,
– mouse clicks and pressing the Shift-key for multiple blocks,
– or using a rectangle by positioning the mouse in the library window,
pressing the left button and draging the mouse.

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.

Blocks may be moved within the work space using Drag&Drop.


A copy of the same block is generated by Drag&Drop using the right button.
A marked block can be rotated using the menues Format Flip Block or
Format Rotate Block.
To connect to blocks mark the first block, press the ctrl-key a click on the
second block. Alternatively, move the mouse to the output port of the first
block, press the left button and release it at the input port of the second
block.
For branches position the mouse on an existing signal and press the right
button, move the mouse to the desired in– or output port.
Blocks with only one input and output port may be dropped into an existing
line.

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

5.2.3 Properties of blocks and signals


Prior to a simulation we have to give the correct parameters to all blocks, e.g.,
factors for the gain blocks or signs for the sum blocks.

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

All signals may be named.

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

5.2.4 Some cosmetic changes

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

5.2.5 Starting a Simulation


The block diagram is now complete, so we can start a simulation. Neverthe-
less, we should change the integration interval using Simulation Parameters

Solver. To capture the interesting part of our simulation set Stop time to .

A simulation can be started using Simulation Start or Ctrl-T or using


the startbutton in the icon bar.
The menu Simulation Parameters Solver controls the simulation
parameters.

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

5.3 MATLAB interfaces


5.3.1 Save block diagram
The block diagram can be saved using the menu File Save As ...

The diagram is saved as a mdl-file. A closed model can be reconstructed by


calling the file name (without extension) from the MATLAB command prompt:
 

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

5.3.2 Using the MATLAB workspace


Block parameters need not to be numbers but may also be variables, e.g.,

The variable J must be a MATLAB workspace variable at simulation start. One


possibility is to store all variables in a file.
 

>> J = 0.64e-6;
>> R = 2e3;
>> C_F = 16e-6;
>> K_I = 8e-2;
>> K_phi = 8e-2;


>> save example_data %write example_data.mat 

The data must be read before starting the simulation. They are evaluated at each
simulation start. All SIMULINK variables reside in the MATLAB workspace.
 

>> load example_data %read example_data.mat




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

J = 0.64e-6; % Inertia [kg*mˆ2/rad]


R = 2e3; % Resistance [Ohm]
C_F = 16e-6; % Spring const. [N*m/rad]
K_I = 8e-2; % Induction [V*s/rad]
K_phi = 8e-2; % Current const. [N*m/A]

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

The set param command is interpreted as follows:


– The first parameter specifies the object to be modified, either a block
diagram or a single block.
– All other parameters are given as couples, first the property, then the
new value.

Using the option Callback tracing from the menu File Preferences Simulink
displays all executed callbacks in the command window.

Some common used Callbacks of models or blocks are:


– PostLoadFcn: After loading a block diagram
– CloseFcn: Before closing a block diagram
– InitFcn: At initialization of a model (before each simulation)
– StopFcn: After finishing a simulation
– OpenFcn: When a block is opened (double click)

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.

Blockschaltbild eines Spannungsmessinstrumentes

K_I alpha
u_I dalpha Winkel
K_I

1/R K_phi m_phi


1/J ddalpha 1 1 alpha
u i s s

Step 1/R K_phi 1/J

Mux

m_F
t C_F

Zeit C_F

The blocks Zeit (time) and Winkel(angle) are To Workspace blocks


from the library Sinks.
The simulation time is generated by the Clock from the library Sources.
The block Mux (Multiplexer) from the library Signals& Systems concate-
nates angle and angle velocity as columns of a matrix.

Alternatively, data can be stored using the menu Simulation Simulation


parameters Workspace I/O. You should choose the Array format.

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


Grand total is 161 elements using 1288 bytes 

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.
 

>> save mysave_data


>> plot(t,alpha)


>> title(’Step response of voltmeter’) 

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

5.4 Excercises for chapter 5


1. Modify the block diagram of the voltmeter as shown in this chapter. Do
some simulations and change some of the simulation parameters.

     
   
2. Let

      
 mit



be a given second order ODE.


(a) Construct a block diagram containing only a source, a sink and blocks
of type Gain, Integrator and Sum.

  
      
    
(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

Initial condition for the integrator:   

98
Chapter 6

Basic simulation techniques

Inhaltsverzeichnis

6.1 Simulation parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100


6.1.1 Parameter studies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
6.2 Blockoriented simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
6.2.1 Execution order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
6.2.2 Algebraic loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
6.2.3 Discrete and continous blocks . . . . . . . . . . . . . . . . . . . . . . 110
6.2.4 Hierarchical models . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
6.2.5 Complex simulation models . . . . . . . . . . . . . . . . . . . . . . . 113
6.3 Exercises for chapter 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

99
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS

6.1 Simulation parameters and parameter studies


The simulation parameters can be modified using the menu Simulation
Simulation parameters

Start time and Stop time define the interval of integration.


The item Solver options define:
– whether to compute with or without step size control,
– the integration algorithm,
– the maximal and minimal step size, the initial step size as well as error
tolerances.
With Output options one can define a time axis for the output. If e.g., the
step size control makes large steps, such that the graphics exhibits corner,
increasing the Refine factor produces additional knots. Note, that these
additional output points are not computed using a smaller step size but by
Spline interpolation.

100
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS

6.1.1 Parameter studies for the Van der Pol equation


(vdp bsp.mdl)
       
van der Pol Differentialgleichung
x x

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
 

>> options=simset(options, ’InitialState’, [1 1]);


>> [t,y]=sim(’vdp_bsp’, 10, options);


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

% Simulation with default values:


% ...with (explicit) Euler and rel. error tol. 10ˆ-3
options=simset(options,...
’Solver’,’ode1’,... % use explicit Euler solver
’RelTol’,1e-3) % with rel. tolerance 10ˆ(-3)
[te,xe]=sim(’vdp_bsp’,T,options);

% ...with Runge-Kutta 2,3 and relative error tolerance 10ˆ(-3)


options=simset(options,...
’Solver’,’ode23’,... % use Runge-Kutta 2,3 solver
’RelTol’,1e-3) % with rel. tolerance 10ˆ(-3)
[trk,xrk]=sim(’vdp_bsp’,T,options);

% Show results
%...

Vergleich Euler (:) und Runge−Kutta 2,3 (.−)


mit Standardeinstellungen
3

1
Zustand x

−1

−2

−3
0 1 2 3 4 5 6 7 8 9 10
Zeit [s]

 

with default values:


Steps | max. Step | error | max. error
euler 51 0.20000 0.02839 3.06124


rk23 65 0.20000 0.00006 0.00904 

103
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS

% Simulation with other parameters:


% ...with (explicit) Euler and small fixed step size
options=simset(options,...
’Solver’,’ode1’,...
’FixedStep’,1e-2);
[te,xe]=sim(’vdp_bsp’,T,options);

% ...with Runge-Kutta 2,3, large step size


% ...and large relative error tolerance
options=simset(options,...
’Solver’,’ode23’,...
’MaxStep’,10,...
’InitialStep’,1,...
’RelTol’,1e-1);
[trk,xrk]=sim(’vdp_bsp’,T,options);

% Show results
%...

Vergleich Euler (:) und Runge−Kutta 2,3 (.−)


veraenderte Einstellungen
3

1
Zustand x

−1

−2

−3
0 1 2 3 4 5 6 7 8 9 10
Zeit [s]

 

with other Parameters


Steps | max. Step | error | max. error
euler 1001 0.01000 0.00120 0.15188


rk23 14 1.51256 0.00806 0.99863 

104
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS

Switching elements (Discontinuities, hff.mdl)

SIMULINK is able to detect ”‘Zero crossings”’ resulting in discontinuities of


the solution.
Sum

Step Input Relay

Scope

Mux

PT_1

1
Outport

We compare the results of a simulation with and without detection of changes of


states (hff sim.m). We use an analytic solution as reference solution.
% analytic solution
[t,y] = hff_analytic;
plot(t,y,’k’)

% numerical solution
options = simget(’hff’); T = 25;

% ... mit default parameters


[trk,xrk,yrk] = sim(’hff’,T,options);
hold on, plot(trk,yrk,’b-o’), hold off

% ... without zero crossing detection


options = simset(options,’ZeroCross’,’off’);
[trk,xrk,yrk] = sim(’hff’,T,options);
hold on, plot(trk,yrk,’r:x’), hold off

105
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.1. SIMULATION PARAMETERS

Vergleich mit und ohne Detektion von Zustandsänderungen


1

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

6.2 Blockoriented simulation


The flexible procedure of how SIMULINK treats models resists on block ori-
ented simulation techniques. Block oriented means, that a model is not simulated
in total but SIMULINK treats all blocks of a model sequentially.

6.2.1 Execution order (loop 1.mdl)


Block_1

Step Input Scope


Block_2

Block_4 Block_3

There is a difference between blocks with or without direct feedthrough:


– All blocks that only depend on the history, e.g., integrators, delay blocks
or dead zones have no direct feedthrough.
– With direct feedthrough are all blocks, where the output depends on its
current input, e.g., gain blocks and static nonlinear blocks.
The knowledge of this property is nessessary to compute the execution or-
der:
– The simulation can not be started using block Block 1 since the sec-
ond input of the sum is not known at simulation start.
– The  -element Block 2 has no direct feedthrough and therefore it
is the first block of the execution order.
– After Block 2 the blocks Block 3, Block 4, and finally Block 1
can be computed.

107
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.2. BLOCKORIENTED SIMULATION

6.2.2 Algebraic loops (loop 2.mdl)


In contrast to the last model the block Block 2* has direct feedthrough.
Block_1

Step Input Scope


Block_2*

Block_4 Block_3

If a closed loop consists only of blocks with direct feedthrough, it is called


an algebraic loop.
 

Warning: Block diagram ’loop_2’ contains 1 algebraic loop


Found algebraic loop containing block(s):
’loop_2/Block_2*’
’loop_2/Block_3’
’loop_2/Block_4’ (discontinuity)
’loop_2/Block_1’ (algebraic variable)
Warning: Discontinuities detected within
algebraic loop(s), may have


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

% ... Model without algebraic loop


tic, [t_wo,x_wo] = sim(’loop_1’,tfinal,options);
time_wo = toc;

% ... Modell with algebraic loop


tic, [t_w,x_w] = sim(’loop_2’,tfinal,options);
time_w = toc;

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

6.2.3 Systems with discrete and continous blocks


(diskr conti1.mdl,diskr conti2.mdl, diskr conti3.mdl)
2 1
Out2 Out1

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

6.2.4 Hierarchical models (example sub.mdl)


Block oriented simulation techniques can be designed much more concise using
hierarchies of arbitrary depth.

Blockschaltbild eines Spannungsmessinstrumentes


mit Subsytemen

u_I
K_I dalpha

alpha

u_I m_phi Winkel


i K_phi
i m_phi dalpha
u
u
Maschenregel m_F 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

The context menu Block Parameters can be used to define a subsystem as


atomic, i.e., for defining the execution order it is treated as a single block.
The blocks Inport and Outport are generated automatically and define the
interface to the superior model.
It is good practice to give reasonable names for the port to increase the
readability. The names are also displayed on the mask of the subsystem
block.

6.2.5 Complex simulation models


The library Subsystem contains predefined subsystems with minimal configura-
tion, i.e., each with one inport and one outport as well as blocks for conditional
execution.

Configurable Subsystem: The user


may choose a subsystem from a library
Enable, Trigger: Conditional execu-
tion
Function Call Generator: Triggered
execution of a subsystem
for, while: Repeated call of a subsys-
tem
if, switch, case: Standard C- or
MATLAB-similar control logic (Bsp.
ifaction.mdl).

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

Step Input Relay


Scope
Mux

PT_1

Hit
Crossing OR [Enable]
Goto
[Enable]
Hit
From
Crossing1 Logical
Operator
[Visualization] In
From1 [Visualization]
Subsystem
Goto1

When a Hit Crossing block detects a discontinuities its output is set to ,



otherwise to  .
Using the logical OR (Logical Operator from Math) both results are com-
bined.
The blocks Goto and From route the detected times to the subsystem with-
out a physical connection.

Due to the Enable block the Sub-


system is only activated if a posi-
tive signal (  ) is given.


Times and values of the disconti-


nuities are displayed (Display) and
saved (To Workspace).

115
CHAPTER 6. BASIC SIMULATION TECHNIQUES 6.3. EXERCISES FOR CHAPTER 6

6.3 Exercises for chapter 6


1. Open the model vdp bsp.mdl. Set the gain factor mu to

   . This
leads to a stiff system. Compute the execution time for the simulation with
different solvers. Write a m–file for the command driven simulation of
SIMULINK-models. Use the file vdp sim.m as a starting point.
Useful commands: tic,toc,sim,simget,simset
2. Use the block diagram of the voltmeter from section 5.2 (example.mdl)
to build a hierarchical block diagram as shown in the example of section
6.2. Verify your new system by comparing the results of both systems.
3. Open the model hff new.mdl and start a simulation. Think about the
results and the working principals.
Modify the system such that also the Relay outport signal is transferred to
the subystem; in the subsystem display and save also this signal.
4. Try the merge block: build a SIMULINK model containing two enabled
subsystems. Generate a signal such that either System1 or System2 is ex-
ecuted but not at the same time. Visualize the last updated signal using a
merge block.
The two subsystems:

1 1 1 1 5 1
Enable In1 Out1 Enable In1 Out1
Gain Gain
SubSystem1 SubSystem2

116
Chapter 7

Advanced techniques

Inhaltsverzeichnis

7.1 Masked subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118


7.1.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
7.2 DEE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
7.2.1 Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
7.2.2 Differential Equation Editor (DEE) . . . . . . . . . . . . . . . . . . . 125
7.3 S-functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
7.3.1 S-functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
7.3.2 Type of S-functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
7.3.3 Integration in a block diagram . . . . . . . . . . . . . . . . . . . . . . 132
7.3.4 Comparison of different realizations . . . . . . . . . . . . . . . . . . 133
7.3.5 MaskS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
7.4 Creating new libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
7.5 Exercises for chapter 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

117
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS

7.1 Masked subsystems


It is possible in SIMULINK to generate your own blocks or even complete new
libraries, e.g., a self-provided library with standard blocks of control design can
be opened with the command
 

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

Edit Mask Subsystem Initialization:


Mask type:
– Enter an arbitrary block identifier.
Prompt, Variable:
– We have to specify the variables to be used in the block Transfer Func-
tion. The variables are entered in the field Variable, the corresponding
text in the field Prompt.
– A new dialog box with input fields is now defined. The number of
fields depends on the number of variables, the field names are given by
the entries of Prompt.
Initialization commands:
– Definition of commands which are used within the block or for dis-
playing the block symbol.
– All MATLAB commands may be used.

120
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS

Edit Mask Subsystem Icon:


Drawing commands:
– Commands for displaying the block icon have to be entered.
– The command plot is only partially available: no line types or colours
are allowd, no matrix parameters.
– To display text use the MATLAB commands disp, fprintf and
text.
– The command image can be used to display graphics as icon.

121
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS

Edit Mask Subsystem Documentation:


Block description:
– Short comment on the functionality of the block.
– This field is displayed in the new block mask.
Block Help
– a detailed help text can be entered, that is displayed when clicking the
help pushbutton in the mask dialog.
– The block help uses the HTML format, so usual HTML commands
may be used.

122
CHAPTER 7. ADVANCED TECHNIQUES 7.1. MASKED SUBSYSTEMS

This new block can now be used in arbitrary simulations.

It is completely functional as soon as reasonable entries for the variables ”Uber-


tragungsbeiwert and Zeitkonstante are given.

123
CHAPTER 7. ADVANCED TECHNIQUES 7.2. DEE

7.2 Differential Equation Editor


7.2.1 Example
For our voltmeter from chapter 5 we want to generate a new block, since it is
used in large plants many times and the complete plant is to be simulated. Since
it will be a complex simulation, the execution time is of importance.
Analytic model:
 
               
  
oder
           
 
 
 


   

  


    
    

Block diagram sfun bd.mdl

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

7.2.2 Differential Equation Editor (DEE)


If we have for the model a system of (possibly non linear) differential equations,
we can make a SIMULINK model using an editor. This editor is integrated in a
SIMULINK block and can be found using the MATLAB command
 

>> dee 

from the command prompt.

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.

In fact, the differential equation editor automatically generates a block diagram


from our system of equations. Using the menu Edit Look Under Mask we
can have a look at the diagram. It is fairly unstructured but works nevertheless.

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

7.3 SIMULINK system funktions (S-functions)


7.3.1 S-functions
Internally, SIMULINK saves every model as a so-called ”‘S-function”’ (system
function), which works as every other MATLAB function. It has a prescribed
parameter structure.

[sizes, x0, str, ts] = model(t, x, u, flag);

Here we need to know something about the simulation technique used by SIMULINK.

Start the simulation


Initialize the model
the current time is computed
the output equations are computed
compute the discrete states
compute the continous states
the numerical integration possibly
needs further evaluations
stop the simulation if end of time inter-
val reached
begin next time step at the end of the
numerical integration process for this
time interval

127
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS

The parameter flag defines what the S-function is supposed to compute.

flag Function Call


0 Initialization once at the beginning
1 Compute the continous states in every time step
2 Compute the discrete states in every time step
3 Compute output values in every time step
9 Finishing tasks after the simulation stops

 

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


1 % Num. of sample times (min. 1) 

7.3.2 Type of S-functions


Block diagrams

All block diagrams generated with SIMULINK are internally managed as S-


functions, see, e.g., sfun bd, sfun dee.

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

function [sys,x0,str,ts] = ...


m_sfun(t,x,u,flag,C_F,K_phi,K_I,R,J)
...
sizes.NumContStates = 2;
sizes.NumDiscStates = 0;
sizes.NumOutputs = 1;
sizes.NumInputs = 1;
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;
...
ts = [0 0];
...
function sys = ...
mdlDerivatives(t,x,u,C_F,K_phi,K_I,R,J)
sys = [0 1;-C_F/J -K_phi*K_I/R/J]*x ...
+ [0;K_phi/R/J]*u;
...
function sys = mdlOutputs(t,x,u)
sys = [1 0]*x;

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

>> mex mex_sfun.c 

MEX-files can be used to


– install new blocks in SIMULINK,
– to incorporate existing C or Fortran sources,
– to reduce the complexity of large models and
– to implement models as mathematical equations.
The command sfundemos gives some examples.

130
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS

S-function Builder

To simplify the programming of S-functions in C, one can use the block S-


Function Builder from the library Functions&Tables. After copying the block
into an empty model it consists of a graphical user interface where parameter can
be specified and fields for the corresponding C-code are given (sfb sfun.mdl).

131
CHAPTER 7. ADVANCED TECHNIQUES 7.3. S-FUNCTIONS

7.3.3 Integration in a block diagram


In the SIMULINK library Functions&Tables the block S-Function for integra-
tion of S-functions can be found.

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

7.3.4 Comparison of different realizations (sfun sim.m)


Simulation results
load example_data
t=[0:.1:5]’;
u=[t,ones(length(t),1)];
options=simget(’sfun_bd’);
% SIMULINK block diagram
[t,x,y]=sim(’sfun_bd’,5,options,u);
% Block diagram generated with DEE
[tdee,xdee,ydee]=sim(’sfun_dee’,5,options,u);
% Block diagram using a M-file S-function
[tm,xm,ym]=sim(’sfun_m’,5,options,u);
% Block diagram using a C-file S-function
[tmex,xmex,ymex]=sim(’sfun_mex’,5,options,u);

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

Comparison of execution times

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

7.4 Creating new libraries


SIMULINK makes a difference between models for simulations and models that
serve as libraries. A new library is created using the menu File New Library.
The new library can be used after copying the corresponding blocks into the
workspace and saving as a mdl-file. Later, this library can be modified or ex-
tended.

Libraries are indicated by Library: at the beginning of the window title.


After the first save, libraries are locked, i.e., before a modification can be
done, one has to unlock the library using, e.g., from the menu Edit the
option Unlock Library.
Changes to library blocks are automatically updated in all blocks, which
contain this block.
Since the linking of blocks to libraries is done by their name, one should
never rename library blocks.

136
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES

Libraries may also be created hierarchically.

First, a new library is created using File New Library.


Then, empty subsystems are copied from the library Subsystems, giving
them new names.
Last, the subsystems are linked to the library using callbacks, either com-
mand line driven,
 

>> set_param(’mymainlib/Messfuehler’,...


’OpenFcn’,’fuehler’) 

or using the menu Edit Block Properties

137
CHAPTER 7. ADVANCED TECHNIQUES 7.4. CREATING NEW LIBRARIES

An icon can, if desired, be generated by the command disp or with an


image using the menu Edit Edit Mask.

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

function blkStruct = slblocks

blkStruct.MaskDisplay = ’disp(’’Eigene Blöcke’’)’;


blkStruct.OpenFcn = ’mymainlib’;
blkStruct.Name = sprintf(’Eigene Bibliotheken’);

Browser(1).Library = ’mymainlib’;
Browser(1).Name = sprintf(’Eigene Bibliotheken’);
blkStruct.Browser = Browser;

% End of slblocks

– The first 3 calls cause the library mymainlib to be included in the


superior library Blocksets and Toolboxes.
– The following assignments have the effectuate the inclusion in the
Simulink Library Browser.

139
CHAPTER 7. ADVANCED TECHNIQUES 7.5. EXERCISES FOR CHAPTER 7

7.5 Exercises for chapter 7


1. Generate a new block with the step response as block symbol for a first
 
      
order all-pass filter ( ). The step response of the -filter reads


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

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

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.

A single STATEFLOW block is a state chart.


The entity of all state charts within a SIMULINK model is the STATEFLOW-
Statemachine.
A new SIMULINK modell with a STATEFLOW block is opened from the MATLAB-
Command Window as follows:
 

>> sfnew 

Optional with the file name as parameter:


 

>> sfnew demo 

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)

The STATEFLOW Block

The STATEFLOW block is a masked subsystem.


The STATEFLOW editor is opened by double-clicking on the chart block.

143
CHAPTER 8. STATEFLOW 8.1. BASICS

8.1.1 STATEFLOW Objects


States

A state has a binary behavior.


It is either active or inactive.

States are hierarchically organized.


There are Superstates, which contain . Substates.
The number of levels is unlimited.

B C

– A is superstate (Parent of A.B and A.C),


– A.B and A.C are substates (Children of A).

States within one hierarchie level are related


– via exclusive OR (XOR, solid line),
which means only one substate is active if the superstate becomes ac-
tive,
– or via logical AND (dashed line)
which means both substates become active (parallel states).

B 1 C 2

144
CHAPTER 8. STATEFLOW 8.1. BASICS

A State has got a label, which is freely editable.


There may be actions associated with the state.

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

Transitions link states.


They represent the switching from source state to destination state.

On

Off

Junctions split transitions into segments and/or collect them.

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

An initial state has to be defined using the Default Transition.

[Condition]
On

Off

– In the example above the state Off is chosen as the initial state.

State charts can have a memory if they hold a History Junction.

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

There is a special notation for labeling transitions :

event [condition] condition action /transition action




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

event [condition] condition action /transition action




Events trigger transitions. A Condition action is executed, if it’s


They have user defined condition is true. They are inclosed in
names. braces ( ).


Conditions are logical ex- A Transition action is executed, if the


pressions, e.g. [x==0] transition switches.
(MATLAB-Notation). It begins with a slash (/).
They are bracketed ([]).

Mealy and Moore Finite State Machines

There are two model types for finite state machines:

Mealy: All actions are associated with transitions.


Moore: All actions are associated with states.

Both concepts are a subset of STATEFLOW models.


There are the following equivalents in both model types for actions:

Moore Mealy
entry transition action of the transition to the destination state
 state
 

 

exit condition action of the transition from the source state


state 
 

 

during inner transition   

149
CHAPTER 8. STATEFLOW 8.1. BASICS

Events

STATEFLOW models are event controlled. Whenever an event occures, a


STATEFLOW block is executed.
As long as no event occurs the STATEFLOW chart is asleep and does not
influence the SIMULINK model.

On
switch_off

Off

switch_on

External events are sent as input from SIMULINK.

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

8.1.2 The STATEFLOW Editor


An Example

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.

We place a default transition on the frame of the state Off.


Transitons are inserted by clicking on the edge of a source state, holding
down the mouse button while going to the destination state and letting it go
at the edge of it.
Start and destination point of a transition can be shifted by clicking.
We edit a transition by clicking on it. A click on an empty spot within the
editor stops the edit mode.
Transition labels can be shifted by clicking on them. They still remain
associated with the transition.

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

The Communication with SIMULINK

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.

At the dialog of Add Event Input from SIMULINK we define the


events light on and light off. For the event light on we choose
the tigger option Rising Edge, for light off Falling Edge. fan on and
fan off are local events (i.e. they are only used within the STATEFLOW
chart, but not exported to SIMULINK).

154
CHAPTER 8. STATEFLOW 8.1. BASICS

The variables count and run defined as Data, Output to SIMULINK


(menu Add Data).

– 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!

Finishes the simulation,


current
time if input signal ~= 0
simulation time
Clock
stop STOP

desired Stop Simulation


5 end
simulation stop time
in sec
Tsim
Chart

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

8.2 Some items of STATEFLOW


8.2.1 Hierarchy by means of Subcharts
Subcharts are charts within charts which contain komplex submodels.
Subcharts function like Superstates with hidden contents.

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

8.2.2 Graphical Functions


The use of graphical functions in Charts has been possible since the STATEFLOW-
version 4.0.

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

8.2.3 Temporal Logic


Temporal logic operators are Boolean operators that operate on recurrence counts
of Stateflow events.
This way it is easier to realize Timer, Counter etc. without the use of additional
data.

These are the temporal logic operators in STATEFLOW:


after(N,BaseEvent)
before(N,BaseEvent)
at(N,BaseEvent)
every(N,BaseEvent)

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;

The operators can be used in


event notation: after(10,takt)
as well as in
condition notation: [after(10,takt)].

160
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS

8.3 STATEFLOW Tools


8.3.1 The Explorer
The STATEFLOW Explorer manages all non graphical objects in charts, i.e. of
events and data.
It is opened with Tools Explore.

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

8.3.2 The Editor – Additional Properties


Apart from editing charts the editor serves for specifying object properties. A
click with the right mouse button on the graphical object opens a shortcut menu
where the option Properties can be chosen.

Properties of charts

Update Method determines the kind of execution for STATEFLOW blocks:


Choosing Triggered or Inherited we deside that the execution is controlled
by other blocks of the SIMULINKmodel.
The STATEFLOW block has one or more event inputs from SIMULINK
that trigger it’s execution.
(default, z.B. proki5).
The option Sampled causes an execution of the chart at equidistant time
steps (Sample Time).
The option Continuous causes an execution of the chart at each simulation
time step.

162
CHAPTER 8. STATEFLOW 8.3. STATEFLOW TOOLS

8.3.3 The Debugger


The debugger serves as a monitoring tool for the chart’s execution in order to
detect unexpected behavior.
It is started by clicking on the menu Tools Debug.

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

Determining the Execution Order of


SIMULINK

Inhaltsverzeichnis

9.1 The SIMULINK Execution Order . . . . . . . . . . . . . . . . . . . . . . . 166


9.2 Conditionally Executed Subsystems . . . . . . . . . . . . . . . . . . . . . . 167
9.2.1 Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
9.2.2 Triggers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
9.3 Exercise for chapter 9 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

165
CHAPTER 9. EXECUTION ORDER 9.1. THE SIMULINK EXECUTION ORDER

9.1 The SIMULINK Execution Order


When starting a simulation, SIMULINK first of all determines the order of exe-
cution.
This ordering is listed by the SIMULINK debugger.

Subsystem1

In1 Out1

1 res
source sink
In1 Out1

Subsystem2

1 1
1
1 In1 z z Out1
z1 z2

For the model shown above the execution order is:

 

(sldebug @0:0 ’ex1/Subsystem1/z2’): step


(sldebug @0:1 ’ex1/Subsystem2/z4’):
(sldebug @0:2 ’ex1/sink’):
(sldebug @0:3 ’ex1/source’):
(sldebug @0:4 ’ex1/Subsystem1/z1’):


(sldebug @0:5 ’ex1/Subsystem2/z3’): 

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

This example shows:


SIMULINK executes a system block by block, regardless of the hierarchy
defined by subsystems.
So if you let SIMULINK determine the execution order, you can not be
sure, that the operations you decided to group as a subsystem, are executed
in one piece.
Every time you add a new block to the system, the execution order for the
entire system may change.
If you want to make sure,
that the system gets executed subsystem by subsystem and
that you can determine the calculation order of the subsystems yourself,
you have to use conditionally executed subsystems to organize a Control Flow.

9.2 Conditionally Executed Subsystems


A conditionally executed subsystem is created by inserting a Trigger block
into an existing subsystem (library Signals & Systems).

f()
fcn_call 1 1 trigger 1 1
1 1
1 In1 z z Out1 1 In1 z z Out1
z1 z2 z1 z2

For a conditionally executed STATEFLOW subsystem we use an


– input from SIMULINK of type trigger (either edge) or function call.
– The matching chart property has to be set to triggered or inherited
(File Chart Properties).
The execution of a conditionally executed subsystem is determined by the
control input.

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

Control Flow 1 Demux


Control Flow 2
fcn_call_1
fcn_call_1 fcn_call_1
f() Demux
fcn_call_2
fcn_call_2
fcn_call_2 Function−Call
Generator
chart
fcn_call() fcn_call()

1 In1 Out1 in_data out_data 1


In1 Out1
Data Flow
Subsystem1 Subsystem2

2. triggers: any kind of condition (rising, falling, either edge)


Any signal can be used as control input for a triggered subsystem. The
trigger detects the zero crossing of the signal.

Control Flow 1 Control Flow 2


trigger_1
1

trigger_2 0

chart

1 In1 Out1 in_data out_data 1


In1 Out1
Data Flow
Subsystem1 Subsystem2

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

9.2.1 Function Calls


Function calls behave like calls of subroutines in progamms.

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.

A control flow organized by function calls behaves like a stack (LIFO).

In example ex21.mdl a STATEFLOW block as Scheduler block provides two


function calls to determine the execution order of two subsystems.

In example ex22.mdl the function call signals are interchanged.

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

In1 Out1 In1 Out1


function call() function call()

We check the execution order again with sldebug:


   

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

Note: All sample times must be set to  inside a triggered subsystem!

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.

The computation of the calling block will not be interrupted.


The control flow organized by trigger signals behaves like a queue (FIFO).

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.

Subsystems called as functions:

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.

Execution order model 1 (triggered):


The call sub1 is sent. It is lined up in the queue. The output of subsystem 2
(most recent) is mapped to subout. Subsystem 1 is now evaluated, because it
is the next process in line.
Execution order model 2 (function call):
The call sub1 is sent. Subsystem 1 is evaluated immediately, the calculation
of the stateflow block is suspended. Afterwards the output of subsystem 1 (now
most recent!!!) is mapped to subout.

171
CHAPTER 9. EXECUTION ORDER 9.3. EXERCISE FOR CHAPTER 9

9.3 Exercise for chapter 9


Aim:
Explore
the different types of control signals and
the SIMULINK debugger (sldebug).
To do:
Start with the model exec ord.mdl in subfolder exercises.
Change the two subsystems into conditionally executed subsystems
Insert a STATEFLOW block. Configure this block to call the two subsys-
tems. I.e.:
– Add two events with scope ”Output to SIMULINK”.
– Set the ”Trigger” property of the first output to Either Edge and the
”Trigger” property of the second output to Function Call
Adapt the settings of the control input of the two subsystems accordingly
and connect the subsystems to the STATEFLOW block.
Now check the execution order of the system using the SIMULINK debugger.
Which subsystem is executed first?

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!

Check the execution order again.

Solution: exec ord sol.mdl

172

You might also like