You are on page 1of 522

Introduction to Stateflow®

with Applications
Steven T. Karris

Orchard Publications
www.orchardpublications.com
Students and working professionals will find

Introduction to Stateflow® Introduction to Stateflow® withApplications to


be a concise and easy-to-learn text. It pro-

with Applications
vides complete, clear, and detailed explana-
tions of the powerful interactive graphical
design tool. All topics are illustrated with real-
world examples.

This text includes the following chapters and appendices:


• The Stateflow Chart • The Stateflow Truth Table • Embedded MATLAB Functions in Stateflow
Charts • Model Coverage for Embedded MATLAB Functions • Graphical Functions • Connective
Junctions • History Junctions and Transitions • Stateflow Boxes • Mealy and Moore Charts in
Stateflow • Introduction to MATLAB • Introduction to Simulink • Masked Subsystems in Simulink
Each chapter contains several practical applications.

Steven T. Karris is the president and founder of Orchard Publications. His undergraduate and
graduate degrees are from Christian Brothers University, Memphis, Tennessee, and from Florida
Institute of Technology, Melbourne, Florida. He is a registered professional engineer in California
and Florida. He has over 30 years of professional engineering experience in industry. In addition,
he has over 30 years of teaching experience as an adjunct professor at several educational insti-
tutions, the most recent at UC Berkeley, CA.

Orchard Publications
Visit us on the Internet
www.orchardpublications.com
or email us: info@orchardpublications.com

ISBN-13: 978-1
1-9
934404-0
08-9
9
$60.00 U.S.A.

ISBN-10: 1-9
934404-0
08-X
X
Introduction to Stateflow®
with Applications
Steven T. Karris

Orchard Publications
www.orchardpublications.com
Introduction to Stateflow ® with Applications

Copyright ©2007 Orchard Publications. All rights reserved. Printed in the United States of America. No part of this
publication may be reproduced or distributed in any form or by any means, or stored in a data base or retrieval system,
without the prior written permission of the publisher.

Direct all inquiries to Orchard Publications, info@orchardpublications.com

Product and corporate names are trademarks or registered trademarks of The MathWorks™, Inc. They are used only
for identification and explanation, without intent to infringe.

Library of Congress Cataloging-in-Publication Data


Library of Congress Control Number 2007934492

ISBN-10: 1-934404-08-X
ISBN-13: 978-1-934404-08-9

Disclaimer
The author has made every effort to make this text as complete and accurate as possible, but no warranty is implied.
The author and publisher shall have neither liability nor responsibility to any person or entity with respect to any loss
or damages arising from the information contained in this text.
Preface
This text is an introduction to Stateflow ®, for use with Simulink® and MATLAB ®. It can be
considered as an continuation of Simulink and is written for students at the undergraduate and
graduate programs, as well as for the working professional.
Although some previous knowledge of MATLAB and Simulink would be helpful, it is not
absolutely necessary; Appendix A of this text is an introduction to MATLAB, and Appendix B is
an introduction to Simulink to enable the reader to begin learning MATLAB, Simulink, and
Stateflow simultaneously, and to perform graphical computations and programming.
Chapters 1 describes the basic workflow for building Stateflow charts that are used to model
eventdriven systems, and how they work with Simulink blocks. It begins with definitions that are
essential in understanding Stateflow and its relation to Simulink and MATLAB. It continues with
the description of a demo model provided by The MathWorks™, and concludes with an example
with step−by−step procedures.
Chapter 2 describes the basic workflow for building Stateflow truth tables to form decision−
making behavior, and how it works with Simulink blocks. We discuss the Truth Table block that
can be added directly to a Simulink model, and the Truth Table that can be called from a
Stateflow Chart block.
Chapter 3 describes the procedure for adding Embedded MATLAB functions to Stateflow charts.
It begins with an introduction to Embedded MATLAB functions using an example, followed by
procedures for building a Simulink model with a Stateflow chart that calls the Embedded
MATLAB function. It concludes with a procedure for debugging Embedded MATLAB functions
in Stateflow Charts.
Chapter 4 describes the procedure for adding Embedded MATLAB functions to Stateflow charts.
It begins with an introduction to Embedded MATLAB functions using an example, followed by
procedures for building a Simulink model with a Stateflow chart that calls the Embedded
MATLAB function.
Chapter 5 describes the procedure for creating graphical functions. It begins with an introduction
to graphical functions followed by procedures for building a Simulink model to define graphical
functions and includes illustrative examples.
Chapter 6 describes the use of connective junctions to represent a decision point between
alternate transition paths for a single transition. Flow diagram notation uses connective junctions
to represent common code structures such as for loops and if−then−else constructs without the
use of states.
Chapter 7 describes the use of history junctions to represent historical decision points in the
Stateflow diagram. A description with an illustrative example is provided, and the chapter
concludes with a discussion on transitions. For easy reference, the examples presented are the
same or similar to those included in the Stateflow documentation.
Chapter 8 is a short chapter describing the use of boxes to extend Stateflow Chart diagrams. We
describe how to create a state and changing it to a box, and how to create a box and change it to
a state.
Chapter 9, the last chapter, begins with an overview of the Mealy and Moore machines, then
describes the procedure for creating Mealy and Moore charts in Stateflow, and concludes with
illustrative examples for each.
Appendix C presents an overview of masked subsystems, and a step−by−step procedure to create
custom user interfaces, i.e., masks for Simulink subsystems. It is included in this text as a quick
reference to masked subsystems in the Stateflow demos.
This text is only an introduction to Stateflow, and the author feels that with the background
gained after studying the material of this text, the reader should not have any difficulty going
through the Stateflow demos which undoubtedly are real−world examples.
This is the first edition of this title, and although every effort was made to correct possible
typographical errors and erroneous references to figures and tables, some may have been
overlooked. Accordingly, the author will appreciate it very much if any such errors are brought to
his attention so that corrections can be made before the next printing.
The author wishes to express his gratitude to the staff of The MathWorks™, the developers of
MATLAB® and Simulink® for the encouragement and unlimited support they have provided me
with during the production of this text.

Orchard Publications
www.orchardpublications.com
info@orchardpublications.com
Table of Contents
1 The Stateflow Chart 1−1
1.1 Finite State Machines..............................................................................................1−1
1.2 Event−Driven Systems.............................................................................................1−2
1.3 Construction of Finite−State Machines with Stateflow..........................................1−2
1.4 Procedure for Creating a Stateflow Chart .............................................................1−11
1.5 Summary ................................................................................................................1−70
1.6 Exercise for the Reader..........................................................................................1−78
1.7 Solution to the End−of−Chapter Exercise.............................................................1−79

2 The Stateflow Truth Table 2−1


2.1 Truth Tables in Stateflow........................................................................................2−1
2.2 Summary ................................................................................................................2−62
2.3 Exercises.................................................................................................................2−64
2.4 Solution to End−of−Chapter Exercises..................................................................2−66

3 Embedded MATLAB Functions in Stateflow Charts 3−1


3.1 Introduction to Embedded MATLAB Functions ....................................................3−1
3.2 Building the Model with a Stateflow Embedded MATLAB Function ...................3−2
3.3 Programming the Stateflow Chart with an Embedded MATLAB Function.........3−11
3.4 Simulation of the Matrix Operations Stateflow Chart ..........................................3−15
3.5 Summary ...............................................................................................................3−35
3.6 Exercises for the Reader........................................................................................3−40
3.7 Solution to the End−of−Chapter Exercises ...........................................................3−42

4 Model Coverage for Embedded MATLAB Functions 4−1


4.1 Introduction to Embedded MATLAB Functions ................................................... 4−1
4.2 Summary .............................................................................................................. 4−18
4.3 Exercises for the Reader....................................................................................... 4−19
4.4 Solution to the End−of−Chapter Exercises........................................................... 4−20

5 Graphical Functions 5−1


5.1 Introduction to Graphical Functions...................................................................... 5−1
5.2 Creating a Graphical Function............................................................................... 5−1
5.3 Subcharts .............................................................................................................. 5−10
5.4 Exporting Graphical Functions to Stateflow ........................................................ 5−17
5.5 Summary ............................................................................................................... 5−29

Introduction to Stateflow®with Applications i


Copyright © Orchard Publications
5.6 Exercise for the Reader ......................................................................................... 5−31
5.7 Solution to the End−of−Chapter Exercise............................................................ 5−32

6 Connective Junctions 6−1


6.1 The Stateflow Connective Junction Tool .............................................................. 6−1
6.2 Creating a Connective Junction ............................................................................ 6−2
6.3 Changing Connective Junction Size ...................................................................... 6−3
6.4 Changing Connective Junction Properties............................................................. 6−6
6.5 Uses of Connective Junctions ................................................................................ 6−7
6.6 Summary .............................................................................................................. 6−16
6.7 Exercise for the Reader ........................................................................................ 6−17
6.8 Solution to the End−of−Chapter Exercise ........................................................... 6−18

7 History Junctions and Transitions 7−1


7.1 History Junction Defined....................................................................................... 7−1
7.2 The Stateflow History Junction Tool .................................................................... 7−1
7.3 Changing the History Junction Size ...................................................................... 7−2
7.4 Changing History Junction Properties................................................................... 7−5
7.5 Entering a State ..................................................................................................... 7−9
7.6 Executing an Active State ................................................................................... 7−10
7.7 Exiting an Active State........................................................................................ 7−11
7.8 Execution Order for Parallel States ..................................................................... 7−13
7.9 Transitions ........................................................................................................... 7−15
7.10 Transition Connections ....................................................................................... 7−19
7.11 Inner Transitions ................................................................................................. 7−22
7.12 Summary .............................................................................................................. 7−25
7.13 Exercise for the Reader ........................................................................................ 7−27
7.14 Solution to the End−of−Chapter Exercise........................................................... 7−28

8 Boxes in Stateflow 8−1


8.1 Creating a Box.......................................................................................................... 8−1
8.2 Changing a State to a Box ....................................................................................... 8−2
8.3 Using Boxes in Stateflow.......................................................................................... 8−4
8.4 Summary .................................................................................................................. 8−6

ii Introduction to Stateflow®with Applications


Copyright © Orchard Publications
9 Mealy and Moore Charts in Stateflow 9−1
9.1 Mealy Machine Defined...........................................................................................9−1
9.2 Moore Machine Defined ..........................................................................................9−3
9.3 Mealy and Moore Machines in Stateflow ................................................................9−4
9.4 Creating a Mealy Chart............................................................................................9−6
9.5 Creating a Moore Chart .........................................................................................9−10
9.6 Changing Chart Type.............................................................................................9−17
9.7 Debugging Mealy and Moore Charts .....................................................................9−17
9.8 Summary.................................................................................................................9−20
9.9 Exercises for the Reader .........................................................................................9−21
9.10 Solution to the End−of−Chapter Exercises............................................................9−22

A Introduction to MATLAB® A−1


A.1 MATLAB® and Simulink®................................................................................A−1
A.2 Command Window .............................................................................................A−1
A.3 Roots of Polynomials ...........................................................................................A−3
A.4 Polynomial Construction from Known Roots......................................................A−4
A.5 Evaluation of a Polynomial at Specified Values ..................................................A−6
A.6 Rational Polynomials ...........................................................................................A−8
A.7 Using MATLAB to Make Plots .........................................................................A−10
A.8 Subplots..............................................................................................................A−18
A.9 Multiplication, Division, and Exponentiation ...................................................A−18
A.10 Script and Function Files...................................................................................A−26
A.11 Display Formats .................................................................................................A−31

B Introduction to Simulink® B−1


B.1 Simulink and its Relation to MATLAB ............................................................... B−1
B.2 Simulink Demos ................................................................................................. B−20

C Masked Subsystems C−1


C.1 Masks Defined ........................................................................................................ C−1
C.2 Advantages Using Masked Subsystems.................................................................. C−1
C.3 Mask Features......................................................................................................... C−1
C.4 Creating a Masked Subsystem ................................................................................ C−2

References R−1

Index IN1

Introduction to Stateflow®with Applications iii


Copyright © Orchard Publications
NOTES:

iv Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 1
The Stateflow Chart

T
his chapter describes the basic workflow for building Stateflow charts that are used to
model event−driven systems, and how they work with Simulink blocks. It begins with defi-
nitions that are essential in understanding Stateflow and its relation to Simulink and MAT-
LAB. It continues with the description of a demo model provided by The MathWorks™, and
concludes with an example with step−by−step procedures.

1.1 Finite State Machines


A finite state machine is a model describing the behavior of a finite number of states, the transi-
tions between those states, and actions.
A state represents an operating mode of a machine, for instance, a typical household portable
space heater has four states, off, low, medium, and high.The on state is omitted because the
machine (space heater) must be on to operate in the low, medium, and high states.
An action describes the activity that is to be performed. An action can be further classified as an
entry action which is performed when entering the state, an exit action which is performed when
exiting the state, and as a transition action which is performed during a transition.
A finite state machine can be represented either by a state diagram or a state transition table.
Thus, a typical household space heater can be represented as shown in Figure 1.1, or as a state
transition table shown as Table 1.1.

State
Medium
Transition

Low High

Off

Figure 1.1. State transition diagram for a typical finite state machine

Introduction to Stateflow®with Applications 1−1


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

TABLE 1.1 Typical state transition table for a finite state machine

State A State B State C State D


Present State / Condition (Off) (Low) (Medium) (High)
Condition 1 1 0 0 0
Condition 2 0 1 0 0
................... ..... ..... ..... .....
Condition N 0 0 0 1

A condition is a Boolean expression that can be true (logic 1) or false (logic 0). In Stateflow, con-
ditions are enclosed in square brackets.

1.2 Event−Driven Systems


An event is an action that can trigger a variety of activities. For example, in a typical household
space heater a switch allows a transition to occur between medium state and high state. Thus,
event driven systems allow the transition from one operating mode to another in response to events
and conditions. Event−driven systems can be implemented as finite−state machines.

1.3 Construction of Finite−State Machines with Stateflow


Stateflow provides us the necessary graphical objects to construct finite−state machines. Like
Simulink, we can drag and drop objects to create state−transition charts in which a series of tran-
sitions directs a flow of logic from one state to another.
Let us examine the example of a Stateflow chart provided with the Stateflow Toolbox. This
example illustrates the logic required to shift gears in an automatic transmission system of a car. It
is assumed that MATLAB, Simulink, and Stateflow are all installed in your system. For installa-
tion procedures, please refer to The MathWorks documentation.
We begin by invoking MATLAB, and at the command prompt we type sf_car. The Simulink
model of Figure 1.2 is then displayed.

1−2 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow

Figure 1.2. The sf_car model in Simulink


The left−most block in Figure 1.2 is the familiar Signal Builder block and provides the signals
shown in Figures 1.3 through 1.6. For the construction of a signal builder block, please refer to
Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1, or to the Simulink
documentation.

Figure 1.3. The passing maneuver state in the Signal Builder block of Figure 1.2

Introduction to Stateflow®with Applications 1−3


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.4. The gradual acceleration state in the Signal Builder block of Figure 1.2

Figure 1.5. The hard braking state in the Signal Builder block of Figure 1.2

Figure 1.6. The coasting state in the Signal Builder block of Figure 1.2

1−4 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow

When this model is simulated, the Scope blocks in Figure 1.2 will display the engine RPM, vehi-
cle MPH and throttle percentage signals depending on the selection of the applied signals shown
in Figures 1.3 through 1.6. Thus, when the Actual Acceleration mode is selected, the engine
RPM Scope block and the vehicle MPH and throttle percentage will display the signals shown in
Figures 1.7 and 1.8 respectively.

Figure 1.7. The engine RPM signal when the Actual Acceleration mode is selected in Figure 1.2

Figure 1.8. The vehicle MPH and throttle % signals when the Actual Acceleration mode is selected in Figure 1.2
The internal blocks and their interconnection for the subsystem Engine in Figure 1.2 are shown
in Figure 1.9 below.

Introduction to Stateflow®with Applications 1−5


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.9. The blocks for the engine subsystem of Figure 1.2

In Figure 1.9 the engine torque* block is a Lookup Table (2−D) block whose inputs are the vec-
tor thvec (first input) representing the throttle signal in Figure 1.4, and the vector nevec (second
input) representing the engine RPM value at the end of the simulation time. The elements of
these vectors can be seen by typing thvect and nevect in MATLAB’s command prompt.
The signal at the minus (−) input of the Sum block in Figure 1.9, denoted as Ti, represents the
impeller torque as we can see from Figure 1.2. A typical value for term lei in the Gain block
denoted as engine + impeller† inertia‡ is 0.02 and in this model the constant value 0.022 is being
used.
The Integrator block in Figure 1.9 is configured with Initial condition set at 1000, Limit output
checked, Upper saturation limit at 6000, and Lower saturation limit at 600.
To see how the values change with simulation time, we add Display blocks as shown in Figure
1.10.

* Torque is the product of force and lever−arm distance, which tends to produce rotation. The SI derived unit
commonly use for torque is the newton metre (joule). Torque has the same units as energy or work.
† An impeller is a rotating component of a pump, usually made of iron, steel, aluminum or plastic, which trans-
fers energy from the motor that drives a pump to the fluid being pumped by forcing the fluid outwards from the
centre of rotation. Impellers are usually short cylinders with protrusions forming paddles to push the fluid and a
splined center to accept a driveshaft.
‡ When a large force is required to speed up a body, slow it down, or deviated sidewise if it is moving, the mass of
the body is large, and thus we say that the body has a large inertia. If only a small force is needed per unit of
acceleration, the mass is small and the inertia is small.

1−6 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow

Figure 1.10. The engine subsystem of Figure 1.2 with values at simulation time T=30
The engine RPM block in Figure 1.10 displays the waveform shown in Figure 1.11.

Figure 1.11. The engine RPM waveform displayed on the Scope block of Figure 1.10
The components of the transmission subsystem block of Figure 1.2 are shown in Figure 1.12
below.

transmission
ratio

Figure 1.12. The components of the transmission subsystem in Figure 1.2

Introduction to Stateflow®with Applications 1−7


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

The Torque Converter* subsystem in Figure 1.12 is a masked subsystem with a mask icon. An
introduction to Masked Subsystems is provided in Appendix C. To unveil its components we
choose Look Under Mask from the Edit menu, and the subsystem components are shown in Fig-
ure 1.13. Both lookup tables in Figure 1.13 perform 1−D interpolation.

Figure 1.13. The components of the torque converter subsystem in Figure 1.12
The components of the transmission ratio subsystem in Figure 1.12 are shown in Figure 1.14. The
lookup table in Figure 1.14 performs 1−D interpolation for the gear ratios in the transmission sys-
tem. A typical four−speed manual transmission has the following gear ratios:

Gear 1st 2nd 3rd 4th Reverse


Ratio 2.97:1 2.07:1 1.43:1 1.00:1 3.28:1

Figure 1.14. The components of transmission ratio subsystem in Figure 1.12

* A torque converter is modified form of a hydrodynamic fluid coupling (a device used to transmit rotating
mechanical power), and like the fluid coupling, is used to transfer rotating power from a prime mover, such as
an internal combustion engine or electric motor, to a rotating driven load. As with the fluid coupling, the torque
converter takes the place of a mechanical clutch. Unlike a fluid coupling, however, a torque converter is able to
multiply torque when there is a substantial difference between input and output rotational speed, thus providing
the equivalent of a reduction gear.

1−8 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Construction of Finite−State Machines with Stateflow

As seen in the table on the previous page, in 1st gear, the engine makes 2.97 revolutions for
every revolution of the transmission’s output. In 4th gear, the gear ratio of 1:1 means that the
engine and the transmission’s output are moving at the same speed. *
The model of Figure 1.2 uses the gear ratios 2.393:1, 1.450:1, 1.000:1, and 0.667:1. These
values can be seen in Function Block Parameters of Figure 1.15 for the Look−Up Table block
in Figure 1.14.

Figure 1.15. Function Block Parameters for the Look−Up Table block in Figure 1.15
The vehicle subsystem in Figure 1.2 is another masked subsystem. As before, to view the compo-
nents of this subsystem we choose Look Under Mask from the Edit menu, and the subsystem
components are shown in Figure 1.16.

* Some automobiles are equipped with 5th and 6th gears and typical gear ratios for these are 0.84:1 and 0.56:1
respectively. These are referred to as overdrive gears in which the output of the transmission is revolving faster
than the engine.
The differential ratio is a measure of the number of revolutions of the transmission to the revolutions of the
wheels of the automobile. Thus, a differential ratio of 3.45 indicates that for every 3.45 revolutions of the
transmission, the wheels complete one revolution.
Multiplication of the differential ratio by the gear ratio in the transmission produces the number of revolutions
in the engine per one revolution of the wheels. Thus, using the gear ratio in the 1st gear in Table 1.2 and a dif-
ferential ratio of 3.45, we obtain 2.97 x 3.45 = 10.25 revolutions for every revolution the wheels make.

Introduction to Stateflow®with Applications 1−9


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.16. The vehicle block subsystem shown in Figure 1.2


It is beyond the scope of this text to provide details for every block in Figure 1.16 above. The
block above the road load block in Figure 1.16 above, is a user−defined function block and repre-
sents the signum function* whose value is – 1 for all negative inputs, and +1 for all positive
inputs.
The components of the Threshold Calculation subsystem block in Figure 1.2 are shown in Fig-
ure 1.17 below. We observe that includes a Function−Call Generator block. We recall† that this
block can be placed in a subsystem to create a triggered subsystem.

Figure 1.17. The components of Threshold Calculation subsystem block shown in Figure 1.2
The interp_up and interp_down blocks in Figure 1.17 are both Look−up 2D tables. To see the
values assigned to them, at the MATLAB command prompt we type upth, downth, uptab, and
downtab.

* The signum function is described in detail in Signals and Systems with MATLAB Computing and Simulink Modeling,
ISBN−13: 978−0−9744239−9−9. It is very useful in deriving the Fourier transform of the unit step function.
† For an example, please refer to Page 11−34, Introduction to Simulink with Engineering Applications, ISBN−13: 978−0−
9744239−7−1

1−10 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Of all the subsystems in the model of Figure 1.2, we are most interested in the shift_logic State-
flow logic block. When we double−click on this block, we obtain the Stateflow chart shown as
Figure 1.18 below.

Figure 1.18. The shift_logic Stateflow logic block


The two dashed rectangles represent two independent modes of operation and are normally
referred to as Parallel (AND) states, and the numbers 1 and 2 indicate the execution order. The
solid rectangles within the parallel states 1 and 2 represent mutually exclusive modes of opera-
tion and are normally referred to as Exclusive (OR) states.

1.4 Procedure for Creating a Stateflow Chart


To understand the basic steps for creating a Stateflow Chart, we will present an example and we
will follow the procedure recommended by The MathWorks illustrated in the functional block
diagram shown in Figure 1.19 below.

Introduction to Stateflow®with Applications 1−11


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

2. Define the states for


modeling each mode 6. Simulate the
of operation Chart

1. Define the Stateflow 3. Define state actions 5. Choose triggering 7. Debug the
Interface to Simulink and variables method Chart

4. Define the transitions


between states

Figure 1.19. Recommended procedure for creating a Simulink model with a Stateflow Chart block

Example 1.1
ABC Company maintains checking and savings accounts with a local bank. The initial deposit in
the checking account is $10,000 and the fixed amount of $10,000 is deposited in the savings
account. The company has also established an overdraft protection for up to $50,000, and has
made an agreement with the bank that if payments by the bank exceed the overdraft protection,
the bank will deduct the excess amount from the savings account.
There will be no fees imposed as long as payments do not exceed present checking account bal-
ance and interest at 0.5% will be earned. A fee of 5% will be imposed for overdrafts, and 1% fee
will be charged if it becomes necessary to draw monies from the savings account.
To simplify the model, we will assume that no deposits to the checking account are made during
the assumed time of payment transactions. When completed, the Stateflow chart will appear as
shown in Figure 1.20. This example is similar to the sf_aircontrol model provided by The Math-
Work’s Stateflow documentation.
The Stateflow Editor chart in Figure 1.20 contains six Exclusive (OR) states represented graphi-
cally by solid rectangles. These states are shown as Transfer On, Overdraft On, Overdraft Off,
Savings On, Savings Off, and TransferOff. No two or more Exclusive (OR) states can be active
or execute at the same time.
The Stateflow Editor chart in Figure 1.20 contains also three Parallel (AND) states represented
graphically by dashed rectangles with a number in the upper right corner. These are shown as
Overdraft (Number 1), Savings (Number 2), and DollarValue (Number 3). The numbers indicate
the execution order. Two or more parallel (AND) states at the same hierarchical level can be
active at the same time but will execute in serial fashion.

1−12 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.20. The Stateflow Editor window for Example 1.1

The unidirectional arrows represent transitions from one state to another


and specify the direction of the flow. The Stateflow chart in Figure 1.20 contains six transitions,
i.e., Overdraft On to Overdraft Off, Overdraft Off to Overdraft On, Savings On to Savings Off,
Savings Off to Savings On, TransferOn to TransferOff, and TransferOff to TransferOn.
Referring again to the Stateflow Editor chart in Figure 1.20, we observe that an arrow with a
solid dot tail is directed towards the Overdraft Off, Savings Off, and TransferOff solid
rectangles and as mentioned earlier, these represent exclusive (OR) states and as such cannot be
active or execute at the same time. The Overdraft On, Savings On, and TransferOn solid rectan-

Introduction to Stateflow®with Applications 1−13


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

gles also represent exclusive (OR) states and since the On and Off states are on the same hierar-
chical level, we must specify which is the default state, On or Off. For this example, the default
states are Off and we use this arrow, referred to as the Default transition, for this purpose.
When the Stateflow chart is inactive, it is in a dormant state, and when the chart is first acti-
vated, the default transition, e.g., TransferOff, makes the chart active. As we will see soon, we
will use a clock signals to “wake up” the chart.
A State Action is an action whose execution is based on the status of the state. The chart in Fig-
ure 1.20 contains an entry action and a during action. Entry actions are executed when the state
is entered, i.e., when it first becomes active. The entry in the TransferOff state is an entry action.
During actions are executed while a state is active and no transition to another state exists. The
during in the TransferOn state is a during action. We can abbreviate the word during as du.
A Condition is a Boolean expression that allows a transition to occur when the expression is true.
A Condition is a text label for the transition and it is enclosed in square brackets ([ ]). The chart
in Figure 1.20 provides four conditions on the transitions between Overdraft and Savings, i.e.,
[EndingBalance < 0], [EndingBalance >= 50000], [EndingBalance < −50000], and [EndingBal-
ance >= −50000].
An Event is an object that can initiate several activities such as “waking up” a Stateflow chart,
transitions to occur from one state to another, and executions of actions.
When our model is complete, it will appear as shown in Figure 1.21 below.

Figure 1.21. The model for Example 1.1

1−14 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

The model in Figure 1.21 contains two edge−triggered events, the CLOCK that is used to “wake
up” the Stateflow chart at each rising or falling edge of a square wave signal, and the TRANS-
FERS that is used to allow transitions to occur between TransferOff and TransferOn at each ris-
ing or falling edge of a pulse signal.
The contents of the Financial Operations subsystem in Figure 1.21 are shown in Figure 1.22,
and the signals in the Signal Builder block are shown in Figure 1.23.

Figure 1.22. The components of the Financial Operations subsystem in Figure 1.21

Introduction to Stateflow®with Applications 1−15


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.23. Waveforms provided by the Signal Builder block


We will now create the model with the following step−by−step procedure.
Step 1: We define the Interface to Simulink

a. We invoke MATLAB and from the main window shown in Figure 1.24 below we select
Simulink by clicking on the Simulink icon . This opens the Simulink Library Browser
window shown in Figure 1.25.

Figure 1.24. The MATLAB main window

1−16 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.25. The Simulink Library Browser window


b. In the Simulink Library Browser window shown in Figure 1.25 we click the Create a

new model icon and a new empty model appears as shown in Figure 1.26.

Figure 1.26. Empty Simulink model for Example 1.1


c. From the Simulink Library Browser window shown in Figure 1.25, we click and drag the
following Simulink blocks into the empty Simulink model in Figure 1.26.
Three Constant blocks, a Product block, a Gain block, an Integrator block, two Inport
blocks and an Outport block from the Commonly Used Blocks Library, and a Multiport

Introduction to Stateflow®with Applications 1−17


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Switch from the Signal Routing Library. The Constant blocks and the Gain block per-
form the functions described by the annotations, to the Limit Inport block we will assign
the value of – 60000 to represent the negative sum of the initial deposit of 10000 and the
maximum Overdraft amount of 50000 . The Integrator block performs the integration
t
EndingBalance = ∫0 En dingBalance_Change + 10000
where 10000 is the initial condition* representing the initial deposit of 10000 into the
checking account. We interconnect these blocks as shown in Figure 1.27.

Figure 1.27. The blocks for the subsystem


d. To create a subsystem, we enclose all blocks, except the Inport and Outport blocks,
within a bounding box, from the Edit drop menu we choose Create Subsystem, and we
label it as Financial Operations.

* The initial condition is specified in the Function Block Parameters dialog box for the Integrator block.

1−18 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

e. We stretch the window of the model in Figure 1.26 and we add the following blocks:
A Signal Builder block from the Sources Library.
A Mux block (heavy vertical bar) from the Commonly Used Blocks Library
A Scope block from the Commonly Used Blocks Library
A Constant block from the Commonly Used Blocks Library
A Chart block from the Stateflow subnode under the Simulink Extras Library
The model now appears as shown in Figure 1.28.

Figure 1.28. The blocks for the model of Example 1.1


f. We double−click the Signal Builder block and the waveform shown in Figure 1.29
appears.

Introduction to Stateflow®with Applications 1−19


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.29.
g. From the Axes drop menu we select Change Time Range, we set Min time to 0, Max
time to 300, we change the name field from Signal 1 to TRANSFERS, we click on the ris-
ing (left) edge of the waveform to select it,* in the T: field under Left Point we enter 10,
we click the falling (right) edge of the waveform to select it, in the T: field under Left Point
we enter 290, and we click OK to accept it. The waveform of the Signal Builder block is
now as shown in Figure 1.30.

* When properly selected, it appears as a heavy red line and the fields in the lower part of the window become active

1−20 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.30. The TRANSFERS waveform for Example 1.1


h. From the Signal drop menu in the Signal Builder window of Figure 1.30 we select New
and from it we choose Square Wave. In the Square Wave dialog box in Figure 1.31 below
we enter the parameters shown.

Figure 1.31. Parameters for the square waveform of the Signal Builder block
i. We change the name field to CLOCK, we click OK to accept these values, and the Signal
Builder block now appears as shown in Figure 1.32.

Introduction to Stateflow®with Applications 1−21


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.32. The TRANSFERS and CLOCK waveforms of the Signal Builder block
j. As we will discuss shortly, in Figure 1.32 the TRANSFERS signal will be used to allow
transitions to occur between TransferOff and TransferOn at each rising or falling edge of a
pulse signal, and the CLOCK is used to “wake up” the Stateflow chart at each rising or fall-
ing edge of a square wave signal.
k. To define the input of the Stateflow Chart block in Figure 1.28, we double−click this
block, and we observe that the Stateflow Editor window appears as shown in Figure 1.33.
From the Add drop menu we select Data>Input from Simulink, and this opens the Data
window shown in Figure 1.34.
In the Name field that appears under the General tab, we change the name to EndingBal-
ance and we leave other fields in their default values. We select the Value Attributes tab
and we check the Watch in debugger box. This will allow us to observe the value of End-
ingBalance at breakpoints during simulation.

1−22 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

l. To define the output of the Stateflow Chart block in Figure 1.28, we double−click this
block, and we observe that the Stateflow Editor window appears as shown in Figure 1.33.
From the Add drop menu we select Data>Output to Simulink, and this opens the Data
window shown in Figure 1.34.

Figure 1.33. The Stateflow Editor window

Figure 1.34. The Data window dialog box for defining the input and output to the Stateflow Chart

Introduction to Stateflow®with Applications 1−23


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

m. In the Name field that appears under the General tab in the Data dialog box in Figure
1.34, we change the name to Payments and we leave other fields in their default values.
We select the Value Attributes tab, for the Limit range we specify 0 for Minimum and 2
for Maximum, where 0 represents no transfer, 1 indicates Overdraft transfer On, and 2
indicates Savings transfer On. We also check the Watch in debugger box to allow us to
observe the value of Payments at breakpoints during simulation.
n. Our Simulink model should now look like that shown in Figure 1.35 where we have
renamed the Stateflow Chart block Transfer Controller.

Figure 1.35. Defined input and output for the Stateflow Chart
Step 2: We define the States for each Mode of Operation
a. In the Simulink model of Figure 1.35 we double−click the Transfer Controller block and
the Stateflow Editor window appears as shown in Figure 1.36.
From the object palette on the left side of the Stateflow Editor window we click the State

tool , we move it to the drawing area, and we observe that it changes to a rectangle
with rounded corners and with a flashing text cursor on the upper left corner as shown in
Figure 1.37. This is a solid rectangle and as we know, it represents an exclusive (OR)
state.

1−24 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.36. The empty Stateflow Editor window

Figure 1.37. The Stateflow Editor window with the first exclusive (OR) state

Introduction to Stateflow®with Applications 1−25


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

b. At the flashing text cursor we enter TransferOn to name this state,* and we stretch the
rectangle. The Stateflow editor window now appears as shown in Figure 1.38.

Figure 1.38. The TransferOn exclusive (OR) state

c. We click the State tool again and we draw a smaller state below the TransferOn
state, and we name it TransferOff. The Stateflow editor window now appears as shown in
Figure 1.39.

d. In the Stateflow Editor in Figure 1.39 we right−click inside the TransferOn state and from
the pop−up menu in Figure 1.40 we select Decomposition> Parallel (AND).

* We can change the text size by choosing the Set Font Size from the Edit drop menu.

1−26 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.39. The TransferOn and TransferOff exclusive (OR) states

e. We left−click the State tool in the Stateflow Editor in Figure 1.39 and we place two
states inside the TransferOn state. We observe that these two states appear as rectangles
with rounded corners and dashed lines indicating that they are parallel (AND) states. We
also observe that these parallel states display numbers in their upper right corners. These
numbers specify the order of execution during simulation. We name these parallel states
as Overdraft and Savings, and the Stateflow Editor window now appears as shown in Fig-
ure 1.41.

Introduction to Stateflow®with Applications 1−27


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.40. Submenu for selecting the parallel (AND) states decomposition
f. We now need to add an observer state whose purpose will be to monitor the status of the

Overdraft and Savings states. We left− click the State tool again and we place
another substate within the TransferOn state under the Overdraft and Savings states. We
name this substate DollarValue and the Stateflow Editor appears as shown in Figure 1.42.

1−28 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.41. The addition of the Overdraft and Savings parallel (AND) states
g. By default, Stateflow execution order is based on implicit ordering. This means that the
execution order of parallel states depends on their location on the chart. The priority is
from top to bottom and then left to right. Thus, if for some reason the Savings substate is
moved to the left and the Overdraft substate is moved to its right, the Savings substate
attains the highest priority, the execution order is changed, and the simulation results will
be altered and probably meaningless. But it is possible to override the default and the exe-
cution order will be based on explicit ordering. We will do this with the next step.

Introduction to Stateflow®with Applications 1−29


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.42. The addition of the DollarValue parallel (AND) state


h. We right−click inside the Overdraft parallel state within the TransferOn main state to call
the state priorities pop−up menu shown in Figure 1.40, we select Execution Order, and in
the Chart window that appears we check the User specified state/transition execution
order field as shown in Figure 1.43. We click OK to accept these settings.

1−30 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.43. The Chart dialog box for specifying User specified state/transition execution order
i. We right−click again and from the Execution Order we choose the assignment order
shown in Figure 1.44.
j. We repeat steps (h) and (i) for the Savings and DollarValue parallel states.

Introduction to Stateflow®with Applications 1−31


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.44. The submenu for User specified state/transition execution order

k. Using the State tool we add two exclusive (OR) substates inside the Overdraft and
Savings parallel (AND) states. Inside the parallel Overdraft and Savings states we name
one of the exclusive states On and the other Off. The Stateflow chart now appears as
shown in Figure 1.45.

1−32 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.45. The addition of On and Off exclusive (OR) states inside the Overdraft and Savings parallel states

Step 3: We define State Actions and Variables


a. States perform actions at different phases of their execution cycle from the time they enter
the active phase to the time they re − enter the inactive phase. The three basic state
actions are listed in Table 1.2 below.

Introduction to Stateflow®with Applications 1−33


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

TABLE 1.2
Type When Executed Frequency of Execution
while State is Active
Entry When state becomes active Once (to initialize data)
During While the state is active and no valid At every time step (to update data)
transition to another state is available
Exit Before transition to another state Once (to re−configure data for the
next transition)

b. We left−click inside the TransferOff state after the last letter of its name to cause a blink-
ing text cursor to appear. We press the Enter key and we type entry: Payments=0; The
Stateflow Editor now appears as shown in Figure 1.46.

Figure 1.46. The addition of entry: Payments=0; entry state action


c. We need to add a during action for DollarValue in the third parallel state within the Trans-
ferOn state, that is, a Boolean expression to specify whether no Savings and no Overdraft

1−34 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

has occurred, or only Overdraft has occurred, or both Overdraft and Savings have
occurred. We click inside the DollarValue state after the last letter of its name to cause a
blinking text cursor to appear. We press the Enter key and we type
during: Payments=in(Overdraft.On)+in(Savings.On);
The Boolean expression in(Overdraft.On) can be true or false. If true, its value is 1 and
Overdraft is active. If false, its value is 0 and Overdraft is inactive. Likewise, the Boolean
expression in(Savings.On) can be true or false. Accordingly, the sum of these Boolean
expressions indicates whether no Savings and no Overdraft has occurred, or only Over-
draft has occurred, or both Overdraft and Savings have occurred. The Stateflow Editor
now appears as shown in Figure 1.47.

Figure 1.47. The addition of during: Payments=in(Overdraft.On)+in(Savings.On); during state action

Introduction to Stateflow®with Applications 1−35


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Step 4: We define Transitions Between States


a. In Stateflow, transitions are added to establish logic flow paths from one state, say A, to
another, say B, in a system. If state A is active and state B is inactive, and a transition
from state A to state B occurs, state A becomes inactive and state B becomes active.
Transitions are unidirectional and are represented by lines with arrowheads. As indicated
earlier in this chapter, the unidirectional arrows represent transitions from one state to
another and specify the direction of the flow. We recall that two exclusive (OR) states
cannot be active at the same time and therefore we must use transitions. However, paral-
lel (AND) states normally execute concurrently and thus we need not add transitions.
b. We need to add a transition from the TransferOff to the TransferOn state. To do this, we
move the cursor over the top edge of TransferOff and we observe that the cursor shape
changes to crosshairs. We hold down the left mouse button, we drag the cursor to the bot-
tom edge of the TransferOn state, we release the mouse, and a transition pointing from
the TransferOff to the TransferOn state is formed. We follow the same procedure to create
a transition from the TransferOn to the TransferOff state and the Stateflow Editor window
now appears as shown in Figure 1.48.

1−36 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.48. The addition of transitions between the TransferOff and the TransferOn states
c. Following the procedure in step (b) above we add transitions between the Off and On
states for the Overdraft and Savings states, and the Stateflow Editor appears as shown in
Figure 1.49.
d. We also need to add default transitions. As stated earlier, since the On and Off states are on
the same hierarchical level, we must specify which is the default state, On or Off. For this
example, we declare that the default states are Off. To add the default transitions we left−

click the Default Transition tool , we move the cursor into the drawing area, and
we observe that it changes to a diagonal arrow.

Introduction to Stateflow®with Applications 1−37


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.49. The addition of transitions On and Off inside the Overdraft and the Savings states
We place the cursor a the left edge of the TransferOff state and when the arrow assumes
an horizontal direction, we release the mouse. The default transition is now attached to
the TransferOff state and appears as a directed line with an arrow at its head and a small
filled−in circle at its tail as shown in Figure 1.50.* Using the same procedure we add
default transitions at the top edges of Overdraft.Off and Savings.Off states as shown in
Figure 1.50.

* The entire default transition arrow must be placed inside the state that it activates.

1−38 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.50. The addition of default transitions


e. Next, we must specify a condition, action, or event that will allow the transition from one
state to another to occur. This is referred to as guarding a transition, and for our example
the requirements for guarding the transitions from one exclusive state to another are
listed in Table 1.3 below.

Introduction to Stateflow®with Applications 1−39


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

TABLE 1.3
Transition Occurrence Guarding
TransferOff to TransferOn At regular time intervals Specify an edge−triggered event
TransferOn to TransferOff At regular time intervals
Overdraft.Off to Overdraft.On When the ending balance at any Specify a condition based on the
time is less than zero balance dollar amount
Overdraft.On to Overdraft.Off When the ending balance at any
time is greater or equal to $50,000
Savings.Off to Savings.On When the ending balance at any
time is less than −50,000
Savings.On to Savings.Off When the ending balance at any
time is greater or equal to −50,000

f. In the Stateflow Editor window in Figure 1.50, we click the transition from Overdraft.Off
to Overdraft.On and we observe that the transition appears highlighted and displays the
question mark (?) character. We click the question mark and where a blinking text cursor
appears we type the expression [EndingBalance < 0].* Using the same procedure we add
the following conditions to the other transitions in Overdraft and Savings.

Transition Condition
Overdraft.On to Overdraft.Off [EndingBalance >= 50000]
Savings.Off to Savings.On [EndingBalance < −50000]
Savings.On to Savings.Off [EndingBalance >= −50000]

The Stateflow Editor now appears as shown in Figure 1.51.

* For readability, it may be necessary to reposition the condition. We do this by clicking outside the condition, then we left−
click and drag the condition expression to a new position. Also, as stated earlier, we can change the text size by choosing the
Set Font Size from the Edit drop menu.

1−40 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.51. The addition of guarding the transitions


g. In the Stateflow Editor window in Figure 1.51, the TransferOn and TransferOff exclusive
(OR) states must change from active to inactive at regular intervals and for this to happen
we must define an event that occurs at the rising or falling edge of an input signal. We
recall that an event is an non−graphical object that triggers activities during the execution
of a Stateflow chart. We add an input event from the Add drop menu by selecting
Event>Input from Simulink in the Stateflow Editor in Figure 1.51, and this opens the
Event properties dialog window shown in Figure 1.52.

Introduction to Stateflow®with Applications 1−41


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.52. The Event dialog box


We change the Name field from event to TRANSFERS, we select Port 1, and the Trigger
field from Rising to Either. The dialog box now appears as shown in Figure 1.53.

Figure 1.53. The Event dialog box for event TRANSFERS


We click OK to accept these changes and the dialog box closes. Our Simulink model now
appears as shown in Figure 1.54 where we observe that a trigger port appears on top of the
Stateflow block.

1−42 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.54. The addition of Trigger input to the Transfer Controller Stateflow Chart
h. The next step is to associate the input event TRANSFERS with the transitions. We open
the Stateflow Editor, we click the transition from the TransferOff state to the TransferOn
state, we click the question mark to obtain a text editor, and we type the name TRANS-
FERS. We repeat this step to add the same event, i.e., TRANSFERS to the transition
from TransferOn to TransferOff. The event TRANSFERS will alternate every time the
Stateflow chart detects a rising or falling signal edge. The complete Stateflow Editor win-
dow appears as shown in Figure 1.55.

Step 5: Adding Triggering Capability to “wake up” the Stateflow Chart


a. As stated earlier, we must provide some means to “wake up” a Stateflow chart. This can
be achieved by sampling the chart at a specified or inherited rate, using a signal as a trig-
ger, or using one Stateflow chart to activate another. As we’ve learned in Step (g).4
above, the event TRANSFERS controls the transitions from the TransferOff state to the
TransferOn state, and vice versa. For this example, we need an edge trigger* to “wake up”
the chart at regular and very frequent time intervals. In the next step, we will define a sec-
ond edge−triggered input event which we will name CLOCK, to “wake up” the Stateflow
chart.

* When using edge triggers there can be a delay from the time the trigger occurs to the time the chart begins executing. Thus,
an edge trigger causes the chart to execute at the beginning of the next simulation time.

Introduction to Stateflow®with Applications 1−43


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.55. The complete Stateflow Editor window


b. We define the CLOCK event by double−clicking the Transfer Controller Stateflow block
in Figure 1.54, in the Stateflow Editor from the Add drop menu we add an input event by
selecting Event>Input from Simulink, in the Event properties dialog box we change the
Name field to CLOCK, the Port field to 2, the Trigger field to Either, and the Event dia-
log box now appears as shown in Figure 1.56. We click OK to accept these settings.

1−44 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.56. Event dialog box for the CLOCK signal


c. We may ponder why only one trigger port appears on top of the Stateflow chart while we
have defined two trigger ports, one for the TRANSFERS, Port 1, and the second for
CLOCK, Port 2. This poses no problem; the Mux block in the model in Figure 1.54 solves*
this problem by providing the necessary indexing into an array.
d. We connect the Mux block output to the trigger port of the Stateflow chart, we connect
the output of the Financial Operations subsystem to the input of the Stateflow chart, and
the output of the Stateflow chart to the top input of the Financial Operations subsystem.
Our model is now complete and it is named Example_1_1 as shown in Figure 1.57.

* When the Mux block is connected to the trigger port on top of the Stateflow chart, the index of the signals in the array is
associated with the numbered ports. Thus, the TRANSFERS signal at the top input port of the Mux block triggers the
event TRANSFERS on trigger Port 1 of the Stateflow chart block, and the CLOCK signal at the second input port of the
Mux block triggers the event CLOCK on trigger port 2 of the Stateflow chart block.

Introduction to Stateflow®with Applications 1−45


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.57. The complete model for Example 1.1


Step 6: Simulation of the Stateflow Chart
a. Before starting the simulation, it is recommended that we make sure there is a default
transition at every level of the Stateflow hierarchy that contains exclusive (OR) states,
that whenever possible, the input data objects inherit properties from the associated Sim-
ulink signal, and that output data objects do not inherit types and sizes because the values
are back propagated from Simulink and may be unpredictable.
b. To set the simulation parameters, we double−click the Transfer Controller block in Figure
1.57, in the Stateflow Editor window from the Simulation drop menu we select Configu-
ration Parameters, we click Solver in the left Select pane, and in the Simulation time
and Solver options panes we verify the selections shown in Figure 1.58, and we make
changes if necessary. We click OK to accept these values.

1−46 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.58. The Configuration Parameters dialog box


c. When a Simulink model that contains a Stateflow Chart block is simulated, we can ani-
mate the Stateflow Chart to highlight the states and the transitions as they occur, and
this feature provides visual verification that our chart behaves as expected. Animation is
enabled by default but we need to specify the speed. To make sure that the animation has
been enabled, in the Stateflow Editor window in Figure 1.55 from the Tools drop menu
we select Open Simulation Target, and this opens the Stateflow Target Builder dialog
box* shown in Figure 1.59.

* A target is a program that executes a Stateflow chart or a Simulink model that contains a Stateflow chart, and the State-
flow Target Builder dialog box in Figure 1.59 is used to configure Stateflow for building targets. Stateflow then builds a
simulation target (sfun) file that allows us to simulate our Stateflow application in Simulink.

Introduction to Stateflow®with Applications 1−47


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.59. The Target Builder window for selecting Target Options and Coder Options
d. In the Stateflow Target Builder dialog box in Figure 1.59, we click the Coder Options
button, and the Stateflow sfun Coder Options dialog box appears as shown in Figure 1.60,
where we observe that Enable debugging/animation is checked.

Figure 1.60. The Coder Options window to Enable debugging/animation

e. To set the animation speed, from the Stateflow Editor window in Figure 1.55 we click the

Debug tool and the Stateflow Debugging window appears as shown in Figure 1.61
where the Delay (sec) has been set to 1 sec so that the animation will proceed at the
slowest speed.

1−48 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.61. The Stateflow Debugging window to start simulation with breakpoints
f. To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in
the debugger to pause simulation during run−time activities. Breakpoints that can set are
listed below.

Breakpoint Description
Chart Entry Simulation halts when Stateflow chart “wakes up”
Event Broadcasta Simulation halts when an event such as TRANSFERS and / or CLOCK occurs.
State Entry Simulation halts when a state becomes active
a. To keep simulation running at a reasonable pace, we will not use Event Broadcast. Otherwise, simulation
would pause at every rising or falling edge of the TRANSFERS and CLOCK signals.

g. In the Stateflow Debugging window in Figure 1.61, we check Chart Entry and State
Entry as breakpoints and this window now appears as shown in Figure 1.62.

Introduction to Stateflow®with Applications 1−49


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.62. The Stateflow Debugging window with selected breakpoints


The option Browse Data in Figure 1.62 is a menu for observing data when simulation
pauses at a breakpoint. In the window of Figure 1.62 the Browse Data is inactive but it will
become active when simulation begins and halts at a breakpoint.
h. Before simulation begins, Stateflow builds the simulation target by performing the follow-
ing actions:
• Parses the Stateflow chart for errors such as no default transition at every level of the
Stateflow hierarchy that contains exclusive (OR) states, input data objects do not
inherit properties from the associated Simulink signal, and output data objects do
inherit types and sizes.
• Generates C code that represents the behavior of the Stateflow chart
• Builds the generated code into an executable program for the simulation target, referred
to as sfun target.
• Creates a directory referred to as sfprj in the directory where the chart resides to store
the generated files that make up the sfun target.
• Creates a MEX (MATLAB executable) file that corresponds to the C source file
During each of these processes, status messages are displayed at the MATLAB Command
Window.

1−50 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

i. We are now ready to begin simulation but before we issue the Start command in the
Stateflow Debugging window, we open the Scope block in the model of Figure 1.57, Page
1−46. We position the Scope block, the Stateflow Editor window, and the Stateflow
Debugger window so that all are visible as shown in Figure 1.63.

Figure 1.63. The Stateflow Editor, the Scope block, and the Stateflow Debugging windows for data observation
j. In the Stateflow Debugger window in Figure 1.63, we begin simulation by clicking the
Start button. We observe that the TransferOff state appears highlighted as part of the ani-
mation and it is shown in Figure 1.64. This indicates that the chart is “awaken” by the
CLOCK signal and the default transition arrow has activated the TransferOff state.

Introduction to Stateflow®with Applications 1−51


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.64. First indication that the Stateflow Chart is awaken


We notice also that the status panel at the upper part of the Stateflow Debugger window
shows the activities at the first breakpoint and that the Browse Data option is now
enabled as shown in Figure 1.65.

1−52 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.65. The Stateflow Debugger for continuing simulation


k. In the Stateflow Debugger window in Figure 1.65, we click the down arrow to the right of
the Browse Data option and we select Watched Data (Current Chart) from the drop
menu. The Stateflow Debugger window now appears as shown in Figure 1.66 and allows
us to view the value of the output of the Stateflow Chart, i.e., Payments.* We can also
view this value in the MATLAB Command window by pressing the Enter key at the
command prompt and MATLAB displays
debug>>
and at the command prompt we type Payments and MATLAB displays
Payments = 0
To view the value of the input of the Stateflow Chart, i.e, EndingBalance, at the com-
mand prompt debug>> we type EndingBalance and MATLAB displays
EndingBalance = 9.8252e+003
that is, the initial deposit of $10,000 in the checking account is now reduced to $9,825.20.

* We recall from Page 1−24, Payments was assigned a minimum value of 0 and a maximum value of 2.

Introduction to Stateflow®with Applications 1−53


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.66. Browse information for watched data in Stateflow Chart


l. To resume simulation, in the Stateflow Debugger window we uncheck the breakpoint
Chart Entry, and we click the Continue button repeatedly until the status panel at the
upper part of the Stateflow Debugger window indicates Simulink Time: 10.000000. We
click the Continue button one more time and we observe that the TransferOn state is
now active while the TransferOff state has returned to the inactive state as shown in Fig-
ure 1.67.

1−54 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.67. The activation of the TransferOn state after the rising edge of the TRANSFERS signal

m. We can speed through the rest of the simulation by unchecking all breakpoints, change
the Animation Delay to 0, and click the Continue button repeatedly. We observe that
eventually both the On states become active as shown in Figure 1.68, and when this
occurs, the Stateflow Debugger window indicates the maximum value of the output of
the Stateflow Chart, i.e., Payments = 2.*

* As described in Page 1−24, this is the maximum value and represents the condition where Overdraft On and Savings On
are both active.

Introduction to Stateflow®with Applications 1−55


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.68. The Stateflow Editor when both the Overdraft and Savings states are On
n. As we continue clicking the Continue button repeatedly, eventually the status panel at
the upper part of the Stateflow Debugger window indicates Simulink Time: 290.000000.
At this time the TRANSFERS signal from the Function Builder block returns to 0 and
the TransferOff state becomes active while the TransferOn state becomes inactive as
shown in Figure 1.69.

1−56 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.69. The deactivation of the TransferOn state after the falling edge of the TRANSFERS signal
o. We continue the simulation until we reach the 300 sec point (end of simulation time)
and we observe that the Stateflow chart goes back to “sleep”. At this time the Scope block
in the model of Figure 1.57, Page 1−46, displays the waveform shown in Figure 1.70, and
this waveform shows how the EndingBalance output of the Stateflow chart changes from
the start to the end of the simulation time.

Introduction to Stateflow®with Applications 1−57


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.70. The Scope block displaying the EndingBalance output

Step 7: Debugging the Stateflow Chart


In Step (a) below we will illustrate a procedure for debugging a state inconsistency error, and
in Step (b) a procedure for debugging data range violations.
a. We save the model as Example_1_1_Debug in the same directory, we double−click the
Transfer Controller to open the Stateflow chart, and we delete the default transitions to
Overdraft Off and Savings Off states by selecting them and pressing the Delete key.
We recall that there must be a default transition at every level of Stateflow hierarchy that
has exclusive (OR) decomposition, and thus removing the default transition will cause a
state inconsistency error. With both default transitions in state TransferOn, our Stateflow
Editor window now appears as shown in Figure 1.71.

1−58 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.71. The Stateflow Editor with missing default transitions

We open the Stateflow debugger by clicking the Debug tool to make sure that State
Inconsistency is checked in the Error checking options panel as shown in Figure 1.72.

Introduction to Stateflow®with Applications 1−59


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.72. The Stateflow Debugging window for checking State Inconsistencies

We save the chart and then we build it by clicking the Build tool in the Stateflow
Editor in Figure 1.71, and the window opens as shown in Figure 1.73 where we observe
that Stateflow has generated two coder warnings indicated by gray bullets. These warnings
indicate that two states identified by numbers #21and #22 have no unconditional path to
a substate and that the sources of the problems are Overdraft and Savings.
To locate the offending states, in the Stateflow Builder in Figure 1.73 we double−click
the coder warnings text or we can click the link to the state numbers in the status panel at
the bottom of the Stateflow Builder dialog box in Figure 1.73. Thus, if we double−click
#21, Stateflow highlights the Overdraft state in the Stateflow Editor chart as shown in Fig-
ure 1.74. Likewise, if we double−click #22, Stateflow highlights the Savings state in the
Stateflow Editor chart.
We add the default transitions to the Overdraft state and to the Savings state in the
Stateflow Editor chart, we build the chart again, and we observe that the chart builds suc-
cessfully without parser or code generation errors as shown in Figure 1.75.

1−60 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.73. The Stateflow Builder showing state inconsistencies

Introduction to Stateflow®with Applications 1−61


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.74. The Stateflow Editor after double−clicking Coder Warnings

1−62 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.75. The Stateflow Editor after removal of inconsistencies


We save the model as Example_1_1_Debug in preparation for the debugging data range
violations below.
b. In the Stateflow Editor window in Figure 1.74, we modify the during action in the Dollar-
Value state by adding 1 to it, that is, it now reads as
during: Payments=in(Overdraft.On)+in(Savings.On) +1;
as shown in Figure 1.76.

Introduction to Stateflow®with Applications 1−63


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.76. Stateflow Editor with data range violation

We open the Stateflow debugger by clicking the Debug tool , we uncheck all break-
points, under Error checking options we check Data Range, and the Stateflow Debug-
ging dialog box now appears as shown in Figure 1.77.

1−64 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.77. Stateflow debugger for detecting data range violations

We save the Stateflow Editor chart, we again build the chart, and the Stateflow Builder
window in Figure 1.78 reports no errors.

Introduction to Stateflow®with Applications 1−65


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.78. Stateflow Builder indicating no parsing errors

We return to the Stateflow Debugging dialog box in Figure 1.77 and we click the Start
button to begin simulation. To continue simulation we click the Continue button repeat-
edly, and after some time simulation pauses and Stateflow generates the Simulation Diag-
nostics window shown in Figure 1.79.

1−66 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.79. Simulation Diagnostics reporting Multiport Switch block error

To isolate the problem, we double click the Block error red bullet in the Simulation Diag-
nostics window in Figure 1.79, and this opens the Financial Operations subsystem shown
in Figure 1.80.

Introduction to Stateflow®with Applications 1−67


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Figure 1.80. Error indication in the Multiport Switch block of the Financial Operations subsystem

In Figure 1.80 we click the Launch Model Explorer tool and this opens the Model
Explorer window shown in Figure 1.81 where the properties of DollarValue are shown on
the right pane. Because the simulation is still running, this pane is read−only.

1−68 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Procedure for Creating a Stateflow Chart

Figure 1.81. Model Explorer window indicating data range violation

Introduction to Stateflow®with Applications 1−69


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

1.5 Summary
• A finite state machine is a model describing the behavior of a finite number of states, the transi-
tions between those states, and actions. A finite state machine can be represented either by a
state diagram or a state transition table.
• A state represents an operating mode of a machine, for instance, a typical household portable
space heater has four states, off, low, medium, and high.The on state is omitted because the
machine (space heater) must be on to operate in the low, medium, and high states.
• An action describes the activity that is to be performed. An action can be further classified as
an entry action which is performed when entering the state, an exit action which is performed
when exiting the state, and as a transition action which is performed during a transition.
• A condition is a Boolean expression that can be true (logic 1) or false (logic 0). In Stateflow,
conditions are enclosed in square brackets.
• An event is an action that can trigger a variety of activities. For example, in a typical household
space heater a switch allows a transition to occur between medium state and high state. Thus,
event driven systems allow the transition from one operating mode to another in response to
events and conditions. Event−driven systems can be implemented as finite−state machines.
• Stateflow provides us the necessary graphical objects to construct finite−state machines. Like
Simulink, we can drag and drop objects to create state−transition charts in which a series of
transitions directs a flow of logic from one state to another.
• Exclusive (OR) states are represented graphically by solid rectangles. No two or more Exclusive
(OR) states can be active or execute at the same time.
• Parallel (AND) states are represented graphically by dashed rectangles with a number in the
upper right corner. The numbers indicate the execution order. Two or more parallel (AND)
states at the same hierarchical level can be active at the same time but execute in serial fash-
ion.

• The unidirectional arrows represent transitions from one state to another


and specify the direction of the flow.
• When two or more Exclusive (OR) states that are on the same hierarchical level, we must
specify which is the default state. The default state is identified by an arrow with a solid dot tail
is directed towards that state. For this purpose this arrow is referred to as the default
transition.
• When the Stateflow chart is inactive, it is in a dormant state, and when the chart is first acti-
vated, the default transition makes the chart active. We usually use a clock signal to “wake up”
the chart.

1−70 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Summary

• A state action is an action whose execution is based on the status of the state.
• Entry actions are executed when the state is entered, i.e., when it first becomes active. The syn-
tax for entry actions is
entry: one or more actions;
en: one or more actions;
• During actions are executed while a state is active and no transition to another state exists. The
syntax for during actions is
during: one or more actions;
du: one or more actions;
• A condition is a Boolean expression that allows a transition to occur when the expression is
true. A condition is a text label for the transition and it is enclosed in square brackets ([ ]).
• An event is an object that can initiate several activities such as “waking up” a Stateflow chart,
transitions to occur from one state to another, and executions of actions.
• The recommended procedure for creating a Simulink model that contains one or more State-
flow charts is as follows:
1. Define the Interface to Simulink
a. Invoke MATLAB and from the main window select Simulink by clicking on the Sim-
ulink icon . This opens the Simulink Library Browser window.

b. In the Simulink Library Browser window click the Create a new model icon and
observe that a new empty model appears.
c. From the Simulink Library Browser window click and drag the Simulink blocks com-
prising the model into the empty Simulink model.
d. To create a subsystem, we enclose all blocks except the Inport and Outport blocks
within a bounding box, and from the Edit drop menu we choose Create Subsystem.
e. From the Simulink Library Browser window we click and drag a Chart block from the
Stateflow subnode under the Simulink Extras Library
f. To define the input of the Stateflow Chart block, we double−click this block, and from
the Stateflow Editor window that appears, from the Add drop menu we select
Data>Input from Simulink, and this opens the Data window. In the Name field that
appears under the General tab, we change the Name field to an appropriate name and
we leave other fields in their default values. We select the Value Attributes tab and
we check the Watch in debugger box. This allows us to observe the value of the name
that we selected at breakpoints during simulation.

Introduction to Stateflow®with Applications 1−71


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

g. To define the output of the Stateflow Chart block, we double−click this block, and
from the Stateflow Editor window that appears, from the Add drop menu we select
Data>Output to Simulink, and this opens the Data window. In the Name field that
appears under the General tab, we change the name to an appropriate name and we
leave other fields in their default values. We select the Value Attributes tab, for the
Limit range we specify appropriate values for Minimum and Maximum. We also
check the Watch in debugger box to allow us to observe the value of the name that we
selected at breakpoints during simulation.

2. Define the States for each Mode of Operation


a. In the Simulink model we double−click the Stateflow Chart block Transfer Controller
block and from the Stateflow Editor window that appears, from the object palette on

the left side of the Stateflow Editor window we click the State tool , we move it to
the drawing area, and we observe that it changes to a rectangle with rounded corners
and with a flashing text cursor at the upper left corner. This is a solid rectangle and it
represents an exclusive (OR) state.
b. At the flashing text cursor we enter a name appropriate for this state, e.g., PowerOn.

We click the State tool again and we draw another state below it, and we name it
appropriately, e.g., PowerOff.
d. In most applications we want to place parallel (AND) states within exclusive (OR)
states. To do this, from the Stateflow Editor we right−click inside the exclusive (OR)
state and from the submenu of Figure that appears we select Decomposition> Parallel

(AND). Then, we left−click the State tool in the Stateflow Editor and we place
the desired number of Parallel (AND) states inside the exclusive (OR) state. These
states appear as rectangles with rounded corners and dashed lines indicating that they
are parallel (AND) states. These parallel (AND) states display numbers in their upper
right corners. These numbers specify the order of execution during simulation. We
name the parallel (AND) states appropriately.
e. We now need to add an observer state whose purpose will be to monitor the status of the
parallel (AND) states inside an exclusive (OR) state. To do this, we left−click the State

tool again and we place another substate within the exclusive (OR) state and we
name it appropriately.
f. By default, Stateflow execution order is based on implicit ordering. This means that the
execution order of parallel states depends on their location on the chart. The priority is

1−72 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Summary

from top to bottom and then left to right. Thus, if for some reason a substate that is
originally located below another substate and then is relocated above it, this substate
attains the higher priority, the execution order is changed, and the simulation results
are altered. But it is possible to override the default and the execution order will be
based on explicit ordering. We specify explicit ordering by right−clicking a parallel
(AND) state inside an explicit (OR) state, in the state priorities submenu that
appears, we select Execution Order, and in the Chart window that appears we check
the User specified state/transition execution order field.
g. Normally, we add exclusive (OR) substates inside parallel (AND) states. For instance,

to add to opposing states, e.g., On and Off, we use the State tool to add two
exclusive (OR) substates inside a parallel (AND) state, and we name one of the exclu-
sive states On and the other Off.
3. Define State Actions and Variables
States perform actions at different phases of their execution cycle from the time they enter
the active phase to the time they re−enter the inactive phase. The three basic state actions
are listed in Table 1.3, Page 1−34.
4. Define Transitions Between States
a. In Stateflow, transitions are added to establish logic flow paths from one state, say A, to
another, say B, in a system. If state A is active and state B is inactive, and a transition
from state A to state B occurs, state A becomes inactive and state B becomes active.
Transitions are unidirectional and are represented by lines with arrowheads. As indi-
cated earlier in this chapter, the unidirectional arrows represent transitions from one
state to another and specify the direction of the flow. We recall that two exclusive
(OR) states cannot be active at the same time and therefore we must use transitions.
However, parallel (AND) states normally execute concurrently and thus we need not
add transitions.
b. To add a transition from one exclusive (OR) state to another opposing exclusive (OR)
state, e.g., PowerOff state to PowerOn state, we move the cursor over the top edge of
PowerOff state and we observe that the cursor shape changes to crosshairs. We hold
down the left mouse button, we drag the cursor to the bottom edge of the PowerOn
state, we release the mouse, and a transition pointing from the PowerOff to the Pow-
erOn state is formed. We follow the same procedure to create a transition from the Pow-
erOn state to the PowerOff state.
c. We also need to add default transitions. As stated earlier, since the On and Off states are
on the same hierarchical level, we must specify which is the default state, On or Off. Nor-
mally, we declare that the default states are Off. To add the default transitions, we left−

Introduction to Stateflow®with Applications 1−73


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

click the Default Transition tool , we move the cursor into the drawing area, and
we observe that it changes to a diagonal arrow. We place the cursor at the left edge of the
Off state and when the arrow assumes an horizontal direction, we release the mouse. The
default transition is now attached to the Off state and appears as a directed line with an
arrow at its head and a small filled−in circle at its tail.
e. We must specify a condition, action, or event that will allow the transition from one state
to another to occur. This is referred to as guarding a transition. Typical requirements for
guarding the transitions from one exclusive state to another are listed in Table 1.4, Page 1−
40. To add a condition, we click the transition arrow and we observe that the transition
appears highlighted and displays the question mark (?) character. We click the question
mark and where a blinking text cursor appears we type desired the expression, e.g., [Tem-
perature < 100].
f. Typically, an On state and an Off exclusive (OR) states must change from active to inactive
at regular intervals and for this to happen we must define an event that occurs at the rising
or falling edge of an input signal. We recall that an event is an non−graphical object that
triggers activities during the execution of a Stateflow chart. We add an input event from
the Add drop menu in the Stateflow Editor by selecting Event>Input from Simulink and
this opens an Event properties dialog window. We change the Name field from event to an
appropriate name, we select the Port number, and from the Trigger field we choose Rising,
Falling, or Either.
g. We need to associate an input event with the transitions. To do this, we open the Stateflow
Editor, we click the transition, say from the Off state to the On state, we click the question
mark to obtain a text editor, and we type the appropriate name, and this event will alter-
nate every time the Stateflow chart detects a rising, falling, or either signal edge as we have
specified in Step 4(f) above.

5. Adding Triggering Capability to “wake up” the Stateflow Chart


a. We must provide some means to “wake up” a Stateflow chart at regular and very fre-
quent time intervals. This can be achieved with a CLOCK signal at a specified fre-
quency.
b. It is possible to define two or more trigger ports with only one trigger port input on top
of a Stateflow chart. This can be done by using a Mux block to provide the necessary
indexing.
6. Simulation of the Stateflow Chart
a. Before starting the simulation, it is recommended that we make sure there is a default
transition at every level of the Stateflow hierarchy that contains exclusive (OR) states,
that whenever possible, the input data objects inherit properties from the associated

1−74 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Summary

Simulink signal, and that output data objects do not inherit types and sizes because the
values are back propagated from Simulink and may be unpredictable.
b. To set the simulation parameters, we double−click the Stateflow Chart block, from the
Simulation drop menu in the Stateflow Editor window we select Configuration
Parameters, we click Solver in the left Select pane, and in the Simulation time and
Solver options panes we verify our selections and we make changes if necessary.
c. When a Simulink model that contains a Stateflow Chart block is simulated, we can
animate the Stateflow Chart to highlight the states and the transitions as they occur,
and this feature provides visual verification that our chart behaves as expected. Ani-
mation is enabled by default but we need to specify the speed. To make sure that the
animation has been enabled, from the Tools drop menu in the Stateflow Editor win-
dow we select Open Simulation Target, and this opens the Stateflow Target Builder
dialog box. In the Stateflow Target Builder dialog box we click the Coder Options
button, and the Stateflow sfun Coder Options dialog box appears where we observe
that Enable debugging/animation is checked.
d. To set the animation speed, from the Stateflow Editor window we click the Debug tool

and the Stateflow Debugging window appears. For the animation to proceed at
the slowest speed, we set the Delay (sec) to 1 sec.
e. To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints
in the debugger to pause simulation during run−time activities. We set breakpoints as
follows:
In the Stateflow Debugging window we check Chart Entry and State Entry as break-
points. The option Browse Data i is a menu for observing data when simulation pauses
at a breakpoint. Initially, the Browse Data is inactive but it will become active when
simulation begins and halts at a breakpoint.
Before simulation begins, Stateflow builds the simulation target parses the Stateflow
chart for errors such as no default transition at every level of the Stateflow hierarchy
that contains exclusive (OR) states, input data objects do not inherit properties from
the associated Simulink signal, and output data objects do inherit types and sizes.
Then, it generates C code that represents the behavior of the Stateflow chart and
builds the generated code into an executable program for the simulation target,
referred to as sfun target. Next, it creates a directory referred to as sfprj in the directory
where the chart resides to store the generated files that make up the sfun target.
Finally, it creates a MEX (MATLAB executable) file that corresponds to the C source
file.
During each of these processes, status messages are displayed at the MATLAB Com-
mand Window.

Introduction to Stateflow®with Applications 1−75


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

f. With the Stateflow Debugger window visible, we begin simulation by clicking the Start
button. We observe that the Off state appears highlighted as part of the animation This
indicates that the chart is “awaken” by a CLOCK signal, if present, and the default tran-
sition arrow has activated the Off state. We notice that the status panel at the upper
part of the Stateflow Debugger window shows the activities at the first breakpoint and
that the Browse Data option is now enabled.
g. In the Stateflow Debugger window we click the down arrow to the right of the Browse
Data option and we select Watched Data (Current Chart) from the drop menu. The
Stateflow Debugger window now appears and allows us to view the value of the output
of the Stateflow Chart, i.e., the output name that we defined earlier. We can also view
this value in the MATLAB Command window by pressing the Enter key at the com-
mand prompt and MATLAB displays
debug>>
and at the command prompt we type the output name.
To view the value of the input of the Stateflow Chart at the command prompt
debug>> we type the input name that we defined earlier.
h. To resume simulation, in the Stateflow Debugger window we uncheck the breakpoint
Chart Entry, and we click the Continue button. We can speed through the rest of the
simulation by unchecking all breakpoints, change the Animation Delay to 0 and click
the Continue button repeatedly. We observe that eventually the On state becomes
active and when this occurs, the Stateflow Debugger window now indicates the maxi-
mum value of the output of the Stateflow Chart.
i. As we continue clicking the Continue button repeatedly, eventually the status panel at
the upper part of the Stateflow Debugger window indicates the ending time in the
Simulink Time field. At this time the signal from the Function Builder block returns
to 0 and the Off state becomes active while the On state becomes inactive, and when
the simulation time reaches its maximum value, the Stateflow chart goes back to
“sleep”.
7. Debugging the Stateflow Chart
We can debug a Stateflow chart for errors such as inconsistency errors, and for debugging
data range violations.
a. To check for inconsistency errors, we open the Stateflow Editor window and we invoke

the Stateflow debugger by clicking Debug tool to make sure that State Inconsis-
tency is checked in the Error checking options panel. In the Stateflow Editor window
we click the Build tool in the Stateflow Editor, and the Stateflow Builder window
opens. If inconsistency errors are present, Stateflow generates coder warnings indicated

1−76 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Summary

by gray bullets. These warnings indicate that states identified by some numbers have
no unconditional path to one or more substates. To locate the offending states in the
Stateflow Builder window chart, we double−click the coder warnings text or we click
the link to the state numbers in the status panel at the bottom of the Stateflow
Builder dialog box, and Stateflow highlights the offending states in the Stateflow Edi-
tor chart.
After making the necessary corrections, we build the chart again, to make sure that the
chart builds successfully without parser or code generation errors.

b. To check for data range violations, we open the Stateflow debugger by clicking the

Debug tool , we uncheck all breakpoints, under Error checking options we check
Data Range, and the Stateflow Debugging dialog box appears, and the Stateflow
Builder window reports no errors. We return to the Stateflow Debugging dialog box in
and we click the Start button to begin simulation. To continue simulation we click the
Continue button repeatedly, and if a data range violation exists, after some time simula-
tion pauses and Stateflow generates the Simulation Diagnostics window.
To isolate the problem, we double click the Block error red bullet in the Simulation Diag-
nostics window and this opens the offending state, block, or subsystem, and we click the
Launch Model Explorer tool . This opens the Model Explorer window and the
source of the problem is shown on the right pane. If the simulation is still running, this
pane is read−only.

Introduction to Stateflow®with Applications 1−77


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

1.6 Exercise for the Reader


ABC Company manufactures PC boards and these are sold to several computer assembly compa-
nies. The daily orders and quantities for boards vary significantly, and for this reason ABC Com-
pany maintains three working shifts, first, second, and graveyard shift. Statistics show that, on a
weekly basis, the minimum number of boards delivered is 5,000 while the maximum is 15,000.
Create a Simulink model that includes a Stateflow chart to schedule the number of shifts based
on the quantities shown below so that the company will meet the promised delivery dates to its
customers.

First shift: Less than 5,000 boards


First shift + 2 hours overtime: 5,000 or more but less than 8,000 boards
Second shift: 8,000 or more but less than 12,000 boards
Graveyard shift: 12,000 or more boards

1−78 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

1.7 Solution to the End−of−Chapter Exercise


Assumptions:
1. The manufacturing plant will be a Simulink subsystem with two inputs and one output as
shown by the block diagram below.

production
boards
max

Manufacturing Plant

2. The max input represents the maximum number of boards that can be manufactured in a
given time period and we will assume a maximum number of 15,000 boards.
3. A provision will be made for manpower. This is a measure of the number of employees
expected to be present minus the number of employees absent, e.g., on vacation or sick leave.
We will represent manpower with a Gain block that provides a constant multiplier that is
used in computing the actual number of employees in the manufacturing plant over a given
period. For this constant multiplier we will assume a value of 0.025.
4. Normally, the first shift is considered to be the most productive while the graveyard shift is
the least productive. For productivity we will be using a constant multiplier derived from the
value of production that will be the output from the Stateflow Chart block, and the Stateflow
Chart will assign one of four productivity factors each with a value that will serve as an index
into a Multiport Switch block. Using this index, the Multiport Switch block will select a pro-
ductivity multiplier that is directly proportional to the productivity factor.
The productivity multiplier for each shift is shown in the table below.

Productivity by Shift Productivity Number Productivity Multiplier


First Shift ON − No Overtime 0 0.00
First Shift ON 2−hr Overtime 1 −0.05
The number of the Boards produced is
lowered by the productivity multiplier −0.05
Second Shift ON 2 −0.10
The number of the Boards produced is
lowered by the productivity multiplier −0.10
Graveyard Shift ON 3 −0.02
The number of the Boards produced is
lowered by the productivity multiplier −0.02

Introduction to Stateflow®with Applications 1−79


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

5. The manufacturing plant computes the number of manufactured boards taking into consider-
ation the manpower multiplier and the productivity multiplier. The output boards of the
manufacturing plant changes with time and we represent this change as board_change where
its value is computed from the expression
boards_change = [ ( max – boards ) × manpower multiplier ] +
[ ( max – boards ) × productivity multiplier ]
and the summation of those changes will be performed with an Integrator block with an
assumed initial value 2,000, that is,
t
boards ( t ) = ∫t ( boards_change ) dt + 2000
0

6. Simulation time will be 300 sec.


7. The Stateflow Chart needs to monitor the number of boards produced by the manufacturing
plant at regular intervals. Therefore, we will use a CLOCK signal that will be provided by a
Signal Builder block and the Stateflow Chart will include an edge trigger event that will
“wake−up” the chart at the rising or falling edge of the clock. The Signal Builder block will
also provide a pulse signal named SWITCH to activate the Stateflow Chart to On and Off.
The CLOCK signal will be a square wave with the following settings:
Frequency: 1.0
Amplitude: 1.0
Offset: 1.0
% Duty cycle: 50%
The SWITCH signal will be a pulse of duration 25 sec with rising edge at 25 sec and falling
edge at 50 sec.

We begin by typing sfnew* at the MATLAB Command prompt, and we observe that a new unti-
tled Simulink model opens with a Stateflow chart. We invoke the Simulink Library Browser
window and we click and drag the following Simulink blocks into the empty Simulink model with
the Stateflow chart:
Four Constant blocks, a Product block, a Gain block, an Integrator block, two Inport blocks
and an Outport block from the Commonly Used Blocks Library, and a Multiport Switch from
the Signal Routing Library. The Constant blocks and the Gain block perform the functions
described by the annotations.
We click the Integrator block and we specify the initial condition as 0 . We interconnect these
blocks as shown below.

* This is a shortcut for adding a Stateflow block to a new Simulink model.

1−80 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

To create a subsystem, we enclose all blocks, except the Inport and Outport blocks, within a
bounding box, from the Edit drop menu we choose Create Subsystem, we reshape the intercon-
necting lines, and we label it as Manufacturing Plant. We double−click the subsystem block and
we rename the Inport and Outport blocks as production, max, and boards, and the components
of the subsystem appear as shown below.

Introduction to Stateflow®with Applications 1−81


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Our Simulink model now appears as shown below.

We stretch the window of the model above and we add the following blocks:

1−82 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

A Signal Builder block from the Sources Library.


A Mux block (heavy vertical bar) from the Commonly Used Blocks Library
A Scope block from the Commonly Used Blocks Library
A Constant block from the Commonly Used Blocks Library
The model now appears as shown below.

We double−click the Signal Builder block and the waveform shown below appears.

Introduction to Stateflow®with Applications 1−83


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

g. From the Axes drop menu we select Change Time Range, we set Min time to 0, Max
time to 300, we change the name field from Signal 1 to SWITCH, we click on the rising
(left) edge of the waveform to select it,* in the T: field under Left Point we enter 10, we
click the falling (right) edge of the waveform to select it, in the T: field under Left Point we
enter 290, and we click OK to accept it. The waveform of the Signal Builder block is now
as shown below.

* When properly selected, it appears as a heavy red line and the fields in the lower part of the window become active

1−84 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

From the Signal drop menu in the Signal Builder window above we select New and from it we
choose Square Wave. In the Square Wave dialog box below we enter the parameters shown.

We change the name field to CLOCK, we click OK to accept these values, and the Signal
Builder block now appears as shown below.

Introduction to Stateflow®with Applications 1−85


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

The SWITCH signal is used to allow transitions to occur between the states AddShiftOff and
AddShiftOn (to be defined shortly), at each rising or falling edge of a pulse signal, and the CLOCK
is used to “wake up” the Stateflow chart at each rising or falling edge of a square wave signal.
To define the input of the Stateflow Chart block in the model shown on Page 1−83, we double−
click this block, and we observe that the Stateflow Editor window appears as shown below.

1−86 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

From the Add drop menu of the Stateflow Editor above, we select Data>Input from Simulink,
and this opens the Data window shown below.

In the Name field that appears under the General tab of the Data dialog box above, we change
the name to boards and we leave other fields in their default values. We select the Value
Attributes tab and we check the Watch in debugger box. This will allow us to observe the value
of boards at breakpoints during simulation.

Introduction to Stateflow®with Applications 1−87


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

To define the output of the Stateflow Chart block in the model shown on Page 1−83, we double−
click this block, and we observe that the Stateflow Editor window appears as shown in the previ-
ous page. From the Add drop menu we select Data>Output to Simulink, and this opens the
Data window shown in the previous page.
In the Name field that appears under the General tab, we change the name to production and we
leave other fields in their default values. We select the Value Attributes tab, for the Limit range
we specify 0 for Minimum and 3 for Maximum, where 0 will represents first shift−no overtime, 1
will represent first shift 2−hr overtime On, 2 will represent second shift On, and 3 will represent
graveyard shift On. We also check the Watch in debugger box to allow us to observe the value of
production at breakpoints during simulation.
Our Simulink model should now look like that shown below where we have renamed the State-
flow Chart block Shift Controller.

In the Simulink model above, we double−click the Shift Controller block and the Stateflow Editor
window appears as shown below.

1−88 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

From the object palette on the left side of the Stateflow Editor window above we click the State

tool , we move it to the drawing area, and we observe that it changes to a rectangle with
rounded corners and with a flashing text cursor on the upper left corner as shown below. This is
a solid rectangle and it represents an exclusive (OR) state.

Introduction to Stateflow®with Applications 1−89


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

At the flashing text cursor we enter AddShiftOn to name this state,* and we stretch the rectangle.
The Stateflow editor window now appears as shown below.

We click the State tool again and we draw a smaller state below the AddShiftOn state, and
we name it AddShiftOff. The Stateflow Editor window now appears as shown below.

* We can change the text size by choosing the Set Font Size from the Edit drop menu.

1−90 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

In the Stateflow Editor window above we right−click inside the AddShiftOn state and from the
pop−up menu below we select Decomposition> Parallel (AND).

Introduction to Stateflow®with Applications 1−91


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We left−click the State tool in the Stateflow Editor window in the previous page and we
place three states inside the AddShiftOn state. We observe that these three states appear as rect-
angles with rounded corners and dashed lines indicating that they are parallel (AND) states. We
also observe that these parallel states display numbers in their upper right corners. These numbers
specify the order of execution during simulation. We name these parallel states Overtime, Sec-
ond, and Graveyard, and the Stateflow Editor window now appears as shown below.

1−92 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

We now need to add an observer state whose purpose will be to monitor the status of the Over-
time, Second, and Graveyard states.

We left−click the State tool and we place another parallel (AND) substate within the
AddShiftOn state under the Overtime, Second, and Graveyard states. We name this substate
BoardNumber and the Stateflow Editor appears as shown below.

Introduction to Stateflow®with Applications 1−93


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We recall that, by default, Stateflow execution order is based on implicit ordering. This means that
the execution order of parallel states depends on their location on the chart. The priority is from
top to bottom and then left to right. Thus, if for some reason the Savings substate is moved to the
left and the Overdraft substate is moved to its right, the Savings substate attains the highest pri-
ority, the execution order is changed, and the simulation results are altered. But it is possible to
override the default and the execution order will be based on explicit ordering. We will do this with
the next step.
We right−click inside the Overtime parallel state within the AddShiftOn exclusive (OR) main
state to call the state priorities pop−up menu below, we select Execution Order.

1−94 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

In the Chart window that appears below we check the User specified state/transition execu-
tion order field as shown. We click OK to accept these settings.

Introduction to Stateflow®with Applications 1−95


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We right−click again and from the Execution Order we choose the assignment order shown in
below.
We repeat these steps for the Second, Graveyard, and BoardNumber parallel states.

1−96 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

Using the State tool we add two exclusive (OR) substates inside the Overtime, Second,
and Graveyard states. Inside the parallel Overtime, Second, and Graveyard states, we name one
of the exclusive states On and the other Off. The Stateflow chart now appears as shown below.

Introduction to Stateflow®with Applications 1−97


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We recall that states perform actions at different phases of their execution cycle from the time
they enter the active phase to the time they re−enter the inactive phase. For convenience, the
three basic state actions are repeated in the table below.

Type When Executed Frequency of Execution


while State is Active
Entry When state becomes active Once (to initialize data)
During While the state is active and no valid At every time step (to update data)
transition to another state is available
Exit Before transition to another state Once (to re−configure data for the
next transition)

We left−click inside the AddShiftOff state after the last letter of its name to cause a blinking text
cursor to appear. We press the Enter key and we type

1−98 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

entry: production=0;
The Stateflow Editor now appears as shown below.

We also need to add a during action for BoardNumber in the fourth parallel state within the
AddShiftOn state, that is, a Boolean expression to specify whether no Graveyard, no Second,
and no Overtime has occurred, or only Overtime has occurred, or Overtime and Second have
occurred, or all three Overtime, Second, and Graveyard have occurred. We click inside the
BoardNumber state after the last letter of its name to cause a blinking text cursor to appear. We
press the Enter key and we type
during: production = in(Overtime.On) + in(Second.On) + in(Graveyard.On);
The Boolean expression in(Overtime.On) can be true or false. If true, its value is 1 and Overtime
is active. If false, its value is 0 and Overtime is inactive. Likewise, the Boolean expressions
in(Second.On) and in(Graveyard.On) can be true or false. Accordingly, the sum of these Boolean
expressions indicates whether no Graveyard, no Second, and no Overtime has occurred, or only

Introduction to Stateflow®with Applications 1−99


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Overtime has occurred, or Overtime and Second have occurred, or all three Overtime, Second,
and Graveyard have occurred. The Stateflow Editor window now appears as shown below.

We need to add a transition from the AddShiftOff to the AddShiftOn state. To do this, we move
the cursor over the top edge of AddShiftOff and we observe that the cursor shape changes to
crosshairs. We hold down the left mouse button, we drag the cursor to the bottom edge of the
AddShiftOn state, we release the mouse, and a transition pointing from the AddShiftOff to the
AddShiftOn state is formed. We follow the same procedure to create a transition from the
AddShiftOn to the AddShiftOff state and the Stateflow Editor window now appears as shown
below.

1−100 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

Following the procedure above we add transitions between the Off and On states for the Over-
time, Second, and Graveyard states, and the Stateflow Editor window appears as shown below.

Introduction to Stateflow®with Applications 1−101


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We also need to add default transitions. As stated earlier, since the On and Off states are on the
same hierarchical level, we must specify which is the default state, On or Off. For this exercise, we
declare that the default states are Off. To add the default transitions we left−click the Default

Transition tool , we move the cursor into the drawing area, and we observe that it changes
to a diagonal arrow. We place the cursor a the left edge of the AddShiftOff state and when the
arrow assumes an horizontal direction, we release the mouse. The default transition is now
attached to the AddShiftOff state and appears as a directed line with an arrow at its head and a
small filled−in circle at its tail.* Using the same procedure we add default transitions at the top
edges of Overtime.Off, Second.Off, and Graveyard.Off states as shown below.

* The entire default transition arrow must be placed inside the state that it activates.

1−102 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

Next, we must specify a condition, action, or event that will allow the transition from one state
to another to occur. This is referred to as guarding a transition, and for our example the require-
ments for guarding the transitions from one exclusive state to another are listed in the table
below.

Introduction to Stateflow®with Applications 1−103


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Transition Occurrence Guarding


AddShiftOff to AddShiftOn At regular time intervals Specify an edge−triggered event
AddShiftOn to AddShiftOff At regular time intervals
Overtime.Off to Overtime.On When the orders are for 5000 or Specify a condition based on
more boards the number of boards ordered
Overtime.On to Overtime.Off When the orders are for less than
5000 boards
Second.Off to Second.On When the orders are for 8000 or
more boards
Second.On to Second.Off When the orders are for less than
8000 boards
Graveyard.Off to Graveyard.On When the orders are for 12000 or
more boards
Graveyard.On to Graveyard.Off When the orders are for less than
12000 boards

In the Stateflow Editor window, we click the transition from Overtime.Off to Overtime.On and
we observe that the transition appears highlighted and displays the question mark (?) character.
We click the question mark and where a blinking text cursor appears we type the expression
[boards >= 5000].* Using the same procedure we add the following conditions to the other transi-
tions in Second and Graveyard.

Transition Condition
Overtime.On to Overtime.Off [boards < 5000]
Second.On to Second.Off [boards < 8000]
Second.Off to Second.On [boards > = 8000]
Graveyard.On to Graveyard.Off [boards < 12000]
Graveyard.Off to Graveyard.On [boards > = 12000]

The Stateflow Editor window now appears as shown below.

* For readability, it may be necessary to reposition the condition. We do this by clicking outside the condition, then we left−
click and drag the condition expression to a new position. Also, as stated earlier, we can change the text size by choosing the
Set Font Size from the Edit drop menu.

1−104 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

In the Stateflow Editor window above, the AddShiftOn and AddShiftOff exclusive (OR) states
must change from active to inactive at regular intervals and for this to happen we must define an
event that occurs at the rising or falling edge of an input signal. We recall that an event is an
non−graphical object that triggers activities during the execution of a Stateflow chart. We add
an input event from the Add drop menu by selecting Event>Input from Simulink in the State-
flow Editor window above and this opens the Event properties dialog window shown below.

Introduction to Stateflow®with Applications 1−105


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We change the Name field from event to SWITCH, we select Port 1, and the Trigger field from
Rising to Either. The updated Event dialog box now appears as shown below.

We click OK to accept these changes and the dialog box closes. Our Simulink model now
appears as shown below where we observe that a trigger port appears on top of the Stateflow
block as shown in the model below. We save this model as Exercise_1_1.

1−106 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

The next step is to associate the input event SWITCH with the transitions. We double−click the
Shift Controller Stateflow chart in the model above to open the Stateflow Editor window, we
click the transition from the AddShiftOff state to the AddShiftOn state, we click the question
mark to obtain a text editor, and we type the name SWITCH. We repeat this step to add the
same event, i.e., SWITCH to the transition from AddShiftOn state to TransferOff state. The
event SWITCH will alternate every time the Stateflow chart detects a rising or falling signal edge.
The completed Stateflow Editor window appears as shown below.

Introduction to Stateflow®with Applications 1−107


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

The final step to complete our model is to provide some means to “wake up” the Stateflow chart.
This can be achieved by sampling the chart at a specified or inherited rate, using a signal as a trig-
ger, or using one Stateflow chart to activate another. As we’ve learned in Step(g).4 above, the
event SWITCH controls the transitions from the AddShiftOff state to the AddShiftOn state, and
vice versa. For this example, we need an edge trigger* to “wake up” the chart at regular and very
frequent time intervals. In the next step, we will define a second edge−triggered input event
which we will name CLOCK, to “wake up” the Stateflow chart.
We define the CLOCK event by double−clicking the Shift Controller Stateflow block in the model
of in the previous page, in the Stateflow Editor from the Add drop menu we add an input event
by selecting Event>Input from Simulink, in the Event properties dialog box we change the
Name field to CLOCK, the Port field to 2, the Trigger field to Either, and the Event dialog box
now appears as shown below. We click OK to accept these settings.

* When using edge triggers there can be a delay from the time the trigger occurs to the time the chart begins executing. Thus,
an edge trigger causes the chart to execute at the beginning of the next simulation time.

1−108 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

We connect the Mux block output to the trigger port of the Stateflow chart, we connect the out-
put of the Manufacturing Plant subsystem to the input of the Stateflow chart, and the output of
the Stateflow chart to the top input of the Manufacturing Plant subsystem. Our model is now
complete and it is named Example_1_1 as shown below.

Introduction to Stateflow®with Applications 1−109


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

Before starting the simulation, it is recommended that we make sure there is a default transition
at every level of the Stateflow hierarchy that contains exclusive (OR) states, that whenever possi-
ble, the input data objects inherit properties from the associated Simulink signal, and that output
data objects do not inherit types and sizes because the values are back propagated from Simulink
and may be unpredictable.
To set the simulation parameters, we double−click the Shift Controller block in the model of the
previous page, in the Stateflow Editor window from the Simulation drop menu we select Config-
uration Parameters, we click Solver in the left Select pane, and in the Simulation time and
Solver options panes we verify the selections shown below, and we make changes if necessary.
We click OK to accept these values.

When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the
Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides
visual verification that our chart behaves as expected. Animation is enabled by default but we
need to specify the speed. To make sure that the animation has been enabled, in the Stateflow
Editor window from the Tools drop menu we select Open Simulation Target, and this opens the
Stateflow Target Builder dialog box shown below.

1−110 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

In the Stateflow Target Builder dialog box above, we click the Coder Options button, and the
Stateflow sfun Coder Options dialog box appears as shown below, where we observe that
Enable debugging/animation is checked.

To set the animation speed, from the Stateflow Editor window we click the Debug tool and
the Stateflow Debugging window appears as shown below where the Delay (sec) field has been
set to 1 sec so that the animation will proceed at the slowest speed.

Introduction to Stateflow®with Applications 1−111


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the
debugger to pause simulation during run−time activities. Breakpoints that can set are listed
below.

Breakpoint Description
Chart Entry Simulation halts when Stateflow chart “wakes up”
Event Broadcasta Simulation halts when an event such as TRANSFERS and / or CLOCK occurs.
State Entry Simulation halts when a state becomes active
a. To keep simulation running at a reasonable pace, we will not use Event Broadcast. Otherwise, simulation
would pause at every rising or falling edge of the TRANSFERS and CLOCK signals.

In the Stateflow Debugging window above, we check Chart Entry and State Entry as break-
points and this window now appears as shown below.

1−112 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

The option Browse Data in the Stateflow Debugging window above is a menu for observing
data when simulation pauses at a breakpoint. In the window above, the Browse Data is inactive
but it will become active when simulation begins and halts at a breakpoint.
We recall that before simulation begins, Stateflow builds the simulation target by performing the
following actions:
• Parses the Stateflow chart for errors such as no default transition at every level of the
Stateflow hierarchy that contains exclusive (OR) states, input data objects do not inherit
properties from the associated Simulink signal, and output data objects do inherit types
and sizes.
• Generates C code that represents the behavior of the Stateflow chart
• Builds the generated code into an executable program for the simulation target, referred
to as sfun target.
• Creates a directory referred to as sfprj in the directory where the chart resides to store the
generated files that make up the sfun target.
• Creates a MEX (MATLAB executable) file that corresponds to the C source file
During each of these processes, status messages are displayed at the MATLAB Command Win-
dow.

Introduction to Stateflow®with Applications 1−113


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We are now ready to begin simulation but before we issue the Start command in the Stateflow
Debugging window in the previous page, we open the Scope block in the model of Page 1−109.
We position the Scope block, the Stateflow Editor window, and the Stateflow Debugger win-
dow so that all are partially visible about as shown below.

1−114 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

Introduction to Stateflow®with Applications 1−115


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

In the Stateflow Debugger window above, we begin simulation by clicking the Start button. We
observe that the TransferOff state appears highlighted as part of the animation and it is shown in
Figure 1.64. This indicates that the chart is “awaken” by the CLOCK signal and the default tran-
sition arrow has activated the TransferOff state.

We notice also that the status panel at the upper part of the Stateflow Debugger window shows
the activities at the first breakpoint and that the Browse Data option is now enabled as shown
below.

1−116 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

In the Stateflow Debugger window above, we click the down arrow to the right of the Browse
Data option and we select All Data (Current Chart) from the drop menu. The Stateflow
Debugger window now appears as shown below and allows us to view the value of the output of
the Stateflow Chart, i.e., production.* We can also view this value in the MATLAB Command
window by pressing the Enter key at the command prompt and MATLAB displays
debug>>
and at the command prompt we type production and MATLAB displays
production = 0
To view the value of the input of the Stateflow Chart, i.e, boards, at the command prompt
debug>> we type boards and MATLAB displays
boards = 186.3330

that is, at this time, the approximate number of boards produced is 186.†

* We recall from Pages 1−79, 1−88 and 1−99 that production was assigned a minimum value of 0 and a maximum value
of 3.
† We recall that the initial condition in the Integrator block inside the Manufacturing Plant subsystem was set to 0.

Introduction to Stateflow®with Applications 1−117


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

To resume simulation, in the Stateflow Debugger window above we uncheck the breakpoint
Chart Entry, and we click the Continue button repeatedly until the status panel at the upper
part of the Stateflow Debugger window indicates Simulink Time: 25.000000. We click the
Continue button once more and we observe that number of boards produced is 6,971 as indi-
cated in the Stateflow Debugger window below, and we also observe that in the Stateflow Editor
window the AddShift On state is now active while the AddShiftOff state has returned to the inac-
tive state as shown below.

1−118 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

Introduction to Stateflow®with Applications 1−119


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

We can speed through the rest of the simulation by unchecking all breakpoints, change the Ani-
mation Delay to 0 and click the Continue button repeatedly. We observe that when the simula-
tion time reaches 25.5 seconds, the Stateflow Debugger window indicates that the number of
boards produced is 6,870, and that the production has changed from 0 to 1. At this time, the
AddShift.On state becomes active as shown below, because the number of boards produced is
greater than 5,000.

As we continue clicking the Continue button repeatedly, eventually the status panel at the upper
part of the Stateflow Debugger window indicates Simulink Time: 50.000000. At this time the
SWITCH signal from the Function Builder block returns to 0 and the AddShiftOff state becomes
active while the AddShiftOn state becomes inactive as shown below.

1−120 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Solution to the End−of−Chapter Exercise

We continue the simulation until we reach the 300 second point (end of simulation time) and
we observe that the Stateflow chart goes back to “sleep”. At this time the Scope block displays
the waveform shown below. This waveform indicates that until the AddShiftOn state becomes
active, the number of boards produced increases unchecked. However, after 25 seconds into the
simulation, the rising edge of the SWITCH signal from the Signal Builder block switches the
AddShiftOn state On and until the falling edge of SWITCH signal at 50 seconds the number of
boards produced remains relatively constant around 5,000 boards. Then the number of boards
produced begins to rise again towards the 15000 limit indicated by the Constant block input to
the Manufacturing Plant subsystem. It is the CLOCK signal that causes the monotonic increase
to about 15,000 boards.
Because the SWITCH pulse width was defined with only 25 seconds duration starting at 25 sec-
onds and ending at 50 seconds, the Second and Graveyard states never switched from the Off to
the On states. The reader is invited to define a wider pulse width for the SWITCH signal and
repeat the simulation.

Introduction to Stateflow®with Applications 1−121


Copyright © Orchard Publications
Chapter 1 The Stateflow Chart

1−122 Introduction to Stateflow®with Applications


Copyright©Orchard Publications
Chapter 2
The Stateflow Truth Table

T
his chapter describes the basic workflow for building Stateflow truth tables to form deci-
sion−making behavior, and how it works with Simulink blocks. We discuss the Truth
Table block that can be added directly to a Simulink model, and the Truth Table that can
be called from a Stateflow Chart block.

2.1 Truth Tables in Stateflow


A Stateflow truth table represents logical decision−making behavior with conditions, decisions, and
actions. As in Chapter 1 where a Stateflow Chart block is inserted as a block in a Simulink model,
a Truth Table block can also be added to a Simulink model to call a truth table function. A
Truth Table block consists of a Condition Table column and two or more Decision columns
denoted as D1, D2, and so on, and an Action Table below the Condition Table with a Descrip-
tion column and Action columns as shown in Table 2.1 below.

TABLE 2.1 Truth Table arrangement in Stateflow


Condition Table
Description Condition D1 D2 D3 D4 ...... DN
A is logical 1 A == 1 T −
B is logical 1 B == 1 T −
C is logical 1 C == 1 T −
D is logical 1 D == 1 T −
..............
Action Table
Description Action t=1
t=2
t=3
t=4
.......

The table above implements the function


t = ttable ( A, B, C, D )

In Table 2.1 above, each of the conditions entered in the Condition column must evaluate to
true (nonzero value) or false (zero value). Outcomes for each condition are specified as T (true),

Introduction to Stateflow®with Applications 2−1


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

F (false), or − (true or false). Each of the Decision columns combines an outcome for each condi-
tion with a logical AND into a compound condition, that is referred to as a decision.

The truth table is evaluated as one decision at a time, beginning with Decision 1. If one of the
decisions is true, we perform its action and truth table execution is complete. For example, if
Conditions 1 and 2 are false and Condition 3 is true, Decision 3 is true and the variable t is set
equal to 3. The remaining decisions are not tested and evaluation of the truth table is finished.
The last decision, denoted as DN in Table 2.1, is the Default Decision, and covers all possible
remaining decisions. If Decisions 1, 2, 3, 4, D N – 1 are false, then the Default Decision is auto-
matically true and its action (t = n) is executed. The Default Decision must be the last decision
on the right with an entry of − for all conditions in the decision where − denotes any outcome for
the condition.
The evaluation of t = k k = 1, 2, …, n in Table 2.1 behaves as the programming sequence
below where the exclamation symbol (!) denotes negation.
if ((A == 1) & !(B == 1) & !(C == 1) & !(D == 1))
t=1;
elseif (!(A == 1) & (B == 1) & !(C == 1) & !(D == 1))
t=2;
elseif (!(A == 1) & !(B == 1) & (C == 1) & !(D == 1))
t=3;
elseif (!(A == 1) & !(B == 1) & !(C == 1) & (D == 1))
t=4;
.....
else
t=n;
endif
or the Boolean expressions

X = ABCD Y = ABCD Z = ABCD W = ABCD …


We can call a Truth Table functions from a Stateflow chart or by adding a Truth Table block
directly to a Simulink model as shown in Figure 2.1 below. Adding a Truth Table block directly
to a Simulink model is the more direct approach and has the advantage of being able to define
truth table inputs and outputs to have inherent types and sizes. Moreover, the Truth Table block
supports the Embedded MATLAB language* for programming conditions and actions, and gener-

* This topic is discussed in Chapter 3.

2−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

ates content as Embedded MATLAB code. This helps in debugging the Truth Table block dur-
ing Simulation.

Call directly to a
Simulink model

Call from a
Stateflow chart

Figure 2.1. The Stateflow Chart and Truth Table blocks

It is best to introduce the addition of a Truth Table block directly to a Simulink model with the
following example.

Example 2.1
In this example we will create a Simulink model that includes a Truth Table block to convert
decimal numbers to Binary Coded Decimals (BCD). The truth table that performs this conver-
sion is shown in Table 2.2. We will refer to this table as the generic truth table for this conversion.

Introduction to Stateflow®with Applications 2−3


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

TABLE 2.2 Generic Decimal−to−BCD Converter


Inputs Outputs
S0 S1 S2 S3 S4 S5 S6 S7 S8 S9 A B C D
1 0 0 0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0 0 0 1
0 0 1 0 0 0 0 0 0 0 0 0 1 0
0 0 0 1 0 0 0 0 0 0 0 0 1 1
0 0 0 0 1 0 0 0 0 0 0 1 0 0
0 0 0 0 0 1 0 0 0 0 0 1 0 1
0 0 0 0 0 0 1 0 0 0 0 1 1 0
0 0 0 0 0 0 0 1 0 0 0 1 1 1
0 0 0 0 0 0 0 0 1 0 1 0 0 0
0 0 0 0 0 0 0 0 0 1 1 0 0 1

From Table 2.2, by inspection, we obtain*


A = S8 + S9
B = S4 + S5 + S6 + S7
(2.1)
C = S2 + S3 + S6 + S7
D = S1 + S3 + S5 + S7 + S9

We will make use of the relations in (2.1) when we program the Truth Table block. We begin by

calling Simulink from the main MATLAB Window of Figure 2.2 using the Simulink tool .

Figure 2.2. Opening the Simulink Library Browser with the Simulink tool

* For a detailed discussion on this and other binary converters, please refer to Digital Circuit Analysis and Design with Sim-
ulink Modeling and Introduction to CPLDs and FPGAs, ISBN 978−1−934404−05−8.

2−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

The Simulink Library Browser window opens as shown in Figure 2.3.

Figure 2.3. The Simulink Library Browser window.

We click on the Create a new model tool (upper left), we scroll down on the left pane and
we choose Stateflow. From the right pane we click and drag the Truth Table block into the new
model named untitled as shown in Figure 2.4. We save this model as dec2BCDtt1 and now it
appears as shown in Figure 2.5.
The truth table block in Figure 2.5 is empty and we must program it to specify its function. We
do this with the following steps:
a. We double click on the Truth Table block of Figure 2.5 and the dec2BCDtt1/Truth Table
window appears as shown in Figure 2.6. We observe that this window consists of a Condition
Table, and an Action Table.

Introduction to Stateflow®with Applications 2−5


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.4. Dragging a Truth Table block into a Simulink model

Figure 2.5. Naming the Simulink model

b. The Condition Table contains a Description column, a Condition column, and two or
more Decision columns denoted as D1, D2,... DN. The Action Table consists of a
Description column and an Action column. The entries in Figure 2.6 are for illustration
purposes and we delete them. Descriptions are optional, but are transferred as comments
into the generated code for the truth table.

2−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.6. The Condition Table and the Action Table in a Stateflow Truth Table block

c. To specify the logical behavior of a truth table, we begin with the Condition column of
the Condition Table. We can also enter an optional description in the Description col-
umn. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns. After
deleting the contents of the 2 rows and the contents of the 3 decision columns D1, D2,
and D3 in the dec2BCDtt1/Truth Table window of Figure 2.6, we are left with 2 empty
rows and three empty decision columns. Accordingly, we must add 8 rows and 8 columns
to the dec2BCDtt1/Truth Table of Figure 2.6. Column D11 is the default decision column
and the need for it will be explained in (d) below. We add 8 rows and 8 columns by click-

ing the Append Row tool 8 times, and by clicking Append Column tool 8
times.

Introduction to Stateflow®with Applications 2−7


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

d. In the Condition Table of Figure 2.6 we make the entries shown in the Condition Table
of Figure 2.7.

Figure 2.7. The contents of the Condition Table for Example 2.1

In the Condition Table of Figure 2.7 above, each decision column D1 through D11 forms
a group of decision outcomes with the logical AND relationship into a decision. The False
(F)* and True (T) entries in decision columns D1 through D10 are in agreement with the
generic table, Table 2.2. The last decision column, D11, is referred to as the default deci-
sion column for the truth table, and covers any remaining decisions not listed in decision
columns D1 through D10. All entries in the default decision column must be indicated
with the dash (−) character and it represents a true or false condition, i.e., a don’t care con-
dition. The default decision column must always be the last decision column.

* We can press the space bar to toggle through the possible values F, −, and T. We can also enter these by typing them. Any
other characters are rejected.

2−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

e. In the Action Table of Figure 2.6 we make the entries shown in Figure 2.8 below. We
observe that the actions X0 through X10 are those appearing in the last row of the Condi-
tion Table in Figure 2.7.

Figure 2.8. The contents of the Action Table for Example 2.1

From the dec2BCDtt1/Truth Table window of Figure 2.7 or Figure 2.8, we click on Edit
Data/Ports from the Add drop menu, and the Ports and Data Manager window appears
as shown in Figure 2.9.

Introduction to Stateflow®with Applications 2−9


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.9. The Ports and Data Manager window

On the left pane of the Ports and Data Manager of Figure 2.9 where the entry data
appears under the Column Name, we change the name to a, and we press Enter. We click
the entry Local under the Scope column, and from the drop menu we select Input. This
means that Simulink provides the value for this data, which it passes to the Stateflow
block through an input port on the Stateflow block.
Using the same procedure we change the name u to Input b, Port 2, and the name y to
Input c, Port 3. The new data now appear as shown in Figure 2.10.

Figure 2.10. The contents of the Ports and Data Manager window for Example 2.1

2−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

We click on the Add Data tool , we observe that a new entry appears with the name data,
and using the procedure above we change the name data to Input d, Port 4. We repeat this pro-
cedure to enter inputs e through j, and outputs t1, t2, t3, and t4. The Ports and Data Manager
window now appears as shown in Figure 2.11.*

Figure 2.11. Defined inputs and outputs in the Ports and Data Manager window for Example 2.1

The Truth Table block now appears as shown in Figure 2.12.

* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking
Port in the Contents pane.

Introduction to Stateflow®with Applications 2−11


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.12. The Truth Table block inputs and outputs

In the Simulink model of Figure 2.12 we add ten Constant blocks as inputs to the Stateflow
Truth Table block and four Display blocks as outputs interconnected as shown in the model of
Figure 2.13. We check the validity of this model by entering
S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=0;
at MATLAB’s Command prompt, and observing that all 4 Display blocks show zero values. As
another check, we enter
S5=1;
and as expected, the Display blocks show the values A=0, B=1, C=0, and D=1. As a last check,
at MATLAB’s Command prompt we enter

S5=0;* S9=1;
and the output values are as shown in Figure 2.13.

* We set the value of S5 to 0 because only one of the inputs can be set to 1 at any time.

2−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.13. The complete Simulink model for Example 2.1

While the model of Figure 2.13 works well, it is not the most elegant design. We can add a Mul-
tiport Switch block and redefine the Truth Table block with only one input. This is left as an
exercise for the reader at the end of this chapter.

The Truth Table block used in Example 2.1 is an Embedded MATLAB truth table function
and has the advantage to adding a Truth Table block directly to a Simulink model instead of
calling truth table functions from a Stateflow Chart block. The Truth Table block uses the
Embedded MATLAB language for programming conditions and actions, and generates content
as Embedded MATLAB code. However, when a Truth Table is called from a Stateflow Chart,
we have two options:

Introduction to Stateflow®with Applications 2−13


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

1. Stateflow Classic (default) − Programming Actions in Stateflow Classic Action Language


2. Embedded MATLAB − Programming Actions in Embedded MATLAB Action Language
We will illustrate the Stateflow Classic Action Language with Example 2.2, and the Embedded
MATLAB Action Language with Example 2.3.

Example 2.2
We will repeat Example 2.1 using the Stateflow Chart block with the Stateflow Classic Action
Language option.

We begin by calling Simulink from the main MATLAB Window of Figure 2.2 using the Simulink

tool
The Simulink Library Browser window opens as shown in Figure 2.3. We click on the Create a

new model tool (upper left), we scroll down on the left pane and we choose Stateflow. From
the right pane we click and drag the Stateflow Chart block into the new model.* We save this
model as dec2BCDcl and now it appears as shown in Figure 2.14.

Figure 2.14. Using the Stateflow Chart Truth Table in the Simulink model of Example 2.1

In the Simulink model window of Figure 2.14, from the Simulation drop menu we select Config-
uration Parameters, we set the Solver Options Type field to Variable−step, and Stop Time to
inf, and we save the model.

* We can also call a Stateflow Chart block by typing sfnew at the MATLAB Command Window prompt.

2−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

The Chart block in the model of Figure 2.14 is empty and we must program it to specify its func-
tion. We do this with the following steps:
a. We double click on the Chart block of Figure 2.14 and the Stateflow diagram editor
named dec2BCDcl/Chart appears as shown in Figure 2.15.

Figure 2.15. Stateflow diagram editor for the Chart block of Figure 2.14

b. In the Stateflow diagram editor of Figure 2.15, we select the Truth Table drawing tool

.
We drag the Truth Table drawing tool into the blank space of the Stateflow diagram editor
and we observe that the cursor transforms into a rectangle. We move it to the upper right
corner and we click. The shaded rectangle appears with the title truthtable and a question
mark (?) below it. We click on the question mark and a flashing text cursor in the center
of the rectangle appears as shown in Figure 2.16.

Introduction to Stateflow®with Applications 2−15


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.16. Calling a Truth Table from the Stateflow Editor window
The generic truth table shown as Table 2.2, has four outputs A, B, C, and D, and each of
these outputs is a function of the inputs S0 through S9. Using the Truth Table drawing

tool we add three more truthtable rectangles as shown in Figure 2.17.

Figure 2.17. Adding three more Truth Table rectangles inside the Stateflow Editor window

2−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

In the first truthtable rectangle of Figure 2.17 where the flashing text cursor appears we
type
t1=ttableA(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
This is referred to as the signature label and defines its name as ttableA, its arguments
(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9), and its return value t1 which is associated with the
output A. Likewise, in the second, third, and fourth truthtable rectangles of Figure 2.17
we type
t2=ttableB(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
t3=ttableC(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
t4=ttableD(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
respectively. The Stateflow diagram editor now appears as shown in Figure 2.18.

Figure 2.18. Defining the Signature labels

c. We right−click on the first truth table function t1 in Figure 2.18 above, and from the pop-
up menu which is shown in Figure 2.19 below, we select Properties. The Truth Table
Properties dialog box for the truth table function ttableA appears as shown in Figure 2.20
below where we have checked the Function Call field.
d. We repeat step (c) above for the truth table functions ttableB, ttableC, and ttableD.

Introduction to Stateflow®with Applications 2−17


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.19. Submenu for selecting Properties

Figure 2.20. Truth Table window for defining the Truth Table properties

e. The fields in the Truth Table Properties for ttableA, ttableB, ttableC, and ttableD, are as
shown in Table 2.3 below.

2−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

TABLE 2.3
Field Description
Name Function name (read only)
Breakpoints When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
Function Inline Option Controls the inlining of the truth table generated code
• Auto − Whether or not to inline the truth table function is decided by Stateflow
• Inline − The truth table function is inlined by Stateflow
• Function − The function is not inlined
Label The signature label is specified
Description Textual description and comments
Document Link A URL address or a MATLAB command may be entered

f. The next step is to specify a call to the truth table functions ttableA, ttableB, ttableC, and
ttableD. This step is necessary because when the Stateflow diagram executes during the
simulation phase, it calls the truth table function(s). We call the truth table functions
ttableA, ttableB, ttableC, and ttableD, from the default transition of its own Stateflow dia-

gram by selecting the Default Transition tool from the drawing toolbar shown in
Figure 2.18. We move the cursor to the left of the truth table functions shown in Figure
2.18, and we observe that the cursor transforms to a downward−pointing arrow as shown
in Figure 2.21. To adjust the arrow to a vertical direction, we move the cursor towards the
solid dot of the arrow, we observe that it changes to a circle around the dot, and we move
it to the right until it becomes vertical. We move the question mark (?) character slightly
to the right and we enter the following text:
{A=ttableA(a,b,c,d,e,f,g,h,i,j);
B=ttableB(a,b,c,d,e,f,g,h,i,j);
C=ttableC(a,b,c,d,e,f,g,h,i,j);
D=ttableD(a,b,c,d,e,f,g,h,i,j);}
The text above forms a condition action that calls the truth table with the arguments
(a,b,c,d,e,f,g,h,i,j) and the return values (A,B,C,D). Thus, when Simulink activates the
Stateflow block during simulation, the default transition becomes active and calls to the
truth table functions ttableA, ttableB, ttableC, and ttableD, are made.
The call to the truth table must match the truth table signature, that is, the type of the
return values A, B, C, and D, must be associated with the type of the signature return val-
ues t1, t2, t3, and t4, and the type of the arguments (a,b,c,d,e,f,g,h,i,j) must be associated
with the type of the signature arguments S0, S1, ..., and S9. This association is also shown
in the Stateflow diagram editor and appears in Figure 2.22. We save the model and in step
(g) below we will define the associations.

Introduction to Stateflow®with Applications 2−19


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.21. Adding the Default Transition

Figure 2.22. The addition of the Truth Table functions

2−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

g. We double−click the truth table function ttableA in the Stateflow diagram editor of Figure
2.22, and the table editor named dec2BCDcl/ttableA appears as shown in Figure 2.23.

Figure 2.23. The Stateflow Truth Table Editor

In the truth table editor of Figure 2.23, we select the Edit Data/Ports tool and the
Model Explorer window appears as shown in Figure 2.24 where the ttableA function is
highlighted under Chart in the Model Hierarchy pane. The Contents pane displays the
inputs (S0, S1, ..., S9) and the output t1 for the ttableA function. Likewise when the tta-
bleB, ttableC, and ttableD functions are highlighted under Chart in the Model Hierarchy
pane, the Contents pane displays the inputs (S0, S1, ..., S9) and the outputs t2, t3, and t4
respectively.
Next, we select Chart in the Model Hierarchy pane and the Model Explorer window
appears as shown in Figure 2.25. From the Add menu we select Data and we observe that

the tool is added to the Contents pane with the default name data in the Name col-
umn. We double click on the name and in the text field we change the name to a and we
press Enter. We click the entry Local under the Scope column, and from the drop menu
we select Input, and this creates an input port to the Stateflow block. We repeat these
steps to add the arguments b through i as inputs, and A, B, C, and D as outputs. The Model
Explorer window now appears as shown* in Figure 2.26.

* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking
Port in the Contents pane.

Introduction to Stateflow®with Applications 2−21


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.24. The Model Explorer window

2−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.25. The Model Explorer window displaying the contents of the Stateflow Chart
The Stateflow chart in the Simulink model now appears as shown in Figure 2.27 where we
have added ten Constant blocks for the inputs S0 through S9 corresponding to the State-
flow block inputs a through j, and four Display blocks for the outputs A, B, C, and D.
We have now built the Simulink model with the Stateflow block and the next step is to
program the Stateflow truth table. We do this in step (h) below.
h. We double click the Stateflow Chart block in Figure 2.27 and the Stateflow diagram editor
appears as shown in Figure 2.28. We double click the truth table function ttableA rectangle
and the truth table editor appears as shown in Figure 2.29. We must now select a Stateflow
Action Language, either the Classic Action Language (default) or the Embedded MAT-
LAB Action Language. For this example, we choose the Classic Action Language by
selecting Language from the Settings drop menu in the truth table editor shown in Figure
2.29.
i. The truth table editor in Figure 2.29 consists of the Condition Table which contains a
Description column, a Condition column, and two or more Decision columns denoted as
D1, D2, ... DN. The Action Table consists of a Description column and an Action col-
umn. Descriptions are optional, but are transferred as comments into the generated code
for the truth table.We begin specifying the logical behavior in a truth table by entering
conditions in the Condition column of the Condition Table in Figure 2.29.

Introduction to Stateflow®with Applications 2−23


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.26. The Model Explorer window with the input and output list

j. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns, and the
truth table editor in Figure 2.29 contains one row and one column shown as D1. Accord-
ingly, we must add 9 rows and 10 columns to the truth table editor shown in Figure 2.29.

We add 9 rows and 10 columns by clicking the Append Row tool 9 times, and by

clicking Append Column tool 10 times. Column D11 is the default decision column.
The truth table editor now appears as shown in Figure 2.30.

2−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.27. The Simulink model with the input and output blocks

Figure 2.28. Using the Stateflow Chart block to program the Truth Table

Introduction to Stateflow®with Applications 2−25


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.29. The Condition Table in its original form

Figure 2.30. The Condition Table with added rows and columns

2−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

In the truth table editor shown in Figure 2.30, we type the entries shown in Figure 2.31.

Figure 2.31. The programmed Condition Table for ttableA

k. In the Condition column of the Condition Table each condition that we enter must be
zero (false) or non−zero (true), that is, each condition must be specified as a == 0 or a ==
1.* For this example arbitrarily we specified S0EQ1: S0 = = 1, S1EQ1: S1 = = 1, and so on
as indicated in Figure 2.31 above. The entries in the Description column are optional.
Whether these three conditions are true or false, they are indicated in the Decision col-
umns D1 through D11. Thus, Decision column D1 indicates that condition S0 = = 1 in
Row 1 is true and the remaining in Rows 2 through 10 are false since only one of the inputs
S0 through S9 can be true at any time, and for this reason we have entered F (False)† in
Rows 2 through 10 of Column D1. Using the same reasoning, we have entered F (False) or
T (True) in Columns D2 through D10. As stated earlier, Column D11 is the default deci-

* We can also use optional brackets, e.g., [a == 1] as in Stateflow language.


† Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered
directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false deci-
sion and it is used in some applications as a don’t care decision.

Introduction to Stateflow®with Applications 2−27


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

sion and includes all other decisions and these are denoted with the dash (−) symbol.
Each decision column binds a group of condition outcomes with the logical AND operation
into a decision. The Actions X0 through X10 are defined in the Action Table which we
will discuss in paragraph l below.
l. We will now program the Action Table of the truth table which appears below the Con-

dition Table. We highlight the Action Table, we click the Append Row tool 12
times, and we make the entries shown in Figure 2.32 where the entries in Rows 1 and 13
are for the initial and final actions respectively. The X0 through X10 actions listed in the
last row of the Condition Table of Figure 2.31 are specified in Rows 2 through 12 in the
Action Table of Figure 2.32.

Figure 2.32. The programmed Action Table for ttableA

m. The Condition Table in Figure 2.31 and the Action Table in Figure 2.32 are for the
ttableA function shown in the Stateflow Chart editor of Figure 2.28. Next, we need to

2−28 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

specify the Condition Tables and the Action Tables for the ttableB, ttableC, and ttableD
functions as defined in the Stateflow Chart editor of Figure 2.28. The entries are shown in
Figures 2.33, 2.34, and 2.35 below where the actions for ttableB, ttableC, and ttableD are
defined as Y0 through Y10, Z0 through Z10, and W0 through W10 respectively.

Figure 2.33. The programmed Condition Table and Action Table for ttableB

Introduction to Stateflow®with Applications 2−29


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.34. The programmed Condition Table and Action Table for ttableC

2−30 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.35. The programmed Condition Table and Action Table for ttableD

n. We have now specified all four truth tables ttableA, ttableB, ttableC, and ttableD. In this
step, we will initiate the process of debugging them. We begin with the truth table editor
of ttableA shown partially in Figure 2.36.

Introduction to Stateflow®with Applications 2−31


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.36. Partial list of the Condition Table for ttableA

In the truth table editor of Figure 2.36 we click on the Run Diagnostics tool . If no
errors are detected, the Builder window displays a message that no errors were detected as
in Figure 2.37 below.

Figure 2.37. The Stateflow Builder window indicating status for ttableA

If errors are detected, the Builder window displays error messages such as that shown
below in Figure 2.38.

2−32 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.38. The Stateflow Builder window indicating status for ttableA if errors have occurred

In the Stateflow diagram editor shown in Figure 2.22, Page 2−20, we double−click on the
ttableB, ttableC, and ttableD functions and in the truth table editors we run the diagnos-

tics using the Run Diagnostics tool . The Builder windows for these functions indi-
cate that no errors were found.

p. We can verify that the Simulink model in Figure 2.27, Page 2-25, produces the correct
output for different inputs. For instance, in MATLAB’s command prompt we enter:
S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=1;
and the Simulink model appears as shown in Figure 2.39.
We also observe that the Initial action and Final action messages in Rows 1 and 13 in
the Action Tables appear in MATLAB’s Command Window as follows:
truth table ttableA entered
truth table ttableA exited
truth table ttableB entered
truth table ttableB exited
truth table ttableC entered
truth table ttableC exited
truth table ttableD entered
truth table ttableD exited

Introduction to Stateflow®with Applications 2−33


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.39. The Simulink model with the Truth Table Chart in its final form

q. Truth table diagnostics are performed automatically when we issue the simulation com-
mand. If no errors are detected, the Builder window is not displayed. However, we can
debug a truth table during simulation by setting a breakpoint for the truth table. The
breakpoint pauses execution during simulation so that we can debug each execution step.
We begin by right−clicking the ttableA function in the Stateflow diagram editor shown in
Figure 2.40 below, and from the pop-up menu shown in Figure 2.41, we select Properties,
the Truth Table properties window appears, and we check the Function Call field for
Breakpoints as shown in Figure 2.42. We click OK and this causes a breakpoint to occur
when this truth table is called in the Stateflow diagram during simulation.

2−34 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.40. Using the Stateflow Truth Table Editor for debugging

Next, in the Stateflow diagram editor toolbar in Figure 2.40, we select the Debug tool

and the Stateflow Debugging window appears as shown in Figure 2.43 where under
the Animation column we have chosen the Enabled option with 0 sec Delay.
From the Stateflow Debugging window in Figure 2.43 we click on the Start button and
we wait until the breakpoint for the call to the truth table is reached, and when this
occurs, the Start button changes to Continue button. We click the Step button four
times to advance simulation to the ttableA truth table, and we observe that the INIT
action of this truth table is highlighted as shown in Figure 2.44.

Introduction to Stateflow®with Applications 2−35


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.41. Truth Table submenu for selecting Properties

Figure 2.42. Truth Table dialog box for ttableA

2−36 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.43. Stateflow Debugging window for starting simulation

Figure 2.44. Partial view of the Action Table during initial simulation steps

We click the Step button twice to execute the INIT action and we observe that the truth
table execution advances to the first condition in the Condition Table as shown in Fig-
ure 2.45.

Introduction to Stateflow®with Applications 2−37


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.45. Partial view of the Condition Table during initial simulation steps

We again click the Step button twice to execute the first condition in the Condition
Table and we observe that the truth table execution advances to the second condition in
the Condition Table. We repeat this step until the truth table execution advances to the
last condition in the Condition Table as shown in Figure 2.46.

Figure 2.46. Partial view of the Condition Table during initial simulation steps

We click on the Step button twice to execute the first decision under Column D1 and we
observe that it is highlighted as shown in Figure 2.47. Again, we click on the Step button
twice and truth table execution advances to the second row in the Action Table which
defines action X0. The truth table execution continues as we click the Step button to
advance to Columns D2 through D10. We finally advance to the FINAL action as shown
in Figure 2.48.

2−38 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.47. The Condition Table during execution of the first Decision

With the steps above, we completed the execution of the truth table ttableA. We repeat
these steps to complete the execution of ttableB, ttableC, and ttableD, and when the exe-
cution of the truth table ttableD is completed, in the Stateflow Debugging window, from
the Browse Data drop menu, we select All Data (Current Chart) and we observe that
an updated display appears as shown in Figure 2.49.

Introduction to Stateflow®with Applications 2−39


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.48. Partial view of the Action Table in Final Action

Figure 2.49. Stateflow Debugging window for simulation continuation

2−40 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Example 2.3
We will repeat Example 2.2 using the Stateflow Chart block with the Stateflow Embedded
MATLAB Action Language option.
We begin by calling Simulink from the main MATLAB Window of Figure 2.50 using the Sim-

ulink tool .

Figure 2.50. Calling Simulink from the MATLAB main window

The Simulink Library Browser window opens as shown in Figure 2.51. We click on the Create

a new model tool (upper left), we scroll down on the left pane and we choose Stateflow.
From the right pane we click and drag the Stateflow Chart block into the new model.* We save
this model as dec2BCDem and now it appears as shown in Figure 2.51.

Figure 2.51. Dragging a Stateflow Chart into the new Simulink model

* We can also call a Stateflow Chart block by typing sfnew at the MATLAB Command Window prompt.

Introduction to Stateflow®with Applications 2−41


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

In the Simulink model window of Figure 2.51, from the Simulation drop menu we select Config-
uration Parameters, we set the Solver Options Type field to Variable−step, and Stop Time to
inf, and we save the model.
The Chart block in the model of Figure 2.51 is empty and we must program it to specify its func-
tion. We do this with the following steps:
a. We double click on the Chart block of Figure 2.51 and the Stateflow diagram editor named
dec2BCDem/Chart appears as shown in Figure 2.52.

Figure 2.52. Stateflow diagram editor for the Chart block of Figure 2.51

b. In the Stateflow diagram editor of Figure 2.52, we select the Truth Table drawing tool

.
We drag the Truth Table drawing tool into the blank space of the Stateflow diagram editor
and we observe that the cursor transforms into a rectangle. We move it to the upper right
corner and we click. The shaded rectangle appears with the title truthtable and a question
mark (?) below it. We click on the question mark and a flashing text cursor in the center of
the rectangle appears as shown in Figure 2.53.

2−42 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.53. Adding a Truth Table rectangle into the Stateflow Truth Table Editor
The generic truth table shown as Table 2.2, Page 2−4, has four outputs A, B, C, and D,
and each of these outputs is a function of the inputs S0 through S9. Accordingly, using

the Truth Table drawing tool we add three more truthtable rectangles as shown in
Figure 2.54.

In the first truthtable rectangle of Figure 2.54 where the flashing text cursor appears we
enter
t1em=ttableAem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
This is referred to as the signature label and defines its name as ttableA, its arguments
(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9), and its return value t1 which is associated with the
output A. Likewise, in the second, third, and fourth truthtable rectangles of Figure 2.54
we enter
t2em=ttableBem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
t3em=ttableCem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
t4em=ttableDem(S0,S1,S2,S3,S4,S5,S6,S7,S8,S9)
respectively. The Stateflow diagram editor now appears as shown in Figure 2.55.

Introduction to Stateflow®with Applications 2−43


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.54. Adding three more Truth Table rectangles into the Stateflow Truth Table Editor

Figure 2.55. Defining the Truth Table rectangles

2−44 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

c. We right−click on the first truth table function t1em in Figure 2.55 above, and from the
pop-up menu shown in Figure 2.56 below, we select Properties. The Truth Table Proper-
ties dialog box for the truth table function ttableAem appears as shown in Figure 2.57
below where we have checked the Function Call field.

Figure 2.56. Pop-up menu to select Truth Table Properties

Figure 2.57. Truth Table dialog box for defining ttableAem

Introduction to Stateflow®with Applications 2−45


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

d. We repeat step (c) for the truth table functions ttableBem, ttableCem, and ttableDem.
e. The description for the fields in the Truth Table Properties for ttableAem, ttableBem, tta-
bleCem, and ttableDem, are as shown in Table 2.4 below.

TABLE 2.4
Field Description
Name Function name (read only)
Breakpoints When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
Function Inline Option Controls the inlining of the truth table generated code
• Auto − Whether or not to inline the truth table function is decided by Stateflow
• Inline − The truth table function is inlined by Stateflow
• Function − The function is not inlined
Label The signature lavel is specified
Description Textual description and comments
Document Link A URL address or a MATLAB command may be entered

f. The next step is to specify a call to the truth table functions ttableAem, ttableBem, tta-
bleCem, and ttableDem. This step is necessary because when the Stateflow diagram exe-
cutes during the simulation phase, it calls the truth table function(s). We call the truth
table functions ttableAem, ttableBem, ttableCem, and ttableDem, from the default transi-

tion of its own Stateflow diagram by selecting the Default Transition tool from the
drawing toolbar shown in Figure 2.55. We move the cursor to the left of the truth table
functions shown in Figure 2.55, and we observe that the cursor transforms to a downward−
pointing arrow as shown in Figure 2.58. To adjust the arrow to a vertical direction, we
move the cursor towards the solid dot of the arrow, we observe that it becomes a circle
around the dot, and we move it to the right until it becomes vertical. We move the ques-
tion mark (?) character slightly to the right and we enter the following text:
{A=ttableAem(a,b,c,d,e,f,g,h,i,j);
B=ttableBem(a,b,c,d,e,f,g,h,i,j);
C=ttableCem(a,b,c,d,e,f,g,h,i,j);
D=ttableDem(a,b,c,d,e,f,g,h,i,j);}
The text above forms a condition action that calls the truth table with the arguments
(a,b,c,d,e,f,g,h,i,j) and the return values (A,B,C,D). Thus, when Simulink activates the
Stateflow block during simulation, the default transition becomes active and calls to the
truth table functions ttableA, ttableB, ttableC, and ttableD, are made.

2−46 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.58. Adding the Default Transition

The call to the truth table must match the truth table signature, that is, the type of the
return values A, B, C, and D, must be associated with the type of the signature return val-
ues t1em, t2em, t3em, and t4em, and the type of the arguments (a,b,c,d,e,f,g,h,i,j) must
must be associated with the type of the signature arguments S0, S1, ..., and S9. This asso-
ciation is also shown in the Stateflow diagram editor and appears in Figure 2.59. We save
the model and in step (g) below we will define the associations.

Figure 2.59. The addition of the Truth Table functions

Introduction to Stateflow®with Applications 2−47


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

g. We double−click the truth table function ttableAem in the Stateflow diagram editor of Fig-
ure 2.59, and the table editor named dec2BCDem/ttableAem appears as shown in Figure
2.60.

Figure 2.60. The Stateflow Truth Table Editor

In the truth table editor of Figure 2.60, we select the Edit Data/Ports tool and the
Model Explorer window appears as shown in Figure 2.61 where the ttableAem function is
highlighted under Chart in the Model Hierarchy pane. The Contents pane displays the
inputs (S0, S1, ..., S9) and the output t1em for the ttableAem function. Likewise when the
ttableBem, ttableCem, and ttableDem functions are highlighted under Chart in the Model
Hierarchy pane, the Contents pane displays the inputs (S0, S1, ..., S9) and the outputs
t2em, t3em, and t4em respectively.
Next, we select Chart in the Model Hierarchy pane and the Model Explorer window
appears as shown in Figure 2.62. From the Add menu we select Data and we observe that

the tool is added to the Contents pane with the default name data in the Name col-
umn. We double click on the name and in the text field we change the name to a and we
press Enter. We click the entry Local under the Scope column, and from the drop menu we
select Input, and this creates an input port to the Stateflow block. We repeat these steps to
add the arguments b through i as inputs, and A , B, C , and D as outputs. The Model
Explorer window now appears as shown* in Figure 2.63.

* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking Port
in the Contents pane.

2−48 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.61. The Model Explorer window

The Stateflow chart in the Simulink model now appears as shown in Figure 2.64 where
we have added 10 Constant blocks for the inputs S0 through S9 corresponding to the
Stateflow block inputs a through j, and 4 Display blocks for the outputs A, B, C, and D.
We have now built the Simulink model with the Stateflow block and the next step is to
program the Stateflow truth table. We do this in step (h) below.

Introduction to Stateflow®with Applications 2−49


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.62. The Model Explorer window displaying the contents of the Stateflow Chart

h. We double click the Stateflow Chart block in Figure 2.64 and the Stateflow diagram editor
appears as shown in Figure 2.65. We double click the truth table function ttableAem rect-
angle and the truth table editor appears as shown in Figure 2.66. We now must select a
Stateflow Action Language, either the Classic Action Language (default) or the Embed-
ded MATLAB Action Language. For this example, we choose the Embedded MATLAB
Action Language by selecting Language from the Settings drop menu in the truth table
editor shown in Figure 2.66. We repeat this step for the truth table functions ttableBem,
ttableCem, and ttableDem, and the Stateflow diagram editor appears as shown in Figure
2.67.
i. The truth table editor in Figure 2.66 consists of the Condition Table which contains a
Description column, a Condition column, and two or more Decision columns denoted as
D1, D2, ... DN. The Action Table consists of a Description column and an Action col-
umn. Descriptions are optional, but are transferred as comments into the generated code
for the truth table. We begin specifying the logical behavior in a truth table by entering
conditions in the Condition column of the Condition Table in Figure 2.66.

2−50 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.63. The Model Explorer window with the input and output list

j. In the Condition Table of the truth table editor in Figure 2.66 we add 9 rows and 10 col-

umns by clicking the Append Row tool 9 times, and by clicking Append Column

tool 10 times. Column D11 is the default decision column. The truth table editor
now appears as shown in Figure 2.68.

Introduction to Stateflow®with Applications 2−51


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.64. The Simulink model with the input and output blocks

Figure 2.65. Using the Stateflow Chart block to program the Truth Table

2−52 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.66. The Condition Table in its original form

Figure 2.67. Using the Stateflow Chart block to program the Truth Table

Introduction to Stateflow®with Applications 2−53


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.68. The Condition Table with added rows and columns

In the Truth Table editor shown in Figure 2.68, we type the entries shown in Figure 2.69.

2−54 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.69. The programmed Condition Table for ttableAem

k. In the Condition column of the Condition Table shown in Figure 2.69, each condition
that we enter must be zero (false) or non−zero (true), that is, each condition must be spec-
ified as a == 0 or a == 1.* For this example, arbitrarily we specified S0EQ1: S0 = = 1,
S1EQ1: S1 = = 1, and so on as indicated in Figure 2.69 above. The entries in the Descrip-
tion column are optional. Whether these three conditions are true or false, they are indi-
cated in the Decision columns D1 through D11. Thus, Decision column D1 indicates
that condition S0 = = 1 in Row 1 is true and the remaining in Rows 2 through 10 are false
since only one of the inputs S0 through S9 can be true at any time, and for this reason we
have entered F (False)† in Rows 2 through 10 of Column D1. Using the same reasoning,
we have entered F (False) or T (True) in Columns D2 through D10. As stated earlier,
Column D11 is the default decision and includes all other decisions and these are denoted

* We can also use optional brackets, e.g., [a == 1] as in Stateflow language.


† Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered
directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false deci-
sion and it is used in some applications as a don’t care decision.

Introduction to Stateflow®with Applications 2−55


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

with the dash (−) symbol.


Each decision column binds a group of condition outcomes with the logical AND opera-
tion into a decision. The Actions X0 through X10 are defined in the Action Table which
we will discuss in paragraph l below.
l. We will now program the Action Table of the truth table which appears below the Condi-

tion Table. We highlight the Action Table, and we click the Append Row tool 12
times. We click the first row in the Description column of the Action Table, and we enter
Initial action: Display message . We press Tab to move to the Action column in the
Action Table, and we enter INIT: eml.extrinsic(‘truth table ttableAem entered’);
For this example we selected the Embedded MATLAB Language. This language provides
a front−end for writing and simulating Embedded MATLAB functions in Stateflow charts.
Accordingly, we need to write an M−code to program our actions in the Action Table. The
M−code allows us to add control flow logic and to call MATLAB functions directly. We
begin with an action in the truth table function ttableAem using the embedded MATLAB
syntax consisting of persistent* variables, if ... else ... end control flows, for loop, and call-
ing the MATLAB command plot directly.
We click the second row in the Description column of the Action Table, and we enter
the description:
Define a counter and a vector of length 10.
Whenever this action is called, the output
t1em assumes the next value of the vector.
We press Tab to move to the Action column in the Action Table, we enter X0:, we press
enter, and we enter the following:
persistent values counter;
cycle = 10;
if isemptly(counter)
% Initialize counter to zero
counter = 0;
else
% Otherwise, increment counter
counter = counter + 1;
end
if isemply(values)
% Values is a vector of 1 to cycle

* Persistent variables are local to the function in which they are declared, but their values are retained in memory between
calls to the function. We declare persistent variables in embedded MATLAB functions using the persistent statement with
the word persistent in front of the variable, e.g., persistent INV_X

2−56 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

values = zeros(1, cycle);


for k = 1; cycle
values(k)=k;
end
% The following is just for debugging purposes
values
end
% Output t1em assumes the next value in values vector
t1em=values(mod(counter, cycle) + 1);
The entries in rows 3 through 12 are the same as those in the previous example except
that output t1 has been changed to t1em. In Row 13 we enter Final action: Display mes-
sage, and FINAL: eml.extrinsic(truth table ttableAem exited’);
The Action Table for truth table ttableAem appears as shown in Figure 2.70

Figure 2.70. The programmed Action Table for ttableAem

The entries for the truth table editors for truth tables ttableBem, ttableCem, and ttable-
Dem, are shown in Figures 2.71, 2.72, and 2.73 respectively.

Introduction to Stateflow®with Applications 2−57


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.71. The programmed Condition Table and Action Table for ttableBem

2−58 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.72. The programmed Condition Table and Action Table for ttableCem

Introduction to Stateflow®with Applications 2−59


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Figure 2.73. The programmed Condition Table and Action Table for ttableDem

Our model is now completed and with the values below entered at the MATLAB command
prompt, appears as shown in Figure 2.74.
S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=1;

2−60 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Truth Tables in Stateflow

Figure 2.74. The Simulink model with the Truth Table Chart in its final form

Truth table diagnostics are performed automatically when we issue the simulation command. If
no errors are detected, the Builder window is not displayed. However, we can debug a truth
table during simulation by setting a breakpoint for the truth table using the same procedure as in
Example 2.2. The breakpoint pauses execution during simulation so that we can debug each exe-
cution step.

Introduction to Stateflow®with Applications 2−61


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2.2 Summary
• We add a Stateflow Truth Table block directly to a Simulink model or by calling truth table
functions from a Stateflow Chart.
• The Truth Table block is an embedded MATLAB truth table function. The Truth Table
block used in Example 2.1 is an embedded MATLAB truth table function.
• Truth table functions called from a Stateflow Chart block can be programmed in Stateflow
Classic Language (default) or in Embedded MATLAB Language. The truth table functions
called in Example 2.2 are programmed in Stateflow Classic Language, and the truth table
functions called in Example 2.3 are programmed in Embedded MATLAB Language.
• A graphical function is a function defined graphically by a Stateflow diagram. We use the
Stateflow editor to create them and they reside in our Stateflow model along with the dia-
grams that invoke them. An example is shown in Figure 2.59 where the functions ttableA, tta-
bleB, ttableC, and ttableD are called in the condition action of the transition from one state to
another.
• Truth Table blocks are easier to program than truth table functions called from a Stateflow
Chart block with graphical functions.
• If we use the Truth Table block in a Simulink model, we can invoke the Truth Table Editor
window to enter the conditions, decisions, and actions. An example is shown in Figures 2.7,
and 2.8. The Truth Table Editor allows us to edit conditions, decisions, and actions, add or
modify Stateflow data and ports using the Ports and Data Manager by clicking the Edit Data/
Ports tool, run diagnostics to detect errors, and view generated content after simulation.
• If we choose the Chart block to call a truth table function in a new Simulink model, we per-
form the following steps:
1. We enter sfnew at the MATLAB command prompt
2. We double−click the Stateflow Chart block, and in the Stateflow diagram editor window
we select the Truth Table tool, we drag it near the upper right corner of the window, and
we observe that it appears as a rectangle with the label truthtable with a flashing text cur-
sor below it.
3. At the flashing text cursor we enter the text defining a function, e.g., z=f(x,y), and we
click outside the truth table box. The function z=f(x,y) is referred to as the signature label
and defines it name as f, its arguments as (x and y), and its return value z. There must be
only one return value in any function within a rectangle.
4. We repeat Steps 2 and 3 above for additional functions, e.g., c=g(a,b).

2−62 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

5. We specify properties by right−clicking the truth table function rectangle in the Stateflow
diagram editor window and we select Properties from the drop menu and the Truth
Table Properties dialog appears. The fields are described in Table 2.4, this chapter.
6. We need to specify a call to the truth table function. This is done by selecting the Default
Transition tool from the drawing toolbar of the Stateflow diagram editor window, we
move it near the upper left corner, we click to place a default transition into a terminating
junction, we click the question mark (?) character, and where a flashing cursor appears,
we enter the desired function name, e.g., {c=f(a,b);}, and we click outside this label to ter-
minate the editing. The return value c must match the return value z of the signature
label, and the values (a,b) must match the values (x,y) of the signature label. However,
the function f must be the same as in the signature label.
7. In the Stateflow diagram editor window we double−click the truth table rectangle to open
the Truth Table Editor window consisting of the Condition Table and Action Table, and
we select the Edit Data/Ports tool. This opens the Model Explorer window. We notice
that in the Model Hierarchy pane (left pane) that the function f is highlighted and the
the Contents pane to the right displays the output z and the inputs x and y.
8. In the Model Hierarchy pane, above the function f is the parent node Chart, and when it
is selected, we notice that there are no data in the Contents pane. From the Add drop
menu we select Data, and we observe that a scalar data is added in the Contents pane.
9. In the Contents pane we double−click the entry data under the Name column. We
observe that a small text field opens with the name data highlighted, we change the name
to a and we press enter. We click the entry Local under the Scope column, and from the
drop menu we select Input. This means that Simulink provides the value for this data and
passes it to the Stateflow through an input port on the Stateflow block. The new data
input a now appears in the Contents pane.
10. From the Add drop menu we select Data, and we observe that a new scalar data is added
in the Contents pane. We repeat step 9 above to add the second input b. Using the same
procedure, we add data c with a scope Output. The Stateflow Chart block now appears
with two inputs a and b, and output c. At this time, we add the appropriate Simulink
blocks from the Simulink Library Browser, and make the necessary connections to the
Stateflow Chart block.
11. The next step is to program the truth table to specify its behavior. If the Classic Action
Language is selected, we follow the steps delineated in Example 2.2. If the Embedded
MATLAB Action Language is selected, we follow the steps in Example 2.3.
12. The final step is to debug the truth table. This is performed with the Run Diagnostics
tool and the detailed procedure is illustrated in Example 2.2.

Introduction to Stateflow®with Applications 2−63


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2.3 Exercises
1. Reprogram the Truth Table block in Example 2.1 so that the model of Figure 2.13 will be con-
figured as shown below.

2. The truth table of the full adder is shown below.

Inputs Outputs
X Y C IN S C OUT
0 0 0 0 0
0 0 1 1 0
0 1 0 1 0
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1
1 1 0 0 1
1 1 1 1 1

2−64 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercises

Create a Simulink model to implement the truth table of a binary full−adder calling truth
table functions from a Stateflow chart.

Introduction to Stateflow®with Applications 2−65


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2.4 Solution to End−of−Chapter Exercises


1. We begin by calling Simulink from the main MATLAB Window of Figure 2.2, Page 2−4, using

the Simulink tool .


The Simulink Library Browser window opens as shown in Figure 2.3, Page 2−5. We click the

Create a new model tool (upper left), we scroll down on the left pane and we choose
Stateflow. From the right pane we click and drag the Truth Table block into the new model
named untitled as shown below.

We save this model as Exercise2_1tt and now it appears as shown below.

The truth table block above is empty and we must program it to specify its function. We do
this with the following steps:

2−66 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

a. We double click the Truth Table block and we observe that the Exercise2_1tt/Truth
Table window appears as shown below. This window consists of a Condition Table, and
an Action Table.

b. The Condition Table contains a Description column, a Condition column, and two or
more Decision columns denoted as D1, D2, ... DN. The Action Table consists of
Description column and an Action column. The entries in the Condition Table and
Action Table above are for illustration purposes and we delete them. Descriptions are
optional, but are transferred as comments into the generated code for the truth table.
c. To specify the logical behavior of a truth table, we begin with the Condition column of
the Condition Table. We can also enter an optional description in the Description col-
umn. The generic truth table of Table 2.2 consists of 10 rows and 10 input columns. After
deleting the contents of the 2 rows and the contents of the 3 decision columns D1, D2,
and D3 in the Exercise2_1tt/Truth Table window above, we are left with 2 empty rows
and three empty decision columns. Accordingly, we must add 8 rows and 8 columns to
the Exercise2_1tt/Truth Table. Column D11 is the default decision column. We add 8

rows and 8 columns by clicking the Append Row tool 8 times, and by clicking

Append Column tool 8 times.

Introduction to Stateflow®with Applications 2−67


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

d. In the Condition Table of Figure 2.6 we make the entries shown in the table below.

The Condition Table appears as shown below.

2−68 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

e. In the Action Table we make the entries shown in the table below.

and the Action Table appears as shown below.

Introduction to Stateflow®with Applications 2−69


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

We observe that the actions X0 through X10 are those appearing in the last row of the
Condition Table.
f. From the Exercise2_1tt/Truth Table on the previous page, we click on Edit Data/Ports
from the Add drop menu, and the Ports and Data Manager window appears as shown
below.

2−70 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

g. On the left pane in the Ports and Data Manager above where the entry u appears under
the column Name, we select it, we change the name to t, and we press Enter. The data t
is an input and thus we need not make any further changes in that row. This means that
Simulink provides the value for this data, which it passes to the Stateflow block through
an input port on the Stateflow block.
h. Next, we need to define the outputs A, B, C, and D. Using the same procedure as in (g)
above, we change name y to A. We click the entry Local under the Scope column, and
from the drop menu we select Output. This means that Simulink provides the value for
this data, which it passes to the Stateflow block through an output port on the Stateflow
block. The new data now appear as shown below.

Introduction to Stateflow®with Applications 2−71


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

i. We click on the Add Data tool , we observe that a new entry appears with the name
data, and using the procedure above, we change the name data to B, Output, Port 2. We
repeat this procedure to enter outputs C and D. The Ports and Data Manager window
now appears as shown below.

j. The Truth Table block in the Simulink model appears as shown below.

2−72 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

k. From the Simulink Library Browser we drag into the Simulink model above eleven Con-
stant blocks, a Manual Switch block, a Multiport Switch block, a Digital Clock block, a
Scope block, and five Display blocks. We configure the blocks and we interconnect them
as shown below.

Introduction to Stateflow®with Applications 2−73


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

We check the validity of this model with the Manual Switch block configured as shown above,
and specifying the simulation time as 0, 1, .... 9.

2−74 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

2. To create a Simulink model that calls a Stateflow block, we will use the following procedure:
a. At the MATLAB command prompt we type and execute the command sfnew, and we
observe that the untitled Simulink model with a Stateflow Chart block appears as shown
below.

b. We click and drag the Stateflow block to the center of the Simulink window, we click on
the Simulink tool to open the Simulink Library Browser, from the Simulink Sources
Library we click and drag the Constant block to the left of the Stateflow block, we click
it and we copy and paste it twice to create two more Constant blocks, from the Sinks
Library we click and drag the Display block, and we click it and we copy and past it to
create one more Display block. Our Simulink model is now as shown in the figure below
where we have labeled the Constant blocks as the inputs shown in the table above, and
the Sink blocks as the outputs.

Introduction to Stateflow®with Applications 2−75


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

c. In the Simulink model above, from the Simulation menu, we select Configuration
Parameters and from the dialog window which appears, we set the Solver Options Type to
Variable−step, and the Stop Time to inf. We click OK to accept these values, we close the
Configuration Parameters dialog window, and we save this model as FullAdder. As we
know from our previous studies, Simulink appends the extension .mdl to this name.
We create a Stateflow Truth Table with the following steps:
1. In the Simulink model above, we double−click the Stateflow block named Chart, and a
blank Stateflow diagram editor appears as shown below.

Truth Table drawing tool

2. In the Stateflow diagram editor above, we click and drag the Truth Table tool
into the empty area and we place it to the right side as shown below. We observe that
it changes to a rectangle with the title truthtable with a flashing text cursor below it.

2−76 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

3. Where the cursor appears in the Stateflow diagram editor above, we enter the label
text t1=ttable1(X,Y,Cin) and we click outside the truth table rectangle. The label text
t1=ttable(X,Y,Cin) is referred to as the signature label where ttable1 defines its name,
(X,Y,Cin) are its arguments, and t1 is its return value. If we must change the signature
label at a later time, we can click the label to place an editing cursor in the text of the
label, and type−in the new name.
4. We repeat steps (2) and (3) above and for the second truthtable we enter the label
text t2=ttable2(X,Y,Cin), and we click outside the truthtable rectangle. The Stateflow
diagram editor now appears as shown below.

Introduction to Stateflow®with Applications 2−77


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

d. We specify the properties of the Truth Table functions with the following steps:

1. We right−click once* the first truth table function rectangle truthtable. The pop-up
menu shown below appears, and we select Properties from it.

* If we right−click twice, the truth table editor will appear. We will discuss this editor shortly.

2−78 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

2. The fields in the Truth Table Properties dialog window below contain the informa-
tion listed in the table below it.

Field Description
Name Function name (read only)
Breakpoints When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
Function Inline Option Controls the inlining of the truth table generated code
• Auto − Whether or not to inline the truth table function is decided by Stateflow
• Inline − The truth table function is inlined by Stateflow
• Function − The function is not inlined
Label The signature lavel is specified
Description Textual description and comments
Document Link A URL address or a MATLAB command may be entered

3. As mentioned earlier, the table functions t1=ttable1(X,Y,Cin) and t2=ttable2(X,Y,Cin)


are referred to as the signature labels where ttable1 and ttable2 define their name,
(X,Y,Cin) are their arguments, and t1 and t2 are their return values.

Introduction to Stateflow®with Applications 2−79


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

Now, we must specify a call to the truth table function in the Stateflow diagram, so
that when later the diagram executes during simulation, it calls* the truth table.
4. To call the ttable1 and ttable2 function from the default transition of their own State-

flow diagram, we select the Default Transition tool from the drawing toolbar
and we move the cursor to a location left of the truth table function. We observe that
the cursor changes to a shape with a downward arrow. We click to place a default tran-
sition into a terminating junction. We click the question mark character (?) that
appears on the highlighted default transition, we move it about two spaces to the right,
and where the blinking cursor for entering the label of the default transition appears,
we type the text {Sum=ttable1(A,B,C); Cout=ttable2(A,B,C);}. The Stateflow diagram
editor now appears as shown below.†

* We can call truth table functions from the actions of any state or transition. We can also call truth tables from other func-
tions including other truth tables and graphical functions, i.e., functions defined graphically. The functions ttable1 and
ttable2 in Figure 2.21 are graphical functions. If we export a truth table, we can call it from any Stateflow chart.
† To display the arrow in a vertical position, we move the cursor near the top of the arrow. and when a small circle appears,
we move it to the right until the arrow becomes vertical.

2−80 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

5. The Default Transition label {Sum=ttable1(A,B,C);Cout=ttable2(A,B,C);}, provides a


condition action that calls the truth table with arguments (A,B,C) and return values
t1 and t2. Thus, when Simulink triggers the Stateflow block during simulation, the
default transitions occur and calls to the truth tables ttable1 and ttable1 are initiated.
We must make sure that a call to the Stateflow truth table is matched with the truth
table signature. In this example, the type of the return values Sum and Cout must
match the return values t1 and t2, and the type of the arguments (A,B,C) match the
signature arguments (X,Y,Cin). The matching procedure is discussed next.
6. We select Model Explorer from the View drop menu of the FullAdder/Chart win-
dow above, and it appears as shown below.

We observe that in the Model Hierarchy (left) pane the functions ttable1 and ttable2
appear under Chart* which is the name of the Stateflow block in the Simulink model
of Figure 2.15. We also observe that when the function ttable1 is highlighted, the
Contents (center) pane displays the signature arguments (X,Y,Cin) as inputs, and the

* It may be necessary to expand Chart to see ttable1 and ttable2.

Introduction to Stateflow®with Applications 2−81


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

return value t1 as the output. Likewise, when the function ttable2 is highlighted, the
Contents pane displays the signature arguments (X,Y,Cin) as inputs, and the return
value t2 as the output. The pane on the right displays the function names, ttable1 and
ttable2 depending on which function is highlighted on the left pane, and shows the
check mark that we added in the Truth Table Properties dialog box. This pane also
shows the names of the default transitions as defined in the Stateflow diagram editor.
7. We now need to add the argument and return data used in calling ttable1 and ttable2.
We begin by selecting Chart in the Model Hierarchy pane and we observe that Chart
contains no data in the Contents pane. From the Add drop menu we select Data and
we observe that the name data appears in the Contents pane. This data matches* the
signature argument X in type and size. In the Contents pane, we double−click the
entry data in the Name column, we change the name to A, we press Enter, we click
the entry Local under the Scope column, and from the drop menu we select Input.†
We can see the new data input A in the Contents pane. We repeat this procedure to
add the data B and C with the Scope Input, and the data t1 and t2 with the Scope
Output. The Stateflow Model Explorer Contents pane now appears as shown below.

8. The Simulink model now appears as shown below.

* This can be verified by right−clicking in the Contents pane and selecting Properties. We observe that the type is double is
scalar which is the default when there is no entry in the Size field.
† The scope input means that Simulink provides this data which it passes to the Stateflow diagram through an input port on
the Stateflow block.

2−82 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

9. In the Chart block of the Simulink model above, the default transition data A, B, C,
t1, and t2, match their counterparts X, Y, Cin, Sum, and Cout, in the truth table sig-
nature in size (scalar) and type (double). We complete the Stateflow Truth Table by
making the connections shown below, and we save it as FullAdder. We are now ready
to program the truth table.

e. The Stateflow diagram editor that we created in Step (d).4, Page 2−80, is empty and
therefore we need to program it by specifying its behavior. We do this with the following
steps:

Introduction to Stateflow®with Applications 2−83


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

1. In the Stateflow diagram editor we double−click the truth table function ttable1 to
open its editor which is shown below. We observe that this empty default truth table
contains a Condition Table and an Action Table each with one row. The Condition
Table also contains a single Decision Column, D1, and a single action row. From the
Settings drop menu we select the Stateflow Classic Language.*

2. To specify the logical behavior of a truth table, we begin with the Condition column of
the Condition Table. We can also enter an optional description in the Description
column. The generic truth table of the full−adder contains the three inputs X, Y, and
Cin, and eight rows indicating that we need eight Decision columns. Therefore, we
must add two rows and seven columns to the Condition Table above. We do this by

clicking the Append Row tool twice, and by clicking Append Column tool
seven times. The Condition Table now appears as shown below where the entries are
described in Step 3 below.

* The programming language options for Stateflow truth tables are the Stateflow Classic (the default), and the Embedded
MATLAB. We have used the Embedded MATLAB option in Example 2.3.

2−84 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

3. In the Condition column of the Condition Table each condition that we enter must
be zero (false) or non−zero (true), that is, each condition must be specified as a == 0
or a == 1.* For this example arbitrarily we specified XEQ1: X = = 1, YEQ1: Y = = 1,
and CinEQ1: Cin = = 1. The entries in the Description column are optional. Whether
these three conditions are true or false, they are indicated in the Decision columns
D1 through D8. Thus, Decision column D1 shows that all three conditions are false
corresponding to Row 1 of the generic truth table for Full Adder, and for this reason
we have entered F (False)† in all three rows of Column D1. However, all three condi-
tions are satisfied in Column D8, and thus we have entered T (True) in that column.
Each decision column binds a group of condition outcomes with the logical AND
operation into a decision. The Actions W1 through W8 are defined in Step 4 below.
4. Next, we will program the Action Table of the truth table which appears below the
Condition Table. The entries to the Action Table for the truth table function
ttable1 are shown below.

* We can also use optional brackets, e.g., [a == 1] as in Stateflow language.


† Pressing the space bar on the keyboard toggles the possible values of F, −, and T. These characters can also be entered
directly. All other entries with other characters are rejected. The dash (−) character represents either a true or false deci-
sion and it is used in some applications as a don’t care decision.

Introduction to Stateflow®with Applications 2−85


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

The entries in the Description column of the Action Table are optional but are recom-
mended because they are carried into the generated code for the truth table as code
comments. The first row in the Action Table displays the initial action with the mes-
sage indicated under the Action column of the Action Table. Likewise, the tenth row
in the Action Table displays the final action with the message indicated under the
Action column of the Action Table. These messages will appear in MATLAB’s Com-
mand Window during simulation.
5. Rows 2 through 9 under the Action column of the Action Table define the Actions
W1 through W8, and these are consistent with the Output S (Sum) column of the
generic truth table of the Full Adder. From the Simulink model we observe that the
Display 1 block receives its input from t1 output of the Stateflow block.
f. The data we provided in Step (e) above are for the truth table function ttable1. We must
now provide the appropriate data for the truth table function ttable2 shown in the Truth-
Table editor below which is repeated for convenience.

2−86 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

We do this with the following steps:


1. We double−click the truth table function ttable2 shown above to open its editor
which is shown below.

From the Settings drop menu we select the Stateflow Classic Language.

Introduction to Stateflow®with Applications 2−87


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2. As with the table function ttable1, we must add two rows and seven columns to the
Condition Table. We do this by clicking the Append Row tool twice, and the
Append Column tool seven times, and we repeat the steps as with the table function
ttable1, above where the Actions V1 through V8 are defined in Rows 2 through 9
under the Action column of the Action Table, and these are consistent with the Out-
put Cout (Carry Out) column of the generic truth table of the Full Adder.

2−88 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

From the Simulink model below we observe that the Display 2 block receives its
input from t2 output of the Stateflow block.

g. The final step in completing the Simulink model for the Full Adder is to debug the truth
tables ttable1 and ttable2.
1. In the Truth Table Editor toolbar for ttable1 shown below, we click on the Diagnos-

tics tool

The Stateflow Builder window below displays a message that no errors were found.

Introduction to Stateflow®with Applications 2−89


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2. We repeat step (g).1 above for the Truth Table Editor toolbar of ttable2, and again we
are told that no errors were found.
3. In the MATLAB Command window, we enter the values X=0; Y=0; Cin=0;
4. We return to the Simulink model, we issue the simulation command, and our Simulink
model now is as shown below. We save the model as FullAdder.

5. We continue stepping through the simulation by changing the values of X, Y, and Cin
in accordance with the generic truth table of the Full adder to verify that the model
outputs the correct values for the Sum and Cout outputs.

2−90 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to End−of−Chapter Exercises

6. The Simulink model above can be improved by replacing the Constant blocks X, Y,
and Cin, with three Pulse Generator blocks, and replacing the Display blocks with
Scope blocks as shown below.

7. The waveforms of the Pulse Generator blocks and the waveforms for Sum and Cout
are shown below.

Introduction to Stateflow®with Applications 2−91


Copyright © Orchard Publications
Chapter 2 The Stateflow Truth Table

2−92 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 3
Embedded MATLAB Functions in Stateflow Charts

T
his chapter describes the procedure for adding Embedded MATLAB functions to Stateflow
charts. It begins with an introduction to Embedded MATLAB functions using an example,
followed by procedures for building a Simulink model with a Stateflow chart that calls the
Embedded MATLAB function. It concludes with a procedure for debugging Embedded MAT-
LAB functions in Stateflow Charts.

3.1 Introduction to Embedded MATLAB Functions


Figure 3.1 below shows a Stateflow Chart in a Simulink model, the Embedded MATLAB func-
tion inside the Stateflow Chart, and the Embedded MATLAB function in the Editor window.

Figure 3.1. Example of a Simulink model with a Stateflow Chart that contains an Embedded MATLAB function

Introduction to Stateflow®with Applications 3−1


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The structure of an Embedded MATLAB function is the same as that of a function used with the
Embedded MATLAB Function block* that is included in the Simulink User-Defined Func-
tions Library. The advantage of adding Embedded MATLAB functions to a Stateflow Chart is
the capability of coding algorithms in the textual MATLAB language instead of the Stateflow
graphical language.
It is best to illustrate the procedure for building a Simulink model with a Stateflow diagram that
calls an Embedded MATLAB function with an example.

Example 3.1
In this example we will build, program, and debug a model with a Stateflow Chart that contains
an Embedded MATLAB Function. The Stateflow Chart will accept a 3 × 3 matrix and will out-
put the value of its determinant and its inverse matrix. We will build the model in Section 3.2, we
will program it in Section 3.3, and will debug it in Section 3.4.

3.2 Building the Model with a Stateflow Embedded MATLAB Function

We begin with a new Simulink model that contains a Constant block, a Stateflow Chart, and two
Display blocks as shown in Figure 3.2. We save this model as matrix_det_inv_stateflow.

Figure 3.2. Blocks for the model of Example 3.1


In the model of Figure 3.2 we double−click the Stateflow Chart block to open the Stateflow Edi-
tor that appears in Figure 3.3.

* For the description of this block please refer to Introduction to Simulink with Engineering Applications, ISBN 978-0-
9744239-7-5 or the online Simulink documentation.

3−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function

Figure 3.3. The Stateflow Editor window


In the Stateflow Editor window of Figure 3.3, we drag two Embedded MATLAB functions into

the empty space of the Stateflow Editor using the Embedded MATLAB Function tool
from the tool palette. We observe that a flashing text cursor appears, and we define the first
function as
detout=detmat(value)
and the second as
invout=invmat(value)
These labels conform to the Embedded MATLAB function syntax
return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix
is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a row or
column with one dimension. Multiple return values are not allowed.
The Stateflow Editor window now appears as shown in Figure 3.4. The label eM above the flash-
ing text cursor where we enter the function name, indicates that this is an Embedded MATLAB
function.

Introduction to Stateflow®with Applications 3−3


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.4. Defined functions in the Stateflow Editor window.

In the Stateflow Editor window in Figure 3.4, we drag the Default Transition tool to form a
terminating junction, we click the question (?) mark to change it to a flashing text editor, and we
type
{det = detmat(invalue);
inv = invmat(invalue);}
and the Stateflow Editor window now appears as shown in Figure 3.5.

The function names at the Default Transition tool and the eM functions must be the
same. Thus, in the Stateflow Editor window in Figure 3.5, the function names detmat and invmat
are the same for the Default Transition tool and the eM functions.
The label on the Default Transition provides a condition action that calls the eM functions with
arguments and a return value. When the Stateflow block is triggered during simulation, the
Default Transition is taken and calls to the detmat and invmat functions are made.

3−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function

Figure 3.5. The Embedded MATLAB Editor window with defined condition actions
The return values of the eM functions, e.g., detout and invout are often referred to as the signa-
ture return values. The return values of the Default Transition, e.g., det and inv must match the
signature return values detout and invout, and the type of arguments in the Default Transition,
e.g., invalue must match the type of the signature arguments, e.g., value. This will be ensured
later when we define the inputs and outputs in the Model Explorer window.
In the Stateflow Editor window in Figure 3.5, we double-click the detmat function to edit its
function body in the Embedded MATLAB Editor shown in Figure 3.6.

Figure 3.6. The Embedded MATLAB Editor window for the detmat function

Introduction to Stateflow®with Applications 3−5


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

In the Embedded MATLAB Editor in Figure 3.6, we select Tools>Model Explorer, and the
Model Explorer window appears as shown in Figure 3.7.

Figure 3.7. Partial view of the Model Explorer window for detmat function
We observe that the function detmat is highlighted in the Model Hierarchy pane (left), and the
Contents pane (right) displays the input argument value and output argument detout. By default,
both are scalars of type double.

We double-click the value row under the Size column and we set the size of value to 3,3.* The
Model Explorer window appears as shown in Figure 3.8.

* This is the size of the input matrix that will be defined in the Constant block of the Simulink model, Figure 3.2.

3−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function

Figure 3.8. Defining the size of the input value for the detmat function in the Contents pane
We return to the Stateflow Editor window in Figure 3.5, and we double-click the invmat func-
tion to edit its function body in the Embedded MATLAB Editor shown in Figure 3.9.

Figure 3.9. The Embedded MATLAB Editor window for the invmat function
In the Embedded MATLAB Editor in Figure 3.9, we select Tools>Model Explorer, and the
Model Explorer window appears as shown in Figure 3.10.

Introduction to Stateflow®with Applications 3−7


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.10. Partial view of the Model Explorer window for invmat function
We observe that the function invmat is highlighted in the Model Hierarchy pane (left), and the
Contents pane (right) displays the input argument value and output argument invmat . By
default, both are scalars of type double.

We double-click the value row under the Size column and we set the size of value to 3,3.* The
Model Explorer window appears as shown in Figure 3.11.

* This is the size of the input matrix that will be defined in the Constant block of the Simulink model, Figure 3.2.

3−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Building the Model with a Stateflow Embedded MATLAB Function

Figure 3.11. Defining the size of the input value for the invmat function in the Contents pane
In the Model Hierarchy pane of the Model Explorer in Figure 3.11, we select Chart, from the
Add drop menu we select , and under the indicated columns in the Contents pane we
add the following data:

Name Scope Size


invalue Input from Simulink 3,3
det Output to Simulink Scalar (no change)
inv Output to Simulink Scalar (no change)

The Model Explorer now appears as shown in Figure 3.12.

Introduction to Stateflow®with Applications 3−9


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.12. Defining the Stateflow Chart input and outputs


Our Simulink model is now built and appears as shown in Figure 3.13 after connecting the Con-
stant block to the input of the Stateflow Chart and the Display blocks to the outputs of the
Stateflow Chart. The matrix A in the Constant block will be defined in the MATLAB command
prompt. The Stateflow chart will be programmed in the next section.

Figure 3.13. The built model for Example 3.1

3−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Programming the Stateflow Chart with an Embedded MATLAB Function

3.3 Programming the Stateflow Chart with an Embedded MATLAB Function


We begin by opening our saved model matrix_det_inv_stateflow and in the Stateflow Editor win-
dow we double-click the detmat function and this opens the Embedded MATLAB Editor win-
dow shown in Figure 3.14.

Figure 3.14. The Embedded MATLAB Editor window for the detmat function
After the function header in the Embedded MATLAB Editor window in Figure 3.14, we enter a
line space and we type the following comment lines:
% This function computes the determinant of a 3x3 matrix A
% that must be defined in MATLAB's Command Window.
%
The Embedded MATLAB Editor window now appears as shown in Figure 3.15

Figure 3.15. The Embedded MATLAB Editor window for the detmat function with comment lines
Next, we enter the following statement:
eml.extrinsic(‘plot’);
There is no need to plot anything in this example but we add this statement to point out that a
number of MATLAB functions are not supported by the Embedded MATLAB subset, and plot is

Introduction to Stateflow®with Applications 3−11


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

one of them. Should there be necessary to use MATLAB functions that are not supported by the
Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Calling
MATLAB Functions” in the Embedded MATLAB documentation.
The complete script for the Embedded MATLAB function detmat is listed below.
function detout=detmat(value)
% This function computes the determinant and the inverse of a 3x3
% matrix A which must be defined in MATLAB's Command Window.
%
eml.extrinsic('plot')
sz=size(value)
detout=determinant(value,sz);
plot(value,'-+');
%
% We also define the subfunction 'determinant' as follows:
%
function det = determinant(A,value)
det=A(1,1)*A(2,2)*A(3,3)+A(1,2)*A(2,3)*A(3,1)+A(1,3)*A(2,1)*A(3,2)...
-A(3,1)*A(2,2)*A(1,3)-A(3,2)*A(2,3)*A(1,1)-A(3,3)*A(2,1)*A(1,2);
This script is entered into the Embedded MATLAB Editor window as shown in Figure 3.16.

Figure 3.16. The Embedded MATLAB Editor window with the complete script for the function detmat
The complete script for the Embedded MATLAB function invmat is listed below.

3−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Programming the Stateflow Chart with an Embedded MATLAB Function

function invout=invmat(value)
% This function computes the inverse of a 3x3 % matrix A which must
% be defined in MATLAB's Command Window.
%
sz=size(value)
invout=inverse(value,sz);
% Now. we define the subfunction "inverse" as follows:
function inv = inverse(A,value)
%
% For a 3x3 matrix where A=[a11 a12 a13; a21 a22 a23; a31 a32 a33],
% the inverse of A is obtained as invA = (1/detA)*adjA where adjA
% represents the adjoint of A.
% Ref: Numerical Analysis, ISBN 0-9709511-1-6
% The cofactors are defined below.
%
b11=A(2,2)*A(3,3)-A(2,3)*A(3,2);
b12=-(A(2,1)*A(3,3)-A(2,3)*A(3,1));
b13=A(2,1)*A(3,2)-A(2,2)*A(3,1);
b21=-(A(1,2)*A(3,3)-A(1,3)*A(3,2));
b22=A(1,1)*A(3,3)-A(1,3)*A(3,1);
b23=-(A(1,1)*A(3,2)-A(1,2)*A(3,1));
b31=A(1,2)*A(2,3)-A(1,3)*A(2,2);
b32=-(A(1,1)*A(2,3)-A(1,3)*A(2,1));
b33=A(1,1)*A(2,2)-A(1,2)*A(2,1);
%
% We must remember that the cofactors of the elements of the ith
% row (column) of A are the elements of the ith column (row) of AdjA.
% Thus, for the next statement below, we use the single quotation
% character (') to transpose the elements of the resulting matrix.
%
adjA=[b11 b12 b13; b21 b22 b23; b31 b32 b33]';
%
inv=(1/det)*adjA
This script is entered into the Embedded MATLAB Editor window as shown in Figure 3.17.

Introduction to Stateflow®with Applications 3−13


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.17. The Embedded MATLAB Editor window with the complete script for the function invmat

3−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

The functions det(A) and inv(A) are defined in MATLAB but are not included in the Embed-
ded MATLAB Run−Time Function Library List. This list includes common functions as sqrt,
sin, cos, and others. Thus, had we issued the simulation command without defining the function
[det, inv] = matrix(A), Simulink would have issued the following warnings:
Output det must be assigned before returning from the function
Output inv must be assigned before returning from the function
Our model is now complete and it is shown in Figure 3.18 where we have named the Stateflow
Chart block Matrix Operations, and we have stretched the Display 2 block to accommodate
the nine elements of the inverse matrix after the simulation command is issued. The value of the
determinant will provide us with an indication whether the given matrix is well-behaved or is an
ill-conditioned matrix.* We save the model and we will simulate it in the next section.

Figure 3.18. The completed model for Example 3.1 prior to execution of the simulation command.

3.4 Simulation of the Matrix Operations Stateflow Chart


To set the simulation parameters, we double−click the Matrix Operations Stateflow chart in Fig-
ure 3.18, in the Stateflow Editor window from the Simulation drop menu we select Configura-
tion Parameters, we click Solver in the left Select pane, and in the Simulation time and Solver
options panes we verify the selections shown in Figure 3.19, and we make changes if necessary.
We click OK to accept these values.

* This topic is discussed in Numerical Analysis Using MATLAB and Excel, ISBN-13: 978-1-934404-03-4

Introduction to Stateflow®with Applications 3−15


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.19. The Configuration Parameters dialog box


When a Simulink model that contains a Stateflow Chart block is simulated, we can animate the
Stateflow Chart to highlight the states and the transitions as they occur, and this feature provides
visual verification that our chart behaves as expected. Animation is enabled by default but we
need to specify the speed. To make sure that the animation has been enabled, we double-click the
Matrix Operations Stateflow Chart in the model in Figure 3.18, in the Stateflow Editor window in
Figure 3.20 from the Tools drop menu we select Open Simulation Target, and this opens the
Stateflow Target Builder dialog box* shown in Figure 3.21.

* A target is a program that executes a Stateflow chart or a Simulink model that contains a Stateflow chart, and the State-
flow Target Builder dialog box in Figure 3.21 is used to configure Stateflow for building targets. Stateflow then builds a
simulation target (sfun) file that allows us to simulate our Stateflow application in Simulink.

3−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.20. The Stateflow Editor window to select Tools>Open Simulation Target

Figure 3.21. The Target Builder window for selecting Target Options and Coder Options

Introduction to Stateflow®with Applications 3−17


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

In the Stateflow Target Builder dialog box in Figure 3.21, we click the Coder Options button,
and the Stateflow sfun Coder Options dialog box appears as shown in Figure 3.22 where we
observe that Enable debugging/animation is checked.

Figure 3.22. The Coder Options window to Enable debugging/animation


To set the animation speed, from the Stateflow Editor window in Figure 3.20 we click the Debug

tool and the Stateflow Debugging window appears as shown in Figure 3.23 where the Delay
(sec) has been set to 1 sec so that the animation will proceed at the slowest speed.

Figure 3.23. The Stateflow Debugging window to start simulation with breakpoints

3−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the
debugger to pause simulation during run−time activities. Breakpoints that can set in the State-
flow Debugging window are listed below.

Breakpoint Description
Chart Entry Simulation halts when Stateflow chart “wakes up”
Event Broadcasta Simulation halts when an external event occurs.
State Entry Simulation halts when a state becomes active
a. There is no such event used in this example, and thus we will not use Event Broadcast.

In the Stateflow Debugging window in Figure 3.23, we check Chart Entry and State Entry as
breakpoints and this window now appears as shown in Figure 3.24.

Figure 3.24. The Stateflow Debugging window with selected breakpoints


The option Browse Data in Figure 3.24 is a menu for observing data when simulation pauses at a
breakpoint. In the window of Figure 3.24 the Browse Data is inactive but it will become active
when simulation begins and halts at a breakpoint.
Before simulation begins, Stateflow builds the simulation target by performing the following
actions:

Introduction to Stateflow®with Applications 3−19


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

• Parses the Stateflow chart for errors such as no default transition at every level of the State-
flow hierarchy that contains exclusive (OR) states, input data objects do not inherit properties
from the associated Simulink signal, and output data objects do inherit types and sizes.
• Generates C code that represents the behavior of the Stateflow chart
• Builds the generated code into an executable program for the simulation target, referred to as
sfun target.
• Creates a directory referred to as sfprj in the directory where the chart resides to store the gen-
erated files that make up the sfun target.
• Creates a MEX (MATLAB executable) file that corresponds to the C source file
During each of these processes, status messages are displayed at the MATLAB Command Win-
dow.
We are now ready to begin simulation but before we issue the Start command in the Stateflow
Debugging window, we position the Simulink model, the Stateflow Editor window, and the
Stateflow Debugger window so that all are visible as shown in Figure 3.25.

3−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.25. The Stateflow Editor, the Scope block, and the Stateflow Debugging windows for data observation
In the Stateflow Debugger window in Figure 3.25, we begin simulation by clicking the Start but-
ton. We observe that Stateflow displays a Block Error message for the Constant block as indi-
cated in Figure 3.26. This is because we failed to define the elements of the matrix A in the
MATLAB Command Window before starting the simulation. Therefore, we open the MATLAB
Command Window and we enter the elements of matrix A as
A=[3 −2 0; −1 4 7; 5 8 −6];
In the Stateflow Debugger window in Figure 3.25 we click again the Start button and we
observe that it is changed to a Continue button as shown in Figure 3.27. We also observe that
the Browse Data field is now active, in the model window in Figure 3.28 the Display blocks
have been filled with zeros, and the Start command button has been replaced with the Stop
button and the Pause button .

Introduction to Stateflow®with Applications 3−21


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.26. Block error message indicating “Undefined function or variable A”

Figure 3.27. The Stateflow Debugging window after the simulation command has been issued
In the Stateflow Debugging window in Figure 3.27 we click the down arrow to the right of the
Browse Data option and we select All Data (Current Chart) from the submenu. The Browse
Data option now appears in green color and displays the status of the model at the start of the
simulation as shown in Figure 3.29.

3−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.28. The Simulink model of Example 3.1 at the start of simulation
We can also view this value in the MATLAB Command window by pressing the Enter key at
the command prompt and MATLAB displays
debug>>
and at the command prompt we type det and MATLAB displays the value of the determinant at
the start of the simulation.
det =
0
To see the value of the inverse of the matrix, at the MATLAB Command Window we type inv
and MATLAB displays
inv =
0 0 0
0 0 0
0 0 0

Introduction to Stateflow®with Applications 3−23


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.29. The Stateflow Debugging window at the start of simulation

As we continue with the simulation, we observe that the plot appears as shown in Figure 3.30,*
and the Default Transition tool in the Stateflow Editor window appears highlighted on and off
during the simulation as shown in Figure 3.31.
To advance through the rest of the simulation in the Stateflow Debugging window in Figure
3.29, we check the Disable all field to remove all breakpoints, and we click the Continue button
and we observe the status at simulation time from zero to 10 seconds. In the Simulink model
shown in Figure 3.32, the Progress bar at the bottom of the window indicates 7.2 seconds have
elapsed after the start of the simulation.

* For clarity, this plot has been edited using the MATLAB Edit Figure properties.

3−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.30. The plot generated by the plot(value,’-+’) statement

Figure 3.31. The Default Transition highlighted on and off during simulation execution

Introduction to Stateflow®with Applications 3−25


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.32. The Simulink model for Example 3.1 at simulation time T=7.2 seconds
The Simulink model at the end of simulation time is shown in Figure 3.33.

Figure 3.33. The Simulink model for Example 3.1 at the end of simulation time

We can use simulation to test our Embedded MATLAB functions for run-time errors that are not
detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the Embedded
MATLAB functions for missing or undefined information and possible logical conflicts. The pro-
cedure is illustrated by simulating and debugging the detmat function during run-time conditions
as follows:

3−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

In the model of Figure 3.33 above we double click the Matrix Operations Stateflow Chart and
this opens the Stateflow Editor window shown in Figure 3.34.

Figure 3.34. The Stateflow Editor window


We double-click the detmat function and the Embedded MATLAB Editor window appears as
shown in Figure 3.35. We click the dash (-) character in the left margin of line 6 and we observe
that a small red ball appears next to line 6 as shown in Figure 3.36 indicating that we’ve set a
breakpoint there.

In the Embedded MATLAB Editor window in Figure 3.36, we click the Start Simulation tool
(green arrow) to begin simulation. If we get any errors, we make corrections before simulation
again. If no errors are detected, the simulation pauses when execution reaches the breakpoint
that we’ve set, and this is indicated by a small green arrow in the left margin as shown in Fig-
ure 3.37.

We click the Step tool to advance the execution one line, i.e., to line 7, indicated by the
small green arrow shown in Figure 3.38. But if we click again the Step tool, execution will
advance to line 8, and we will not see the execution of the subfunction determinant. For this rea-

son, we need to click the Step In tool which is immediately to the right of the Step tool on
the main task bar in the Embedded MATLAB Editor window. Therefore, to advance execution
to the first line of the subfunction determinant, we click the Step In tool, and the Embedded
MATLAB Editor window now appears as shown in Figure 3.39.

Introduction to Stateflow®with Applications 3−27


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.35. The Embedded MATLAB Editor window where we click the dash (-) character in line 6

Figure 3.36. The Embedded MATLAB Editor window with the small red ball in line 6 indicating a breakpoint

3−28 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.37. Green arrow in line 6 indicating that execution has reached the breakpoint that we’ve set

Figure 3.38. Using the Step tool to advance execution one line

Introduction to Stateflow®with Applications 3−29


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.39. Using the Step In tool to track execution of the determinant subfunction
Once we are in the subfunction line, we can advance through the subfunction statements one
line at a time. with the Step tool. But if the subfunction calls another subfunction, we should use
the Step In tool to step into it.
If we want to continue through the remaining lines of the subfunction and go back to the line

after the subfunction call, we should use the Step Out tool .
When the subfunction finishes execution, we will see a green arrow pointing down under its last
line as shown in Figure 3.40.

3−30 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.40. The Editor window with a green arrow pointing down to indicate end of execution
We click the Step tool to return to the detmat function and we observe that execution advances
to line 8 as shown in Figure 3.41, and the plot is displayed as shown in Figure 3.42.
If we want to see the value of the variable sz in line 6, we place the text cursor over the text sz
for about two seconds, and the value appears as shown in Figure 3.43. Using the same procedure,
we can see the value of any data.
The values can also be seen in the MATLAB Command window. When a breakpoint is reached,
the debug >> command appears.* At this prompt, we enter the name of the data, for example,
debug>> sz
sz =
3 3
debug>>

* We may need to press the Enter key to see it.

Introduction to Stateflow®with Applications 3−31


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.41. Clicking the Step tool one more time causes execution to advance to line 8

Figure 3.42. Generated plot when execution advances to line 8

3−32 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulation of the Matrix Operations Stateflow Chart

Figure 3.43. Display of the size of matrix A when the text cursor is placed over the text sz
If we want to leave the function until it is called again, we click the Continue Debugging tool

and the breakpoint on line 6 is reached again. Then, we can advance through the execution
of the remaining statements with the Continue Debugging tool.
To remove the breakpoint at line 6, we click it and then we click the green arrow to complete
execution of the simulation. The model then will be completed as shown below.

Introduction to Stateflow®with Applications 3−33


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Figure 3.44. Model with computed values of determinant and inverse of the matrix at completion of simulation

3−34 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

3.5 Summary
• Embedded MATLAB functions insert the powerful features of MATLAB into Stateflow
Charts.
• The Embedded MATLAB Run−Time Function Library List includes common functions as
sum, sqrt, sin, cos, and others. Those not included in this list must be declared to be extrinsic
so that they can be resolved as MATLAB functions. The command plot, and the functions
det and inv are examples of commands and functions not included in this list and thus they
must be declared to be extrinsic or defined as subfunctions.
• The structure of an Embedded MATLAB function is the same as that of a function used with
the Embedded MATLAB Function block that is included in the Simulink User-Defined
Functions Library.
• The advantage of adding Embedded MATLAB functions to a Stateflow Chart is the capabil-
ity of coding algorithms in the textual MATLAB language instead of the Stateflow graphical
language.
• To place Embedded MATLAB functions into Stateflow Editor we drag the Embedded MAT-

LAB Function tool from the tool palette into the Stateflow Editor window. The label
eM above the flashing text cursor where we enter the function name, indicates that this is an
Embedded MATLAB function.
• The syntax for Embedded MATLAB functions is return_value=function_name(argument1,
argument2,...) where the return_value and each argument can be a scalar, vector, or matrix of
values. A matrix is a two−dimensional array (rows and columns) of values, and a vector is a
matrix with a row or column with one dimension. Multiple return values are not allowed.

• The function names at the Default Transition tool and the eM functions must be the
same. Thus, in the Stateflow Editor window below

the function names detmat and invmat are the same for the Default Transition tool and the
eM functions.

Introduction to Stateflow®with Applications 3−35


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The label on the Default Transition provides a condition action that calls the eM functions
with arguments and a return value. When the Stateflow block is triggered during simulation,
the Default Transition is taken and calls to the detmat and invmat are made.
• The return values of the eM functions, e.g., detout and invout are often referred to as the sig-
nature return values. The return values of the Default Transition, e.g., det and inv must match
the signature return values detout and invout, and the type of arguments in the Default Tran-
sition, e.g., invalue must match the type of the signature arguments, e.g., value. This is
ensured by the entries we make into the Model Explorer window to define the inputs and
outputs of the Stateflow chart.
• To access the Model Explorer window to define the inputs and outputs of the Stateflow
chart, we click each of the eM functions in the Stateflow Editor window, and in the Embed-
ded MATLAB Editor window that appears we select Tools>Model Explorer, and in the
Model Explorer window the Model Hierarchy pane (left), and the Contents pane (right) dis-
play the input and output arguments of the eM function with the appropriate size under the
Size column.
• To ensure that the type of arguments in the Default Transition match the type of the signa-
ture arguments, in the Model Hierarchy pane of the Model Explorer in Figure 3.11, we select
Chart, from the Add drop menu we select , and under the indicated columns in the
Contents pane we add the appropriate data.
• To program a Stateflow Chart with an Embedded MATLAB function, in the Stateflow Editor
window we double-click the eM function and this opens the Embedded MATLAB Editor
window. After the function header in the Embedded MATLAB Editor window, we enter a
line space and appropriate comment lines.
• To use MATLAB functions that are not supported by the Embedded MATLAB subset, we
must first declare them to be extrinsic as described in “Calling MATLAB Functions” in the
Embedded MATLAB documentation.
• To set the simulation parameters, we double−click the Stateflow chart, in the Stateflow Editor
window from the Simulation drop menu we select Configuration Parameters, we click
Solver in the left Select pane, and in the Simulation time and Solver options panes we verify
the selections chosen earlier, and we make changes if necessary. We click OK to accept these
values.
• We can animate the Stateflow Chart to highlight the states and the transitions as they occur,
and this feature provides visual verification that our chart behaves as expected. Animation is
enabled by default but we need to specify the speed. To make sure that the animation has
been enabled, we double-click the Stateflow Chart, in the Stateflow Editor window from the
Tools drop menu we select Open Simulation Target, and this opens the Stateflow Target
Builder dialog box. In the Stateflow Target Builder dialog box, we click the Coder Options

3−36 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

button, and the Stateflow sfun Coder Options dialog box appears and by default we observe
that Enable debugging/animation is checked.

• To set the animation speed, from the Stateflow Editor window we click the Debug tool
and the Stateflow Debugging window appears. It is best to set the Delay (sec) to 1 sec so
that initially the animation will proceed at the slowest speed.
• To observe the behavior of our Stateflow chart in slow motion, we need to set breakpoints in
the debugger to pause simulation during run−time activities. Breakpoints that can set are
listed below.

Breakpoint Description
Chart Entry Simulation halts when Stateflow chart “wakes up”
Event Broadcasta Simulation halts when an external event occurs.
State Entry Simulation halts when a state becomes active
a. Breakpoint at this event is normally omitted

• To start simulation with breakpoints, it is best to begin by checking the Chart Entry and
State Entry as breakpoints in the Stateflow Debugging dialog box. The option Browse Data
is a menu for observing data when simulation pauses at a breakpoint. This option is initially
inactive but it becomes active when simulation begins and halts at a breakpoint.
• Before simulation begins, Stateflow builds the simulation target by performing the following
actions:
1. Parses the Stateflow chart for errors such as no default transition at every level of the
Stateflow hierarchy that contains exclusive (OR) states, input data objects do not
inherit properties from the associated Simulink signal, and output data objects do
inherit types and sizes.
2. Generates C code that represents the behavior of the Stateflow chart
3. Builds the generated code into an executable program for the simulation target,
referred to as sfun target.
4. Creates a directory referred to as sfprj in the directory where the chart resides to store
the generated files that make up the sfun target.
5. Creates a MEX (MATLAB executable) file that corresponds to the C source file
During each of these processes, status messages are displayed at the MATLAB Command
Window.

Introduction to Stateflow®with Applications 3−37


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

• Before issuing the Start command in the Stateflow Debugging window, it is a good idea to
position the Simulink model window, the Stateflow Editor window, and the Stateflow
Debugger window so that all are visible and we can observe the changes as the simulation
advances. as shown in Figure 3.25. If an error is detected, Stateflow displays a Block Error
message with the name and location of the offending block, and we are allowed to make the
necessary corrections. After the corrections are made, in the Stateflow Debugger window in
we click again the Start button and we observe that it is changed to a Continue button. We
also observe that the Browse Data field is now active, and in the model window the Display
blocks have been filled with zeros, and the Start command button has been replaced with
the Stop button and the Pause button . We click the down arrow to the right of the
Browse Data option and we select All Data (Current Chart) from the submenu. The
Browse Data option now appears in green color and displays the status of the model at the
start of the simulation. We can also view this value in the MATLAB Command window by
pressing the Enter key at the command prompt and entering the value where MATLAB dis-
plays debug>>.
• To advance through the rest of the simulation in the Stateflow Debugging window we check
the Disable all field to remove all breakpoints, we click the Continue button, and we observe
the status at simulation time from zero to 10 seconds or any other simulation time that we
have chosen. The Progress bar at the bottom of the model window indicates the time that
has elapsed after the start of the simulation.
• We can use simulation to test our Embedded MATLAB functions for run-time errors that are
not detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the
Embedded MATLAB functions for missing or undefined information and possible logical con-
flicts. The procedure for simulating and debugging an eM function during run-time conditions
is as follows:

1 In the Stateflow Editor window, we double-click the eM function and the Embedded
MATLAB Editor window that appears, we click the dash (-) character in the left margin
of a line of interest and we observe that a small red ball appears next to that line 6 indicat-
ing that we’ve set a breakpoint there.

2. In the Embedded MATLAB Editor window we click the Start Simulation tool (green
arrow) to begin simulation. If we get any errors, we make corrections before simulation
again. If no errors are detected, the simulation pauses when execution reaches the break-
point that we’ve set, and this is indicated by a small green arrow in the left margin.

3. We click the Step tool to advance the execution one line indicated by the small
green arrow. If we click again the Step tool, execution will advance to another line and we
will not see the execution of the subfunction that we’ve selected. To advance execution to

3−38 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

the first line of the subfunction that we’ve selected, we click the Step In Step In tool
tool.
4. Once we are in the subfunction line, we can advance through the subfunction statements
one line at a time. with the Step tool. But if the subfunction calls another subfunction, we
should use the Step In tool to step into it.
5. If we want to continue through the remaining lines of the subfunction and go back to the

line after the subfunction call, we should use the Step Out tool .
6. When the subfunction finishes execution, we will see a green arrow pointing down under
its last line.
7. If we want to see the value of a variable, we place the text cursor over the text of that vari-
able for about two seconds, and the value appears above the text of that variable. Using
the same procedure, we can see the value of any data.
8. The values can also be seen in the MATLAB Command window. When a breakpoint is
reached, the debug >> command appears.* At this prompt, we enter the name of the
data.
9. If we want to leave the function until it is called again, we click the Continue Debugging

tool and the breakpoint on selected line is reached again. Then, we can advance
through the execution of the remaining statements with the Continue Debugging tool.
10. To remove the breakpoint at the selected line, we click it and then we click the green
arrow to complete execution of the simulation.

* We may need to press the Enter key to see it.

Introduction to Stateflow®with Applications 3−39


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

3.6 Exercises for the Reader


1. From antenna theory, for a half-wave dipole in the direction of maximum radiation, the power
density P in watts per square meter and the electric field strength E in volts per meter, in the
direction of maximum radiation are given by
2
P = 1.64P t ⁄ 4πR

E = ( 49.2P t ) ⁄ R

respectively where P t is the transmitted power in watts and R is the distance in meters.

Using Embedded MATLAB Functions, create a Simulink model that includes a Stateflow
Chart block to display the values of the power density P and the electric field strength E for
given values of P t and R . Use the plot command by declaring it as extrinsic to display the coor-
dinates of the input values of P t and R .

2. The dimensionless unit named the Erlang is used in telephony as a statistical measure of the
volume of telecommunications traffic. It is named after the Danish telephone engineer A. K.
Erlang, the originator of traffic engineering and queueing theory. Traffic of one Erlang refers to
a single resource being in continuous use, or two channels being at fifty percent use, and so on.
For example, if an office had two telephone operators who are both busy all the time, that
would represent two Erlangs of traffic. Alternatively, an Erlang may be regarded as a "use mul-
tiplier" per unit time, so 100% use is 1 Erlang, 200% use is 2 Erlangs, and so on. For example, if
total cell phone use in a given area per hour is 180 minutes, this represents 180/60 = 3 Erlangs.
In general, if the mean arrival rate of new calls is λ per unit time and the mean call holding
time is h , then the traffic in Erlangs A is:
A = λ×h
This may be used to determine if a system is over-provisioned or under-provisioned (has too
many or too few resources allocated). For example, the traffic measured over many busy hours
might be used for a T1 or E1 circuit group to determine how many voice lines are likely to be
used during the busiest hours. If no more than 12 out of 24 channels are likely to be used at any
given time, the other 12 might be made available as data channels.
Traffic, measured in Erlangs, is used to calculate grade of service (GoS) or quality of service
(QoS). There are a range of different Erlang formulae to calculate these, including Poisson,
Erlang B, and Erlang C.
Blocking refers to the inability to interconnect two idle lines connected to a network because
all possible paths between them are already in use.

3−40 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercises for the Reader

The three most commonly models for determining the probability of blocked calls are the Pois-
son, Erlang B, and Erlang C models. All three assume an infinite number of sources, random
traffic arrival pattern, and hold times exponentially distributed. The Poisson model assumes
blocked calls held, the Erlang B model assumes blocked calls cleared, and the Erlang C model
assumes blocked calls delayed.
The Poisson model gives the probability P of blocking as
c–1
–a
∑a
n
P = 1–e ⁄ n!
n=0

The Erlang B model gives the probability P of blocking as

⎛ c ⎞
P = ( a ⁄ c! ) ⁄ ⎜ a ⁄ n!⎟
c

n
⎜ ⎟
⎝ n=0 ⎠

The Erlang C model gives the probability of blocking as

⎛ c–1 ⎞
P = a c ⁄ c( c – a) ⁄ ⎜ a ⁄ n! + a c ⁄ c ( c – a )⎟
c c

n
⎜ ⎟
⎝ n=0 ⎠

where:
a = traffic load in Erlangs
c = number of circuits commonly referred to as trunks
P= probability of blocking
Create a Simulink model that includes a Stateflow Chart block to display the probability val-
ues for each of these three models. Should you encounter any problems, replace the Stateflow
Chart with the Simulink Embedded MATLAB Function block found in the Simulink User-
Defined Function Library.

Introduction to Stateflow®with Applications 3−41


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

3.7 Solution to the End-of-Chapter Exercises


1. In the MATLAB Command window we type
sfnew
and the untitled model shown below is displayed.

From the Simulink Library Browser, we highlight the Commonly Used Blocks library and
from it we drag two Constant blocks. Then we highlight the Sinks library and from it we drag
two Display blocks. We rearrange, we rename the Constant blocks as Constant 1 and Con-
stant 2 , and the Display blocks as Display 1 and Display 2 . We save this model as
Dipole_Stateflow. The model now appears as shown below.

We double-click the Stateflow Chart and the Stateflow Editor window appears as shown
below.

3−42 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

In the Stateflow Editor window above, we drag two Embedded MATLAB functions into the

empty space of the Stateflow Editor using the Embedded MATLAB Function tool from
the tool palette. We observe that a flashing text cursor appears, and we define the first func-
tion as
PowerDensity=dipoleP(value1,value2)
and the second as
ElectricField=dipoleE(value1,value2)
These labels conform to the Embedded MATLAB function syntax
return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A
matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with
a row or column with one dimension. Multiple return values are not allowed.

Introduction to Stateflow®with Applications 3−43


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The Stateflow Editor window now appears as shown below. The label eM above the flashing
text cursor where we enter the function name, indicates that this is an Embedded MATLAB
function.

In the Stateflow Editor window above, we drag the Default Transition tool to form a ter-
minating junction, we click the question (?) mark to change it to a flashing text editor, and we
type
{Power = dipoleP(invalue1,invalue2);
Field = dipoleE(invalue1,invalue2);}
and the Stateflow Editor window now appears as shown below.

3−44 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The function names at the Default Transition tool and the eM functions must be the
same. Thus, in the Stateflow Editor window below, the function names dipoleP and dipoleE
are the same for the Default Transition tool and the eM functions.
The label on the Default Transition provides a condition action that calls the eM functions
with arguments and a return value. When the Stateflow block is triggered during simulation,
the Default Transition is taken and calls to the dipoleP and dipoleE functions are made.The
return values of the eM functions, i.e., PowerDensity and ElectricField are often referred to as
the signature return values. The return values of the Default Transition, i.e., Power and Field
must match the signature return values PowerDensity and ElectricField, and the type of argu-
ments in the Default Transition, e.g., invalue1 must match the type of the signature argu-
ments, i.e., value1. This will be ensured later when we define the inputs and outputs in the
Model Explorer window.
In the Stateflow Editor window above, we double-click the eM dipoleP function to edit its
function body in the Embedded MATLAB Editor shown below.

In the Embedded MATLAB Editor above, we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.

Introduction to Stateflow®with Applications 3−45


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We observe that the function dipoleP is highlighted in the Model Hierarchy pane (left), and
the Contents pane (right) displays the input arguments value1 and value2, and output argu-
ment PowerDensity. By default, both are scalars of type double.
We return to the Stateflow Editor window and we double-click the eM dipoleE function to
edit its function body in the Embedded MATLAB Editor shown in below.

3−46 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.

We observe that the function dipoleE is highlighted in the Model Hierarchy pane (left), and
the Contents pane (right) displays the input arguments value1 and value2, and output argu-
ment ElectricField. By default, both are scalars of type double.

Introduction to Stateflow®with Applications 3−47


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

In the Model Hierarchy pane of the Model Explorer above, we select Chart, from the Add
drop menu we select , and under the indicated columns in the Contents pane we add
the following data:

Name Scope Size


invalue1 Input from Simulink Scalar (no change)
invalue2 Input from Simulink Scalar (no change)
Power Output to Simulink Scalar (no change)
Field Output to Simulink Scalar (no change)

The Contents pane in the Model Explorer now appears as shown below.

Our Simulink model is now built and appears as shown below after connecting the Constant
blocks to the inputs of the Stateflow Chart and the Display blocks to the outputs of the State-

3−48 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

flow Chart. We have renamed the Constant blocks P t for Power transmitted, and R for dis-
tance. The values of P t and R will be defined in the MATLAB command prompt. We save
the model and we will program the Stateflow chart in the next paragraphs.

We begin the programming by opening our saved model Dipole_Stateflow and in the Stateflow
Editor window we double-click the dipoleP function and this opens the Embedded MATLAB
Editor window shown below.

After the function header in the Embedded MATLAB Editor window above, we enter a line
space and we type the following comment lines:
% This function computes the Power Density of a half-wave
% dipole in terms of the transmitted power Pt and distance R
% whose values will be entered in MATLAB's Command Window.
%
The Embedded MATLAB Editor window now appears as shown below.

Introduction to Stateflow®with Applications 3−49


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Next, we enter the following statement:


eml.extrinsic(‘plot’);
This statement will enable us to see the input values of P t and R in a plot to be defined below.
As we now know, there are a number of MATLAB functions are not supported by the Embed-
ded MATLAB subset, and plot is one of them. Should there be necessary to use MATLAB
functions that are not supported by the Embedded MATLAB subset, we must first declare
them to be extrinsic as described in “Calling MATLAB Functions” in the Embedded MAT-
LAB documentation.
The complete script for the Embedded MATLAB function PowerDensity is listed below.

function PowerDensity=dipoleP(value1,value2)
% This function computes the Power Density of a half-wave
% dipole in terms of the transmitted power Pt and distance R
% whose values will be entered in MATLAB's Command Window.
%
eml.extrinsic('plot')
PowerDensity=PD(value1,value2)
function Power=PD(Pt,R)
Power=1.64*Pt/(4*pi*R^2);
plot(Pt,R,’-+’);
%
This script is entered into the Embedded MATLAB Editor window as shown below.

3−50 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The complete script for the Embedded MATLAB function ElectricField is listed below.
function ElectricField=dipoleE(value1,value2)
% This function computes the Electric Field of a half-wave
% dipole in terms of the transmitted power Pt and distance R
% whose values will be entered in MATLAB's Command Window.
%
ElectricField=EF(value1,value2);
function Field=EF(Pt,R)
Field=sqrt(49.2.*Pt)./R;
%
This script is entered into the Embedded MATLAB Editor window as shown below.

Introduction to Stateflow®with Applications 3−51


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We name the Stateflow Chart as shown below and save the model. We will simulate it in the
next paragraph.

To set the simulation parameters, we double−click the Stateflow chart in the Simulink model
above, in the Stateflow Editor window from the Simulation drop menu we select Configura-
tion Parameters, we click Solver in the left Select pane, and in the Simulation time and
Solver options panes we verify the selections shown below, and we make changes if necessary.
We click OK to accept these values.

3−52 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

When a Simulink model that contains a Stateflow Chart block is simulated, we can animate
the Stateflow Chart to highlight the states and the transitions as they occur, and this feature
provides visual verification that our chart behaves as expected. Animation is enabled by
default but we need to specify the speed. To make sure that the animation has been enabled,
we double-click the Computations Stateflow Chart in the model Dipole_Stateflow in the pre-
vious page, and the Stateflow Editor window appears as shown below. From the Tools drop
menu we select Open Simulation Target, and this opens the Stateflow Target Builder dialog
box shown below.

Introduction to Stateflow®with Applications 3−53


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

In the Stateflow Target Builder dialog box above, we click the Coder Options button, and
the Stateflow sfun Coder Options dialog box appears as shown below where we observe that
Enable debugging/animation is checked.

3−54 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

We can set the animation speed from the Stateflow Editor window below.

In the Stateflow Editor window above we click the Debug tool and the Stateflow Debug-
ging window appears below where the Delay (sec) has been set to 1 sec so that the animation
will proceed at the slowest speed.

Introduction to Stateflow®with Applications 3−55


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the
debugger to pause simulation during run−time activities. Breakpoints that can set in the State-
flow Debugging window are listed below.

Breakpoint Description
Chart Entry Simulation halts when Stateflow chart “wakes up”
Event Broadcasta Simulation halts when an external event occurs.
State Entry Simulation halts when a state becomes active
a. There is no such event used in this example, and thus we will not use Event Broadcast.

In the Stateflow Debugging window above, we check Chart Entry and State Entry as break-
points and this window now appears as shown below.

3−56 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The option Browse Data in the lower part of the Stateflow Debugging window above is a
menu for observing data when simulation pauses at a breakpoint. In the window above the
Browse Data is inactive but it will become active when simulation begins and halts at a break-
point.
Before simulation begins, Stateflow builds the simulation target by performing the following
actions:
• Parses the Stateflow chart for errors such as no default transition at every level of the State-
flow hierarchy that contains exclusive (OR) states, input data objects do not inherit prop-
erties from the associated Simulink signal, and output data objects do inherit types and
sizes.
• Generates C code that represents the behavior of the Stateflow chart
• Builds the generated code into an executable program for the simulation target, referred to
as sfun target.
• Creates a directory referred to as sfprj in the directory where the chart resides to store the
generated files that make up the sfun target.
• Creates a MEX (MATLAB executable) file that corresponds to the C source file
During each of these processes, status messages are displayed at the MATLAB Command
Window.

Introduction to Stateflow®with Applications 3−57


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We are now ready to begin simulation but before we issue the Start command in the Stateflow
Debugging window, we position the Simulink model, the Stateflow Editor window, and the
Stateflow Debugger window so that all are visible as shown below.

In the Stateflow Debugger window above, we begin simulation by clicking the Start button.
As shown below, the Stateflow displays two Block error messages indicating that the values of
P t and R are not defined. This is because we failed to define these values in the MATLAB
Command window before starting the simulation. Therefore, we open the MATLAB Com-
mand Window and we enter the values of P t and R as
Pt=2; R=1000;

3−58 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

In the Stateflow Debugger window we click again the Start button and we observe that it is
changed to a Continue button. We also observe that the Browse Data field is now active as
shown below.

Introduction to Stateflow®with Applications 3−59


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We also observe that in the model window the Display blocks have been filled with zeros, and
the Start command button has been replaced with the Stop button and the Pause button
, as shown below.

In the Stateflow Debugging window we click the down arrow to the right of the Browse Data
option and we select All Data (Current Chart) from the submenu. The Browse Data option
now appears in green color and displays the status of the model at the start of the simulation as
shown below.
We can also view this value in the MATLAB Command window by pressing the Enter key at
the command prompt and MATLAB displays
debug>>
The values of the outputs Power and Field at this time can be displayed by entering
debug>> Power
Power =
0

debug>> Field

Field =
0

debug>>

3−60 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

As we continue with the simulation, we observe that the plot appears as shown below where
the cross (+) symbol indicates the coordinates of the specified input values, that is, P t = 2
(horizontal axis), and R = 1000 (vertical axis). and the Default Transition tool in the State-
flow Editor window appears highlighted on and off during the simulation as shown below.

Introduction to Stateflow®with Applications 3−61


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

3−62 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

To advance through the rest of the simulation in the Stateflow Debugging window we check
the Disable all field to remove all breakpoints, and we click the Continue button and we
observe the status at simulation time from zero to 10 seconds. In the Simulink model shown
below, the Progress bar at the bottom of the window indicates 2.6 seconds have elapsed after
the start of the simulation.

The Simulink model at the end of simulation time is shown below.

We can use simulation to test our Embedded MATLAB functions for run-time errors that are
not detectable by Stateflow diagnostics. When we simulate our model, Simulink tests the
Embedded MATLAB functions for missing or undefined information and possible logical con-

Introduction to Stateflow®with Applications 3−63


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

flicts. The procedure is illustrated by simulating and debugging the dipoleP function during
run-time conditions as follows:
In the Dipole_Stateflow model above we double click the Stateflow Chart and the Stateflow
Editor window appears as shown below.

Figure 3.45.
We double-click the dipoleP function and the Embedded MATLAB Editor window appears as
shown below. We click the dash (-) character in the left margin of line 6 and we observe that a
small red ball appears next to line 7 as shown indicating that we’ve set a breakpoint there.

In the Embedded MATLAB Editor window, we click the Start Simulation tool (green
arrow) to begin simulation. If we get any errors, we make corrections before simulation again. If
no errors are detected, the simulation pauses when execution reaches the breakpoint that
we’ve set, and this is indicated by a small green arrow in the left margin as shown below.

3−64 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

Introduction to Stateflow®with Applications 3−65


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We click the Step tool to advance the execution one line, i.e., to line 8, indicated by the
small green arrow shown below.

If we click again the Step tool, execution will advance to line 10, and we will not see the exe-

cution of the subfunction Power. For this reason, we need to click the Step In tool which
is immediately to the right of the Step tool on the main task bar in the Embedded MATLAB
Editor window. Therefore, to advance execution to the first line of the subfunction Power, we
click the Step In tool, and the Embedded MATLAB Editor window now appears as shown
below.

3−66 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

Once we are in the subfunction line, we can advance through the subfunction statements one
line at a time. with the Step tool. But if the subfunction calls another subfunction, we should
use the Step In tool to step into it.
If we want to continue through the remaining lines of the subfunction and go back to the line

after the subfunction call, we should use the Step Out tool .
When the subfunction finishes execution, we will see a green arrow pointing down under its
last line as shown below.
We click the Step tool to return to the PowerDensity function and we observe that execution
advances to line 8 as shown below.

Introduction to Stateflow®with Applications 3−67


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The plot is displayed as shown below.

3−68 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

If we want to see the value of the variable Power in line 10, we place the text cursor over the
text Power for about two seconds, and the value appears as shown below. Using the same pro-
cedure, we can see the value of any data.
The values can also be seen in the MATLAB Command window. When a breakpoint is
reached, the debug>> command appears.* At this prompt, we enter the name of the data,
for example,
debug>> Power
Power =
2.6101e-007
debug>>

* We may need to press the Enter key to see it.

Introduction to Stateflow®with Applications 3−69


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

If we want to leave the function until it is called again, we click the Continue Debugging tool

and the breakpoint on line 7 is reached again as shown below. Then, we can advance
through the execution of the remaining statements with the Continue Debugging tool.

3−70 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

To remove the breakpoint at line 7, we click it and then we click the green arrow to complete
execution of the simulation. The model then will be completed as shown below.

NOTE:
In electromagnetic waves and antennas textbooks the Power Density and Electric Field
Strength are plotted in logarithmic scales in terms of the radiated power P t and distance R .
These can be easily constructed with the following MATLAB script:

Introduction to Stateflow®with Applications 3−71


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

Pt=1; R=10:10000;
PD=1.64.*Pt./(4.*pi.*R.^2);
EF=sqrt(49.2.*Pt)./R;
loglog(R,PD,R,EF); grid;
xlabel('Distance in meters');
ylabel('Power Density, Field Strenth');
title('Power Density and Field Strenth as a function of distance');

3−72 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

2.
In the MATLAB Command window we type
sfnew
and the untitled model shown below is displayed.

From the Simulink Library Browser, we highlight the Commonly Used Blocks library and
from it we drag two Constant blocks. Then we highlight the Sinks library and from it we drag
three Display blocks. We name it Poisson_Erlang_Stateflow and now it appears as shown
below.

We double-click the Stateflow Chart and the Stateflow Editor window appears as shown
below.

Introduction to Stateflow®with Applications 3−73


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

In the Stateflow Editor window above, we drag three Embedded MATLAB functions into the

empty space of the Stateflow Editor using the Embedded MATLAB Function tool from
the tool palette. We observe that a flashing text cursor appears, and we define the first func-
tion as
Poissonout=Poisson(value1,value2)
the second as
ErlangBout=ErlangB(value1,value2)
and the third as
ErlangCout=ErlangC(value1,value2)
These labels conform to the Embedded MATLAB function syntax
return_value=function_name(argument1, argument2,...)
where the return_value and each argument can be a scalar, vector, or matrix of values. A
matrix is a two−dimensional array (rows and columns) of values, and a vector is a matrix with a
row or column with one dimension. Multiple return values are not allowed.

3−74 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The Stateflow Editor window now appears as shown below. The label eM above the flashing
text cursor where we enter the function name, indicates that this is an Embedded MATLAB
function.

In the Stateflow Editor window above, we drag the Default Transition tool to form a ter-
minating junction, we click the question (?) mark to change it to a flashing text editor, and we
type
{PoissonProb = Poisson(invalue1,invalue2);
ErlangBProp = ErlangB(invalue1,invalue2);
ErlangCProp = ErlangC(invalue1,invalue2);}
and the Stateflow Editor window now appears as shown below.

Introduction to Stateflow®with Applications 3−75


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The function names at the Default Transition tool and the eM functions must be the
same. Thus, in the Stateflow Editor window below, the function names Poisson, ErlangB, and
ErlangC are the same for the Default Transition tool and the eM functions.
The label on the Default Transition provides a condition action that calls the eM functions
with arguments and a return value. When the Stateflow block is triggered during simulation,
the Default Transition is taken and calls to the Poisson, ErlangB, and ErlangC functions are
made.The return values of the eM functions, i.e., Poissonout, ErlangBout, and ErlangCout are
often referred to as the signature return values. The return values of the Default Transition, i.e.,
PoissonProb, ErlangBProb, and ErlangCProb must match the signature return values Pois-
sonout, ErlangBout, and ErlangCout, and the type of arguments in the Default Transition,
i.e., invalue1 must match the type of the signature arguments, i.e., value1. This will be ensured
later when we define the inputs and outputs in the Model Explorer window.
In the Stateflow Editor window above, we double-click the eM dipoleP function to edit its
function body in the Embedded MATLAB Editor shown below.

3−76 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

In the Embedded MATLAB Editor above, we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.

We observe that the function Poisson is highlighted in the Model Hierarchy pane (left), and
the Contents pane (right) displays the input arguments value1 and value2, and output argu-
ment Poissonout. By default, both are scalars of type double.

Introduction to Stateflow®with Applications 3−77


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We return to the Stateflow Editor window and we double-click the eM ErlangB function to
edit its function body in the Embedded MATLAB Editor shown in below.

In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.

3−78 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

We observe that the function ErlangB is highlighted in the Model Hierarchy pane (left), and
the Contents pane (right) displays the input arguments value1 and value2, and output argu-
ment ErlangBout. By default, both are scalars of type double.
We return to the Stateflow Editor window and we double-click the eM ErlangC function to
edit its function body in the Embedded MATLAB Editor shown in below.

In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.

Introduction to Stateflow®with Applications 3−79


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We observe that the function ErlangC is highlighted in the Model Hierarchy pane (left), and
the Contents pane (right) displays the input arguments value1 and value2, and output argu-
ment ErlangCout. By default, both are scalars of type double.
In the Model Hierarchy pane of the Model Explorer above, we select Chart, from the Add
drop menu we select , and under the indicated columns in the Contents pane we add
the following data:

Name Scope Size


invalue1 Input from Simulink Scalar (no change)
invalue2 Input from Simulink Scalar (no change)
PoissonProb Output to Simulink Scalar (no change)
ErlangBProb Output to Simulink Scalar (no change)
ErlangCProb Output to Simulink Scalar (no change)

3−80 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The Contents pane in the Model Explorer now appears as shown below.

Our Simulink model is now built and appears as shown below after connecting the Constant
blocks to the inputs of the Stateflow Chart and the Display blocks to the outputs of the State-
flow Chart. We have renamed the Constant blocks E for the number of Erlangs, and T for the
number of Trunks. The values of E and T will be defined in the MATLAB command prompt.
We save the model and we will program the Stateflow chart in the next paragraphs.

Introduction to Stateflow®with Applications 3−81


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

We begin the programming by opening our saved model Poisson_Erlang_Stateflow and in the
Stateflow Editor window we double-click the eM Poisson function and this opens the Embed-
ded MATLAB Editor window shown below.

After the function header in the Embedded MATLAB Editor window above, we enter a line
space and we type the following comment lines:
% This function computes the probability of blocked calls for a
% traffic system using the Poisson model. The number of Erlangs
% and Trunks will be entered in MATLAB's Command Window.
%
The Embedded MATLAB Editor window now appears as shown below.

3−82 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

Next, we enter the following statement:


eml.extrinsic(‘plot’,’sum’);
The command plot will enable us to see the input values of E and T in a plot to be defined
below, and the function sum will enable us to perform summation of values over a range spec-
ified by the equation that defines the Poisson model. As we now know, there are a number of
MATLAB functions are not supported by the Embedded MATLAB subset, and plot is one of
them. Should there be necessary to use MATLAB functions that are not supported by the
Embedded MATLAB subset, we must first declare them to be extrinsic as described in “Call-
ing MATLAB Functions” in the Embedded MATLAB documentation.
The complete script for the Embedded MATLAB function Poissonout is listed below.
function Poissonout=Poisson(value1,value2)
% This function computes the probability of blocked calls for a
% traffic system using the Poisson model. The number of Erlangs
% and Trunks will be entered in MATLAB's Command Window.
%
eml.extrinsic('plot',’sum’)
Poissonout=PP(value1,value2)
function PoissonProb=PP(E,T)
PoissonProb=1−exp(−E).*sum(E.^(0:T-1)./factorial(0:T-1));
plot(E,T,’-+’);
%
This script is entered into the Embedded MATLAB Editor window as shown below.

Introduction to Stateflow®with Applications 3−83


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The complete script for the Embedded MATLAB function ErlangBout is listed below.

function ErlangBout=ErlangB(value1,value2)
% This function computes the probability of blocked calls for a
% traffic system using the ErlangB model. The number of Erlangs
% and Trunks will be entered in MATLAB's Command Window.
%
ErlangBout=PEB(value1,value2)
function ErlangBProb=PEB(E,T)
ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T)));
%
This script is entered into the Embedded MATLAB Editor window as shown below.

3−84 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

The complete script for the Embedded MATLAB function ErlangCout is listed below.

function ErlangCout=ErlangC(value1,value2)
% This function computes the probability of blocked calls for a
% traffic system using the ErlangC model. The number of Erlangs
% and Trunks will be entered in MATLAB's Command Window.
%
ErlangCout=PEC(value1,value2)
function ErlangCProb=PEC(E,T)
ErlangCProb=(E.^T./(factorial(T).*(T−E)))./((sum(E.^(0:T-1)...
./factorial(0:T-1))+E.^T./(factorial(T).*(T-E))))
%
This script is entered into the Embedded MATLAB Editor window as shown below.

Introduction to Stateflow®with Applications 3−85


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

The saved model is shown below.

In MATLAB’s Command Window we enter the values


E=4; T=10;
we issue the simulation command, and Simulink responds with the following messages:

3−86 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

Let us replace the Stateflow Chart with an Embedded MATLAB Function block from the
Simulink User-Defined Function library, as shown below, to find out whether this block
imposes the same requirement.

We name this model Poisson_Erlang_Simulink. We double-click the Embedded MATLAB


Function block and in the Embedded MATLAB Editor window we erase the existing con-
tents and we define a new function file as:

Introduction to Stateflow®with Applications 3−87


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

function [PoissonProb,ErlangBProb,ErlangCProb]=Probability(E,T)

% This function computes the probability of blocked calls for a


% traffic system using the Poisson, Erlang B, and Erlang C models.
% The number of Erlangs (E) and Trunks (T) will be entered in
% MATLAB's Command Window.
%
PoissonProb=1-exp(-E).*sum(E.^(0:T-1)./factorial(0:T-1));
%
ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T)));
%
ErlangCProb=(E.^T./(factorial(T).*(T-E)))./((sum(E.^(0:T-1)...
./factorial(0:T-1))+E.^T./(factorial(T).*(T-E))));
%
The Embedded MATLAB Editor window now appears as shown below.

The Simulink model now appears as shown below.

3−88 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

We interconnect the blocks as shown below, in MATLAB’s Command Window we enter the
values
E=4; T=10;
we issue the simulation command, and Simulink responds with the following messages:

These are the same error messages that we received with the Stateflow Chart.

Introduction to Stateflow®with Applications 3−89


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

To obtain the probability values for each of the three traffic models, in the Embedded MAT-
LAB Editor window we replace the offending variable T with its numerical value, i.e., T = 10 ,
so that 0:T-1 is replaced with 0:9 .* When this is done, we re-issue the simulation command
and the Simulink model now appears as shown below.

These values are verified in MATLAB, i.e.,


E=4; T=10;
>>
>> PoissonProb=1-exp(-E).*sum(E.^(0:T-1)./factorial(0:T-1))
PoissonProb =
0.0081
>> ErlangBProb=(E.^T/factorial(T))./(sum(E.^(0:T)./factorial(0:T)))
ErlangBProb =
0.0053
>> ErlangCProb=(E.^T./(factorial(T).*(T-E)))./((sum(E.^(0:T-1)...
./factorial(0:T-1))+E.^T./(factorial(T).*(T-E))))
ErlangCProb =
8.8852e-004
It should be noted that these traffic models are used differently as described below.

* Of course, this is not a viable solution. When limitations of this nature occur in Stateflow Charts and in Simulink, we
would be better off to use just MATLAB.

3−90 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercises

In the Poisson model, blocked calls are held until a trunk becomes available, and assumes a
random call arrival pattern. The caller makes only one attempt to place the call and blocked
calls are lost.
The Erlang B model is used when blocked calls are rerouted, and they never come back to the
original trunk. It assumes a random call arrival pattern. The caller makes only one attempt and
if the call is blocked, then it is rerouted.
The Erlang C model assumes a random call arrival pattern where the caller makes one call and
it is held in a queue until the call is answered.

For more information on traffic models for data, the interested reader may refer to:
http://www.cisco.com/en/US/tech/tk652/tk701/
technologies_white_paper09186a00800d6b74.shtml

Introduction to Stateflow®with Applications 3−91


Copyright © Orchard Publications
Chapter 3 Embedded MATLAB Functions in Stateflow Charts

NOTES:

3−92 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 4
Model Coverage for Embedded MATLAB Functions

T
his chapter describes the procedure for adding Embedded MATLAB functions to Stateflow
charts. It begins with an introduction to Embedded MATLAB functions using an example,
followed by procedures for building a Simulink model with a Stateflow chart that calls the
Embedded MATLAB function.

4.1 Introduction to Embedded MATLAB Functions


Figure 4.1 below shows an example of a Stateflow Chart in a Simulink model and Model Cover-
age for an Embedded MATLAB function inside the Stateflow Chart.

Figure 4.1. Example with a Stateflow Chart that contains a Model Coverage for Embedded MATLAB function

Introduction to Stateflow®with Applications 4−1


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

The Stateflow documentation presents an example model named intersecting_rectangles where


the if statement is tested for Decision Coverage. Other statements that can be tested for Deci-
sion Coverage are switch, for, and while. However, we can create a model without these state-
ments as illustrated with the example below.

Example 4.1
Consider the electric circuit shown in Figure 4.2.

R L C
IS

Figure 4.2. A parallel resonant frequency circuit

From electric circuit* theory, we know that the resonant frequency f 0 is found from the relation

1
f 0 = ------------------- †
2π LC

or in terms of the radian frequency ω 0 from the relation

1 -
ω 0 = -----------
LC
Often, we want to adjust the variable capacitor indicated with an arrow in Figure 4.2, to produce
a desired resonant frequency. In practice, the value of the inductor L is held fixed and the value
of the capacitor is varied.
For our model, we want to set the value of the capacitor C so that the radian resonant frequency
ω 0 will be 1000 rad ⁄ sec . It is known that the capacitor can be adjusted from 1 μF to 20 μF at
increments of 1 μF .

We begin by typing sfnew at the MATLAB command prompt. A Stateflow Chart block appears
and from the Simulink Sinks Library we drag a Display block. Our model now is as shown in Fig-
ure 4.3.

* For a detailed discussion on parallel resonant frequency, please refer to Circuit Analysis II with MATLAB Applications,
ISBN 0−9709511−5−9.
† The value of the resistor R is independent of the frequency.

4−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.3. The components of the model of Example 4.1


In Figure 4.3 we double−click the Stateflow Chart and in the Stateflow Editor window we use the

State tool to drag a state (rectangle with rounded corners), we drag and attach the Default

Transition tool to it, we drag the Embedded MATLAB Function tool , and we
type the labels shown in Figure 4.4.

Figure 4.4. The Stateflow Chart Editor for Example 4.1

Introduction to Stateflow®with Applications 4−3


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

As shown in the Stateflow Editor window in Figure 4.4, the Stateflow Chart has a state with a
default transition and en(entry) and du(during) actions. The state executes its entry action for the
first time that is entered for the first time sample. Thereafter, each time sample calls the during
action of the active state.
In the Stateflow Editor window in Figure 4.4, we click the Add drop menu, we select Data>Out-
put to Simulink, we change the name to wout, and in the Scope field we specify Port 1. Our
model now appears as shown in Figure 4.5 after connecting the output of the Stateflow Chart to
the input of the Display block.

Figure 4.5. The model for Example 4.1 after interconnecting the blocks

In the Stateflow Editor window in Figure 4.4, we click the Explorer tool and the Model
Explorer window appears as shown in Figure 4.6. We observe that when the frequency variable is
highlighted in the Model Hierarchy pane (left) the variables Cin and woutput are shown in the
Contents pane.* Initially, there are no values indicated for the variables Cin and woutput under
the Size column. We double−click the Cin row under the Size column and we set the size of Cin
to 1,20 as indicated in Figure 4.6. Using the same procedure, we set the size of the variable wout-
put to 1,20.
In the Model Explorer window in Figure 4.6 we click the Chart in the Model Hierarchy pane
(left) to select it and we observe that the Contents pane displays the variables wout, C, and val-
ueC as shown in Figure 4.7. Initially, there are no values indicated for these variables under the
Size column. We double−click the wout row under the Size column and we set the size of wout to
1,20 as indicated in Figure 4.7. Using the same procedure, we set the sizes of the variables C, and
valueC to 1,20.

* If these values are not shown, they can be added using the Add Data tool .They can also be modified using the mouse
text editor.

4−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.6. The Model Explorer for Example 4.1 showing the input and outputs of the frequency function

Introduction to Stateflow®with Applications 4−5


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.7. The Model Explorer for Example 4.1 showing the Chart variables
In the Stateflow Editor window of Figure 4.4, we double−click the eM woutput=frequency(Cin)
Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor
window appears where line 1 displays function woutput = frequency(Cin). Under this line we add
the following script:
% The generated plot will display the value of
% the capacitance for which the resonant frequency
% is 10000 rad/sec.
eml.extrinsic('plot','grid','xlabel','ylabel','title');
L=0.1;
C=10^(−6):10^(−6):20*10^(−6);
woutput=1./sqrt(L.*C);
plot(C,'−+'); grid;
xlabel('Capacitande in microfarads');
ylabel('Frequency in rads/sec')
The Embedded MATLAB Editor window now appears as shown in Figure 4.8.

4−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.8. The Embedded MATLAB Editor window for the woutput function
In the model of Figure 4.9 we issue the start simulation command and the Display block shows
the first four values of the radian frequency corresponding to the capacitance values from 1 μF
to 20 μF . Perhaps the reader can think of a method to display the 20 values of the radian fre-
quency in a column. This is left as an exercise for the reader at the end of this chapter. The plot
in Figure 4.10 shows the radian frequency versus capacitance and that the resonant frequency
occurs when the variable capacitor is set at 10 μF .

Figure 4.9. The values of the radian frequency after the simulation start command

Introduction to Stateflow®with Applications 4−7


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.10.

In Example 4.1 above, we did not use decisions and conditions of Embedded MATLAB functions
in Stateflow. We will use decisions and conditions in Example 4.2 below.

Example 4.2
From analytic geometry we know that two straight line segments L 1 and L 2 are orthogonal (per-
pendicular) to each other if their slopes m 1 and m 2 satisfy the relation m 1 m 2 = – 1 as shown in
Figure 4.11 below.
y
m1 ⋅ m2 = –1
slope = m 1

slope = m 2

x
Figure 4.11. Orthogonal straight line segments

4−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

We will create a model with Embedded MATLAB Function Decisions. We will name this
model orthogonal_segments. It consists of a Stateflow Chart block with no input and its output
is sent to a Display block as shown in Figure 4.12 below. As before, the Stateflow Chart was cre-
ated by typing sfnew in the MATLAB command prompt, and the Display blocks were dragged
from the Simulink Sinks Library.

Figure 4.12. The blocks for the model of Example 4.2

In Figure 4.12 we double−click the Stateflow Chart and in the Stateflow Editor window we use

the State tool to drag a state (rectangle with rounded corners), we drag and attach the

Default Transition tool to it, we drag the Embedded MATLAB Function tool ,
and we type the labels shown in Figure 4.13.
As shown in the Stateflow Editor window in Figure 4.13, the Stateflow Chart has a state with a
default transition and en(entry) and du(during) actions. The state executes its entry action for
the first time that is entered for the first time sample. Thereafter, each time sample calls the dur-
ing action of the active state.
In the Stateflow Editor window in Figure 4.13, we click the Add drop menu, we select
Data>Output to Simulink, we change the name to m1, and in the Scope field we specify Port
1. Using the same procedure the second output m2. Our model now appears as shown in Figure
4.14 where we have connected the outputs of the Stateflow Chart to the inputs of the Display
blocks.

Introduction to Stateflow®with Applications 4−9


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.13. The Stateflow Chart Editor for the model of Example 4.2

Figure 4.14. The interconnected blocks for the model of Example 4.2

In the Stateflow Editor window in Figure 4.13, we click the Explorer tool and the Model
Explorer window appears as shown in Figure 4.15. We observe that when the Chart is high-
lighted in the Model Hierarchy pane (left) the variable m2 is shown in the Contents pane.

4−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.15. The Model Explorer showing the Chart variables

We click the slope1 function under Chart in the Model Hierarchy pane (left) and we observe
that the argument segment and output m1 and are displayed in the Contents pane as shown in
Figure 4.16. We also click slope2 function under Chart in the Model Hierarchy pane (left) and
we observe that the argument segment and output m2 are displayed in the Contents pane as
shown in Figure 4.17.

Introduction to Stateflow®with Applications 4−11


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.16. The Model Explorer showing the slope1 variables

In the Stateflow Editor window of Figure 4.13, we double−click the eM m1=slope1(segment)


Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor
window appears where line 1 displays function m1=slope1(segment). Under this line we add the
following script:
% The variable m2 outputs the slope of the
% second line segment
eml.extrinsic('input','if','else','end');
m1=input('Enter value of the slope of first straight line segment ');
if m1>0
m2=−1/m1;
else
m2=abs(1/m1);
end
disp('slope of segment 2 is');
disp(m2)
end

4−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.17. The Model Explorer showing the slope2 variables

The Embedded MATLAB Editor window for function m1 now appears as shown in Figure 4.18.

Introduction to Stateflow®with Applications 4−13


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.18. The Embedded MATLAB Editor for the slope1 function

In the Stateflow Editor window of Figure 4.13, we double−click the eM m2=slope2(segment)


Embedded MATLAB Function rectangle and we observe that the Embedded MATLAB Editor
window appears where line 1 displays function m2=slope2(segment). Under this line we add the
following script:
m1=input('Enter value of the slope of first straight line segment ');
if m1>0
m2=−1/m1;
else
m2=abs(1/m1);
end
disp('slope of segment 2 is');
disp(m2)

x=input('Another slope? (<enter>=no, 1=yes)','s');

m1=input('Enter value of the slope of first straight line segment ');


if m1>0
m2=−1/m1;
else
m2=abs(1/m1);
end
disp('slope of segment 2 is');
disp(m2)

4−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

The Embedded MATLAB Editor window for function m2 now appears as shown in Figure 4.19.

Figure 4.19. The Embedded MATLAB Editor for the slope2 function

Our Simulink model now appears as shown in Figure 4.20.

Introduction to Stateflow®with Applications 4−15


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

Figure 4.20. The complete model for Example 4.2

With the Command window and the model in Figure 4.20 both visible, we start simulation by
clicking the Start Simulation tool and the Command window returns the message below:
Enter value of the slope of first straight line segment
We type 2 and the model displays both slopes as shown in Figure 4.21.
We start simulation again, and in response to the message above, we type −0.75 and the model
displays both slopes as shown in Figure 4.22.

Figure 4.21. The values of m1 and m2 after the simulation command execution

4−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Introduction to Embedded MATLAB Functions

Figure 4.22. The model for Example 4.2 with different values of m1 and m2

Introduction to Stateflow®with Applications 4−17


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

4.2 Summary
• This chapter describes the procedure for adding Embedded MATLAB functions to Stateflow
charts.
• The Model Coverage tool in Simulink reports model coverages for the decisions and condi-
tions of Embedded MATLAB functions in Stateflow.
• We use the Model Coverage tool for Embedded MATLAB functions to ascertain that all
decisions and conditions are in conformance with the simulation objectives in our model.
• A description of Model Coverage topics is provided in the Simulink documentation.
• During simulation, the following Embedded MATLAB block function statements are tested
for Decision Coverage:
1. Function header − Decision coverage is 100% if the function or subfunction is executed.
2. If − Decision coverage is 100% if the if expression evaluates to true at least once and false at
least once.
3. switch − Decision coverage is 100% if every switch case is taken, including the fall−through
case.
4. for − Decision coverage is 100% if the equivalent loop condition evaluates to true at least
once, and false at least once.
5. while − Decision coverage is 100% if the equivalent loop condition evaluates to true at least
once, and false at least once.
• During simulation, the following logical conditions are tested for Condition Coverage and
The Modified Condition Decision Coverage (MCDC)* in the Embedded MATLAB block
function:
1. If statement conditions
2. while statement conditions, if present
• The Stateflow documentation presents an example model intersecting_rectangles where the if
statement is tested for Decision Coverage.

* The MCDC option reports a test's coverage of occurrences in which changing an individual subcondition within
a transition results in changing the entire transition trigger expression from true to false or false to true.

4−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercises for the Reader

4.3 Exercises for the Reader


1.
In Example 4.1 the values of the radian frequency were displayed in a row−wise vector. Can
you think of a method that these values will be displayed in a column−wise vector as shown
below?

2.
A book distributor offers discounts to booksellers in accordance with the following quantities:

Books Sold Percent Discount


Less than 25 20
Exactly 25 30
More than 25 40

For a book whose retail price is $50.00, create a Simulink model that includes a Stateflow
Chart that returns the cost to the booksellers after the discounts shown in the table above
have been applied.

Introduction to Stateflow®with Applications 4−19


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

4.4 Solution to the End−of−Chapter Exercises


1.
One way is to insert the Simulink Reshape block* from the Math Operations library between
the Stateflow Chart and the Display block as shown below.

2.
We will create a model with Embedded MATLAB Function Decisions. We will name this
model books_stateflow. It will consist of a Stateflow Chart block with no input and its output
will be sent to a Display block as shown below. As before, the Stateflow Chart was created by

* This block is discussed in Introduction to Simulink with Engineering Applications, ISBN 0−9744239−7−1.

4−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises

typing sfnew in the MATLAB command prompt, and the Display block was dragged from the
Simulink Sinks Library.

In the model above, we double−click the Stateflow Chart and in the Stateflow Editor window we

use the State tool to drag a state (rectangle with rounded corners), we drag and attach the

Default Transition tool to it, we drag the Embedded MATLAB Function tool ,
and we type the labels shown below.

Introduction to Stateflow®with Applications 4−21


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

As shown in the Stateflow Editor window above, the Stateflow Chart has a state with a default
transition and en(entry) and du(during) actions. The state executes its entry action for the first
time that is entered for the first time sample. Thereafter, each time sample calls the during action
of the active state.
In the Stateflow Editor window above, we click the Add drop menu, we select Data>Output to
Simulink, we change the name to cost, and in the Scope field we specify Port 1. Our model now
appears as shown below where we have connected the output of the Stateflow Chart to the input
of the Display block.

In the Stateflow Editor window, we click the Explorer tool and the Model Explorer window
appears as shown below. We observe that the Chart is highlighted in the Model Hierarchy pane
(left) the row vector cost is shown in the Contents pane.

4−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises

Under Chart in the Model Hierarchy pane (left), we click the books function and we observe
that the input argument x and output argument cost are displayed in the Contents pane as
shown below.

Introduction to Stateflow®with Applications 4−23


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

In the Stateflow Editor window, we double−click the eM cost=books(x) Embedded MATLAB


Function rectangle and we observe that the Embedded MATLAB Editor window appears where
line 1 displays function cost=books(x) as shown below.

Under this line we add the following script:


% The cost varies with the amount x of the books sold
%
eml.extrinsic(‘input’, 'if','elseif','end');

4−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises

x=input('Enter number of books sold x: ');


cost=50*x;
if x<=10
cost=(1−20/100)*cost;
elseif x==25
cost=(1−30/100)*cost;
else
cost=(1−40/100)*cost;
end

The Embedded MATLAB Editor window for function cost now appears as shown below.

With the Command window and the model both visible, we start simulation by clicking the Start
Simulation tool and the Command window returns the message below:
Enter number of books sold x: 30
cost =
900
Enter number of books sold x:
In response to the number of books sold, i.e., x=30 the model displays the answer 900 as shown
below.

Introduction to Stateflow®with Applications 4−25


Copyright © Orchard Publications
Chapter 4 Model Coverage for Embedded MATLAB Functions

4−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 5
Graphical Functions

T
his chapter describes the procedure for creating graphical functions. It begins with an intro-
duction to graphical functions followed by procedures for building a Simulink model to
define graphical functions and includes illustrative examples.

5.1 Introduction to Graphical Functions


Stateflow defines three types of functions: truth table, Embedded MATLAB, and graphical. We
described truth table and Embedded MATLAB functions in the previous chapters. In this chap-
ter we will discuss graphical functions.
Like the truth table and Embedded MATLAB functions, a graphical function is an extension of
Stateflow actions. We define a program once in a function, and we can call it as many times as we
need in Stateflow action language.

5.2 Creating a Graphical Function


We create a Stateflow graphical function in Stateflow diagrams with the following steps:

1. We select the graphical tool function from the Stateflow drawing toolbar in the Stateflow
Editor window, we move the cursor inside the empty area of the Stateflow Editor, and we click
to place it near the top of the empty area. The graphical function now appears as an unnamed
object in the Stateflow Editor with a flashing text cursor as shown in Figure 5.1 below. We save
this function as graph_func_stateflow.

2. The syntax of a typical graphical function has a signature of the following form:
y = f ( x 1, x 2, … , x n )

Accordingly, in the Stateflow Editor window we define our function as


w = f ( x, y, z )
and the Stateflow Editor window now appears as shown in Figure 5.2.

3. We click the Model Explorer icon at the top toolbar of the Stateflow Editor window and
this function now appears in the Model Explorer window shown in Figure 5.3.

Introduction to Stateflow®with Applications 5−1


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.1. Unnamed graphical function with flashing text cursor

Figure 5.2. Named graphical function

5−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Graphical Function

Figure 5.3. The Model Explorer window with the f( ) f function object highlighted

4. In Figure 5.3 above we observe that when the f( ) f function object is highlighted the Scope
field in the Contents pane indicates the role of each argument or return value. Thus the argu-
ments x, y, and z are labeled as inputs, and the w is shown as the output.

5. A graphical function can reside anywhere in a chart, state, or subchart. The location of a
function determines its scope, that is, the set of states and transitions that can call the func-
tion. Graphical functions are visible to the chart, to the parent state and its parents, and to
sibling transitions and states with the following exceptions:
a. If the chart containing the function exports its graphical functions, the scope of the func-
tion is the entire Stateflow machine, which encompasses all the charts in the model as it is
illustrated in the next section.
b. A function defined in a state or subchart overrides any functions of the same name defined
in the parents and ancestors of that state or subchart.

Introduction to Stateflow®with Applications 5−3


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.4. The Contents pane when Chart is highlighted in the Model Hierarchy pane

Example 5.1
We will create a Simulink model with a graphical function to compute the magnitude of the
impedance Z in an AC electric circuit defined as
2 2
Z = R + ( XL – XC )

We begin by typing sfnew at the MATLAB Command prompt, and Simulink returns the State-
flow Chart shown in Figure 5.5.

5−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Graphical Function

Figure 5.5. Stateflow Chart for Example 5.1

We double-click the Stateflow Chart block shown in Figure 5.5 and in the Stateflow Editor that

appears, we select the graphical tool function from the Stateflow drawing toolbar on the
left side, we move the cursor inside the empty area of the Stateflow Editor, and we click to place
it near the top of the empty area. The graphical function now appears as an unnamed object in
the Stateflow Editor with a flashing text cursor as shown in Figure 5.6 below.

Figure 5.6. Unnamed graphical function with flashing text cursor

Introduction to Stateflow®with Applications 5−5


Copyright © Orchard Publications
Chapter 5 Graphical Functions

In the graphical function rectangle shown in Figure 5.6, we enter the condition action of the
function signature Z=f(R,XL,XC), a default transition with a terminating junction, the equation
for the impedance Z = sqrt ( R^2+(XL-XC )^2) , and the default transition for the function argu-
ment Zout = f ( Rin, XLin, XCin ) . We save this function as impedance_stateflow, and the State-
flow Chart Editor now appears as shown in Figure 5.7.

Figure 5.7. The Stateflow Chart Editor with the graphical function

Next we click the Model Explorer tool and the Model Explorer window appears as shown in
Figure 5.8 where with the Chart highlighted in the Model Hierarchy pane (left), the Contents
pane (right) shows the function arguments Rin , X L , and X C as inputs, and the return value
Zout as the output.

5−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Graphical Function

Figure 5.8. The Model Explorer for the model of Example 5.1 when Chart is highlighted in the left pane

We expand the Chart field in the left pane and under it appears the function object f( )f and in
the right pane appear the signature function arguments R , XL , and XC , as inputs, and the
return value Z as the output.

Introduction to Stateflow®with Applications 5−7


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.9. The Model Explorer for the model of Example 5.1 when f( )f is highlighted in the left pane

The model with the Stateflow Chart now appears as shown in Figure 5.10 where we have added
three Constant blocks as inputs to the Stateflow Chart, and a Display block for the output.

5−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Graphical Function

Figure 5.10. The completed model for Example 5.1


At the MATLAB command prompt we enter the inputs to the Stateflow Chart, i.e.,
R=50; XL=75; XC=100;
and after issuing the simulation command, the Display block shows the result as shown in Figure
5.11 below.

Figure 5.11. The model for Example 5.1 after execution of the simulation command

Introduction to Stateflow®with Applications 5−9


Copyright © Orchard Publications
Chapter 5 Graphical Functions

5.3 Subcharts
A graphical function can be complicated and long, and may be difficult to fit into the Stateflow
Editor window. But we can make the function smaller and hide its contents. This is possible with
the use of subcharts as described below.
Stateflow allows us to create charts within charts, and a chart that is embedded in another chart
is referred to as a subchart. A subcharted state is a superstate of the states and charts that it con-
tains, and it appears as a block with its name in the block center.
As an example, consider the model in Figure 5.12 that performs the division z = x ⁄ y , and in the
MATLAB command prompt we have entered x=48, and y=3.

Figure 5.12. Model to perform the operation z=x/y

To view the contents of the Stateflow Editor, we double click the Chart block and Simulink dis-
plays the Stateflow Editor with the contents shown in Figure 5.13.
To convert the graphical function to a subchart, we right-click the graphical function block and
the pop-up menu shown in Figure 5.14 appears. In that menu, we select Make Contents and
from the submenu we select Subcharted. This has made the graphical function opaque as shown
in Figure 5.15, and it appears as a block with its name in the block center.

5−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Subcharts

Figure 5.13. The Stateflow Editor for the model in Figure 5.12

Figure 5.14. The Stateflow editor shortcut menu

Introduction to Stateflow®with Applications 5−11


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.15. The graphical function in subcharted (opaque) appearance

To return* to the original Stateflow diagram, we right-click the subchart and in the pop-up menu
we select Make Contents. In the resulting submenu we select the Subcharted item.

Example 5.2
We will create a Simulink model that includes a Stateflow Chart to return the values of the out-
put y corresponding to the inputs values x from 0 to 6 in steps of 1 for the function
5 3
y = 3x – 2x + 6x – 8
using the graphical function method.
We begin by typing sfnew at the MATLAB command prompt and in the model that appears we
add a Constant block from the Commonly Used Blocks Library, two Reshape blocks from the
Math Operations Library, and two Display blocks from the Sinks Library. Our model is as shown
in Figure 5.16.

Figure 5.16. The Simulink blocks for the model of Example 5.2

* We cannot undo the operation of converting a subchart back to its original form because the undo and redo selections are
disabled.

5−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Subcharts

We double click the Chart block and Simulink displays the Stateflow Editor with the contents

that we have added after selecting and moving the graphical function tool in the empty
area as shown in Figure 5.17 below.

Figure 5.17. The Stateflow Editor with the graphical function

To convert the graphical function to a subchart, we right-click the graphical function block and
the pop-up menu shown in Figure 5.18 appears. In that menu, we select Make Contents and
from the submenu we select Subcharted. This has made the graphical function opaque as shown
in Figure 5.19, and it appears as a block with its name in the block center.

Introduction to Stateflow®with Applications 5−13


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.18. The graphical function’s pop-up menu

Figure 5.19. The graphical function in subcharted (opaque) appearance

5−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Subcharts

In the Stateflow Chart Editor in Figure 5.19, we click the Model Explorer icon and in the
Model Hierarchy pane (left), we select Chart, and when it is highlighted it appears as shown in
Figure 5.20 below.

Figure 5.20. The Model Explorer window with the Chart field selected

In the toolbar of the Model Explorer window of Figure 5.20, we click Add, we select , in
the Contents pane we change data to xin, from the Scope column we choose Input, and with this
row selected, under the Size column we enter 1,6.* We click Add again, we select , in
the Contents pane we change data to yout, from the Scope column we choose Output, and with
this row selected, under the Size column we enter 1,6. The Model Explorer now appears as
shown in Figure 5.21, and the Simulink model is shown in Figure 5.22 with the blocks intercon-
nected.

* We specified six values, 0 through 5 for the input x and therefore the input size must be specified as a row vector of size
(1,6). The same is true for the output y.

Introduction to Stateflow®with Applications 5−15


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.21. The Model Explorer with the input and output specified as row vectors

Figure 5.22. The model for Example 5.2 with the Simulink blocks interconnected

5−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

We name this model polynomial01_stateflow and in the MATLAB command window we enter
x=0:5;
We issue the simulation command and the model displays the input and corresponding output
values.

Figure 5.23. The model for Example 5.2 displaying the input and output values

5.4 Exporting Graphical Functions to Stateflow


We can export the root-level functions of a chart to the remaining charts in the chart's model.
Exporting a chart's functions extends their scope to include all other charts in the same model.
We can also export functions in library charts to a model as long as the library charts are present
in the model. In the following example, the model Main Chart has two library Stateflow charts,
Library 1 Chart and Library 2 Chart. as shown in Figure 5.24, where the Library Charts are indi-
cated in blue color and the letter L .

Introduction to Stateflow®with Applications 5−17


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.24. Main Stateflow Chart with two Library Stateflow Charts

To begin with, from the Simulink Library Browser, we select File>New>Library, we name it
library1_stateflow, and we rename the Chart block Library 1 Chart as shown in Figure 5.25.

Figure 5.25. The Library 1 Stateflow chart

As indicated in the lower right corner of the Library 1 Stateflow chart, the Chart is locked* and
to access the flow diagram we must unlock it. This is done by selecting Edit>Unlock Library and
it is now unlocked as shown in Figure 5.26.

* This occurs whenever we save and close the model and we reopen it at a later time.

5−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

Figure 5.26. The Library 1 Chart Unlocked

In Figure 5.26 above, we double-click the Library 1 Chart block and in the Stateflow Editor we
enter the function definition and graphical function shown in the flow diagram in Figure 5.27.*
The flow diagram must include a default transition with a terminating junction.

Figure 5.27. The function definition and graphical function for Library 1 Chart

We right-click outside the graphical function box shown in Figure 5.27, and from the pop-up
menu shown in Figure 5.28 we select Properties.

* The function box has been enlarged to accommodate the width of the label signature. This can be done by moving the cur-
sor to one of the corners of the box and when it shows as a double-headed arrow we move it to enlarge the box.

Introduction to Stateflow®with Applications 5−19


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.28. Selecting Properties from the pop-up menu

The Chart Properties dialog box for Library 1 Chart appears as shown in Figure 5.29 where we
have checked the Export Chart Level Functions to enable it.

5−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

Figure 5.29. The Chart Properties dialog box for selecting Export Chart Level Functions
From the Simulink Library Browser, we select File>New>Library, we name it
library2_stateflow, and we rename the Chart block Library 2 Chart as shown in Figure 5.30.

Figure 5.30. The Library 2 Stateflow chart

Introduction to Stateflow®with Applications 5−21


Copyright © Orchard Publications
Chapter 5 Graphical Functions

In Figure 5.30 above, we double-click the Library 2 Chart block and in the Stateflow Editor we
enter the function definition and graphical function shown in the flow diagram in Figure 5.31.*
The flow diagram must include a default transition with a terminating junction.

Figure 5.31. The function definition and graphical function for Library 2 Chart
We right-click outside the graphical function box shown in Figure 5.31, and from the pop-up
menu shown in Figure 5.32 we select Properties.

* The function box has been enlarged to accommodate the width of the label signature. This can be done by moving the cursor
to one of the corners of the box and when it shows as a double-headed arrow we move it to enlarge the box.

5−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

Figure 5.32. Selecting Properties from the pop-up menu

The Chart Properties dialog box for Library 2 Chart appears as shown in Figure 5.33 where we
have checked the Export Chart Level Functions to enable it.
In MATLAB’s Command window we type
sfnew
We we name it model_stateflow, and we rename the Chart block Main Chart as shown in Figure
5.34.

Introduction to Stateflow®with Applications 5−23


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.33. The Chart Properties dialog box for selecting Export Chart Level Functions

Figure 5.34. The Main Chart model

In the model of Figure 5.34 above, we double-click the Main Chart block and in the Stateflow
Editor we enter the function definition and graphical function shown in the flow diagram in Fig-
ure 5.35. The flow diagram must include a default transition with a terminating junction.

5−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

Figure 5.35. The function definition and graphical function for Model Chart

We right-click outside the graphical function box shown in Figure 5.35, and from the pop-up
menu shown in Figure 5.36 we select Properties.

Introduction to Stateflow®with Applications 5−25


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.36. Selecting Properties from the pop-up menu

The Chart Properties dialog box for Model Chart appears as shown in Figure 5.37 where we have
checked the Export Chart Level Functions to enable it.

5−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exporting Graphical Functions to Stateflow

Figure 5.37. The Chart Properties dialog box for selecting Export Chart Level Functions

Figure 5.38 below contains the model model_stateflow , the library Stateflow charts
library1_stateflow and library2_stateflow, their function definition, their graphical functions, and
their interrelationship.

Introduction to Stateflow®with Applications 5−27


Copyright © Orchard Publications
Chapter 5 Graphical Functions

Figure 5.38. The three charts and their graphical functions

Next, we drag both Library 1 Chart and Library 2 Chart into the model Chart and the Simulink
model with the three charts is shown in Figure 5.39.

Figure 5.39. The three charts in one Simulink model

Each chart now defines a graphical function that can be called by any other chart placed in the
model where the Main Chart block resides.The sequence of action in simulation of the Main
Chart model is as follows:
The chart named Main Chart block calls the graphical function library1_func, with the three
arguments, x, y, and z. Then, library1_func calls the graphical function library2_func, passing the
same three arguments. Finally, library2_func calls the graphical function model_func, and this
adds x, y, and z.The result of the addition is assigned to w.
We must remember that states are not allowed in graphical functions. This is because a function
must execute completely when it is called.

5−28 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

5.5 Summary
• Stateflow defines three types of functions: truth table, Embedded MATLAB, and graphical.
We described truth table and Embedded MATLAB functions in the previous chapters. In this
chapter we discussed graphical functions.
• Like the truth table and Embedded MATLAB functions, a graphical function is an extension
of Stateflow actions. We define a program once in a function, and we can call it as many times
as we need in Stateflow action language.
• To create a Stateflow graphical function in Stateflow diagrams we select the graphical tool

function from the Stateflow drawing toolbar in the Stateflow Editor window, we move
the cursor inside the empty area of the Stateflow Editor, and we click to place it near the top
of the empty area. The graphical function now appears as an unnamed object in the Stateflow
Editor with a flashing text cursor.
• The syntax of a typical graphical function has a signature of the following form:
y = f ( x 1, x 2, …, x n )

Accordingly, in the Stateflow Editor window we define our function as


w = f ( x, y, z )
• A graphical function can reside anywhere in a chart, state, or subchart. The location of a func-
tion determines its scope, that is, the set of states and transitions that can call the function.
Graphical functions are visible to the chart, to the parent state and its parents, and to sibling
transitions and states with the following exceptions:
a. If the chart containing the function exports its graphical functions, the scope of the func-
tion is the entire Stateflow machine, which encompasses all the charts in the model.
b. A function defined in a state or subchart overrides any functions of the same name defined
in the parents and ancestors of that state or subchart.
• A subchart is a chart that is embedded in another chart. A subcharted state is a superstate of
the states and charts that it contains, and it appears as a block with its name in the block cen-
ter.
• To convert a graphical function to a subchart, we right-click the graphical function block,
from the pop-up menu we select Make Contents and from the submenu we select Sub-
charted. This makes the graphical function opaque, and it appears as a block with its name in
the block center.
• We can export the root-level functions of a chart to the remaining charts in the chart's model.
Exporting a chart's functions extends their scope to include all other charts in the same model.

Introduction to Stateflow®with Applications 5−29


Copyright © Orchard Publications
Chapter 5 Graphical Functions

• We can also export functions in library charts to a model as long as the library charts are
present in the model.
• States are not allowed in graphical functions. This is because a function must execute com-
pletely when it is called.

5−30 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercise for the Reader

5.6 Exercise for the Reader


Using the graphical function method, create a Simulink model that includes a Stateflow Chart to
approximate the roots accurate to two decimal places of the function
y = cos 2x + sin 2x + x – 1

Introduction to Stateflow®with Applications 5−31


Copyright © Orchard Publications
Chapter 5 Graphical Functions

5.7 Solution to the End-of-Chapter Exercise


As a first approximation, we use the MATLAB plot command to plot y versus x .
x=-1:0.01:5; y=cos(2.*x)+sin(2.*x)+x-1; plot(x,y); grid

The plot above reveals that one root is at x = 0 , and this can be easily verified by inspection of
the given function. The second root is near the vicinity x = 1.3 , and the third near the vicinity
x = 2.2 . Following the procedure of Example 5.2, we begin by typing sfnew at the MATLAB
command prompt and in the model that appears we add a Constant block from the Commonly
Used Blocks Library, two Reshape blocks from the Math Operations Library, and two Display
blocks from the Sinks Library. Our model is as shown below.

5−32 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercise

We double click the Chart block and Simulink displays the Stateflow Editor with the contents

that we have added after selecting and moving the graphical function tool in the empty
area as shown below.

To convert the graphical function to a subchart, we right-click the graphical function block and
the pop-up menu shown below appears. In that menu, we select Make Contents and from the
submenu we select Subcharted. This has made the graphical function opaque as shown in Figure
5.19, and it appears as a block with its name in the block center.

Introduction to Stateflow®with Applications 5−33


Copyright © Orchard Publications
Chapter 5 Graphical Functions

5−34 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercise

In the Stateflow Chart Editor above, we click the Model Explorer icon and in the Model
Hierarchy pane (left), we select Chart, and when it is highlighted, it appears as shown below.

In the toolbar of the Model Explorer window above, we click Add, we select , in the
Contents pane we change data to xin, from the Scope column we choose Input, and with this
row selected, under the Size column we enter 1,6.* We click Add again, we select , in
the Contents pane we change data to yout, from the Scope column we choose Output, and with
this row selected, under the Size column we enter 1,6. The Model Explorer now appears as
shown below.

* We specified six values, 0 through 5 for the input x and therefore the input size must be specified as a row vector of size
(1,6). The same is true for the output y.

Introduction to Stateflow®with Applications 5−35


Copyright © Orchard Publications
Chapter 5 Graphical Functions

The Simulink model is shown in Figure 5.22 with the blocks interconnected.

5−36 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End-of-Chapter Exercise

We name this model polynomial02_stateflow and in the MATLAB command window we enter
x=1.27:0.01:1.32; % This is the range where the second root is located
We issue the simulation command and the model displays the input and corresponding output
values.

From the input and output values in the model above, we observe that at x = 1.28 , y = – 0.006 ,
and thus we can say that the second root of the given function is approximately x = 1.28 .

To find the third root, we use the same model and at the MATLAB command prompt we enter
x=2.19:0.01:2.24; % This is the range where the third root is located

Introduction to Stateflow®with Applications 5−37


Copyright © Orchard Publications
Chapter 5 Graphical Functions

From the input and output values in the model above, we observe that at x = 2.23 , y ≈ 0.012 ,
and thus we can say that the second root of the given function is approximately x = 2.23 .

5−38 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 6
Connective Junctions

T
his chapter describes the use of connective junctions to represent a decision point between
alternate transition paths for a single transition. Flow diagram notation uses connective
junctions to represent common code structures such as for loops and if−then−else con-
structs without the use of states.

6.1 The Stateflow Connective Junction Tool


Figure 6.1 is our familiar Stateflow Editor window, and when we place the mouse cursor over the

Connective Junction tool , its name appears at the bottom of the window.

Figure 6.1. The Stateflow Editor window

Introduction to Stateflow®with Applications 6−1


Copyright © Orchard Publications
Chapter 6 Connective Junctions

6.2 Creating a Connective Junction


To create a connective junction, we do the following:

1. In the diagram toolbar, we click the Connective Junction tool .


2. We move the cursor into the diagram editor.The cursor takes on the shape of a connective
junction as shown in Figure 6.2. We click to place a connective junction in the desired loca-
tion in the drawing area.

Figure 6.2. Placing a connective junction in the drawing area

To create multiple connective junctions, we do the following:

1. In the diagram toolbar, we double−click the Connective Junction tool and the connec-
tive junction is now in multiple object mode.
2. We click anywhere in the drawing area to place a connective junction in the drawing area. We
move to and click another location to create an additional connective junction. We click the
Connective Junction tool or we press the Esc key to terminate the operation. To move a con-
nective junction to a new location, we click and we drag it to the new position.

6−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing Connective Junction Size

Figure 6.3.

6.3 Changing Connective Junction Size


To change the size of connective junctions, we do the following:
1. We select the connective junctions whose size we want to change.
2. We place the cursor over one of the connective junctions and we right−click. In the resulting
pop−up menu shown in Figure 6.4, we place the cursor over Junction Size. A submenu of
junction sizes appears as shown in Figure 6.5, and we select a size from the menu of junction
sizes.

Introduction to Stateflow®with Applications 6−3


Copyright © Orchard Publications
Chapter 6 Connective Junctions

Figure 6.4. Pop-up menu for changing the size of a connective junction

6−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing Connective Junction Size

Figure 6.5. Pop up menu and submenu for selecting connective junction sizes

We selected Size 10 for the connective junction on the left, and we changed the size to 10 as
shown in Figure 6.6.

Introduction to Stateflow®with Applications 6−5


Copyright © Orchard Publications
Chapter 6 Connective Junctions

Size 7

Size 10 Size 7

Figure 6.6. Larger size for a connective junction

6.4 Changing Connective Junction Properties


To edit the properties for a connective junction, we do the following:
1. We right−click a connective junction. In the resulting pop−up menu shown in Figure 6.4
above, we select Properties. The Connective Junction dialog box appears as shown in Figure
6.7 below.

Figure 6.7. The Connective Junction dialog box

6−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Uses of Connective Junctions

2. We edit the fields in the properties dialog, which are described in the table below.

Field Description
Parent Parent of this state; read−only; click the hypertext link to bring the
parent to the foreground.
Description Textual description/comment.
Document Link Enter a URL address or a general MATLAB command.
Examples are www.mathworks.com, mailto:email_address,
and edit/spec/data/speed.txt.

6.5 Uses of Connective Junctions


We use connective junctions to represent common code structures like for loops and if−then−
else constructs without the use of states. This reduces the number of states in our Stateflow dia-
grams, and the flow diagram notation produces more efficient generated code that optimizes
memory use.
With flow diagram notation we use combinations of the following:
• Transitions to and from connective junctions
• Self−loops to connective junctions
• Inner transitions to connective junctions
One Stateflow diagram can include flow diagram notation, states, and state−to−state transitions.
It is imperative that we represent flow diagram notation with action language as illustrated in the
examples that follow. In all examples, the rectangles with rounded corners represent states, the
letter e represents events, and the letter c followed by a number, both enclosed in brackets, rep-
resents a condition.

The general label format for a transition entering a state is shown in Figure 6.8* below.

Figure 6.8. The general label format for a transition entering a state

Execution of a transition from State S1 to State S2 in Figure 6.8 occurs as follows:


1. When an event (event) occurs, state S1 is checked for an outgoing transition with a matching
event specified.

* We recall from Chapter 1 that to draw transitions between states, we move the cursor to an edge of the origination state
until the cursor shape changes to crosshairs, we hold down the left mouse button, we drag the cursor to an edge of the des-
tination state, and we release the mouse button.

Introduction to Stateflow®with Applications 6−7


Copyright © Orchard Publications
Chapter 6 Connective Junctions

2. If a transition with a matching event is found, the condition for that transition ([condition]) is
evaluated.
3. If the condition condition evaluates to true, the condition action ({condition_action}) is exe-
cuted.
4. If the destination state (S2) is determined to be a valid destination, the transition occurs.
5. State S1 is exited.
6. The transition action (transition_action) is executed when the transition occurs.
7. State S2 is entered.
The general label format for a transition segment entering a junction is the same as for transitions
entering states, as shown in Figure 6.9 below.

Figure 6.9. The general label format for a transition segments

1. In Figure 6.9, when an event occurs, state S1 is checked for an outgoing transition with a
matching event specified.
2. If a transition with a matching event is found, the transition condition for that transition (in
brackets) is evaluated.
3. If condition_1 evaluates to true, the condition action condition_action (in braces) is executed.
4. The outgoing transitions from the junction are checked for a valid transition. Assuming that
condition_2 is true, a valid state−to−state transition (S1 to S2) is found.
5. State S1 is exited and this includes the execution of S1's exit action.

6−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Uses of Connective Junctions

6. The transition action transition_action is executed.


7. The completed state−to−state transition (S1 to S2) is taken.
8. State S2 is entered and this includes the execution of S2's entry action.

Example 6.1
This is a connective junction example with all conditions specified.
Let us consider the flow diagram notations in Figure 6.10.

Figure 6.10. Flow diagram notations for Example 6.1

In the flow diagram on the left, if state D is active when event e occurs, the transition from state
D to any of states E, F, or G takes place if one of the conditions [c1], [c2], or [c3] is met.
In the equivalent representation on the right, a transition from the source state to a connective
junction is labeled by the event. Transitions from the connective junction to the destination
states are labeled by the conditions. If state D is active when event e occurs, the transition from
D to the connective junction occurs first. The transition from the connective junction to a desti-
nation state follows based on which of the conditions [c1], [c2], or [c3] is true. If none of the con-
ditions is true, no transition occurs and state D remains active.

Example 6.2
This is a connective junction example with one unconditional transition specified.

Let us consider the flow diagram notations in Figure 6.11.*

* We could have used the simpler notations e, [c1], and [c2].

Introduction to Stateflow®with Applications 6−9


Copyright © Orchard Publications
Chapter 6 Connective Junctions

Figure 6.11. Flow diagram notations for Example 6.2

In the flow diagram above, the transition A to B occurs if state A is active, if event e_one occurs,
and [c_one] is true. The transition A to C occurs if state A is active, if event e_one occurs, and
[c_two] is true. The transition A to D occurs if state A is active and event e_one occurs. Since we
did not specify [c_three], the transition condition is not [c_one] and not [c_two].

Example 6.3
This is a connective junction example with a self−loop.
In some situations, the transition event occurs but a condition is not met. No transition is taken,
but an action is generated. We can represent this situation by using a connective junction or a
self−loop transition (transition from state to itself).
Let us consider the flow diagram notations in Figure 6.12.

Figure 6.12. Flow diagram notations for Example 6.3

In the flow diagram on the left, if state A is active when event e occurs and the condition [c1] is
met, the transition from state A to state B occurs, and generates action a1. The transition from
state A to state A is valid if event e occurs and [c1] is not true. In this self−loop transition, the sys-
tem exits and reenters state A, and executes action a2.
In the equivalent representation on the right, the use of a connective junction makes it unneces-
sary to specify the implied condition [~c1] explicitly.

6−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Uses of Connective Junctions

Example 6.4
This is a connective junction example with and For Loops.
Let us consider the flow diagram notations in Figure 6.13.

Figure 6.13. Flow diagram notations for Example 6.4

This flow diagram shows a combination of flow diagram notation and state transition notation.
Self−loop transitions to connective junctions can be used to represent for loop constructs.
In state A, event e occurs. The transition from state A to state B is valid if the conditions along
the transition path are true. The first segment of the transition does not have a condition, but
does have a condition action {i=0}, and this condition action is executed. The condition on the
self−loop transition is evaluated as true and the condition actions {i++;func1()} execute. The
condition actions execute until the condition [i<10] is false. The condition actions on both the
first segment and the self−loop transition to the connective junction effectively execute a for
loop (for i values 0 to 9 execute func1()). The for loop is executed outside the context of a state.
The remainder of the path is evaluated. Because there are no conditions, the transition com-
pletes at the destination, state B.

Example 6.5
This is a flow diagram notation example.
Let us consider the flow diagram notations in Figure 6.14.

Figure 6.14. Flow diagram notations for Example 6.5

Introduction to Stateflow®with Applications 6−11


Copyright © Orchard Publications
Chapter 6 Connective Junctions

This Stateflow diagram models an 8−bit analog−to−digital converter (ADC)*, and shows a use of
flow diagram notation and state transition notation.
We begin with the assumption that state Sensor.Low is active and event Update occurs. The
default transition to the first connective junction is valid. The next transition segment has a con-
dition action, {start_adc()}, which initiates a reading from the ADC. The self−loop on the second
connective junction repeatedly tests the condition [adc_busy()]. This condition evaluates as true
once the reading settles (stabilizes) and the loop completes. This self−loop transition is used to
introduce the delay needed for the ADC reading to settle. The delay could have been represented
by another state with some sort of counter. Using flow notation in this example avoids an unnec-
essary use of a state and produces more efficient code.
The next transition segment condition action, {sensor_value=read_adc()}, places the new value
read from the ADC in the data object sensor_value. The final transition segment is determined
by the value of sensor_value. If [sensor_value <100] is true, the destination is the state Sen-
sor.Low. If [sensor_value >200] is true, the destination is the state Sensor.High. Otherwise, the
destination is state Sensor.Normal.

Example 6.6
This is an example of a connective junction from a common source to multiple destinations.
Let us consider the flow diagram notations in Figure 6.15.

Figure 6.15. Flow diagram notations for Example 6.6

In the flow diagram on the left, transitions A to B and A to C share a common source state A.
In the equivalent representation on the right, one arrow from A to a connective junction is used,
and multiple arrows labeled by events from the junction to the destination states B and C.

* For popular types and hardware implementations of ADCs, please refer to Electronic Devices and Amplifier Circuits with
MATLAB Applications, ISBN 0−9709511−7−5.

6−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Uses of Connective Junctions

Example 6.7
This is an example of a connective junction common events.
Let us consider the flow diagram notations in Figure 6.16.

Figure 6.16. Flow diagram notations for Example 6.7

In the flow diagram on the left, when event e1 occurs, the system whether it is in state B or C,
transfers this event to state A.
In the equivalent representation on the right, transitions from states B and C are drawn to a con-
nective junction, then a transition from the junction to state A is drawn labeled with event e1.

Example 6.8
This is an example of an IF−Then−Else decision construct.
Let us consider the flow diagram notations in Figure 6.17.

Figure 6.17. Flow diagram notations for Example 6.8

As shown in the flow diagram in Figure 6.17, after the name, we enter optional action statements
for the state with a keyword label that identifies the type of action. We can specify none, some,

Introduction to Stateflow®with Applications 6−13


Copyright © Orchard Publications
Chapter 6 Connective Junctions

or all of them. The colon after each keyword is required. The slash following the state name is
optional as long as it is followed by a carriage return. For each type of action, we can enter more
than one action by separating each action with a carriage return, semicolon, or a comma. We can
specify actions for more than one event by adding additional on event_name lines for different
events.If we enter the name and slash followed directly by actions, the actions are interpreted as
entry action(s). This shorthand is useful if we are only specifying entry actions.
We assume that the Stateflow chart is asleep and state A is active, and the transition segments on
the connective junction are evaluated for validity starting at the twelve o’clock position on the
connective junction. Condition [c_2] is true. The sequence of operation is as follows:
1. Event e_1 occurs and awakens the Stateflow diagram.
2. The Stateflow diagram root checks to see if there is a valid transition as a result of the occur-
rence of event e_1. A valid transition from state A to the connective junction is found, and
the first transition segment from the connective junction to state B labeled [c_1] is not valid.
3. The next transition segment from the connective junction to state C labeled [c_2] is valid, and
thus the transition from state A to state C is valid and completed.
4. State A exit action (exitA()) executes and is completed.
5. State A becomes inactive.
6. State C is active.
7. State C entry action (entC()) executes and is completed.
8. The Stateflow diagram goes back to sleep.

Example 6.9
This is an example of a backtracking behavior in Stateflow graphs.
Let us consider the flow diagram notations in Figure 6.18.

Figure 6.18. Flow diagram notations for Example 6.9

We assume that state A is active, and conditions [c1], [c2], and [c3] are true. The sequence of
operation is as follows:

6−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Uses of Connective Junctions

1. The Stateflow diagram root checks to see if there is a valid transition from state A.
There is a valid transition segment indicated with the condition [c1] from state A to the first
connective junction.
2. Condition [c1] is true and thus action {a1} is executed.
3. Condition [c3] is true and thus action {a3} is executed.
4. Condition [c4] is not true and thus control flow is backtracked to state A.
5. The Stateflow diagram root checks to see if there is another valid transition from state A.
There is a valid transition segment indicated with the condition [c2] from state A to the first
connective junction.
6. Condition [c2] is true and thus action {a2} is executed.
7. Condition [c3] is true and thus action {a3} is executed.
8. Condition [c4] is not true and thus control flow is backtracked to state A.
9. The Stateflow diagram goes to sleep.

Example 6.10
This is an example of a more efficient backtracking behavior in Stateflow graphs.
In Example 6.9 above, because of the behavior of executing both actions {a1} and {a2}, action
{a3} was executed twice.
Let us consider the amended flow diagram notations in Figure 6.19.

Figure 6.19. Flow diagram notations for Example 6.10

The addition of the two terminating junctions allow the flow to terminate if either [c3] or [c4] is
not true, and it leaves state A active without taking any unnecessary actions.

Introduction to Stateflow®with Applications 6−15


Copyright © Orchard Publications
Chapter 6 Connective Junctions

6.6 Summary
• Connective junctions provide decision points between alternate transition paths.
• To create a single junction, in the diagram toolbar, we click the Connective Junction tool

and we move the cursor into the diagram editor.The cursor takes on the shape of a con-
nective junction, and we click to place a connective junction in the desired location in the
drawing area.
• To create multiple connective junctions, in the diagram toolbar, we double−click the Connec-
tive Junction tool and the connective junction is now in multiple object mode. We click any-
where in the drawing area to place a connective junction in the drawing area. We move to and
click another location to create an additional connective junction. We click the Connective
Junction tool or we press the Esc key to terminate the operation.
• To move a connective junction to a new location, we click and we drag it to the new position.
• To change the size of connective junctions, we select the connective junctions whose size we
want to change, we place the cursor over one of the connective junctions and we right−click.
In the resulting pop−up menu we place the cursor over Junction Size. A submenu of junction
sizes appears and we select a size from the menu of junction sizes.
• To edit the properties for a connective junction, we right−click a connective junction. In the
resulting pop−up menu we select Properties. The Connective Junction dialog box appears,
and we edit the fields in the properties dialog.
• We use connective junctions to represent common code structures like for loops and if−then−
else constructs without the use of states. This reduces the number of states in our Stateflow
diagrams, and the flow diagram notation produces more efficient generated code that opti-
mizes memory use.
• With flow diagram notation we use combinations of the following:
1. Transitions to and from connective junctions
2. Self−loops to connective junctions
3.Inner transitions to connective junctions
• One Stateflow diagram can include flow diagram notation, states, and state−to−state transi-
tions. It is imperative that we represent flow diagram notation with action language.

6−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercise for the Reader

6.7 Exercise for the Reader


The Stateflow diagram below shows the behavior of a transition from an OR substate to another
OR substate.

It is assumed that State A.A1 is initially active, event e_1 occurs and awakens the Stateflow dia-
gram, and Condition [c_1] is true. Describe the sequence of operation in a hierarchical order.

Introduction to Stateflow®with Applications 6−17


Copyright © Orchard Publications
Chapter 6 Connective Junctions

6.8 Solution to the End−of−Chapter Exercise

The sequence of operations in a hierarchical order is as follows:


1. The Stateflow diagram root checks to see if there is a valid transition resulting from event e_1,
and finds that there is a valid transition from State A.A1 to State B.B1, since it was given that
Condition [c_1] is true.
2. State A during actions (durA()) is executed and completed.
3. State A.A1 exit actions (exitA1()) is executed and completed.
4. State A.A1 becomes inactive.
5. State A exit actions (exitA()) is executed and completed.
6. State A becomes inactive.
7. The transition action A is executed and completed.
8. State B becomes active.
9. State B entry actions (entB()) is executed and completed.
10. State A.A1 becomes active.
11. State B.B1 entry actions (entB1()) is executed and completed.
12. The Stateflow diagram goes back to sleep until awakened by another event.

6−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 7
History Junctions and Transitions

T
his chapter describes the use of history junctions to represent historical decision points in
the Stateflow diagram. A description with an illustrative example is provided, and the
chapter concludes with a discussion on transitions. For easy reference, the examples pre-
sented are the same or similar to those included in the Stateflow documentation.

7.1 History Junction Defined


A history junction records a previously active state in which it is resident. It is used to represent
historical decision points in the Stateflow diagram. The decision points are based on historical
data relative to state activity. Placing a history junction in a superstate* indicates that historical
state activity information is used to determine the next state to become active. The history junc-
tion applies only to the level of the hierarchy in which it appears.

7.2 The Stateflow History Junction Tool


Figure 7.1 is our familiar Stateflow Editor window, and when we place the mouse cursor over the

History Junction tool , its name appears at the bottom of the window.
To create a history junction, we do the following:

1. In the diagram toolbar, we click the History Junction tool .


2. We move the cursor into the diagram editor.The cursor takes on the shape of a history junc-
tion as shown in Figure 7.2. We click to place a connective junction in the desired location in
the drawing area.

* We recall from Chapter 1 that objects in Stateflow exist in a hierarchy and states can contain other states referred to as sub-
states, and can be contained by other states referred to as superstates.

Introduction to Stateflow®with Applications 7−1


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 7.1. The Stateflow Editor window with the mouse pointer near the History Junction tool

7.3 Changing the History Junction Size


To change the size of history junctions, we do the following:
1. We select the history junctions whose size we want to change.
2. We place the cursor over one of the connective junctions and we right−click. In the resulting
pop−up menu shown in Figure 7.3, we place the cursor over Junction Size. A submenu of
junction sizes appears as shown in Figure 7.4, and we select a size from the menu of junction
sizes.

7−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing the History Junction Size

Figure 7.2. Placing a history junction in the drawing area

Figure 7.3. Pop−up menu for changing the size of a connective junction

Introduction to Stateflow®with Applications 7−3


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 7.4. Pop−up menu and submenu for selecting connective junction sizes

We can change a history junction to a connective junction and vice versa from the pop−up menu
above by selecting Type. The pop−up menu and the resulting submenu then appear as shown in
Figure 7.5.

7−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing History Junction Properties

Figure 7.5. Converting a history junction to a connective junction and vice versa from the pop−up menu.

7.4 Changing History Junction Properties


To edit the properties for a history junction, we do the following:
1. We right−click a history junction. In the resulting pop−up menu shown in Figure 7.5 above,
we select Properties. The History Junction dialog box appears as shown in Figure 7.6 below.

Introduction to Stateflow®with Applications 7−5


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 6.6. The History Junction dialog box

2. We edit the fields in the properties dialog, which are described in the table below.

Field Description
Parent Parent of this state; read−only; click the hypertext link to bring the
parent to the foreground.
Description Textual description/comment.
Document Link Enter a URL address or a general MATLAB command.
Examples are www.mathworks.com, mailto:email_address,
and edit/spec/data/speed.txt.

Example 7.1
This is a History Junction example.
Let us consider the flow diagram in Figure 7.7 that uses a history junction.

7−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing History Junction Properties

Figure 7.7. Flow diagram for Example 7.1

Superstate Power_on has a history junction and contains two substates. If state Power_off is
active and event switch_on occurs, the system could enter either Power_on.Low or
Power_on.High . The first time superstate Power_on is entered, substate Power_on.Low is
entered because it has a default transition. At some point afterward, if state Power_on.High is
active and event switch_off occurs, superstate Power_on is exited and state Power_off becomes
active. Then event switch_on occurs. Since Power_on.High was the last active state, it becomes
active again. After the first time Power_on becomes active, the choice between entering
Power_on.Low or Power_on.High is determined by the history junction.

Example 7.2
This is a History Junction example with Default Transition.
Let us consider the flow diagram notations in Figure 7.8 that shows the behavior of a superstate
with a default transition and a history junction.

Introduction to Stateflow®with Applications 7−7


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 7.8. Flow diagram notations for Example 7.2

Initially the Stateflow diagram is asleep. State A is active. There is a history junction and state B4
was the last active substate of superstate B. Event E_one occurs and awakens the Stateflow dia-
gram. Event E_one is processed from the root of the Stateflow diagram down through the hierar-
chy of the Stateflow diagram:
1. The Stateflow diagram root checks to see if there is a valid transition as a result of E_one.
There is a valid transition from state A to superstate B.
2. State A exit actions (exitA()) execute and complete.
3. State A is marked inactive.
4. State B is marked active.
5. State B entry actions (entB()) execute and complete.
6. State B uses the history junction to determine the substate destination of the transition into
the superstate.
The history junction indicates that substate B.B4 was the last active substate, which becomes
the destination of the transition.

7−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Entering a State

7. State B.B4 is marked active.


8. State B.B4 entry actions (entB4()) execute and complete.
9. The Stateflow diagram goes back to sleep, waiting to be awakened by another event.
This sequence completes the execution of this Stateflow diagram associated with event E_one.

7.5 Entering a State


A state is entered (becomes active) in one of the following ways:
1. Its boundaries are crossed by an incoming executed transition.
2. Its boundary terminates the arrow end of an incoming transition.
3. It is the parallel state child of an activated state.
A state performs its entry action (if specified) when it becomes active. The state is marked active
before its entry action is executed and completed.
The execution steps for entering a state are as follows:
1. If the parent of the state is not active, perform steps 2 through 4 for the parent first.
2. If this is a parallel state, check if a sibling parallel state previous in entry order is active. If so,
start at step 1 for this parallel state.
Parallel (AND) states are ordered for entry based on their vertical top−to−bottom position in
the diagram editor. Parallel states that occupy the same vertical level are ordered for entry
from left to right.
In the example in Figure 7.9, the order of execution is determined by the position of the states.

Figure 7.9. The position of the states A,B,C, and D determines the order of execution

Introduction to Stateflow®with Applications 7−9


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

In the example in Figure 7.9, parallel states A and B are aligned at the same horizontal level
while states A and C and states B and D are aligned at the same vertical position.
Based on their top−down positions in the diagram editor, the order of entry for these states is
A or B, then D, then C. Because A is left of B, A is evaluated first and the order of entry is A,
B, D, C. Stateflow marks this order with an order number in the upper right−hand corner of
the state (1, 2, 3, 4, respectively)
Step 2 says that if we are entering state D in step 1, we should check if state B is active. If it is
not, we should start at Step 1 for state B. Step 2 repeats for state B and, if A is not active, start
at Step 1 for A. Since there are no parallel states of lesser entry order, we continue with Step 3
below for state A.
3. Mark the state active.
4. Perform any entry actions.
5. Enter children, if needed:
a. Execute the default flow paths for the state unless it contains a history junction.
b. If the state contains a history junction and there is an active child of this state at some
point after the most recent chart initialization, perform the entry actions for that child.
c. If this state has children that are parallel states (parallel decomposition), perform entry
steps 1 to 5 for each state according to its entry order.
6. If this is a parallel state, perform all entry steps for the sibling state next in entry order if one
exists.
7. If the transition path parent is not the same as the parent of the current state, perform entry
steps 6 and 7 for the immediate parent of this state.
8. The chart goes to sleep.

7.6 Executing an Active State


Active states that receive an event that does not result in an exit from that state execute a during
action to completion if a during action is specified for that state. An on event_name action exe-
cutes to completion when the event specified, event_name, occurs and that state is active. An
active state executes its during and on event_name actions before processing any of its children's
valid transitions. During and on event_name actions are processed based on their order of
appearance in the state label.
The execution steps for executing a state that receives an event while it is active are as follows:
1. The set of outer flow graphs is executed. If this causes a state transition, execution of the state
stops. This step is never required for parallel states

7−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exiting an Active State

2. During actions and valid on event name actions are performed.


3. The set of inner flow graphs is executed. If this does not cause a state transition, the active
children are executed, starting at step 1. Parallel states are executed in the same order that
they are entered.

7.7 Exiting an Active State


A state is exited (becomes inactive) in one of the following ways:
1. Its boundary is the origin of an outgoing executed transition.
2. Its boundary is crossed by an outgoing executed transition.
3. It is a parallel state child of an activated state.
A state performs its exit action (if specified) before it becomes inactive. The state is marked inac-
tive after the exit action has executed and completed.
The execution steps for exiting a state are as follows:
1. If this is a parallel state, and one of its sibling states was entered before this state, exit the sib-
lings starting with the last−entered and progressing in reverse order to the first−entered. See
step 2 of Entering a State.
2. If there are any active children, perform the exit steps on these states in the reverse order they
were entered.
3. Perform any exit actions.
4. Mark the state as inactive.

Example 7.3
This is a state execution example.
The Stateflow diagram in Figure 7.10 illustrates the execution semantics (behavior) of event
reactive behavior by active and inactive states.
Initially the Stateflow diagram and its states are inactive. This is the semantic sequence that fol-
lows an event:
1. An event occurs and the Stateflow diagram is awakened.
2. The Stateflow diagram checks to see if there is a valid transition as a result of the event.
A valid default transition to state A is detected.
3. State A is marked active.
4. State A entry actions (entA()) execute and complete.

Introduction to Stateflow®with Applications 7−11


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 7.10. A state execution example

5. The Stateflow diagram goes back to sleep.

Example 7.4
This is a sleeping diagram event reaction example.
The Stateflow diagram in Figure 7.10 is now asleep and waits to be awaken by another event.
Refer now to the state diagram in Figure 7.11.

State A is
marked
inactive

State B is
marked
active

Figure 7.11. Continuation of the state execution example

1. Event E_one occurs and the Stateflow diagram is awakened.


State A is active from the preceding example, steps 1 to 5.

7−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Execution Order for Parallel States

2. The Stateflow diagram root checks to see if there is a valid transition as a result of E_one. A
valid transition is detected from state A to state B.
3. State A exit actions (exitA()) execute and complete.
4. State A is marked inactive.
5. State B is marked active.
6. State B entry actions (entB()) execute and complete.
7. The Stateflow diagram goes back to sleep, to be awakened by the next event.

7.8 Execution Order for Parallel States

Multiple parallel (AND) states in the same chart execute concurrently. However, Stateflow
must determine when to activate each one during simulation. This ordering determines when
each parallel state performs the actions that take it through all stages of execution, as described
in Entering, Executing, and Exiting a State in the previous section.
Unlike exclusive (OR) states, parallel states do not typically use transitions. Instead, order of
execution is determined by one of the following mechanisms:
1. Implicit ordering by geometry
Stateflow uses a set of internal rules to order parallel states according to geometric position as
described below.
2. Explicit ordering specified by the user
We can override implicit rules by explicitly specifying the execution order of parallel states on
an individual basis as described below.
Parallel states are assigned priority numbers based on order of execution. The lower the number,
the higher the priority. Each state's priority number appears in its upper right corner.
Execution order is a chart property; all parallel states in the chart inherit the property setting.
We cannot mix implicit and explicit ordering in the same Stateflow chart, but we can mix charts
with different ordering modes in the same Simulink model.
Implicit Ordering of Parallel States
By default, Stateflow orders parallel states implicitly based on where they are located in the state
diagram. Priority goes from top to bottom and then left to right, according to these rules:
1. The higher a parallel state's vertical position in the diagram, the higher its priority for execu-
tion.
2. Among parallel states with the same vertical position, the left−most state receives highest pri-
ority.

Introduction to Stateflow®with Applications 7−13


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

An example to illustrate how these rules apply to top−level parallel states and parallel substates is
shown in Figure 7.12.

Figure 7.12. Implicit ordering of parallel states

Explicit Ordering of Parallel States


A disadvantage of implicit ordering is that it creates a dependency between design layout and
execution priority. When we rearrange parallel states in our diagram, we may inadvertently
change order of execution and affect simulation results. To gain more control over our designs,
we can override implicit ordering by explicitly setting execution priorities.
To use explicit ordering for parallel states, we perform these tasks:
From the File menu we select Chart Properties and in the properties dialog box we place a
check mark in the field labeled User specified state/transition execution order as shown in
Figure 7.13, and we click OK.

7−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Transitions

Figure 7.13. Chart dialog box for selecting User/specified state/transition execution order

Alternately, we can right−click inside the top level of the Stateflow chart and from the pop−up
menu we select Properties. We can also right−click inside one of the parallel states in the
chart and from the pop−up menu we select Execution Order and from the submenu we can
select the desired execution order of individual parallel states. We right−click the parallel state
of interest and we select a new priority from the Execution Order menu.
If the Stateflow chart already contains parallel states that have been ordered implicitly, the
existing priorities are preserved until we explicitly change them. When we add new parallel
states in explicit mode, Stateflow automatically assigns priorities based on order of creation
However we can now explicitly change execution order on a state by state basis.

7.9 Transitions
A transition is a curved line with an arrowhead that links one graphical object to another. In
most cases, a transition represents the passage of the system from one mode (state) object to
another. A transition is attached to a source and a destination object. The source object is where

Introduction to Stateflow®with Applications 7−15


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

the transition begins and the destination object is where the transition ends. Figure 7.14 below is
an example of a transition from a source state A to a destination state B.

Figure 7.14. Transition from State A (source) to State B (destination)

As we already know from the previous chapter, connective junctions divide a transition into tran-
sition segments. In this case, a full transition consists of the segments taken from the origin to the
destination state. Each segment is evaluated in the process of determining the validity of a full
transition.
Figure 7.15 below shows an example that has two segmented transitions: one from state A to a
connective junction where one transition from the connective junction goes to state B, and the
other from the connective junction back to state A.

Figure 7.15. Example of a connective junction that divides one transition into transition segments

We are familiar with default transitions. As a review, default transitions are primarily used to
specify which exclusive (OR) state is to be entered when there is ambiguity among two or more
neighboring exclusive (OR) states. They have a destination but no source object. For example,
default transitions specify which substate of a superstate with exclusive (OR) decomposition the
system enters by default in the absence of any other information such as a history junction.
Default transitions are also used to specify that a junction should be entered by default.
Transition Hierarchy dictates that transitions cannot contain other objects like states can. How-
ever, transitions are contained by states. A transition's hierarchy is described in terms of the tran-
sition's parent, source, and destination. The parent is the lowest level that contains the source
and destination of the transition. Figure 7.16 shows three transitions and the parentage is
resolved in Table 7.1 where the Stateflow diagram is represented by the slash (/) character, and
each level in the hierarchy of states is separated by the period (.) character.

7−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Transitions

Figure 7.16. A transition hierarchy example

TABLE 7.1
Transition Label Transition Parent Transition Source Transition Destination
switch_off / /Power_on.Low.Heat /Power_off
switch_high /Power_on /Power_on.Low.Heat /Power_on.High
switch_cold /Power_on.Low /Power_on.Low.Heat /Power_on.Low.Cold

A transition is characterized by its label. The label can consist of an event, a condition, a condi-
tion action, and/or a transition action. The question mark (?) character is the default transition
label. Transition labels have the following general format:
event[condition]{condition_action}/transition_action
We need to replace the names for event, condition, condition_action, and transition_action with
appropriate contents as shown in the example in Figure 7.17. Each part of the label is optional.

Figure 7.17. Typical label for a transition

In the label above, E is referred to as an event trigger. It specifies an event that causes the transi-
tion to be taken, provided the condition, if specified, is true. Specifying an event is optional. The

Introduction to Stateflow®with Applications 7−17


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

absence of an event indicates that the transition is taken upon the occurrence of any event. Mul-
tiple events are specified using the OR logical operator (|). In this example, the broadcast of
event E triggers the transition from A to B provided the condition [off_count==0] is true.
Condition: Specifies a boolean expression that, when true, validates a transition to be taken for
the specified event trigger. We must enclose the condition in square brackets ([]). In this exam-
ple, the condition [off_count==0] must evaluate as true for the condition action to be executed
and for the transition from the source to the destination to be valid.
Condition Action: A condition action follows the condition for a transition and is enclosed in
curly braces ({}). It is executed as soon as the condition is evaluated as true and before the tran-
sition destination has been determined to be valid. If no condition is specified, an implied condi-
tion evaluates to true and the condition action is executed. In this example, if the condition
[off_count==0] is true, the condition action off_count++ is immediately executed.
Transition Action: The transition action is executed after the transition destination has been
determined to be valid provided the condition, if specified, is true. If the transition consists of
multiple segments, the transition action is only executed when the entire transition path to the
final destination is determined to be valid. We must precede the transition action with a back-
slash. In this example, if the condition [off_count==0] is true, and the destination state B is valid,
the transition action Light_off is executed.
Valid Transitions
In most cases, a transition is valid when the source state of the transition is active and the transi-
tion label is valid. Default transitions are slightly different because there is no source state. Valid-
ity of a default transition to a substate is evaluated when there is a transition to its superstate,
assuming the superstate is active. This labeling criterion applies to both default transitions and
general case transitions.
The following are possible combinations of valid transition labels.

Transition Label Is Valid If...


Event only That event occurs
Event and condition That event occurs and the condition is true
Condition only Any event occurs and the condition is true
Action only Any event occurs
Not specified Any event occurs

7−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Transition Connections

7.10 Transition Connections


Stateflow notation supports a wide variety of transition connections, which are illustrated by the
examples in the following topics:
Transitions to and from Exclusive (OR) States
The example in Figure 7.18 shows simple transitions to and from exclusive (OR) states.

Initially active

Figure 7.18. Example of transitions to and from Exclusive (OR) states

The transition On → Off is valid when state On is active and the event Switch_off occurs. The
transition Off → On is valid when state Off is active and event Switch_on occurs.
Transitions to and from Connective Junctions
The example in Figure 7.19 shows transitions to and from connective junctions.

Initially active

Figure 7.19. Example of transitions to and from Connective Junctions

This is a Stateflow diagram of a soda machine. The Stateflow diagram is called when the external
event Selection_made occurs. The Stateflow diagram awakens with the Waiting state active.

Introduction to Stateflow®with Applications 7−19


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

The Waiting state is a common source state. When the event Selection_made occurs, the State-
flow diagram transitions from the Waiting state to one of the other states based on the value of
the variable select. One transition is drawn from the Waiting state to the connective junction.
Four additional transitions are drawn from the connective junction to the four possible destina-
tion states.
Transitions to and from Exclusive (OR) Superstates
The example in Figure 7.20 shows transitions to and from an exclusive (OR) superstate and the
use of a default transition.

Figure 7.20. Example of transitions to and from Exclusive (OR) superstates

This is an expansion of the soda machine Stateflow diagram that includes the initial example of
the On and Off exclusive (OR) states. On is now a superstate containing the Waiting and soda
choices states. The transition Off → On is valid when state Off is active and event Switch_on
occurs. Since On is a now a superstate, this is an explicit transition to the On superstate.
For a transition to a superstate to be a valid, the destination substate must be implicitly defined.
The destination substate for On is implicitly defined by making the Waiting substate the destina-
tion state of a default transition. This notation defines that the resultant transition is made from
the Off state to the state On.Waiting.
The transition from On to Off is valid when state On is active and event Switch_off occurs. How-
ever, when the Switch_off event occurs, a transition to the Off state must take place no matter
which of the substates of On is active. This top−down approach simplifies the Stateflow diagram

7−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Transition Connections

by looking at the transitions out of the superstate without considering all the details of states and
transitions within the superstate.
Transitions to and from Substates
The following example shows transitions to and from exclusive (OR) substates.

Figure 7.21. Example of transitions to and from substates

The example in Figure 7.21 a transition from one OR substate to another OR substate, i.e., the
transition from Waiting.Ready to Orange.The transition to the state In_motion is valid when
state Waiting.Ready is active and the event Selection_made occurs, provided that the variable
select equals 1. This transition defines an explicit exit from the Waiting.Ready state and an
implicit exit from the Waiting superstate. On the destination side, this transition defines an
implicit entry into the Orange superstate and an explicit entry into the Orange.In_motion sub-
state.
Self−Loop Transitions
The example in Figure 7.22 shows a transition segment from a state to a connective junction
that has an outgoing transition segment from the connective junction back to the state.

Figure 7.22. Example of self−loop transitions

Introduction to Stateflow®with Applications 7−21


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

7.11 Inner Transitions


An inner transition is a transition that does not exit the source state.* Inner transitions are most
powerful when defined for superstates with exclusive (OR) decomposition. Use of inner transi-
tions can greatly simplify a Stateflow diagram, as shown by the following examples:
We will show how the Stateflow diagram in Figure 7.23 can be simplified by using an inner transi-
tion.

Figure 7.23. Stateflow diagram that could be simplified by an inner transition

In the Stateflow diagram in Figure 7.23, any event occurs and awakens the Stateflow diagram.
The default transition to the connective junction is valid. The destination of the transition is
determined by [C_one] and [C_two]. If [C_one] is true, the transition to A1 is true. If [C_two] is
true, the transition to A2 is valid. If neither [C_one] nor [C_two] is true, the transition to A3 is
valid. The transitions among A1, A2, and A3 are determined by E_one, [C_one], and [C_two].
The Stateflow diagram in Figure 7.23 can be simplified by using an inner transition to a connec-
tive junction as shown in Figure 7.24.

* To draw an inner transition, we move the cursor at one of the edges of the state until the cursor shape changes to crosshairs,
we hold down the left mouse button, we drag the cursor inside the state to any object such as a connective junction or history
junction, and we release the left mouse button.

7−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Inner Transitions

Figure 7.24. The simplified version of the Stateflow diagram in Figure 7.9 with an inner transition

In the Stateflow diagram in Figure 7.24, we assume that State A is initially active, and with the
occurrence of any event, the Stateflow diagram is awakened. The default transition to the con-
nective junction is valid. The destination of the transitions is determined by [C_one] and
[C_two].
The Stateflow diagram is simplified by using an inner transition in place of the many transitions
among all the states in the previous Stateflow diagram in Figure 7.23. If state A is already active,
the inner transition is used to reevaluate which of the substates of state A is to be active. When
event E_one occurs, the inner transition is potentially valid. If [C_one] is true, the transition to
A1 is valid. If [C_two] is true, the transition to A2 is valid. If neither [C_one] nor [C_two] is true,
the transition to A3 is valid. This version with the inner transition is much simpler than the pre-
vious one.

Example 7.5
This is a History Junction example with an Inner Transition.
The Stateflow diagram Figure 7.25 shows an inner transition and a history junction. By specify-
ing an inner transition to a history junction, we can specify that, based on a specified event and/
or condition, the active state is to be exited and then immediately reentered.

Introduction to Stateflow®with Applications 7−23


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Figure 7.25. Inner transition to a history junction

We assume that state Power_on.High is initially active. When event Reset occurs, the inner
transition to the history junction is valid. Because the inner transition is valid, the currently
active state, Power_on.High, is exited. When the inner transition to the history junction is pro-
cessed, the last active state, Power_on.High, becomes active (is reentered). If Power_on.Low was
active under the same circumstances, Power_on.Low would be exited and reentered as a result.
The inner transition in this example is equivalent to drawing an outer self−loop transition on
both Power_on.Low and Power_on.High, as shown in Figure 7.26.

Figure 7.26. Stateflow diagram equivalent to that in Figure 7.25

7−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Summary

7.12 Summary
• A history junction records a previously active state in which it is resident. It is used to repre-
sent historical decision points in the Stateflow diagram. The decision points are based on his-
torical data relative to state activity. Placing a history junction in a superstate indicates that
historical state activity information is used to determine the next state to become active.

• To place a history junction into the Stateflow Editor we click the History Junction tool
and we move it to the desired location in the Stateflow Editor drawing area.
• We can change a history junction to a connective junction and vice versa by right−clicking
the drawing area in the Stateflow Editor and from the pop−up menu we select Type.
• A transition is a curved line with an arrowhead that links one graphical object to another. In
most cases, a transition represents the passage of the system from one mode (state) object to
another. A transition is attached to a source and a destination object. The source object is
where the transition begins and the destination object is where the transition ends.
• Connective junctions divide a transition into transition segments. In this case, a full transition
consists of the segments taken from the origin to the destination state. Each segment is evalu-
ated in the process of determining the validity of a full transition.
• Transitions cannot contain other objects like states can. However, transitions are contained
by states. A transition's hierarchy is described in terms of the transition's parent, source, and
destination. The parent is the lowest level that contains the source and destination of the
transition.
• A transition is characterized by its label. The label can consist of an event, a condition, a con-
dition action, and/or a transition action. The question mark (?) character is the default transi-
tion label. Transition labels have the following general format:
event[condition]{condition_action}/transition_action
where:
event is an event trigger that specifies an event that causes the transition to be taken, pro-
vided the condition, if specified, is true. Specifying an event is optional. The absence of an
event indicates that the transition is taken upon the occurrence of any event.
Condition specifies a boolean expression that, when true, validates a transition to be taken for
the specified event trigger. We must enclose the condition in square brackets ([]).
Condition Action follows the condition for a transition and is enclosed in curly braces ({}). It is
executed as soon as the condition is evaluated as true and before the transition destination
has been determined to be valid. If no condition is specified, an implied condition evaluates to
true and the condition action is executed.

Introduction to Stateflow®with Applications 7−25


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

Transition Action is executed after the transition destination has been determined to be valid
provided the condition, if specified, is true. If the transition consists of multiple segments, the
transition action is only executed when the entire transition path to the final destination is
determined to be valid. We must precede the transition action with a backslash.
• In default transitions there is no source state. Validity of a default transition to a substate is
evaluated when there is a transition to its superstate, assuming the superstate is active. This
labeling criterion applies to both default transitions and general case transitions.
• Stateflow notation supports a wide variety of transition connections and these are illustrated
by examples in this chapter.
• An inner transition is a transition that does not exit the source state. Inner transitions are
most powerful when defined for superstates with exclusive (OR) decomposition. Use of inner
transitions can greatly simplify a Stateflow diagram.

7−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercise for the Reader

7.13 Exercise for the Reader


The Stateflow diagram below represents an automobile automatic transmission system. Describe
what the history junction indicates when clutch_engaged causes a transition from neutral to the
engaged superstate.

Introduction to Stateflow®with Applications 7−27


Copyright © Orchard Publications
Chapter 7 History Junctions and Transitions

7.14 Solution to the End−of−Chapter Exercise


The history junction indicates that when clutch_engaged causes a transition from neutral to the
engaged superstate, the substate that becomes active, either the first or second, is based on
which of those substates was most recently active.

7−28 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 8
Boxes in Stateflow

T
his is a short chapter describing the use of boxes to extend Stateflow Chart diagrams. We
describe how to create a state and changing it to a box, and how to create a box and change
it to a state.

8.1 Creating a Box


Boxes offer a convenience for organizing related items in our charts. We create a box by using the

Box tool in the Stateflow Editor window shown in Figure 8.1.

Figure 8.1. The Stateflow Editor window with the mouse pointer near the Box tool

Introduction to Stateflow®with Applications 8−1


Copyright © Orchard Publications
Chapter 8 Boxes in Stateflow

To create a Box we use the following steps:


1. We select the Box tool.
2. We move the cursor into the drawing area. In the drawing area, the mouse cursor becomes
box-shaped, and we click in a desired location to create a box.
3. The created box appears with a question mark (?) name in its upper left-hand corner, we click
the question mark label, and a text cursor appears in place of the question mark.
4. We enter a name for the box and click outside of the box when finished. A typical box appears
as shown in Figure 8.2.

Figure 8.2. A created box

To delete a box, we click it to select it and we press the Delete key, or we choose Cut (Ctrl+X)
from the Edit menu.

8.2 Changing a State to a Box


We can change an existing state to a box and back to a state with the following procedure:
1. We right-click the state and the pop-up menu shown in Figure 8.3 appears.

8−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing a State to a Box

Figure 8.3. Pop-up menu for changing a state to a box

2. From the pop-up menu in Figure 8.3, we select Type. A submenu appears adjacent to the pop-
up menu as shown in Figure 8.4.
3. From the submenu, we select Box, and Stateflow converts the state to a box, redrawing its
border with sharp corners to indicate its changed status.
4. We can change the box to a state from the submenu of Figure 8.4 by selecting State.

Introduction to Stateflow®with Applications 8−3


Copyright © Orchard Publications
Chapter 8 Boxes in Stateflow

Figure 8.4. Submenu for selecting box

8.3 Using Boxes in Stateflow


We use boxes to graphically organize our diagram. Shown in Figure 8.5 is an example of a State-
flow diagram object.

Figure 8.5. A Stateflow diagram object

8−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Using Boxes in Stateflow

If the Stateflow diagram in Figure 8.5 is to be used in several different Simulink models, we can
convert this diagram to a box as shown in Figure 8.6 below, and call it whenever it is needed.

Figure 8.6. The Stateflow diagram in Figure 8.5 converted to a box

Once we create a box we can use it in one of the following ways:


1. We can move or draw objects inside of a box to organize our diagram.
2. We can draw the box first as a state around the objects we want inside it, and then convert it
to a box.
3. We can add data to a box so that all the elements in the box can share the same data.
4. We can group a box and its contents into a single graphical element .
5. We can subchart a box to hide its elements.

Introduction to Stateflow®with Applications 8−5


Copyright © Orchard Publications
Chapter 8 Boxes in Stateflow

8.4 Summary
• Boxes offer a convenience for organizing related items in our charts. We create a box by using

the Box tool in the Stateflow Editor window.


• To create a Box we select it, we move the cursor into the drawing area. In the drawing area,
the mouse cursor becomes box-shaped, and we click in a desired location to create a box. The
created box appears with a question mark (?) name in its upper left-hand corner, we click the
question mark label, and a text cursor appears in place of the question mark. We enter a name
for the box and click outside of the box when finished.
• To delete a box, we click it to select it and we press the Delete key, or we choose Cut
(Ctrl+X) from the Edit menu.
• To change an existing state to a box and back to a state, we right-click the state and from the
pop-up menu that appears, we select Type. From the submenu, we select Box, and Stateflow
converts the state to a box, redrawing its border with sharp corners to indicate its changed sta-
tus. We can change the box to a state from the submenu by selecting State.
• Once we create a box we can use it in one of the following ways:
1. We can move or draw objects inside of a box to organize our diagram.
2. We can draw the box first as a state around the objects we want inside it, and then convert
it to a box.
3. We can add data to a box so that all the elements in the box can share the same data.
4. We can group a box and its contents into a single graphical element .
5. We can subchart a box to hide its elements.

8−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Chapter 9
Mealy and Moore Charts in Stateflow

T
his chapter begins with an overview of the Mealy and Moore machines, then describes the
procedure for creating Mealy and Moore charts in Stateflow, and concludes with illustra-
tive examples for each.

9.1 Mealy Machine Defined


In the theory of computation, a Mealy machine is a finite state machine that generates an output
based on its current state and an input. This means that the state diagram will include both an
input and output signal for each transition edge.

Example 9.1
This is a Mealy machine example.
Let us consider the state table below denoted as Table 9.1.

TABLE 9.1
Present State Input Next State Output

Q1
n
Q0
n x n+1
Q1 Q0
n+1 y

0 0 0 0 1 0
0 0 1 1 1 1
0 1 0 1 0 0
0 1 1 0 0 1
1 0 0 1 1 0
1 0 1 0 1 1
1 1 0 0 0 0
1 1 1 1 0 1

We can represent the state table above with the timing diagram shown in Figure 9.1 below.

Introduction to Stateflow®with Applications 9−1


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

CP
0 1 0 1 0 1 0 1 0
x
n 0 0 1 1 0 0 1 1 0
Q0

n 0 0 0 0 1 1 1 1 0
Q1
1 1 0 0 0 0 0
n+1 0 1 1
Q0
0 1 1 0 1 0 0 1 0
n+1
Q1
0 1 0 1 0 1 0 1 0
y

Figure 9.1. Timing diagram for state table Table 9.1


The Mealy machine for the state table in Table 9.1 and timing diagram in Figure 9.1 is shown in
Figure 9.2 below.

00

11 01

10

Figure 9.2. The Mealy machine for Example 9.1


In the state diagram in Figure 9.2, the numbers inside the states represented by the circles are the
four states of a synchronous counter that counts clockwise from 00 to 01 to 10 to 11 to 00 and
repeats whenever the input signal x is 0 , and counts counterclockwise from 11 to 10 to 01 to
00 to 11 and repeats whenever the input signal x is 1 .

9−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Moore Machine Defined

In a Mealy machine such as that of Figure 9.2, it is customary to indicate that the output y is
dependent on the current state, e.g., 00 and the input x by expressing the transition from one
state to another as x ⁄ y and placing it near the transition arrow. For example, for the transition
from state 00 to 01 the arrow in the clockwise direction has the designation 0 ⁄ 0 , and for the
transition from state 01 to 00 the arrow in the counterclockwise direction has the designation
1 ⁄ 1.

9.2 Moore Machine Defined


In contrast to the Mealy machine whose output depends on its current state and input, the out-
put of a Moore machine depends only on the machine's current state.
Besides showing the state inside the circle representing a state, Moore machines show also the
n n
outputs inside the circle. Thus, for a two−bit Moore machine, the state is represented as Q 1 Q 0 ,
the output is represented as y 1 y 0 , and the state and output are separated by a slash (/). For
instance, in the designation 10 ⁄ 01 , 10 indicates the state, and 01 indicates the output.

Example 9.2
This is a Moore machine example.
Let us consider the Moore machine shown in Figure 9.3.

00 ⁄ 01

11 ⁄ 00 01 ⁄ 10

10 ⁄ 11

Figure 9.3. Moore machine for Example 9.2

Introduction to Stateflow®with Applications 9−3


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

In the Moore machine shown in Figure 9.3, the variable z is not an input that will influence the
output value as in the case with Mealy machines. Here, z is an input that will transition us from
one state to another depending on its value, 0 or 1 . For this example, the values of z are
0 1 0 1 0 1 0 1 and when z = 0 , there is no transition to another state, while when z = 1 , the
transition follows a clockwise pattern as shown. We observe that at state 00 the output is 01 as
indicated by the designation 00 ⁄ 01 . Likewise, at state 01 the output is 10 and so on.

Table 9.2 lists some of the advantages and disadvantages of the Mealy and Moore machines.

TABLE 9.2 Mealy and Moore machines − Advantages and Disadvantages


Machine Advantages Disadvantages
Mealy Fewer states Input changes can cause very fast
React faster to inputs changes in output and this can
cause problems when two or more
machines are interconnected.
Moore Safer to use − outputs change at More states − typically for a Mealy
clock edge, always one cycle later machine with N states and k inputs,
the equivalent Moore machine
k
requires 2 states

9.3 Mealy and Moore Machines in Stateflow


The Stateflow charts we’ve created thus far, are called classic. In Stateflow, it is the default type.
We can also choose to create Mealy and Moore machines from the Chart dialog box* shown in
Figure 9.4. As we can see in Chart dialog box, from the State Machine Type field we can choose
Classic, Mealy, or Moore.

In Classic Stateflow, the output behaves like a state† since output values persist between time
steps and the output is available outside the chart through output ports. By contrast, output in
Mealy and Moore charts does not persist and instead must be computed in each time step.

* We access the Chart dialog box from the Stateflow Editor window by right−clicking a chart in that window and from the
pop−up menu that appears, we choose Properties.
† As we now know, a state is combination of local data, i.e., data defined in the current Stateglow chart only, and chart
activity, and thus computing a state implies the update of local data and making transitions from a currently active state to
another state.

9−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Mealy and Moore Machines in Stateflow

Figure 9.4. The Chart dialog box for selecting a Classic, Mealy, or Moore machine.
To ascertain that the output of Mealy and Moore machines is well defined at every time step, we
place a check mark in the Initialize Outputs Every Time Chart Wakes Up field as shown in
Figure 9.4 above, and this option initializes outputs to a default value* whenever the chart is trig-
gered.
As we now know, Mealy machines compute output on transitions, while Moore machines com-
pute outputs in states. Therefore, Mealy charts can compute output earlier than Moore charts,
that is, at the time Stateflow executes the chart’s default path. In Mealy charts, the computation
occurs at t = 1 and this is referred to as the next time step. But if we want the computation to
occur at t = 0 , we must place a check mark in the Execute (enter) Chart At Initialization field
as shown in the Chart dialog box in Figure 9.4 above. By contrast, Moore machines can compute
outputs only after Stateflow executes the default path. Until then, outputs take the default val-
ues.

* Normally, charts compute output data in every execution, but when this option is selected, the computed out-
puts override the default values. However, when output is not computed, the default values apply.

Introduction to Stateflow®with Applications 9−5


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

In summary, the earliest time at which an output can be computed in a Mealy machine is t = 0
provided that the Execute (enter) Chart At Initialization field is checked in the Chart dialog
box; otherwise, it is computed at t = 1 . In a Moore machine, the earliest time at which an output
can be computed is at t = 1 if the Execute (enter) Chart At Initialization field is checked in the
Chart dialog box; if not, it is computed at t = 2 .
Mealy and Moore charts offer the following advantages over Classic Stateflow:
1. Stateflow verifies that the Mealy and Moore charts we create will ensure us that they conform
to their formal definitions and semantic rules. Stateflow reports violations at compile time, not
at design time.
2. Moore charts provide a more efficient implementation of Stateflow than Classic charts, both
for C and Hardware Description Language (HDL) targets.

9.4 Creating a Mealy Chart


To create a new Mealy or Moore chart, we follow these steps:
1. We add a new Stateflow block to a Simulink model, then we double−click the block to open
the Stateflow Editor.
2. We right−click in the Stateflow Editor and from the pop−up menu we select Properties.
3. From the Chart dialog box we select Mealy from the State Machine Type field, we click OK,
and the Stateflow chart icon updates to display the selected chart type as shown in Figure 9.5.

Figure 9.5. The Mealy Stateflow Chart

We must ensure that the output is in a Mealy machine is a function of input and state. Accord-
ingly, the selection of a Mealy state machine enforce the following rules:

9−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Mealy Chart

1. Outputs never depend on previous outputs


2. Outputs never depend on the next state

3. Chart wakes up periodically based on a system clock*


4. Chart must compute outputs whenever there is a change on the input port
5. Chart must compute outputs only in transitions, not in states
To conform to the Mealy definition of a state machine, Stateflow must ensure that a Mealy chart
computes outputs every time there is a change on the input port. As a result, Stateflow imposes a
set of design rules for Mealy charts as follows:
1. Compute Outputs in Condition Actions Only
We can compute outputs only in the condition actions of outer and inner transitions. A com-
mon modeling style for Mealy machines is to test inputs in conditions and compute outputs in
the associated action.
2. Do Not Use State Actions or Transition Actions
We cannot use state actions or transition actions in Mealy charts. This restriction enforces
semantics† by preventing us from computing output without considering changes on the input
port, and ensuring that output depends on current state and not next state.
3. Restrict Use of Data

We can define inputs, outputs, local data‡, parameters, and constants in Mealy charts, but we
must restrict Machine−Parented Data to Constants and Parameters** and must not define
data store memory.††

* Stateflow provides one time base for clock and input, as determined by the Simulink solver. The Simulink solver
sets the clock rate to be fast enough to capture input changes. As a result, in Mealy charts, Stateflow commonly
computes outputs and changes states in the same time step.
† Semantics describe how the notation is interpreted and implemented.
‡ Local data are data defined in the current Stateflow chart only.
**Machine−parented data is data that we define for a Stateflow machine, which is the collection of all Stateflow
blocks in a Simulink model. The Stateflow machine is the highest level of the Stateflow hierarchy. When we
define data at this level, every Stateflow chart in the machine can read and modify the data. To ensure that
Mealy charts do not access data that can be modified unpredictably outside the chart, Stateflow only allows us
to define constants and parameters at the machine level. Stateflow parameters have constant value during sim-
ulation and code generation.
†† We cannot define Data Store Memory (DSM) in Mealy charts because DSM objects can be modified by
objects external to the chart. Stateflow uses data store memory to share data with Simulink. DSM acts as global
data that can be modified by other blocks and models in the Simulink hierarchy that contains the chart. Mealy
charts should not access data that can change unpredictably.

Introduction to Stateflow®with Applications 9−7


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

4. Restrict Use of Events

We can use events to trigger the chart and temporal logic to guard transitions* but we cannot
broadcast any type of event or use local or machine−parented events to guard transitions.†
5. Initialize Outputs Every Time Chart Wakes Up
Stateflow automatically applies the initial value of outputs every time a Mealy chart wakes up
to prevent latching of outputs. This is a requirement for Mealy charts to ensure that outputs do
not depend on previous values of outputs. When we create a Mealy chart, Stateflow enforces
the chart property Initialize Outputs Every Time Chart Wakes Up.
6. Calculate Output and State Using One Time Base
Stateflow provides one time base for clock and input, as determined by the Simulink solver.
The Simulink solver sets the clock rate to be fast enough to capture input changes. As a result,
in Mealy charts, Stateflow commonly computes outputs and changes states in the same time
step.

Example 9.3
This is the classical Vending Machine example implemented with a Mealy state machine.

In this example, the vending machine requires 15 cents‡ to release a can of soda. The purchaser
can insert a nickel or a dime, one at a time, to purchase the soda. The chart behaves like a Mealy
machine because its output soda depends on both the input coin and current state.
The Stateflow diagram for this example is shown in Figure 9.3.

* We can use temporal logic in Mealy charts because it behaves synchronously. Think of the change in value of a
temporal logic condition as an event that the chart schedules internally. Therefore, at each time step, the chart
retains its notion of state because it knows how many ticks remain before the temporal event executes. In Mealy
charts, the base event for temporal logic operators must be a predefined event such as tick or wakeup.
† We cannot use local or machine−parented events in Mealy charts because they are not deterministic. These
events can occur while the chart computes outputs and, therefore, violate Mealy semantics which require charts
to compute outputs whenever input changes.
‡ Obviously, we cannot buy a soda today for 15 cents, and to make the example more realistic, we could use a
price like $1.50. But to be consistent with the Stateflow documentation where this example appears, we will stay
with the 15 cents price.

9−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Mealy Chart

Figure 9.6. Flowchart diagram for Example 9.3

The sequence of execution of the Stateflow chart in Figure 9.6 is as follows:


When initial state got_0 is active. No coin has been received or no coins are left.
1. If a nickel is received (coin == 1), output soda remains 0, but state got_nickel becomes active.
2. If a dime is received (coin == 2), output soda remains 0, but state got_dime becomes active.
3. If input coin is not a dime or a nickel, state got_0 stays active and no soda is released (output
soda = 0).
In active state got_nickel. A nickel was received.
1. If another nickel is received (coin == 1), state got_dime becomes active, but no can is released
(soda remains at 0).
2. If a dime is received (coin == 2), a can is released (soda = 1), the coins are banked, and the
active state becomes got_0 because no coins are left.
3. If input coin is not a dime or a nickel, state got_nickel stays active and no can is released (out-
put soda = 0).
In active state got_dime. A dime was received.
1. If a nickel is received (coin == 1), a can is released (soda = 1), the coins are banked, and the
active state becomes got_0 because no coins are left.

Introduction to Stateflow®with Applications 9−9


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

2. If a dime is received (coin == 2), a can is released (soda = 1), 15 cents is banked, and the
active state becomes got_nickel because a nickel (change) is left.
3. If input coin is not a dime or a nickel, state got_dime stays active and no can is released (output
soda = 0).

Example 9.3 of a Mealy vending machine illustrates the following Mealy design rules:
1. The chart computes outputs in condition actions.
2. There are no state actions or transition actions.
3. The chart defines chart inputs (coin) and outputs (soda).
4. The value of the input coin determines the output − whether or not soda is released.

9.5 Creating a Moore Chart


In Moore charts, output is a function of current state only. At every time step, a Moore chart
wakes up, computes its outputs, and then evaluates its inputs to reconfigure itself for the next
time step. Thus, after evaluating its inputs, the Moore chart may take transitions to a new config-
uration of active states, also called next state. However, the Moore chart must always compute its
outputs before changing state.
To ensure that output is a function only of state, Moore state machines enforce the following
rules:
1. Outputs depend only on the current state, not the next state
2. Outputs never depend on previous outputs
3. Chart must compute outputs only in states, not in transitions
4. Chart must compute outputs before updating state
To conform to the Moore definition of a state machine, Stateflow must ensure that every time a
Moore chart wakes up, it computes outputs from the current set of active states without regard to
input. As a result, Stateflow imposes a set of design rules for Moore charts.
1. Compute Outputs in State Actions, Not on Transitions
To ensure that outputs depend solely on current state, we must compute outputs in state
actions, subject to the following restrictions:
a. Combine During and Exit Actions
For Classic charts, Stateflow allows us to define different types of actions in states. Each
action can consist of multiple command statements. However, in Moore charts, Stateflow

9−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Moore Chart

allows only one action per state, but executes the action as both a during and exit action. This
duality ensures that Stateflow never exits a state before computing its outputs because:
I. Stateflow executes the action while the state is active and there are no valid transitions
to take (like a during action)
II. Stateflow also executes the action just before exiting the state to take a valid transition
(like an exit action)
In other words, all active states in Moore charts compute their outputs in a consistent way
whether an outer transition is valid or not.
To implement the duality of execution, the during and exit actions must be identical, as
shown in the example in Figure 9.7.

Moore_State Classic_State
y=x; du: y=x;
func(y); is equivalent to: func(y);
ex: y=x;
func(y);

Figure 9.7. Example where the during and exit actions are identical

Moore states do not differentiate between during and exit actions, as illustrated in the
example in Figure 9.8.

Classic_State
Moore_State
du: y=x;
y=x;
is not equivalent to: ex: func(y);
func(y);

Figure 9.8. Example where Moore states do not differentiate between the during and exit actions

b. Allow Actions in Leaf States Only

In Moore charts, we can add actions only to leaf states.* This restriction ensures that when
we compute outputs in state actions
I. Outputs are not defined at multiple levels in the hierarchy with different values
II. Stateflow can use the same top−down semantics for executing Moore charts as for
Classic charts. In this way Stateflow computes outputs as if it evaluates actions before

* A leaf state is a state that resides at the lowest level of the Stateflow hierarchy and, therefore, does not parent
any other states.

Introduction to Stateflow®with Applications 9−11


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

inner and outer flow graphs and, therefore, guarantees that the outputs will be identical
for both chart types.
We can compute outputs in leaf states that have exclusive (OR) or parallel (AND) decom-
position. However, we should not compute the same outputs in sibling parallel (AND)
states because the values computed by the last state executed will prevail, overwriting the
previously computed values.
c. Do Not Label State Actions
We are not allowed to label state actions in Moore charts with any keywords such as du,
during, ex, or exit. Stateflow executes the state actions in Moore charts as during and exit
actions automatically, as explained earlier. Moore charts never execute entry actions
because these actions always execute as the result of a transition and, therefore, depend on
inputs.
We cannot define actions on transitions because transitions almost always depend on inputs.
For example, if we compute outputs in a condition action on a transition, Stateflow updates
outputs whenever there is a change on the input and this is a violation of Moore rules.
2. Restrict Data to Inputs, Outputs, and Constants
We can define inputs, outputs, parameters, and constants in Moore charts, but other data
restrictions apply:
a. Do Not Define Local Data
We cannot define local data in Moore charts. In Classic Stateflow charts, we can use local
data to transfer inputs to outputs, as in this example:
local_D = input_U;
output_Y = local_D;
However, in Moore charts, we compute outputs from current state only, but never from
local data. When a chart contains local data, Stateflow cannot easily verify that outputs do
not depend on inputs.
b. Restrict Machine−Parented Data to Constants and Parameters
Machine−parented data is data that we define for a Stateflow machine, which is the collec-
tion of Stateflow blocks in a Simulink model. The Stateflow machine is the highest level of
the Stateflow hierarchy. When we define data at this level, every Stateflow chart in the
machine can read and modify the data. To ensure that Moore charts do not access data
that can be modified unpredictably outside the chart, Stateflow only allows us to define
constants and parameters at the machine level. As stated earlier, Stateflow parameters
have constant value during simulation and code generation.

9−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Moore Chart

c. Do Not Define Data Store Memory


We cannot define Data Store Memory (DSM) in Moore charts because DSM objects can
be modified by objects external to the chart. Stateflow uses data store memory to share
data with Simulink. Data store memory acts as global data that can be modified by other
blocks and models in the Simulink hierarchy that contains the chart. Moore charts should
not access data that can change unpredictably.
3. Reference Input Only in Conditions
In Classic Stateflow, we can test inputs in conditions on transitions, and then modify outputs
in associated condition actions and transition actions. However in Moore charts, outputs can
never depend on inputs. Therefore, we can set up conditions on transitions that reference
inputs, but we cannot add actions to transitions that modify outputs based on those condi-
tions. For example, the following transitions are allowed in a Moore chart such as that shown
in Figure 9.9.

Figure 9.9. Legal Moore Chart


In the example in Figure 9.9, each transition tests input u in a condition, but modifies output y
in a state action.
By contrast, the following transitions are illegal in a Moore chart:

Figure 9.10. Illegal Moore Chart


In the example in Figure 9.10, each transition tests input u in a condition, but modifies output
y in a condition action, based on the value of the input. This construct violates Moore seman-
tics and generates a compiler error. Similarly, we cannot use transition actions in Moore
charts.

Introduction to Stateflow®with Applications 9−13


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

4. Do Not Use Actions on Transitions


We are not allowed to define condition actions or transition actions in Moore charts.
5. Do Not Use Graphical Functions
We cannot use graphical functions in Moore charts. This restriction prevents scenarios that
violate Moore rules, such as
a. Adding conditions that call functions which compute outputs as a side effect
b. Adding state actions that call functions which reference inputs
6. Restrict Use of Events

We can use events to trigger the chart and temporal logic to guard transitions* but we cannot
broadcast any type of event or use local or machine−parented events to guard transitions.†
7. Initialize Outputs Every Time Chart Wakes Up
Stateflow automatically applies the initial value of outputs every time a Moore chart wakes up
to prevent latching of outputs. This is a requirement for Moore charts to ensure that outputs
do not depend on previous values of outputs.
When we create a Moore chart, Stateflow automatically enables the chart property Initialize
Outputs Every Time Chart Wakes Up and does not allow us to disable it.

Example 9.4
This is the classical Traffic Light example implemented with a Moore state machine.
To create the traffic light model, we begin by typing sfnew at the MATLAB command prompt,
and we double−click the Stateflow Chart. In the Stateflow Editor window we right−click any-
where inside the chart area, from the pop−up menu we select Properties, and from the Chart dia-
log box we choose Moore. The Stateflow Chart block now appears as shown in Figure 9.11.

* We can use temporal logic in Moore charts because it behaves synchronously. Think of the change in value of a
temporal logic condition as an event that the chart schedules internally. Therefore, at each time step, the chart
retains its notion of state because it knows how many ticks remain before the temporal event executes. In Moore
charts, the base event for temporal logic operators must be a predefined event such as tick or wakeup.
† We cannot use local or machine−parented events in Moore charts because they are not deterministic. These
events can occur while the chart computes outputs and, therefore, violate Moore semantics which require charts
to compute outputs whenever input changes.

9−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Creating a Moore Chart

Figure 9.11. The Moore Stateflow Chart


We return to the Stateflow Editor window, using the State tool we insert five states, and we
interconnect these as shown in Figure 9.12 with the appropriate state transitions.

Figure 9.12. The Moore state machine for the Traffic Light model
In this example, the traffic light model contains a Stateflow Moore chart called Light_Controller,
which operates in five traffic states. Each state represents the color of the traffic light in two
opposite directions − North-South and East-West − and the duration of the current color. The
name of each state represents the operation of the light viewed from the North-South direction.
This chart uses temporal logic to regulate state transitions. The after operator implements a
countdown timer, which Stateflow initializes when the source state is entered. By default, the
timer provides a longer green light in the East-West direction than in the North-South direction
because the volume of traffic is greater on the East-West road. The green light in the East-West
direction stays on for at least 20 clock ticks, but it can remain green as long as no traffic arrives in
the North-South direction. A sensor detects whether cars are waiting at the red light in the
North-South direction. If so, the light turns green in the North-South direction to keep traffic
moving.

Introduction to Stateflow®with Applications 9−15


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

The Light_Controller chart behaves like a Moore machine because it updates its outputs based on
current state before transitioning to a new state, as follows:
When initial state Stop is active. Traffic light is red for North-South, green for East-West.
1. Sets output y1 = RED (North-South) based on current state
2. Sets output y2 = GREEN (East-West) based on current state
3. After 20 clock ticks, active state becomes StopForTraffic
In active state StopForTraffic. Traffic light has been red for North-South, green for East-West
for at least 20 clock ticks.
1. Sets output y1 = RED (North-South) based on current state
2. Sets output y2 = GREEN (East-West) based on current state
3. Checks sensor sens
4. If sensor indicates cars are waiting ([sens] is true) in the North-South direction, active state
becomes StopToGo
In active state StopToGo. Traffic light must reverse traffic flow in response to sens.
1. Sets output y1 = RED (North-South) based on current state
2. Sets output y2 = YELLOW (East-West) based on current state
3. After 3 clock ticks, active state becomes Go.
In active state Go. Traffic light has been red for North-South, yellow for East-West for 3 clock
ticks.
1. Sets output y1 = GREEN (North-South) based on current state
2. Sets output y2 = RED (East-West) based on current state
3. After 10 clock ticks, active state becomes GoToStop
In active state GoToStop. Traffic light has been green for North-South, red for East-West for 10
clock ticks.
1. Sets output y1 = YELLOW (North-South) based on current state
2. Sets output y2 = RED (East-West) based on current state
3. After 3 clock ticks, active state becomes Stop
Design Rules in Moore Traffic Light
This example of a Moore traffic light illustrates the following Moore design rules:
1. The chart computes outputs in state actions.

9−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Changing Chart Type

2. Actions appear in leaf states only.


3. Leaf states contain no more than one action.
4. The chart tests inputs in conditions on transitions
5. The chart uses temporal logic, but no asynchronous events
6. The chart defines chart inputs (sens) and outputs (y1and y2)

9.6 Changing Chart Type

The best practice is not to change from one Stateflow chart type to another in the middle of
development. Stateflow does not automatically convert the semantics of the original chart to con-
form to the design rules of the new chart type. Changing type usually requires us to redesign our
chart to achieve equivalent behavior, that is, where both charts produce the same sequence of out-
puts given the identical sequence of inputs. To assist us, Stateflow provides informative diagnos-
tic messages at compile time. In some cases, however, there may be no way to translate specific
behaviors without violating chart definitions.
Here is a summary of how Stateflow responds when we change chart types mid−design:

From To Result
Mealy Classic Mealy charts retain their semantics when changed to Classic type.
Classic Mealy If the Classic chart confirms to Mealy semantic rules, the Mealy chart exhibits
equivalent behavior, provided that output is defined at every time step.
Moore Classic Stateflow interprets the state actions in the Moore chart as entry actions
because they are not labeled. Therefore, the Classic chart will not exhibit
behavior that is equivalent to the original Moore chart. Requires redesign.
Classic Moore Stateflow interprets actions that are unlabeled in the Classic chart (entry
actions by default) as during and exit actions. Therefore, the Moore chart will
not exhibit behavior that is equivalent to the original Classic chart. Requires
redesign.
Mealy Moore Converting between these two types does not produce equivalent behavior
Moore Mealy because Mealy and Moore rules about placement of actions are mutually exclu-
sive. Requires redesign.

9.7 Debugging Mealy and Moore Charts


Stateflow verifies the semantics of Mealy and Moore charts at compile time and provides infor-
mative diagnostic messages to help us
1. Design Mealy and Moore charts from scratch

Introduction to Stateflow®with Applications 9−17


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

2. Redesign legacy Classic charts to conform to Mealy and Moore semantics


3. Redesign charts to convert between Mealy and Moore types
For example, recall the Mealy vending machine chart repeated below for convenience in Figure
9.13.

Figure 9.13. Mealy diagram for vending machine example

If we change the chart type to Moore and rebuild, Stateflow provides diagnostics to alert us to the
fact that we cannot define actions on transitions. Without actions, we cannot compute outputs
on transitions in Moore charts. According to Moore semantics, we must instead compute outputs
in state actions.
In the Mealy chart, each condition action computes output (whether or not soda is released) based
on input (the coin received). Each state represents one of the three possible coin inputs: nickel,
dime, or no coin. Stateflow computes the output as the Mealy chart transitions to the next state.
When we move this logic out of transitions and into state actions in the Moore chart, we need
more states. The reason is that in the Moore chart, each state must represent not only coins
received, but also the soda release condition. In the Moore chart, Stateflow must compute output
according to the active state before considering input. As a result, there will be a delay in releasing
soda, even if the machine receives enough money to cover the cost.
The vending machine, designed as a Moore chart is shown in Figure 9.14.

9−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Debugging Mealy and Moore Charts

Figure 9.14. Moore diagram for vending machine example

The following table compares the Mealy and Moore vending machine Stateflow diagrams in Fig-
ures 9.13 and 9.14.

Mealy Vending Machine Moore Vending Machine


Uses 3 states Uses 5 states
Computes outputs in condition actions Computes outputs in state actions
Updates output based on input Updates output before evaluating input, requir-
ing an extra time step to produce the soda

For this vending machine, Mealy is a better modeling paradigm because there is no delay in
releasing soda once sufficient coins are received. By contrast, the Moore vending machine
requires an extra time step to pass before producing soda. Since the Moore vending machine
accepts a nickel, a dime, or no coin in a given time step, it is possible that the soda will be pro-
duced in a time step in which a coin is accepted toward the next purchase. In this situation, the
delivery of a soda may appear to be in response to this coin, but actually occurs because the
vending machine received the purchase price in previous time steps.

Introduction to Stateflow®with Applications 9−19


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

9.8 Summary
• A Mealy machine is a finite state machine that generates an output based on its current state
and an input. This means that the state diagram will include both an input and output signal
for each transition edge.
• A Moore machine is a finite state machine whose output depends only on the machine's cur-
rent state.
• A Mealy machine has fewer states and reacts faster to inputs, but input changes can cause
fast changes in output and this can cause problems when two or more machines are intercon-
nected.
• A Moore machine is generally safer to use since outputs change at clock edge always one
cycle later but requires more states than an equivalent Mealy machine.
• In Stateflow we can choose Classic, Mealy, or Moore machine.
• In Stateflow, to ascertain that the output of Mealy and Moore machines is well defined at
every time step, we place a check mark in the Initialize Outputs Every Time Chart Wakes
Up field in the Chart dialog box.
• Moore states do not differentiate between during and exit actions
• It is not recommended to change from one Stateflow chart type to another in the middle of
development because Stateflow does not automatically convert the semantics of the original
chart to conform to the design rules of the new chart type.

9−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Exercises for the Reader

9.9 Exercises for the Reader


1. Describe the operation of the Mealy machine shown below.

00

11 10

2. In the Moore machine shown below, the input z goes high (from 0 to 1 ) before the first pos-
itive edge of the clock pulse, and follows the sequence 1 1 0 1 1 0 . Draw a timing diagram to
show the sequence of operation of this machine.

00 ⁄ 01

01 ⁄ 11
10 ⁄ 11

Introduction to Stateflow®with Applications 9−21


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

9.10 Solution to the End−of−Chapter Exercises


1.

00

(e) (a)
(f)

11 10
(b)
(d)
(c)

Transition (a) says that if the input x is 1 we will transition from state 00 to state 10 and the
output y will be 1 .
The loop in state 10 says that if the input x is 1 we will loop back to state 10 and the output
y will be 0 . This cannot occur in a Moore machine because its output depends on its state
only and not on its input.
Transition (c) says that if the input x is 0 we will transition from state 10 to state 11 and the
output y will be 1 .
Transition (d) says that if the input x is 0 we will transition from state 11 to state 10 and the
output y will be 0 .
Transition (e) says that if the input x is 1 we will transition from state 11 to state 00 and the
output y will be 1 .
Transition (f) says that if the input x is 0 we will transition from state 11 to state 10 and the
output y will be 1 .

9−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Solution to the End−of−Chapter Exercises

2.

00 ⁄ 01

01 ⁄ 11
10 ⁄ 11

We are told that the input z goes high (from 0 to 1 ) before the first positive edge of the clock
pulse, and follows the sequence 1 1 0 1 1 0 . Then, the input z in relation to the clock pulse is
as shown below.
t0 t1 t2 t3 t4 t5

CP

1 1 0 1 1 0
z

The sequence of transitions are as follows:


a. Before the occurrence of the positive edge of t 0 , Q 1 Q 0 = 00 and y 1 y 0 = 01 or 00 ⁄ 01 as
we can see from the state diagram.
b. After the occurrence of the positive edge of t 1 , z = 1 still, and thus we transition to
Q 1 Q 0 = 01 and y 1 y 0 = 11 or 01 ⁄ 11 .

c. Before the occurrence of the positive edge of t 2 , z = 0 and as we can see from the state
diagram, we loop back to Q 1 Q 0 = 01 and y 1 y 0 = 11 or 01 ⁄ 11 .

d. After the occurrence of the positive edge of t 3 , z = 1 again, and thus we transition to
Q 1 Q 0 = 10 and y 1 y 0 = 11 or 10 ⁄ 11 .

e. After the occurrence of the positive edge of t 4 , z = 1 still, and thus we transition to
Q 1 Q 0 = 00 and y 1 y 0 = 01 or 00 ⁄ 01 .

f. After the occurrence of the positive edge of t 5 , z = 0 , and thus we transition to


Q 1 Q 0 = 10 and y 1 y 0 = 11 or 10 ⁄ 11 .

Introduction to Stateflow®with Applications 9−23


Copyright © Orchard Publications
Chapter 9 Mealy and Moore Charts in Stateflow

The complete timing diagram is shown below. We must remember that while the input signal z
tells the synchronous machine what to do, the clock pulse CP tells it when to do it.
t0 t1 t2 t3 t4 t5

CP

Q1

Q0

y1

y0

9−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Appendix A
Introduction to MATLAB®

T
his appendix serves as an introduction to the basic MATLAB commands and functions,
procedures for naming and saving the user generated files, comment lines, access to MAT-
LAB’s Editor / Debugger, finding the roots of a polynomial, and making plots. Several exam-
ples are provided with detailed explanations.

A.1 MATLAB® and Simulink®


MATLAB and Simulink are products of The MathWorks,™ Inc. These are two outstanding soft-
ware packages for scientific and engineering computations and are used in educational institu-
tions and in industries including automotive, aerospace, electronics, telecommunications, and
environmental applications. MATLAB enables us to solve many advanced numerical problems
rapidly and efficiently.

A.2 Command Window


To distinguish the screen displays from the user commands, important terms, and MATLAB
functions, we will use the following conventions:
Click: Click the left button of the mouse
Courier Font: Screen displays
Helvetica Font: User inputs at MATLAB’s command window prompt >> or EDU>>*
Helvetica Bold: MATLAB functions
Times Bold Italic: Important terms and facts, notes and file names
When we first start MATLAB, we see various help topics and other information. Initially, we are
interested in the command screen which can be selected from the Window drop menu. When the
command screen, we see the prompt >> or EDU>>. This prompt is displayed also after execution
of a command; MATLAB now waits for a new command from the user. It is highly recommended
that we use the Editor/Debugger to write our program, save it, and return to the command screen
to execute the program as explained below.
To use the Editor/Debugger:
1. From the File menu on the toolbar, we choose New and click on M−File. This takes us to the
Editor Window where we can type our script (list of statements) for a new file, or open a previ-

* EDU>> is the MATLAB prompt in the Student Version

Introduction to Stateflow®with Applications A−1


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

ously saved file. We must save our program with a file name which starts with a letter. Impor-
tant! MATLAB is case sensitive, that is, it distinguishes between upper− and lower−case let-
ters. Thus, t and T are two different letters in MATLAB language. The files that we create are
saved with the file name we use and the extension .m; for example, myfile01.m. It is a good
practice to save the script in a file name that is descriptive of our script content. For instance,
if the script performs some matrix operations, we ought to name and save that file as
matrices01.m or any other similar name. We should also use a floppy disk or an external drive
to backup our files.
2. Once the script is written and saved as an m−file, we may exit the Editor/Debugger window by
clicking on Exit Editor/Debugger of the File menu. MATLAB then returns to the command
window.
3. To execute a program, we type the file name without the .m extension at the >> prompt;
then, we press <enter> and observe the execution and the values obtained from it. If we have
saved our file in drive a or any other drive, we must make sure that it is added it to the desired
directory in MATLAB’s search path. The MATLAB User’s Guide provides more information
on this topic.
Henceforth, it will be understood that each input command is typed after the >> prompt and fol-
lowed by the <enter> key.
The command help matlab\iofun will display input/output information. To get help with other
MATLAB topics, we can type help followed by any topic from the displayed menu. For example,
to get information on graphics, we type help matlab\graphics. The MATLAB User’s Guide con-
tains numerous help topics.
To appreciate MATLAB’s capabilities, we type demo and we see the MATLAB Demos menu.
We can do this periodically to become familiar with them. Whenever we want to return to the
command window, we click on the Close button.
When we are done and want to leave MATLAB, we type quit or exit. But if we want to clear all
previous values, variables, and equations without exiting, we should use the command clear. This
command erases everything; it is like exiting MATLAB and starting it again. The command clc
clears the screen but MATLAB still remembers all values, variables and equations that we have
already used. In other words, if we want to clear all previously entered commands, leaving only
the >> prompt on the upper left of the screen, we use the clc command.
All text after the % (percent) symbol is interpreted as a comment line by MATLAB, and thus it is
ignored during the execution of a program. A comment can be typed on the same line as the func-
tion or command or as a separate line. For instance,
conv(p,q) % performs multiplication of polynomials p and q
% The next statement performs partial fraction expansion of p(x) / q(x)

A−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Roots of Polynomials

are both correct.


One of the most powerful features of MATLAB is the ability to do computations involving com-
plex numbers. We can use either i , or j to denote the imaginary part of a complex number, such as
3-4i or 3-4j. For example, the statement
z=3−4j
displays
z = 3.0000−4.0000i
In the above example, a multiplication (*) sign between 4 and j was not necessary because the
complex number consists of numerical constants. However, if the imaginary part is a function, or
variable such as cos ( x ) , we must use the multiplication sign, that is, we must type cos(x)*j or
j*cos(x) for the imaginary part of the complex number.

A.3 Roots of Polynomials


In MATLAB, a polynomial is expressed as a row vector of the form [ a n a n – 1 … a 2 a 1 a0 ] . These
are the coefficients of the polynomial in descending order. We must include terms whose coeffi-
cients are zero.
We find the roots of any polynomial with the roots(p) function; p is a row vector containing the
polynomial coefficients in descending order.

Example A.1
Find the roots of the polynomial
4 3 2
p 1 ( x ) = x – 10x + 35x – 50x + 24
Solution:
The roots are found with the following two statements where we have denoted the polynomial as
p1, and the roots as roots_ p1.
p1=[1 −10 35 −50 24] % Specify and display the coefficients of p1(x)
p1 =
1 -10 35 -50 24
roots_ p1=roots(p1) % Find the roots of p1(x)
roots_p1 =
4.0000
3.0000
2.0000

Introduction to Stateflow®with Applications A−3


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

1.0000
We observe that MATLAB displays the polynomial coefficients as a row vector, and the roots as a
column vector.

Example A.2
Find the roots of the polynomial
5 4 2
p 2 ( x ) = x – 7x + 16x + 25x + 52

Solution:
There is no cube term; therefore, we must enter zero as its coefficient. The roots are found with
the statements below, where we have defined the polynomial as p2, and the roots of this polyno-
mial as roots_ p2. The result indicates that this polynomial has three real roots, and two complex
roots. Of course, complex roots always occur in complex conjugate* pairs.
p2=[1 −7 0 16 25 52]
p2 =
1 -7 0 16 25 52
roots_ p2=roots(p2)
roots_p2 =
6.5014
2.7428
-1.5711
-0.3366 + 1.3202i
-0.3366 - 1.3202i

A.4 Polynomial Construction from Known Roots


We can compute the coefficients of a polynomial, from a given set of roots, with the poly(r) func-
tion where r is a row vector containing the roots.

Example A.3
It is known that the roots of a polynomial are 1, 2, 3, and 4 . Compute the coefficients of this
polynomial.

* By definition, the conjugate of a complex number A = a + jb is A∗ = a – jb

A−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Polynomial Construction from Known Roots

Solution:
We first define a row vector, say r3 , with the given roots as elements of this vector; then, we find
the coefficients with the poly(r) function as shown below.
r3=[1 2 3 4] % Specify the roots of the polynomial
r3 =
1 2 3 4
poly_r3=poly(r3) % Find the polynomial coefficients
poly_r3 =
1 -10 35 -50 24
We observe that these are the coefficients of the polynomial p 1 ( x ) of Example A.1.

Example A.4
It is known that the roots of a polynomial are – 1, – 2, – 3, 4 + j5, and 4 – j5 . Find the coeffi-
cients of this polynomial.
Solution:
We form a row vector, say r4 , with the given roots, and we find the polynomial coefficients with
the poly(r) function as shown below.
r4=[ −1 −2 −3 4+5j 4−5j ]
r4 =
Columns 1 through 4
-1.0000 -2.0000 -3.0000 -4.0000+ 5.0000i
Column 5
-4.0000- 5.0000i
poly_r4=poly(r4)
poly_r4 =
1 14 100 340 499 246
Therefore, the polynomial is
5 4 3 2
p 4 ( x ) = x + 14x + 100x + 340x + 499x + 246

Introduction to Stateflow®with Applications A−5


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

A.5 Evaluation of a Polynomial at Specified Values


The polyval(p,x) function evaluates a polynomial p ( x ) at some specified value of the indepen-
dent variable x .

Example A.5
Evaluate the polynomial
6 5 3 2
p 5 ( x ) = x – 3x + 5x – 4x + 3x + 2 (A.1)
at x = – 3 .
Solution:
p5=[1 −3 0 5 −4 3 2]; % These are the coefficients of the given polynomial
% The semicolon (;) after the right bracket suppresses the
% display of the row vector that contains the coefficients of p5.
%
val_minus3=polyval(p5, −3) % Evaluate p5 at x=−3; no semicolon is used here
% because we want the answer to be displayed
val_minus3 =
1280

Other MATLAB functions used with polynomials are the following:


conv(a,b) − multiplies two polynomials a and b
[q,r]=deconv(c,d) − divides polynomial c by polynomial d and displays the quotient q and
remainder r.
polyder(p) − produces the coefficients of the derivative of a polynomial p.

Example A.6
Let
5 4 2
p 1 = x – 3x + 5x + 7x + 9
and
6 4 2
p 2 = 2x – 8x + 4x + 10x + 12

Compute the product p 1 ⋅ p 2 using the conv(a,b) function.

A−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Evaluation of a Polynomial at Specified Values

Solution:
p1=[1 −3 0 5 7 9]; % The coefficients of p1
p2=[2 0 −8 0 4 10 12]; % The coefficients of p2
p1p2=conv(p1,p2) % Multiply p1 by p2 to compute coefficients of the product p1p2
p1p2 =
2 -6 -8 34 18 -24 -74 -88 78 166 174 108
Therefore,
11 10 9 8 7 6
p 1 ⋅ p 2 = 2x – 6x – 8x + 34x + 18x – 24x
5 4 3 2
– 74x – 88x + 78x + 166x + 174x + 108

Example A.7
Let
7 5 3
p 3 = x – 3x + 5x + 7x + 9
and
6 5 2
p 4 = 2x – 8x + 4x + 10x + 12

Compute the quotient p 3 ⁄ p 4 using the [q,r]=deconv(c,d) function.


Solution:
% It is permissible to write two or more statements in one line separated by semicolons
p3=[1 0 −3 0 5 7 9]; p4=[2 −8 0 0 4 10 12]; [q,r]=deconv(p3,p4)
q =
0.5000
r =
0 4 -3 0 3 2 3
Therefore,
5 4 2
q = 0.5 r = 4x – 3x + 3x + 2x + 3

Example A.8
Let
6 4 2
p 5 = 2x – 8x + 4x + 10x + 12

d
Compute the derivative ------ p 5 using the polyder(p) function.
dx

Introduction to Stateflow®with Applications A−7


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

Solution:
p5=[2 0 −8 0 4 10 12]; % The coefficients of p5
der_p5=polyder(p5) % Compute the coefficients of the derivative of p5
der_p5 =
12 0 -32 0 8 10
Therefore,
d
------ p 5 = 12x 5 – 32x 3 + 4x 2 + 8x + 10
dx

A.6 Rational Polynomials


Rational Polynomials are those which can be expressed in ratio form, that is, as
n n–1 n–2
bn x + bn – 1 x + bn – 2 x + … + b1 x + b0
( x ) = -----------------------------------------------------------------------------------------------------------------------
R ( x ) = Num
-------------------- - (A.2)
Den ( x ) m
am x + am – 1 x
m–1
+ am – 2 x
m–2
+ … + a1 x + a0

where some of the terms in the numerator and/or denominator may be zero. We can find the roots
of the numerator and denominator with the roots(p) function as before.
As noted in the comment line of Example A.7, we can write MATLAB statements in one line, if
we separate them by commas or semicolons. Commas will display the results whereas semicolons
will suppress the display.

Example A.9
Let
p num 5 4 2
R ( x ) = ----------- x – 3x + 5x + 7x + 9-
- = --------------------------------------------------------
p den 6 4
x – 4x + 2x + 5x + 6
2

Express the numerator and denominator in factored form, using the roots(p) function.
Solution:
num=[1 −3 0 5 7 9]; den=[1 0 −4 0 2 5 6]; % Do not display num and den coefficients
roots_num=roots(num), roots_den=roots(den) % Display num and den roots
roots_num =
2.4186 + 1.0712i 2.4186 - 1.0712i -1.1633
-0.3370 + 0.9961i -0.3370 - 0.9961i

A−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Rational Polynomials

roots_den =
1.6760 + 0.4922i 1.6760 - 0.4922i -1.9304
-0.2108 + 0.9870i -0.2108 - 0.9870i -1.0000
As expected, the complex roots occur in complex conjugate pairs.
For the numerator, we have the factored form
p num = ( x – 2.4186 – j1.0712 ) ( x – 2.4186 + j1.0712 ) ( x + 1.1633 )
( x + 0.3370 – j0.9961 ) ( x + 0.3370 + j0.9961 )
and for the denominator, we have
p den = ( x – 1.6760 – j0.4922 ) ( x – 1.6760 + j0.4922 ) ( x + 1.9304 )
( x + 0.2108 – j 0.9870 ) ( x + 0.2108 + j0.9870 ) ( x + 1.0000 )
We can also express the numerator and denominator of this rational function as a combination of
linear and quadratic factors. We recall that, in a quadratic equation of the form x 2 + bx + c = 0
whose roots are x 1 and x 2 , the negative sum of the roots is equal to the coefficient b of the x
term, that is, – ( x 1 + x 2 ) = b , while the product of the roots is equal to the constant term c , that
is, x 1 ⋅ x 2 = c . Accordingly, we form the coefficient b by addition of the complex conjugate roots
and this is done by inspection; then we multiply the complex conjugate roots to obtain the con-
stant term c using MATLAB as follows:
(2.4186 + 1.0712i)*(2.4186 −1.0712i)
ans = 6.9971
(−0.3370+ 0.9961i)*(−0.3370−0.9961i)
ans = 1.1058
(1.6760+ 0.4922i)*(1.6760−0.4922i)
ans = 3.0512
(−0.2108+ 0.9870i)*(−0.2108−0.9870i)
ans = 1.0186
Thus,
p num 2
( x – 4.8372x + 6.9971 ) ( x + 0.6740x + 1.1058 ) ( x + 1.1633 )
2
R ( x ) = -----------
- = -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-
p den 2 2
( x – 3.3520x + 3.0512 ) ( x + 0.4216x + 1.0186 ) ( x + 1.0000 ) ( x + 1.9304 )

Introduction to Stateflow®with Applications A−9


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

We can check this result of Example A.9 above with MATLAB’s Symbolic Math Toolbox which is
a collection of tools (functions) used in solving symbolic expressions. They are discussed in detail
in MATLAB’s Users Manual. For the present, our interest is in using the collect(s) function that
is used to multiply two or more symbolic expressions to obtain the result in polynomial form. We
must remember that the conv(p,q) function is used with numeric expressions only, that is, poly-
nomial coefficients.
Before using a symbolic expression, we must create one or more symbolic variables such as x, y, t,
and so on. For our example, we use the following script:
syms x % Define a symbolic variable and use collect(s) to express numerator in polynomial form
collect((x^2−4.8372*x+6.9971)*(x^2+0.6740*x+1.1058)*(x+1.1633))
ans =
x^5-29999/10000*x^4-1323/3125000*x^3+7813277909/
1562500000*x^2+1750276323053/250000000000*x+4500454743147/
500000000000
and if we simplify this, we find that is the same as the numerator of the given rational expression
in polynomial form. We can use the same procedure to verify the denominator.

A.7 Using MATLAB to Make Plots


Quite often, we want to plot a set of ordered pairs. This is a very easy task with the MATLAB
plot(x,y) command that plots y versus x, where x is the horizontal axis (abscissa) and y is the ver-
tical axis (ordinate).

Example A.10
Consider the electric circuit of Figure A.1, where the radian frequency ω (radians/second) of the
applied voltage was varied from 300 to 3000 in steps of 100 radians/second, while the amplitude
was held constant.
R1
A

R2
C
V L

Figure A.1. Electric circuit for Example A.10

A−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Using MATLAB to Make Plots

The ammeter readings were then recorded for each frequency. The magnitude of the impedance
|Z| was computed as Z = V ⁄ A and the data were tabulated on Table A.1.

TABLE A.1 Table for Example A.10

ω (rads/s) |Z| Ohms ω (rads/s) |Z| Ohms


300 39.339 1700 90.603
400 52.589 1800 81.088
500 71.184 1900 73.588
600 97.665 2000 67.513
700 140.437 2100 62.481
800 222.182 2200 58.240
900 436.056 2300 54.611
1000 1014.938 2400 51.428
1100 469.83 2500 48.717
1200 266.032 2600 46.286
1300 187.052 2700 44.122
1400 145.751 2800 42.182
1500 120.353 2900 40.432
1600 103.111 3000 38.845
Plot the magnitude of the impedance, that is, |Z| versus radian frequency ω .
Solution:
We cannot type ω (omega) in the MATLAB Command prompt, so we will use the English letter
w instead.
If a statement, or a row vector is too long to fit in one line, it can be continued to the next line by
typing three or more periods, then pressing <enter> to start a new line, and continue to enter
data. This is illustrated below for the data of w and z. Also, as mentioned before, we use the semi-
colon (;) to suppress the display of numbers that we do not care to see on the screen.
The data are entered as follows:
w=[300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1900....
2000 2100 2200 2300 2400 2500 2600 2700 2800 2900 3000];
%
z=[39.339 52.789 71.104 97.665 140.437 222.182 436.056....
1014.938 469.830 266.032 187.052 145.751 120.353 103.111....
90.603 81.088 73.588 67.513 62.481 58.240 54.611 51.468....
48.717 46.286 44.122 42.182 40.432 38.845];
Of course, if we want to see the values of w or z or both, we simply type w or z, and we press

Introduction to Stateflow®with Applications A−11


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

<enter>. To plot z (y−axis) versus w (x−axis), we use the plot(x,y) command. For this example,
we use plot(w,z). When this command is executed, MATLAB displays the plot on MATLAB’s
graph screen and MATLAB denotes this plot as Figure 1. This plot is shown in Figure A.2.

1200

1000

800

600

400

200

0
0 500 1000 1500 2000 2500 3000

Figure A.2. Plot of impedance z versus frequency ω for Example A.10

This plot is referred to as the magnitude frequency response of the circuit.


To return to the command window, we press any key, or from the Window pull−down menu, we
select MATLAB Command Window. To see the graph again, we click on the Window pull−down
menu, and we choose Figure 1.
We can make the above, or any plot, more presentable with the following commands:
grid on: This command adds grid lines to the plot. The grid off command removes the grid. The
command grid toggles them, that is, changes from off to on or vice versa. The default* is off.
box off: This command removes the box (the solid lines which enclose the plot), and box on
restores the box. The command box toggles them. The default is on.
title(‘string’): This command adds a line of the text string (label) at the top of the plot.
xlabel(‘string’) and ylabel(‘string’) are used to label the x− and y−axis respectively.
The magnitude frequency response is usually represented with the x−axis in a logarithmic scale.
We can use the semilogx(x,y) command which is similar to the plot(x,y) command, except that
the x−axis is represented as a log scale, and the y−axis as a linear scale. Likewise, the semil-
ogy(x,y) command is similar to the plot(x,y) command, except that the y−axis is represented as a

* A default is a particular value for a variable that is assigned automatically by an operating system and remains
in effect unless canceled or overridden by the operator.

A−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Using MATLAB to Make Plots

log scale, and the x−axis as a linear scale. The loglog(x,y) command uses logarithmic scales for
both axes.
Throughout this text it will be understood that log is the common (base 10) logarithm, and ln is
the natural (base e) logarithm. We must remember, however, the function log(x) in MATLAB is
the natural logarithm, whereas the common logarithm is expressed as log10(x), and the logarithm
to the base 2 as log2(x).
Let us now redraw the plot with the above options by adding the following statements:
semilogx(w,z); grid; % Replaces the plot(w,z) command
title('Magnitude of Impedance vs. Radian Frequency');
xlabel('w in rads/sec'); ylabel('|Z| in Ohms')
After execution of these commands, the plot is as shown in Figure A.3.
If the y−axis represents power, voltage or current, the x−axis of the frequency response is more
often shown in a logarithmic scale, and the y−axis in dB (decibels).
Magnitude of Impedance vs. Radian Frequency
1200

1000

800
|Z| in Ohms

600

400

200

0
2 3 4
10 10 10
w in rads/sec

Figure A.3. Modified frequency response plot of Figure A.2.

To display the voltage v in a dB scale on the y−axis, we add the relation dB=20*log10(v), and we
replace the semilogx(w,z) command with semilogx(w,dB).

The command gtext(‘string’)* switches to the current Figure Window, and displays a cross−hair
that can be moved around with the mouse. For instance, we can use the command gtext(‘Imped-
ance |Z| versus Frequency’), and this will place a cross−hair in the Figure window. Then, using

* With the latest MATLAB Versions 6 and 7 (Student Editions 13 and 14), we can add text, lines and arrows directly into
the graph using the tools provided on the Figure Window. For advanced MATLAB graphics, please refer to The Math-
Works Using MATLAB Graphics documentation.

Introduction to Stateflow®with Applications A−13


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

the mouse, we can move the cross−hair to the position where we want our label to begin, and we
press <enter>.
The command text(x,y,’string’) is similar to gtext(‘string’). It places a label on a plot in some
specific location specified by x and y, and string is the label which we want to place at that loca-
tion. We will illustrate its use with the following example which plots a 3−phase sinusoidal wave-
form.
The first line of the script below has the form
linspace(first_value, last_value, number_of_values)
This function specifies the number of data points but not the increments between data points. An
alternate function is
x=first: increment: last
and this specifies the increments between points but not the number of data points.
The script for the 3−phase plot is as follows:
x=linspace(0, 2*pi, 60); % pi is a built−in function in MATLAB;
% we could have used x=0:0.02*pi:2*pi or x = (0: 0.02: 2)*pi instead;
y=sin(x); u=sin(x+2*pi/3); v=sin(x+4*pi/3);
plot(x,y,x,u,x,v); % The x−axis must be specified for each function
grid on, box on, % turn grid and axes box on
text(0.75, 0.65, 'sin(x)'); text(2.85, 0.65, 'sin(x+2*pi/3)'); text(4.95, 0.65, 'sin(x+4*pi/3)')
These three waveforms are shown on the same plot of Figure A.4.
1

sin(x) sin(x+2*pi/3) sin(x+4*pi/3)


0.5

-0.5

-1
0 1 2 3 4 5 6 7

Figure A.4. Three−phase waveforms

A−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Using MATLAB to Make Plots

In our previous examples, we did not specify line styles, markers, and colors for our plots. How-
ever, MATLAB allows us to specify various line types, plot symbols, and colors. These, or a com-
bination of these, can be added with the plot(x,y,s) command, where s is a character string con-
taining one or more characters shown on the three columns of Table A.2. MATLAB has no
default color; it starts with blue and cycles through the first seven colors listed in Table A.2 for
each additional line in the plot. Also, there is no default marker; no markers are drawn unless
they are selected. The default line is the solid line. But with the latest MATLAB versions, we can
select the line color, line width, and other options directly from the Figure Window.

TABLE A.2 Styles, colors, and markets used in MATLAB

Symbol Color Symbol Marker Symbol Line Style


b blue . point − solid line
g green o circle : dotted line
r red x x−mark −. dash−dot line
c cyan + plus −− dashed line
m magenta * star
y yellow s square
k black d diamond
w white ∨ triangle down
∧ triangle up
< triangle left
> triangle right
p pentagram
h hexagram

For example, plot(x,y,'m*:') plots a magenta dotted line with a star at each data point, and
plot(x,y,'rs') plots a red square at each data point, but does not draw any line because no line was
selected. If we want to connect the data points with a solid line, we must type plot(x,y,'rs−'). For
additional information we can type help plot in MATLAB’s command screen.
The plots we have discussed thus far are two−dimensional, that is, they are drawn on two axes.
MATLAB has also a three−dimensional (three−axes) capability and this is discussed next.
The plot3(x,y,z) command plots a line in 3−space through the points whose coordinates are the
elements of x, y and z, where x, y and z are three vectors of the same length.
The general format is plot3(x1,y1,z1,s1,x2,y2,z2,s2,x3,y3,z3,s3,...) where xn, yn and zn are vectors
or matrices, and sn are strings specifying color, marker symbol, or line style. These strings are the
same as those of the two−dimensional plots.

Introduction to Stateflow®with Applications A−15


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

Example A.11
Plot the function
3 2
z = – 2x + x + 3y – 1 (A.3)
Solution:
We arbitrarily choose the interval (length) shown on the script below.
x= −10: 0.5: 10; % Length of vector x
y= x; % Length of vector y must be same as x
z= −2.*x.^3+x+3.*y.^2−1; % Vector z is function of both x and y*
plot3(x,y,z); grid
The three−dimensional plot is shown in Figure A.5.

3000

2000

1000

-1000

-2000
10
5 10
0 5
0
-5 -5
-10 -10

Figure A.5. Three dimensional plot for Example A.11

In a two−dimensional plot, we can set the limits of the x− and y−axes with the axis([xmin xmax
ymin ymax]) command. Likewise, in a three−dimensional plot we can set the limits of all three
axes with the axis([xmin xmax ymin ymax zmin zmax]) command. It must be placed after the
plot(x,y) or plot3(x,y,z) commands, or on the same line without first executing the plot com-
mand. This must be done for each plot. The three−dimensional text(x,y,z,’string’) command will
place string beginning at the co−ordinate (x,y,z) on the plot.
For three−dimensional plots, grid on and box off are the default states.

* This statement uses the so called dot multiplication, dot division, and dot exponentiation where the multiplication, division,
and exponential operators are preceded by a dot. These important operations will be explained in Section A.9.

A−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Using MATLAB to Make Plots

We can also use the mesh(x,y,z) command with two vector arguments. These must be defined as
length ( x ) = n and length ( y ) = m where [ m, n ] = size ( Z ) . In this case, the vertices of the mesh
lines are the triples { x ( j ), y ( i ), Z ( i, j ) } . We observe that x corresponds to the columns of Z, and y
corresponds to the rows.
To produce a mesh plot of a function of two variables, say z = f ( x, y ) , we must first generate the
X and Y matrices that consist of repeated rows and columns over the range of the variables x and
y. We can generate the matrices X and Y with the [X,Y]=meshgrid(x,y) function that creates the
matrix X whose rows are copies of the vector x, and the matrix Y whose columns are copies of the
vector y.

Example A.12
The volume V of a right circular cone of radius r and height h is given by
1 2
V = --- πr h (A.4)
3

Plot the volume of the cone as r and h vary on the intervals 0 ≤ r ≤ 4 and 0 ≤ h ≤ 6 meters.
Solution:
The volume of the cone is a function of both the radius r and the height h, that is,
V = f ( r, h )
The three−dimensional plot is created with the following MATLAB script where, as in the previ-
ous example, in the second line we have used the dot multiplication, dot division, and dot expo-
nentiation. This will be explained in Section A.9.
[R,H]=meshgrid(0: 4, 0: 6); % Creates R and H matrices from vectors r and h;...
V=(pi .* R .^ 2 .* H) ./ 3; mesh(R, H, V);...
xlabel('x−axis, radius r (meters)'); ylabel('y−axis, altitude h (meters)');...
zlabel('z−axis, volume (cubic meters)'); title('Volume of Right Circular Cone'); box on
The three−dimensional plot of Figure A.6 shows how the volume of the cone increases as the
radius and height are increased.
The plots of Figure A.5 and A.6 are rudimentary; MATLAB can generate very sophisticated
three−dimensional plots. The MATLAB User’s Manual and the Using MATLAB Graphics Man-
ual contain numerous examples.

Introduction to Stateflow®with Applications A−17


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

Volume of Right Circular Cone

z-axis, volume (cubic meters)


150

100

50

0
6
4 4
3
2 2
1
0 0
y-axis, altitude h (meters) x-axis, radius r (meters)

Figure A.6. Volume of a right circular cone.

A.8 Subplots
MATLAB can display up to four windows of different plots on the Figure window using the com-
mand subplot(m,n,p). This command divides the window into an m × n matrix of plotting areas
and chooses the pth area to be active. No spaces or commas are required between the three inte-
gers m, n and p. The possible combinations are shown in Figure A.7.
We will illustrate the use of the subplot(m,n,p) command following the discussion on multiplica-
tion, division and exponentiation that follows.

111
Default
Full Screen

211 221 222


121 122
212 223 224

221 222 211 221 222


122 121
212 223 224 223 224
Figure A.7. Possible subplot arrangements in MATLAB

A.9 Multiplication, Division, and Exponentiation


MATLAB recognizes two types of multiplication, division, and exponentiation. These are the
matrix multiplication, division, and exponentiation, and the element−by−element multiplication,
division, and exponentiation. They are explained in the following paragraphs.

A−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Multiplication, Division, and Exponentiation

In Section A.2, the arrays [ a b c … ] , such a those that contained the coefficients of polynomi-
als, consisted of one row and multiple columns, and thus are called row vectors. If an array has
one column and multiple rows, it is called a column vector. We recall that the elements of a row
vector are separated by spaces. To distinguish between row and column vectors, the elements of a
column vector must be separated by semicolons. An easier way to construct a column vector, is to
write it first as a row vector, and then transpose it into a column vector. MATLAB uses the single
quotation character (′) to transpose a vector. Thus, a column vector can be written either as
b=[−1; 3; 6; 11]
or as
b=[−1 3 6 11]'
As shown below, MATLAB produces the same display with either format.
b=[−1; 3; 6; 11]
b =
-1
3
6
11
b=[−1 3 6 11]' % Observe the single quotation character (‘)
b =
-1
3
6
11
We will now define Matrix Multiplication and Element−by−Element multiplication.
1. Matrix Multiplication (multiplication of row by column vectors)
Let
A = [ a1 a2 a3 … an ]
and
B = [ b 1 b2 b 3 … b n ]'

be two vectors. We observe that A is defined as a row vector whereas B is defined as a col-
umn vector, as indicated by the transpose operator (′). Here, multiplication of the row vector
A by the column vector B , is performed with the matrix multiplication operator (*). Then,

A*B = [ a 1 b 1 + a 2 b 2 + a 3 b 3 + … + a n b n ] = sin gle value (A.5)

Introduction to Stateflow®with Applications A−19


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

For example, if
A = [1 2 3 4 5]
and
B = [ – 2 6 – 3 8 7 ]'

the matrix multiplication A*B produces the single value 68, that is,

A∗ B = 1 × ( – 2 ) + 2 × 6 + 3 × ( – 3 ) + 4 × 8 + 5 × 7 = 68
and this is verified with the MATLAB script
A=[1 2 3 4 5]; B=[ −2 6 −3 8 7]'; A*B % Observe transpose operator (‘) in B
ans =
68
Now, let us suppose that both A and B are row vectors, and we attempt to perform a row−by−
row multiplication with the following MATLAB statements.
A=[1 2 3 4 5]; B=[−2 6 −3 8 7]; A*B % No transpose operator (‘) here
When these statements are executed, MATLAB displays the following message:
??? Error using ==> *
Inner matrix dimensions must agree.
Here, because we have used the matrix multiplication operator (*) in A*B, MATLAB expects
vector B to be a column vector, not a row vector. It recognizes that B is a row vector, and
warns us that we cannot perform this multiplication using the matrix multiplication operator
(*). Accordingly, we must perform this type of multiplication with a different operator. This
operator is defined below.
2. Element−by−Element Multiplication (multiplication of a row vector by another row vector)
Let
C = [ c1 c2 c3 … cn ]
and
D = [ d1 d2 d3 … dn ]

be two row vectors. Here, multiplication of the row vector C by the row vector D is per-
formed with the dot multiplication operator (.*). There is no space between the dot and the
multiplication symbol. Thus,
C.∗ D = [ c 1 d 1 c2 d2 c3 d3 … cn dn ] (A.6)

A−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Multiplication, Division, and Exponentiation

This product is another row vector with the same number of elements, as the elements of C
and D .
As an example, let
C = [1 2 3 4 5]
and
D = [ –2 6 –3 8 7 ]
Dot multiplication of these two row vectors produce the following result.
C.∗ D = 1 × ( – 2 ) 2 × 6 3 × ( – 3 ) 4 × 8 5 × 7 = – 2 12 – 9 32 35
Check with MATLAB:
C=[1 2 3 4 5]; % Vectors C and D must have
D=[−2 6 −3 8 7]; % same number of elements
C.*D % We observe that this is a dot multiplication
ans =
-2 12 -9 32 35
Similarly, the division (/) and exponentiation (^) operators, are used for matrix division and
exponentiation, whereas dot division (./) and dot exponentiation (.^) are used for element−
by−element division and exponentiation, as illustrated in Examples A.11 and A.12 above.
We must remember that no space is allowed between the dot (.) and the multiplication, divi-
sion, and exponentiation operators.
Note: A dot (.) is never required with the plus (+) and minus (−) operators.

Example A.13
Write the MATLAB script that produces a simple plot for the waveform defined as
2
y = f ( t ) = 3e
–4 t
cos 5t – 2e
–3 t t -
sin 2t + ---------- (A.7)
t+1

in the 0 ≤ t ≤ 5 seconds interval.


Solution:
The MATLAB script for this example is as follows:
t=0: 0.01: 5; % Define t−axis in 0.01 increments
y=3 .* exp(−4 .* t) .* cos(5 .* t)−2 .* exp(−3 .* t) .* sin(2 .* t) + t .^2 ./ (t+1);
plot(t,y); grid; xlabel('t'); ylabel('y=f(t)'); title('Plot for Example A.13')
The plot for this example is shown in Figure A.8.

Introduction to Stateflow®with Applications A−21


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

Plot for Example A.13


5

3
y=f(t)

-1
0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5
t

Figure A.8. Plot for Example A.13


Had we, in this example, defined the time interval starting with a negative value equal to or less
than – 1 , say as – 3 ≤ t ≤ 3 , MATLAB would have displayed the following message:
Warning: Divide by zero.
This is because the last term (the rational fraction) of the given expression, is divided by zero
when t = – 1 . To avoid division by zero, we use the special MATLAB function eps, which is a
– 16
number approximately equal to 2.2 × 10 . It will be used with the next example.

The command axis([xmin xmax ymin ymax]) scales the current plot to the values specified by
the arguments xmin, xmax, ymin and ymax. There are no commas between these four argu-
ments. This command must be placed after the plot command and must be repeated for each plot.
The following example illustrates the use of the dot multiplication, division, and exponentiation,
the eps number, the axis([xmin xmax ymin ymax]) command, and also MATLAB’s capability
of displaying up to four windows of different plots.

Example A.14
Plot the functions

y = sin 2x, z = cos 2x, w = sin 2x ⋅ cos 2x, v = sin 2x ⁄ cos 2x

in the interval 0 ≤ x ≤ 2π using 100 data points. Use the subplot command to display these func-
tions on four windows on the same graph.

A−22 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Multiplication, Division, and Exponentiation

Solution:
The MATLAB script to produce the four subplots is as follows:
x=linspace(0,2*pi,100); % Interval with 100 data points
y=(sin(x).^ 2); z=(cos(x).^ 2);
w=y.* z;
v=y./ (z+eps);% add eps to avoid division by zero
subplot(221);% upper left of four subplots
plot(x,y); axis([0 2*pi 0 1]);
title('y=(sinx)^2');
subplot(222); % upper right of four subplots
plot(x,z); axis([0 2*pi 0 1]);
title('z=(cosx)^2');
subplot(223); % lower left of four subplots
plot(x,w); axis([0 2*pi 0 0.3]);
title('w=(sinx)^2*(cosx)^2');
subplot(224); % lower right of four subplots
plot(x,v); axis([0 2*pi 0 400]);
title('v=(sinx)^2/(cosx)^2');
These subplots are shown in Figure A.9.

y=(sinx)2 z=(cosx)2
1 1

0.5 0.5

0 0
0 2 4 6 0 2 4 6
2 2 2 2
w=(sinx) *(cosx) v=(sinx) /(cosx)
400

0.2
200
0.1

0 0
0 2 4 6 0 2 4 6

Figure A.9. Subplots for the functions of Example A.14

The next example illustrates MATLAB’s capabilities with imaginary numbers. We will introduce
the real(z) and imag(z) functions that display the real and imaginary parts of the complex quan-
tity z = x + iy, the abs(z), and the angle(z) functions that compute the absolute value (magni-
tude) and phase angle of the complex quantity z = x + iy = r ∠θ. We will also use the
polar(theta,r) function that produces a plot in polar coordinates, where r is the magnitude, theta

Introduction to Stateflow®with Applications A−23


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

is the angle in radians, and the round(n) function that rounds a number to its nearest integer.

Example A.15
Consider the electric circuit of Figure A.10.

a
10 Ω

10 Ω
Z ab
10 μF
0.1 H

b
Figure A.10. Electric circuit for Example A.15
With the given values of resistance, inductance, and capacitance, the impedance Z ab as a func-
tion of the radian frequency ω can be computed from the following expression:
4 6
10 – j ( 10 ⁄ ω )
Z ab = Z = 10 + --------------------------------------------------------
5
(A.8)
10 + j ( 0.1ω – 10 ⁄ ω )

a. Plot Re { Z } (the real part of the impedance Z) versus frequency ω.


b. Plot Im { Z } (the imaginary part of the impedance Z) versus frequency ω.
c. Plot the impedance Z versus frequency ω in polar coordinates.
Solution:
The MATLAB script below computes the real and imaginary parts of Z ab which, for simplicity,
are denoted as z , and plots these as two separate graphs (parts a & b). It also produces a polar
plot (part c).
w=0: 1: 2000; % Define interval with one radian interval;...
z=(10+(10 .^ 4 −j .* 10 .^ 6 ./ (w+eps)) ./ (10 + j .* (0.1 .* w −10.^5./ (w+eps))));...
%
% The first five statements (next two lines) compute and plot Re{z}
real_part=real(z); plot(w,real_part);...
xlabel('radian frequency w'); ylabel('Real part of Z'); grid

A−24 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Multiplication, Division, and Exponentiation

1200

1000

Real part of Z 800

600

400

200

0
0 200 400 600 800 1000 1200 1400 1600 1800 2000
radian frequency w

Figure A.11. Plot for the real part of the impedance in Example A.15
% The next five statements (next two lines) compute and plot Im{z}
imag_part=imag(z); plot(w,imag_part);...
xlabel('radian frequency w'); ylabel('Imaginary part of Z'); grid

600

400
Imaginary part of Z

200

-200

-400

-600
0 200 400 600 800 1000 1200 1400 1600 1800 2000
radian frequency w

Figure A.12. Plot for the imaginary part of the impedance in Example A.15
% The last six statements (next five lines) below produce the polar plot of z
mag=abs(z); % Computes |Z|;...
rndz=round(abs(z)); % Rounds |Z| to read polar plot easier;...
theta=angle(z); % Computes the phase angle of impedance Z;...
polar(theta,rndz); % Angle is the first argument
ylabel('Polar Plot of Z'); grid

Introduction to Stateflow®with Applications A−25


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

90 1500
120 60
1000
150 30
500

Polar Plot of Z
180 0

210 330

240 300
270

Figure A.13. Polar plot of the impedance in Example A.15


Example A.15 clearly illustrates how powerful, fast, accurate, and flexible MATLAB is.

A.10 Script and Function Files


MATLAB recognizes two types of files: script files and function files. Both types are referred to as
m−files since both require the .m extension.
A script file consists of two or more built−in functions such as those we have discussed thus far.
Thus, the script for each of the examples we discussed earlier, make up a script file. Generally, a
script file is one which was generated and saved as an m−file with an editor such as the MAT-
LAB’s Editor/Debugger.
A function file is a user−defined function using MATLAB. We use function files for repetitive
tasks. The first line of a function file must contain the word function, followed by the output argu-
ment, the equal sign ( = ), and the input argument enclosed in parentheses. The function name
and file name must be the same, but the file name must have the extension .m. For example, the
function file consisting of the two lines below
function y = myfunction(x)
y=x.^ 3 + cos(3.* x)
is a function file and must be saved as myfunction.m
For the next example, we will use the following MATLAB functions:
fzero(f,x) − attempts to find a zero of a function of one variable, where f is a string containing the
name of a real−valued function of a single real variable. MATLAB searches for a value near a
point where the function f changes sign, and returns that value, or returns NaN if the search fails.

A−26 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Script and Function Files

Important: We must remember that we use roots(p) to find the roots of polynomials only, such as
those in Examples A.1 and A.2.
fplot(fcn,lims) − plots the function specified by the string fcn between the x−axis limits specified
by lims = [xmin xmax]. Using lims = [xmin xmax ymin ymax] also controls the y−axis limits.
The string fcn must be the name of an m−file function or a string with variable x .
NaN (Not−a−Number) is not a function; it is MATLAB’s response to an undefined expression
such as 0 ⁄ 0 , ∞ ⁄ ∞ , or inability to produce a result as described on the next paragraph. We can
avoid division by zero using the eps number, which we mentioned earlier.

Example A.16
Find the zeros, the minimum, and the maximum values of the function
1
f ( x ) = --------------------------------------- 1
- – ---------------------------------------
- – 10 (A.9)
2 2
( x – 0.1 ) + 0.01 ( x – 1.2 ) + 0.04

in the interval – 1.5 ≤ x ≤ 1.5


Solution:
We first plot this function to observe the approximate zeros, maxima, and minima using the fol-
lowing script.
x=−1.5: 0.01: 1.5;
y=1./ ((x−0.1).^ 2 + 0.01) −1./ ((x−1.2).^ 2 + 0.04) −10;
plot(x,y); grid
The plot is shown in Figure A.14.

100

80

60

40

20

-20

-40
-1.5 -1 -0.5 0 0.5 1 1.5

Figure A.14. Plot for Example A.16 using the plot command

Introduction to Stateflow®with Applications A−27


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

The roots (zeros) of this function appear to be in the neighborhood of x = – 0.2 and x = 0.3 . The
maximum occurs at approximately x = 0.1 where, approximately, y max = 90 , and the minimum
occurs at approximately x = 1.2 where, approximately, y min = – 34 .

Next, we define and save f(x) as the funczero01.m function m−file with the following script:
function y=funczero01(x)
% Finding the zeros of the function shown below
y=1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10;
To save this file, from the File drop menu on the Command Window, we choose New, and when
the Editor Window appears, we type the script above and we save it as funczero01. MATLAB
appends the extension .m to it.
Now, we can use the fplot(fcn,lims) command to plot f ( x ) as follows:
fplot('funczero01', [−1.5 1.5]); grid
This plot is shown in Figure A.15. As expected, this plot is identical to the plot of Figure A.14
which was obtained with the plot(x,y) command as shown in Figure A.14.

100

80

60

40

20

-20

-40
-1.5 -1 -0.5 0 0.5 1 1.5

Figure A.15. Plot for Example A.16 using the fplot command

We will use the fzero(f,x) function to compute the roots of f ( x ) in Equation (A.9) more precisely.
The MATLAB script below will accomplish this.
x1= fzero('funczero01', −0.2);
x2= fzero('funczero01', 0.3);
fprintf('The roots (zeros) of this function are r1= %3.4f', x1);
fprintf(' and r2= %3.4f \n', x2)

A−28 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Script and Function Files

MATLAB displays the following:


The roots (zeros) of this function are r1= -0.1919 and r2= 0.3788
The earlier MATLAB versions included the function fmin(f,x1,x2) and with this function we
could compute both a minimum of some function f ( x ) or a maximum of f ( x ) since a maximum of
f ( x ) is equal to a minimum of – f ( x ) . This can be visualized by flipping the plot of a function f ( x )
upside−down. This function is no longer used in MATLAB and thus we will compute the maxima
and minima from the derivative of the given function.
From elementary calculus, we recall that the maxima or minima of a function y = f ( x ) can be
found by setting the first derivative of a function equal to zero and solving for the independent
variable x . For this example we use the diff(x) function which produces the approximate deriva-
tive of a function. Thus, we use the following MATLAB script:
syms x ymin zmin; ymin=1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10;...
zmin=diff(ymin)
zmin =
-1/((x-1/10)^2+1/100)^2*(2*x-1/5)+1/((x-6/5)^2+1/25)^2*(2*x-12/5)
When the command
solve(zmin)
is executed, MATLAB displays a very long expression which when copied at the command
prompt and executed, produces the following:
ans =
0.6585 + 0.3437i
ans =
0.6585 - 0.3437i
ans =
1.2012
The real value 1.2012 above is the value of x at which the function y has its minimum value as
we observe also in the plot of Figure A.15.
To find the value of y corresponding to this value of x, we substitute it into f ( x ) , that is,
x=1.2012; ymin=1 / ((x−0.1) ^ 2 + 0.01) −1 / ((x−1.2) ^ 2 + 0.04) −10
ymin = -34.1812
We can find the maximum value from – f ( x ) whose plot is produced with the script
x=−1.5:0.01:1.5; ymax=−1./((x−0.1).^2+0.01)+1./((x−1.2).^2+0.04)+10; plot(x,ymax); grid
and the plot is shown in Figure A.16.

Introduction to Stateflow®with Applications A−29


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

40

20

-20

-40

-60

-80

-100
-1.5 -1 -0.5 0 0.5 1 1.5

Figure A.16. Plot of – f ( x ) for Example A.16

Next we compute the first derivative of – f ( x ) and we solve for x to find the value where the max-
imum of ymax occurs. This is accomplished with the MATLAB script below.
syms x ymax zmax; ymax=−(1/((x−0.1)^2+0.01)−1/((x−1.2)^2+0.04)−10); zmax=diff(ymax)
zmax =
1/((x-1/10)^2+1/100)^2*(2*x-1/5)-1/((x-6/5)^2+1/25)^2*(2*x-12/5)
solve(zmax)
When the command
solve(zmax)
is executed, MATLAB displays a very long expression which when copied at the command
prompt and executed, produces the following:
ans =
0.6585 + 0.3437i
ans =
0.6585 - 0.3437i
ans =
1.2012
ans =
0.0999
From the values above we choose x = 0.0999 which is consistent with the plots of Figures A.15
and A.16. Accordingly, we execute the following script to obtain the value of ymin .

A−30 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Display Formats

x=0.0999; % Using this value find the corresponding value of ymax


ymax=1 / ((x−0.1) ^ 2 + 0.01) −1 / ((x−1.2) ^ 2 + 0.04) −10

ymax = 89.2000

A.11 Display Formats


MATLAB displays the results on the screen in integer format without decimals if the result is an
integer number, or in short floating point format with four decimals if it a fractional number. The
format displayed has nothing to do with the accuracy in the computations. MATLAB performs all
computations with accuracy up to 16 decimal places.
The output format can changed with the format command. The available MATLAB formats can
be displayed with the help format command as follows:
help format
FORMAT Set output format.
All computations in MATLAB are done in double precision.
FORMAT may be used to switch between different output display formats
as follows:
FORMAT Default. Same as SHORT.
FORMAT SHORT Scaled fixed point format with 5 digits.
FORMAT LONG Scaled fixed point format with 15 digits.
FORMAT SHORT E Floating point format with 5 digits.
FORMAT LONG E Floating point format with 15 digits.
FORMAT SHORT G Best of fixed or floating point format with 5 digits.
FORMAT LONG G Best of fixed or floating point format with 15 digits.
FORMAT HEX Hexadecimal format.
FORMAT + The symbols +, - and blank are printed for positive, negative,
and zero elements.Imaginary parts are ignored.
FORMAT BANK Fixed format for dollars and cents.
FORMAT RAT Approximation by ratio of small integers.
Spacing:
FORMAT COMPACT Suppress extra line-feeds.
FORMAT LOOSE Puts the extra line-feeds back in.
Some examples with different format displays age given below.
format short 33.3335 Four decimal digits (default)
format long 33.33333333333334 16 digits
format short e 3.3333e+01 Four decimal digits plus exponent
format short g 33.333 Better of format short or format short e
format bank 33.33 two decimal digits
format + only + or - or zero are printed

Introduction to Stateflow®with Applications A−31


Copyright © Orchard Publications
Appendix A Introduction to MATLAB®

format rat 100/3 rational approximation


The disp(X) command displays the array X without printing the array name. If X is a string, the
text is displayed.
The fprintf(format,array) command displays and prints both text and arrays. It uses specifiers to
indicate where and in which format the values would be displayed and printed. Thus, if %f is
used, the values will be displayed and printed in fixed decimal format, and if %e is used, the val-
ues will be displayed and printed in scientific notation format. With this command only the real
part of each parameter is processed.
This appendix is just an introduction to MATLAB.* This outstanding software package consists
of many applications known as Toolboxes. The MATLAB Student Version contains just a few of
these Toolboxes. Others can be bought directly from The MathWorks,™ Inc., as add−ons.

* For more MATLAB applications, please refer to Numerical Analysis Using MATLAB and Spreadsheets,
ISBN 0−9709511−1−6.

A−32 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Appendix B
Introduction to Simulink®

T
his appendix is a brief introduction to Simulink. This author feels that we can best intro-
duce Simulink with a few examples. Some familiarity with MATLAB is essential in under-
standing Simulink, and for this purpose, Appendix A is included as an introduction to
MATLAB.

B.1 Simulink and its Relation to MATLAB


The MATLAB® and Simulink® environments are integrated into one entity, and thus we can
analyze, simulate, and revise our models in either environment at any point. We invoke Simulink
from within MATLAB. We will introduce Simulink with a few illustrated examples.

Example B.1
For the circuit of Figure B.1, the initial conditions are i L ( 0 − ) = 0 , and v c ( 0 − ) = 0.5 V . We will
compute v c ( t ) .
R L
+
1Ω 1⁄4 H C
+ vC ( t )
− i(t)
4⁄3 F

vs ( t ) = u0 ( t )
Figure B.1. Circuit for Example B.1
For this example,
dv
i = i L = i C = C --------C- (B.1)
dt
and by Kirchoff’s voltage law (KVL),
di
Ri L + L ------L- + v C = u 0 ( t ) (B.2)
dt
Substitution of (B.1) into (B.2) yields

Introduction to Stateflow®with Applications B−1


Copyright © Orchard Publications
Introduction to Simulink®

2
dv d vC
RC --------C- + LC ----------
- + vC = u0 ( t ) (B.3)
dt dt
2

Substituting the values of the circuit constants and rearranging we obtain:


2
1 d v C 4 dv C
--- ----------- + --- --------- + v C = u 0 ( t )
3 dt 2 3 dt

2
d vC dv
----------- + 4 --------C- + 3v C = 3u 0 ( t ) (B.4)
dt
2 dt

2
d vC dv
----------- + 4 --------C- + 3v C = 3 t>0 (B.5)
dt
2 dt

To appreciate Simulink’s capabilities, for comparison, three different methods of obtaining the
solution are presented, and the solution using Simulink follows.
First Method − Assumed Solution
Equation (B.5) is a second−order, non−homogeneous differential equation with constant coeffi-
cients, and thus the complete solution will consist of the sum of the forced response and the natu-
ral response. It is obvious that the solution of this equation cannot be a constant since the deriva-
tives of a constant are zero and thus the equation is not satisfied. Also, the solution cannot
contain sinusoidal functions (sine and cosine) since the derivatives of these are also sinusoids.
– at
However, decaying exponentials of the form ke where k and a are constants, are possible candi-
dates since their derivatives have the same form but alternate in sign.
–s t –s t
It can be shown* that if k 1 e 1 and k 2 e 2 where k 1 and k 2 are constants and s 1 and s 2 are the
roots of the characteristic equation of the homogeneous part of the given differential equation,
–s1 t –s2 t
the natural response is the sum of the terms k 1 e and k 2 e . Therefore, the total solution will
be
–s1 t –s2 t
v c ( t ) = natural response + forced response = v cn ( t ) + v cf ( t ) = k 1 e + k2 e + v cf ( t ) (B.6)

The values of s 1 and s 2 are the roots of the characteristic equation

* Please refer to Circuit Analysis II with MATLAB Applications, ISBN 0−9709511−5−9, Appendix B for a
thorough discussion.

B−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB
2
s + 4s + 3 = 0 (B.7)
Solution of (B.7) yields of s 1 = – 1 and s 2 = – 3 and with these values (B.6) is written as

–t –3 t
vc ( t ) = k1 e + k2 e + v cf ( t ) (B.8)

The forced component v cf ( t ) is found from (B.5), i.e.,


2
d vC dv
----------- + 4 --------C- + 3v C = 3 t>0 (B.9)
dt
2 dt

Since the right side of (B.9) is a constant, the forced response will also be a constant and we
denote it as v Cf = k 3 . By substitution into (B.9) we obtain

0 + 0 + 3k 3 = 3
or
v Cf = k 3 = 1 (B.10)

Substitution of this value into (B.8), yields the total solution as


–t –3 t
v C ( t ) = v Cn ( t ) + v Cf = k 1 e + k 2 e +1 (B.11)

The constants k 1 and k 2 will be evaluated from the initial conditions. First, using v C ( 0 ) = 0.5 V
and evaluating (B.11) at t = 0 , we obtain
0 0
v C ( 0 ) = k 1 e + k 2 e + 1 = 0.5

k 1 + k 2 = – 0.5 (B.12)

Also,
dv C dv C i
i L = i C = C ---------, --------- = ---L-
dt dt C
and
dv iL ( 0 ) 0
--------C- = -----------
- = ---- = 0 (B.13)
dt t=0
C C

Next, we differentiate (B.11), we evaluate it at t = 0 , and equate it with (B.13). Thus,


dv
--------C- = – k 1 – 3k 2 (B.14)
dt t=0

By equating the right sides of (B.13) and (B.14) we obtain

Introduction to Stateflow®with Applications B−3


Copyright © Orchard Publications
Introduction to Simulink®

– k 1 – 3k 2 = 0 (B.15)

Simultaneous solution of (B.12) and (B.15), gives k 1 = – 0.75 and k 2 = 0.25 . By substitution into
(B.8), we obtain the total solution as
–t –3 t
v C ( t ) = ( – 0.75 e + 0.25e + 1 )u 0 ( t ) (B.16)

Check with MATLAB:


syms t % Define symbolic variable t
y0=−0.75*exp(−t)+0.25*exp(−3*t)+1; % The total solution y(t), for our example, vc(t)
y1=diff(y0) % The first derivative of y(t)
y1 =
3/4*exp(-t)-3/4*exp(-3*t)
y2=diff(y0,2) % The second derivative of y(t)
y2 =
-3/4*exp(-t)+9/4*exp(-3*t)
y=y2+4*y1+3*y0 % Summation of y and its derivatives
y =
3
Thus, the solution has been verified by MATLAB. Using the expression for v C ( t ) in (B.16), we
find the expression for the current as
dv C 4 3 –t
i = i L = i C = C ---------- = --- ⎛ --- e – 3
--- e ⎞ = e – e A
– 3t – t – 3t
(B.17)
dt 3⎝ 4 4 ⎠

Second Method − Using the Laplace Transformation


The transformed circuit is shown in Figure B.2.
R L
+
1 0.25s C

+ 3 ⁄ 4s VC ( s )
Vs ( s ) = 1 ⁄ s −
I(s) + V (0)
− C
0.5 ⁄ s −
Figure B.2. Transformed Circuit for Example B.1

B−4 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

By the voltage division* expression,


2
3 ⁄ 4s 0.5s + 2s + 3-
V C ( s ) = ---------------------------------------------- ⋅ ⎛ 1
--- – 0.5
-------⎞ + 0.5 1.5 - + 0.5
------- = -------------------------------- ------- = -----------------------------------
( 1 + 0.25s + 3 ⁄ 4s ) ⎝ s s ⎠ s 2
s ( s + 4s + 3 ) s s(s + 1)(s + 3)

Using partial fraction expansion,† we let


2
-----------------------------------
r2
0.5s + 2s + 3- = r---1- + --------------- r3
- + ---------------
- (B.18)
s(s + 1 )( s + 3) s (s + 1) (s + 3)
2
0.5s + 2s + 3
r 1 = ---------------------------------- = 1
(s + 1)(s + 3) s=0

2
r 2 = 0.5s + 2s + 3-
--------------------------------- = – 0.75
s(s + 3) s = –1

2
0.5s + 2s + 3-
r 3 = --------------------------------- = 0.25
s(s + 1) s = –3

and by substitution into (B.18)


2
0.5s + 2s + 3- = 1
V C ( s ) = ----------------------------------- – 0.75- + ---------------
--- + --------------- 0.25 -
s(s + 1)(s + 3) s (s + 1) (s + 3)

Taking the Inverse Laplace transform‡ we find that


–t – 3t
v C ( t ) = 1 – 0.75e + 0.25e

Third Method − Using State Variables


di
Ri L + L ------L- + v C = u 0 ( t ) **
dt

* For derivation of the voltage division and current division expressions, please refer to Circuit Analysis I with
MATLAB Applications, ISBN 0−9709511−2−4.
† Partial fraction expansion is discussed in Chapter 3, this text.
‡ For an introduction to Laplace Transform and Inverse Laplace Transform, please refer Chapters 2 and 3, this
text.
** Usually, in State−Space and State Variables Analysis, u ( t ) denotes any input. For distinction, we will denote
the Unit Step Function as u0 ( t ) . For a detailed discussion on State−Space and State Variables Analysis, please
refer to Chapter 5, this text.

Introduction to Stateflow®with Applications B−5


Copyright © Orchard Publications
Introduction to Simulink®

By substitution of given values and rearranging, we obtain


1--- di
------L- = ( – 1 )i L – v C + 1
4 dt
or
di
------L- = – 4i L – 4v C + 4 (B.19)
dt

Next, we define the state variables x 1 = i L and x 2 = v C . Then,

di
x· 1 = ------L- * (B.20)
dt
and
dv
x· 2 = --------C- (B.21)
dt
Also,
dv
i L = C --------C-
dt
and thus,
dv 4
x 1 = i L = C --------C- = Cx· 2 = --- x· 2
dt 3
or
3
x· 2 = --- x 1 (B.22)
4
Therefore, from (B.19), (B.20), and (B.22), we obtain the state equations
x· 1 = – 4x 1 – 4x 2 + 4
3
x· 2 = --- x 1
4
and in matrix form,
x· 1 x
= –4 –4 1 + 4 u0 ( t ) (B.23)
·x 2 3 ⁄ 4 0 x2 0

Solution† of (B.23) yields

* The notation x· (x dot) is often used to denote the first derivative of the function x , that is, x· = dx ⁄ dt .
† The detailed solution of (B.23) is given in Chapter 5, Example 5.10, Page 5−23, this text.

B−6 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

x1 –t – 3t
= e –e
x2 –t
1 – 0.75 e + 0.25e
– 3t

Then,
–t – 3t
x1 = iL = e –e (B.24)
and
–t – 3t
x 2 = v C = 1 – 0.75e + 0.25e (B.25)

Modeling the Differential Equation of Example B.1 with Simulink


To run Simulink, we must first invoke MATLAB. Make sure that Simulink is installed in your sys-
tem. In the MATLAB Command prompt, we type:
simulink
Alternately, we can click on the Simulink icon shown in Figure B.3. It appears on the top bar on
MATLAB’s Command prompt.

Figure B.3. The Simulink icon

Upon execution of the Simulink command, the Commonly Used Blocks appear as shown in Fig-
ure B.4.
In Figure B.4, the left side is referred to as the Tree Pane and displays all Simulink libraries
installed. The right side is referred to as the Contents Pane and displays the blocks that reside in
the library currently selected in the Tree Pane.
Let us express the differential equation of Example B.1 as
2
d vC dv
----------- = – 4 --------C- – 3v C + 3u 0 ( t ) (B.26)
dt
2 dt

A block diagram representing relation (B.26) above is shown in Figure B.5. We will use Simulink
to draw a similar block diagram.*

* Henceforth, all Simulink block diagrams will be referred to as models.

Introduction to Stateflow®with Applications B−7


Copyright © Orchard Publications
Introduction to Simulink®

Figure B.4. The Simulink Library Browser

2
d vC dv
----------- --------C-
2
dt dt vC
u0 ( t ) 3 Σ ∫ dt ∫ dt

−4

−3

Figure B.5. Block diagram for equation (B.26)


To model the differential equation (B.26) using Simulink, we perform the following steps:
1. On the Simulink Library Browser, we click on the leftmost icon shown as a blank page on the
top title bar. A new model window named untitled will appear as shown in Figure B.6.

B−8 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

Figure B.6. The Untitled model window in Simulink.


The window of Figure B.6 is the model window where we enter our blocks to form a block dia-
gram. We save this as model file name Equation_1_26. This is done from the File drop menu of
Figure B.6 where we choose Save as and name the file as Equation_1_26. Simulink will add
the extension .mdl. The new model window will now be shown as Equation_1_26, and all
saved files will have this appearance. See Figure B.7.

Figure B.7. Model window for Equation_1_26.mdl file


2. With the Equation_1_26 model window and the Simulink Library Browser both visible, we
click on the Sources appearing on the left side list, and on the right side we scroll down until
we see the unit step function shown as Step. See Figure B.8. We select it, and we drag it into
the Equation_1_26 model window which now appears as shown in Figure B.8. We save file
Equation_1_26 using the File drop menu on the Equation_1_26 model window (right side of
Figure B.8).
3. With reference to block diagram of Figure B.5, we observe that we need to connect an ampli-
fier with Gain 3 to the unit step function block. The gain block in Simulink is under Com-
monly Used Blocks (first item under Simulink on the Simulink Library Browser). See Figure
B.8. If the Equation_1_26 model window is no longer visible, it can be recalled by clicking on
the white page icon on the top bar of the Simulink Library Browser.
4. We choose the gain block and we drag it to the right of the unit step function. The triangle on
the right side of the unit step function block and the > symbols on the left and right sides of
the gain block are connection points. We point the mouse close to the connection point of the
unit step function until is shows as a cross hair, and draw a straight line to connect the two

Introduction to Stateflow®with Applications B−9


Copyright © Orchard Publications
Introduction to Simulink®

blocks.* We double−click on the gain block and on the Function Block Parameters, we
change the gain from 1 to 3. See Figure B.9.

Figure B.8. Dragging the unit step function into File Equation_1_26

Figure B.9. File Equation_1_26 with added Step and Gain blocks

* An easy method to interconnect two Simulink blocks by clicking on the source block to select it, then hold down
the Ctrl key and left−click on the destination block.

B−10 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

5. Next, we need to add a thee−input adder. The adder block appears on the right side of the
Simulink Library Browser under Math Operations. We select it, and we drag it into the
Equation_1_26 model window. We double click it, and on the Function Block Parameters
window which appears, we specify 3 inputs. We then connect the output of the of the gain
block to the first input of the adder block as shown in Figure B.10.

Figure B.10. File Equation_1_26 with added gain block


6. From the Commonly Used Blocks of the Simulink Library Browser, we choose the Integra-
tor block, we drag it into the Equation_1_26 model window, and we connect it to the output
of the Add block. We repeat this step and to add a second Integrator block. We click on the
text “Integrator” under the first integrator block, and we change it to Integrator 1. Then, we
change the text “Integrator 1” under the second Integrator to “Integrator 2” as shown in Fig-
ure B.11.

Figure B.11. File Equation_1_26 with the addition of two integrators


7. To complete the block diagram, we add the Scope block which is found in the Commonly
Used Blocks on the Simulink Library Browser, we click on the Gain block, and we copy and
paste it twice. We flip the pasted Gain blocks by using the Flip Block command from the For-
mat drop menu, and we label these as Gain 2 and Gain 3. Finally, we double−click on these
gain blocks and on the Function Block Parameters window, we change the gains from to −4
and −3 as shown in Figure B.12.

Figure B.12. File Equation_1_26 complete block diagram

Introduction to Stateflow®with Applications B−11


Copyright © Orchard Publications
Introduction to Simulink®

dv
8. The initial conditions i L ( 0 − ) = C --------C- −
= 0 , and v c ( 0 ) = 0.5 V are entered by double
dt t=0
clicking the Integrator blocks and entering the values 0 for the first integrator, and 0.5 for the
second integrator. We also need to specify the simulation time. This is done by specifying the
simulation time to be 10 seconds on the Configuration Parameters from the Simulation drop
menu. We can start the simulation on Start from the Simulation drop menu or by clicking on

the icon.
9. To see the output waveform, we double click on the Scope block, and then clicking on the

Autoscale icon, we obtain the waveform shown in Figure B.13.

Figure B.13. The waveform for the function v C ( t ) for Example B.1

Another easier method to obtain and display the output v C ( t ) for Example B.1, is to use State−
Space block from Continuous in the Simulink Library Browser, as shown in Figure B.14.

Figure B.14. Obtaining the function v C ( t ) for Example B.1 with the State−Space block.

B−12 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

The simout To Workspace block shown in Figure B.14 writes its input to the workspace. The
data and variables created in the MATLAB Command window, reside in the MATLAB Work-
space. This block writes its output to an array or structure that has the name specified by the
block's Variable name parameter. This gives us the ability to delete or modify selected variables.
We issue the command who to see those variables. From Equation B.23, Page B−6,

x· 1 x
= –4 –4 1 + 4 u0 ( t )
·x 2 3 ⁄ 4 0 x2 0

The output equation is


y = Cx + du
or
x1
y = [0 1] + [ 0 ]u
x2

We double−click on the State−Space block, and in the Functions Block Parameters window we
enter the constants shown in Figure B.15.

Figure B.15. The Function block parameters for the State−Space block.

Introduction to Stateflow®with Applications B−13


Copyright © Orchard Publications
Introduction to Simulink®

The initials conditions [ x1 x2 ]' are specified in MATLAB’s Command prompt as


x1=0; x2=0.5;

As before, to start the simulation we click clicking on the icon, and to see the output wave-

form, we double click on the Scope block, and then clicking on the Autoscale icon, we
obtain the waveform shown in Figure B.16.

Figure B.16. The waveform for the function v C ( t ) for Example B.1 with the State−Space block.

The state−space block is the best choice when we need to display the output waveform of three or
more variables as illustrated by the following example.

Example B.2
A fourth−order network is described by the differential equation
4 3 2
d y d y d y dy
--------- + a 3 --------3- + a 2 -------2- + a 1 ------ + a 0 y ( t ) = u ( t ) (B.27)
dt
4
dt dt dt

where y ( t ) is the output representing the voltage or current of the network, and u ( t ) is any input,
and the initial conditions are y ( 0 ) = y' ( 0 ) = y'' ( 0 ) = y''' ( 0 ) = 0 .
a. We will express (B.27) as a set of state equations

B−14 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

b. It is known that the solution of the differential equation


4 2
d y d y
-------- + 2 -------2- + y ( t ) = sin t (B.28)
4
dt dt

subject to the initial conditions y ( 0 ) = y' ( 0 ) = y'' ( 0 ) = y''' ( 0 ) = 0 , has the solution
2
y ( t ) = 0.125 [ ( 3 – t ) – 3t cos t ] (B.29)
In our set of state equations, we will select appropriate values for the coefficients
a 3, a 2, a 1, and a 0 so that the new set of the state equations will represent the differential equa-
tion of (B.28), and using Simulink, we will display the waveform of the output y ( t ) .
1. The differential equation of (B.28) is of fourth−order; therefore, we must define four state vari-
ables that will be used with the four first−order state equations.
We denote the state variables as x 1, x 2, x 3 , and x 4 , and we relate them to the terms of the
given differential equation as
2 3
dy d y d y
x1 = y ( t ) x 2 = ------ x 3 = --------- x 4 = --------- (B.30)
dt dt
2
dt
3

We observe that
x· 1 = x 2
x· 2 = x 3
x· 3 = x 4 (B.31)
4
d y = x· = – a x – a x – a x – a x + u ( t )
---------
4 4 0 1 1 2 2 3 3 4
dt
and in matrix form
x· 1 0 1 0 0 x1 0
x· 2 0 0 1 0 x2
= + 0 u(t) (B.32)
x· 3 0 0 0 1 x3 0
x· 4 –a0 –a1 –a2 –a3 x4 1

In compact form, (B.32) is written as


x· = Ax + bu (B.33)
Also, the output is
y = Cx + du (B.34)
where

Introduction to Stateflow®with Applications B−15


Copyright © Orchard Publications
Introduction to Simulink®

x· 1 0 1 0 0 x1 0
x· 2 0 0 1 0 x2
x· = , A= , x= , b= 0, and u = u ( t ) (B.35)
x· 3 0 0 0 1 x3 0
x· 4 –a0 –a1 –a2 –a3 x4 1

and since the output is defined as


y ( t ) = x1
relation (B.34) is expressed as

x1
x2
y = [1 0 0 0] ⋅ + [ 0 ]u ( t ) (B.36)
x3
x4

2. By inspection, the differential equation of (B.27) will be reduced to the differential equation of
(B.28) if we let
a3 = 0 a2 = 2 a1 = 0 a0 = 1 u ( t ) = sin t

and thus the differential equation of (B.28) can be expressed in state−space form as

x· 1 0 1 0 0 x1 0
x· 2 0 0 1 0 x2
= + 0 sin t (B.37)
x· 3 0 0 0 1 x3 0
x· 4 –a0 0 –2 0 x4 1

where

x· 1 0 1 0 0 x1 0
x· 2 0 0 1 0 x2
x· = , A= , x= , b= 0, and u = sin t (B.38)
x· 3 0 0 0 1 x3 0
x· 4 –a0 0 –2 0 x4 1

Since the output is defined as


y ( t ) = x1
in matrix form it is expressed as

B−16 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

x1
x2
y = [1 0 0 0] ⋅ + [ 0 ] sin t (B.39)
x3
x4

We invoke MATLAB, we start Simulink by clicking on the Simulink icon, on the Simulink
Library Browser we click on the Create a new model (blank page icon on the left of the top
bar), and we save this model as Example_1_2. On the Simulink Library Browser we select
Sources, we drag the Signal Generator block on the Example_1_2 model window, we click
and drag the State−Space block from the Continuous on Simulink Library Browser, and we
click and drag the Scope block from the Commonly Used Blocks on the Simulink Library
Browser. We also add the Display block found under Sinks on the Simulink Library
Browser. We connect these four blocks and the complete block diagram is as shown in Figure
B.17.

Figure B.17. Block diagram for Example B.2


We now double−click on the Signal Generator block and we enter the following in the Func-
tion Block Parameters:
Wave form: sine
Time (t): Use simulation time
Amplitude: 1
Frequency: 2
Units: Hertz
Next, we double−click on the state−space block and we enter the following parameter values
in the Function Block Parameters:
A: [0 1 0 0; 0 0 1 0; 0 0 0 1; −a0 −a1 −a2 −a3]
B: [0 0 0 1]’
C: [1 0 0 0]
D: [0]
Initial conditions: x0

Introduction to Stateflow®with Applications B−17


Copyright © Orchard Publications
Introduction to Simulink®

Absolute tolerance: auto


Now, we switch to the MATLAB Command prompt and we type the following:
>> a0=1; a1=0; a2=2; a3=0; x0=[0 0 0 0]’;

We change the Simulation Stop time to 25 , and we start the simulation by clicking on the
icon. To see the output waveform, we double click on the Scope block, then clicking on the

Autoscale icon, we obtain the waveform shown in Figure B.18.

Figure B.18. Waveform for Example B.2


The Display block in Figure B.17 shows the value at the end of the simulation stop time.

Examples B.1 and B.2 have clearly illustrated that the State−Space is indeed a powerful block. We
could have obtained the solution of Example B.2 using four Integrator blocks by this approach
would have been more time consuming.

Example B.3
Using Algebraic Constraint blocks found in the Math Operations library, Display blocks found
in the Sinks library, and Gain blocks found in the Commonly Used Blocks library, we will create
a model that will produce the simultaneous solution of three equations with three unknowns.
The model will display the values for the unknowns z 1 , z 2 , and z 3 in the system of the equations

a1 z1 + a2 z2 + a3 z3 + k1 = 0
a4 z1 + a5 z2 + a6 z3 + k2 = 0 (B.40)
a7 z1 + a8 z2 + a9 z3 + k3 = 0

B−18 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Simulink and its Relation to MATLAB

The model is shown in Figure B.19.

Figure B.19. Model for Example B.3


Next, we go to MATLAB’s Command prompt and we enter the following values:
a1=2; a2=−3; a3=−1; a4=1; a5=5; a6=4; a7=−6; a8=1; a9=2;...
k1=−8; k2=−7; k3=5;
After clicking on the simulation icon, we observe the values of the unknowns as z 1 = 2 ,
z 2 = – 3 , and z 3 = 5 .These values are shown in the Display blocks of Figure B.19.

The Algebraic Constraint block constrains the input signal f ( z ) to zero and outputs an algebraic
state z . The block outputs the value necessary to produce a zero at the input. The output must
affect the input through some feedback path. This enables us to specify algebraic equations for
index 1 differential/algebraic systems (DAEs). By default, the Initial guess parameter is zero. We
can improve the efficiency of the algebraic loop solver by providing an Initial guess for the alge-
braic state z that is close to the solution value.

Introduction to Stateflow®with Applications B−19


Copyright © Orchard Publications
Introduction to Simulink®

An outstanding feature in Simulink is the representation of a large model consisting of many


blocks and lines, to be shown as a single Subsystem block.* For instance, we can group all blocks
and lines in the model of Figure B.19 except the display blocks, we choose Create Subsystem
from the Edit menu, and this model will be shown as in Figure B.20† where in MATLAB’s Com-
mand prompt we have entered:
a1=5; a2=−1; a3=4; a4=11; a5=6; a6=9; a7=−8; a8=4; a9=15;...
k1=14; k2=−6; k3=9;

Figure B.20. The model of Figure B.19 represented as a subsystem

The Display blocks in Figure B.20 show the values of z 1 , z 2 , and z 3 for the values specified in
MATLAB’s Command prompt.

B.2 Simulink Demos


At this time, the reader with no prior knowledge of Simulink, should be ready to learn Simulink’s
additional capabilities. It is highly recommended that the reader becomes familiar with the block
libraries found in the Simulink Library Browser. Then, the reader can follow the steps delineated
in The MathWorks Simulink User’s Manual to run the Demo Models beginning with the thermo
model. This model can be seen by typing
thermo
in the MATLAB Command prompt.

* The Subsystem block is described in detail in Chapter 2, Section 2.1, Page 2−2, Introduction to Simulink with
Engineering Applications, ISBN 0−9744239−7−1.
† The contents of the Subsystem block are not lost. We can double−click on the Subsystem block to see its con-
tents. The Subsystem block replaces the inputs and outputs of the model with Inport and Outport blocks. These
blocks are described in Section 2.1, Chapter 2, Page 2−2, Introduction to Simulink with Engineering Applica-
tions, ISBN 0−9744239−7−1.

B−20 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Appendix C
Masked Subsystems

T
his appendix presents an overview of masked subsystems, and a step−by−step procedure to
create custom user interfaces, i.e., masks for Simulink subsystems.

C.1 Masks Defined


A mask is a custom user interface for a subsystem. A masked subsystem conceals the subsystem's
contents, and it appear to the user as an atomic block with its own icon and parameter dialog box.
However, a masked subsystem provides only graphical, not functional, grouping. We can create a
mask for any Simulink subsystem using the Mask Editor.

C.2 Advantages Using Masked Subsystems


A masked subsystem allows us to
1. Replace the parameter dialogs of a subsystem and its contents with a single parameter dialog
with its own block description, parameter prompts, and help text.
2. Replace a subsystem's standard icon with a custom icon that shows its purpose.
3. Prevent accidental modification of subsystems by concealing their contents behind a mask.
4. Placing a masked subsystem in a library. We can also mask S−Function and Model blocks.

C.3 Mask Features


Masks can include any of the following features:
Mask Icon − The mask icon replaces a subsystem's standard icon, i.e., it appears in a block
diagram in place of the standard icon for a subsystem block. Simulink uses
MATLAB code that we supply to draw the custom icon. We can use any
MATLAB drawing command in the icon code.
Mask Parameters − Masked subsystems allow us to define a set of user−specified parameters.
Simulink stores the values of these parameters in the mask workspace as the
value of a variable whose name you specify. These associated variables allow
us to link mask parameters to specific parameters of blocks inside a masked
subsystem.

Introduction to Stateflow® with Applications C−1


Copyright © Orchard Publications
Appendix C Masked Subsystems

Mask Parameter Dialog Box − The mask parameter dialog box contains controls that enable a
user to set the values of the mask's parameters and hence the
values of any internal parameters linked to the mask parameters.
The mask parameter dialog box replaces the subsystem's standard
parameter dialog box, i.e., clicking on the masked subsystem's
icon causes the mask dialog box to appear instead of the standard
parameter dialog box for a Subsystem block
Mask Initialization Code − The initialization code is MATLAB code that you specify and that
Simulink runs to initialize the masked subsystem at critical times,
such as model loading and the start of a simulation run (see
Initialization Pane). You can use the initialization code to set the
initial values of the masked subsystem's mask parameters.
Mask Workspace − Simulink associates a workspace with each masked subsystem that you
create. Simulink stores the current values of the subsystem's parameters in
the workspace as well as any variables created by the block's initialization
code and parameter callbacks. You can use model and mask workspace
variables to initialize a masked subsystem and to set the values of blocks
inside the masked subsystem, subject to the following rules.
A block parameter expression can refer only to variables defined in the mask workspaces of the
subsystem or nested subsystems that contain the block or in the model's workspace.
A valid reference to a variable defined on more than one level in the model hierarchy resolves to
the most local definition.
For example, let us suppose that model M contains masked subsystem A, which contains masked
subsystem B. Also, let us suppose that B refers to a variable x that exists in both A's and M's
workspaces. In this case, the reference resolves to the value in A's workspace.
A masked subsystem's initialization code can refer only to variables in its local workspace.
The mask workspace of a Model block is not visible to the model that it references. Any variables
used by the referenced model must resolve to workspaces defined in the referenced model or to
the base (i.e., the MATLAB) workspace.

C.4 Creating a Masked Subsystem


It is best to illustrate the creation of a masked subsystem with an example.

Example C.1
2
The Simulink model in Figure C.1 below implements the quadratic equation y = ax + bx + c .

C−2 Introduction to Stateflow® with Applications


Copyright © Orchard Publications
Creating a Masked Subsystem

Figure C.1. Simulink model for Example C.1


To create a subsystem, we encircle all blocks except the Unknown x and Display blocks, and from
the Edit drop menu we select Create Subsystem. The model now appears as shown in Figure C.2.

Figure C.2. The model for Example C.1 shown as a subsystem block
To see the contents of the Subsystem in Figure C.2, we double−click the Subsystem block and
now the model appears as shown in Figure C.3.

Introduction to Stateflow® with Applications C−3


Copyright © Orchard Publications
Appendix C Masked Subsystems

Figure C.3. The contents of the subsystem block


From the Edit drop menu we click on the Mask Subsystem and the Mask Editor window appears
as shown in Figure C.4. With the Icon tab selected as shown in Figure C.4, we position the text
cursor in the Drawing commands pane, and we enter the MATLAB command
image(imread(‘quadratic.jpg’));, we press Enter, and we click OK. It is assumed that this image
was previously created and saved in MATLAB’s saved files path. The Mask Editor now appears
as shown in Figure C.5.

C−4 Introduction to Stateflow® with Applications


Copyright © Orchard Publications
Creating a Masked Subsystem

Figure C.4. The Mask Editor window for Example c.1

Figure C.5. The masked subsystem with an imported image

Introduction to Stateflow® with Applications C−5


Copyright © Orchard Publications
Appendix C Masked Subsystems

We right−click on the Subsystem block in Figure C.5, and from the drop menu we select Edit
Mask. From the Mask Editor window which appears, we select the Parameters tab shown in Fig-
ure C.6 below.

Figure C.6. The Parameters tab for the Mask Editor window

We select the Add tool and the Mask Editor window now appears as shown in Figure C.7.

C−6 Introduction to Stateflow® with Applications


Copyright © Orchard Publications
Creating a Masked Subsystem

Figure C.7. The Mask Editor window for specifying the attributes of the masked parameters
The Mask Editor in Figure C.7 is used to specify the attributes of the masked parameters. The
Prompt column under Dialog parameters is used as a text label to describe the parameter. For
our example we enter Constant a, Constant b, and Constant c. The Variable column is used to
enter the names of the variables that store the parameter values. For this example we enter a, b,
and c as shown in Figure C.8.

Introduction to Stateflow® with Applications C−7


Copyright © Orchard Publications
Appendix C Masked Subsystems

Figure C.8. The Masked Editor with the equation constants specified
We right−click on the masked subsystem block shown in Figure C.5, Page C−5, and in the Func-
tion Block Parameters dialog box we enter the values 1, −5, and 6 for the variables a, b, and c
respectively, as shown in Figure C.9.

C−8 Introduction to Stateflow® with Applications


Copyright © Orchard Publications
Creating a Masked Subsystem

Figure C.9. The Function Block Parameters window with the values of the constants
With the variables defined as above, the masked subsystem implements the quadratic equation
2
y = x – 5x + 6

and the roots of this equation are x 1 = 2 and x 2 = 3 . Our model is tested for the first root as
shown in Figure C.10.

Figure C.10.
The Mask Editor also contains the Initialization tab that allows us to enter MATLAB commands
that initialize the masked subsystem, and the Documentation tab that lets us define or modify the
type description and help text for a masked subsystem. These tabs are shown in Figures C.11 and
C.12, and are not used in this example.

Introduction to Stateflow® with Applications C−9


Copyright © Orchard Publications
Appendix C Masked Subsystems

Figure C.11. The Initialization tab for the Mask Editor Window

Figure C.12. The Documentation tab for the Mask Editor window.

C−10 Introduction to Stateflow® with Applications


Copyright © Orchard Publications
References and Suggestions for Further Study
A. The following publications by The MathWorks, are highly recommended for further study. They
are available from The MathWorks, 3 Apple Hill Drive, Natick, MA, 01760,
www.mathworks.com.
1. Getting Started with MATLAB®

2. Using MATLAB®

3. Using MATLAB® Graphics

4. Using Simulink®
5. Sim Power Systems for Use with Simulink®
6. Fixed−Point Toolbox
7. Simulink® Fixed−Point
8. Real−Time Workshop
9. Signal Processing Toolbox
10. Getting Started with Signal Processing Blockset
10. Signal Processing Blockset
11. Control System Toolbox

12. Stateflow®
B. Other references indicated in text pages and footnotes throughout this text, are listed below.
1. Mathematics for Business, Science, and Technology, ISBN 0−9709511−0−8

2. Numerical Analysis Using MATLAB® and Spreadsheets, ISBN 0−9709511−1−6

3. Circuit Analysis I with MATLAB® Applications, ISBN 0−9709511−2−4

4. Circuit Analysis II with MATLAB® Applications, ISBN 0−9709511−5−9


5. Signals and Systems with MATLAB Computing and Simulink Modeling, ISBN 0-9744239-9-8

6. Electronic Devices and Amplifier Circuits with MATLAB® Applications, ISBN 0−9709511−7−5
7. Digital Circuit Analysis and Design with Simulink Modeling and Introduction to CPLDs and FPGAs,
ISBN 978-1-934404-05-8

Introduction to Stateflow®with Applications R−1


Copyright © Orchard Publications
8. Introduction to Simulink® with Engineering Applications, ISBN 0−9744239−7−1
9. Reference Data for Radio Engineers, ISBN 0−672−21218−8, Howard W. Sams & Co.
10.Electronic Engineers’ Handbook, ISBN 0−07−020981−2, McGraw−Hill
11. Network Analysis and Synthesis, L. Weinberg, McGraw−Hill
12. Elecrronic Filter Design Handbook, Williams and Taylor, McGraw−Hill

R−2 Introduction to Stateflow®with Applications


Copyright © Orchard Publications
Index
Symbols D exit in MATLAB A-2
exit action 1-1
% (percent) symbol in MATLAB A-2 data icon 3-6 exiting an Active State 7-11
data points in MATLAB A-14 explicit ordering 1-29
A data range 1-64 explicit ordering of parallel states 7-14
data range violation 1-58 exporting graphical functions
abs(z) in MATLAB A-23 Debug tool 1-48, 3-18 to Stateflow 5-17
action 1-1 decibels A-13
action table 2-1 decision 2-1, 2-2 F
actions 2-1 decision columns 2-1, 2-2
algebraic constrain blocks in Simulink B-18 decision coverage 4-2 figure window in MATLAB A-13
All Data (Current Chart) in Simulink 3-22 decomposition 1-26 finite state machine 1-10
angle(z) in MATLAB A-23 deconv in MATLAB A-6 Flip Block command in Simulink B-11
animation in Simulink 3-16 default A-12 for 4-18
animation delay 1-55 default color A-15 for loops 6-11
animation of Stateflow charts 1-47 default decision 2-2 format A-31
autoscale icon in Simulink B-12 default decision column 2-8 fplot in MATLAB A-27
axis in MATLAB A-16 default line in MATLAB A-15 function block parameters B-10
default marker in MATLAB A-15 function file in MATLAB A-26
B default transition 1-14, 7-16 function header 4-18
default transition 7-16 fzero in MATLAB A-26
backtracking behavior 6-14 Default Transition tool 1-37, 3-4
block error 1-67 default transitions 1-37 G
blocking 3-40 delay 3-18
box in Stateflow 8-1 demo in MATLAB A-2 Gain block in Simulink B-18
box in MATLAB A-12 description 2-1 graphical functions 5-1
box tool in Stateflow 8-1 Disable all field 3-24 graphical tool function 5-1
breakpoints 1-49, 3-19 Display block in Simulink B-18 grid in MATLAB A-12
Browse Data 1-50, 3-19 display formats in MATLAB A-31 gtext in MATLAB A-13
Build tool 1-60 dot multiplication operator in MATLAB A-20 guarding a transition 1-39
during action 1-14
C H
E
changing a box to a state 8-1 history junction 7-1
changing a state to a box 8-1 Editor window in MATLAB A-1 History Junction tool 7-1
Chart Entry 1-49, 3-19 Editor/Debugger in MATLAB A-1
Chart Entry 3-19 electric field strength example 3-40 I
Classic Machine in Stateflow 9-4 element-by-element division and
clc in MATLAB A-2 exponentiation in MATLAB A-21 If 4-18
clear in MATLAB A-2 element-by-element multiplication if-then-else 6-13
code generation errors 1-60 in MATLAB A-18, A-20 imag(z) in MATLAB A-23
Coder Options 1-48, 3-18 eM functions 3-4 implicit ordering 1-29
column vector A-19 Embedded MATLAB Editor 3-7 increments between points in MATLAB A-14
command screen in MATLAB A-1 Embedded MATLAB function 3-1 inner transition 7-22
Command Window in MATLAB A-1 Embedded MATLAB Function tool 3-3 input argument 3-6
commas in MATLAB A-8 Entering a State 7-9
comment line in MATLAB A-2 entry action 1-1, 1-14 L
Commonly Used Blocks in Simulink B-7 eps in MATLAB A-22
complex conjugate A-4 Erlang 3-40 Launch Model Explorer tool 1-68
complex numbers in MATLAB A-3 Erlang B 3-40 lims = in MATLAB A-27
condition 1-2, 1-14, 7-18 Erlang B model 3-41 linspace in MATLAB A-14
condition action 7-18 Erlang C 3-40 local data 9-7
condition table 2-1 Erlang C model 3-41 log in MATLAB A-13
conditions 2-1 error checking options 1-59 log(x) A-13
configuration parameters 1-46, 3-15, B-12 event 1-2, 1-14, 7-17 log10(x) in MATLAB A-13
Connective Junction 6-1 event driven systems 1-2 log2(x) in MATLAB A-13
Contents pane 3-6, B-7 event properties dialog box 1-44 loglog in MATLAB A-13
Continue button 1-56, 3-21 event trigger 7-17 loglog(x,y) in MATLAB A-13
Continue Debugging 3-33 exclusive (OR) state 1-12
conv in MATLAB A-6 executing an Active State 7-10 M
Creating a Mealy Chart 9-6 execution order 1-12, 1-27
Creating a Moore Chart 9-10 execution Order for Parallel States 7-13 mask C-1

IN1
Mask Editor C-1 S U
mask icon C-1
mask parameters C-1 Scope block in Simulink B-12 User specified state/transition
masked subsystem 1-8, C-1 script file in MATLAB A-26 execution order 1-30
Math Operations B-11 semantics 9-7 using boxes in Stateflow 8-1
MATLAB Demos A-2 semicolons in MATLAB A-8
MATLAB’s Editor/Debugger A-1 semilogx in MATLAB A-12 V
matrix multiplication in MATLAB A-19 semilogy in MATLAB A-12
Mealy machine 9-1 sfprj 1-50 valid transitions 7-18
Mealy machines in Stateflow 9-4 sfprj 3-20 Vending Machine example with a
mesh(x,y,z) in MATLAB A-17 sfun 1-48 Mealy state machine 9-8
meshgrid(x,y) in MATLAB A-17 sfun 3-18
m-file in MATLAB A-1, A-26 signature label 2-17 W
Model Coverage for an Embedded signature return values 3-45
MATLAB function 4-1 simout To Workspace block B-13 while 4-18
Model Explorer 3-5 simulation diagnostics 1-66
Model Explorer tool 5-6 Simulation drop menu B-12 X
Model Hierarchy pane 3-6 simulation start icon B-12
Modified Condition Decision Coverage 4-18 Simulation Target 1-47, 3-16 xlabel in MATLAB A-12
Moore machine 9-3 Simulink icon B-7
Moore machines in Stateflow 9-4 Simulink Library Browser B-8 Y
multiple connective junctions 6-2 Sinks library B-18
Start button 3-21 ylabel in MATLAB A-12
N Start command button 3-21
Start simulation B-12
NaN in MATLAB A-26 Start Simulation tool 3-27
state 1-1
O state action 1-14
state entry 1-49
observer state 1-28 state inconsistency error 1-58
order of execution 1-27 State tool 1-24
output argument 3-6 Stateflow Builder 1-60
Stateflow Debugging 1-48
P Stateflow Debugging 3-18
Stateflow Editor 1-24
Parallel (AND) state 1-12 Stateflow Editor chart 1-12
parser errors 1-60 Stateflow Target Builder 3-16
Pause button 3-21 State-Space block B-12
plot in MATLAB A-10, A-15 Step In tool 3-27
plot3 in MATLAB A-15 Step Out tool 3-30
Poisson 3-40 Step tool 3-27
Poisson model 3-41 Stop button 3-21
polar plot in MATLAB A-23, A-24 string in MATLAB A-16
poly in MATLAB A-4 subchart 5-10
polyder in MATLAB A-7 subcharted state 5-10
Polynomial construction from known subplot(m,n,p) in MATLAB A-18
roots in MATLAB A-4 switch 4-18
polyval in MATLAB A-6
power density example 3-40 T
progress bar in Simulink 3-24
Target Builder 1-48, 3-18
Q text A-14
title(‘string’) in MATLAB A-12
quit in MATLAB A-2 Traffic Light example with a Moore
state machine 9-14
R transition action 1-1, 7-18
transition connections 7-19
real(z) in MATLAB A-23 transitions 7-15
roots in MATLAB A-3 Tree Pane B-7
roots of polynomials in MATLAB A-3 trigger port 1-42
round(n) in MATLAB A-24 Truth Table block 2-1
row vector in MATLAB A-3, A-19
running Simulink B-7
run-time activities 3-19

IN2

You might also like