Академический Документы
Профессиональный Документы
Культура Документы
with Applications
Steven T. Karris
Orchard Publications
www.orchardpublications.com
Introduction to Stateflow
with 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 institutions, the most recent at UC Berkeley, CA.
Orchard Publications
Visit us on the Internet
www.orchardpublications.com
or email us: info@orchardpublications.com
1-9
934404-0
08-9
9
ISBN-13: 978-1
934404-0
08-X
X
ISBN-10: 1-9
$60.00 U.S.A.
Introduction to Stateflow
with Applications
Steven T. Karris
Orchard Publications
www.orchardpublications.com
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 stepbystep 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 ifthenelse 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 stepbystep 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 realworld 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.2
1.3
1.4
1.5
1.6
1.7
31
21
11
41
Graphical Functions
51
Connective Junctions
6.1
6.2
6.3
6.4
6.5
6.6
6.7
6.8
71
Boxes in Stateflow
8.1
8.2
8.3
8.4
ii
61
81
Creating a Box.......................................................................................................... 81
Changing a State to a Box ....................................................................................... 82
Using Boxes in Stateflow.......................................................................................... 84
Summary .................................................................................................................. 86
91
Introduction to MATLAB
A.1
A.2
A.3
A.4
A.5
A.6
A.7
A.8
A.9
A.10
A.11
B
C
Introduction to Simulink
B.1
B.2
B1
Masked Subsystems
C.1
C.2
C.3
C.4
A1
C1
References
R1
Index
IN1
iii
NOTES:
iv
Chapter 1
The Stateflow Chart
his chapter 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 stepbystep procedures.
Low
Transition
High
Off
Figure 1.1. State transition diagram for a typical finite state machine
11
State A
(Off)
1
0
.....
0
State B
(Low)
0
1
.....
0
State C
(Medium)
0
0
.....
0
State D
(High)
0
0
.....
1
A condition is a Boolean expression that can be true (logic 1) or false (logic 0). In Stateflow, conditions are enclosed in square brackets.
12
The leftmost 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 0974423971, or to the Simulink
documentation.
Figure 1.3. The passing maneuver state in the Signal Builder block of Figure 1.2
13
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
14
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.
15
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 (2D) block whose inputs are the vector 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 MATLABs 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 leverarm 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 transfers 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.
*
16
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
17
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 1D interpolation for the gear ratios in the transmission system. A typical fourspeed manual transmission has the following gear ratios:
Gear
Ratio
1st
2.97:1
2nd
2.07:1
3rd
1.43:1
4th
1.00:1
Reverse
3.28:1
18
Figure 1.15. Function Block Parameters for the LookUp Table block in Figure 1.15
The vehicle subsystem in Figure 1.2 is another masked subsystem. As before, to view the components 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 differential ratio of 3.45, we obtain 2.97 x 3.45 = 10.25 revolutions for every revolution the wheels make.
19
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 userdefined function block and represents 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 Figure 1.17 below. We observe that includes a FunctionCall 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 Lookup 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,
ISBN13: 9780974423999. It is very useful in deriving the Fourier transform of the unit step function.
For an example, please refer to Page 1134, Introduction to Simulink with Engineering Applications, ISBN13: 9780
974423971
110
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 operation and are normally referred to as Exclusive (OR) states.
111
6. Simulate the
Chart
5. Choose triggering
method
7. Debug the
Chart
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 balance 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 MathWorks Stateflow documentation.
The Stateflow Editor chart in Figure 1.20 contains six Exclusive (OR) states represented graphically 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.
112
113
114
Figure 1.22. The components of the Financial Operations subsystem in Figure 1.21
115
We will now create the model with the following stepbystep 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
window shown in Figure 1.25.
116
b. In the Simulink Library Browser window shown in Figure 1.25 we click the Create a
new model icon
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
117
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.
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.
118
f. We doubleclick the Signal Builder block and the waveform shown in Figure 1.29
appears.
119
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 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 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
120
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.
121
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 falling edge of a square wave signal.
k. To define the input of the Stateflow Chart block in Figure 1.28, we doubleclick 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 EndingBalance 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 EndingBalance at breakpoints during simulation.
122
Figure 1.34. The Data window dialog box for defining the input and output to the Stateflow Chart
123
Figure 1.35. Defined input and output for the Stateflow Chart
124
Figure 1.37. The Stateflow Editor window with the first exclusive (OR) state
125
* We can change the text size by choosing the Set Font Size from the Edit drop menu.
126
127
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.
128
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 execution order will be based on explicit ordering. We will do this with the next step.
129
h. We rightclick inside the Overdraft parallel state within the TransferOn main state to call
the state priorities popup 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.
130
Figure 1.43. The Chart dialog box for specifying User specified state/transition execution order
i. We rightclick 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.
131
Figure 1.44. The submenu for User specified state/transition execution order
132
Figure 1.45. The addition of On and Off exclusive (OR) states inside the Overdraft and Savings parallel states
133
When Executed
Frequency of Execution
Entry
During
Exit
b. We leftclick inside the TransferOff state after the last letter of its name to cause a blinking 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.
c. We need to add a during action for DollarValue in the third parallel state within the TransferOn state, that is, a Boolean expression to specify whether no Savings and no Overdraft
134
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 Overdraft has occurred, or both Overdraft and Savings have occurred. The Stateflow Editor
now appears as shown in Figure 1.47.
135
136
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.
137
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
filledin 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.
138
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.
139
Occurrence
TransferOff to TransferOn
TransferOn to TransferOff
Guarding
Specify an edgetriggered event
Savings.On to Savings.Off
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
Savings.Off to Savings.On
Savings.On to Savings.Off
* 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.
140
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 nongraphical 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.
141
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.
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.
142
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 TRANSFERS. 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 window 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 trigger, or using one Stateflow chart to activate another. As weve 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 second edgetriggered 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.
143
b. We define the CLOCK event by doubleclicking 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 dialog box now appears as shown in Figure 1.56. We click OK to accept these settings.
144
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.
145
146
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. 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 Stateflow 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.
147
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.
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.
148
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 runtime activities. Breakpoints that can set are
listed below.
Breakpoint
Description
Chart Entry
Event Broadcasta
State Entry
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.
149
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 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
Window.
150
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 animation 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.
151
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.
152
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>>
153
154
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 124, this is the maximum value and represents the condition where Overdraft On and Savings On
are both active.
155
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.
156
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 146, 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.
157
158
159
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 doubleclick
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 doubleclick
#21, Stateflow highlights the Overdraft state in the Stateflow Editor chart as shown in Figure 1.74. Likewise, if we doubleclick #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 successfully without parser or code generation errors as shown in Figure 1.75.
160
161
162
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 DollarValue state by adding 1 to it, that is, it now reads as
during: Payments=in(Overdraft.On)+in(Savings.On) +1;
163
164
We save the Stateflow Editor chart, we again build the chart, and the Stateflow Builder
window in Figure 1.78 reports no errors.
165
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 repeatedly, and after some time simulation pauses and Stateflow generates the Simulation Diagnostics window shown in Figure 1.79.
166
To isolate the problem, we double click the Block error red bullet in the Simulation Diagnostics window in Figure 1.79, and this opens the Financial Operations subsystem shown
in Figure 1.80.
167
Figure 1.80. Error indication in the Multiport Switch block of the Financial Operations subsystem
168
169
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 activated, the default transition makes the chart active. We usually use a clock signal to wake up
the chart.
170
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 syntax 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 Stateflow charts is as follows:
1. Define the Interface to Simulink
a. Invoke MATLAB and from the main window select Simulink by clicking on the Simulink icon
b. In the Simulink Library Browser window click the Create a new model icon
observe that a new empty model appears.
and
c. From the Simulink Library Browser window click and drag the Simulink blocks comprising 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 doubleclick 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 Stateflowwith Applications
Copyright Orchard Publications
171
172
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 rightclicking 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 exclusive 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 reenter the inactive phase. The three basic state actions
are listed in Table 1.3, Page 134.
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 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, 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 PowerOn state is formed. We follow the same procedure to create a transition from the PowerOn 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. Normally, we declare that the default states are Off. To add the default transitions, we left
173
174
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 doubleclick 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. Animation 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 window 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 runtime activities. We set breakpoints as
follows:
In the Stateflow Debugging window we check Chart Entry and State Entry as breakpoints. 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 Command Window.
175
176
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 doubleclick 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 Editor 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 simulation pauses and Stateflow generates the Simulation Diagnostics window.
To isolate the problem, we double click the Block error red bullet in the Simulation Diagnostics 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 readonly.
177
178
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 productivity 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
0.00
0.05
Second Shift ON
The number of the Boards produced is
lowered by the productivity multiplier 0.10
0.10
Graveyard Shift ON
The number of the Boards produced is
lowered by the productivity multiplier 0.02
0.02
179
and the summation of those changes will be performed with an Integrator block with an
assumed initial value 2,000, that is,
boards ( t ) =
t ( boards_change ) dt + 2000
0
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 untitled 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.
180
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 interconnecting lines, and we label it as Manufacturing Plant. We doubleclick 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.
181
We stretch the window of the model above and we add the following blocks:
182
We doubleclick the Signal Builder block and the waveform shown below appears.
183
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
184
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.
185
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 183, we double
click this block, and we observe that the Stateflow Editor window appears as shown below.
186
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.
187
In the Simulink model above, we doubleclick the Shift Controller block and the Stateflow Editor
window appears as shown below.
188
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.
189
* We can change the text size by choosing the Set Font Size from the Edit drop menu.
190
In the Stateflow Editor window above we rightclick inside the AddShiftOn state and from the
popup menu below we select Decomposition> Parallel (AND).
191
192
We now need to add an observer state whose purpose will be to monitor the status of the Overtime, Second, and Graveyard states.
and we place another parallel (AND) substate within the
We leftclick the State tool
AddShiftOn state under the Overtime, Second, and Graveyard states. We name this substate
BoardNumber and the Stateflow Editor appears as shown below.
193
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 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 will do this with
the next step.
We rightclick inside the Overtime parallel state within the AddShiftOn exclusive (OR) main
state to call the state priorities popup menu below, we select Execution Order.
194
In the Chart window that appears below we check the User specified state/transition execution order field as shown. We click OK to accept these settings.
195
We rightclick 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.
196
197
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 reenter the inactive phase. For convenience, the
three basic state actions are repeated in the table below.
Type
When Executed
Frequency of Execution
Entry
During
Exit
We leftclick 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
198
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
199
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.
1100
Following the procedure above we add transitions between the Off and On states for the Overtime, Second, and Graveyard states, and the Stateflow Editor window appears as shown below.
1101
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 leftclick 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 filledin 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.
1102
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 the table
below.
1103
Occurrence
Guarding
AddShiftOff to AddShiftOn
AddShiftOn to AddShiftOff
Overtime.Off to Overtime.On
Overtime.On to Overtime.Off
Second.Off to Second.On
Second.On to Second.Off
Graveyard.Off to Graveyard.On
Graveyard.On to Graveyard.Off
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 transitions in Second and Graveyard.
Transition
Condition
Overtime.On to Overtime.Off
Second.On to Second.Off
Second.Off to Second.On
Graveyard.On to Graveyard.Off
Graveyard.Off to Graveyard.On
* 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.
1104
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
nongraphical 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 window above and this opens the Event properties dialog window shown below.
1105
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.
1106
The next step is to associate the input event SWITCH with the transitions. We doubleclick 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.
1107
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 trigger, or using one Stateflow chart to activate another. As weve 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 edgetriggered input event
which we will name CLOCK, to wake up the Stateflow chart.
We define the CLOCK event by doubleclicking 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.
1108
We connect the Mux block output to the trigger port of the Stateflow chart, we connect the output 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.
1109
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.
1110
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.
1111
To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the
debugger to pause simulation during runtime activities. Breakpoints that can set are listed
below.
Breakpoint
Description
Chart Entry
Event Broadcasta
State Entry
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 breakpoints and this window now appears as shown below.
1112
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 Window.
1113
1114
1115
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.
1116
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>>
* We recall from Pages 179, 188 and 199 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.
1117
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 indicated 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 inactive state as shown below.
1118
1119
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.
1120
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 seconds 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.
1121
1122
Chapter 2
The Stateflow Truth Table
his chapter describes the basic workflow for building Stateflow truth tables to form decisionmaking 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.
DN
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 Stateflowwith Applications
Copyright Orchard Publications
21
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-
22
Call directly to a
Simulink model
Call from a
Stateflow chart
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 conversion is shown in Table 2.2. We will refer to this table as the generic truth table for this conversion.
Introduction to Stateflowwith Applications
Copyright Orchard Publications
23
S1
S2
S3
S4
S5
S6
S7
S8
S9
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
1
1
Outputs
B
C
0
0
0
0
1
1
1
1
0
0
0
1
0
1
0
1
0
1
0
1
0
0
1
1
0
0
1
1
0
0
(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 Simulink Modeling and Introduction to CPLDs and FPGAs, ISBN 9781934404058.
24
25
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.
26
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 column. 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 clicking the Append Row tool
times.
27
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 decision 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 dont care condition. 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.
28
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.
29
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
210
Figure 2.11. Defined inputs and outputs in the Ports and Data Manager window for Example 2.1
* The sequence in which the inputs and outputs are displayed is immaterial. The sequence can be rearranged by clicking
Port in the Contents pane.
211
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 MATLABs 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 MATLABs Command prompt we enter
S5=0;* S9=1;
* We set the value of S5 to 0 because only one of the inputs can be set to 1 at any time.
212
While the model of Figure 2.13 works well, it is not the most elegant design. We can add a Multiport 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 Stateflowwith Applications
Copyright Orchard Publications
213
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 Configuration Parameters, we set the Solver Options Type field to Variablestep, 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.
214
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.
215
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
Figure 2.17. Adding three more Truth Table rectangles inside the Stateflow Editor window
216
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.
c. We rightclick on the first truth table function t1 in Figure 2.18 above, and from the popup 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.
217
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.
218
Label
Description
Document Link
Description
Function name (read only)
When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
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
The signature label is specified
Textual description and comments
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 diagram 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 downwardpointing 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 values 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 Stateflowwith Applications
Copyright Orchard Publications
219
220
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 ttableB, 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 column. 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.
221
222
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 Stateflow 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 MATLAB 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 column. 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 Stateflowwith Applications
Copyright Orchard Publications
223
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. Accordingly, 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
224
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
225
Figure 2.30. The Condition Table with added rows and columns
226
k. In the Condition column of the Condition Table each condition that we enter must be
zero (false) or nonzero (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 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 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 decision and it is used in some applications as a dont care decision.
227
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
228
Figure 2.33. The programmed Condition Table and Action Table for ttableB
229
Figure 2.34. The programmed Condition Table and Action Table for ttableC
230
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.
231
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.
232
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 220, we doubleclick on the
ttableB, ttableC, and ttableD functions and in the truth table editors we run the diagnostics using the Run Diagnostics tool
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 MATLABs command prompt we enter:
S0=0; S1=0; S2=0; S3=0; S4=0; S5=0; S6=0; S7=0; S8=0; S9=1;
table
table
table
table
table
table
table
table
ttableA
ttableA
ttableB
ttableB
ttableC
ttableC
ttableD
ttableD
entered
exited
entered
exited
entered
exited
entered
exited
233
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 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. The
breakpoint pauses execution during simulation so that we can debug each execution step.
We begin by rightclicking 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.
234
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.
235
236
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 Figure 2.45.
237
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.
238
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 execution 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.
239
240
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.
241
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.
242
Figure 2.53. Adding a Truth Table rectangle into the Stateflow Truth Table Editor
The generic truth table shown as Table 2.2, Page 24, 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
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.
243
Figure 2.54. Adding three more Truth Table rectangles into the Stateflow Truth Table Editor
244
245
Label
Description
Document Link
Description
Function name (read only)
When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
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
The signature lavel is specified
Textual description and comments
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, ttableCem, and ttableDem. 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 ttableAem, ttableBem, ttableCem, and ttableDem, from the default transition 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 question 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.
246
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 values 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 association 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.
247
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 column. 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.
248
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.
249
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 rectangle 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 Embedded 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 column. 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.
250
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 columns by clicking the Append Row tool
tool
10 times. Column D11 is the default decision column. The truth table editor
now appears as shown in Figure 2.68.
251
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
252
Figure 2.67. Using the Stateflow Chart block to program the Truth Table
253
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.
254
k. In the Condition column of the Condition Table shown in Figure 2.69, each condition
that we enter must be zero (false) or nonzero (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.69 above. 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 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
255
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
256
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 message, and FINAL: eml.extrinsic(truth table ttableAem exited);
The Action Table for truth table ttableAem appears as shown in Figure 2.70
The entries for the truth table editors for truth tables ttableBem, ttableCem, and ttableDem, are shown in Figures 2.71, 2.72, and 2.73 respectively.
257
Figure 2.71. The programmed Condition Table and Action Table for ttableBem
258
Figure 2.72. The programmed Condition Table and Action Table for ttableCem
259
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;
260
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 execution step.
261
262
Summary
5. We specify properties by rightclicking 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 terminate 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 doubleclick 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 doubleclick 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.
263
264
Outputs
C IN
C OUT
0
0
0
0
1
1
1
1
0
0
1
1
0
0
1
1
0
1
0
1
0
1
0
1
0
1
1
0
1
0
0
1
0
0
0
1
0
1
1
1
Exercises
Create a Simulink model to implement the truth table of a binary fulladder calling truth
table functions from a Stateflow chart.
265
The Simulink Library Browser window opens as shown in Figure 2.3, Page 25. 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.
The truth table block above is empty and we must program it to specify its function. We do
this with the following steps:
266
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 column. 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
Append Column tool
8 times.
267
268
e. In the Action Table we make the entries shown in the table below.
269
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.
270
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.
271
j. The Truth Table block in the Simulink model appears as shown below.
272
k. From the Simulink Library Browser we drag into the Simulink model above eleven Constant 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.
273
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.
274
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.
275
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.
276
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 typein 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.
277
d. We specify the properties of the Truth Table functions with the following steps:
1. We rightclick once* the first truth table function rectangle truthtable. The pop-up
menu shown below appears, and we select Properties from it.
If we rightclick twice, the truth table editor will appear. We will discuss this editor shortly.
278
Field
Name
Breakpoints
Function Inline Option
Label
Description
Document Link
Description
Function name (read only)
When Function Call is checked, it sets a breakpoint to pause execution
during simulation when the truth table function is called.
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
The signature lavel is specified
Textual description and comments
A URL address or a MATLAB command may be entered
279
* We can call truth table functions from the actions of any state or transition. We can also call truth tables from other functions 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.
280
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
281
This can be verified by rightclicking 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.
282
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 signature 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 280, is empty and
therefore we need to program it by specifying its behavior. We do this with the following
steps:
283
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 fulladder 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.
284
3. In the Condition column of the Condition Table each condition that we enter must
be zero (false) or nonzero (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 conditions 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.
285
The entries in the Description column of the Action Table are optional but are recommended 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 message 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 MATLABs Command 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 TruthTable editor below which is repeated for convenience.
286
From the Settings drop menu we select the Stateflow Classic Language.
Introduction to Stateflowwith Applications
Copyright Orchard Publications
287
288
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 Diagnostics tool
The Stateflow Builder window below displays a message that no errors were found.
289
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.
290
7. The waveforms of the Pulse Generator blocks and the waveforms for Sum and Cout
are shown below.
291
292
Chapter 3
Embedded MATLAB Functions in Stateflow Charts
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 MATLAB functions in Stateflow Charts.
Figure 3.1. Example of a Simulink model with a Stateflow Chart that contains an Embedded MATLAB function
31
In the model of Figure 3.2 we doubleclick the Stateflow Chart block to open the Stateflow Editor that appears in Figure 3.3.
* For the description of this block please refer to Introduction to Simulink with Engineering Applications, ISBN 978-09744239-7-5 or the online Simulink documentation.
32
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)
where the return_value and each argument can be a scalar, vector, or matrix of values. A matrix
is a twodimensional 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 flashing text cursor where we enter the function name, indicates that this is an Embedded MATLAB
function.
Introduction to Stateflowwith Applications
Copyright Orchard Publications
33
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.
34
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 signature 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
35
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.
36
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 function 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.
37
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.
38
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
add the following data:
Name
Scope
Size
invalue
3,3
det
Output to Simulink
inv
Output to Simulink
39
Our Simulink model is now built and appears as shown in Figure 3.13 after connecting the Constant 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.
310
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
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 Stateflowwith Applications
Copyright Orchard Publications
311
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.
312
This script is entered into the Embedded MATLAB Editor window as shown in Figure 3.17.
313
Figure 3.17. The Embedded MATLAB Editor window with the complete script for the function invmat
314
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.
* This topic is discussed in Numerical Analysis Using MATLAB and Excel, ISBN-13: 978-1-934404-03-4
315
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 Stateflow 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.
316
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
317
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
318
Description
Chart Entry
Event Broadcasta
State Entry
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.
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:
319
320
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 button. We observe that Stateflow displays a Block Error message for the Constant block as indicated 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 Stateflowwith Applications
Copyright Orchard Publications
321
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.
322
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
323
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.
324
Figure 3.31. The Default Transition highlighted on and off during simulation execution
325
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 procedure is illustrated by simulating and debugging the detmat function during run-time conditions
as follows:
326
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 weve 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 weve set, and this is indicated by a small green arrow
ure 3.37.
327
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
328
Figure 3.37. Green arrow in line 6 indicating that execution has reached the breakpoint that weve set
Figure 3.38. Using the Step tool to advance execution one line
329
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.
330
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>>
331
Figure 3.41. Clicking the Step tool one more time causes execution to advance to line 8
332
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.
333
Figure 3.44. Model with computed values of determinant and inverse of the matrix at completion of simulation
334
Summary
3.5 Summary
Embedded MATLAB functions insert the powerful features of MATLAB into Stateflow
Charts.
The Embedded MATLAB RunTime 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 capability 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 MATLAB 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 twodimensional 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
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 Stateflowwith Applications
Copyright Orchard Publications
335
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 doubleclick 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
336
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 runtime activities. Breakpoints that can set are
listed below.
Breakpoint
Description
Chart Entry
Event Broadcasta
State Entry
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.
337
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 indicating that weve 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 breakpoint that weve set, and this is indicated by a small green arrow
338
Summary
the first line of the subfunction that weve 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 variable 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.
339
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 coordinates 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 multiplier" 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
340
P = 1e
n!
n=0
n
a n!
P = ( a c! )
n=0
c
n
P = a c c( c a)
a n! + a c c ( c a )
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 values 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 UserDefined Function Library.
341
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 Constant 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.
342
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 function as
PowerDensity=dipoleP(value1,value2)
where the return_value and each argument can be a scalar, vector, or matrix of values. A
matrix is a twodimensional 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.
343
In the Stateflow Editor window above, 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
{Power = dipoleP(invalue1,invalue2);
Field = dipoleE(invalue1,invalue2);}
344
In the Embedded MATLAB Editor above, we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.
345
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 argument 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.
346
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 argument ElectricField. By default, both are scalars of type double.
Introduction to Stateflowwith Applications
Copyright Orchard Publications
347
Size
invalue1
invalue2
Power
Output to Simulink
Field
Output to Simulink
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-
348
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.
%
349
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 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 Calling MATLAB Functions in the Embedded MATLAB 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.
350
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.
351
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 doubleclick the Stateflow chart in the Simulink model
above, 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 shown below, and we make changes if necessary.
We click OK to accept these values.
352
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 previous 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.
353
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.
354
We can set the animation speed from the Stateflow Editor window below.
355
To observe the behavior of our Stateflow chart in slow motion, we will set breakpoints in the
debugger to pause simulation during runtime activities. Breakpoints that can set in the Stateflow Debugging window are listed below.
Breakpoint
Description
Chart Entry
Event Broadcasta
State Entry
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 breakpoints and this window now appears as shown below.
356
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 breakpoint.
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
Window.
357
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 Command Window and we enter the values of P t and R as
Pt=2; R=1000;
358
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.
359
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>>
360
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 Stateflow Editor window appears highlighted on and off during the simulation as shown below.
361
362
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-
363
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 weve 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
weve set, and this is indicated by a small green arrow
364
365
If we click again the Step tool, execution will advance to line 10, and we will not see the execution 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.
366
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.
367
368
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 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>> Power
Power =
2.6101e-007
debug>>
*
369
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.
370
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 Stateflowwith Applications
Copyright Orchard Publications
371
372
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.
373
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 function as
Poissonout=Poisson(value1,value2)
the second as
ErlangBout=ErlangB(value1,value2)
where the return_value and each argument can be a scalar, vector, or matrix of values. A
matrix is a twodimensional 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.
374
In the Stateflow Editor window above, 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
{PoissonProb = Poisson(invalue1,invalue2);
ErlangBProp = ErlangB(invalue1,invalue2);
ErlangCProp = ErlangC(invalue1,invalue2);}
375
376
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 argument Poissonout. By default, both are scalars of type double.
377
In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.
378
In the Embedded MATLAB Editor above we select Tools>Model Explorer, and the Model
Explorer window appears as shown below.
379
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 argument 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
the following data:
Name
380
Size
invalue1
invalue2
PoissonProb
Output to Simulink
ErlangBProb
Output to Simulink
ErlangCProb
Output to Simulink
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 Stateflow 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.
381
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 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 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.
%
382
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 specified 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 Calling 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=1exp(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.
383
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.
384
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).*(TE)))./((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.
385
we issue the simulation command, and Simulink responds with the following messages:
386
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.
387
388
We interconnect the blocks as shown below, in MATLABs 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.
389
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.
390
391
392
Chapter 4
Model Coverage for Embedded MATLAB Functions
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.
Figure 4.1. Example with a Stateflow Chart that contains a Model Coverage for Embedded MATLAB function
41
IS
From electric circuit* theory, we know that the resonant frequency f 0 is found from the relation
1
f 0 = -------------------
2 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 Figure 4.3.
* For a detailed discussion on parallel resonant frequency, please refer to Circuit Analysis II with MATLAB Applications,
ISBN 0970951159.
The value of the resistor R is independent of the frequency.
42
In Figure 4.3 we doubleclick 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
type the labels shown in Figure 4.4.
, and we
43
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 doubleclick 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 woutput 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 valueC as shown in Figure 4.7. Initially, there are no values indicated for these variables under the
Size column. We doubleclick 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
text editor.
44
Figure 4.6. The Model Explorer for Example 4.1 showing the input and outputs of the frequency function
45
Figure 4.7. The Model Explorer for Example 4.1 showing the Chart variables
The Embedded MATLAB Editor window now appears as shown in Figure 4.8.
46
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 frequency 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
47
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 (perpendicular) 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
48
In Figure 4.12 we doubleclick 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
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 during 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.
49
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 highlighted in the Model Hierarchy pane (left) the variable m2 is shown in the Contents pane.
410
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.
411
412
The Embedded MATLAB Editor window for function m1 now appears as shown in Figure 4.18.
413
Figure 4.18. The Embedded MATLAB Editor for the slope1 function
414
Figure 4.19. The Embedded MATLAB Editor for the slope2 function
415
With the Command window and the model in Figure 4.20 both visible, we start simulation by
clicking the Start Simulation tool
Figure 4.21. The values of m1 and m2 after the simulation command execution
416
Figure 4.22. The model for Example 4.2 with different values of m1 and m2
417
* 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.
418
2.
In Example 4.1 the values of the radian frequency were displayed in a rowwise vector. Can
you think of a method that these values will be displayed in a columnwise vector as shown
below?
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.
419
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 0974423971.
420
In the model above, we doubleclick 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
421
422
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.
423
424
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
425
426
Chapter 5
Graphical Functions
his chapter 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.
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.
51
52
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 arguments 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 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 function 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.
53
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
Z =
R + ( XL XC )
We begin by typing sfnew at the MATLAB Command prompt, and Simulink returns the Stateflow Chart shown in Figure 5.5.
54
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.
55
Figure 5.7. The Stateflow Chart Editor with the graphical function
56
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.
57
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.
58
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
59
To view the contents of the Stateflow Editor, we double click the Chart block and Simulink displays 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.
510
Subcharts
Figure 5.13. The Stateflow Editor for the model in Figure 5.12
511
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 output y corresponding to the inputs values x from 0 to 6 in steps of 1 for the function
5
y = 3x 2x + 6x 8
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.
512
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
area as shown in Figure 5.17 below.
in the empty
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.
513
514
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 interconnected.
* 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.
515
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
516
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
517
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.
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.
518
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 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.
519
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.
520
Figure 5.29. The Chart Properties dialog box for selecting Export Chart Level Functions
521
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.
522
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 MATLABs 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.
523
Figure 5.33. The Chart Properties dialog box for selecting Export Chart Level Functions
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 Figure 5.35. The flow diagram must include a default transition with a terminating junction.
524
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.
525
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.
526
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.
527
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.
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.
528
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 )
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 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 function 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 center.
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 Subcharted. 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.
529
530
531
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.
532
in the empty
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.
533
534
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
, in
row selected, under the Size column we enter 1,6.* We click Add again, we select
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.
535
The Simulink model is shown in Figure 5.22 with the blocks interconnected.
536
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
537
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 .
538
Chapter 6
Connective Junctions
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 ifthenelse constructs without the use of states.
61
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 location in the drawing area.
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 connective junction to a new location, we click and we drag it to the new position.
62
Figure 6.3.
63
Figure 6.4. Pop-up menu for changing the size of a connective junction
64
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.
65
Size 7
Size 10
Size 7
66
Description
Parent
Parent of this state; readonly; click the hypertext link to bring the
parent to the foreground.
Description
Textual description/comment.
Document Link
Figure 6.8. The general label format for a transition entering a state
67
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 statetostate transition (S1 to S2) is found.
5. State S1 is exited and this includes the execution of S1's exit action.
68
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 destination state follows based on which of the conditions [c1], [c2], or [c3] is true. If none of the conditions 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.*
69
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 selfloop.
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
selfloop transition (transition from state to itself).
Let us consider the flow diagram notations in Figure 6.12.
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 selfloop transition, the system exits and reenters state A, and executes action a2.
In the equivalent representation on the right, the use of a connective junction makes it unnecessary to specify the implied condition [~c1] explicitly.
610
This flow diagram shows a combination of flow diagram notation and state transition notation.
Selfloop 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
selfloop 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 selfloop 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 completes 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.
611
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 0970951175.
612
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 connective 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 IFThenElse decision construct.
Let us consider the flow diagram notations in Figure 6.17.
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,
613
We assume that state A is active, and conditions [c1], [c2], and [c3] are true. The sequence of
operation is as follows:
614
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.
615
616
It is assumed that State A.A1 is initially active, event e_1 occurs and awakens the Stateflow diagram, and Condition [c_1] is true. Describe the sequence of operation in a hierarchical order.
617
618
Chapter 7
History Junctions and Transitions
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 presented are the same or similar to those included in the Stateflow documentation.
2. We move the cursor into the diagram editor.The cursor takes on the shape of a history junction 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 substates, and can be contained by other states referred to as superstates.
71
Figure 7.1. The Stateflow Editor window with the mouse pointer near the History Junction tool
72
Figure 7.3. Popup menu for changing the size of a connective junction
73
Figure 7.4. Popup menu and submenu for selecting connective junction sizes
We can change a history junction to a connective junction and vice versa from the popup menu
above by selecting Type. The popup menu and the resulting submenu then appear as shown in
Figure 7.5.
74
Figure 7.5. Converting a history junction to a connective junction and vice versa from the popup menu.
75
2. We edit the fields in the properties dialog, which are described in the table below.
Field
Description
Parent
Parent of this state; readonly; click the hypertext link to bring the
parent to the foreground.
Description
Textual description/comment.
Document Link
Example 7.1
This is a History Junction example.
Let us consider the flow diagram in Figure 7.7 that uses a history junction.
76
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.
77
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 diagram. Event E_one is processed from the root of the Stateflow diagram down through the hierarchy 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.
78
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.
Figure 7.9. The position of the states A,B,C, and D determines the order of execution
79
710
711
State A is
marked
inactive
State B is
marked
active
Figure 7.11. Continuation of the state execution example
712
713
714
Transitions
Figure 7.13. Chart dialog box for selecting User/specified state/transition execution order
Alternately, we can rightclick inside the top level of the Stateflow chart and from the popup
menu we select Properties. We can also rightclick inside one of the parallel states in the
chart and from the popup menu we select Execution Order and from the submenu we can
select the desired execution order of individual parallel states. We rightclick 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 Stateflowwith Applications
Copyright Orchard Publications
715
As we already know from the previous chapter, 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 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. 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. 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.
716
Transitions
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 condition 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.
In the label above, E is referred to as an event trigger. It specifies an event that causes the transition to be taken, provided the condition, if specified, is true. Specifying an event is optional. The
717
the specified event trigger. We must enclose the condition in square brackets ([]). In this example, 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 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. 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 backslash. 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 transition label is valid. Default transitions are slightly different because 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.
The following are possible combinations of valid transition labels.
Transition Label
Event only
Event and condition
Condition only
Action only
Not specified
718
Is Valid If...
That event occurs
That event occurs and the condition is true
Any event occurs and the condition is true
Any event occurs
Any event occurs
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
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
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 Stateflowwith Applications
Copyright Orchard Publications
719
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 destination 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. However, 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 topdown approach simplifies the Stateflow diagram
720
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.
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 substate.
SelfLoop 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.
721
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 connective 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.
722
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 connective 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 previous 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 specifying 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.
723
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 processed, 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 selfloop transition on
both Power_on.Low and Power_on.High, as shown in Figure 7.26.
724
Summary
7.12 Summary
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.
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 rightclicking
the drawing area in the Stateflow Editor and from the popup 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 evaluated 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 condition 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
where:
event is an event trigger that specifies an event that causes the transition to be taken, provided 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.
725
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.
726
727
728
Chapter 8
Boxes in Stateflow
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.
Figure 8.1. The Stateflow Editor window with the mouse pointer near the Box tool
81
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.
82
2. From the pop-up menu in Figure 8.3, we select Type. A submenu appears adjacent to the popup 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.
83
84
85
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 status. 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.
86
Chapter 9
Mealy and Moore Charts in Stateflow
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 illustrative examples for each.
Input
Q1
Q0
Next State
Output
n+1
n+1
Q1
Q0
We can represent the state table above with the timing diagram shown in Figure 9.1 below.
91
CP
0
x
Q0
Q1
n+1
Q0
n+1
Q1
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
01
11
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 .
92
outputs inside the circle. Thus, for a twobit 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
01 10
11 00
10 11
93
Advantages
Disadvantages
Mealy
Fewer states
React faster to inputs
Moore
requires 2 states
* We access the Chart dialog box from the Stateflow Editor window by rightclicking a chart in that window and from the
popup 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.
94
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 triggered.
As we now know, Mealy machines compute output on transitions, while Moore machines compute outputs in states. Therefore, Mealy charts can compute output earlier than Moore charts,
that is, at the time Stateflow executes the charts 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 values.
* Normally, charts compute output data in every execution, but when this option is selected, the computed outputs override the default values. However, when output is not computed, the default values apply.
95
We must ensure that the output is in a Mealy machine is a function of input and state. Accordingly, the selection of a Mealy state machine enforce the following rules:
96
* 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.
**Machineparented 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 simulation 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.
97
* 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 machineparented 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.
98
99
910
is equivalent to:
Classic_State
du: y=x;
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.
Moore_State
y=x;
func(y);
Classic_State
du: y=x;
ex: func(y);
Figure 9.8. Example where Moore states do not differentiate between the during and exit actions
* A leaf state is a state that resides at the lowest level of the Stateflow hierarchy and, therefore, does not parent
any other states.
911
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 MachineParented Data to Constants and Parameters
Machineparented data is data that we define for a Stateflow machine, which is the collection 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.
912
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:
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 Stateflowwith Applications
Copyright Orchard Publications
913
* 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 machineparented 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.
914
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 Stateflowwith Applications
Copyright Orchard Publications
915
916
To
Result
Mealy
Classic
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
Moore
Mealy
Converting between these two types does not produce equivalent behavior
because Mealy and Moore rules about placement of actions are mutually exclusive. Requires redesign.
917
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.
918
The following table compares the Mealy and Moore vending machine Stateflow diagrams in Figures 9.13 and 9.14.
Mealy Vending Machine
Uses 3 states
Uses 5 states
Updates output before evaluating input, requiring 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 produced 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.
919
920
00
10
11
2. In the Moore machine shown below, 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 . Draw a timing diagram to
show the sequence of operation of this machine.
00 01
10 11
01 11
921
00
(e)
(a)
(f)
10
11
(d)
(b)
(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 .
922
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
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 .
923
t1
t2
t3
t4
t5
CP
z
Q1
Q0
y1
y0
924
Appendix A
Introduction to MATLAB
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 MATLABs Editor / Debugger, finding the roots of a polynomial, and making plots. Several examples are provided with detailed explanations.
A1
A2
Roots of Polynomials
are both correct.
One of the most powerful features of MATLAB is the ability to do computations involving complex 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=34j
displays
z = 3.00004.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.
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]
p1 =
1
-10
roots_ p1=roots(p1)
35
-50
24
roots_p1 =
4.0000
3.0000
2.0000
Introduction to Stateflowwith Applications
Copyright Orchard Publications
A3
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 polynomial 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
16
25
52
roots_ p2=roots(p2)
roots_p2 =
6.5014
2.7428
-1.5711
-0.3366 + 1.3202i
-0.3366 - 1.3202i
A4
r3 =
1
poly_r3=poly(r3)
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 coefficients 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 45j ]
r4 =
Columns 1 through 4
-1.0000
-2.0000
-3.0000
Column 5
-4.0000- 5.0000i
-4.0000+ 5.0000i
poly_r4=poly(r4)
poly_r4 =
1
14
100
340
499
246
A5
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
p 1 = x 3x + 5x + 7x + 9
and
6
p 2 = 2x 8x + 4x + 10x + 12
A6
p1p2 =
2 -6
-8
34
% The coefficients of p1
% The coefficients of p2
% Multiply p1 by p2 to compute coefficients of the product p1p2
18
-24
-74
-88
78
166
174
108
Therefore,
p 1 p 2 = 2x
11
6x
10
Example A.7
Let
7
p 3 = x 3x + 5x + 7x + 9
and
6
p 4 = 2x 8x + 4x + 10x + 12
q =
0.5000
r =
0
-3
Therefore,
5
q = 0.5
r = 4x 3x + 3x + 2x + 3
Example A.8
Let
6
p 5 = 2x 8x + 4x + 10x + 12
d
dx
A7
der_p5 =
12
% The coefficients of p5
% Compute the coefficients of the derivative of p5
-32
10
Therefore,
d
------ p 5 = 12x 5 32x 3 + 4x 2 + 8x + 10
dx
n1
n2
bn x + bn 1 x
+ bn 2 x
+ + b1 x + b0
( x ) = -----------------------------------------------------------------------------------------------------------------------------------------R ( x ) = Num
m
m1
m2
Den ( x )
am x + am 1 x
+ am 2 x
+ + a1 x + a0
(A.2)
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
5
4
2
p num
x 3x + 5x + 7x + 9R ( x ) = ----------- = -------------------------------------------------------6
4
2
p den
x 4x + 2x + 5x + 6
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];
roots_num=roots(num), roots_den=roots(den)
roots_num =
2.4186 + 1.0712i
-0.3370 + 0.9961i
A8
2.4186 - 1.0712i
-0.3370 - 0.9961i
-1.1633
Rational Polynomials
roots_den =
1.6760 + 0.4922i
-0.2108 + 0.9870i
1.6760 - 0.4922i
-0.2108 - 0.9870i
-1.9304
-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 constant term c using MATLAB as follows:
(2.4186 + 1.0712i)*(2.4186 1.0712i)
ans = 6.9971
(0.3370+ 0.9961i)*(0.33700.9961i)
ans = 1.1058
(1.6760+ 0.4922i)*(1.67600.4922i)
ans = 3.0512
(0.2108+ 0.9870i)*(0.21080.9870i)
ans = 1.0186
Thus,
2
2
p num
( x 4.8372x + 6.9971 ) ( x + 0.6740x + 1.1058 ) ( x + 1.1633 )
R ( x ) = ----------- = ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------2
2
p den
( x 3.3520x + 3.0512 ) ( x + 0.4216x + 1.0186 ) ( x + 1.0000 ) ( x + 1.9304 )
A9
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.
R1
R2
C
V
A10
|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 semicolon (;) 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 Stateflowwith Applications
Copyright Orchard Publications
A11
500
1000
1500
2000
2500
3000
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 yaxis respectively.
The magnitude frequency response is usually represented with the xaxis in a logarithmic scale.
We can use the semilogx(x,y) command which is similar to the plot(x,y) command, except that
the xaxis is represented as a log scale, and the yaxis as a linear scale. Likewise, the semilogy(x,y) command is similar to the plot(x,y) command, except that the yaxis 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.
A12
1000
|Z| in Ohms
800
600
400
200
0
2
10
10
w in rads/sec
10
To display the voltage v in a dB scale on the yaxis, 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 crosshair
that can be moved around with the mouse. For instance, we can use the command gtext(Impedance |Z| versus Frequency), and this will place a crosshair 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 MathWorks Using MATLAB Graphics documentation.
A13
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 3phase plot is as follows:
x=linspace(0, 2*pi, 60);
% pi is a builtin 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 xaxis 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
A14
Color
Symbol
Marker
Symbol
Line Style
blue
point
solid line
green
circle
dotted line
red
xmark
dashdot line
cyan
plus
dashed line
magenta
star
yellow
square
black
diamond
white
triangle down
triangle up
<
triangle left
>
triangle right
pentagram
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 MATLABs command screen.
The plots we have discussed thus far are twodimensional, that is, they are drawn on two axes.
MATLAB has also a threedimensional (threeaxes) capability and this is discussed next.
The plot3(x,y,z) command plots a line in 3space 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 twodimensional plots.
A15
(A.3)
z = 2x + x + 3y 1
Solution:
% Length of vector x
% Length of vector y must be same as x
z= 2.*x.^3+x+3.*y.^21;
plot3(x,y,z); grid
3000
2000
1000
0
-1000
-2000
10
5
0
-5
-10
-10
-5
10
In a twodimensional plot, we can set the limits of the x and yaxes with the axis([xmin xmax
ymin ymax]) command. Likewise, in a threedimensional 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 command. This must be done for each plot. The threedimensional text(x,y,z,string) command will
place string beginning at the coordinate (x,y,z) on the plot.
For threedimensional 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.
A16
(A.4)
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 threedimensional plot is created with the following MATLAB script where, as in the previous example, in the second line we have used the dot multiplication, dot division, and dot exponentiation. 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('xaxis, radius r (meters)'); ylabel('yaxis, altitude h (meters)');...
zlabel('zaxis, volume (cubic meters)'); title('Volume of Right Circular Cone'); box on
The threedimensional 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
threedimensional plots. The MATLAB Users Manual and the Using MATLAB Graphics Manual contain numerous examples.
A17
150
100
50
0
6
4
2
A.8 Subplots
MATLAB can display up to four windows of different plots on the Figure window using the command 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 integers 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 multiplication, division and exponentiation that follows.
111
Full Screen
211
212
221 222
212
221
223
211
223 224
Default
222
224
121
221
223
122
122
121
222
224
A18
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]'
b =
-1
3
6
11
We will now define Matrix Multiplication and ElementbyElement 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 column 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)
A19
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
ans =
68
Now, let us suppose that both A and B are row vectors, and we attempt to perform a rowby
row multiplication with the following MATLAB statements.
A=[1 2 3 4 5]; B=[2 6 3 8 7]; A*B
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. ElementbyElement 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 performed with the dot multiplication operator (.*). There is no space between the dot and the
multiplication symbol. Thus,
C. D = [ c 1 d 1
A20
c2 d2
c3 d3
cn dn ]
(A.6)
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
ans =
-2
-9
12
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
byelement 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, division, 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
y = f ( t ) = 3e
4 t
cos 5t 2e
3 t
t sin 2t + ---------t+1
(A.7)
A21
5
4
y=f(t)
3
2
1
0
-1
0.5
1.5
2.5
t
3.5
4.5
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
number approximately equal to 2.2 10
16
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 arguments. 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 MATLABs capability
of displaying up to four windows of different plots.
Example A.14
Plot the functions
y = sin 2x,
z = cos 2x,
v = sin 2x cos 2x
in the interval 0 x 2 using 100 data points. Use the subplot command to display these functions on four windows on the same graph.
A22
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);
plot(x,z); axis([0 2*pi 0 1]);
subplot(223);
plot(x,w); axis([0 2*pi 0 0.3]);
subplot(224);
plot(x,v); axis([0 2*pi 0 400]);
title('z=(cosx)^2');
title('w=(sinx)^2*(cosx)^2');
title('v=(sinx)^2/(cosx)^2');
These subplots are shown in Figure A.9.
y=(sinx)2
0.5
z=(cosx)2
0.5
4
2
4
2
w=(sinx) *(cosx)
6
2
v=(sinx) /(cosx)
400
0.2
200
0.1
0
The next example illustrates MATLABs capabilities with imaginary numbers. We will introduce
the real(z) and imag(z) functions that display the real and imaginary parts of the complex quantity z = x + iy, the abs(z), and the angle(z) functions that compute the absolute value (magnitude) 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 Stateflowwith Applications
Copyright Orchard Publications
A23
10
10
Z ab
10 F
0.1 H
With the given values of resistance, inductance, and capacitance, the impedance Z ab as a function of the radian frequency can be computed from the following expression:
4
10 j ( 10 )
Z ab = Z = 10 + -------------------------------------------------------5
10 + j ( 0.1 10 )
(A.8)
A24
Real part of Z
800
600
400
200
0
200
400
600
1400
1600
1800
2000
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
Imaginary part of Z
400
200
0
-200
-400
-600
200
400
600
1400
1600
1800
2000
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
A25
1500
120
60
1000
Polar Plot of Z
150
30
500
180
210
330
240
300
270
Example A.15 clearly illustrates how powerful, fast, accurate, and flexible MATLAB is.
A26
Example A.16
Find the zeros, the minimum, and the maximum values of the function
1
1
f ( x ) = --------------------------------------- --------------------------------------- 10
2
2
( x 0.1 ) + 0.01 ( x 1.2 ) + 0.04
(A.9)
-1
-0.5
0.5
1.5
Figure A.14. Plot for Example A.16 using the plot command
A27
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
0
-20
-40
-1.5
-1
-0.5
0.5
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)
A28
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 / ((x0.1) ^ 2 + 0.01) 1 / ((x1.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./((x0.1).^2+0.01)+1./((x1.2).^2+0.04)+10; plot(x,ymax); grid
and the plot is shown in Figure A.16.
Introduction to Stateflowwith Applications
Copyright Orchard Publications
A29
-1
-0.5
0.5
1.5
Next we compute the first derivative of f ( x ) and we solve for x to find the value where the maximum of ymax occurs. This is accomplished with the MATLAB script below.
syms x ymax zmax; ymax=(1/((x0.1)^2+0.01)1/((x1.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)
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 .
A30
Display Formats
x=0.0999;
% Using this value find the corresponding value of ymax
ymax=1 / ((x0.1) ^ 2 + 0.01) 1 / ((x1.2) ^ 2 + 0.04) 10
ymax = 89.2000
A31
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 values 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 addons.
* For more MATLAB applications, please refer to Numerical Analysis Using MATLAB and Spreadsheets,
ISBN 0970951116.
A32
Appendix B
Introduction to Simulink
his appendix is a brief introduction to Simulink. This author feels that we can best introduce Simulink with a few examples. Some familiarity with MATLAB is essential in understanding Simulink, and for this purpose, Appendix A is included as an introduction to
MATLAB.
14 H
i(t)
+
C
43 F
vs ( t ) = u0 ( t )
vC ( t )
(B.1)
(B.2)
B1
Introduction to Simulink
2
d vC
dv
- + vC = u0 ( t )
RC --------C- + LC ---------2
dt
dt
(B.3)
1 d v C 4 dv C
--- ----------- + --- --------- + v C = u 0 ( t )
3 dt 2 3 dt
2
dv
d vC
----------- + 4 --------C- + 3v C = 3u 0 ( t )
2
dt
dt
2
dv
d vC
----------- + 4 --------C- + 3v C = 3
2
dt
dt
(B.4)
t>0
(B.5)
To appreciate Simulinks 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 secondorder, nonhomogeneous differential equation with constant coefficients, and thus the complete solution will consist of the sum of the forced response and the natural response. It is obvious that the solution of this equation cannot be a constant since the derivatives 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 candidates 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,
the natural response is the sum of the terms k 1 e
be
s1 t
and k 2 e
s2 t
s1 t
+ k2 e
s2 t
+ v cf ( t )
(B.6)
* Please refer to Circuit Analysis II with MATLAB Applications, ISBN 0970951159, Appendix B for a
thorough discussion.
B2
(B.7)
s + 4s + 3 = 0
Solution of (B.7) yields of s 1 = 1 and s 2 = 3 and with these values (B.6) is written as
t
vc ( t ) = k1 e + k2 e
3 t
+ v cf ( t )
(B.8)
t>0
(B.9)
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
(B.10)
v Cf = k 3 = 1
v C ( t ) = v Cn ( t ) + v Cf = k 1 e + k 2 e
3 t
+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
v C ( 0 ) = k 1 e + k 2 e + 1 = 0.5
k 1 + k 2 = 0.5
Also,
(B.12)
dv C dv C i
i L = i C = C ---------, --------- = ---Ldt
dt
C
and
dv
--------Cdt
t=0
iL ( 0 ) 0
= ----------- = ---- = 0
C
C
(B.13)
= k 1 3k 2
(B.14)
t=0
B3
Introduction to Simulink
(B.15)
k 1 3k 2 = 0
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
v C ( t ) = ( 0.75 e + 0.25e
3 t
+ 1 )u 0 ( t )
(B.16)
y1 =
3/4*exp(-t)-3/4*exp(-3*t)
y2=diff(y0,2)
y2 =
-3/4*exp(-t)+9/4*exp(-3*t)
y=y2+4*y1+3*y0
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
3t
t 3t
i = i L = i C = C ---------- = --- --- e 3
--- e = e e A
dt
3 4
4
(B.17)
Vs ( s ) = 1 s
0.25s C
3 4s
I(s)
0.5 s
VC ( s )
+ V (0)
C
B4
0.5s + 2s + 3
r 1 = ---------------------------------(s + 1)(s + 3)
= 1
s=0
+ 2s + 3--------------------------------r 2 = 0.5s
s(s + 3)
= 0.75
s = 1
0.5s + 2s + 3r 3 = --------------------------------s(s + 1)
(B.18)
= 0.25
s = 3
v C ( t ) = 1 0.75e + 0.25e
3t
* For derivation of the voltage division and current division expressions, please refer to Circuit Analysis I with
MATLAB Applications, ISBN 0970951124.
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 StateSpace 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 StateSpace and State Variables Analysis, please
refer to Chapter 5, this text.
B5
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
dt
(B.19)
(B.20)
dv
x 2 = --------Cdt
(B.21)
and
Also,
and thus,
dv
i L = C --------Cdt
dv
4
x 1 = i L = C --------C- = Cx 2 = --- x 2
3
dt
or
3
x 2 = --- x 1
4
(B.22)
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
(B.23)
* 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 523, this text.
B6
e e
3t
1 0.75 e + 0.25e
3t
Then,
t
x1 = iL = e e
3t
(B.24)
and
t
x 2 = v C = 1 0.75e + 0.25e
3t
(B.25)
Alternately, we can click on the Simulink icon shown in Figure B.3. It appears on the top bar on
MATLABs Command prompt.
Upon execution of the Simulink command, the Commonly Used Blocks appear as shown in Figure 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
dv
d vC
----------- = 4 --------C- 3v C + 3u 0 ( t )
2
dt
dt
(B.26)
A block diagram representing relation (B.26) above is shown in Figure B.5. We will use Simulink
to draw a similar block diagram.*
B7
Introduction to Simulink
u0 ( t )
d vC
----------2
dt
dt
dv
--------Cdt
dt
vC
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.
B8
The window of Figure B.6 is the model window where we enter our blocks to form a block diagram. 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.
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 amplifier with Gain 3 to the unit step function block. The gain block in Simulink is under Commonly 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 Stateflowwith Applications
Copyright Orchard Publications
B9
Introduction to Simulink
blocks.* We doubleclick 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 leftclick on the destination block.
B10
6. From the Commonly Used Blocks of the Simulink Library Browser, we choose the Integrator 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 Figure B.11.
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 Format drop menu, and we label these as Gain 2 and Gain 3. Finally, we doubleclick 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.
B11
Introduction to Simulink
dv
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
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 StateSpace block.
B12
y = Cx + du
or
y = [0 1]
x1
x2
+ [ 0 ]u
We doubleclick on the StateSpace 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 StateSpace block.
B13
Introduction to Simulink
The initials conditions [ x1 x2 ]' are specified in MATLABs Command prompt as
x1=0; x2=0.5;
form, we double click on the Scope block, and then clicking on the Autoscale
obtain the waveform shown in Figure B.16.
icon, we
Figure B.16. The waveform for the function v C ( t ) for Example B.1 with the StateSpace block.
The statespace 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 fourthorder network is described by the differential equation
3
4
d y
d y
dy
d y
--------- + a 3 --------3- + a 2 -------2- + a 1 ------ + a 0 y ( t ) = u ( t )
4
dt
dt
dt
dt
(B.27)
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
B14
4
d y
d y
-------- + 2 -------2- + y ( t ) = sin t
4
dt
dt
(B.28)
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 equation 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 fourthorder; therefore, we must define four state variables that will be used with the four firstorder 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
x1 = y ( t )
We observe that
dy
x 2 = -----dt
d y
x 3 = --------2
dt
d y
x 4 = --------3
dt
x 1 = x 2
x 2 = x 3
x 3 = x 4
(B.30)
(B.31)
d y = x = a x a x a x a x + u ( t )
--------4
0 1
1 2
2 3
3 4
4
dt
0
0
=
0
a0
1
0
0
a1
0
1
0
a2
0
0
1
a3
x1
0
x2
+ 0 u(t)
x3
0
1
x4
(B.32)
x = Ax + bu
(B.33)
y = Cx + du
(B.34)
where
B15
Introduction to Simulink
x =
x 1
x 2
x 3
x 4
0
0
A=
0
a0
1
0
0
a1
0
1
0
a2
x1
0
0
,
1
a3
x2
x=
x3
x4
0
b= 0,
0
1
and u = u ( t )
(B.35)
y = [1 0 0 0]
x3
+ [ 0 ]u ( t )
(B.36)
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 statespace form as
x 1
x 2
0
0
=
0
a0
x 3
x 4
1
0
0
0
0
1
0
2
0
0
1
0
x1
0
+ 0 sin t
x3
0
1
x4
x2
(B.37)
where
x =
x 1
x 2
x 3
x 4
0
0
A=
0
a0
1
0
0
0
0
1
0
2
0
0
,
1
0
x1
x=
x2
x3
x4
0
b= 0,
0
1
and u = sin t
(B.38)
B16
x2
x3
+ [ 0 ] sin t
(B.39)
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 StateSpace 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.
We now doubleclick on the Signal Generator block and we enter the following in the Function Block Parameters:
Wave form: sine
Time (t): Use simulation time
Amplitude: 1
Frequency: 2
Units: Hertz
Next, we doubleclick on the statespace 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 Stateflowwith Applications
Copyright Orchard Publications
B17
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
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 StateSpace 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
B18
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 algebraic state z that is close to the solution value.
B19
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 MATLABs Command 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;
The Display blocks in Figure B.20 show the values of z 1 , z 2 , and z 3 for the values specified in
MATLABs Command prompt.
* The Subsystem block is described in detail in Chapter 2, Section 2.1, Page 22, Introduction to Simulink with
Engineering Applications, ISBN 0974423971.
The contents of the Subsystem block are not lost. We can doubleclick on the Subsystem block to see its contents. 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 22, Introduction to Simulink with Engineering Applications, ISBN 0974423971.
B20
Appendix C
Masked Subsystems
C1
The Simulink model in Figure C.1 below implements the quadratic equation y = ax + bx + c .
C2
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 doubleclick the Subsystem block and
now the model appears as shown in Figure C.3.
C3
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 MATLABs saved files path. The Mask Editor now appears
as shown in Figure C.5.
C4
C5
Figure C.6. The Parameters tab for the Mask Editor window
C6
tool and the Mask Editor window now appears as shown in Figure C.7.
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.
C7
Figure C.8. The Masked Editor with the equation constants specified
We rightclick on the masked subsystem block shown in Figure C.5, Page C5, and in the Function 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.
C8
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
Copyright Orchard Publications
C9
Figure C.11. The Initialization tab for the Mask Editor Window
Figure C.12. The Documentation tab for the Mask Editor window.
C10
R1
R2
Index
Symbols
A
abs(z) in MATLAB A-23
action 1-1
action table 2-1
actions 2-1
algebraic constrain blocks in Simulink B-18
All Data (Current Chart) in Simulink 3-22
angle(z) in MATLAB A-23
animation in Simulink 3-16
animation delay 1-55
animation of Stateflow charts 1-47
autoscale icon in Simulink B-12
axis in MATLAB A-16
B
backtracking behavior 6-14
block error 1-67
blocking 3-40
box in Stateflow 8-1
box in MATLAB A-12
box tool in Stateflow 8-1
breakpoints 1-49, 3-19
Browse Data 1-50, 3-19
Build tool 1-60
C
E
changing a box to a state 8-1
changing a state to a box 8-1
Chart Entry 1-49, 3-19
Chart Entry 3-19
Classic Machine in Stateflow 9-4
clc in MATLAB A-2
clear in MATLAB A-2
code generation errors 1-60
Coder Options 1-48, 3-18
column vector A-19
command screen in MATLAB A-1
Command Window in MATLAB A-1
commas in MATLAB A-8
comment line in MATLAB A-2
Commonly Used Blocks in Simulink B-7
complex conjugate A-4
complex numbers in MATLAB A-3
condition 1-2, 1-14, 7-18
condition action 7-18
condition table 2-1
conditions 2-1
configuration parameters 1-46, 3-15, B-12
Connective Junction 6-1
Contents pane 3-6, B-7
Continue button 1-56, 3-21
Continue Debugging 3-33
conv in MATLAB A-6
Creating a Mealy Chart 9-6
Creating a Moore Chart 9-10
IN2
T
Target Builder 1-48, 3-18
text A-14
title(string) in MATLAB A-12
Traffic Light example with a Moore
state machine 9-14
transition action 1-1, 7-18
transition connections 7-19
transitions 7-15
Tree Pane B-7
trigger port 1-42
Truth Table block 2-1
V
valid transitions 7-18
Vending Machine example with a
Mealy state machine 9-8
W
while 4-18
X
xlabel in MATLAB A-12
Y
ylabel in MATLAB A-12