Stateflow Guide
Stateflow Guide
Stateflow Guide
User's Guide
R2019a
How to Contact MathWorks
Phone: 508-647-7000
Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-9
v
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
State Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
State Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
State Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10
Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-18
Transition Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
Transition Label Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Valid Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-22
Transition Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23
vi Contents
Stateflow Semantics
3
Stateflow Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Stateflow Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3
Nongraphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-4
vii
Default Transition Is Missing . . . . . . . . . . . . . . . . . . . . . . . . 3-33
Default Transition Path Does Not Terminate in a State . . . . . 3-34
Unexpected Backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-35
Transition Loops Outside Natural Parent . . . . . . . . . . . . . . . 3-36
Transition Action Precedes a Condition Action Along This Path
............................................ 3-37
Transition Begins or Ends in a Parallel State . . . . . . . . . . . . . 3-39
Monitoring Leaf or Child State Activity of Parallel States . . . 3-39
Invalid Transitions Crossing into Graphical Function . . . . . . 3-40
Invalid Transitions Crossing out of Graphical Function . . . . . 3-40
viii Contents
Outgoing Transition Example . . . . . . . . . . . . . . . . . . . . . . . . 3-66
Outgoing Transition Example with Backtracking . . . . . . . . . . 3-67
Condition and Transition Actions . . . . . . . . . . . . . . . . . . . . . 3-70
ix
Select a State Machine Type . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Specify State Actions and Transition Conditions . . . . . . . . . . . 4-2
Define Persistent Data to Store State Variables . . . . . . . . . . . . 4-3
Simplify State Actions and Transition Conditions with Function
Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-3
Check That Your System Representation Is Complete . . . . . . . 4-4
x Contents
Model Logic Patterns and Iterative Loops Using Flow
Charts
5
Flow Charts in Stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Draw a Flow Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Best Practices for Creating Flow Charts . . . . . . . . . . . . . . . . . 5-3
xi
Build Mealy and Moore Charts
7
Overview of Mealy and Moore Machines . . . . . . . . . . . . . . . . . . 7-2
Semantics of Mealy and Moore Machines . . . . . . . . . . . . . . . . 7-2
Create Mealy and Moore Charts . . . . . . . . . . . . . . . . . . . . . . . 7-3
Advantages of Mealy and Moore Charts . . . . . . . . . . . . . . . . . 7-4
xii Contents
Rules of Subchart Conversion . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Convert a State to a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Manipulate Subcharts as Objects . . . . . . . . . . . . . . . . . . . . . . 8-7
Open a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
Edit a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-7
Navigate Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-8
xiii
Define Data
9
Add Stateflow Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Add Data Through the Symbols Window . . . . . . . . . . . . . . . . . 9-2
Add Data by Using the Stateflow Editor Menu . . . . . . . . . . . . 9-3
Add Data Through the Model Explorer . . . . . . . . . . . . . . . . . . 9-3
Best Practices for Using Data in Charts . . . . . . . . . . . . . . . . . 9-4
xiv Contents
Inherit Input or Output Size from Simulink Signals . . . . . . . . 9-41
Guidelines for Sizing Data with Numeric Values . . . . . . . . . . 9-41
Guidelines for Sizing Data with MATLAB Expressions . . . . . . 9-42
Examples of Valid Data Size Expressions . . . . . . . . . . . . . . . . 9-43
Name Conflict Resolution for Variables in Size Expressions . . 9-43
Best Practices for Sizing Stateflow Data . . . . . . . . . . . . . . . . 9-43
Define Events
10
Synchronize Model Components by Broadcasting Events . . . 10-2
Types of Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-2
Define Events in a Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-3
Access Event Information from a Stateflow Chart . . . . . . . . . 10-4
Best Practices for Using Events in Stateflow Charts . . . . . . . 10-4
xv
Activate a Stateflow Chart by Sending Input Events . . . . . . . 10-9
Activate a Stateflow Chart by Using Edge Triggers . . . . . . . . 10-9
Activate a Stateflow Chart by Using Function Calls . . . . . . . 10-12
Association of Input Events with Control Signals . . . . . . . . 10-12
Data Types Allowed for Input Events . . . . . . . . . . . . . . . . . 10-12
Messages
11
View Differences Between Stateflow Messages, Events, and
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
xvi Contents
Control Message Activity in Stateflow Charts . . . . . . . . . . . . 11-18
Access Message Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-18
Send a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-18
Guard Transitions and Actions . . . . . . . . . . . . . . . . . . . . . . 11-19
Receive a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-20
Discard a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-21
Forward a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Determine if a Message Is Valid . . . . . . . . . . . . . . . . . . . . . 11-23
Determine the Length of the Queue . . . . . . . . . . . . . . . . . . 11-24
Determine When a Queue Overflows . . . . . . . . . . . . . . . . . . 11-24
xvii
Supported Operations for Chart Data . . . . . . . . . . . . . . . . . . 12-14
Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-14
Unary Operations and Actions . . . . . . . . . . . . . . . . . . . . . . 12-17
Assignment Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-17
Pointer and Address Operations . . . . . . . . . . . . . . . . . . . . . 12-18
Type Cast Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-19
Replace Operations with Application Implementations . . . . 12-20
xviii Contents
Directed Local Event Broadcast Using Qualified Event Names
........................................... 12-46
Diagnostic for Detecting Undirected Local Event Broadcasts
........................................... 12-47
xix
Auto Correction When Using MATLAB as the Action Language
............................................ 13-2
C to MATLAB Syntax Conversion . . . . . . . . . . . . . . . . . . . . . 13-3
Rules for Using MATLAB as the Action Language . . . . . . . . . 13-4
xx Contents
Add History Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11
Print State Transition Tables . . . . . . . . . . . . . . . . . . . . . . . 14-12
Select and Clear Table Elements . . . . . . . . . . . . . . . . . . . . . 14-12
Undo and Redo Edit Operations . . . . . . . . . . . . . . . . . . . . . 14-12
Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-12
xxi
Benefits of Using Atomic Subcharts . . . . . . . . . . . . . . . . . . . 15-3
Create an Atomic Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . 15-4
When to Use Atomic Subcharts . . . . . . . . . . . . . . . . . . . . . . . 15-6
xxii Contents
Save and Restore Simulations with Operating Point
16
Using Operating Points in Stateflow . . . . . . . . . . . . . . . . . . . . 16-2
Division of a Long Simulation into Segments . . . . . . . . . . . . . 16-3
Test of a Chart Response to Different Settings . . . . . . . . . . . 16-3
xxiii
Vectors and Matrices in Stateflow Charts
17
Vectors and Matrices in Stateflow Charts . . . . . . . . . . . . . . . . 17-2
When to Use Vectors and Matrices . . . . . . . . . . . . . . . . . . . . 17-2
Where You Can Use Vectors and Matrices . . . . . . . . . . . . . . . 17-2
Rules for Vectors and Matrices in Stateflow Charts . . . . . . . . 17-3
Best Practices for Vectors and Matrices in Stateflow Charts
............................................ 17-4
xxiv Contents
Rules for Using Variable-Size Data . . . . . . . . . . . . . . . . . . . . 18-4
xxv
String Data in Charts
20
Manage Textual Information by Using Strings . . . . . . . . . . . . 20-2
Example of String Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Computation with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-3
Where to Use Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-7
xxvi Contents
Fixed-Point Data in Stateflow Charts
22
Fixed-Point Data in Stateflow Charts . . . . . . . . . . . . . . . . . . . . 22-2
Fixed-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Specify Fixed-Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Conversion Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4
Fixed-Point Context-Sensitive Constants . . . . . . . . . . . . . . . . 22-5
Tips for Using Fixed-Point Data . . . . . . . . . . . . . . . . . . . . . . 22-6
Automatic Scaling of Fixed-Point Data . . . . . . . . . . . . . . . . . 22-7
Share Fixed-Point Data with Simulink Models . . . . . . . . . . . . 22-7
Implementation of Fixed-Point Data in Stateflow . . . . . . . . . . 22-8
Complex Data
23
Complex Data in Stateflow Charts . . . . . . . . . . . . . . . . . . . . . . 23-2
Define Complex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
When to Use Complex Data . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
Where You Can Use Complex Data . . . . . . . . . . . . . . . . . . . . 23-2
xxvii
How You Can Use Complex Data . . . . . . . . . . . . . . . . . . . . . . 23-3
xxviii Contents
Implement Interfaces to Simulink Models . . . . . . . . . . . . . . 24-12
Define a Triggered Stateflow Block . . . . . . . . . . . . . . . . . . . 24-12
Define a Sampled Stateflow Block . . . . . . . . . . . . . . . . . . . . 24-13
Define an Inherited Stateflow Block . . . . . . . . . . . . . . . . . . 24-14
Define a Continuous Stateflow Block . . . . . . . . . . . . . . . . . 24-14
Define Function-Call Output Events . . . . . . . . . . . . . . . . . . 24-14
Define Edge-Triggered Output Events . . . . . . . . . . . . . . . . . 24-15
xxix
Simplify Stateflow Charts by Incorporating Active State Output
............................................... 24-37
Modify the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-37
View Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-39
xxx Contents
Schedule Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-12
xxxi
Language Options for Stateflow Truth Tables . . . . . . . . . . . . . 27-8
C Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8
MATLAB Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8
Select a Language for Stateflow Truth Tables . . . . . . . . . . . . 27-9
Migration from C to MATLAB Truth Tables . . . . . . . . . . . . . . 27-9
xxxii Contents
View the Stateflow Chart for the Truth Table . . . . . . . . . . . 27-64
xxxiii
Simulink Functions in Stateflow Charts
29
Reuse Simulink Components in Stateflow Charts . . . . . . . . . . 29-2
Where to Define a Simulink Function in a Chart . . . . . . . . . . 29-2
Call a Simulink Function from Multiple Sites in a Chart . . . . 29-2
Rules for Using Simulink Functions in Stateflow Charts . . . . 29-3
xxxiv Contents
Build Targets
30
Simulate a Chart That Calls Custom Code . . . . . . . . . . . . . . . 30-2
Guidelines for Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2
xxxv
Use Library Charts in Your Model . . . . . . . . . . . . . . . . . . . . 30-18
Code Generation
31
Generate C or C++ Code from Stateflow Blocks . . . . . . . . . . . 31-2
Generate Code for Rapid Prototyping and Production
Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-2
Traceability of Stateflow Objects in Generated Code . . . . . . . 31-3
xxxvi Contents
Select Array Layout for Matrices in Generated Code . . . . . . . 31-5
Column-Major Array Layout . . . . . . . . . . . . . . . . . . . . . . . . . 31-5
Row-Major Array Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-6
Multidimensional Array Layout . . . . . . . . . . . . . . . . . . . . . . . 31-7
xxxvii
Detect Common Modeling Errors During Chart Simulation
............................................... 32-28
State Inconsistencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-28
Data Range Violations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-30
Cyclic Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-31
xxxviii Contents
Explore and Modify Charts
33
Manage Data, Events, and Messages in the Symbols Window
................................................ 33-2
Add and Modify Data, Events, and Messages . . . . . . . . . . . . 33-3
Detect Unused Data in the Symbols Window . . . . . . . . . . . . . 33-4
Trace Data, Events, and Messages . . . . . . . . . . . . . . . . . . . . 33-5
Symbols Window Limitations . . . . . . . . . . . . . . . . . . . . . . . 33-11
xxxix
Capabilities and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 34-6
xl Contents
Semantic Rules Summary
A
Summary of Chart Semantic Rules . . . . . . . . . . . . . . . . . . . . . . A-2
Enter a Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Execute an Active Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Enter a State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-2
Execute an Active State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3
Exit an Active State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . A-3
Execute a Set of Flow Charts . . . . . . . . . . . . . . . . . . . . . . . . . A-4
Execute an Event Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . . A-5
Semantic Examples
B
Categories of Semantic Examples . . . . . . . . . . . . . . . . . . . . . . . B-2
xli
Process Events with an Inner Transition to a Connective
Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-23
Inner Transition to a History Junction . . . . . . . . . . . . . . . . . B-26
Glossary
xlii Contents
1
For example, you can use a state machine to represent the automatic transmission of a
car. The transmission has these operating states: park, reverse, neutral, drive, and low. As
the driver shifts from one position to another, the system makes a transition from one
state to another, for example, from park to reverse.
You can include Stateflow charts as blocks in a Simulink® model. The collection of these
blocks in a Simulink model is the Stateflow machine.
A Stateflow chart enables the representation of hierarchy, parallelism, and history. You
can organize complex systems by defining a parent and offspring object structure. For
example, you can organize states within other higher-level states. A system with
parallelism can have two or more orthogonal states active at the same time. You can also
specify the destination state of a transition based on historical information.
1-2
See Also
Notation
Notation defines a set of objects and the rules that govern the relationships between
those objects. Stateflow chart notation provides a way to communicate the design
information in a Stateflow chart.
Semantics
Semantics describe how to interpret chart notation. A typical Stateflow chart contains
actions associated with transitions and states. The semantics describe the sequence of
these actions during chart execution.
See Also
Chart | State Transition Table | Truth Table
More About
• “Overview of Stateflow Objects” on page 2-2
• “Model Reactive Systems in Stateflow” on page 4-2
• “How Stateflow Objects Interact During Execution” on page 3-5
• “Specify Properties for Stateflow Charts” on page 24-3
1-3
1 Stateflow Chart Concepts
A Simulink model can consist of combinations of Simulink blocks, toolbox blocks, and
Stateflow blocks (charts). A chart consists of graphical objects (states, boxes, functions,
notes, transitions, connective junctions, and history junctions) and nongraphical objects
(events, messages, and data).
There is a one-to-one correspondence between the Simulink model and the Stateflow
machine. Each Stateflow block in the Simulink model appears as a single Stateflow chart.
Each Stateflow machine has its own object hierarchy. The Stateflow machine is the
highest level in the Stateflow hierarchy. The object hierarchy beneath the Stateflow
machine consists of combinations of graphical and nongraphical objects. See “Hierarchy
of Stateflow Objects” on page 1-7.
Stateflow charts are event-driven. Events can be local to the Stateflow block or can
propagate to and from the Simulink model. Data can be local to the Stateflow block or can
pass to and from the Simulink model and external code sources.
Defining the interface for a Stateflow block can involve some or all these tasks:
1-4
Stateflow Charts and Simulink Models
In the following example, the Simulink model consists of a Sine Wave block, a Scope
block, and a single Stateflow block, titled On_off.
1-5
1 Stateflow Chart Concepts
To learn how these objects interact, see “How Stateflow Objects Interact During
Execution” on page 3-5.
1-6
Hierarchy of Stateflow Objects
The highest object in Stateflow hierarchy is the Stateflow machine. This object contains
all other Stateflow objects in a Simulink model. The Stateflow machine contains all the
charts in a model. In addition, the Stateflow machine for a model can contain its own
data.
1-7
1 Stateflow Chart Concepts
Similarly, charts can contain state, box, function, data, event, message, transition,
junction, and note objects. Continuing with the Stateflow hierarchy, states can contain all
these objects as well, including other states. You can represent state hierarchy with
superstates and substates.
A transition out of a superstate implies transitions out of any of its active substates.
Transitions can cross superstate boundaries to specify a substate destination. If a
substate becomes active, its parent superstate also becomes active.
1-8
Bibliography
Bibliography
[1] Hatley, D. J. and I. A. Pirbhai. Strategies for Real-Time System Specification. New York,
NY: Dorset House Publishing, 1988.
1-9
2
Graphical Objects
The following table lists each type of graphical object you can draw in a chart and the
toolbar icon to use for drawing the object.
Default transition
Connective junction
Graphical function
MATLAB® function
Box
Simulink function
Nongraphical Objects
You can define data, event, and message objects that do not appear graphically in the
Stateflow Editor. However, you can see them in the Symbols window and the Model
Explorer. See “Use the Model Explorer with Stateflow Objects” on page 33-13.
2-2
Overview of Stateflow Objects
Data Objects
A Stateflow chart stores and retrieves data that it uses to control its execution. Stateflow
data resides in its own workspace, but you can also access data that resides externally in
the Simulink model or application that embeds the Stateflow machine. You must define
any internal or external data that you use in a Stateflow chart.
Event Objects
An event is a Stateflow object that can trigger a whole Stateflow chart or individual
actions in a chart. Because Stateflow charts execute by reacting to events, you specify
and program events into your charts to control their execution. You can broadcast events
to every object in the scope of the object sending the event, or you can send an event to a
specific object. You can define explicit events that you specify directly, or you can define
implicit events to take place when certain actions are performed, such as entering a state.
For more information, see “Synchronize Model Components by Broadcasting Events” on
page 10-2.
Message Objects
Stateflow message objects are queued objects that can carry data. You can send a
message from one Stateflow chart to another to communicate between charts. You can
also send local messages within a chart. You define the type of message data. You can
view the lifeline of a message in the Sequence Viewer block. For more information, see
“Communicate with Stateflow Charts by Sending Messages” on page 11-10.
2-3
2 Stateflow Chart Notation
• hasChangedTo
Complex data • complex “Supported Operations for
• imag Complex Data” on page 23-4
• real
2-4
Rules for Naming Stateflow Objects
• int32
• int16
• int8
• single
• uint32
• uint16
• uint8
Data type operations • cast “Type Cast Operations” on page
• fixdt 12-19
• type
Explicit events • send “Broadcast Local Events to
Synchronize Parallel States” on
page 12-45
Implicit events • change “Define Chart Behavior by
• chg Using Implicit Events” on page
10-33
• tick
• wakeup
Messages • send “Communicate with Stateflow
• forward Charts by Sending Messages”
on page 11-10
• discard
• isvalid
• length
• receive
Literal symbols • inf “Supported Symbols in Actions”
• t (C charts only) on page 12-22
2-5
2 Stateflow Chart Notation
• during
• en
• entry
• ex
• exit
• on
State activity • in “Check State Activity by Using
the in Operator” on page 12-77
Temporal logic • after “Control Chart Execution by
• at Using Temporal Logic” on page
12-49
• before
• every
• sec
• msec
• usec
• temporalCount
• elapsed
• t
• duration
• count
2-6
States
States
A state describes an operating mode of a reactive system. In a Stateflow chart, states are
used for sequential design to create state transition diagrams.
States can be active or inactive. The activity or inactivity of a state can change depending
on events and conditions. The occurrence of an event drives the execution of the state
transition diagram by making states become active or inactive. At any point during
execution, active and inactive states exist.
State Hierarchy
To manage multilevel state complexity, use hierarchy in your Stateflow chart. With
hierarchy, you can represent multiple levels of subcomponents in a system.
In the following example, three levels of hierarchy appear in the chart. Drawing one state
within the boundaries of another state indicates that the inner state is a substate (or
child) of the outer state (or superstate). The outer state is the parent of the inner state.
In this example, the chart is the parent of the state Car_done. The state Car_done is the
parent state of the Car_made and Car_shipped states. The state Car_made is also the
parent of the Parts_assembled and Painted states. You can also say that the states
Parts_assembled and Painted are children of the Car_made state.
2-7
2 Stateflow Chart Notation
To represent the Stateflow hierarchy textually, use a slash character (/) to represent the
chart and use a period (.) to separate each level in the hierarchy of states. The following
list is a textual representation of the hierarchy of objects in the preceding example:
• /Car_done
• /Car_done.Car_made
• /Car_done.Car_shipped
• /Car_done.Car_made.Parts_assembled
• /Car_done.Car_made.Painted
States can contain all other Stateflow objects. Stateflow chart notation supports the
representation of graphical object hierarchy in Stateflow charts with containment. A state
is a superstate if it contains other states. A state is a substate if it is contained by another
state. A state that is neither a superstate nor a substate of another state is a state whose
parent is the Stateflow chart itself.
States can also contain nongraphical data, event, and message objects. The hierarchy of
this containment appears in the Model Explorer. You define data, event, and message
containment by specifying the parent object.
State Decomposition
Every state (or chart) has a decomposition that dictates what type of substates the state
(or chart) can contain. All substates of a superstate must be of the same type as the
superstate decomposition. State decomposition can be exclusive (OR) or parallel (AND).
Substates with solid borders indicate exclusive (OR) state decomposition. Use this
decomposition to describe operating modes that are mutually exclusive. When a state has
exclusive (OR) decomposition, only one substate can be active at a time.
In the following example, either state A or state B can be active. If state A is active, either
state A1 or state A2 can be active at a given time.
2-8
States
Substates with dashed borders indicate parallel (AND) decomposition. Use this
decomposition to describe concurrent operating modes. When a state has parallel (AND)
decomposition, all substates are active at the same time.
In the following example, when state A is active, A1 and A2 are both active at the same
time.
In the following example, when state A becomes active, both states B and C become active
at the same time. When state C becomes active, either state C1 or state C2 can be active.
2-9
2 Stateflow Chart Notation
State Labels
The label for a state appears on the top left corner of the state rectangle with the
following general format:
name/
entry:entry actions
during:during actions
exit:exit actions
on event_name:on event_name actions
on message_name:on message_name actions
bind:events
2-10
States
Each action in the state label appears in the subtopics that follow. For more information
on state actions, see:
• “Execution of a Stateflow Chart” on page 3-44 — Describes how and when chart
execution occurs.
• “State Action Types” on page 12-2 — Gives more detailed descriptions of each type
of state action, entry, during, exit.
State Name
A state label starts with the name of the state followed by an optional / character. In the
preceding example, the state names are On and Off. Valid state names consist of
alphanumeric characters and can include the underscore (_) character. For more
information, see “Rules for Naming Stateflow Objects” on page 2-4.
Hierarchy provides some flexibility in naming states. The name that you enter on the state
label must be unique when preceded by ancestor states. The name in the Stateflow
hierarchy is the text you enter as the label on the state, preceded by the names of parent
states separated by periods. Each state can have the same name appear in the label, as
long as their full names within the hierarchy are unique. Otherwise, the parser indicates
an error.
2-11
2 Stateflow Chart Notation
Each of these states has a unique name because of its location in the chart. The full
names for the states in FAN1 and FAN2 are:
• PowerOn.FAN1.On
• PowerOn.FAN1.Off
• PowerOn.FAN2.On
• PowerOn.FAN2.Off
State Actions
After the name, you enter optional action statements for the state with a keyword label
that identifies the type of action. You can specify none, some, or all of them. The colon
2-12
States
after each keyword is required. The slash following the state name is optional as long as it
is followed by a carriage return.
For each type of action, you can enter more than one action by separating each action
with a carriage return, semicolon, or a comma. You can specify actions for more than one
event or message by adding additional on event_name or on message_name lines.
If you enter the name and slash followed directly by actions, the actions are interpreted
as entry action(s). This shorthand is useful if you are specifying only entry actions.
Entry Action
Preceded by the prefix entry or en for short. In the preceding example, state On has
entry action on_count=0. This means that the value of on_count is reset to 0
whenever state On becomes active (entered).
During Action
Preceded by the prefix during or du for short. In the preceding label example, state On
has two during actions, light_on() and on_count++. These actions are executed
whenever state On is already active and any event occurs.
Exit Action
Preceded by the prefix exit or ex for short. In the preceding label example, state Off
has the exit action light_off(). If the state Off is active, but becomes inactive
(exited), this action is executed.
On Action
Preceded by the prefix bind. Events bound to a state can only be broadcast by that state
or its children.
2-13
2 Stateflow Chart Notation
State Hierarchy
To manage multilevel state complexity, use hierarchy in your Stateflow chart. With
hierarchy, you can represent multiple levels of subcomponents in a system.
In this example, the chart is the parent of the state Car_done. The state Car_done is the
parent state of the Car_made and Car_shipped states. The state Car_made is also the
parent of the Parts_assembled and Painted states. You can also say that the states
Parts_assembled and Painted are children of the Car_made state.
To represent the Stateflow hierarchy textually, use a slash character (/) to represent the
chart and use a period (.) to separate each level in the hierarchy of states. The following
list is a textual representation of the hierarchy of objects in the preceding example:
• /Car_done
• /Car_done.Car_made
• /Car_done.Car_shipped
2-14
State Hierarchy
• /Car_done.Car_made.Parts_assembled
• /Car_done.Car_made.Painted
States can also contain nongraphical data, event, and message objects. The hierarchy of
this containment appears in the Model Explorer. You define data, event, and message
containment by specifying the parent object.
2-15
2 Stateflow Chart Notation
State Decomposition
Every state (or chart) has a decomposition that dictates what type of substates the state
(or chart) can contain. All substates of a superstate must be of the same type as the
superstate decomposition. State decomposition can be exclusive (OR) or parallel (AND).
In the following example, either state A or state B can be active. If state A is active, either
state A1 or state A2 can be active at a given time.
In the following example, when state A is active, A1 and A2 are both active at the same
time.
2-16
State Decomposition
In the following example, when state A becomes active, both states B and C become active
at the same time. When state C becomes active, either state C1 or state C2 can be active.
2-17
2 Stateflow Chart Notation
Transitions
A transition is a 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) to another.
A transition typically connects a source and a destination object. The source object is
where the transition begins and the destination object is where the transition ends. The
following chart shows a transition from a source state, B, to a destination state, A.
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.
The following example has two segmented transitions: one from state On to state Off, and
the other from state On to itself:
2-18
Transitions
A default transition is a special type of transition that has no source object. See “Default
Transitions” on page 2-33 for details.
Transition Hierarchy
Transitions cannot contain other objects the way that states can. However, transitions are
contained by states. The hierarchy for a transition is described in terms of its parent,
source, and destination states. The parent is the lowest level that contains the source and
destination of the transition. Consider the parents for the transitions in the following
example:
2-19
2 Stateflow Chart Notation
The following table resolves the parentage of each transition in the preceding example.
The / character represents the chart. Each level in the hierarchy of states is separated by
the period (.) character.
event_or_message[condition]{condition_action}/transition_action
2-20
Transitions
Specifies an event or message that causes the transition to occur when the condition is
true. Specify multiple events using the OR logical operator (|). Specifying an event or
message is optional. The absence of an event or message indicates that the transition
takes place on the occurrence of any event. For more information, see “Synchronize
Model Components by Broadcasting Events” on page 10-2 and “Communicate with
Stateflow Charts by Sending Messages” on page 11-10.
In the previous example, the broadcast of event E triggers the transition from On to Off if
the condition [off_count==0] is true.
Condition
Specifies a Boolean expression that, when true, validates a transition for the specified
event or message trigger. Enclose the condition in square brackets ([]). If no condition is
specified, an implied condition evaluates to true. For more information, see “Conditions”
on page 12-8.
In the previous example, when the event E occurs, the condition [off_count==0] must
evaluate as true for the transition from On to Off to be valid.
Condition Action
Executes after the condition for the transition is evaluated as true, but before the
transition to the destination is determined to be valid. Enclose the condition action in
curly braces ({}) following the condition. For more information, see “Condition Action
Behavior” on page B-10.
2-21
2 Stateflow Chart Notation
In the previous example, if the event E occurs and the condition [off_count==0] is
true, then the condition action {off_count = off_count + 1} is immediately
executed.
Transition Action
Executes after the transition to the destination is determined to be valid. If the transition
consists of multiple segments, then the transition action is executed when the entire
transition path to the final destination is determined to be valid. Transition actions occur
after the exit actions of the source state and before the entry actions of the destination
state. Precede the transition action with a /. For more information, see “Condition and
Transition Action Behavior” on page B-11.
In the preceding example, if the event E occurs and the condition [off_count==0] is
true, then the transition action {Light_off()} is executed when the transition from On
to Off is determined to be valid. The transition action occurs after On becomes inactive,
but before Off becomes active.
Valid Transitions
Usually, a transition is valid when the source state of the transition is active and the
transition label is valid. Default transitions are 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 table lists possible
combinations of valid transition labels.
2-22
Transitions
Transition Connections
Transitions to and from Exclusive (OR) States
This example shows simple transitions to and from exclusive (OR) states.
See “Transition Between Exclusive States” on page B-4 for more information on the
semantics of this notation.
2-23
2 Stateflow Chart Notation
The chart uses temporal logic to determine when the input u equals 1.
For more information about temporal logic, see “Control Chart Execution by Using
Temporal Logic” on page 12-49. For more information on the semantics of this notation,
see “Transition from a Common Source to Multiple Destinations” on page B-34.
This example shows transitions to and from an exclusive (OR) superstate and the use of a
default transition.
The chart has two states at the highest level in the hierarchy, Power_off and Power_on.
By default, Power_off is active. The event Switch toggles the system between the
Power_off and Power_on states. Power_on has three substates: First, Second, and
Third. By default, when Power_on becomes active, First also becomes active. When
Shift equals 1, the system transitions from First to Second, Second to Third, Third
to First, for each occurrence of the event Switch, and then the pattern repeats.
2-24
See Also
For more information on the semantics of this notation, see “Control Chart Execution by
Using Default Transitions” on page B-16.
The following example shows transitions to and from exclusive (OR) substates.
For details on how this chart works, see “Debounce Signals with Fault Detection” on page
26-7. For information on the semantics of this notation, see “Transition from a Substate
to a Substate with Events” on page B-8.
See Also
More About
• “Default Transitions” on page 2-33
• “Transition Action Types” on page 12-7
• “Control Chart Execution by Using Condition Actions” on page B-10
2-25
2 Stateflow Chart Notation
2-26
Self-Loop Transitions
Self-Loop Transitions
A self-loop transition is a transition that originates from and terminates on the same state.
The following chart contains four self-loop transitions:
2-27
2 Stateflow Chart Notation
See these sections for more information about the semantics of this notation:
2-28
Inner Transitions
Inner Transitions
An inner transition is a transition that does not exit the source state. Inner transitions are
powerful when defined for superstates with exclusive (OR) decomposition. Use of inner
transitions can greatly simplify a Stateflow chart, as shown by the following examples:
2-29
2 Stateflow Chart Notation
Any event occurs and awakens the Stateflow chart. The default transition to the
connective junction is valid. The destination of the transition is determined by [c1 > 0]
and [c2 > 0]. If [c1 > 0] is true, the transition to A1 is true. If [c2 > 0] is true, the
transition to A2 is valid. If neither [c1 > 0] nor [c2 > 0] is true, the transition to A3 is
valid. The transitions among A1, A2, and A3 are determined by E, [c1 > 0], and [c2 >
0].
An event occurs and awakens the chart. The default transition to the connective junction
is valid. The destination of the transitions is determined by [c1 > 0] and [c2 > 0].
You can simplify the chart by using an inner transition in place of the transitions among
all the states in the original example. 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 occurs,
the inner transition is potentially valid. If [c1 > 0] is true, the transition to A1 is valid. If
[c2 > 0] is true, the transition to A2 is valid. If neither [c1 > 0] nor [c2 > 0] is true,
the transition to A3 is valid. This chart design is simpler than the previous one.
2-30
Inner Transitions
Note When you use an inner transition to a connective junction, an active substate can
exit and reenter when the transition condition for that substate is valid. For example, if
substate A1 is active and [c1 > 0] is true, the transition to A1 is valid. In this case:
See “Process the First Event with an Inner Transition to a Connective Junction” on page
B-24 for more information on the semantics of this notation.
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
2-31
2 Stateflow Chart Notation
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 self-loop transition on both Power_on.Low and Power_on.High.
See “Example of History Junctions” on page 2-44 for another example using a history
junction.
See “Inner Transition to a History Junction” on page B-26 for more information on the
semantics of this notation.
2-32
Default Transitions
Default Transitions
A default transition specifies which exclusive (OR) state to enter when there is ambiguity
among two or more neighboring exclusive (OR) states. A default transition has a
destination but no source object. For example, a default transition specifies 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. A default transition
can also specify that a junction should be entered by default.
Tip When labeling default transitions, ensure that there is at least one valid default
transition. Otherwise, a chart can transition into an inconsistent state.
2-33
2 Stateflow Chart Notation
Without the default transition to state PowerOff, when the Stateflow chart wakes up,
none of the states becomes active. A state inconsistency error is reported at run time.
See “Control Chart Execution by Using Default Transitions” on page B-16 for
information on the semantics of this notation.
2-34
Default Transitions
The default transition to the connective junction defines that upon entering the chart, the
destination depends on the condition of each transition segment.
See “Default Transition to a Junction” on page B-17 for information on the semantics of
this notation.
When the chart wakes up, the data p and v initialize to 10 and 15, respectively.
2-35
2 Stateflow Chart Notation
See “Labeled Default Transitions” on page B-19 for more information on the semantics
of this notation.
2-36
Connective Junctions
Connective Junctions
A connective junction enables representation of different possible transition paths for a
single transition. Connective junctions are used to help represent the following:
See “Represent Multiple Paths by Using Connective Junctions” on page B-28 for a
summary of the semantics of connective junctions.
Flow chart notation, states, and state-to-state transitions coexist in the same Stateflow
chart. The key to representing flow chart notation is in the labeling of transitions, as
shown in the following examples.
2-37
2 Stateflow Chart Notation
2-38
Connective Junctions
For more information about this chart, see “Phases of Chart Execution” on page 3-9.
For more information on the semantics of this notation, see “If-Then-Else Decision
Construct” on page B-29.
The chart uses temporal logic to determine when the input u equals 1.
For more information about temporal logic, see “Control Chart Execution by Using
Temporal Logic” on page 12-49. For more information on the semantics of this notation,
see “If-Then-Else Decision Construct” on page B-29.
This example shows a combination of flow chart notation and state transition notation.
Self-loop transitions to connective junctions can represent for loop constructs. The chart
uses implicit ordering of outgoing transitions (see “Implicit Ordering” on page 3-65).
2-39
2 Stateflow Chart Notation
See “For-Loop Construct” on page B-31 for information on the semantics of this
notation.
This example shows the use of flow chart notation. The chart uses implicit ordering of
outgoing transitions (see “Implicit Ordering” on page 3-65).
2-40
Connective Junctions
See “Flow Chart Notation” on page B-32 for information on the semantics of this
notation.
This example shows transition segments from a common source to multiple conditional
destinations using a connective junction. The chart uses implicit ordering of outgoing
transitions (see “Implicit Ordering” on page 3-65).
See “Transition from a Common Source to Multiple Destinations” on page B-34 for
information on the semantics of this notation.
This example shows transition segments from multiple sources to a single destination
based on the same event using a connective junction.
2-41
2 Stateflow Chart Notation
See “Transition from a Source to a Destination Based on a Common Event” on page B-37
for information on the semantics of this notation.
Field Description
Parent Parent of the connective junction (read-only). To
bring the parent to the foreground, click the
hypertext link.
Description Textual description or comment.
Document link Link to other information. Enter a URL address or a
general MATLAB command. Examples are
www.mathworks.com, mailto:email_address,
and edit/spec/data/speed.txt.
2-42
Connective Junctions
2-43
2 Stateflow Chart Notation
History Junctions
A history junction represents historical decision points in the Stateflow chart. The
decision points are based on historical data relative to state activity. Placing a history
junction in a superstate indicates that historical state activity information is used to
determine the next state to become active. The history junction applies only to the level of
the hierarchy in which it appears.
Superstate Power_on has a history junction and contains two substates. If state
Power_off is active and event switch_on occurs, the system can enter 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. Because
Power_on.High was the last active substate, it becomes active again. After the first time
Power_on becomes active, the history junction determines whether to enter
Power_on.Low or Power_on.High.
See “Default Transition and a History Junction” on page B-17 for more information on
the semantics of this notation.
2-44
History Junctions
See “Using an Inner Transition to a History Junction” on page 2-31 for an example of this
notation.
See “Inner Transition to a History Junction” on page B-26 for more information on the
semantics of this notation.
2-45
2 Stateflow Chart Notation
• Flow chart — Encapsulate flow charts containing if-then-else, switch-case, for, while,
or do-while patterns. For more information, see “Reuse Logic Patterns by Defining
Graphical Functions” on page 8-16.
• MATLAB — Write matrix-oriented algorithms; call MATLAB functions for data analysis
and visualization. For more information, see “Reuse MATLAB Code by Defining
MATLAB Functions” on page 28-2.
• Simulink — Call Simulink function-call subsystems directly to streamline design and
improve readability. For more information, see “Reuse Simulink Components in
Stateflow Charts” on page 29-2.
• Truth table — Represent combinational logic for decision-making applications such as
fault detection and mode switching. For more information, see “Reuse Combinatorial
Logic by Defining Truth Tables” on page 27-2.
Use the function format that is most natural for the type of calculation required in the
state action or transition condition.
If the four standard types of Stateflow functions do not work, you can write your own C or
C++ code for integration with your chart. For more information about custom code
integration, see “Reuse Custom Code in Stateflow Charts” on page 30-26.
See Also
More About
• “Reuse Logic Patterns by Defining Graphical Functions” on page 8-16
• “Reuse MATLAB Code by Defining MATLAB Functions” on page 28-2
• “Reuse Combinatorial Logic by Defining Truth Tables” on page 27-2
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Reuse Custom Code in Stateflow Charts” on page 30-26
2-46
3
Stateflow Semantics
Stateflow Semantics
In Stateflow, semantics describe the execution behavior of your Stateflow chart. Various
factors can affect how your chart executes, including:
As you build your chart, you expect it to behave in a certain way. By knowing how these
factors affect your chart, you can create a chart that behaves with intentional interaction
of the graphical and nongraphical objects. Graphical and nongraphical objects are the
building blocks for all Stateflow charts.
Stateflow Objects
Stateflow objects are the building blocks of Stateflow charts. These objects can be
categorized as either graphical or nongraphical. Graphical objects consist of objects that
appear graphically in a chart. Nongraphical objects appear textually in a chart and often
refer to data, events, and messages. This chart shows a variety of both graphical and
nongraphical objects.
3-2
Stateflow Semantics
Graphical Objects
To build graphical objects, use the object palette in the Stateflow Editor (see “Stateflow
Editor Operations” on page 4-28).
Self-loop transitions
3-3
3 Stateflow Semantics
Nongraphical Objects
You create nongraphical objects textually in your chart. See “Add Stateflow Data” on page
9-2, “Define Events in a Chart” on page 10-3, and “Define Messages in a Chart” on
page 11-10 for details. Examples of nongraphical objects include:
See Also
More About
• “Graphical Objects” on page 2-2
• “Nongraphical Objects” on page 2-2
• “Types of Chart Execution” on page 3-41
3-4
How Stateflow Objects Interact During Execution
For details of the chart semantics, see “Phases of Chart Execution” on page 3-9.
3-5
3 Stateflow Semantics
• Checking in to a hotel
• Calling room service
• Triggering a fire alarm
• Sending an all-clear signal after a
fire alarm
3-6
How Stateflow Objects Interact During Execution
The Hotel chart contains graphical objects, such as states and history junctions, and
nongraphical objects, such as conditions and condition actions.
3-7
3 Stateflow Semantics
For a mapping of objects to their locations in the chart, see “Stateflow Objects” on page
3-2.
3-8
How Stateflow Objects Interact During Execution
When simulation starts, the chart wakes up and executes its default transitions because
the Execute (enter) Chart At Initialization option is on (see “Execution of a Chart at
Initialization” on page 3-42). Then the chart goes to sleep.
Note If this option is off, the chart does not wake up until you toggle one of the Manual
Switch blocks. You can verify the setting for this option in the Chart properties dialog box.
Right-click inside the top level of the chart and select Properties from the context menu.
The chart wakes up again only when an edge-triggered input event occurs: check_in,
room_service, fire_alarm, or all_clear. When you toggle a Manual Switch block
for an input event during simulation, the chart detects a rising or falling edge and wakes
up. While the chart is awake:
• The Multiport Switch block provides a value for the chart input data room_type.
• The Display block shows any change in value for the chart output data fee.
Chart Inactivity
After completing all possible phases of execution, the chart goes back to sleep.
3-9
3 Stateflow Semantics
This section describes what happens in the Front_desk state just after the chart wakes
up.
3-10
How Stateflow Objects Interact During Execution
3-11
3 Stateflow Semantics
This section describes what happens after exiting the Front_desk state: the evaluation
of a group of outgoing transitions from a single junction.
3-12
How Stateflow Objects Interact During Execution
3-13
3 Stateflow Semantics
Because the Multiport Switch block outputs only 1, 2, or 3, room_type cannot have any
other values. However, if room_type has a value other than 1, 2, or 3, the chart stays in
the Front_desk state. This behavior applies because no transition path out of that state
is valid.
This section describes what happens after you enter the Checked_in state, regardless of
which substate becomes active.
3-14
How Stateflow Objects Interact During Execution
3-15
3 Stateflow Semantics
This part of the chart describes how you can perform function calls while a state is active.
3-16
How Stateflow Objects Interact During Execution
function y = expenses(x)
if (room_type == 1)
y = 1500 + (x*50);
else
if (room_type == 2)
y = 1000 + (x*25);
else
y = 500 + (x*5);
end
end
Modeling Guidelines for Function Calls. The following guidelines apply to function
calls.
This part of the chart shows how a state with exclusive (OR) decomposition executes.
3-17
3 Stateflow Semantics
3-18
How Stateflow Objects Interact During Execution
This part of the chart shows how a state with parallel (AND) decomposition executes.
3-19
3 Stateflow Semantics
3-20
How Stateflow Objects Interact During Execution
3-21
3 Stateflow Semantics
This part of the chart describes how events can guard transitions between exclusive (OR)
states.
3-22
How Stateflow Objects Interact During Execution
a Dining_area
b Executive_suite
c Checked_in
d Check_in
2 Waiting_area becomes active.
2 If an all-clear signal When the chart receives an event broadcast for all_clear, a
occurs, you can leave the transition from Waiting_area to the previously active substate
waiting area and return of Check_in occurs.
to your previous location
inside the hotel. The history junction at each level of hierarchy in Check_in
enables the chart to remember which substate was previously
active before the transition to Waiting_area occurred.
a Check_in
b Checked_in (The default transition does not apply.)
c Executive_suite
d Dining_area (The default transition does not apply.)
3-23
3 Stateflow Semantics
3-24
Modeling Guidelines for Stateflow Charts
Unless an execution delay is necessary, use condition actions instead of transition actions.
3-25
3 Stateflow Semantics
This guideline enables reuse of state actions that apply to multiple substates. You write
the state actions only once, instead of writing them separately in each substate.
Note You cannot use boxes for this purpose because boxes do not support state actions.
3-26
Modeling Guidelines for Stateflow Charts
3-27
3 Stateflow Semantics
Enable the edit-time checking and syntax error highlighting through the Display > Error
& Warnings check box.
3-28
Detect Modeling Errors During Edit Time
Note Subcharts with syntax errors appear red in the parent chart with a badge
indicating a syntax issue. In the subchart editor, the object is highlighted in red, however
there is no badge indicating the issue.
Dangling Transition
A dangling transition is not connected to a destination object. Transitions must have a
valid source state or junction and a valid destination state or junction. See “Transitions”
on page 2-18.
Control the level of diagnostic action by setting the Unreachable execution path
diagnostic configuration parameter.
3-29
3 Stateflow Semantics
Unreachable State
A state is unreachable when there is no valid execution path leading to the state. To make
the state a reachable destination, connecting it with a transition from a reachable state or
junction.
Control the level of diagnostic action by setting the Unreachable execution path
diagnostic configuration parameter.
Transition Shadowing
Transition shadowing occurs when a chart contains an unconditional transition
originating from a source that prevents other transitions from the same source from
executing. To avoid transition shadowing:
• Create no more than one unconditional transition for each group of outgoing
transitions from a state or junction.
• Explicitly specify an unconditional transition as a lower evaluation order than any
transitions with conditions. See “Transition Evaluation Order” on page 3-65.
3-30
Detect Modeling Errors During Edit Time
Control the level of diagnostic action by setting the Unreachable execution path
diagnostic configuration parameter.
3-31
3 Stateflow Semantics
Control the level of diagnostic action by setting the Transition outside natural parent
diagnostic configuration parameter.
3-32
Detect Modeling Errors During Edit Time
3-33
3 Stateflow Semantics
If one path along the default transition remains unconditional, you can include multiple
junctions and transitions.
3-34
Detect Modeling Errors During Edit Time
Unexpected Backtracking
Unintended backtracking of control flow can occur at a junction when these conditions
are true:
• The junction does not have an unconditional transition path to a state or terminating
junction.
• Multiple transition paths that share a source lead to the junction.
3-35
3 Stateflow Semantics
3-36
Detect Modeling Errors During Edit Time
To prevent the chart from exiting and reentering state A, move the transition so that it is
contained within state A.
Control the level of diagnostic action by setting the Transition outside natural parent
diagnostic configuration parameter.
3-37
3 Stateflow Semantics
For example, in this chart, if ConditionA and ConditionB are true, then
ConditionAction2 occurs before TransitionAction1. The transition path from state
A to state B follows this order:
• State A is active.
• Chart evaluates ConditionA.
• Chart evaluates ConditionB.
• Chart executes ConditionAction2.
• State A becomes inactive.
• Chart executes TransitionAction1.
• State B becomes active.
To improve the clarity of the chart, place the transition action after the last condition
action on the path.
3-38
Detect Modeling Errors During Edit Time
Control the level of diagnostic action by setting the Transition action specified before
condition action diagnostic configuration parameter.
3-39
3 Stateflow Semantics
See Also
More About
• “Detect Common Modeling Errors During Chart Simulation” on page 32-28
• “Modeling Guidelines for Stateflow Charts” on page 3-25
• “Stateflow Semantics” on page 3-2
• “Model Configuration Parameters: Stateflow Diagnostics” (Simulink)
3-40
Types of Chart Execution
Stage Description
Inactive Chart has no active states
Active Chart has active states
Sleeping Chart has active states, but no events to
process
When a Simulink model first triggers a Stateflow chart, the chart is inactive and has no
active states. After the chart executes and completely processes its initial trigger event
from the Simulink model, it transfers control back to the model and goes to sleep. At the
next Simulink trigger event, the chart changes from the sleeping to active stage.
If executing the default flow paths does not cause state entry, a state inconsistency error
occurs.
3-41
3 Stateflow Semantics
By default, the first time a chart wakes up, it executes the default transition paths. At this
time, the chart can access inputs, write to outputs, and broadcast events.
If you want your chart to begin executing from a known configuration, you can enable the
Execute (enter) Chart At Initialization chart property. When you turn on this option,
the state configuration of a chart initializes at time 0 instead of the first occurrence of an
input event. The default transition paths of the chart execute during the model
initialization phase at time 0, corresponding to the mdlInitializeConditions() phase for S-
functions. For more information, see “Execute (Enter) Chart at Initialization” on page 24-
7.
Note If an output of this chart connects to a SimEvents® block, do not select this check
box. To learn more about using Stateflow charts and SimEvents blocks together in a
model, see the SimEvents documentation.
Due to the transient nature of the initialization phase, do not perform certain actions in
the default transition paths of the chart — and associated state entry actions — which
execute at initialization. Follow these guidelines:
• Do not access chart input data, because blocks connected to chart input ports might
not have initialized their outputs yet.
• Do not call exported graphical functions from other charts, because those charts might
not have initialized yet.
• Do not broadcast function-call output events, because the triggered subsystems might
not have initialized yet.
You can control the level of diagnostic action for invalid access to chart input data in the
Diagnostics > Stateflow pane of the Configuration Parameters dialog box. For more
information, see the documentation for the “Invalid input data access in chart
initialization” (Simulink) diagnostic.
3-42
See Also
See Also
More About
• “Execution of a Stateflow Chart” on page 3-44
• “Exit a State” on page 3-58
• “Evaluate Transitions” on page 3-63
3-43
3 Stateflow Semantics
When a chart wakes up for the first time, the chart is initialized and becomes active. See
“Chart Entry” on page 3-52. Once the chart is active but with no more actions to take,
the chart goes to sleep until it is triggered by a new time step or an event.
3-44
Execution of a Stateflow Chart
3-45
3 Stateflow Semantics
During Actions
During actions for a state execute when:
• The state is active, a new time step occurs, and no valid transition to another state is
available.
• The state is active, an event occurs, and no valid transition to another state is
available.
During actions are preceded by the prefix during or du, and then followed by a required
colon (:), followed by one or more actions. Separate multiple actions with a carriage
return, semicolon (;), or a comma (,). If you do not specify the state action type explicitly
for a statement, the chart treats that statement as an entry,during action.
A state performs its during actions (if specified) when the chart wakes up. The preceding
flow chart depicts the process of state execution and shows when during actions occur.
If your Stateflow chart does not contain states, each time the chart is executed, Stateflow
always evaluates the default transition path.
Outgoing Transition
Stateflow marks outgoing transitions for evaluation as a part of the execution of a
Stateflow chart. Once an outgoing transition is marked for evaluation, follow the
“Workflow for Evaluating Transitions” on page 3-64. For more information about how
Stateflow evaluates outgoing transitions, see “Evaluate Transitions” on page 3-63.
Inner Transitions
Stateflow marks inner transitions for evaluation as a part of the execution of a Stateflow
chart. Once an inner transition is marked for evaluation, follow the “Workflow for
Evaluating Transitions” on page 3-64. For more information about how Stateflow
evaluates inner transitions, see “Evaluate Transitions” on page 3-63.
3-46
Execution of a Stateflow Chart
By following the “Workflow for Stateflow Chart Execution” on page 3-44, the execution
steps for chart execution are in this order:
To complete the time step, follow the “Workflow for Exiting a State” on page 3-58 for
StateA and the “Workflow for Entering a Chart or State” on page 3-50 for StateB.
3-47
3 Stateflow Semantics
By following the “Workflow for Stateflow Chart Execution” on page 3-44 until the chart
goes to sleep, the execution steps for chart execution are in this order:
3-48
See Also
See Also
More About
• “Enter a Chart or State” on page 3-50
• “Exit a State” on page 3-58
• “Evaluate Transitions” on page 3-63
3-49
3 Stateflow Semantics
• A chart is activated for the first time. This is called chart initialization.
• A valid transition into a state exists. See “Evaluate Transitions” on page 3-63.
3-50
Enter a Chart or State
3-51
3 Stateflow Semantics
Chart Entry
The first time that your Stateflow chart becomes active is called initialization. When
initialization of your chart occurs, the chart is entered and Stateflow executes any default
transitions for exclusive (OR) states. If the states at the top level of your chart are parallel
(AND), they become active based on their order number.
If you want your chart to take any default transitions at time t = 0, in the Chart
Properties dialog box, select the Execute (enter) Chart At Initialization check box.
The default transition paths of the chart then execute during the model initialization
phase.
State Entry
When a state is marked for entry, entry actions for a state execute. Once your chart is
active and has gone through initialization, the top-level state becomes active. A state is
marked for entry in one of these ways:
Entry Actions
Entry actions are preceded by the prefix entry or en for short, followed by a required
colon (:), and then followed by one or more actions. You separate multiple actions by
using a carriage return, a semicolon (;), or a comma (,). If you do not specify the state
action type explicitly for a statement, the chart treats that statement as an entry,during
action.
3-52
Enter a Chart or State
By following the “Workflow for Entering a Chart or State” on page 3-50 until the chart
goes to sleep, the steps for chart initialization are in this order:
3-53
3 Stateflow Semantics
Steps 1 through 14 take place in the initial time step. This completes the chart
initialization process.
In this example, a light can be on or off. These options are indicated by the states
Power_on and Power_off. The options are controlled by the input events switch_on
and switch_off. When the light is on, it can be dim or bright. These options are
indicated by the states Low and High and are controlled by the input events switch_low
and switch_high.
Initially, the chart is asleep. The state Power_off is active. When the state Power_on
was last active, High was the previously active substate. The event switch_on occurs
and the state Power_on is marked for entry. At this time p = 0.
3-54
Enter a Chart or State
By following the “Workflow for Entering a Chart or State” on page 3-50 until the chart
goes to sleep, the execution steps for entering the state Power_on are in this order:
3-55
3 Stateflow Semantics
When a state is entered through a supertransition, before the entry actions for the final
destination are executed, its superstates must be marked active and their entry actions
must be executed. In this example, StateB1 has been marked for entry from StateA2. At
this point, x = 5, y = 5, and z = 1.
By following the “Workflow for Entering a Chart or State” on page 3-50 until the chart
goes to sleep, the execution steps for entering the state StateB1 are in this order:
3-56
See Also
See Also
More About
• “Execution of a Stateflow Chart” on page 3-44
• “Exit a State” on page 3-58
• “Evaluate Transitions” on page 3-63
3-57
3 Stateflow Semantics
Exit a State
When there is a valid transition out of a state, that state is marked for exit. A state is
marked for exit in one of these ways:
3-58
Exit a State
Exit Actions
Exit actions for a state execute when the state is active and a valid transition from the
state exists. A state performs its exit actions before becoming inactive.
Exit actions are preceded by the prefix exit or ex, followed by a required colon (:), and
then followed by one or more actions. Separate multiple actions with a carriage return,
semicolon (;), or a comma (,).
3-59
3 Stateflow Semantics
By following the “Workflow for Stateflow Chart Execution” on page 3-44 and the
“Workflow for Evaluating Transitions” on page 3-64, StateB has been marked for entry.
StateA is the source of the transition. At this time step x = 5, y = 2, and z = 0.
By following the flow chart for state exit actions until the chart goes to sleep, the
execution steps for this chart are in this order:
These steps complete the exit workflow for StateA. However, the chart is not yet
asleep.
Perform the “Workflow for Entering a Chart or State” on page 3-50 for StateB to
complete the time step.
3-60
Exit a State
When a state is exited through a supertransition, after the exit actions for the source of
the transition are executed, its superstates are marked inactive and exit actions of the
superstates are executed. In this example, StateA2 is marked for exit and StateB1 is
marked for entry. At this point, x = 5, y = 5, and z = 0.
By following the “Workflow for Entering a Chart or State” on page 3-50 until the chart
goes to sleep, the execution steps for exiting the state StateA2 are in this order:
1 StateA2 is not a superstate of the destination state (StateB1).
2 Perform the exit actions for StateA2 and mark StateA2 as inactive.
3 StateA2 does have a parent state, StateA.
4 StateA is not a superstate of the destination state (StateB1).
5 Perform the exit actions for StateA, and mark StateA as inactive.
6 StateA does not have a parent state.
These actions complete the exit workflow for StateA2 and StateA. However, the chart
is not yet asleep.
3-61
3 Stateflow Semantics
Perform the “Workflow for Entering a Chart or State” on page 3-50 for StateB and
StateB1 to complete the time step.
See Also
More About
• “Execution of a Stateflow Chart” on page 3-44
• “Enter a Chart or State” on page 3-50
• “Evaluate Transitions” on page 3-63
3-62
Evaluate Transitions
Evaluate Transitions
Stateflow uses transitions in charts to move from one exclusive (OR) state to another
exclusive (OR) state. For the entry and execution workflows of chart execution,
Stateflow evaluates transitions to determine if they are valid. A valid transition is a
transition whose condition labels are true and whose path ends at a state. If a transition is
valid, Stateflow exits from the source state and enters the destination state. To learn
about when evaluation occurs during the execution and entry workflows, see
“Execution of a Stateflow Chart” on page 3-44 and “Enter a Chart or State” on page 3-50.
3-63
3 Stateflow Semantics
3-64
Evaluate Transitions
Note Use explicit ordering to avoid your transitions from changing order while you are
editing a chart.
Explicit Ordering
When you open a new Stateflow chart, all outgoing transitions from a source are
automatically numbered in the order in which you create them. The order starts with 1
and continues to the next available number for the source.
To change the execution order of a transition, right-click the transition, place your cursor
over Execution Order, and select the order in which you want your transition to
execute. When you change a transition number, the Stateflow chart automatically
renumbers the other outgoing transitions for the source by preserving their relative
order.
Implicit Ordering
For C charts in implicit ordering mode, a Stateflow chart evaluates a group of outgoing
transitions from a single source based on:
• Hierarchy.
3-65
3 Stateflow Semantics
A chart evaluates a group of outgoing transitions with equal hierarchical and label
priority based on angular position on the surface of the source object. The transition
with the smallest clock position has the highest priority. For example, a transition with
a 2 o'clock source position has a higher priority than a transition with a 4 o'clock
source position. A transition with a 12 o'clock source position has the lowest priority.
3-66
Evaluate Transitions
By following the “Workflow for Evaluating Transitions” on page 3-64, the steps for
evaluating the transitions of this chart are in this order:
To complete the time step, follow the “Workflow for Exiting a State” on page 3-58 for
StateA and the “Workflow for Entering a Chart or State” on page 3-50 for StateE.
In this example, the Stateflow chart is initialized and the entry actions are performed for
StateA. A new time step occurs, and the chart wakes up. By following the “Workflow for
Stateflow Chart Execution” on page 3-44, Stateflow finds multiple outgoing transitions
from StateA. At this time step x = 1, y = 1, and z = 1.
3-67
3 Stateflow Semantics
By following the “Workflow for Evaluating Transitions” on page 3-64, the steps for
evaluating the transitions of this chart are in this order:
3-68
Evaluate Transitions
To complete the time step, follow the “Workflow for Exiting a State” on page 3-58 for
StateA and the “Workflow for Entering a Chart or State” on page 3-50 for StateE.
Prevent Backtracking
By following the “Workflow for Evaluating Transitions” on page 3-64, the steps for
evaluating the transitions of this chart are in this order:
3-69
3 Stateflow Semantics
To complete the time step, follow the “Workflow for Stateflow Chart Execution” on page
3-44 for StateA, starting where you left off.
In transition label syntax, condition actions follow the transition condition and are
enclosed in curly braces ({}). Condition actions are executed when the condition is
evaluated as true but before the transition path has been determined to be valid.
Transition Actions
In transition label syntax, transition actions are preceded with a forward slash (/) and are
enclosed in curly braces ({}). Transition actions execute only after the transition path is
determined to be valid.
In this example, both condition actions and transition actions exist. The Stateflow chart is
initialized and the entry actions are performed for StateA. A new time step occurs and
the chart wakes up. There are multiple outgoing transitions from StateA. At this time
step x = 1, y = 1, and z = 1.
3-70
Evaluate Transitions
By following the “Workflow for Evaluating Transitions” on page 3-64, the steps for
evaluating the transitions of this chart are in this order:
3-71
3 Stateflow Semantics
To complete the time step, follow the “Workflow for Exiting a State” on page 3-58 for
StateA and the “Workflow for Entering a Chart or State” on page 3-50 for StateE.
See Also
More About
• “Execution of a Stateflow Chart” on page 3-44
• “Enter a Chart or State” on page 3-50
• “Exit a State” on page 3-58
3-72
Super Step Semantics
When you enable super step semantics, a Stateflow chart executes multiple times for
every active input event or for every time step when the chart has no input events. The
chart takes valid transitions until either of these conditions occurs:
• No more valid transitions exist, that is, the chart is in a stable active state
configuration.
• The number of transitions taken exceeds a user-specified maximum number of
iterations.
In a super step, your chart responds faster to inputs but performs more computations in
each time step. Therefore, when generating code for an embedded target, make sure that
the chart can finish the computation in a single time step. To achieve this behavior, fine-
tune super step parameters by setting an upper limit on the number of transitions that
the chart takes per time step (see “Maximum Number of Iterations” on page 3-73).
For simulation targets, specify whether the chart goes to the next time step or generates
an error if it reaches the maximum number of transitions prematurely. However, in
generated code for embedded targets, the chart always goes to the next time step after
taking the maximum number of transitions.
3-73
3 Stateflow Semantics
2 In the Chart properties dialog box, select the Enable Super Step Semantics check
box.
3-74
Super Step Semantics
The chart always takes one transition during a super step, so the value N that you
specify represents the maximum number of additional transitions (for a total of N+1).
Try to choose a number that allows the chart to reach a stable state within the time
step, based on the mode logic of your chart. For more information, see “Maximum
Number of Iterations” on page 3-73
4 Select an action from the drop-down menu in the field Behavior after too many
iterations.
Your selection determines how the chart behaves during simulation if it exceeds the
maximum number of iterations in the super step before reaching a stable state.
Behavior Description
Proceed The chart goes back to sleep with the last active state
configuration, that is, after updating local data at the last
valid transition in the super step.
Throw Error Simulation stops and the chart generates an error,
indicating that too many iterations occurred while trying
to reach a stable state.
Note This option is relevant only for simulation targets. For embedded targets, code
generation goes to the next time step rather than generating an error.
3-75
3 Stateflow Semantics
By default, the chart takes only one transition in each simulation step, incrementing y
each time.
When you enable super step semantics, the chart takes all valid transitions in each time
step, stopping at state C with y = 3.
3-76
Super Step Semantics
3-77
3 Stateflow Semantics
In this model, the Sum block produces a 2-by-1 vector signal that goes from [0,0] to [1,1]
at time t = 1. As a result, when the model wakes up the chart, events E1 and E2 are both
active:
If you enable super step semantics, the chart takes all valid transitions for event E1. The
chart takes transitions from state A to B and then from state B to C in a single super step.
The scope shows that y = 3 at the end of the super step:
3-78
Super Step Semantics
In a super step, this chart never transitions to state D because there is no path from state
C to state D.
3-79
3 Stateflow Semantics
In this example, the transitions between states A and B cycle and produce an infinite loop
because the value of x remains constant at 1. One way to detect infinite loops is to
configure your chart to generate an error if it reaches a maximum number of iterations in
a super step. See “Enable Super Step Semantics” on page 3-73.
3-80
How Events Drive Chart Execution
Because a chart runs on a single thread, actions that take place based on an event are
atomic to that event. All activity caused by the event in the chart finishes before execution
returns to the activity that was taking place before receiving the event. Once an event
initiates an action, the action completes unless interrupted by an early return.
3-81
3 Stateflow Semantics
Events have hierarchy (a parent) and scope. The parent and scope together define a
range of access to events. The parent of an event usually determines who can trigger on
the event (has receive rights). See the Name and Parent fields for an event in “Set
Properties for an Event” on page 10-6 for more information.
All events, except for the output edge trigger to a Simulink block (see the following note),
have the following execution in a chart:
1 If the receiver of the event is active, then it executes (see “Execution of a Stateflow
Chart” on page 3-44). (The event receiver is the parent of the event unless a directed
event broadcast occurs using the send() function.)
2 If the receiver of the event is not active, nothing happens.
3 After broadcasting the event, the broadcaster performs early return logic based on
the type of action statement that caused the event.
To learn about early return logic, see “Early Return Logic for Event Broadcasts” on
page 3-93.
3-82
Group and Execute Transitions
• Default flow charts are all default transition segments that start with the same parent.
• Inner flow charts are all transition segments that originate on a state and reside
entirely within that state.
• Outer flow charts are all transition segments that originate on the respective state but
reside at least partially outside that state.
Each set of flow charts includes other transition segments connected to a qualifying
transition segment through junctions and transitions. Consider the following example:
In this example, state A has both an inner and a default transition that connect to a
junction with outgoing transitions to states A.A1 and A.A2. If state A is active, its set of
inner flow charts includes:
3-83
3 Stateflow Semantics
• The two outgoing transitions from the junction to state A.A1 and A.A2
In this case, the two outgoing transition segments from the junction are members of more
than one flow chart type.
An active state can have several possible outgoing transitions. The chart orders these
transitions before checking them for validity. See “Transition Evaluation Order” on
page 3-65.
2 Select the next transition segment in the set of ordered transitions.
3 Test the transition segment for validity.
4 If the segment is invalid, go to step 2.
5 If the destination of the transition segment is a state, do the following:
3-84
Group and Execute Transitions
a Backtrack the incoming transition segment that brought you to the junction.
b Continue at step 2, starting with the next transition segment after the backup
segment.
The set of flow charts completes execution when all starting transitions have been
tested.
3-85
3 Stateflow Semantics
Unlike exclusive (OR) states, parallel states do not typically use transitions. Instead, order
of execution depends on:
• Explicit ordering
Specify explicitly the execution order of parallel states on a state-by-state basis (see
“Explicit Ordering of Parallel States” on page 3-86).
• Implicit ordering
Override explicit ordering by letting a Stateflow chart use internal rules to order
parallel states (see “Implicit Ordering of Parallel States” on page 3-88).
Parallel states are assigned priority numbers based on order of execution. The lower the
number, the higher the priority. The priority number of each state appears in the upper
right corner.
Because execution order is a chart property, all parallel states in the chart inherit the
property setting. You cannot mix explicit and implicit ordering in the same Stateflow
chart. However, you can mix charts with different ordering modes in the same Simulink
model.
When you open a new Stateflow chart — or one that does not yet contain any parallel
states — the chart automatically assigns priority numbers to parallel states in the order
3-86
Execution Order for Parallel States
you create them. Numbering starts with the next available number within the parent
container.
When you enable explicit ordering in a chart that contains implicitly ordered parallel
states, the implicit priorities are preserved for the existing parallel states. When you add
new parallel states, execution order is assigned in the same way as for new Stateflow
charts — in order of creation.
You can reset execution order assignments at any time on a state-by-state basis, as
described in “Set Execution Order for Parallel States Individually” on page 3-88. When
you change execution order for a parallel state, the Stateflow chart automatically
renumbers the other parallel states to preserve their relative execution order. For details,
see “Order Maintenance for Parallel States” on page 3-89.
1 Right-click inside the top level of the chart and select Properties from the context
menu.
If your chart already contains parallel states that have been ordered implicitly, the
existing priorities are preserved until you explicitly change them. When you add new
parallel states in explicit mode, your chart automatically assigns priorities based on
order of creation (see “How Explicit Ordering Works” on page 3-86). However you
can now explicitly change execution order on a state-by-state basis, as described in
“Set Execution Order for Parallel States Individually” on page 3-88.
3-87
3 Stateflow Semantics
In explicit ordering mode, you can change the execution order of individual parallel
states. Right-click the parallel state of interest and select a new priority from the
Execution Order menu.
In implicit ordering mode, a Stateflow chart orders parallel states implicitly based on
location. Priority goes from top to bottom and then left to right, based on these rules:
• The higher the vertical position of a parallel state in the chart, the higher the
execution priority for that state.
• Among parallel states with the same vertical position, the leftmost state receives
highest priority.
The following example shows how these rules apply to top-level parallel states and
parallel substates.
Note Implicit ordering creates a dependency between design layout and execution
priority. When you rearrange parallel states in your chart, you can accidentally change
order of execution and affect simulation results. For more control over your designs, use
the default explicit ordering mode to set execution priorities.
3-88
Execution Order for Parallel States
1 Right-click inside the top level of the chart and select Properties from the context
menu.
2 In the Chart properties dialog box, clear the User specified state/transition
execution order check box.
3 Click OK.
For explicit ordering, a chart preserves the user-specified priorities. Consider this
example of explicit ordering:
3-89
3 Stateflow Semantics
Because of explicit ordering, the priority of each state and substate matches the order of
creation in the chart. The chart reprioritizes the parallel states and substates when you
perform these actions:
The chart preserves the priority set explicitly for top-level state b, but renumbers all other
parallel states to preserve their prior relative order.
For implicit ordering, a chart preserves the intended relative priority based on geometry.
Consider this example of implicit ordering:
If you remove top-level state b and substate e, the chart automatically reprioritizes the
remaining parallel states and substates to preserve implicit geometric order:
3-90
Execution Order for Parallel States
However, in explicit ordering mode, a chart cannot always reinstate the original execution
priority to a restored state. It depends on how you restore the state.
If you remove a state And restore the state What is the priority?
by... by...
Deleting, cutting, dragging Using the undo command The original priority is
outside the boundaries of restored.
the parent state, or
dragging so its boundaries
overlap the parent state
Dragging outside the Dragging it back into the The original priority is lost.
boundaries of the parent parent state The Stateflow chart treats
state or so its boundaries the restored state as the last
overlap the parent state and created and assigns it the
releasing the mouse button lowest execution priority.
Dragging outside the Dragging it back into the The original priority is
boundaries of the parent parent state restored.
state or so its boundaries
overlap the parent state
without releasing the mouse
button
3-91
3 Stateflow Semantics
If you remove a state And restore the state What is the priority?
by... by...
Dragging so its boundaries Dragging it to a location The original priority is
overlap one or more sibling with no overlapping restored.
states boundaries inside the same
parent state
Cutting Pasting The original priority is lost.
The Stateflow chart treats
the restored state as the last
created and assigns it the
lowest execution priority.
When you convert a state with parallel decomposition into a subchart, its substates retain
their relative execution order based on the prevailing explicit or implicit rules.
3-92
Early Return Logic for Event Broadcasts
3-93
3 Stateflow Semantics
In this example, assume that state A is initially active. Event E occurs, causing the
following behavior:
1 The chart root checks to see if there is a valid transition out of the active state A as a
result of event E.
2 A valid transition to state B exists.
3 The condition action of the valid transition executes and broadcasts event F.
State C is now the only active substate of its chart. The Stateflow chart cannot return to
the transition from state A to state B and continue after the condition action that
broadcast event F (step 3). First, its source, state A, is no longer active. Second, if the
chart allowed the transition, state B would become the second active substate of the
chart. This behavior violates the guideline that a state (or chart) with exclusive (OR)
3-94
Early Return Logic for Event Broadcasts
decomposition can never have more than one active substate. Therefore, the chart uses
early return logic and halts the transition from state A to state B.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
3-95
4
If your system has no operating modes, the system is stateless. If your system has
operating modes, the system is modal.
• Classic — The default machine type. Provides the full set of semantics for MATLAB
charts and C charts.
• Mealy — Machine type in which output is a function of inputs and state.
• Moore — Machine type in which output is a function of state.
For more information, see “How Stateflow Objects Interact During Execution” on page 3-
5, “Differences Between MATLAB and C as Action Language Syntax” on page 13-6, and
“Overview of Mealy and Moore Machines” on page 7-2.
4-2
Model Reactive Systems in Stateflow
1 For each state, what are the actions you want to perform?
2 What are the rules for transitioning between your states? If your chart has no states,
what are the rules for transitioning between branches of your flow logic?
Using your answers to those questions, specify state actions and transition conditions:
1 Draw states to represent your operating modes, if any. See “Represent Operating
Modes by Using States” on page 4-5.
2 Implement the state actions by adding state labels that use the appropriate syntax.
See “State Action Types” on page 12-2.
3 Draw transitions to represent the direction of flow logic, between states or between
branches of your flow chart. See “Transition Between Operating Modes” on page 4-
19.
4 Implement the transition conditions by adding transition labels that use the
appropriate syntax. See “Transition Action Types” on page 12-7.
1 Add local data to the appropriate level of the chart hierarchy. See “Add Stateflow
Data” on page 9-2.
You can also use the Symbol Wizard to add data to your chart. See “Resolve Symbols
Through the Symbol Wizard” on page 30-36.
2 Specify the type, size, complexity, and other data properties. See “Set Data
Properties” on page 9-5.
• Flow chart — Encapsulate flow charts containing if-then-else, switch-case, for, while,
or do-while patterns.
4-3
4 Create Stateflow Charts
• MATLAB — Write matrix-oriented algorithms; call MATLAB functions for data analysis
and visualization.
• Simulink — Call Simulink function-call subsystems directly to streamline design and
improve readability.
• Truth table — Represent combinational logic for decision-making applications such as
fault detection and mode switching.
Use the function format that is most natural for the type of calculation in the state action
or transition condition. For more information on the four types of functions, see:
If the four types of Stateflow functions do not work, you can write your own C or C++
code for integration with your chart. For more information about custom code integration,
see “Reuse Custom Code in Stateflow Charts” on page 30-26.
• To create a new chart, repeat all the steps in this basic workflow.
• To add hierarchy, repeat the previous three steps on lower levels of the current
chart.
4-4
Represent Operating Modes by Using States
States can be active or inactive. The activity or inactivity of a state can change depending
on events and conditions. The occurrence of an event drives the execution of the state
transition diagram by making states become active or inactive. For more information, see
“States” on page 2-7.
Create a State
You create states by drawing them in the editor for a particular chart (block). Follow
these steps:
In the drawing area, the pointer becomes state-shaped (rectangular with oval
corners).
3 Click in a particular location to create a state.
The created state appears with a question mark (?) label in its upper left-hand
corner.
4 Click the question mark.
The label for a state specifies its required name and optional actions. See “Label States”
on page 4-15 for more detail.
4-5
4 Create Stateflow Charts
When your pointer is over a corner, it appears as a double-ended arrow (PC only;
pointer appearance varies with other platforms).
2 Click and drag the state's corner to resize the state and release the left mouse
button.
Note A parent state must be graphically large enough to accommodate all its substates.
You might need to resize a parent state before dragging a new substate into it. You can
bypass the need for a state of large graphical size by declaring a superstate to be a
subchart. See “Encapsulate Modal Logic by Using Subcharts” on page 8-5 for details.
Group States
When to Group a State
Group a state to move all graphical objects inside a state together. When you group a
state, the chart treats the state and its contents as a single graphical unit. This behavior
simplifies editing of a chart. For example, moving a grouped state moves all substates and
functions inside that state.
You can group a state by right-clicking it and then selecting Group & Subchart > Group
in the context menu. The state appears shaded in gray to indicate that it is now grouped.
4-6
Represent Operating Modes by Using States
If you try to move objects such as states and graphical functions into a grouped state,
you see an invalid intersection error message. Also, the objects with an invalid
intersection have a red border.
You can ungroup a state by right-clicking it and then clearing Group & Subchart >
Group in the context menu. The background of the state no longer appears gray.
4-7
4 Create Stateflow Charts
To alter a state's decomposition, select the state, right-click to display the state's
Decomposition context menu, and select OR (Exclusive) or AND (Parallel) from the
menu.
You can also specify the state decomposition of a chart. In this case, the Stateflow chart
treats its top-level states as substates. The chart creates states with exclusive
decomposition. To specify a chart's decomposition, deselect any selected objects, right-
click to display the chart's Decomposition context menu, and select OR (Exclusive) or
AND (Parallel) from the menu.
4-8
Represent Operating Modes by Using States
• By default, when you create a new Stateflow chart, explicit ordering applies. In this
case, you specify the activation order on a state-by-state basis.
• You can also override explicit ordering by letting the chart order parallel states based
on location. This mode is known as implicit ordering.
For more information, see “Explicit Ordering of Parallel States” on page 3-86 and
“Implicit Ordering of Parallel States” on page 3-88.
Note The activation order of a parallel state appears in its upper right corner.
The State properties dialog box appears. For descriptions of properties, see
“Properties You Can Set in the General Pane” on page 4-9 and “Properties You Can
Set in the Logging Pane” on page 4-11.
2 Modify property settings and then click one of these buttons:
• Apply to save the changes and keep the State dialog box open
• Cancel to return to the previous settings
• OK to save the changes and close the dialog box
• Help to display the documentation in an HTML browser window
The General pane of the State properties dialog box appears as shown.
4-9
4 Create Stateflow Charts
Property Description
Name Stateflow chart name; read-only; click this hypertext link to
bring the state to the foreground.
4-10
Represent Operating Modes by Using States
Property Description
Execution order Set the execution order of a parallel (AND) state. This property
does not appear for exclusive (OR) states. See “Execution
Order for Parallel States” on page 3-86.
Create data for Select this option to create state activity data. See “Monitor
monitoring State Activity Through Active State Data” on page 24-26.
Function Inline Option Select one of these options to control the inlining of state
functions in generated code:
• Auto
The Logging pane of the State properties dialog box appears as shown.
4-11
4 Create Stateflow Charts
Property Description
Log self activity Saves the self activity value to the MATLAB workspace during
simulation.
4-12
Represent Operating Modes by Using States
Property Description
Test point Designates the state as a test point that can be monitored with
a floating scope during model simulation. You can also log test
point values into MATLAB workspace objects. See “Monitor
Test Points in Stateflow Charts” on page 32-46.
Logging name Specifies the name associated with the logged self activity.
Simulink software uses the signal name as its logging name by
default. To specify a custom logging name, select Custom from
the list box and enter the new name in the adjacent edit field.
Limit data points to Limits the self activity logged to the most recent samples.
last
Decimation Limits self activity logged by skipping samples. For example, a
decimation factor of 2 saves every other sample.
The Documentation pane of the State properties dialog box appears as shown.
4-13
4 Create Stateflow Charts
Property Description
Description Textual description or comment.
Document link Enter a URL address or a general MATLAB command.
Examples are www.mathworks.com,
mailto:email_address, and edit /spec/data/
speed.txt.
4-14
Represent Operating Modes by Using States
Label States
The label for a state specifies its required name for the state and the optional actions
executed when the state is entered, exited, or receives an event while it is active.
name/
entry:entry actions
during:during actions
exit:exit actions
bind:data and events
on event_or_message_name:on event_or_message_name actions
4-15
4 Create Stateflow Charts
Initially, a state's label is empty. The Stateflow chart indicates this by displaying a ? in the
state's label position (upper left corner). Begin labeling the state by entering a name for
the state with the following steps:
1 Click the state.
The state turns to its highlight color and a question mark character appears in the
upper left-hand corner of the state.
2 Click the ? to edit the label.
Enter the state's name in the first line of the state's label. Names are case sensitive.
To avoid naming conflicts, do not assign the same name to sibling states. However,
you can assign the same name to states that do not share the same parent.
After labeling the state, click outside it. Otherwise, continue entering actions. To
reedit the label, click the label text near the character position you want to edit.
Enter Actions
After entering the name of the state in the label, you can enter actions for any of the
following action types:
• Entry Actions — begin on a new line with the keyword entry or en, followed by a
colon, followed by one or more action statements on one or more lines. To separate
multiple actions on the same line, use a comma or a semicolon.
4-16
See Also
You can begin entry actions on the same line as the state's name. In this case, begin
the entry action with a forward slash (/) instead of the entry keyword.
• Exit Actions — begin on a new line with the keyword exit or ex, followed by a colon,
followed by one or more action statements on one or more lines. To separate multiple
actions on the same line, use a comma or a semicolon.
• During Actions — begin on a new line with the keyword during or du, followed by a
colon, followed by one or more action statements on one or more lines. To separate
multiple actions on the same line, use a comma or a semicolon.
• Bind Actions — begin on a new line with the keyword bind followed by a colon,
followed by one or more data or events on one or more lines. To separate multiple
actions on the same line, use a comma or a semicolon.
• On Actions — begin with the keyword on, followed by a space and the name of an
event or message, followed by a colon, followed by one or more action statements on
one or more lines, for example
on ev1: exit();
To separate multiple actions on the same line, use a comma or a semicolon. If you
want different events to trigger different actions, enter multiple on blocks in the state
label. Each block specifies the action for a specific event or message, for example:
The execution of the actions you enter for a state is dependent only on their action type,
and not the order in which you enter actions in the label. If you do not specify the action
type explicitly for a statement, the chart treats that statement as an entry action.
Tip You can also edit the label in the properties dialog box for the state. See “Change
State Properties” on page 4-9.
See Also
States
More About
• “State Action Types” on page 12-2
• “Eliminate Redundant Code by Combining State Actions” on page 12-11
4-17
4 Create Stateflow Charts
4-18
Transition Between Operating Modes
Create a Transition
Follow these steps to create transitions between states and junctions:
• Transitions do not attach to the corners of states. Corners are used exclusively for
resizing.
• Transitions exit a source and enter a destination at angles perpendicular to the source
or destination surface.
• All transitions have smart behavior.
To delete a transition, click it and select Edit > Cut, or press the Delete key.
See the following sections for help with creating self-loop and default transitions:
Label Transitions
Transition labels contain syntax that accompanies the execution of a transition. The
following topics discuss creating and editing transition labels:
4-19
4 Create Stateflow Charts
For more information on transition concepts, see “Transition Label Notation” on page 2-
20.
For more information on transition label contents, see “Transition Action Types” on page
12-7.
The transition changes to its highlight color and a question mark (?) appears on the
transition. The ? character is the default empty label for transitions.
2 Left-click the ? to edit the label.
To apply and exit the edit, deselect the object. To reedit the label, simply left-click the
label text near the character position you want to edit.
event_or_message [condition]{condition_action}/transition_action
4-20
Transition Between Operating Modes
Transitions do not need labels. You can specify some, all, or none of the parts of the label.
Rules for writing valid transition labels include:
• Can have any alphanumeric and special character combination, with the exception of
embedded spaces
• Cannot begin with a numeric character
• Can have any length
• Can have carriage returns in most cases
• Must have an ellipsis (...) to continue on the next line
Move Transitions
You can move transition lines with a combination of several individual movements. These
movements are described in the following topics:
In addition, transitions move along with the movements of states and junctions.
You can move or "bow" transition lines with the following procedure:
1 Place your pointer on the transition at any point along the transition except the arrow
or attach points.
2 Click and drag your pointer to move the transition point to another location.
Only the transition line moves. The arrow and attachment points do not move.
3 Release the mouse button to specify the transition point location.
4-21
4 Create Stateflow Charts
The result is a bowed transition line. Repeat the preceding steps to move the transition
back into its original shape or into another shape.
You can move the source or end points of a transition to place them in exact locations as
follows:
1 Place your pointer over an attach point until it changes to a small circle.
2 Click and drag your pointer to move the attach point to another location.
3 Release the mouse button to specify the new attach point.
The appearance of the transition changes from a solid to a dashed line when you detach
and release a destination attach point. Once you attach the transition to a destination, the
dashed line changes to a solid line.
The appearance of the transition changes to a default transition when you detach and
release a source attach point. Once you attach the transition to a source, the appearance
returns to normal.
You can move transition labels to make the Stateflow chart more readable. To move a
transition label, do the following:
1 Click and drag the label to a new location.
2 Release the left mouse button.
If you mistakenly click and then immediately release the left mouse button on the label,
you will be in edit mode for the label. Press the Esc key to deselect the label and try
again. You can also click the mouse on an empty location in the chart to deselect the
label.
4-22
Transition Between Operating Modes
1 Create the transition by clicking and dragging from the source state or junction.
2 Press the S key or right-click your mouse to enable a curved transition.
3 Continue dragging the transition tip back to a location on the source state or
junction.
Click the Default Transition button in the toolbar and click a location in the drawing
area close to the state or junction you want to be the destination for the default
transition. Drag your pointer to the destination object to attach the default transition.
The size of the endpoint of the default transition is proportional to the arrowhead size.
See “Change Transition Arrowhead Size” on page 4-22.
Default transitions can be labeled just like other transitions. See “Label Default
Transitions” on page 2-33 for an example.
4-23
4 Create Stateflow Charts
4-24
Transition Between Operating Modes
4-25
4 Create Stateflow Charts
Field Description
Source Source of the transition; read-only; click the
hypertext link to bring the transition source to the
foreground.
Destination Destination of the transition; read-only; click the
hypertext link to bring the transition destination to
the foreground.
Parent Parent of this state; read-only; click the hypertext
link to bring the parent to the foreground.
Execution order The order in which the chart executes the transition.
Label The transition's label. See “Transition Label
Notation” on page 2-20 for more information on
valid label formats.
Description Textual description or comment.
Document link Enter a Web URL address or a general MATLAB
command. Examples are www.mathworks.com,
mailto:email_address, and edit/spec/data/
speed.txt.
2 After making changes, click one of these buttons:
• Apply to save the changes and keep the Transition dialog box open.
• Cancel to return to the previous settings for the dialog box.
• OK to save the changes and close the dialog box.
• Help to display Stateflow online help in an HTML browser window.
See Also
Transitions
More About
• “Transition Action Types” on page 12-7
• “Default Transitions” on page 2-33
4-26
See Also
4-27
4 Create Stateflow Charts
Stateflow Editor
Use the Stateflow Editor to draw, zoom, modify, print, and save a chart shown in the
window.
Command Result
sfnew Creates a chart with the default action
language. For more information, see
sfnew.
sfnew -matlab Creates an empty chart with MATLAB
as the action language.
sfnew -C Creates an empty C chart.
stateflow Creates an empty chart with the default
action language and displays the
Stateflow block library.
4-28
Stateflow Editor Operations
• Title bar
The full chart name appears here in model name/chart name* format. The * character
appears on the end of the chart name for a newly created chart or for an existing chart
that has been edited but not saved yet.
• Menu bar and toolbar
Most editor commands are available from the menu bar. The toolbar contains buttons
for cut, copy, paste, and other commonly used editor commands. You can identify each
4-29
4 Create Stateflow Charts
tool of the toolbar by placing your pointer over it until an identifying tool tip appears.
The toolbar also contains buttons for navigating the chart hierarchy (see “Navigate
Subcharts” on page 8-8).
• Object palette
Displays a set of tools for drawing states, transitions, and other chart objects. To add
an object, you can use the palette to:
• Click the icon for the object and move the cursor to the spot in the drawing area
where you want to place the object.
• Drag the icon for the object into the drawing area.
4-30
Stateflow Editor Operations
• Double-click the icon and then click multiple times in the drawing area to make
copies of the object.
• Explorer bar
The breadcrumb shows the systems that you have open in the editor. Click a system in
the breadcrumb to display that system.
• Model Browser
Click the double arrows in the bottom left corner to open or close a tree-
structured view of the model in the editor.
• Drawing area — This area displays an editable copy of a chart.
• Context menus (shortcut menus) — These menus pop up from the drawing area when
you right-click an object. They display commands that apply only to that object. If you
right-click an empty area of the chart, the context menu applies to the chart object.
• Status information — Near the top of the editor, you can see (and reset) the
simulation time and the simulation mode. The bottom status bar displays the status of
the Stateflow processing, tool tips, the zoom factor, and the solver.
4-31
4 Create Stateflow Charts
You can undo and redo many operations you complete on Stateflow objects in the Symbols
or Property Inspector windows.
You can undo or redo all editor operations, with the following exceptions:
• You cannot undo the operation of turning subcharting off for a state previously
subcharted.
Note When you perform one of the preceding operations, the undo and redo buttons
are disabled from undoing and redoing any prior operations.
4-32
Stateflow Editor Operations
To change the display size for a single element in the chart, right-click the element, and
then select a new Format option from the context menu. The options available depend on
the element that you select.
Through the Colors & Fonts dialog box, you can specify a color scheme for the chart or
specify colors and label fonts for different types of objects in a chart. To open the Colors
& Fonts dialog box, select File > Stateflow Preferences > Style.
4-33
4 Create Stateflow Charts
In the Colors & Fonts dialog box, the drawing area displays examples of the colors and
label fonts specified by the current color scheme for the chart. You can choose a different
color scheme from the Schemes menu. To modify the display options for a single type of
chart element, position your pointer over the sample object.
• To change the color of the element, click the sample object and select a new color in
the dialog box.
4-34
Stateflow Editor Operations
• To change the font of the element, right-click the sample object and select a new font,
style, or size in the dialog box.
4-35
4 Create Stateflow Charts
To apply the scheme to the chart, click Apply. To apply the scheme and close the dialog
box, click OK.
To make the scheme the default scheme for all charts, select Options > Make this the
'Default' scheme.
To save changes to the default color scheme, select Options > Save defaults to disk. If
the modified scheme is not the default scheme, choosing Save defaults to disk has no
effect.
4-36
Stateflow Editor Operations
For example, the Temporal Logic chart uses content preview. The chart Without Temporal
Logic does not.
To turn on content preview for Stateflow charts and subcharts, right-click the chart and
select Format > Content Preview. For Simulink functions, right-click the function and
select Content Preview. For details on content preview in Simulink, see “Preview
Content of Model Components” (Simulink).
Note In order to see the content preview, you may need to enlarge the Stateflow chart or
object.
4-37
4 Create Stateflow Charts
options for keywords, data, event, messages, and function names, without having to
navigate the Model Explorer. In a Stateflow chart, to complete entries:
1 Type the first few characters of the word that you want.
2 Press Tab to see the list of possible matches.
3 Use the arrow keys to select a word.
4 Press Tab to make the selection.
• Close the list without selecting anything by pressing the Esc key.
• Type additional characters onto your original term to narrow the list of possible
matches.
If you press Tab and no words are listed, then the current word is the only possible
match.
• Keyword
• Comment
• Event
• Message
• Function
• String
• Number
The following chart illustrates the default highlighting for language elements.
4-38
Stateflow Editor Operations
If the parser cannot resolve a syntax element, the chart displays the element in the
default text color.
To modify color assignments, see “Edit Syntax Highlighting” on page 4-39. To disable
syntax highlighting, see “Enable and Disable Syntax Highlighting” on page 4-39.
4-39
4 Create Stateflow Charts
This step adds objects to the list of already selected objects unless an object was
already selected, in which case, the object is deselected. This type of multiple object
selection is useful for selecting objects within a state without selecting the state itself.
• To deselect all selected objects, click in the drawing area, but not on an object.
When an object is selected, it appears highlighted in the color set as the selection color
(blue by default; see “Specify Colors and Fonts in a Chart” on page 4-32 for more
information).
• To cut an object, right-click the object and select Cut from the context menu.
• To paste the most recently cut selection of objects, right-click in the chart and select
Paste from the context menu.
4-40
Stateflow Editor Operations
Note If you copy and paste a state in the chart, these rules apply:
• If the original state uses the default ? label, then the new state retains that label.
• If the original state does not use the default ? label, then a unique name is generated
for the new state.
Alternatively, to copy from one chart to another, select Copy and then Paste from the
right-click context menu.
• Alignment
• Distribution
• Resizing
• States
• Functions
• Boxes
4-41
4 Create Stateflow Charts
• Junctions
The basic steps to align, distribute, or resize chart objects are similar.
1 If the chart includes parallel states or outgoing transitions from a single source,
make sure that the chart uses explicit ordering.
To set explicit ordering, in the Chart properties dialog box, select User specified
state/transition execution order.
Note If a chart uses implicit ordering to determine execution order of parallel states
or evaluation order of outgoing transitions, the order can change after you align,
distribute, or resize chart objects. Using explicit ordering prevents this change from
occurring. For more information, see “Execution Order for Parallel States” on page 3-
86 and “Transition Evaluation Order” on page 3-65.
2 Select the chart objects that you want to align, distribute, or resize.
You can select objects in any order, one-by-one or by drawing a box around them.
3 Decide which object to use as the anchor for aligning, distributing, or resizing other
chart objects. This object is the reference object.
To set an object as the reference, right-click the object. Brackets appear around the
reference object. In the following example, the Door and Motion states are selected,
and the Door state is the reference.
4-42
Stateflow Editor Operations
Note If you select objects one-by-one, the last object that you select acts as the
reference.
4 Select an option from the Chart > Arrange menu to align, distribute, or resize your
chosen objects.
For more information about chart object distribution options, see “Options for
Distributing Chart Objects” on page 4-44
4-43
4 Create Stateflow Charts
Option Description
Distribute Horizontally The center-to-center horizontal distance
between any two objects is the same.
Suppose that you open the sf_pool model and see a chart with multiple MATLAB
functions.
4-44
Stateflow Editor Operations
This object is the reference (or anchor) for aligning the three functions. Brackets
appear around the function.
4-45
4 Create Stateflow Charts
This step aligns the right edges of the three functions based on the right edge of
getBallInteraction.
4-46
Stateflow Editor Operations
Suppose that you open the sf_frame_sync_controller model and see a chart with
three states.
Tip Double-click the Frame Sync Controller block to open the chart.
4-47
4 Create Stateflow Charts
4-48
Stateflow Editor Operations
4-49
4 Create Stateflow Charts
Note When you select the three states in any order, your reference object might
differ from the one shown. This difference does not affect distribution of vertical
white space.
3 Select Chart > Arrange > Even Vertical Gaps.
This step ensures that the vertical white space between any two states is the same.
Suppose that you open the sf_clutch_enabled_subsystems model and see a chart
with graphical functions of different sizes.
To resize the graphical functions so that they all match the size of detectSlip:
4-50
Stateflow Editor Operations
This step ensures that the three functions are the same size.
4-51
4 Create Stateflow Charts
a To align the functions, select Chart > Arrange > Align Left.
4-52
Stateflow Editor Operations
b To distribute the functions evenly in terms of vertical spacing, select Chart >
Arrange > Even Vertical Gaps.
4-53
4 Create Stateflow Charts
To format your chart, select Chart > Arrange > Arrange Automatically.
4-54
Stateflow Editor Operations
4-55
4 Create Stateflow Charts
4-56
Stateflow Editor Operations
3 Enter the destination directory of the report file and select options to specify what
objects appear in the report.
For details on setting the fields in the File locations/naming options section, see
“Print Model Reports” (Simulink). For details on the report you receive, see “System
Report Options” on page 4-58 and “Report Format” on page 4-58.
4 Click Print.
The Print Details dialog box appears and tracks the report generation. See “Print Model
Reports” (Simulink) for more details on this window.
Tip If you have the Simulink Report Generator™ installed, you can generate a detailed
report about a system. To do so, in the Simulink Editor, select File > Reports > System
Design Description. For more information, see “System Design Description” (Simulink
Report Generator).
4-57
4 Create Stateflow Charts
Reports for the current Stateflow chart vary with your choice of one of the System
reporting options fields:
• Current — Reports on the chart or subchart in the current editor window and its
immediate parent Simulink system.
• Current and above — This option is grayed out and unavailable for printing chart
details.
• Current and below — Reports on the chart or subchart in the current editor window
and all contents at lower levels of the hierarchy, along with the immediate Simulink
system.
• Entire model — Reports on the entire model including all charts and all Simulink
systems.
If you select this option, you can modify the report as follows:
• Look under mask dialog – Includes the contents of masked subsystems in the
report.
• Expand unique library links – Includes the contents of library blocks that are
subsystems in the report.
The report includes a library subsystem only once even if it occurs in more than
one place in the model.
Report Format
• The report shows the title of the system in the Simulink model containing the chart or
subchart in current view.
• A representation of Simulink hierarchy for the containing system and its subsystems
follows. Each subsystem in the hierarchy links to the report of its Stateflow charts.
• The report section for the Stateflow charts of each system or subsystem begins with a
small report on the system or subsystem, followed by a report of each contained chart.
• Each chart report includes a reproduction of its chart with links for subcharted states
that have reports of their own.
• An appendix tabulates the covered Stateflow and Simulink objects in the report.
4-58
5
A best practice is to encapsulate flow charts in graphical functions to create modular and
reusable logic that you can call anywhere in a chart. For more information about
graphical functions, see “Reuse Logic Patterns by Defining Graphical Functions” on page
8-16.
if u > 0
y = 1;
else
y = 0;
end
1 Open a chart.
5-2
Flow Charts in Stateflow
2 From the editor toolbar, drag one or more connective junctions into the chart with
the Connective Junction tool:
You can control the level of diagnostic action for unintended backtracking in the
Diagnostics > Stateflow pane of the Model Configuration Parameters dialog box. For
more information, see the documentation for the “Unexpected backtracking” (Simulink)
diagnostic.
• The junction does not have an unconditional transition path to a state or terminating
junction.
• Multiple transition paths lead to that junction.
5-3
5 Model Logic Patterns and Iterative Loops Using Flow Charts
Flow charts test transitions, but do not execute them (and, therefore, never execute
transition actions).
See Also
Related Examples
• “Create Flow Charts by Using Pattern Wizard” on page 5-6
• “How Stateflow Objects Interact During Execution” on page 3-5
More About
• “States” on page 2-7
5-4
See Also
5-5
5 Model Logic Patterns and Iterative Loops Using Flow Charts
The Pattern Wizard generates flow charts whose geometry and layout comply with the
guidelines from the MathWorks Automotive Advisory Board (MAAB). You can customize
your flow chart by modifying the conditions and actions or by inserting additional logic
patterns. You can also save your flow chart as a custom pattern in the Pattern Wizard for
later reuse.
For example, suppose that you want to use the Pattern Wizard to create a graphical
function for iterating over the upper triangle of a two-dimensional matrix. The function
consists of two nested for loops in which the row index i is always less than or equal to
the column index j. By using the Pattern Wizard, you can:
1 Create a flow chart for the outer loop that iterates over the row index i.
2 Extend the flow chart by inserting an inner loop that iterates over the column index
j.
3 Save the flow chart as a custom pattern in the Pattern Wizard.
4 Reuse the custom pattern in a graphical function.
5-6
Create Flow Charts by Using Pattern Wizard
The Stateflow Patterns dialog box prompts you for conditions and actions specific to the
pattern that you select. For more information on flow chart patterns, see “MAAB-
Compliant Patterns from the Pattern Wizard” on page 5-14.
For example, to create the outer for loop in the upper triangle iterator pattern:
1 In the Stateflow editor, select Chart > Add Pattern in Chart > Loop > For.
2 In the Stateflow Patterns dialog box, specify the initializer, loop test, and counting
expressions for iterating through the first dimension of the matrix:
5-7
5 Model Logic Patterns and Iterative Loops Using Flow Charts
To complete the upper triangle iterator pattern, insert a second for loop along the
vertical transition in this flow chart.
For example, to add the second loop in the upper triangle iterator pattern:
1 In the Stateflow editor, from the outer for loop pattern, select the vertical transition
labeled {action1}.
2 Select Chart > Insert Pattern on Selection > Loop > For.
3 In the Stateflow Patterns dialog box, specify the initializer, loop test, and counting
expressions for iterating through the second dimension of the matrix. The initializer
expression ensures that i never exceeds j. Also enter an action that retrieves each
element in the upper triangle of the matrix.
5-8
Create Flow Charts by Using Pattern Wizard
4 Click OK. The Pattern Wizard adds the second loop to the flow chart.
5-9
5 Model Logic Patterns and Iterative Loops Using Flow Charts
• You can select only one transition to extend at a time. The selected transition must be
exactly vertical and have a destination junction.
• You can extend only flow charts created by the Pattern Wizard.
• The Stateflow chart containing the flow chart can contain only junctions and
transitions. The chart cannot contain other objects, such as states, functions, or truth
tables.
• You cannot extend a pattern that has been custom-created or modified.
• You cannot choose a custom pattern as the extension.
5-10
Create Flow Charts by Using Pattern Wizard
If your selection is not eligible for insertion, when you select Chart > Insert Pattern on
Selection, you see a message instead of pattern options.
Message Issue
Select a vertical transition You have not selected a vertical transition.
Selected transition must be exactly vertical You selected a transition, but it is not
vertical.
Select only one vertical transition You have selected more than one transition.
Editor must contain only transitions and There are other objects, such as states,
junctions functions, or truth tables, in the chart.
For example, suppose that you want to save the upper triangle iterator pattern for later
reuse:
1 Create a folder for storing your custom patterns. See “Guidelines for Creating a
Custom Pattern Folder” on page 5-12.
2 In the Stateflow editor, select the upper triangle iterator flow chart.
3 Select Chart > Save Pattern.
4 If you have not designated the custom pattern folder, the Pattern Wizard prompts you
to select a folder. Choose the folder that you created and click Select Folder.
5 At the prompt, name your pattern UpperTriangleIterator and click Save. The
Pattern Wizard saves your pattern as a model file UpperTriangleIterator.slx in
the custom pattern folder.
Note You can use the Pattern Wizard to reuse only flow charts. To reuse states and
subcharts, create an atomic subchart. For more information, see “Create Reusable
Subcomponents by Using Atomic Subcharts” on page 15-2.
5-11
5 Model Logic Patterns and Iterative Loops Using Flow Charts
The Pattern Wizard uses a single, flat folder for saving and retrieving flow chart patterns.
• Store all flow charts at the top level of the custom pattern folder. Do not create
subfolders.
• Make sure that all flow chart files have an .mdl or .slx extension.
The Pattern Wizard remembers your choice of custom pattern folder for future sessions.
To choose a different folder, rename your existing custom pattern folder and do one of the
following:
For example, to add the upper triangle iterator custom pattern to a graphical function:
1 From the object palette, add a graphical function to your chart as described in
“Define a Graphical Function” on page 8-16.
2 Enter this function signature:
Input Description
u 2-D matrix
numrow Number of rows in the matrix
5-12
Create Flow Charts by Using Pattern Wizard
Input Description
numcol Number of columns in the matrix
3 Right-click inside the function and select Group & Subchart > Subchart. The
function appears as an opaque box.
5-13
5 Model Logic Patterns and Iterative Loops Using Flow Charts
6 Select the upper triangle iterator pattern and click OK. The Pattern Wizard adds your
custom pattern to the graphical function.
7 In the graphical function, in place of action1, substitute an appropriate action. This
action repeats once for every row of the matrix.
5-14
Create Flow Charts by Using Pattern Wizard
if
if-else
5-15
5 Model Logic Patterns and Iterative Loops Using Flow Charts
if-elseif
if-elseif-else
5-16
Create Flow Charts by Using Pattern Wizard
if-elseif-elseif-else
Nested if
5-17
5 Model Logic Patterns and Iterative Loops Using Flow Charts
for
while
5-18
Create Flow Charts by Using Pattern Wizard
do-while
Switch Patterns
5-19
5 Model Logic Patterns and Iterative Loops Using Flow Charts
5-20
See Also
See Also
More About
• “Flow Charts in Stateflow” on page 5-2
5-21
5 Model Logic Patterns and Iterative Loops Using Flow Charts
5-22
6
To initialize Simulink blocks when switching between Simulink based states, use
Stateflow textual notation or Simulink State Reader and State Writer blocks.
To create linked Simulink based states, use libraries to save action subsystems. When you
copy an action subsystem from a library model into a Stateflow chart, it appears as a
linked Simulink based state. When you update the library block, the changes are reflected
in all Stateflow charts containing the block.
Using Simulink based states means that you do not have to use complex textual syntax in
Stateflow to model hybrid systems.
• You want to model hybrid dynamic systems that include continuous or periodic
dynamics.
• The structure of the system dynamics change substantially between the various modes
of operation, for example, modeling PID controllers.
For systems where you call logic intermittently, use Simulink functions.
When the structure of the Simulink algorithm remains substantially unchanged, but
certain gains or parameters switch between various models, use Simulink logic outside of
Stateflow. An example of this type of algorithm is gain scheduling. See “Model Gain-
Scheduled Control Systems in Simulink” (Simulink Control Design).
6-2
Simulink Subsystems as States
in the Simulink based state Run_up. In the second stage, the vaulter plants the pole and
takes off, which is modeled by the Simulink based state Take_off. The final stage
happens when the vaulter clears the bar and releases the pole, which is modeled by the
Simulink based state Fly.
6-3
6 Simulink Subsystems as Stateflow States
6-4
Simulink Subsystems as States
The states Run_up and Fly are easier to model by using Cartesian coordinates. The state
Take_off is easier to model by using polar coordinates. To switch from one coordinate
system to another, use Simulink functions InitTakeOff and InitFly.
The default state in the chart PoleVaulter is Run_up. This state models the pole vaulter
traveling along the ground toward the jump. The pole vaulter starts at -10 on the x-axis
and runs toward zero. As the pole vaulter moves along the ground, the position of the pole
vaulter in the xy-plane is continuously changing, but the state of running remains the
same. In this model, the integrator blocks Position and Velocity are state owner
blocks for State Reader blocks in the Simulink function InitTakeOff. This subsystem
outputs the Cartesian coordinates of the pole vaulter.
6-5
6 Simulink Subsystems as Stateflow States
Once the position of the pole vaulter along the x-axis, Run_up.p(1), becomes greater
than -4, the transition from Run_up to Take_off occurs. During the transition
InitTakeOff is initialized, the State Reader block connects to its owner block, and the
function is executed. This function converts the Cartesian coordinates from Position
and Velocity to polar coordinates, r, theta, rdot, and theta_dot. These coordinates
are output as State Writer blocks, which are connected to owner blocks in the state
Take_off.
6-6
Simulink Subsystems as States
Once the position of the pole vaulter along the x-axis, Run_up.p(1), becomes greater
than -4, the active state becomes Take_off. This Simulink subsystem models the pole
vaulter during the take off phase of the jump. The subsystem outputs the Cartesian
coordinates of the pole vaulter.
6-7
6 Simulink Subsystems as Stateflow States
Once the angle of the pole vaulter, theta, becomes less than pi/2, the transition from
Take_off to Fly occurs. During the transition InitFly is initialized, the State Reader
block connects to its owner block, and the function is executed. This function converts the
polar coordinates from r, theta, and theta_dot to Cartesian coordinates, xy_integ
and xydot. These coordinates are output as State Writer blocks, which are connected to
owner blocks in the state Fly.
6-8
Simulink Subsystems as States
Once the angle of the pole vaulter, theta, is less than pi/2, the active state becomes
Fly. This state models the pole vaulter after the jump has cleared and the pole vaulter is
falling to the ground. As the pole vaulter falls, the position of the pole vaulter in the x-y
plane is continuously changing, but the state of falling remains the same. In this model,
the integrator blocks xydot and xy_integ are state owner blocks for State Writer blocks
in the Simulink function InitFly. This subsystem outputs the Cartesian coordinates of
the pole vaulter.
6-9
6 Simulink Subsystems as Stateflow States
Limitations
You cannot use Simulink based states with:
• Moore charts
• Discrete Event charts
• HDL Coder
• PLC Coder
• Simulink Code Inspector
• Super step transitions
6-10
See Also
See Also
More About
• “Create and Edit Simulink Based States” on page 6-12
• “Reuse Charts in Models with Chart Libraries” on page 24-17
• “Custom Libraries and Linked Blocks” (Simulink)
6-11
6 Simulink Subsystems as Stateflow States
You can create Simulink based state by using the drawing tool. To reuse systems from
separate Simulink models, copy and paste enabled subsystems. To reuse subsystems in
multiple Stateflow charts, copy and paste action subsystems that are saved in a library.
• Create an empty Simulink based state by using the Simulink based state drawing tool.
• Create a Simulink based state from another model by copying an enabled subsystem
or an action subsystem to your Stateflow chart.
• Create a linked Simulink based state by copying an action subsystem from a library to
your Stateflow chart.
1 Add a Stateflow chart block to a Simulink model. To open the Stateflow editor,
double-click the block.
2
On the object palette, click the Simulink based state drawing tool . Move your
cursor onto your chart.
3 To place the new Simulink based state, click the Stateflow canvas. A shaded state
appears.
6-12
Create and Edit Simulink Based States
4 Enter the state label. In this example, the state models a pole vaulter running along a
flat surface, so the state label is Run_up. Simulink based states are action
subsystems, so an Action Port appears with your new state.
5 Build your Simulink subsystem. This subsystem outputs the Cartesian coordinates of
the pole vaulter. For more information about this model, see “Access Block State
Data” on page 6-19.
To create a Simulink based state in your Stateflow chart, copy enabled subsystems from
separate Simulink models. You can reuse components from Simulink models in a
Stateflow chart without creating a brand new Simulink based state.
6-13
6 Simulink Subsystems as Stateflow States
2 From the model, copy the block Slipping to your Stateflow chart.
6-14
Create and Edit Simulink Based States
3 The inports and outports of your Simulink subsystem appear as undefined symbols in
your Stateflow chart. To add corresponding input and output data to your Stateflow
To create a linked Simulink based state in your Stateflow chart, copy an action subsystem
from a library to Stateflow. When the library block is updated, the changes are reflected
in all Stateflow charts containing the block.
3 To display a link in the bottom leftmost corner on a linked subsystem, select Display
> Library Links > All.
6-15
6 Simulink Subsystems as Stateflow States
4 The outports of this Simulink subsystem, xy, appears as an undefined symbol in your
Stateflow chart. To add a corresponding output data to your Stateflow chart, click the
When you create an empty Simulink based state, Stateflow creates inputs and outputs in
your Simulink subsystem that correspond to inputs and outputs that exist in the parent
Stateflow chart. However, if you add inports and outports to your Simulink based state
after it is created, you must create corresponding input and output data for your
Stateflow chart.
resolve the undefined symbol, click the Resolve undefined symbols button .
4 A chart inport named In1 is created.
6-16
Create and Edit Simulink Based States
In this example, you create an additional outport for the model sf_pole_vault:
button .
6-17
6 Simulink Subsystems as Stateflow States
5 Stateflow creates an output in the chart called theta_out that corresponds to the
outport theta_out.
For more information about editing data, see “Add and Modify Data, Events, and
Messages” on page 33-3.
See Also
More About
• “Simulink Subsystems as States” on page 6-2
• “Access Block State Data” on page 6-19
• “Map Variables in a Simulink Based State” on page 6-27
• “Reuse Charts in Models with Chart Libraries” on page 24-17
• “Custom Libraries and Linked Blocks” (Simulink)
6-18
Access Block State Data
You can read and write the state of blocks within your Simulink based states in transition
actions of your Stateflow chart. You can read and write the state of blocks textually on the
chart transitions or by using Simulink State Reader and State Writer blocks.
This Stateflow chart models a person moving through the stages of pole vaulting. The first
stage is the approach run of the vaulter, which is modeled by the Simulink based state
Run_up. In the second stage, the vaulter plants the pole and takes off, which is modeled
by the Simulink based state Take_off. The final stage happens when the vaulter clears
the bar and releases the pole, which is modeled by the Simulink based state Fly.
The states Run_up and Fly are easier to model by using Cartesian coordinates. The state
Take_off is easer to model by using polar coordinates. The Simulink functions
InitTakeOff and InitFly are used to switch from one coordinate system to another.
For more details on this chart, see “Model a Pole Vaulter by Using Simulink Based States”
on page 6-2.
6-19
6 Simulink Subsystems as Stateflow States
6-20
Access Block State Data
Textual Access
This subsystem is contained within the Simulink based state Run_up. For the transition
from Run_up to Take_off to occur, the position of the pole vaulter along the x-axis,
p(1), must be greater than -4.
By setting the State Name of the integrator block Position to 'p', you can textually
access the state of this block from your Stateflow chart. To access the state of the
integrator block in the transition condition, type [Run_up.p(1)> -4]. When this
condition becomes true, the transition is taken and the active state becomes Take_off.
6-21
6 Simulink Subsystems as Stateflow States
In the Symbols Window, you can see that the state 'p' appears under the state Run_up.
6-22
Access Block State Data
Graphical Access
Stateflow uses State Reader and State Writer blocks to connect the subsystems within a
Simulink based state to other Simulink subsystems in your model. State Reader and State
Writer blocks display the name of the state owner block that they are connected to.
Conversely, the state owner block displays a tag indicating a link to a State Reader or
a State Writer block. If you click the label above the tag, a list opens with a link for
navigating to the State Writer block.
The following subsystem is contained within the Simulink function InitTakeOff. The
function uses State Reader blocks to connect to the state Run_up and reads p and v. The
function then converts the Cartesian values for the position of the pole vaulter and
velocity into polar coordinates, r and theta and rdot and theta_dot, respectively.
These polar coordinates are then accessed by using state owner blocks in the state
Take_off.
When the transition action occurs, the State Reader blocks in InitTakeOff read the
state of their state owner blocks. Once the Simulink function finishes executing, the State
Writer blocks write to the state owner blocks in the Simulink based state Take_off.
6-23
6 Simulink Subsystems as Stateflow States
To connect a State Reader or a State Writer block to an owner block within a Simulink
subsystem:
6-24
See Also
3 By connecting the State Reader block to the Position integrator block, this
Simulink function can use the state of the integrator Position to execute.
See Also
More About
• “Simulink Subsystems as States” on page 6-2
• State Reader
6-25
6 Simulink Subsystems as Stateflow States
• State Writer
6-26
Map Variables for Simulink Based States
You can access inports or outports of a subsystem within a Simulink based state by using
inputs and outputs in Stateflow that have the same name as your inports and outports.
For Simulink based states that are created by copying and pasting enabled subsystems
and action subsystems from a library, click the Resolve undefined symbols button to
map your Simulink inports and outports to Stateflow inputs and outputs automatically.
See “Create Inports and Outports” on page 6-16.
If you are using a linked Simulink based state where the name of the inport or outport
differs from the Stateflow chart input or output, you must ensure that your variables are
mapped correctly. You can change your mappings from the Property Inspector or in the
Mappings dialog box.
6-27
6 Simulink Subsystems as Stateflow States
Under Input Mapping, you can specify which parent chart input maps to an inport in
your Simulink subsystem.
Under Output Mapping, you can specify which parent chart output maps to an outport
in your Simulink subsystem.
6-28
See Also
See Also
More About
• “Simulink Subsystems as States” on page 6-2
• “Create and Edit Simulink Based States” on page 6-12
• “Access Block State Data” on page 6-19
• “Resolve Symbols Through the Symbols Window” on page 30-35
6-29
6 Simulink Subsystems as Stateflow States
Set and modify the properties of a Simulink based state in the Property Inspector or in a
Simulink based state properties dialog box.
6-30
See Also
See Also
More About
• “Rules for Naming Stateflow Objects” on page 2-4
• “Watch Stateflow Data Values” on page 32-36
• “Specify Size of Stateflow Data” on page 9-40
• “Specify Type of Stateflow Data” on page 9-33
6-31
7
X(n + 1) = f (X(n), u)
In this equation:
State persists from one time step to the next time step.
Mealy machines are finite state machines in which transitions occur on clock edges. The
output of a Mealy chart is a function of inputs and state:
y = g(X, u)
At every time step, a Mealy chart wakes up, evaluates its input, and then transitions to a
new configuration of active states, also called its next state. The chart computes its
output as it transitions to the next state.
To ensure that output is a function of input and state, Mealy state machines enforce these
semantics:
7-2
Overview of Mealy and Moore Machines
Mealy machines compute their output on transitions. Therefore, Mealy charts can
compute their first output at the time that the default path for the chart executes. If you
enable the chart property Execute (enter) Chart At Initialization for a Mealy chart,
this computation occurs at t = 0 (first time step). Otherwise, it occurs at t = 1 (next time
step). For more information, see “Execute (Enter) Chart at Initialization” on page 24-7.
Moore machines are finite state machines in which output is modified at clock edges. The
output of a Moore chart is a function only of state:
y = g(X)
At every time step, a Moore chart wakes up, computes its output, and then evaluates its
input to reconfigure itself for the next time step. For example, after evaluating its input,
the chart can transition to a new configuration of active states. The chart computes its
output before evaluating its input and updating its state.
To ensure that output is a function only of the current state, Moore state machines
enforce these semantics:
Moore machines compute their output in states. Therefore, Moore machines can compute
outputs only after the default path executes. Until then, outputs take the default values.
7-3
7 Build Mealy and Moore Charts
sfnew -moore
Alternatively, after adding a Stateflow chart block to a Simulink model, you can choose
the type of semantics for the chart by setting the State Machine Type chart property.
For more information, see “State Machine Type” on page 24-4.
• You can verify that the Mealy and Moore charts you create conform to their formal
definitions and semantic rules. Error messages appear at compile time (not at design
time).
• Moore charts provide a more efficient implementation than Classic charts for C/C++
and HDL targets.
• You can use a Moore chart to model a feedback loop. In Moore charts, inputs do not
have direct feedthrough. You can design a loop with feedback from the output port to
the input port without introducing an algebraic loop. Mealy and Classic charts have
direct feedthrough and produce an error in the presence of an algebraic loop.
7-4
See Also
See Also
sfnew
More About
• “Design Considerations for Mealy Charts” on page 7-6
• “Design Considerations for Moore Charts” on page 7-11
• “Sequence Recognition by Using Mealy and Moore Charts”
• “Model a Vending Machine by Using Mealy Semantics” on page 7-9
• “Model a Traffic Light by Using Moore Semantics” on page 7-15
• “Convert Charts Between Mealy and Moore Semantics” on page 7-18
7-5
7 Build Mealy and Moore Charts
Mealy Semantics
To ensure that output is a function of input and state, Mealy state machines enforce these
semantics:
Note A chart provides one time base for input and clock (see “Calculate Output and
State by Using One Time Base” on page 7-8).
You can compute outputs only in the condition actions of outer and inner transitions. A
common modeling style for Mealy machines is to test inputs in conditions and compute
outputs in the associated action.
You cannot use state actions or transition actions in Mealy charts. This restriction
enforces Mealy semantics by:
• Preventing the chart from computing output without considering changes on the input
port.
7-6
Design Considerations for Mealy Charts
• Ensuring that output depends on the current state and not the next state.
• Restrict Machine-Parented Data. Machine-parented data is data that you define for
a Stateflow machine. The Stateflow machine is the highest level of the Stateflow
hierarchy. When you define data at this level, every 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, do not use machine-parented data.
• Do Not Define Data Store Memory. You cannot define data store memory (DSM) in
Mealy charts because objects external to the chart can modify DSM. A Stateflow chart
uses data store memory to share data with a Simulink model. Data store memory acts
as global data. In the Simulink hierarchy that contains the chart, other blocks and
models can modify DSM. Mealy charts must not access data that can change
unpredictably.
• Valid Uses:
The change in value of a temporal logic condition behaves like an event that the
Mealy chart schedules internally. At each time step, the number of ticks before the
temporal event executes depends only on the state of the chart. For more
information, see “Operators for Event-Based Temporal Logic” on page 12-50.
Note In Mealy charts, the base event for temporal logic operators must be a
predefined event such as tick or wakeup (see “Keywords for Implicit Events” on
page 10-33).
• Invalid Uses:
7-7
7 Build Mealy and Moore Charts
• You cannot use local events to guard transitions. Local events violate Mealy
semantics because they are not deterministic and can occur while the chart
computes its outputs.
• You cannot use implicit events such as chg(data_name), en(state_name), or
ex(state_name).
You can use 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, a Mealy chart commonly computes outputs and changes states in the same time
step. For more information, see “Solvers” (Simulink).
See Also
More About
• “Overview of Mealy and Moore Machines” on page 7-2
• “Model a Vending Machine by Using Mealy Semantics” on page 7-9
• “Convert Charts Between Mealy and Moore Semantics” on page 7-18
7-8
Model a Vending Machine by Using Mealy Semantics
In this example, the vending machine requires 15 cents to release a can of soda. The
purchaser can insert a nickel or a dime, one at a time, to purchase the soda. The chart
behaves like a Mealy machine because its output soda depends on both the input coin
and current state:
When initial state got_0 is active. No coin has been received or no coins are left.
• If a nickel is received (coin == 1), output soda remains 0, but state got_nickel
becomes active.
• If a dime is received (coin == 2), output soda remains 0, but state got_dime
becomes active.
• If input coin is not a dime or a nickel, state got_0 stays active and no soda is released
(output soda = 0).
7-9
7 Build Mealy and Moore Charts
• If another nickel is received (coin == 1), state got_dime becomes active, but no can
is released (soda remains at 0).
• If a dime is received (coin == 2), a can is released (soda = 1), the coins are
banked, and the active state becomes got_0 because no coins are left.
• If input coin is not a dime or a nickel, state got_nickel stays active and no can is
released (output soda = 0).
• If a nickel is received (coin == 1), a can is released (soda = 1), the coins are
banked, and the active state becomes got_0 because no coins are left.
• If a dime is received (coin == 2), a can is released (soda = 1), 15 cents are banked,
and the active state becomes got_nickel because a nickel (change) is left.
• If input coin is not a dime or a nickel, state got_dime stays active and no can is
released (output soda = 0).
This example of a Mealy vending machine illustrates these Mealy design rules:
See Also
More About
• “Overview of Mealy and Moore Machines” on page 7-2
• “Design Considerations for Mealy Charts” on page 7-6
• “Convert Charts Between Mealy and Moore Semantics” on page 7-18
7-10
Design Considerations for Moore Charts
Moore Semantics
To ensure that output is a function only of the current state, Moore state machines
enforce these semantics:
To ensure that outputs depend solely on the current state, you can compute outputs in
state actions, subject to these restrictions:
• Combine Actions. In Moore charts, you can include only one action per state. The
action can consist of multiple command statements. Stateflow evaluates states in
Moore charts from the top level down. Active states in Moore charts execute the state
action before evaluating the transitions. Therefore, outputs are computed at each time
step whether an outer transition is valid or not.
• Do Not Label State Actions. Do not label state actions in Moore charts with any
keywords, such as entry,during, or exit. By default, Moore charts execute the
actions in the active states before evaluating inputs and updating state.
7-11
7 Build Mealy and Moore Charts
Transitions in Moore charts can contain condition and transition actions if these actions
do not introduce a dependency between output values and input values. For example, in
this chart, each transition tests the input u in a condition and modifies the output y in a
condition action. Because the output value depends on the value of the input, this
construct violates Moore semantics and triggers an error.
In Moore charts, outputs cannot depend on inputs. Using an input to contribute directly
or indirectly to the computation of an output triggers an error.
• Restrict Machine-Parented Data. Machine-parented data is data that you define for
a Stateflow machine. The Stateflow machine is the highest level of the Stateflow
hierarchy. When you define data at this level, every 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, do not use machine-parented data.
• Do Not Define Data Store Memory. You cannot define data store memory (DSM) in
Moore charts because objects external to the chart can modify DSM objects. A
Stateflow chart uses data store memory to share data with a Simulink model. Data
store memory acts as global data. In the Simulink hierarchy that contains the chart,
other blocks and models can modify DSM. Moore charts must not access data that can
change unpredictably.
When calling extrinsic functions with coder.extrinsic, it is not possible to enforce that
the outputs depend only on the current state. Calling an extrinsic function with
coder.extrinsic in a Moore chart triggers an error.
7-12
Design Considerations for Moore Charts
You cannot use Simulink functions in Moore charts. This restriction prevents violations of
Moore semantics during chart execution.
• Valid Uses:
The change in value of a temporal logic condition behaves like an event that the
Moore chart schedules internally. At each time step, the number of ticks before the
temporal event executes depends only on the state of the chart. For more
information, see “Operators for Event-Based Temporal Logic” on page 12-50.
Note In Moore charts, the base event for temporal logic operators must be a
predefined event such as tick or wakeup (see “Keywords for Implicit Events” on
page 10-33).
• Invalid Uses:
7-13
7 Build Mealy and Moore Charts
• You cannot use local events to guard transitions. Local events violate Moore
semantics because they are not deterministic and can occur while the chart
computes its outputs.
• You cannot use implicit events such as chg(data_name), en(state_name), or
ex(state_name).
In Moore charts, you cannot set the update method to Continuous. For modeling
systems with continuous time in Stateflow, use Classic or Mealy charts.
See Also
More About
• “Overview of Mealy and Moore Machines” on page 7-2
• “Model a Traffic Light by Using Moore Semantics” on page 7-15
• “Convert Charts Between Mealy and Moore Semantics” on page 7-18
7-14
Model a Traffic Light by Using Moore Semantics
In this example, the traffic light model contains a 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 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.
The Light_Controller chart behaves like a Moore machine because it updates its outputs
based on current state before transitioning to a new state:
7-15
7 Build Mealy and Moore Charts
When initial state Stop is active. Traffic light is red for North-South, green for East-
West.
In active state StopForTraffic. Traffic light has been red for North-South, green for
East-West for at least 20 clock ticks.
In active state StopToGo. Traffic light must reverse traffic flow in response to sensor.
In active state Go. Traffic light has been red for North-South, yellow for East-West for 3
clock ticks.
In active state GoToStop. Traffic light has been green for North-South, red for East-
West for 10 clock ticks.
This example of a Moore traffic light illustrates these Moore design rules:
7-16
See Also
See Also
More About
• “Overview of Mealy and Moore Machines” on page 7-2
• “Design Considerations for Moore Charts” on page 7-11
• “Convert Charts Between Mealy and Moore Semantics” on page 7-18
• “Model An Intersection Of One-Way Streets”
• “Model a Distributed Traffic Control System by Using Messages”
7-17
7 Build Mealy and Moore Charts
A best practice is to not change from one Stateflow chart type to another in the middle of
development. You cannot automatically convert the semantics of the original chart to
conform to the design rules of the new chart type. Changing chart type usually requires
you to redesign your chart to achieve the equivalent behavior of the original chart, so that
both charts produce the same sequence of outputs given the same sequence of inputs.
Sometimes, however, there is no way to translate specific behaviors without violating
chart definitions.
This table lists a summary of what happens when you change chart types mid-design.
From To Result
Mealy Classic Mealy charts retain their semantics when changed to Classic type.
Classic Mealy If the Classic chart defines its output at every time step and
conforms to Mealy semantic rules, the Mealy chart exhibits behavior
equivalent to the original Classic chart.
Moore Classic State actions in the Moore chart behave as entry and during
actions because they are not labeled. The Classic chart exhibits
behavior that is not equivalent to the original Moore chart. Requires
redesign.
Classic Moore Actions that are unlabeled in the Classic chart (entry and during
actions by default) behave as during and exit actions. The Moore
chart exhibits behavior that is not equivalent to the original Classic
chart. Requires redesign.
Mealy Moore Mealy and Moore rules about placement of actions are mutually
Moore Mealy exclusive. Converting chart types between Mealy and Moore
semantics does not produce equivalent behavior. Requires redesign.
7-18
Convert Charts Between Mealy and Moore Semantics
In the Mealy chart, each state represents one of the three possible coin inputs: nickel,
dime, or no coin. Each condition action computes output (whether soda is released) based
on input (the coin received) as the chart transitions to the next state. If you change the
chart type to Moore, you get a compile-time diagnostic message indicating that the chart
violates Moore chart semantics. According to Moore semantics, the chart output soda
cannot depend on the value of the input coin.
To convert the chart to valid Moore semantics, redesign your chart by moving the logic
that computes the output out of the transitions and into the states. In the Moore chart,
each state must represent both coins received and the soda release condition (soda = 0
or soda = 1). As a result, the redesigned chart requires more states.
7-19
7 Build Mealy and Moore Charts
Before considering the value of coin, the Moore chart must compute the value of soda
according to the active state. As a result, there is a delay in releasing soda, even if the
machine receives enough money to cover the cost.
This table compares the semantics of the charts before and after the transformation.
For this vending machine, Mealy is a better modeling paradigm because there is no delay
in releasing the soda once sufficient coins are received. By contrast, the Moore vending
machine requires an extra time step before producing the soda. Therefore, it is possible
for the Moore vending machine to produce a can of soda at the same time step that it
accepts a coin toward the next purchase. In this situation, the delivery of a soda can
appear to be in response to this coin, but actually occurs because the vending machine
received the purchase price in previous time steps.
7-20
Convert Charts Between Mealy and Moore Semantics
In the Moore chart, each state represents the colors of the traffic light in two opposite
directions and the duration of the current color. Each state action computes output (the
colors of the traffic light) regardless of input (if there are cars waiting at a sensor). If you
change the chart type to Mealy, you get a compile-time diagnostic message indicating
that the chart violates Mealy chart semantics. According to Mealy semantics, the chart
cannot compute its outputs in state actions.
To convert the chart to valid Mealy semantics, redesign your chart by moving the logic
that computes the output out of the states and into the transitions. The redesigned Mealy
chart consists of five states, just like the Moore chart. In most transitions, a temporal
logic expression or the Boolean input sens guards a condition action computing the
outputs y1 and y2. The only exceptions are:
• The default transition, which computes the initial outputs without a guarding
condition.
• The transition from the Stop state to the StopForTraffic state, which does not
compute new outputs.
7-21
7 Build Mealy and Moore Charts
In the same time step, the Mealy chart evaluates the temporal logic expressions and the
input signal sens, and computes the value of the outputs y1 and y2. As a result, in the
Mealy chart, the output changes one time step before the corresponding change occurs in
the original Moore chart. In the Simulink model, you can compensate for the anticipated
changes in output by adding a Delay block to each output signal.
This table compares the semantics of the charts before and after the transformation.
See Also
More About
• “Overview of Mealy and Moore Machines” on page 7-2
• “Design Considerations for Mealy Charts” on page 7-6
7-22
See Also
7-23
7 Build Mealy and Moore Charts
the specialized semantics impact how a function initializes its persistent data. Because
the initialization must be independent of the input to the function, follow these guidelines:
if isempty(n)
n = u;
y = 1;
return
end
y = n;
n = n + u;
end
This type of initialization results in an error because the initial value of n depends on the
input u and the return statement interrupts the normal control flow of the function.
To correct the error, initialize the persistent variable by setting it to a constant value and
remove the return statement. For example, this function initializes the persistent
variable without producing an error.
function y = fcn(u)
persistent n
7-24
Initialize Persistent Variables in MATLAB Functions
if isempty(n)
n = 1;
end
y = n;
n = n + u;
end
Because the Allow direct feeedthrough check box is cleared, the initialization
results in an error.
If you modify the function so it initializes n independently of the input, then you can
simulate an error-free model.
7-25
7 Build Mealy and Moore Charts
7-26
Initialize Persistent Variables in MATLAB Functions
Because the model contains a State Control block in Synchronous mode, the
initialization results in an error.
If you modify the function so it initializes n independently of the input, then you can
simulate an error-free model.
7-27
7 Build Mealy and Moore Charts
7-28
Initialize Persistent Variables in MATLAB Functions
Because the chart implements Moore semantics, the initialization results in an error.
If you modify the function so it initializes n independently of the input, then you can
simulate an error-free model.
7-29
7 Build Mealy and Moore Charts
See Also
Chart | MATLAB Function | State Control | persistent
7-30
See Also
More About
• “Use Nondirect Feedthrough in a MATLAB Function Block” (Simulink)
• “Synchronous Subsystem Behavior with the State Control Block” (HDL Coder)
• “Design Considerations for Moore Charts” on page 7-11
7-31
8
To move a history junction to a new location, click and drag it to the new position.
8-2
Record State Activity by Using History Junctions
Field Description
Parent Parent of this history junction; read-only; click the
hypertext link to bring the parent to the foreground.
Description Textual description/comment.
8-3
8 Techniques for Streamlining Chart Design
Field Description
Document Link Enter a URL address or a general MATLAB command.
Examples are www.mathworks.com,
mailto:email_address, and edit/spec/data/
speed.txt.
3 When finished editing, click one of the following buttons:
8-4
Encapsulate Modal Logic by Using Subcharts
Using subcharts, you can reduce a complex chart to a set of simpler, hierarchically
organized units. This design makes the chart easier to understand and maintain, without
changing the chart behavior. Subchart boundaries do not apply during simulation and
code generation.
The subchart appears as a block with its name in the block center. However, you can
define actions and default transitions for subcharts just as you can for superstates. You
can also create transitions to and from subcharts just as you can create transitions to and
from superstates. You can create transitions between states residing outside a subchart
and any state within a subchart. The term supertransition refers to a transition that
crosses subchart boundaries in this way. See “Move Between Levels of Hierarchy by
Using Supertransitions” on page 8-9 for more information.
Some subcharts can become atomic units if they meet certain modeling requirements. For
more information, see “Restrictions for Converting to Atomic Subcharts” on page 15-32.
Create a Subchart
You create a subchart by converting an existing state, box, or graphical function into the
subchart. The object to convert can be one that you create for making a subchart or an
existing object whose contents you want to turn into a subchart.
1 Right-click the object and select Group & Subchart > Subchart.
2 Confirm that the object now appears as a subchart.
To convert the subchart back to its original form, right-click the subchart. In the context
menu, select Group & Subchart > Subchart.
8-5
8 Techniques for Streamlining Chart Design
You cannot undo the operation of converting a subchart back to its original form. When
you perform this operation, the undo and redo buttons are disabled from undoing and
redoing any prior operations.
1 To convert the On state to a subchart, right-click the state and select Group &
Subchart > Subchart.
2 Confirm that the On state now appears as a subchart.
8-6
Encapsulate Modal Logic by Using Subcharts
Open a Subchart
Opening a subchart allows you to view and change its contents. To open a subchart, do
one of the following:
Edit a Subchart
After you open a subchart (see “Open a Subchart” on page 8-7), you can perform any
editing operation on its contents that you can perform on a top-level chart. This means
that you can create, copy, paste, cut, relabel, and resize the states, transitions, and
subcharts in a subchart. You can also group states, boxes, and graphical functions inside
subcharts.
8-7
8 Techniques for Streamlining Chart Design
You can also cut and paste objects between different levels in your chart. For example, to
copy objects from a top-level chart to one of its subcharts, first open the top-level chart
and copy the objects. Then open the subchart and paste the objects into the subchart.
Transitions from outside subcharts to states or junctions inside subcharts are called
supertransitions. You create supertransitions differently than you do ordinary transitions.
See “Move Between Levels of Hierarchy by Using Supertransitions” on page 8-9 for
information on creating supertransitions.
Navigate Subcharts
The Stateflow Editor toolbar contains a set of buttons for navigating the subchart
hierarchy of a chart.
Tool Description
If the Stateflow Editor is displaying a subchart, clicking this button
replaces the subchart with the parent of the subchart in the Stateflow
Editor. If the Stateflow Editor is displaying a top-level chart, clicking this
button replaces the chart with the Simulink model window containing that
chart.
Clicking this button shows the chart that you visited before the current
chart, so that you can navigate up the hierarchy.
Clicking this button shows the chart that you visited after visiting the
current chart, so that you can navigate down the hierarchy.
Note You can also use the Escape key to navigate up to the parent object for a
subcharted state, box, or function.
8-8
Move Between Levels of Hierarchy by Using Supertransitions
The point where a supertransition enters or exits a subchart is called a slit. Slits divide a
supertransition into graphical segments. For example, the sf_boiler model shows a
supertransition leaving the On subchart:
8-9
8 Techniques for Streamlining Chart Design
8-10
Move Between Levels of Hierarchy by Using Supertransitions
Note You cannot undo the operation of drawing a supertransition. When you perform this
operation, the undo and redo buttons are disabled from undoing and redoing any prior
operations.
A supertransition appears, extending from the source state into the subchart with its
arrowhead penetrating a slit in the subchart.
If you are not happy with the initial position of the slit, you can continue to drag the
slit around the inside edge of the subchart to the desired location.
8-11
8 Techniques for Streamlining Chart Design
The tip of the arrowhead of the supertransition appears highlighted in red, entering
the subchart.
8-12
Move Between Levels of Hierarchy by Using Supertransitions
1 Draw an inner transition segment from the source object anywhere just outside the
border of the subchart
2 Navigate up to the parent object by selecting View > Navigate > Up to Parent.
The tip of the arrowhead of the supertransition appears highlighted in red, exiting
the subchart.
8-13
8 Techniques for Streamlining Chart Design
8-14
Move Between Levels of Hierarchy by Using Supertransitions
Note If the parent chart is itself a subchart and the terminating object resides at a
higher level in the subchart hierarchy, repeat these steps until you reach the desired
parent. In this way, you can connect objects separated by any number of layers in the
subchart hierarchy.
Label Supertransitions
A supertransition is displayed with multiple resulting transition segments for each layer
of containment traversed. For example, if you create a transition between a state outside
a subchart and a state inside a subchart of that subchart, you create a supertransition
with three segments, each displayed at a different containment level.
You can label any one of the transition segments constituting a supertransition using the
same procedure used to label a regular transition (see “Label Transitions” on page 4-19).
The resulting label appears on all the segments that constitute the supertransition. Also,
if you change the label on any one of the segments, the change appears on all segments.
8-15
8 Techniques for Streamlining Chart Design
• Create modular, reusable logic that you can call anywhere in your chart.
• Track simulation behavior visually during chart animation.
A graphical function can reside anywhere in a chart, state, or subchart. The location of
the function determines the set of states and transitions that can call the function.
• If you want to call the function only within one state or subchart and its substates, put
your graphical function in that state or subchart. That function overrides any other
functions of the same name in the parents and ancestors of that state or subchart.
• If you want to call the function anywhere in that chart, put your graphical function at
the chart level.
• If you want to call the function from any chart in your model, put your graphical
function at the chart level and enable exporting of chart-level functions. For more
information, see “Export Stateflow Functions for Reuse” on page 8-22.
For example, this graphical function has the name f1. It takes three arguments (a, b, and
c) and returns three output values (x, y, and z). The function contains a flow chart that
computes three different products of the arguments.
8-16
Reuse Logic Patterns by Defining Graphical Functions
2 Enter the signature label for the function, as described in “Declare Function
Arguments and Return Values” on page 8-18.
3 To program the function, construct a flow chart inside the function box, as described
in “Flow Charts in Stateflow” on page 5-2.
Because a graphical function must execute completely when you call it, you cannot
use states. Connective junctions and transitions are the only graphical elements that
you can use in a graphical function.
4 In the Model Explorer, expand the chart object and select the graphical function. The
arguments and return values of the function signature appear as data items that
belong to your function. Arguments have the scope Input. Return values have the
scope Output.
5 In the Data properties dialog box for each argument and return value, specify the
data properties, as described in “Set Data Properties” on page 9-5.
6 Create any additional data items required by your function. For more information, see
“Add Data Through the Model Explorer” on page 9-3.
Your function can access its own data or data belonging to parent states or the chart.
The data items in the function can have one of these scopes:
• Local — Local data persists from one function call to the next function call. Valid
for C charts only.
• Constant — Constant data retains its initial value through all function calls.
• Parameter — Parameter data retains its initial value through all function calls.
• Temporary — Temporary data initializes at the start of every function call. Valid
for C charts only.
In charts that use C as the action language, define temporary data when you want to use
data that is only valid while a function executes. For example, you can designate a loop
counter to have Temporary scope if the counter value does not need to persist after the
function completes.
In charts that use MATLAB as the action language, you do not need to define temporary
function data. If you use an undefined variable, Stateflow creates a temporary variable.
The variable is available to the rest of the function.
You can initialize your function data (other than arguments and return values) from the
MATLAB workspace. For more information, see “Initialize Data from the MATLAB Base
Workspace” on page 9-24.
8-17
8 Techniques for Streamlining Chart Design
You can specify multiple return values and multiple input arguments. Each return value
and input argument can be a scalar, vector, or matrix of values. For functions with only
one return value, omit the brackets in the signature label.
You can use the same variable name for both arguments and return values. For example,
a function with this signature label uses the variables y1 and y2 as both inputs and
outputs:
If you export this function to C code, y1 and y2 are passed by reference (as pointers), and
u is passed by value. Passing inputs by reference reduces the number of times that the
generated code copies intermediate data, resulting in more optimal code.
The syntax for a call to a graphical function is the same as the function signature, with
actual arguments replacing the formal ones specified in a signature. If the data types of
an actual and formal argument differ, a function casts the actual argument to the type of
the formal argument.
Tip If the formal arguments of a function signature are scalars, verify that inputs and
outputs of function calls follow the rules of scalar expansion. For more information, see
“How Scalar Expansion Works for Functions” on page 17-9.
8-18
Reuse Logic Patterns by Defining Graphical Functions
Name
Function name. Click the function name link to bring your function to the foreground in
its native chart.
Label
Signature label for your function. For more information, see “Declare Function Arguments
and Return Values” on page 8-18.
Description
Function description. You can enter brief descriptions of functions in the hierarchy.
Document Link
Link to online documentation for the function. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow displays the documentation.
8-19
8 Techniques for Streamlining Chart Design
To make the graphical function box opaque, right-click the function and clear the
Content Preview property from the context menu.
To dedicate the entire chart window to programming your function, access the flow chart
in your subcharted graphical function by double-clicking the function box.
See Also
More About
• “Flow Charts in Stateflow” on page 5-2
8-20
See Also
8-21
8 Techniques for Streamlining Chart Design
• Graphical functions
• MATLAB functions
• Truth tables
When you select Export Chart Level Functions, you can call exported functions by
using Simulink Caller blocks with dot notation, chartName.functionName. To call the
exported functions throughout the model from any Stateflow or Simulink Caller block,
select Treat Exported Functions as Globally Visible. Do not use dot notation to call
these functions. You cannot export functions with the same name.
Simulink functions can also be defined directly in the Simulink canvas. For more
information, see Simulink Function.
You must perform this step to export functions from library charts. Otherwise, a
simulation error occurs.
You cannot export a chart-level function when inputs or outputs have any of the following
properties:
8-22
Export Stateflow Functions for Reuse
If you try to export Simulink functions, an error appears when you simulate your model.
To avoid this behavior, clear the Export Chart Level Functions check box in the Chart
properties dialog box.
You cannot export functions from a referenced model and call the functions from a parent
model.
8-23
8 Techniques for Streamlining Chart Design
• In the Model Explorer, for each of the function inputs and outputs, a, b, and c, set
these properties:.
• Size to 1
• Complexity to Off
• Type to double
3 For modChart, add a graphical function and a default transition with a lib1_func
action.
8-24
Export Stateflow Functions for Reuse
a In the Model Explorer, for each of the function inputs and outputs, a, b, and c,
set:
• Size to 1
• Complexity to Off
• Type to double
b Open the Chart properties dialog box.
c In the Chart properties dialog box, select Export Chart Level Functions and
Treat Exported Functions as Globally Visible.
d Click OK.
5 Drag lib1Chart and lib2Chart into main_model from lib1 and lib2,
respectively. Your main model should look something like this:
Each chart now defines a graphical function that any chart in main_model can call.
6 Open the Model Explorer.
7 In the Model Hierarchy pane of the Model Explorer, navigate to main_model.
8 Add the data x and y to the Stateflow machine:
8-25
8 Techniques for Streamlining Chart Design
This step ensures that input and output data are defined globally to support exported
graphical functions.
9 Open the Model Configuration Parameters dialog box.
10 In the Model Configuration Parameters dialog box, go to the Solver pane.
11 In the Solver selection section, make these changes:
This step ensures that when you simulate your model, a discrete solver is used. For
more information, see “Solvers” (Simulink).
When you simulate the model, these actions take place during each time step.
8-26
Export Stateflow Functions for Reuse
To view the simulation results, add a scope to your model. Follow these steps:
{x = lib1_func(x,y); z = x;}
7 In the model, connect the outport from modChart to the inport of the Scope block.
8-27
8 Techniques for Streamlining Chart Design
10 After the simulation ends, right-click in the scope display and select Autoscale.
8-28
Group Chart Objects by Using Boxes
For example, in this chart, the box Heater groups together related states Off and On.
Boxes add a level of hierarchy to Stateflow charts. This property affects visibility of
functions and states inside a box to objects that reside outside of the box. If you refer to a
box-parented function or state from a location outside of the box, you must include the
box name in the path. See “Group Functions Using a Box” on page 8-32.
Boxes affect the implicit activation order of parallel states in a chart. If your chart uses
implicit ordering, parallel states within a box wake up before other parallel states that are
8-29
8 Techniques for Streamlining Chart Design
lower or to the right in that chart. Within a box, parallel states wake up in top-down, left-
right order. See “Group States Using a Box” on page 8-33.
• Include the box name in the path when you use dot notation to refer to a box-parented
function or state from a location outside of the box.
• You can move or draw graphical objects inside a box, such as functions and states.
• You can add data to a box so that all the elements in the box can share the same data.
• You can group a box and its contents into a single graphical element. See “Group
States” on page 4-6.
• You can subchart a box to hide its elements. See “Encapsulate Modal Logic by Using
Subcharts” on page 8-5.
• You cannot define action statements for a box, such as entry, during, and exit
actions.
• You cannot define a transition to or from a box. However, you can define a transition to
or from a state within a box.
You create boxes in your chart by using the box tool shown below.
8-30
Group Chart Objects by Using Boxes
8-31
8 Techniques for Streamlining Chart Design
The new box appears with a question mark (?) name in its upper left corner.
4 Click the question mark label.
5 Enter a name for the box and then click outside of the box.
Delete a Box
This chart shows a box named Status that groups together MATLAB functions.
Note Because the MATLAB function resides inside a box, the path of the function
call must include the box name Status. If you omit this prefix, an error message
appears.
8-32
Group Chart Objects by Using Boxes
3 If the value of the input data temp exceeds 80, a transition to the state Warm occurs.
4 Upon entry, the state Warm invokes the function Status.msgWarm.
Note Because the MATLAB function resides inside a box, the path of the function
call must include the box name Status. If you omit this prefix, an error message
appears.
5 If the value of the input data temp drops below 60, a transition to the state Cold
occurs.
6 Steps 2 through 5 repeat until the simulation ends.
This chart shows a box named Status that groups together related states. The chart uses
implicit ordering for parallel states, instead of the default explicit mode. (For details, see
“Implicit Ordering of Parallel States” on page 3-88.)
8-33
8 Techniques for Streamlining Chart Design
• The state Temp wakes up first, followed by the state Wind_Chill. Then, the state
Monitor wakes up.
Note This implicit activation order occurs because Temp and Wind_Chill reside in a
box. If you remove the box, the implicit activation order changes, as shown, to: Temp,
Monitor, Wind_Chill.
• Based on the input data temp, transitions between substates occur in the parallel
states Status.Temp and Status.Wind_Chill.
• When the transition from Status.Temp.Cold to Status.Temp.Warm occurs, the
transition condition in(Status.Temp.Warm) becomes true.
• When the transition from Status.Temp.Warm to Status.Temp.Cold occurs, the
transition condition in(Status.Temp.Cold) becomes true.
8-34
Reuse Functions by Using Atomic Boxes
• Faster simulation after making small changes to a function in a chart with many states
or levels of hierarchy.
• Reuse of the same functions across multiple charts and models.
• Ease of team development for people working on different parts of the same chart.
• Manual inspection of generated code for a specific function in a chart.
An atomic box looks opaque and includes the label Atomic in the upper left corner. If you
use a linked atomic box from a library, the label Link appears in the upper left corner.
8-35
8 Techniques for Streamlining Chart Design
The top model sf_timer_modelref reuses the timer function in multiple referenced
blocks. Because there are no exported functions, you can use more than one instance of
the referenced block in the top model.
8-36
Reuse Functions by Using Atomic Boxes
Atomic boxes contain only functions. They cannot contain states. Adding a state to an
atomic box results in a compilation-time error.
To call a function that resides in an atomic box from a location outside the atomic box, use
dot notation to specify its full path:
atomic_box_name.function_name
• Makes clear the dependency on the function in the linked atomic box.
• Avoids pollution of the global namespace.
• Does not affect the efficiency of generated code.
To create a container for your functions that allows for faster debugging and code
generation workflows, convert an existing box into an atomic box. In your chart, right-
click a normal box and select Group & Subchart > Atomic Subchart. The label Atomic
appears in the upper left corner of the box.
The conversion process gives the atomic box its own copy of every data object that the
box accesses in the chart. Local data is copied as data store memory. The scope of other
data, including input and output data, does not change.
Note If a box contains any states or messages, you cannot convert it to an atomic box.
8-37
8 Techniques for Streamlining Chart Design
To create a collection of functions for reuse across multiple charts and models, create a
link from a library model. Copy a chart in a library model and paste it to a chart in
another model. If the library chart contains only functions and no states, it appears as a
linked atomic box with the label Link in the upper left corner.
This modeling method minimizes maintenance of reusable functions. When you modify the
atomic box in the library, your changes propagate to the links in all charts and models.
If the library chart contains any states, then it appears as a linked atomic subchart in the
chart. For more information, see “Create Reusable Subcomponents by Using Atomic
Subcharts” on page 15-2.
Converting an atomic box back to a normal box removes all of its variable mappings by
merging subchart-parented data objects with the chart-parented data to which they map.
1 If the atomic box is a library link, right-click the atomic box and select Library Link
> Disable Link.
2 To convert an atomic box to a subcharted box, right-click the atomic box and clear
the Group & Subchart > Atomic Subchart check box.
3 To convert the subcharted box back to a normal box, right-click the subchart and
clear the Group & Subchart > Subchart check box.
4 If necessary, rearrange graphical objects in your chart.
• The atomic box maps a parameter to an expression other than a single variable name.
For example, mapping a parameter data1 to one of these expressions prevents the
conversion of an atomic box to a normal box:
• 3
• data2(3)
• data2 + 3
• Both of these conditions are true:
• The atomic box contains MATLAB functions or truth table functions that use
MATLAB as the action language.
8-38
Reuse Functions by Using Atomic Boxes
• The atomic box does not map each variable to a variable of the same name in the
main chart.
Suppose that you want to test a sequence of changes to a library of functions. The
functions are part of a chart that contains many states or several levels of hierarchy, so
recompiling the entire chart can take a long time. If you define the functions in an atomic
box, recompilation occurs for only the box and not for the entire chart. For more
information, see “Reduce the Compilation Time of a Chart” on page 15-43.
Reuse Functions
Suppose that you have a set of functions for use in multiple charts and models. The
functions reside in the library model to enable easier configuration management. To use
the functions in another model, you can either:
• Configure the library chart to export functions and create a link to the library chart in
the model.
• Link the library chart as an atomic box in each chart of the model.
Models that use these functions can appear as referenced blocks in a top model. When
the functions are exported, you can use only one instance of that referenced block for
each top model. For more information, see “Model Reference Requirements and
Limitations” (Simulink).
With atomic boxes, you can avoid this limitation. Because there are no exported functions
in the charts, you can use more than one instance of the referenced block in the top
model.
Suppose that multiple people are working on different parts of a chart. If you store each
library of functions in a linked atomic box, different people can work on different libraries
without affecting the other parts of the chart. For more information, see “Divide a Chart
into Separate Units” on page 15-45.
Suppose that you want to inspect code generated by Simulink Coder or Embedded Coder
manually for a specific function. You can specify that the code for an atomic box appears
8-39
8 Techniques for Streamlining Chart Design
in a separate file to avoid searching through unrelated code. For more information, see
“Generate Reusable Code for Unit Testing” on page 15-48.
See Also
More About
• “Group Chart Objects by Using Boxes” on page 8-29
• “Create Reusable Subcomponents by Using Atomic Subcharts” on page 15-2
• “Map Variables for Atomic Subcharts and Boxes” on page 15-9
8-40
Add Descriptive Comments in a Chart
Create Notes
You can enter comments or notes in any location on the chart.
1 Double-click in the desired location of the chart and start typing your comments.
2 Press the Enter key to start a new line.
3 After you finish typing, click outside the note text.
• Borders
• Text alignment and word wrap
• Text color and background color
• Margins between the text and the borders of the note
TeX Instructions
In your notes, you can embed a subset of TeX commands to produce special characters.
For example, you can embed Greek letters and mathematical symbols.
8-41
8 Techniques for Streamlining Chart Design
\it{\omega_N = e^{(-2\pii)/N}}
4 Click outside the note.
8-42
9
Define Data
Data defined in a Stateflow chart is visible by multiple Stateflow objects in the chart,
including states, transitions, MATLAB functions, and truth tables. To determine what data
is used in a state or transition, right-click the state or transition and select Explore. A
context menu lists the names and scopes of all resolved symbols in the state or transition.
Selecting a symbol from the context menu displays its properties in the Model Explorer.
Selecting an output event from the context menu opens the Simulink subsystem or
Stateflow chart associated with the event.
Note Stateflow data is not available to Simulink functions within a Stateflow chart.
You can add data through the Symbols window, the Chart menu in the Stateflow Editor,
or the Model Explorer.
• Input Data
• Local Data
• Output Data
• Constant
• Data Store Memory
• Parameter
• Temporary
4 Edit the name of the data.
5 For input and output data, click the PORT field and choose a port number.
9-2
Add Stateflow Data
6 To specify properties for data, open the Property Inspector. In the Symbols window,
right-click the row for the symbol and select Explore. For more information, see
“Stateflow Data Properties” on page 9-5.
9-3
9 Define Data
Stateflow output data should not inherit properties from output signals, because the
values back propagate from Simulink blocks and can be unpredictable.
• Enumerated data
• Simulink functions
• Chart operating point
• Implicit change events
• Detection of unused data
• Model referencing (see “Model Reference Requirements and Limitations” (Simulink) )
• Analysis by Simulink Design Verifier™ software
• Code generation by Simulink PLC Coder™ software
• Parameters binding to a Simulink.Parameter object in the base workspace
To make Stateflow data accessible to other charts and blocks in a model, use data store
memory. For details, see “Access Data Store Memory from a Chart” on page 9-28.
See Also
More About
• “Set Data Properties” on page 9-5
• “Specify Type of Stateflow Data” on page 9-33
• “Manage Data, Events, and Messages in the Symbols Window” on page 33-2
• “Resolve Undefined Symbols in Your Chart” on page 30-35
9-4
Set Data Properties
• Property Inspector
Properties vary according to the scope and type of the data object. For many data
properties, you can enter expressions or parameter values. Using parameters to set
properties for many data objects simplifies maintenance of your model because you can
update multiple properties by changing a single parameter.
Name
Name of the data object. For more information, see “Rules for Naming Stateflow Objects”
on page 2-4.
Scope
9-5
9 Define Data
Setting Description
Local Data defined in the current chart only.
Constant Read-only constant value that is visible to the parent Stateflow
object and its children.
Parameter Constant whose value is defined in the MATLAB base workspace
or derived from a Simulink block parameter that you define and
initialize in the parent masked subsystem. The Stateflow data
object must have the same name as the MATLAB variable or the
Simulink parameter. For more information, see “Share Parameters
with Simulink and the MATLAB Workspace” on page 9-26.
Input Input argument to a function if the parent is a graphical function,
truth table, or MATLAB function. Otherwise, the Simulink model
provides the data to the chart through an input port on the
Stateflow block. For more information, see “Share Input and
Output Data with Simulink” on page 9-23.
Output Return value of a function if the parent is a graphical function,
truth table, or MATLAB function. Otherwise, the chart provides
the data to the Simulink model through an output port on the
Stateflow block. For more information, see “Share Input and
Output Data with Simulink” on page 9-23.
Data Store Data object that binds to a Simulink data store, which is a signal
Memory that functions like a global variable. All blocks in a model can
access that signal. This binding allows the chart to read and write
to the Simulink data store, sharing global data with the model.
The Stateflow object must have the same name as the Simulink
data store. For more information, see “Access Data Store Memory
from a Chart” on page 9-28.
Temporary Data that persists during only the execution of a function. For C
charts, you can define temporary data only for a graphical
function, truth table, or MATLAB function.
Exported Data from the Simulink model that is made available to external
code defined in the Stateflow hierarchy. You can define exported
data only for a Stateflow machine.
Imported Data parented by the Simulink model that you define in external
code embedded in the Stateflow machine. You can define imported
data only for a Stateflow machine.
9-6
Set Data Properties
Port
Index of the port associated with the data object. This property applies only to input and
output data. See “Share Input and Output Data with Simulink” on page 9-23.
Update Method
Specifies whether a variable updates in discrete or continuous time. This property applies
only when the chart is configured for continuous-time simulation. See “Continuous-Time
Modeling in Stateflow” on page 21-2.
Specifies that output or local data explicitly inherits properties from Simulink.Signal
objects of the same name in the MATLAB base workspace or the Simulink model
workspace. The data can inherit these properties:
• Size
• Complexity
• Type
• Unit
• Minimum value
• Maximum value
• Initial value
• Storage class
• Sampling mode (for Truth Table block output data)
This option is available only when you set the model configuration parameter Signal
resolution to a value other than None. For more information, see “Resolve Data
Properties from Simulink Signal Objects” on page 9-55.
Size
Size of the data object. The size can be a scalar value or a MATLAB vector of values. To
specify a scalar, set the Size property to 1 or leave it blank. To specify a MATLAB vector,
use a multidimensional array. The number of dimensions equals the length of the vector
and the size of each dimension that corresponds to the value of each vector element.
The scope of the data object determines what sizes you can specify. Stateflow data store
memory inherits all its properties, including its size, from the Simulink data store to
9-7
9 Define Data
which it is bound. For all other scopes, size can be scalar, vector, or a matrix of n-
dimensions.
For more information, see “Specify Size of Stateflow Data” on page 9-40.
Variable Size
Specifies that the data object changes dimensions during simulation. This option is
available for input and output data only when you enable the chart property Support
variable-size arrays. For more information, see “Declare Variable-Size Data in Stateflow
Charts” on page 18-2.
Complexity
Setting Description
Off Data object does not accept complex values.
On Data object accepts complex values.
Inherited Data object inherits the complexity setting from a Simulink block.
The default value is Off. For more information, see “Complex Data in Stateflow Charts”
on page 23-2.
First Index
Index of the first element of the data array. The first index can be any non-negative
integer. The default value is 0. This property is available only for C charts.
Type
For more information, see “Specify Type of Stateflow Data” on page 9-33.
9-8
Set Data Properties
Note If you enter an expression for a fixed-point data type, you must specify scaling
explicitly. For example, you cannot enter an incomplete specification such as
fixdt(1,16) in the Type field. If you do not specify scaling explicitly, an error appears
when you try to simulate your model.
Prevents replacement of the current fixed-point type with an autoscaled type chosen by
the “Fixed-Point Tool” (Fixed-Point Designer). For more information, see “Autoscaling
Using the Fixed-Point Tool” (Fixed-Point Designer).
Specifies physical units for input and output data. For more information, see “Specify
Units for Stateflow Data” on page 24-41.
Initial Value
Initial value of the data object. The options for initializing values depend on the scope of
the data object.
If you do not specify a value, the default value for numeric data is 0. For enumerated data,
the default value is the first one listed in the enumeration section of the definition,
9-9
9 Define Data
unless you specify otherwise in the methods section of the definition. For more
information, see “Enter Expressions and Parameters for Data Properties” on page 9-20.
Specifies that local, constant, or output data inherits its initial value from a Simulink
parameter in the MATLAB base workspace. For more information, see “Initialize Data
from the MATLAB Base Workspace” on page 9-24.
Range of acceptable values for this data object. Stateflow charts use this range to validate
the data object during simulation.
• Minimum — The smallest value allowed for the data item during simulation. You can
enter an expression or parameter that evaluates to a numeric scalar value.
• Maximum — The largest value allowed for the data item during simulation. You can
enter an expression or parameter that evaluates to a numeric scalar value.
The smallest value that you can set for Minimum is -inf. The largest value that you can
set for Maximum is inf. For more information, see “Enter Expressions and Parameters
for Data Properties” on page 9-20.
Note A Simulink model uses the Limit range properties to calculate best-precision
scaling for fixed-point data types. Before you select Calculate Best-Precision Scaling,
specify a minimum or maximum value. For more information, see “Calculate Best-
Precision Scaling” on page 9-14.
Enables watching the data values in the Stateflow Breakpoints and Watch window. For
more information, see “Watch Stateflow Data Values” on page 32-36.
9-10
Set Data Properties
9-11
9 Define Data
Signedness
Specifies whether the fixed-point data is Signed or Unsigned. Signed data can represent
positive and negative values. Unsigned data represents positive values only. The default
setting is Signed.
Word Length
Specifies the bit size of the word that holds the quantized integer. Large word sizes
represent large values with greater precision than small word sizes. The default value is
16.
• Word length can be any integer from 0 through 128 for chart-level data of these
scopes:
• Input
• Output
• Parameter
• Data Store Memory
• For other Stateflow data, word length can be any integer from 0 through 32.
Scaling
Specifies the method for scaling your fixed-point data to avoid overflow conditions and
minimize quantization errors. The default method is Binary point scaling.
9-12
Set Data Properties
Setting Description
Binary point If you select this mode, the Data Type Assistant displays the
Fraction length field, which specifies the binary point location.
Slope and bias If you select this mode, the Data Type Assistant displays fields for
entering the Slope and Bias for the fixed-point encoding scheme.
Slope can be any positive real number. The default value is 1.0.
Specifies whether to inherit the data type override setting of the Fixed-Point Tool that
applies to this model. If the data does not inherit the model-wide setting, the specified
data type applies. For more information about the Fixed-Point Tool, see fxptdlg.
9-13
9 Define Data
Specifies whether to calculate the best-precision values for Binary point and Slope
and bias scaling, based on the values in the Minimum and Maximum fields in the
Limit range section.
Simulink software calculates the scaling values and displays them in the Fraction length
field or the Slope and Bias fields. For more information, see “Constant Scaling for Best
Precision” (Fixed-Point Designer).
Note The Limit range properties do not apply to Constant and Parameter scopes. For
Constant, Simulink software calculates the scaling values based on the Initial value
setting. The software cannot calculate best-precision scaling for data of Parameter
scope.
Displays information about the fixed-point data type that is defined in the Data Type
Assistant:
• Minimum and Maximum show the same values that appear in the corresponding
Minimum and Maximum fields in the Limit range section.
• Representable minimum, Representable maximum, and Precision show the
minimum value, maximum value, and precision that the fixed-point data type can
represent.
If the value of a field cannot be determined without first compiling the model, the Fixed-
point details subpane shows the value as Unknown.
9-14
Set Data Properties
9-15
9 Define Data
The values displayed by the Fixed-point details subpane do not automatically update if
you change the values that define the fixed-point data type. To update the values shown in
the Fixed-point details subpane, click Refresh Details.
Clicking Refresh Details does not modify the model. It changes only the display. To apply
the displayed values, click Apply or OK.
The Fixed-point details subpane indicates any error resulting from the fixed-point data
type specification. For example, this figure shows two errors.
9-16
Set Data Properties
The row labeled Maximum indicates that the value specified in the Maximum field of the
Limit range section is not representable by the fixed-point data type. To correct the
9-17
9 Define Data
error, make one of these modifications so the fixed-point data type can represent the
maximum value:
• Decrease the value in the Maximum field of the Limit range section.
• Increase Word length.
• Decrease Fraction length.
The row labeled Minimum shows the error Cannot evaluate because evaluating the
expression MySymbol, specified in the Minimum field of the Limit range section, does
not return a numeric value. When an expression does not evaluate successfully, the
Fixed-point details subpane shows the unevaluated expression (truncating to 10
characters as needed) in place of the unavailable value. To correct this error, define
MySymbol in the base workspace to provide a numeric value. If you click Refresh
Details, the error indicator and description are removed and the value of MySymbol
appears in place of the unevaluated text.
Logging Properties
You can set logging properties for data in:
Saves the data value to the MATLAB base workspace during simulation. For more
information, see “Log Simulation Output for States and Data” on page 32-51.
Test Point
Designates the data as a test point. A test point is a signal that you can observe in a
Floating Scope block in a model. Data objects can be test points if:
• Scope is Local.
• Parent is not a Stateflow machine.
• Data type is not ml.
For more information, see “Monitor Test Points in Stateflow Charts” on page 32-46.
9-18
Set Data Properties
Logging Name
Specifies the name associated with logged signal data. Simulink software uses the signal
name as its logging name by default. To specify a custom logging name, select Custom
from the list box and enter the new name in the adjacent edit field.
Decimation
Limits the amount of data logged by skipping samples. For example, a decimation factor
of 2 saves every other sample.
Additional Properties
You can set additional data properties in:
Assigns the value of the data item to a variable of the same name in the MATLAB base
workspace at the end of simulation. This option is available only in the Model Explorer for
C charts. For more information, see “Model Workspaces” (Simulink).
Units
Units of measurement associated with the data object. The unit in this field resides with
the data object in the Stateflow hierarchy. This property is available only in the Model
Explorer for C charts.
Description
Description of the data object. You can enter brief descriptions of data in the hierarchy.
Document Link
Link to online documentation for the data object. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
9-19
9 Define Data
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow evaluates the link and displays the documentation.
Expressions can contain a mix of parameters, constants, arithmetic operators, and calls to
MATLAB functions.
When you leave an expression or parameter field blank, Stateflow assumes a default
value.
Field Default
Initial value 0.0
Maximum inf
Minimum –inf
Word length 16
Slope 1.0
Bias 0.0
Binary point 0
First index 0
Size −1 (inherited), for inputs, parameters, and function outputs
9-20
Set Data Properties
You can include parameters in expressions. A parameter is a constant value that you can:
You can mix both types of parameters in an expression. For more information, see “Share
Parameters with Simulink and the MATLAB Workspace” on page 9-26.
For expressions in the Data properties dialog box, you can use numeric constants of the
appropriate type and size. Do not use Stateflow constants in these expressions.
In the Data properties dialog box, you can use these arithmetic operators in expressions:
• +
• –
• *
• /
In fields that accept expressions, you can call functions that return property values of
other variables defined in the Stateflow hierarchy, MATLAB base workspace, or Simulink
masked subsystem. For example, these functions can return appropriate values for
specified fields in the Data properties dialog box.
9-21
9 Define Data
See Also
More About
• “Add Stateflow Data” on page 9-2
• “Rules for Naming Stateflow Objects” on page 2-4
• “Specify Type of Stateflow Data” on page 9-33
• “Identify Data by Using Dot Notation” on page 9-50
9-22
Share Data with Simulink and the MATLAB Workspace
Charts also can access Simulink parameters and data stores. For more information, see
“Share Parameters with Simulink and the MATLAB Workspace” on page 9-26 and
“Access Data Store Memory from a Chart” on page 9-28.
1 Add a data object to the chart, as described in “Add Stateflow Data” on page 9-2.
2 Set the Scope property for the data object.
• To define input data, set Scope to Input Data. An input port appears on the left
side of the chart block.
• To define output data, set Scope to Output Data. An output port appears on the
right side of the chart block.
By default, Port values appear in the order in which you add data objects. You can
change these assignments by modifying the Port property of the data. When you
change the Port property for an input or output data object, the Port values for the
remaining input or output data objects automatically renumber.
3 Set the data type of the data object, as described in “Specify Type of Stateflow Data”
on page 9-33.
4 Set the size of the data object, as described in “Specify Size of Stateflow Data” on
page 9-40.
Note You cannot set the type or size of Stateflow input data to accept frame-based data
from Simulink.
9-23
9 Define Data
When the simulation starts, data resolution occurs. During this process, the Stateflow
data object gets its initial value from the associated MATLAB variable.
One-dimensional Stateflow arrays are compatible with MATLAB row and column vectors
of the same size. For example, a Stateflow vector of size 5 is compatible with a MATLAB
row vector of size [1,5] or column vector of size [5,1]. Each element of the Stateflow
array initializes to the same value as the corresponding element of the array in the
MATLAB base workspace.
The time of initialization depends on the data parent and scope of the Stateflow data
object.
9-24
See Also
This option is available for data symbols of all scopes except Constant and Parameter.
See Also
More About
• “Add Stateflow Data” on page 9-2
• “Set Data Properties” on page 9-5
• “Share Parameters with Simulink and the MATLAB Workspace” on page 9-26
• “Access Data Store Memory from a Chart” on page 9-28
9-25
9 Define Data
Use parameters to avoid hard-coding data values and properties. Share Simulink
parameters with charts to maintain consistency with your Simulink model.
You can access parameter values in multiple Stateflow objects in a chart such as states,
MATLAB functions, and truth tables. You can include parameters in expressions defining
data properties such as:
• Size
• Type
• Initial Value
• Minimum and Maximum
• Fixed-Point Data Properties
For more information, see “Enter Expressions and Parameters for Data Properties” on
page 9-20
When the simulation starts, data resolution occurs. During this process, the Stateflow
parameter gets its value from the associated MATLAB variable.
9-26
See Also
1 In the Simulink mask editor for the parent subsystem, define and initialize a Simulink
parameter.
2 In the Stateflow hierarchy, define a data object with the same name as the Simulink
parameter.
3 Set the scope of the Stateflow data object to Parameter.
When the simulation starts, Simulink tries to resolve the Stateflow data object to a
parameter at the lowest-level masked subsystem. If unsuccessful, Simulink moves up the
model hierarchy to resolve the data object to a parameter at higher-level masked
subsystems.
See Also
More About
• “Create a Mask to Share Parameters with Simulink” on page 24-22
• “Add Stateflow Data” on page 9-2
• “Set Data Properties” on page 9-5
9-27
9 Define Data
To access global data from a chart, bind a Stateflow data object to a Simulink data store.
After you create the binding, the Stateflow data object becomes a symbolic representation
of the Simulink data store memory. You can then use this symbolic object to store and
retrieve global data.
• Local data stores are visible to all blocks in one model. To interact with a local data
store, a chart must reside in the model where you define the local data store. You can
define a local data store by adding a Data Store Memory block to a model or by
creating a Simulink signal object.
• Global data stores have a broader scope that crosses model reference boundaries. To
interact with global data stores, a chart must reside in the top model where you define
9-28
Access Data Store Memory from a Chart
the global data store or in a model that the top model references. You implement
global data stores as Simulink signal objects.
For more information, see “Local and Global Data Stores” (Simulink).
The Stateflow data object inherits all additional properties from the data store memory to
which you bind the object.
Multiple local and global data stores with the same name can exist in the same model
hierarchy. In this situation, the Stateflow data object binds to the data store that is the
nearest ancestor.
For example, in this chart, the state actions read from and write to a Data Store Memory
block called myglobal.
9-29
9 Define Data
When you bind a Stateflow data object to a data store, the Stateflow object inherits all of
its properties from the data store. To ensure that properties propagate correctly, when
you create the Simulink data stores:
• Verify that your models do not contain any Data Store Memory blocks. You can include
Data Store Read and Data Store Write blocks.
• In the MATLAB base workspace, create a Simulink.Signal object with these
attributes:
• Set Data type to an explicit data type. The data type cannot be Auto.
• Fully specify Dimensions. The signal dimensions cannot be –1 or Inherited.
9-30
Access Data Store Memory from a Chart
To avoid algorithm latency, write to data store memory before reading from it. Otherwise,
the read actions retrieve the value that was stored in the previous time step, rather than
the value computed and stored in the current time step. When unconnected blocks share
global data while running at different rates:
To avoid situations when multiple reads and writes occur unintentionally in the same time
step, enable the Data Store Memory block diagnostics to:
If you use a data store memory block as a persistent global storage area for accumulating
values across time steps, avoid unnecessary warnings by disabling the Data Store
Memory block diagnostics. For more information, see “Data Store Diagnostics”
(Simulink).
9-31
9 Define Data
See Also
Data Store Read | Data Store Write | Data Store Memory | Simulink.Signal
More About
• “Add Stateflow Data” on page 9-2
• “Data Store Basics” (Simulink)
• “Model Global Data by Creating Data Stores” (Simulink)
• “Data Store Diagnostics” (Simulink)
• “Control and Display the Sorted Order” (Simulink)
9-32
Specify Type of Stateflow Data
Alternatively, use the Data Type Assistant to specify a data Mode and select the data type
based on that mode:
1 In the Model Explorer, on the Data pane, click the Show data type assistant button
.
2 Select a Mode from the drop-down list. The list of available modes depends on the
scope of the data object.
Scope Modes
Local Inherit (available only in charts that use MATLAB as the action language),
Built in, Fixed point, Enumerated, Bus object, Expression
Constant Built in, Fixed point, Expression
Parameter Inherit, Built in, Fixed point, Enumerated, Bus object,
Expression
Input Inherit, Built in, Fixed point, Enumerated, Bus object,
Expression
Output Inherit, Built in, Fixed point, Enumerated, Bus object,
Expression
Data Store Inherit
Memory
3 Specify additional information based on the mode. The Data Type Assistant populates
the Type field based on your specification.
9-33
9 Define Data
• For charts that use MATLAB as the action language, if scope is Local, the
data infers its type from the context of the MATLAB code in the chart.
• If the scope is Parameter, the data inherits its type from the associated
parameter, which you can define in the Simulink model or in the MATLAB
base workspace. See “Share Parameters with Simulink and the MATLAB
Workspace” on page 9-26.
• If the scope is Input, the data inherits its type from the Simulink input
signal on the designated input port. See “Share Input and Output Data
with Simulink” on page 9-23.
• If the scope is Output, the data inherits its type from the Simulink output
signal on the designated output port. See “Share Input and Output Data
with Simulink” on page 9-23.
Note Avoid inheriting data types from output signals. See “Avoid
inheriting output data properties from Simulink blocks” on page 9-4.
• If the scope is Data Store Memory, the data inherits its type from the
Simulink data store to which you bind the data object. See “Access Data
Store Memory from a Chart” on page 9-28.
For more information, see “Inherit Data Types from Simulink Objects” on
page 9-36.
9-34
Specify Type of Stateflow Data
9-35
9 Define Data
For more information, see “Enter Expressions and Parameters for Data
Properties” on page 9-20.
4 To save the data type settings, click Apply.
The Data Type Assistant is available only through the Model Explorer.
Scope Description
Input Inherits type from the Simulink input signal connected to
corresponding input port in chart.
Output Inherits type from the Simulink output signal connected to
corresponding output port in chart.
Avoid inheriting data types from output signals. Values that back-
propagate from Simulink blocks can be unpredictable.
Parameter Inherits type from the corresponding MATLAB base workspace
variable or Simulink parameter in a masked subsystem.
9-36
Specify Type of Stateflow Data
Scope Description
Data Store Inherits type from the corresponding Simulink data store.
Memory
type(data_obj)
For example, in the model sf_bus_demo, the expression type(inbus) returns the data
type of the input structure inbus. Because inbus derives its type from the
Simulink.Bus object COUNTERBUS, the data type of the local structure
counterbus_struct also derives its data type from COUNTERBUS.
9-37
9 Define Data
After you build your model, the CompiledType column of the Model Explorer shows the
type used in the compiled simulation application.
For example, suppose that you want to define a data type alias MyFloat that corresponds
to the built-in data type single. At the MATLAB command prompt, enter:
MyFloat = Simulink.AliasType;
MyFloat.BaseType = 'single';
To use this alias to specify the type of a data object, select the object in the Property
Inspector or the Model Explorer. In the Type field, enter the alias name MyFloat.
After you build your model, the CompiledType column of the Model Explorer shows the
type used in the compiled simulation application.
9-38
See Also
If you clear the Use Strong Data Typing with Simulink I/O chart property, the chart
converts inputs signals of type double to the type of the corresponding input data object
in the chart. The chart converts output data objects to type double before exporting
them as output signals to Simulink models.
Note The Use Strong Data Typing with Simulink I/O chart property is provided for
backward compatibility. Clearing this check box can produce unpredictable results and is
not recommended.
See Also
More About
• “Set Data Properties” on page 9-5
• “Specify Properties for Stateflow Charts” on page 24-3
• “About Data Types in Simulink” (Simulink)
9-39
9 Define Data
Stateflow data store memory inherits all data properties, including size, from the
Simulink data store to which it resolves. You cannot specify any properties explicitly for
data store memory.
9-40
Specify Size of Stateflow Data
The equivalent API command for specifying an inherited data size is:
data_handle.Props.Array.Size = '-1';
Chart actions that store values in the specified output infer the inherited size of output
data. If the expected size in the Simulink signal matches the inferred size, inheritance is
successful. Otherwise, a mismatch occurs during build time.
Note Charts cannot inherit frame-based data sizes from Simulink signals.
9-41
9 Define Data
One-dimensional Stateflow vectors are compatible with Simulink row or column vectors of
the same size. For example, Stateflow input or output data of size 3 is compatible with a
Simulink row vector of size [1 3] or column vector of size [3 1].
9-42
Specify Size of Stateflow Data
1 Mask parameters
2 Model workspace
3 MATLAB base workspace
4 Stateflow data
For example, if a variable named off exists in the MATLAB base workspace and as local
chart data, do not use off in the Size field of the data properties.
Instead of using a size(u) expression, use a MATLAB expression that evaluates directly
to the size of Stateflow data.
9-43
9 Define Data
See Also
More About
• “Stateflow Data Properties” on page 9-5
9-44
Handle Integer Overflow for Chart Data
For more information about saturation and wrapping for integer overflow, see “Saturation
and Wrapping” (Fixed-Point Designer).
9-45
9 Define Data
Check Box When to Use This Overflow Handling Example of the Result
Setting
Selected Overflow is possible for Overflows saturate to An overflow associated
data in your chart and you either the minimum or with a signed 8-bit integer
want explicit saturation maximum value that the saturates to –128 or +127
protection in the data type can represent. in the generated code.
generated code.
Cleared You want to optimize The handling of overflows The number 130 does not
efficiency of the generated depends on the C compiler fit in a signed 8-bit integer
code. that you use for generating and wraps to –126 in the
code. generated code.
Arithmetic operations for which you can enable saturation protection are:
9-46
Handle Integer Overflow for Chart Data
• Unary minus: –a
• Binary operations: a + b, a – b, a * b, a / b, a ^ b
• Assignment operations: a += b, a –=b, a *= b, a /= b
• In C charts, increment and decrement operations: ++, --
• Saturation applies to all intermediate operations, not just the output or final result.
• The code generator can detect some cases when overflow is not possible. In these
cases, the generated code does not include saturation protection.
To determine whether clearing the Saturate on integer overflow check box is a safe
option, perform a careful analysis of your logic, including simulation if necessary. If
saturation is necessary in only some sections of the logic, encapsulate that logic in atomic
subcharts or MATLAB functions and define a different set of saturation settings for those
units.
• All arithmetic operations use a data type that has the same word length as the target
word size. Therefore, the intermediate data type in a chained arithmetic operation can
be different from the data type of the operands or the final result.
• For operands with integer types smaller than the target word size, promotion to a
larger type of the same word length as the target size occurs. This implicit cast occurs
before any arithmetic operations take place.
For example, when the target word size is 32 bits, an implicit cast to int32 occurs for
operands with a type of uint8, uint16, int8, or int16 before any arithmetic
operations occur.
Suppose that you have the following expression, where y, u1, u2, and u3 are of uint8
type:
9-47
9 Define Data
For each calculation, the following data types and saturation limits apply.
Suppose that u1, u2, and u3 are equal to 200. Because the saturation limits depend on
the intermediate data types and not the operand types, you get the following values:
• tmp is 400.
• result is 200.
• y is 200.
9-48
Define Temporary Data for Functions in C Charts
In charts that use MATLAB as the action language, you do not need to define temporary
function data in the Model Explorer. If a variable is used and not previously defined, then
it is automatically created. The variable is available to the rest of the function.
The Model Explorer adds a default definition for the data in the Stateflow hierarchy,
with a scope set to Temporary by default.
4 Change other properties of the data if necessary, as described in “Set Data
Properties” on page 9-5.
9-49
9 Define Data
For example, in this chart, the symbol data resides in the substate aa of the state a. The
state and transition actions use qualified data names to refer to this symbol.
• In the default transition, the action uses the qualified data name a.aa.data to specify
a path from the chart to the top-level state a, to the substate aa, and finally to data.
• In state a, the entry action uses the qualified data name aa.data to specify a path
from the substate aa to data.
• In state b, the entry action uses the qualified data name a.aa.data to specify a path
from the chart to the state a, to the substate aa, and then to data.
• For a state action, the starting point is the state containing the action.
• For a transition label, the starting point is the parent of the transition source.
The resolution process searches each level of the chart hierarchy for a path to the data. If
a data object matches the path, the process adds that data object to the list of possible
matches. Then, the process continues the search one level higher in the hierarchy. The
resolution process stops after it searches the chart level of the hierarchy. If a unique
9-50
Identify Data by Using Dot Notation
match exists, the qualified data name resolves to the matching path. Otherwise, the
resolution process fails. Simulation stops, and you see an error message.
This flow chart illustrates the different stages in the process for resolving qualified data
names.
9-51
9 Define Data
To improve the chances of finding a unique search result when resolving qualified data
names:
In this chart, the entry action in state b contains the qualified data name aa.data. If the
symbol data resides in state aa, then Stateflow cannot resolve the qualified data name.
This table lists the different stages in the resolution process for the qualified data name
aa.data.
The search ends at the chart level with no match found for aa.data, resulting in an error.
To avoid this error, in the entry action of state b, specify the data with the more specific
qualified data name a.aa.data.
9-52
Identify Data by Using Dot Notation
In this chart, the entry action in state a contains two instances of the qualified data name
aa.data. If both states named aa contain a data object named data, then Stateflow
cannot resolve the qualified data name.
This table lists the different stages in the resolution process for the qualified data name
aa.data.
The search ends at the chart level with two matches found for aa.data, resulting in an
error.
• To specify the data object in the substate of state a, use the qualified data name
a.aa.data.
• To specify the data object in the top-level state aa, use the qualified data name /
aa.data.
• Rename one of the states containing data.
• Enclose the top-level state aa in a box or in another state. Adding an enclosure
prevents the search process from detecting data in the top-level state.
9-53
9 Define Data
See Also
More About
• “State Action Types” on page 12-2
• “Transition Action Types” on page 12-7
• “State Hierarchy” on page 2-14
9-54
Resolve Data Properties from Simulink Signal Objects
For information about Simulink® signal resolution, see “Symbol Resolution” (Simulink)
and “Symbol Resolution Process” (Simulink).
Inherited Properties
When Stateflow local or output data resolve to Simulink signal objects, they inherit these
properties:
• Size
• Complexity
• Type
• Minimum value
• Maximum value
• Initial value
• Storage class
Storage class controls the appearance of chart data in the generated code. See “Apply
Custom Storage Classes to Individual Signal, State, and Parameter Data Elements”
(Embedded Coder).
1 Set Configuration Parameters > Diagnostics > Data Validity > Signal
resolution to a value other than None. For more information about the other options,
see “Signal resolution” (Simulink).
2 In the model workspace, base workspace, or data dictionary, define a
Simulink.Signal object with the properties you want your Stateflow data to
inherit. For more information about creating Simulink signals, see
Simulink.Signal.
9-55
9 Define Data
A Simple Example
This model shows how a chart resolves local and output data to Simulink.Signal
objects.
In the base workspace, there are three Simulink.Signal objects, each with a different
set of properties.
9-56
Resolve Data Properties from Simulink Signal Objects
The chart contains three data objects — two outputs and a local variable — that will
resolve to a signal with the same name.
When you build the model, each data object inherits the properties of the identically
named signal.
9-57
9 Define Data
The generated code declares the data based on the storage class that the data inherits
from the associated Simulink signal. For example, the header file below declares local to
be an exported global variable:
/*
* Exported States
*
* Note: Exported states are block states with an exported
* global storage class designation.
*
*/
extern real32_T local; /* '<Root>/Signal Object Chart' */
See Also
Simulink.Signal
More About
• “Symbol Resolution” (Simulink)
• “Apply Custom Storage Classes to Individual Signal, State, and Parameter Data
Elements” (Embedded Coder)
9-58
Transfer Data Across Models
1 In the Contents pane of the Model Explorer, right–click the data object you want to
copy and select Copy from the context menu.
2 In the Model Hierarchy pane, right-click the destination Stateflow machine and
select Paste from the context menu.
9-59
10
Define Events
For simulation purposes, there is no limit to the number of events in a Stateflow chart.
However, for code generation, the underlying C compiler enforces a theoretical limit of
231-1 events.
Types of Events
An implicit event is a built-in event that is broadcasted during chart execution. These
events are implicit because you do not define or trigger them explicitly. For more
information, see “Define Chart Behavior by Using Implicit Events” on page 10-33.
An explicit event is an event that you define explicitly. Explicit events can have one of
these scopes.
Scope Description
Input Event that is broadcast to a Stateflow chart from outside the
chart. For more information, see “Activate a Stateflow Chart by
Sending Input Events” on page 10-9 and “Design Human-
Machine Interface Logic by Using Stateflow Charts” on page 34-
28.
Local Event that can occur anywhere in a Stateflow chart but is visible
only in the parent object and its descendants. Local events are
supported only in Stateflow charts in Simulink models. For more
information, see “Broadcast Local Events to Synchronize Parallel
States” on page 12-45.
Output Event that occurs in a Stateflow chart but is broadcast to a
Simulink block. Output events are supported only in Stateflow
charts in Simulink models. For more information, see “Activate a
Simulink Block by Sending Output Events” on page 10-21.
You can define explicit events at these levels of the Stateflow hierarchy.
10-2
Synchronize Model Components by Broadcasting Events
• Input Event
• Local Event
• Output Event
4 Edit the name of the event.
5 For input and output events, click the PORT field and choose a port number.
6 To specify properties for the event, open the Property Inspector. In the Symbols
window, right-click the row for the event and select Explore. For more information,
see “Set Properties for an Event” on page 10-6.
1 In a Stateflow chart in a Simulink model, select the menu option corresponding to the
scope of the event that you want to add.
10-3
10 Define Events
To broadcast explicit events in state or transition actions, use the send command. Using
this command enhances readability of a chart and ensures that explicit events are not
mistaken for data. For more information, see “Broadcast Local Events to Synchronize
Parallel States” on page 12-45.
10-4
See Also
To check state activity, use the in operator instead of the implicit event enter. For more
information, see “Check State Activity by Using the in Operator” on page 12-77.
Mixing input events that use edge triggers and function calls results in an error during
parsing and simulation.
See Also
More About
• “Set Properties for an Event” on page 10-6
• “Broadcast Local Events to Synchronize Parallel States” on page 12-45
• “Activate a Stateflow Chart by Sending Input Events” on page 10-9
• “Activate a Simulink Block by Sending Output Events” on page 10-21
• “Rules for Naming Stateflow Objects” on page 2-4
• “Identify Data by Using Dot Notation” on page 9-50
10-5
10 Define Events
• Property Inspector
Name of the event. Actions reference events by their names. Names must begin with an
alphabetic character, cannot include spaces, and cannot be shared by sibling events. For
more information, see “Rules for Naming Stateflow Objects” on page 2-4.
Scope
Scope of the event. The scope specifies where the event occurs relative to the parent
object.
Scope Description
Local Event that can occur anywhere in a Stateflow machine but is
visible only in the parent object and its descendants. For more
information, see “Directed Event Broadcasting” on page 12-45.
10-6
Set Properties for an Event
Scope Description
Input from Event that occurs in a Simulink block but is broadcast to a
Simulink Stateflow chart. For more information, see “Activate a Stateflow
Chart by Sending Input Events” on page 10-9.
Output to Event that occurs in a Stateflow chart but is broadcast to a
Simulink Simulink block. For more information, see “Activate a Simulink
Block by Sending Output Events” on page 10-21.
Port
Index of the port associated with the event. This property applies only to input and output
events.
• For input events, port is the index of the input signal that triggers the event. For more
information, see “Association of Input Events with Control Signals” on page 10-12.
• For output events, port is the index of the signal that outputs this event. For more
information, see “Association of Output Events with Output Ports” on page 10-31.
Trigger
Type of signal that triggers an input or output event. For more information, see “Activate
a Stateflow Chart by Sending Input Events” on page 10-9 and “Activate a Simulink
Block by Sending Output Events” on page 10-21.
Debugger Breakpoints
Option for setting debugger breakpoints at the start or end of an event broadcast.
Available breakpoints depend on the scope of the event.
For more information, see “Set Breakpoints to Debug Charts” on page 32-5.
Description
Description of the event. You can enter brief descriptions of events in the hierarchy.
10-7
10 Define Events
Document Link
Link to online documentation for the event. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow displays the documentation.
See Also
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Directed Event Broadcasting” on page 12-45
• “Activate a Stateflow Chart by Sending Input Events” on page 10-9
• “Activate a Simulink Block by Sending Output Events” on page 10-21
• “Rules for Naming Stateflow Objects” on page 2-4
• “Identify Data by Using Dot Notation” on page 9-50
10-8
Activate a Stateflow Chart by Sending Input Events
• To specify an edge-triggered input event, set the Trigger property to one of these
options:
• Rising
• Falling
• Either
• To specify a function-call input event, set the Trigger property to Function
call.
You cannot mix edge-triggered and function-call input events in the same Stateflow
chart. Mixing these input events results in an error during parsing and simulation.
10-9
10 Define Events
In all cases, the value of the control signal must cross zero to be a valid edge trigger. For
example, a signal that changes from -1 to 1 is a valid rising edge trigger. A signal that
changes from 1 to 2 is not a valid rising edge trigger.
Use an edge-triggered input event to activate a chart when your model requires regular
or periodic chart execution. For example, in the model sf_loop_scheduler, an edge-
triggered input event activates the Edge to Function chart at regular intervals. For more
information, see “Schedule A Subsystem Multiple Times in a Single Step” on page 26-18.
10-10
Activate a Stateflow Chart by Sending Input Events
At any given time step, input events are checked in ascending order based on their port
numbers. The chart awakens once for each valid event. For edge-triggered input events,
multiple edges can occur in the same time step, waking the chart more than once in that
time step. In this situation, the events wake the chart in ascending order based on their
port numbers.
10-11
10 Define Events
Use a function-call input event to activate a chart when your model requires access to
output data from the chart in the same time step as the function call. For example, in the
model sf_loop_scheduler, a function-call input event activates the Looping Scheduler
chart. For more information, see “Schedule A Subsystem Multiple Times in a Single Step”
on page 26-18.
For function-call input events, only one trigger event exists. The caller of the event
explicitly calls and executes the chart. Only one function call is valid in a single time step.
By default, Port values appear in the order that you add input events. You can change
these assignments by modifying the Port property of the events. When you change the
Port property for an input event, the Port values for the remaining input events
automatically renumber.
10-12
See Also
You cannot mux two input signals of different data types, such as boolean and double.
See Also
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Set Properties for an Event” on page 10-6
• “Control States in Charts Enabled by Function-Call Input Events” on page 10-14
• “Schedule A Subsystem Multiple Times in a Single Step” on page 26-18
• “View Differences Between Stateflow Messages, Events, and Data” on page 11-2
10-13
10 Define Events
Setting Description
Held Maintain most recent values of the states.
Reset Revert to the initial values of the states.
Inherit Inherit setting from the parent subsystem.
For new charts, the default setting is Held. For more information, see “Activate a
Stateflow Chart by Sending Input Events” on page 10-9.
10-14
Control States in Charts Enabled by Function-Call Input Events
Each time that the Callee chart executes, the output data y increments by one.
10-15
10 Define Events
In the Chart properties dialog box for Callee, States When Enabling is Inherit.
Because the parent of this chart is the model root, the behavior is the same as when
States When Enabling is Held. During simulation, the output y maintains its most
recent value when the function-call input event reenables the chart at t = 20 and t = 40.
Suppose that you change the States When Enabling property for Callee to Reset.
During simulation, y reverts to its initial value of zero when the function-call input event
reenables the chart at t = 20 and t = 40.
10-16
Control States in Charts Enabled by Function-Call Input Events
In the Model block, the Caller chart uses the event E to wake up and execute the
Callee chart, as in the previous example.
10-17
10 Define Events
In the Chart properties dialog box for Callee, States When Enabling is Inherit.
Because this chart is inside a Model block, the behavior is the same as when States
When Enabling is Reset. During simulation, the output y reverts to its initial value of
zero when the function-call input event reenables the chart at t = 20 and t = 40.
10-18
Control States in Charts Enabled by Function-Call Input Events
Suppose that you change the States When Enabling property for Callee to Held.
During simulation, y maintains its most recent value when the function-call input event
reenables the chart at t = 20 and t = 40.
10-19
10 Define Events
See Also
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Activate a Stateflow Chart by Sending Input Events” on page 10-9
• “Model References” (Simulink)
10-20
Activate a Simulink Block by Sending Output Events
10-21
10 Define Events
The chart contains the edge-triggered output event e1 which alternates between 0 and 1
during simulation.
• The output event triggers the Either edge subsystem on every broadcast. The trigger
occurs when the event signal switches from 0 to 1 or from 1 to 0.
• The output event triggers the Rising edge subsystem on every other broadcast. The
trigger occurs only when the event signal switches from 0 to 1.
10-22
Activate a Simulink Block by Sending Output Events
A chart dispatches only one broadcast of an edge-triggered output event for each time
step. When there are multiple broadcasts in a single time step, the chart dispatches one
broadcast and queues up the remaining broadcasts for dispatch in successive time steps.
For example, in this model, the Caller chart uses the edge-triggered output event
output_cmd to activate the Callee chart.
10-23
10 Define Events
The Caller chart tries to broadcast the same edge-triggered output event four times in a
single time step.
Each time the Callee chart is activated, the output data y increments by one.
When you simulate the model, at time t = 1, the Caller chart dispatches one of the four
output events. The Callee chart executes once during that time step. The Caller chart
queues up the other three event broadcasts for future dispatch at a time t = 2, t = 3, and
t = 4. As a result, the value of y grows in increments of one at time t = 1, t = 2, t = 3, and
t = 4.
10-24
Activate a Simulink Block by Sending Output Events
Use a function-call output event to activate a Simulink block when your model requires
access to output data from the block in the same time step as the function call. For
example, the model sf_loop_scheduler contains two function-call output events:
• In the Edge to Function chart, the output event call activates the Looping Scheduler
chart.
• In the Looping Scheduler chart, the output event A1 activates a Simulink subsystem.
For more information, see “Schedule A Subsystem Multiple Times in a Single Step” on
page 26-18.
10-25
10 Define Events
When there are multiple broadcasts of a function-call output event in a single time step,
the chart dispatches all the broadcasts in that time step. Execution of function-call
subsystems is interleaved with the execution of the chart, so that output from the
function-call subsystem is available immediately in the chart. For example, in this model,
the Caller chart uses the function-call output event output_cmd to activate the Callee
chart.
10-26
Activate a Simulink Block by Sending Output Events
The Caller chart tries to broadcast the same function-call output event four times in a
single time step.
Each time the Callee chart is activated, the output data y increments by one.
When you simulate the model, the Caller chart dispatches all four output events at time t
= 1. The Callee chart executes four times during that time step. Execution of the Callee
chart is interleaved with execution of the Caller chart so that output from the Callee chart
is immediately available. As a result, the value of | y | increases from 0 to 4 at time t = 1.
10-27
10 Define Events
For example, in this model, the edge-triggered output event output_cmd activates the
enabled subsystem.
10-28
Activate a Simulink Block by Sending Output Events
The Caller chart broadcasts the edge-triggered output event by using the send operator.
When simulation starts, the value of the trigger signal is 0. At time t = 20, the chart
dispatches output_cmd, changing the value of the trigger signal to 1. The enabled
subsystem becomes active and executes during that time step. Because no other event
broadcasts occur, the enabled subsystem continues to execute at every time step until
simulation ends at t= 40. The Display block shows a final value of 40.
10-29
10 Define Events
To approximate a function call, add a second event broadcast in the same action.
When simulation starts, the value of the trigger signal is 0. At time t = 20, the chart
dispatches output_cmd, changing the value of the trigger signal to 1. The enabled
subsystem becomes active and executes during that time step. The chart queues up the
second event for dispatch at the next time step. At time t= 21, the chart dispatches the
10-30
Activate a Simulink Block by Sending Output Events
second output event, which changes the value of the trigger signal back to 0. The enabled
subsystem stops executing and the Display block shows a final value of 20.
Although you can approximate a function call, there is a subtle difference in execution
behavior. Execution of a function-call subsystem occurs during execution of the chart
action that provides the trigger. Execution of an enabled subsystem occurs after
execution of the chart action is complete.
By default, Port values appear in the order in which you add output events. You can
change these assignments by modifying the Port property of the events. When you
change the Port property for an output event, the Port values for the remaining output
events automatically renumber.
10-31
10 Define Events
See Also
send
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Set Properties for an Event” on page 10-6
• “Schedule A Subsystem Multiple Times in a Single Step” on page 26-18
• “View Differences Between Stateflow Messages, Events, and Data” on page 11-2
• “Using Triggered Subsystems” (Simulink)
• “Using Function-Call Subsystems” (Simulink)
10-32
Define Chart Behavior by Using Implicit Events
• Chart waking up
• Entry into a state
• Exit from a state
• Value assigned to an internal data object
These events are implicit because you do not define or trigger them explicitly. Implicit
events are children of the chart in which they occur and are visible only in the parent
chart.
event(object)
where event is the name of the implicit event and object is the state or data in which
the event occurs.
Each keyword below generates implicit events in the action language notation for states
and transitions.
10-33
10 Define Events
If more than one object has the same name, use the dot operator to qualify the name of
the object with the name of its parent. These examples are valid references to implicit
events:
enter(switch_on)
en(switch_on)
change(engine.rpm)
Note The tick (or wakeup) event refers to the chart containing the action being
evaluated. The event cannot refer to a different chart by argument.
10-34
Define Chart Behavior by Using Implicit Events
Fan and Heater are parallel (AND) superstates. The first time that an event awakens the
Stateflow chart, the states Fan.Off and Heater.Off become active.
Assume that you are running a discrete-time simulation. Each time that the chart
awakens, a tick event broadcast occurs. After four broadcasts, the transition from
Fan.Off to Fan.On occurs. Similarly, after three broadcasts, the transition from
Heater.Off to Heater.On occurs.
For information about the after operator, see “Control Chart Execution by Using
Temporal Logic” on page 12-49.
When multiple transitions are valid in the same time step, the transitions execute based
on the order in which they were created in the chart. This order does not necessarily
match the activation order of the parallel states that contain the transitions. For example,
consider the following chart:
10-35
10 Define Events
When the transition from IV.HERE to IV.THERE occurs, the condition ex(IV.HERE) is
valid for the transitions from A to B for the parallel states I, II, and III. The three
transitions from A to B execute in the order in which they were created: in state I, then II,
and finally III. This order does not match the activation order of those states.
To ensure that valid transitions execute in the same order that the parallel states become
active, use the in operator instead of implicit enter or exit events:
10-36
Define Chart Behavior by Using Implicit Events
With this modification, the transitions from A to B occur in the same order as activation of
the parallel states. For more information about the in operator, see “Check State Activity
by Using the in Operator” on page 12-77.
10-37
10 Define Events
The chart awakens and remains in the Observe state, until the input data u is positive.
Then, the transition to the state Collect_Data occurs.
10-38
Count Events by Using the temporalCount Operator
After the state Collect_Data becomes active, the value of the input data u is assigned
to the first element of the vector y. While this state is active, each subsequent value of u
is assigned to successive elements of y using the temporalCount operator.
After 10 ticks, the data collection process ends, and the transition to the state Observe
occurs. Just before the state Collect_Data becomes inactive, a function call to status
displays the vector data at the MATLAB prompt.
For more information about ticks in a Stateflow chart, see “Define Chart Behavior by
Using Implicit Events” on page 10-33.
10-39
11
Messages
• “View Differences Between Stateflow Messages, Events, and Data” on page 11-2
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
• “Set Properties for a Message” on page 11-14
• “Control Message Activity in Stateflow Charts” on page 11-18
• “Use the Sequence Viewer Block to Visualize Messages, Events, and Entities”
on page 11-28
11 Messages
Sender Charts
This model has three sender charts: DataSender, EventSender, and MessageSender.
Each sender chart has one state. In the entry action of the state, the charts assign a value
to data, send a function-call event, or send a message.
11-2
View Differences Between Stateflow Messages, Events, and Data
Receiver Charts
For each of the sender charts, there is a corresponding receiver chart. Each receiver
chart has a state diagram with states A0, A1, A2, and A3. The implicit event
after(3,sec) triggers the transition from A0 to A1. The data, event, or message from
the corresponding sender chart guards the transitions between A1, A2, and A3.
11-3
11 Messages
Scope Output
Each receiver chart has active state output enabled and connected to a scope. The scope
shows which states are active in each time step. This output highlights the difference in
behavior between output data, events, and messages.
11-4
View Differences Between Stateflow Messages, Events, and Data
11-5
11 Messages
Behavior of Data
The DataSender chart assigns a value of 1 to the output data M, which connects as an
input to the DataReceiver chart.
The DataReceiver chart executes once at every time step. At the start of simulation,
state A0 is active. At time t=3, the transition from A0 to A1 occurs. At time t=4, the chart
tests whether M equals 1. This condition is true, so the chart transitions from A1 to A2. At
time t=5, M still equals 1, so the chart transitions from A2 to A3. On the scope, you see
that DataReceiver changes states three times.
After data is assigned a value, it holds its value throughout the simulation. Therefore,
each time that the DataReceiver evaluates the condition [M == 1], it transitions to a
new state.
11-6
View Differences Between Stateflow Messages, Events, and Data
Behavior of Event
The EventSender chart uses the command send(M) to send a function-call output event
to wake up the EventReceiver chart.
The EventReceiver chart executes only when the input event M wakes up the chart. At
the start of simulation, state A0 is active. The transition from A0 to A1 is based on
absolute-time temporal logic and is not valid at time t=0. A0 remains active and the chart
goes back to sleep. Because EventSender sends the event M only once, EventReceiver
does not wake up again. On the scope, you see that EventReceiver never transitions out
of A0.
Events do not remain valid across time steps, so the receiving chart has only one chance
to respond to the event. When EventSender sends the event, EventReceiver is not
ready to respond to it. The opportunity for EventReceiver to transition in response to
the event is lost.
11-7
11 Messages
Behavior of Message
The MessageSender chart uses the syntax send(M) to send a message through the
output message port. The message goes into the input message queue of the
MessageReceiver chart. The message waits in the queue until MessageReceiver
evaluates it.
The MessageReceiver chart executes once at every time step. At the start of simulation,
state A0 is active. At time t=3, the transition from A0 to A1 occurs. At time t=4, the chart
determines that M is present in the queue, so it takes the transition to A2. At the end of
the time step, the chart removes M from the queue. At time t=5, there is no message
present in the queue, so the chart does not transition to A3. A2 remains the active state.
On the scope, you see that MessageReceiver changes state only two times.
11-8
See Also
Unlike events, messages are queued. The receiving chart can choose to respond to a
message anytime after it was sent. Unlike data, the message does not remain valid
indefinitely. The message is destroyed at the end of the time step.
See Also
More About
• “Share Data with Simulink and the MATLAB Workspace” on page 9-23
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
11-9
11 Messages
Messages are queued until the chart wakes up. When the chart wakes up, it can respond
to the messages in the queue.
When a chart transition or state action evaluates the message, the chart determines if the
queue contains any messages. If it does, the chart removes the message from the queue.
The message remains valid until the end of the time step or until the chart forwards or
discards it. While the message is valid, other transitions or actions can access the
message data and the chart does not remove another message from the queue. The chart
destroys all valid messages at the end of the current time step.
11-10
Communicate with Stateflow Charts by Sending Messages
1 In the Stateflow Editor, select the menu option corresponding to the scope of the
message that you want to add.
• Input Message
• Local Message
• Output Message
4 Edit the name of the message.
5 For input and output messages, click the PORT field and choose a port number.
6 To specify properties for the message, open the Property Inspector. In the Symbols
window, right-click the row for the message and select Explore. For more
information, see “Set Properties for a Message” on page 11-14.
11-11
11 Messages
3 In the Model Explorer menu, select Add > Message. The new message with a default
definition appears in the Contents pane of the Model Explorer.
4 In the Message pane, specify the properties of the message. For more information,
see “Set Properties for a Message” on page 11-14.
A message becomes valid when a chart evaluates or receives it. The message remains
valid until:
• The end of the current time step, when the chart destroys any remaining valid
messages.
• The chart forwards the message to another queue. The message continues its lifetime
in the receiving queue.
• The chart discards the message.
While a message is valid, other transitions and actions can evaluate the message and
access its data. To check if a message is valid, use the isvalid operator.
To view the interchange of messages during simulation, add a Sequence Viewer block to
your Simulink model. The Sequence Viewer block displays:
• Sent messages
• Received messages
• Forwarded messages
• Dropped messages
• Destroyed messages
• Discarded messages
For more information, see “Use the Sequence Viewer Block to Visualize Messages,
Events, and Entities” on page 11-28.
11-12
See Also
• Moore charts
• Atomic subcharts
• Breakpoint condition expressions
• Model reference inputs and outputs
See Also
Related Examples
• “View Differences Between Stateflow Messages, Events, and Data” on page 11-2
More About
• “Set Properties for a Message” on page 11-14
• “Control Message Activity in Stateflow Charts” on page 11-18
• “Send Messages with String Data” on page 20-14
• “Use the Sequence Viewer Block to Visualize Messages, Events, and Entities” on
page 11-28
11-13
11 Messages
You can specify message properties in either the Property Inspector or the Model
Explorer.
• Property Inspector
For more information, see “Communicate with Stateflow Charts by Sending Messages” on
page 11-10.
Name of the message. For more information, see “Rules for Naming Stateflow Objects” on
page 2-4.
Scope
Scope of the message. The scope specifies where the message occurs relative to the
parent object.
11-14
Set Properties for a Message
Scope Description
Input from Message that is received from another Stateflow chart. Each
Simulink input message has a receiving queue.
Output to Message that is sent through an output port to another
Simulink Stateflow chart.
Local Message that is local to the Stateflow chart. A local message has
a receiving queue with the same properties as an input message
queue. When you send a local message, a transition or action in
the same chart can evaluate the local message. You cannot send
a local message outside the chart.
Port
Index of the port associated with the message. This property applies only to input and
output messages.
Size
Size of the message data field. For more information, see “Specify Size of Stateflow Data”
on page 9-40.
Complexity
The default value is Off. For more information, see “Complex Data in Stateflow Charts”
on page 23-2.
Type
11-15
11 Messages
Enables watching the message queue and data field in the Stateflow Breakpoints and
Watch window. For more information, see “Watch Stateflow Data Values” on page 32-36.
Queue Capacity
For input and local messages, specifies the maximum number of messages held in the
queue. If a chart sends a message when the receiving queue is full, a message overflow
occurs. To avoid dropped messages, set the queue capacity high enough so incoming
messages do not cause the queue to overflow. The maximum queue length is 216–1.
Specifies the diagnostic action when the number of incoming messages exceeds the
queue capacity. The default option is Error.
Queue Type
Specifies the order in which messages are removed from the queue. The default option is
FIFO.
11-16
See Also
See Also
More About
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
• “Control Message Activity in Stateflow Charts” on page 11-18
• “Rules for Naming Stateflow Objects” on page 2-4
• “Specify Size of Stateflow Data” on page 9-40
• “Specify Type of Stateflow Data” on page 9-33
• “Complex Data in Stateflow Charts” on page 23-2
• “Watch Stateflow Data Values” on page 32-36
11-17
11 Messages
Using Stateflow operators, you can access message data, and send, receive, discard, or
forward a message. You can also determine whether a message is valid and find the
number of messages in a queue. For more information, see “Communicate with Stateflow
Charts by Sending Messages” on page 11-10.
message_name.data
If you send a message without first assigning a value to the message data, the default
value for numeric data is 0. For enumerated data, the default is the first value listed in the
enumeration section of the definition, unless you specify otherwise in the methods
section of the definition.
You cannot access message data for messages that are still in the queue or that have
already been discarded.
Send a Message
To send a message, use the send operator:
11-18
Control Message Activity in Stateflow Charts
send(message_name)
For example, in this chart, the entry action in state A sends a message M with a data value
of 3. If the message is Local, then the message goes in the local message queue. If the
message scope is Output, then the chart sends the message through the output port to
the input message queue of the receiving chart.
In a single time step, you can send multiple messages through an output port or to a local
queue.
In this chart, a message M guards the transition from state A to state B. The transition
occurs when both of these conditions are true:
If a message is not present or if the data value is not equal to 3, then the transition does
not occur. If a message is present, it is removed from the queue regardless of whether the
transition occurs.
11-19
11 Messages
In this chart, a message M guards the on action in state A. When state A becomes active, it
increments the value of x if both of these conditions are true:
If a message is not present or if the data value is not equal to 3, then the value of x does
not change. If a message is present, it is removed from the queue regardless of whether x
is modified.
Receive a Message
To receive a message, use the receive operator:
receive(message_name)
If a valid message M exists, receive(M) returns true. If a valid message does not exist
but there is a message in the queue, then the chart removes the message from the queue
and receive(M) returns true. If a valid message does not exist and there are no
messages in the queue, receive(M) returns false.
For example, in this chart, the during action in state A checks the queue for message M
and increments the value of x if both of these conditions are true:
11-20
Control Message Activity in Stateflow Charts
If a message is not present or if the data value is not equal to 3, then the value of x does
not change. If a message is present, it is removed from the queue regardless of whether x
is modified.
Discard a Message
To discard a valid message, use the discard operator:
discard(message_name)
After a chart discards a message, it can remove another message from the queue in the
same time step. A chart cannot access the data of a discarded message.
For example, in this chart, the during action in state A checks the queue for message M.
If a message is present, the chart removes it from the queue. If the message has a data
value equal to 3, the chart discards the message.
11-21
11 Messages
Forward a Message
To forward a message from an input queue to an output port, or to and from local
message queues, use the forward operator:
forward(input_message_name, output_message_name)
After a chart forwards a message, it can remove another message from the queue in the
same time step.
In this chart, state A checks the input queue for message M_in. If a message is present,
the chart removes the message from the queue and forwards it to the output port M_out.
After the chart forwards the message, the message is no longer valid in state A.
In this chart, state A checks the input queue for message M_in. If a message is present,
the chart forwards the message to the local message queue M_local. After a delay of 0.3
seconds, the transition from state A to state B removes the message from the M_local
message queue and forwards it to the output port M_out.
11-22
Control Message Activity in Stateflow Charts
isvalid(message_name)
A message is valid if the chart has removed it from the queue and has not forwarded or
discarded it. Use the isvalid operator to check if a message is valid in a Simulink model
that contains more than one Stateflow chart.
For example, this chart first executes state A, as described in “Discard a Message” on
page 11-21. When the chart executes state B, the during action checks whether the
message M is valid. If the message is valid and has a data value equal to 6, the chart
discards the message.
11-23
11 Messages
length(message_name)
For example, in this chart, the during action in state A checks the queue for message M.
If a message is present, the chart removes it from the queue. If exactly seven messages
remain in the queue, the chart increments the value of x.
overflowed(message_name)
In each time step, the value of this operator is set when a chart adds a message to, or
removes a message from, a queue. It is invalid to use the overflowed operator before
sending or retrieving a message in the same time step.
By default, when a message queue overflows, simulation stops with an error. To prevent a
run-time error and allow the overflowed operator to dynamically react to dropped
messages, set the value of the Queue Overflow Diagnostic property to Warning or
None. For more information, see “Queue Overflow Diagnostic” on page 11-16.
To check the overflow status of an input message queue, first remove a message from the
queue. You can:
11-24
Control Message Activity in Stateflow Charts
• Guard a transition with the message and call the overflowed operator in the entry
action of the destination state.
• Guard a state on action with the message and call the overflowed operator in the
action.
• In a state action, use the receive operator followed by the overflowed operator.
11-25
11 Messages
Calling the overflowed operator before retrieving an input message in the same time
step results in a run-time error.
To check the overflow status of an output message queue, first add a message to the
queue. You can:
11-26
See Also
Calling the overflowed operator before sending or forwarding an output message in the
same time step results in a run-time error.
To check the overflow status of a local message queue, either add a message to the queue
or remove a message from the queue before calling the overflowed operator. Calling the
overflowed operator before sending or retrieving a local message in the same time step
results in a run-time error.
See Also
discard | forward | isvalid | length | overflowed | receive | send
More About
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
• “Set Properties for a Message” on page 11-14
• “Rules for Naming Stateflow Objects” on page 2-4
• “Specify Size of Stateflow Data” on page 9-40
• “Specify Type of Stateflow Data” on page 9-33
• “Complex Data in Stateflow Charts” on page 23-2
• “Watch Stateflow Data Values” on page 32-36
11-27
11 Messages
In the Sequence Viewer block, you can view event data related to Stateflow chart
execution and the exchange of messages between Stateflow charts. The Sequence Viewer
window shows messages as they are created, sent, forwarded, received, and destroyed at
different times during model execution. The Sequence Viewer window also displays state
activity, transitions, and function calls to Stateflow graphical functions, Simulink
functions, and MATLAB functions.
With the Sequence Viewer block, you can visualize the movement of entities between
blocks when simulating SimEvents models. All SimEvents blocks that can store entities
appear as lifelines in the Sequence Viewer window. Entities moving between these blocks
appear as lines with arrows. You can view calls to Simulink Function blocks and to
MATLABFunction blocks.
You can add a Sequence Viewer block to the top level of a model or any subsystem. If you
place a Sequence Viewer block in a subsystem that does not have messages, events, or
state activity, the Sequence Viewer window informs you that there is nothing to display.
For instance, suppose that you simulate the Stateflow example sf_msg_traffic_light.
11-28
Use the Sequence Viewer Block to Visualize Messages, Events, and Entities
This model has three Simulink subsystems: Traffic Light 1, Traffic Light 2, and GUI. The
Stateflow charts in these subsystems exchange data by sending messages. As messages
pass through the system, you can view them in the Sequence Viewer window. The
Sequence Viewer window represents each block in the model as a vertical lifeline with
simulation time progressing downward.
11-29
11 Messages
At the top of the Sequence Viewer window, a navigation toolbar displays the model
hierarchy path. Using the toolbar buttons, you can:
•
Show or hide the Property Inspector.
•
Select an automatic or manual layout.
•
Show or hide inactive lifelines.
•
Save Sequence Viewer block settings.
11-30
Use the Sequence Viewer Block to Visualize Messages, Events, and Entities
•
Restore Sequence Viewer block settings.
•
Configure Sequence Viewer block parameters.
•
Access the Sequence Viewer block documentation.
Property Inspector
• Events
• Messages
• Function Calls
• State Changes and Transitions
Header Pane
The header pane below the Sequence Viewer toolbar shows lifeline headers containing
the names of the corresponding blocks in a model.
To open a block in the model, click the name in the corresponding lifeline header. To show
or hide a lifeline, double-click the corresponding header. To resize a lifeline header, click
and drag its right-hand side. To fit all lifeline headers in the Sequence Viewer window,
press the space bar.
Message Pane
Below the header pane is the message pane. The message pane displays messages,
events, and function calls between lifelines as arrows from the sender to the receiver. To
display sender, receiver, and payload information in the Property Inspector, click the
arrow corresponding to the message, event, or function call.
11-31
11 Messages
In the message pane, a thick, gray lifeline indicates that you can expand the lifeline to see
its children. To show the children of a lifeline, click the expander icon below the
header or double-click the parent lifeline.
For example, expanding the lifeline for the Traffic Light 1 block reveals two new lifelines
corresponding to the Stateflow charts Ped Button Sensor and Controller.
11-32
Use the Sequence Viewer Block to Visualize Messages, Events, and Entities
The Sequence Viewer window displays masked subsystems as white blocks. To show the
children of a masked subsystem, point over the bottom left corner of the lifeline header
and click the arrow.
For example, the GUI subsystem contains four masked subsystems: Traffic Lamp 1,Traffic
Lamp 2, Ped Lamp 1, and Ped Lamp 2.
11-33
11 Messages
You can display the child lifelines in these masked subsystems by clicking the arrow in the
parent lifeline header.
To make a lifeline the root of focus for the viewer, point over the bottom left corner of the
lifeline header and click the arrow. Alternatively, you can use the navigation toolbar at the
top of the Sequence Viewer window to move the current root up and down the lifeline
hierarchy. To move the current root up one level, press the Esc key.
The Sequence Viewer window displays the current root lifeline path and shows its child
lifelines. Any external events and messages are displayed as entering or exiting through
vertical slots in the diagram gutter. When you point to a slot in the diagram gutter, a
tooltip displays the name of the sending or receiving block.
11-34
Use the Sequence Viewer Block to Visualize Messages, Events, and Entities
In this example, you can see a transition from Go to PrepareToStop followed, after 1
second, by a transition to Stop.
11-35
11 Messages
To display the start state, end state, and full transition label in the Property Inspector,
click the arrow corresponding to the transition.
To display information about the interactions that occur while a state is active, click the
yellow bar corresponding to the state. In the Property Inspector, use the Search Up and
Search Down buttons to move through the transitions, messages, events, and function
calls that take place while the state is active.
11-36
Use the Sequence Viewer Block to Visualize Messages, Events, and Entities
The Sequence Viewer window displays function calls as solid arrows labeled with the
format function_name(argument_list). Replies to function calls are displayed as
dashed arrows labeled with the format [argument_list]=function_name.
11-37
11 Messages
time by using a combination of linear and nonlinear displays. The time ruler shows linear
simulation time. The time grid shows time in a nonlinear fashion. Each time grid row,
bordered by two blue lines, contains events that occur at the same simulation time. The
time strip provides the times of the events in that grid row.
Time grid
Time strip
Time ruler
Time slider
To show events in a specific simulation time range, use the scroll wheel or drag the time
slider up and down the time ruler. To navigate to the beginning or end of the simulation,
click the Go to first event or Go to last event buttons. To see the entire simulation
duration on the time ruler, click the Fit to view button .
When using a variable step solver, you can adjust the precision of the time ruler. In the
Model Explorer, on the Main tab of the Sequence Viewer Block Parameters pane, adjust
the value of the Time Precision for Variable Step field.
lifeline state. To save a particular viewer state, click the Save Settings button in the
toolbar. Saving the model then saves that state information across sessions. To load the
11-38
See Also
You can modify the Time Precision for Variable Step and History parameters only
between simulations. You can access the buttons in the toolbar before simulation or when
the simulation is paused. During a simulation, the buttons in the toolbar are disabled.
See Also
Sequence Viewer
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
11-39
12
name/
entry:entry actions
during:during actions
exit:exit actions
bind:data_name, event_name
on event_name:on event_name actions
on message_name:on message_name actions
Enter actions of different types on separate lines after the name of the state. You can
enter these actions in any order. If you do not specify the action type explicitly for a
statement, the chart treats that statement as a combined entry,during action.
12-2
State Action Types
For more information about the after, before, at, and every temporal logic operators,
see “Control Chart Execution by Using Temporal Logic” on page 12-49.
Note You can call the temporal logic operators after and before by using the absolute-
time keywords sec, msec, and usec. For details, see “Operators for Absolute-Time
Temporal Logic” on page 12-56.
12-3
12 Use Actions in Charts
entry Actions
Entry actions are executed when a state becomes active. Entry actions consist of the
prefix entry (or the abbreviation en) followed by a colon (:) and one or more actions. To
separate multiple entry actions, use semicolons or commas. You can also enter the actions
on separate lines.
In the preceding example, the entry action id = x+y executes when the chart takes the
default transition and state A becomes active. See “Enter a Chart or State” on page 3-50.
exit Actions
Exit actions are executed when a state is active and a transition out of the state occurs.
Exit actions consist of the prefix exit (or the abbreviation ex) followed by a colon (:) and
one or more actions. To separate multiple exit actions, use semicolons or commas. You
can also enter the actions on separate lines.
In the preceding example, the exit action time_out executes when the chart takes one of
the transitions from state A to state B or C. See “Exit a State” on page 3-58.
during Actions
During actions are executed when a state is active, an event occurs, and no valid
transition to another state is available. During actions consist of the prefix during (or the
abbreviation du) followed by a colon (:) and one or more actions. To separate multiple
during actions, use semicolons or commas. You can also enter the actions on separate
lines.
In the preceding example, the during action switch_on() executes whenever the state C
is active because there are no valid transitions to another state. See “Execution of a
Stateflow Chart” on page 3-44.
bind Actions
You can bind the data and events to a state by using a bind action. A bind action consists
of the prefix bind followed by a colon (:) and one or more events or data. To separate
multiple events and data, use semicolons or commas. You can also enter the events and
data on separate lines.
12-4
State Action Types
Only a state and its children can change data or broadcast events bound to that state.
Other states can read the bound data or listen for the bound event, but they cannot
change the bound data or send the bound events.
Bind actions apply to a chart whether the binding state is active or not. In the preceding
example, the bind action bind: id, time_out for state A binds the data id and the
event time_out to state A. This binding prevents any other state (or its children) in the
chart from changing id or broadcasting event time_out.
If another state includes actions that change data or broadcast events that bind to
another state, a parsing error occurs. This chart contains two state actions that produce
parsing errors.
Binding a function-call event to a state also binds the function-call subsystem that it calls.
The function-call subsystem is enabled when the binding state is entered and disabled
when the binding state is exited. For more information about this behavior, see “Control
Function-Call Subsystems by Using bind Actions” on page 12-85.
12-5
12 Use Actions in Charts
on Actions
On actions are executed when the state is active and it receives an event or message. On
actions consist of the prefix on followed by a unique event event_name or message
message_name, a colon (:), and one or more actions. To separate multiple on actions, use
semicolons or commas. You can also enter the actions on separate lines.
You can specify actions for more than one event or message. For example, if you want
different events to trigger different actions, enter multiple on action statements in the
state action label:
on ev1: action1();
on ev2: action2();
If multiple events occur at the same time, the corresponding on actions execute in the
order that they appear in the state action label. For instance, in the previous example, if
events ev1 and ev2 occur at the same time, then action1() executes first and
action2() executes second. See “Execution of a Stateflow Chart” on page 3-44.
See Also
Related Examples
• “Execution of a Stateflow Chart” on page 3-44
• “Enter a Chart or State” on page 3-50
• “Exit a State” on page 3-58
• “Eliminate Redundant Code by Combining State Actions” on page 12-11
• “Control Function-Call Subsystems by Using bind Actions” on page 12-85
• “Operators for Absolute-Time Temporal Logic” on page 12-56
12-6
Transition Action Types
event_or_message trigger[condition]{condition_action}/{transition_action}
12-7
12 Use Actions in Charts
Event triggers specify an event that causes the transition to be taken, provided the
condition, if specified, is true. Specifying an event is optional. Message triggers specify
the transition to be taken if the message is present in the message queue. The absence of
an event or message indicates that the transition is taken upon the occurrence of any
event. Multiple events or messages are specified using the OR logical operator (|).
Conditions
In transition label syntax, conditions are Boolean expressions enclosed in square brackets
([]). In the example in “Transition Action Types” on page 12-7, the transition from state A
to state C has the condition temp > 50.
A condition is a Boolean expression to specify that a transition occurs given that the
specified expression is true. Follow these guidelines for defining and using conditions:
• The condition expression must be a Boolean expression that evaluates to true (1) or
false (0).
• The condition expression can consist of any of the following:
• Boolean operators that make comparisons between data and numeric values
• A function that returns a Boolean value
• An in(state_name) condition that evaluates to true when the state specified as
the argument is active (see “Check State Activity by Using the in Operator” on
page 12-77)
Note A chart cannot use the in condition to trigger actions based on the activity
of states in other charts.
• Temporal logic conditions (see “Control Chart Execution by Using Temporal Logic”
on page 12-49)
12-8
Transition Action Types
• The condition expression can call a graphical function, truth table function, or
MATLAB function that returns a numeric value.
Note If the condition expression calls a function with multiple return values, only the
first value applies. The other return values are not used.
• The condition expression should not call a function that causes the chart to change
state or modify any variables.
• Boolean expressions can be grouped using & for expressions with AND relationships
and | for expressions with OR relationships.
• Assignment statements are not valid condition expressions.
• Unary increment and decrement actions are not valid condition expressions.
Condition Actions
In transition label syntax, condition actions follow the transition condition and are
enclosed in curly braces ({}). In the example in “Transition Action Types” on page 12-7,
the transition from state A to state C has the condition action func1(), a function call.
Condition actions are executed as soon as the condition is evaluated as true, but 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.
Transition Actions
In transition label syntax, transition actions are preceded with a forward slash (/) and are
enclosed in curly braces ({}). In the example in “Transition Action Types” on page 12-7,
the transition from state A to state B has the transition action data1 = 5. In C charts,
transition actions are not required to be enclosed in curly braces. In charts that use
MATLAB as the action language, the syntax is auto corrected if the curly braces are
missing from the transition action. See “Auto Correction When Using MATLAB as the
Action Language” on page 13-2.
12-9
12 Use Actions in Charts
Transition actions execute only after the complete transition path is taken. They execute
after the transition destination has been determined to be valid, and the condition, if
specified, is true. If the transition consists of multiple segments, the transition action
executes only after the entire transition path to the final destination is determined to be
valid.
12-10
Eliminate Redundant Code by Combining State Actions
By combining state actions that execute the same tasks, you eliminate redundant code.
For example:
Combining state actions this way produces the same chart execution behavior (semantics)
and generates the same code as the equivalent separate actions.
Valid Combinations
You can use any combination of the three actions. For example, the following
combinations are valid:
• en, du:
• en, ex:
12-11
12 Use Actions in Charts
• du, ex:
• en, du, ex:
You can combine actions in any order in the comma-separated list. For example, en, du:
gives the same result as du, en:.
Invalid Combinations
You cannot combine two or more actions of the same type. For example, the following
combinations are invalid:
• en, en:
• ex, en, ex:
• du, du, ex:
If you combine multiple actions of the same type, you receive a warning that the chart
executes the action only once.
1 Entry actions first, from top to bottom in the order they appear in the state
2 During actions second, from top to bottom
3 Exit actions last, from top to bottom
The order in which you combine actions does not affect state execution behavior. For
example:
12-12
See Also
1 en: y=y+1;
2 en: y = 0;
3 du: y=y+1;
1 en: y=y+1;
2 en: y = 10;
3 du: y=y+1;
4 ex: y = 10;
See Also
More About
• “State Action Types” on page 12-2
12-13
12 Use Actions in Charts
•
MATLAB as the action language.
•
C as the action language.
For more information, see “Differences Between MATLAB and C as Action Language
Syntax” on page 13-6.
Binary Operations
This table summarizes the interpretation of all binary operations in Stateflow charts
according to their order of precedence (0 = highest, 10 = lowest). Binary operations are
left associative so that, in any expression, operators with the same precedence are
evaluated from left to right. The order of evaluation for other operations is unspecified.
For example, in this assignment
the order of evaluation of f() and g() is unspecified. For more predictable results, it is
good coding practice to split expressions that depend on the order of evaluation into
multiple statements.
12-14
Supported Operations for Chart Data
12-15
12 Use Actions in Charts
12-16
Supported Operations for Chart Data
Assignment Operations
This table summarizes the interpretation of assignment operations in Stateflow charts.
12-17
12 Use Actions in Charts
12-18
Supported Operations for Chart Data
For example, the model sf_bus_demo contains a custom C function that takes pointers as
arguments. When the chart calls the custom code function, it uses the & operation to pass
the Stateflow data by address. For more information, see “Integrate Custom Structures in
Stateflow Charts” on page 25-11.
To cast a numeric expression to an explicit data type, use a MATLAB type conversion
function of the form:
<type_fun>(expression)
<type_fun> is a type conversion function that can be double, single, int32, int16,
int8, uint32, uint16, or uint8. In charts that use C as the action language,
<type_fun> can also be boolean. For example, this statement casts the expression x+3
to a 16-bit unsigned integer and assigns its value to the data y:
y = uint16(x+3)
Alternatively, in charts that use MATLAB as the action language, you can use the cast
function with a type keyword <type_key>:
cast(expression,<type_key>)
y = cast(x+3,'uint16')
12-19
12 Use Actions in Charts
To make type casting easier, you can convert the type of a numeric expression based on
the types of other data.
In charts that use MATLAB as the action language, call the cast function with the
keyword 'like'. For example, this statement converts the value of x+3 to the same type
as that of data z and assigns it to y:
y = cast(x+3,'like',z)
In this case, the data z can have any acceptable Stateflow type.
In charts that use C as the action language, the type operator returns the type of an
existing Stateflow data. Use this return value in place of an explicit type in a cast
operation. For example, this statement converts the value of x+3 to the same type as that
of data z and assigns it to y:
cast(x+3,type(z))
Operation entries of the code replacement library can specify integral or fixed-point
operand and result patterns. You can use operation entries for these operations:
• Addition +
• Subtraction -
• Multiplication *
• Division /
For example, in this expression, you can replace the addition operator + with a target-
specific implementation if u1, u2, and y have types that permit a match with an addition
entry in the code replacement library:
y = u1+u2
12-20
See Also
C chart semantics limit operator entry matching because the chart uses the target integer
size as its intermediate type in arithmetic expressions. For example, this arithmetic
expression computes the intermediate addition into a target integer:
y = (u1 + u2) % 3
If the target integer size is 32 bits, then you cannot replace this expression with an
addition operator from the code replacement library and produce a signed 16-bit result
without a loss of precision.
For more information about using code replacement libraries that MathWorks® provides,
see “What Is Code Replacement?” (Simulink Coder) and “Code Replacement Libraries”
(Simulink Coder). For information about developing custom code replacement libraries,
see “What Is Code Replacement Customization?” (Embedded Coder) and “Code You Can
Replace From Simulink Models” (Embedded Coder).
See Also
More About
• “Differences Between MATLAB and C as Action Language Syntax” on page 13-6
• “Specify Properties for Stateflow Charts” on page 24-3
• “Supported Operations for Fixed-Point Data” on page 22-21
12-21
12 Use Actions in Charts
cooling_fan = true;
heating_fan = false;
Tip These symbols are case-sensitive. Therefore, TRUE and FALSE are not Boolean
symbols.
Do not use true and false in the following cases. Otherwise, error messages appear.
• true++;
• false += 3;
• [true, false] = my_function(x);
• Argument of the change implicit event (see “Define Chart Behavior by Using Implicit
Events” on page 10-33)
• change(true);
• chg(false);
• Indexing into a vector or matrix (see “Supported Operations for Vectors and Matrices”
on page 17-11)
• x = true[1];
• y = false[1][1];
Note If you define true and false as Stateflow data objects, your custom definitions of
true and false override the built-in Boolean constants.
12-22
Supported Symbols in Actions
You can also include comments in generated code for an embedded target (see “Model
Configuration Parameters: Code Generation Comments” (Simulink Coder). C chart
comments in generated code use multibyte character code. Therefore, you can have code
comments with characters for non-English alphabets, such as Japanese Kanji characters.
Note If you define inf as a Stateflow data object, your custom definition of inf
overrides the built-in value.
12-23
12 Use Actions in Charts
$
ptr -> field = 1.0;
$
Time Symbol, t
For C charts, use the letter t to represent absolute time that the chart inherits from a
Simulink signal in simulation targets. For example, the condition [t - On_time >
Duration] specifies that the condition is true if the difference between the simulation
time t and On_time is greater than the value of Duration.
The letter t has no meaning for nonsimulation targets, since t depends on the specific
application and target hardware.
Note If you define t as a Stateflow data object, your custom definition of t overrides the
built-in value.
For charts that use MATLAB as the action language the letter t is not a reserved symbol.
To get the simulation time, use the function getSimulationTime().
12-24
Call C Library Functions in C Charts
•
MATLAB as the action language.
•
C as the action language.
abs* **
acos** asin** atan** atan2** ceil**
cos** cosh** exp** fabs floor** fmod**
labs ldexp** log** log10** pow** rand
** ** ** ** **
sin sinh sqrt tan tanh
*
The Stateflow abs function goes beyond that of its standard C counterpart with its own
built-in functionality. See “Call the abs Function” on page 12-26.
**
You can also replace calls to the C Math Library with application-specific
implementations for this subset of functions. For more information, see “Replacement of
Math Library Functions with Application Implementations” on page 12-27.
When you call these math functions, double precision applies unless all the input
arguments are explicitly single precision. When a type mismatch occurs, a cast of the
input arguments to the expected type replace the original arguments. For example, if you
call the sin function with an integer argument, a cast of the input argument to a floating-
point number of type double replaces the original argument.
If you call other C library functions not listed above, include the appropriate
#include... statement in the Simulation Target pane of the Configuration
Parameters.
12-25
12 Use Actions in Charts
If you want to use the abs function in the strict sense of standard C, cast its argument or
return values to integer types. See “Type Cast Operations” on page 12-19.
Note If you declare x in custom code, the standard C abs function applies in all cases.
For instructions on inserting custom code into charts, see “Reuse Custom Code in
Stateflow Charts” on page 30-26.
To allow compatibility with user graphical functions named min() or max(), generated
code uses a mangled name of the following form: <prefix>_min. However, if you export
min() or max() graphical functions to other charts in your model, the name of these
functions can no longer be emitted with mangled names in generated code and conflict
occurs. To avoid this conflict, rename the min() and max() graphical functions.
12-26
Call C Library Functions in C Charts
For more information about replacing code, using code replacement libraries that
MathWorks provides, see “What Is Code Replacement?” (Simulink Coder) and “Code
Replacement Libraries” (Simulink Coder). For information about developing custom code
replacement libraries, see “What Is Code Replacement Customization?” (Embedded
Coder) and “Code You Can Replace From Simulink Models” (Embedded Coder).
12-27
12 Use Actions in Charts
For example, your custom function can include a for-loop that uses sizeof as follows:
for(i=0; i < sizeof(input); i++) {
......
}
• If your custom function uses the value of the input vector length multiple times,
include an input to your function that specifies the input vector length.
For example, you can use input_length as the second input to a sum function as
follows:
int sum(double *input, double input_length)
Your sum function can include a for-loop that iterates over all elements of the input
vector:
for(i=0; i < input_length; i++) {
......
}
12-28
Call C Library Functions in C Charts
Example formats of function calls using transition action notation appear in the following
chart.
A function call to fcn1 occurs with arg1, arg2, and arg3 if the following are true:
• S1 is active.
• Event e occurs.
• Condition c is true.
• The transition destination S2 is valid.
The transition action in the transition from S2 to S3 shows a function call nested within
another function call.
Example formats of function calls using state action notation appear in the following
chart.
12-29
12 Use Actions in Charts
A Stateflow action can pass arguments to a user-written function by reference rather than
by value. In particular, an action can pass a pointer to a value rather than the value itself.
For example, an action could contain the following call:
f(&x);
If x is the name of a data item defined in the Stateflow hierarchy, the following rules
apply:
• Do not use pointers to pass data items input from a Simulink model.
If you need to pass an input item by reference, for example, an array, assign the item
to a local data item and pass the local item by reference.
12-30
Call C Library Functions in C Charts
• If x is a Simulink output data item having a data type other than double, the chart
property Use Strong Data Typing with Simulink I/O must be on (see “Specify
Properties for Stateflow Charts” on page 24-3).
• If the data type of x is boolean, you must turn off the coder option Use bitsets for
storing state configuration.
• If x is an array with its first index property set to 0 (see “Set Data Properties” on page
9-5), then you must call the function as follows.
f(&(x[0]));
f(&(x[1]));
12-31
12 Use Actions in Charts
•
MATLAB as the action language.
•
C as the action language.
In charts that use C as the action language, you can call built-in MATLAB functions and
access MATLAB workspace variables by using the ml namespace operator or the ml
function.
Caution Because MATLAB functions are not available in a target environment, do not
use the ml namespace operator and the ml function if you plan to build a code generation
target.
ml Namespace Operator
For C charts, the ml namespace operator uses standard dot (.) notation to reference
MATLAB variables and functions. For example, the statement a = ml.x returns the value
of the MATLAB workspace variable x to the Stateflow data a.
For example, the statement [a, b, c] = ml.matfunc(x, y) passes the return values
from the MATLAB function matfunc to the Stateflow data a, b, and c.
If the MATLAB function you call does not require arguments, you must still include the
parentheses. If you omit the parentheses, Stateflow software interprets the function name
as a workspace variable, which, when not found, generates a run-time error during
simulation.
12-32
Access MATLAB Functions and Workspace Data in C Charts
Examples
In these examples, x, y, and z are workspace variables and d1 and d2 are Stateflow data:
• a = ml.sin(ml.x)
In this example, the MATLAB function sin evaluates the sine of x, which is then
assigned to Stateflow data variable a. However, because x is a workspace variable,
you must use the namespace operator to access it. Hence, ml.x is used instead of just
x.
• a = ml.sin(d1)
In this example, the MATLAB function sin evaluates the sine of d1, which is assigned
to Stateflow data variable a. Because d1 is Stateflow data, you can access it directly.
• ml.x = d1*d2/ml.y
The result of the expression is assigned to x. If x does not exist prior to simulation, it
is automatically created in the MATLAB workspace.
• ml.v[5][6][7] = ml.matfunc(ml.x[1][3], ml.y[3], d1, d2, 'string')
The workspace variables x and y are arrays. x[1][3] is the (1,3) element of the
two-dimensional array variable x. y[3] is the third element of the one-dimensional
array variable y. The last argument, 'string', is a character vector.
The return from the call to matfunc is assigned to element (5,6,7) of the workspace
array, v. If v does not exist prior to simulation, it is automatically created in the
MATLAB workspace.
ml Function
For C charts, you can use the ml function to specify calls to MATLAB functions. The
format for the ml function call uses this notation:
ml(evalString, arg1, arg2,...);
The format specifiers used in ml functions are the same as those used in the C functions
printf and sprintf. The ml function call is equivalent to calling the MATLAB eval
12-33
12 Use Actions in Charts
function with the ml namespace operator if the arguments arg1, arg2,... are
restricted to scalars or literals in the following command:
Stateflow software assumes scalar return values from ml namespace operator and ml
function calls when they are used as arguments in this context. See “How Charts Infer the
Return Size for ml Expressions” on page 12-39.
Examples
In these examples, x is a MATLAB workspace variable, and d1 and d2 are Stateflow data:
• a = ml('sin(x)')
In this example, the ml function calls the MATLAB function sin to evaluate the sine of
x in the MATLAB workspace. The result is then assigned to Stateflow data variable a.
Because x is a workspace variable, and sin(x) is evaluated in the MATLAB
workspace, you enter it directly in the evalString argument ('sin(x)').
• a = ml('sin(%f)', d1)
In this example, the MATLAB function sin evaluates the sine of d1 in the MATLAB
workspace and assigns the result to Stateflow data variable a. Because d1 is Stateflow
data, its value is inserted in the evalString argument ('sin(%f)') using the format
expression %f. This means that if d1 = 1.5, the expression evaluated in the MATLAB
workspace is sin(1.5).
• a = ml('matfunc(%g, ''abcdefg'', x, %f)', d1, d2)
12-34
Access MATLAB Functions and Workspace Data in C Charts
ml Expressions
For C charts, you can mix ml namespace operator and ml function expressions along with
Stateflow data in larger expressions. The following example squares the sine and
cosine of an angle in workspace variable X and adds them:
ml.power(ml.sin(ml.X),2) + ml('power(cos(X),2)')
The first operand uses the ml namespace operator to call the sin function. Its argument
is ml.X, since X is in the MATLAB workspace. The second operand uses the ml function.
Because X is in the workspace, it appears in the evalString expression as X. The
squaring of each operand is performed with the MATLAB power function, which takes
two arguments: the value to square, and the power value, 2.
Expressions using the ml namespace operator and the ml function can be used as
arguments for ml namespace operator and ml function expressions. The following
example nests ml expressions at three different levels:
a = ml.power(ml.sin(ml.X + ml('cos(Y)')),2)
In composing your ml expressions, follow the levels of precedence set out in “Binary
Operations” on page 12-14. Use parentheses around power expressions with the ^
operator when you use them in conjunction with other arithmetic operators.
Stateflow software checks expressions for data size mismatches in your actions during
parsing of charts and during run time. Because the return values for ml expressions are
not known until run time, Stateflow software must infer the size of their return values.
See “How Charts Infer the Return Size for ml Expressions” on page 12-39.
12-35
12 Use Actions in Charts
The for loop creates four new matrix variables in the MATLAB workspace. The default
transition initializes the Stateflow counter i to 0, while the transition segment
between the top two junctions increments it by 1. If i is less than 5, the transition
segment back to the top junction evaluates the ml function call ml('A%d =
rand(%d)',i,i) for the current value of i. When i is greater than or equal to 5, the
transition segment between the bottom two junctions occurs and execution stops.
The transition executes the following MATLAB commands, which create a workspace
scalar (A1) and three matrices (A2, A3, A4):
A1 = rand(1)
A2 = rand(2)
A3 = rand(3)
A4 = rand(4)
• Use the ml function with full MATLAB notation.
You cannot use full MATLAB notation with the ml namespace operator, as the
following example shows:
ml.A = ml.magic(4)
B = ml('A + A''')
This example sets the workspace variable A to a magic 4-by-4 matrix using the ml
namespace operator. Stateflow data B is then set to the addition of A and its transpose
matrix, A', which produces a symmetric matrix. Because the ml namespace operator
cannot evaluate the expression A', the ml function is used instead. However, you can
call the MATLAB function transpose with the ml namespace operator in the
following equivalent expression:
12-36
Access MATLAB Functions and Workspace Data in C Charts
B = ml.A + ml.transpose(ml.A)
As another example, you cannot use arguments with cell arrays or subscript
expressions involving colons with the ml namespace operator. However, these can be
included in an ml function call.
ml Data Type
Stateflow data of type ml is typed internally with the MATLAB type mxArray for C charts.
You can assign (store) any type of data available in the Stateflow hierarchy to a data of
type ml. These types include any data type defined in the Stateflow hierarchy or returned
from the MATLAB workspace with the ml namespace operator or ml function.
• You can initialize ml data from the MATLAB workspace just like other data in the
Stateflow hierarchy (see “Initialize Data from the MATLAB Base Workspace” on page
9-24).
• Any numerical scalar or array of ml data in the Stateflow hierarchy can participate in
any kind of unary operation and any kind of binary operation with any other data in
the hierarchy.
If ml data participates in any numerical operation with other data, the size of the ml
data must be inferred from the context in which it is used, just as return data from the
ml namespace operator and ml function are. See “How Charts Infer the Return Size
for ml Expressions” on page 12-39.
Note The preceding rule does not apply to ml data storing MATLAB 64-bit integers.
You can use ml data to store 64-bit MATLAB integers but you cannot use 64-bit
integers in C charts.
• You cannot define ml data with the scope Constant.
This option is disabled in the Data properties dialog box and in the Model Explorer for
Stateflow data of type ml.
• You can use ml data to build a simulation target but not to build an embeddable code
generation target.
12-37
12 Use Actions in Charts
• If data of type ml contains an array, you can access the elements of the array via
indexing with these rules:
a You can index only arrays with numerical elements.
b You can index numerical arrays only by their dimension.
In other words, you can access only one-dimensional arrays by a single index
value. You cannot access a multidimensional array with a single index value.
c The first index value for each dimension of an array is 1, and not 0, as in C
language arrays.
In the examples that follow, mldata is a Stateflow data of type ml, ws_num_array is a
2-by-2 MATLAB workspace array with numerical values, and ws_str_array is a 2-
by-2 MATLAB workspace array with character vector values.
mldata = ml.ws_num_array; /* OK */
n21 = mldata[2][1]; /* OK for numerical data of type ml */
n21 = mldata[3]; /* NOT OK for 2-by-2 array data */
mldata = ml.ws_str_array; /* OK */
s21 = mldata[2][1]; /* NOT OK for character vector data of type ml*/
• ml data cannot have a scope outside a C chart; that is, you cannot define the scope of
ml data as Input from Simulink or Output to Simulink.
Both the ml namespace operator and the ml function can access data directly in the
MATLAB workspace and return it to a C chart. However, maintaining data in the MATLAB
workspace can present Stateflow users with conflicts with other data already resident in
the workspace. Consequently, with the ml data type, you can maintain ml data in a chart
and use it for MATLAB computations in C charts.
As an example, in the following statements, mldata1 and mldata2 are Stateflow data of
type ml:
mldata1 = ml.rand(3);
mldata2 = ml.transpose(mldata1);
In the first line of this example, mldata1 receives the return value of the MATLAB
function rand, which, in this case, returns a 3-by-3 array of random numbers. Note that
mldata1 is not specified as an array or sized in any way. It can receive any MATLAB
workspace data or the return of any MATLAB function because it is defined as a Stateflow
data of type ml.
12-38
Access MATLAB Functions and Workspace Data in C Charts
In the second line of the example, mldata2, also of Stateflow data type ml, receives the
transpose matrix of the matrix in mldata1. It is assigned the return value of the MATLAB
function transpose in which mldata1 is the argument.
Note the differences in notation if the preceding example were to use MATLAB workspace
data (wsdata1 and wsdata2) instead of Stateflow ml data to hold the generated
matrices:
ml.wsdata1 = ml.rand(3);
ml.wsdata2 = ml.transpose(ml.wsdata1);
In this case, each workspace data must be accessed through the ml namespace operator.
For example, the size of the return values from the expressions ml.var, ml.func(),
or ml(evalString, arg1, arg2,...), where var is a MATLAB workspace
variable and func is a MATLAB function, cannot be known until run-time.
• Stateflow data of type ml
• Graphical functions that return Stateflow data of type ml
When these expressions appear in actions, Stateflow code generation creates temporary
data to hold intermediate returns for evaluation of the full expression of which they are a
part. Because the size of these return values is unknown until run time, Stateflow
software must employ context rules to infer the sizes for creation of the temporary data.
During run time, if the actual returned value from one of these commands differs from the
inferred size of the temporary variable that stores it, a size mismatch error appears. To
prevent run-time errors, use the following guidelines to write actions with MATLAB
commands or ml data:
12-39
12 Use Actions in Charts
Guideline Example
Return sizes of MATLAB commands or data in an In the expression ml.func() * (x +
expression must match return sizes of peer expressions. ml.y), if x is a 3-by-2 matrix, then
ml.func() and ml.y are also assumed
to evaluate to 3-by-2 matrices. If either
returns a value of different size (other
than a scalar), an error results during
run-time.
Expressions that return a scalar never produce an error. In the expression ml.x + y, if y is a 3-
by-2 matrix and ml.x returns a scalar,
You can combine matrices and scalars in larger the resulting value is the result of adding
expressions because MATLAB commands use scalar the scalar value of ml.x to every
expansion. member of y to produce a matrix with
the size of y, that is, a 3-by-2 matrix.
12-40
Access MATLAB Functions and Workspace Data in C Charts
Guideline Example
MATLAB command or data elements used in an In the function call ml.func(x +
expression for the input argument of a MATLAB function ml.y), if x is a 3-by-2 array, ml.y must
called through the ml namespace operator are resolved return a 3-by-2 array or a scalar.
for size. This resolution uses the rule for peer
expressions (preceding rule 1) for the expression itself,
because no size definition prototype is available.
MATLAB command or data elements used for the input If the graphical function gfunc has the
argument for a graphical function in an expression are prototype gfunc(arg1), where arg1 is
resolved for size by the function prototype. a 2-by-3 Stateflow data array, the calling
expression, gfunc(ml.y + x), requires
that both ml.y and x evaluate to 2-by-3
arrays (or scalars) during run-time.
ml function calls can take only scalar or character vector In the expression a = ml('sin(x)'),
literal arguments. Any MATLAB command or data that the ml function calls the MATLAB
specifies an argument for the ml function must return a function sin to evaluate the sine of x in
scalar value. the MATLAB workspace. Stateflow data
variable a stores that result.
In an assignment, the size of the right-hand expression In the expression s = ml.func(x),
must match the size of the left-hand expression, with one where x is a 3-by-2 matrix and s is scalar
exception. If the left-hand expression is a single MATLAB Stateflow data, ml.func(x) must return
variable, such as ml.x, or Stateflow data of type ml, the a scalar to match the left-hand
right-hand expression determines the sizes of both expression, s. However, in the
expressions. expression ml.y = x + s, where x is a
3-by-2 data array and s is scalar, the left-
hand expression, workspace variable y,
is assigned the size of a 3-by-2 array to
match the size of the right-hand
expression, x+s, a 3-by-2 array.
In an assignment, Stateflow column vectors on the left- In the expression s = ml.func(),
hand side are compatible with MATLAB row or column where ml.func() returns a 1-by-3
vectors of the same size on the right-hand side. matrix, if s is a vector of size 3, the
assignment is valid.
A matrix you define with a row dimension of 1 is
considered a row vector. A matrix you define with one
dimension or with a column dimension of 1 is considered
a column vector.
12-41
12 Use Actions in Charts
Guideline Example
If you cannot resolve the return size of MATLAB In the expression ml.x = ml.y +
command or data elements in a larger expression by any ml.z, none of the preceding rules can be
of the preceding rules, they are assumed to return scalar used to infer a common size among
values. ml.x, ml.y, and ml.z. In this case, both
ml.y and ml.z are assumed to return
scalar values. Even if ml.y and ml.z
return matching sizes at run-time, if they
return nonscalar values, a size mismatch
error results.
The preceding rules for resolving the size of member The expression x + ml.str, where
MATLAB commands or Stateflow data of type ml in a ml.str is a character vector workspace
larger expression apply only to cases in which numeric variable, produces a run-time error
values are expected for that member. For nonnumeric stating that ml.str is not a numeric
returns, a run-time error results. type.
Special cases exist, in which no size checking occurs to resolve the size of MATLAB
command or data expressions that are part of larger expressions. Use of the following
expressions does not require enforcement of size checking at run-time:
• ml.var
• ml.func()
• ml(evalString, arg1, arg2,...)
• Stateflow data of type ml
• Graphical function returning a Stateflow data of type ml
For example, in the expression ml.x = ml.y, ml.y is a MATLAB workspace variable
of any size and type (structure, cell array, character vector, and so on).
12-42
Access MATLAB Functions and Workspace Data in C Charts
For example, in the expression m_x = ml.func(), m_x is a Stateflow data of type ml.
• Input arguments of a MATLAB function
Note If you replace the inputs in the preceding cases with non-MATLAB numeric
Stateflow data, conversion to an ml type occurs.
12-43
12 Use Actions in Charts
Array Notation
A Stateflow action in a C chart uses C style syntax and zero-based indexing by default to
access array elements. This syntax differs from MATLAB notation, which uses one-based
indexing. For example, suppose that you define a Stateflow input A of size [3 4]. To
access the element in the first row, second column, use the expression A[0][1]. Other
examples of zero-based indexing in C charts include:
local_array[1][8][0] = 10;
local_array[i][j][k] = 77;
var = local_array[i][j][k];
Note Use the same notation for accessing arrays in C charts, from Simulink models, and
from custom code.
local_array = 10;
Scalar expansion is available for performing general operations. This statement is valid if
the arrays array_1, array_2, and array_3 have the same value for the Sizes property.
Note Any array variable that is referred to in a C chart but is not defined in the Stateflow
hierarchy is identified as a custom code variable.
12-44
Broadcast Local Events to Synchronize Parallel States
Using a directed local event broadcast provides the following benefits over an undirected
broadcast:
For information about avoiding unwanted recursion, see “Guidelines for Avoiding
Unwanted Recursion in a Chart” on page 32-34.
send(event_name,state_name)
where event_name is broadcast to state_name and any offspring of that state in the
hierarchy. The event you send must be visible to both the sending state and the receiving
state (state_name).
The state_name argument can include a full hierarchy path to the state. For example, if
the state A contains the state A1, send an event e to state A1 with the following
broadcast:
send(e, A.A1)
Tip Do not include the chart name in the full hierarchy path to a state.
12-45
12 Use Actions in Charts
In this example, event E_one belongs to the chart and is visible to both A and B. See
“Directed Event Broadcast Using Send” on page B-50 for more information on the
semantics of this notation.
send(state_name.event_name)
where event_name is broadcast to its owning state (state_name) and any offspring of
that state in the hierarchy. The event you send is visible only to the receiving state
(state_name).
The state_name argument can also include a full hierarchy path to the receiving state.
Do not use the chart name in the full path name of the state.
The following example shows the use of a qualified event name in a directed local event
broadcast.
12-46
See Also
In this example, event E_one belongs to state B and is visible only to that state. See
“Directed Event Broadcast Using Qualified Event Name” on page B-51 for more
information on the semantics of this notation.
You can control the level of diagnostic action for undirected local event broadcasts in the
Diagnostics > Stateflow pane of the Model Configuration Parameters dialog box. Set
the Undirected event broadcasts diagnostic to none, warning, or error. For more
information, see the documentation for the “Undirected event broadcasts” (Simulink)
diagnostic.
See Also
send
12-47
12 Use Actions in Charts
More About
• “Synchronize Model Components by Broadcasting Events” on page 10-2
• “Set Properties for an Event” on page 10-6
• “Broadcast Local Events in Parallel States” on page B-50
12-48
Control Chart Execution by Using Temporal Logic
• State actions
• Transitions that originate from states
• Transition segments that originate from junctions when the full transition path
connects two states
Note This restriction means that you cannot use temporal logic operators in default
transitions or flow chart transitions.
Every temporal logic operator has an associated state, which is the state in which the
action appears or from which the transition originates.
• Use event notation to express event-based temporal logic in state actions. See
“Notation for Event-Based Temporal Logic” on page 12-54.
• You can use any explicit or implicit event as a base event for a temporal operator. A
base event is a recurring event on which a temporal operator operates.
• For a chart with no input events, you can use the tick or wakeup event to denote the
implicit event of a chart waking up.
• Use one of the keywords sec , msec, or usec to define simulation time in seconds,
milliseconds, or microseconds that have elapsed since activation of a state. These
keywords are valid only in state actions and in transitions that originate from states.
Use absolute-time temporal logic instead of the implicit tick event for these reasons:
• Delay expressions that use absolute-time temporal logic are independent of the
sample time of the model. However, the tick event is dependent on sample time.
12-49
12 Use Actions in Charts
• Absolute-time temporal logic works in charts that have function-call input events.
The tick event does not work in charts with function-call inputs.
12-50
Control Chart Execution by Using Temporal Logic
12-51
12 Use Actions in Charts
You can use quotation marks to enclose the keywords 'tick' and 'wakeup'. For
example, after(5,'tick') is equivalent to after(5,tick).
Note Temporal logic operators compare the threshold n to an internal counter of integer
type. If n is a fixed-point number defined by using either a slope that is not an integer
power of two or a nonzero bias, then the comparison can yield unexpected results due to
rounding. For more information, see “Relational Operations for Fixed-Point Data” on page
22-33.
12-52
Control Chart Execution by Using Temporal Logic
12-53
12 Use Actions in Charts
Event Notation
Use event notation to define a state action or a transition condition that depends only on a
base event.
tlo(n,E)[C]
where
12-54
Control Chart Execution by Using Temporal Logic
Conditional Notation
Use conditional notation to define a transition condition that depends on base and
nonbase events.
E1[tlo(n,E2) && C]
where
12-55
12 Use Actions in Charts
Note You must use event notation in state actions because the syntax of state actions
does not support conditional notation.
12-56
Control Chart Execution by Using Temporal Logic
12-57
12 Use Actions in Charts
12-58
Control Chart Execution by Using Temporal Logic
You can use quotation marks to enclose the keywords 'sec', 'msec', and 'usec'. For
example, after(5,'sec') is equivalent to after(5,sec).
Note Temporal logic operators compare the threshold n to an internal counter of integer
type. If n is a fixed-point number defined by using either a slope that is not an integer
power of two or a nonzero bias, then the comparison can yield unexpected results due to
rounding. For more information, see “Relational Operations for Fixed-Point Data” on page
22-33.
12-59
12 Use Actions in Charts
12-60
Control Chart Execution by Using Temporal Logic
If a chart has a discrete sample time, any action in the chart occurs at integer multiples of
this sample time. For example, suppose that you change the configuration parameters so
that the Simulink® solver uses a fixed step of size 0.1 seconds. Then, the first transition
from state Input to state Output occurs at t = 0.1 seconds. This behavior applies
because the solver does not wake the chart at exactly t = 5.33 milliseconds. Instead, the
solver wakes the chart at integer multiples of 0.1 seconds, such as t = 0.0 and 0.1
seconds.
In this model, the Step block provides a unit step input to the chart.
• If the input equals 1 before t = 2 seconds, a transition occurs from Start to Fast.
• If the input equals 1 between t = 2 and t = 5 seconds, a transition occurs from Start
to Good.
• If the input equals 1 after t = 5 seconds, a transition occurs from Start to Slow.
You can use absolute-time temporal logic in a chart that resides in a conditionally
executed subsystem. When the subsystem is disabled, the chart becomes inactive and the
12-61
12 Use Actions in Charts
temporal logic operator pauses while the chart is asleep. The operator does not continue
to count simulation time until the subsystem is reenabled and the chart is awake.
This model has an enabled subsystem with the States when enabling parameter set to
held.
The Signal Builder block provides an input signal with these characteristics:
12-62
Control Chart Execution by Using Temporal Logic
This graph shows the total time elapsed in an enabled state (either A or B).
12-63
12 Use Actions in Charts
When the input signal enables the subsystem at time t = 0, the state A becomes active, or
enabled. While the state is active, the time elapsed increases. However, when the
subsystem is disabled at t = 2, the chart goes to sleep and state A becomes inactive.
For 2 < t < 6, the time elapsed in an enabled state stays frozen at 2 seconds because
neither state is active. When the chart wakes up at t = 6, state A becomes active again
and time elapsed starts to increase. The transition from state A to state B depends on the
time elapsed while state A is enabled, not on the simulation time. Therefore, state A stays
active until t = 9, so that the time elapsed in that state totals 5 seconds.
When the transition from A to B occurs at t = 9, the output value y changes from 0 to 1.
12-64
Control Chart Execution by Using Temporal Logic
This model behavior applies only to subsystems where you set the Enable block
parameter States when enabling to held. If you set the parameter to reset, the chart
reinitializes completely when the subsystem is reenabled. In other words, default
transitions execute and any temporal logic counters reset to 0.
If you use the at operator with absolute-time temporal logic, an error message appears
when you try to simulate your model. Use the after operator instead.
12-65
12 Use Actions in Charts
Suppose that you want to define a time delay using the transition at(5.33, sec).
Use an Outer Self-Loop Transition with the after Operator to Replace the every
Operator
In a Stateflow model, if you use the every operator with absolute-time temporal logic, an
error message appears when you try to simulate your model. Use an outer self-loop
transition with the after operator instead.
Suppose that you want to print a status message for an active state every 2.5 seconds
during chart execution, as shown in the state action of Check_status.
12-66
Control Chart Execution by Using Temporal Logic
Replace the state action with an outer self-loop transition, as shown in this chart.
Also add a history junction in the state so that the chart remembers the state settings
prior to each self-loop transition. See “Record State Activity by Using History Junctions”
on page 8-2.
Use Charts with Discrete Sample Times for More Efficient Code Generation
The code generated for discrete charts that are not inside a triggered or enabled
subsystem uses integer counters to track time instead of Simulink provided time. This
12-67
12 Use Actions in Charts
allows for more efficient code generation in terms of overhead and memory, as well as
enabling this code for use in software-in-the-loop (SIL) and processor-in-the-loop (PIL)
simulation modes. For more information, see “SIL and PIL Simulations” (Embedded
Coder).
See Also
after | at | before | count | duration | elapsed | every | temporalCount
More About
• “Control Oscillations by Using the duration Operator” on page 12-95
• “Reduce Transient Signals by Using Debouncing Logic” on page 26-2
12-68
Detect Changes in Data Values
Change detection operators return true if there is a change in data value and false if
there is no change in data value.
12-69
12 Use Actions in Charts
• A scalar variable.
• A matrix or an element of a matrix. See “Supported Operations for Vectors and
Matrices” on page 17-11.
• A structure or a field in a structure. See “Index and Assign Values to Stateflow
Structures” on page 25-8.
• Any valid combination of structure fields or matrix indices.
For the hasChangedFrom and hasChangedTo operators, the second argument v can be
any expression that resolves to a value that is comparable with u.
Alternatively, in a chart that uses C as the action language, v can resolve to a scalar
value. The chart uses scalar expansion to compare u to a matrix whose elements are
all equal to the value specified by v. See “Convert Scalars to Nonscalars by Using
Scalar Expansion” on page 17-9.
• If u is a structure, then v must resolve to a structure value whose field specification
matches u exactly.
12-70
Detect Changes in Data Values
The model uses a fixed-step solver with a step size of 1. The signal increments by 1 at
each time step. At each time step, the chart analyzes the input signal u for these changes:
To check the signal, the chart calls three change detection operators in a transition
action. The chart outputs the return values as y1, y2, and y3.
During simulation, the Scope block shows the input and output signals to the chart.
12-71
12 Use Actions in Charts
12-72
Detect Changes in Data Values
chart compares the value at the beginning of the previous execution step with the value
at the beginning of the current execution step. To detect changes, the chart double-
buffers these values in local variables.
Double-buffering occurs once per time step except when multiple input events occur in
the same time step. If multiple input events occur in the same time step, double-buffering
occurs once per input event. See “Detect Value Changes Between Input Events” on page
12-76.
When you invoke a change detection operator in an action, the Stateflow chart:
• Double-buffers data values after a Simulink event triggers the chart but before the
chart begins execution.
• Compares values in _prev and _start buffers. If the values match, the change
detection operator returns false (no change); otherwise, it returns true (change).
This diagram places these tasks in the context of the chart life cycle.
12-74
Detect Changes in Data Values
12-75
12 Use Actions in Charts
Buffering occurs before chart execution and affects change detection when:
Stateflow charts attempt to filter out transient changes in local chart variables by
evaluating their values only at time boundaries. The chart evaluates the specified local
variable only once at the end of the execution step. The return value of the change
detection operators remains constant even if the value of the local variable fluctuates
within a given time step.
For example, suppose that in the current time step a local variable temp changes from its
value at the previous time step but then reverts to the original value. The operator
hasChanged(temp) returns false for the next time step, indicating that no change
occurred.
When multiple input events occur in the same time step, the Stateflow chart updates the
_prev and _start buffers once per event. A chart detects changes between input
events, even if the changes occur more than once in a given time step.
See Also
hasChanged | hasChangedFrom | hasChangedTo
More About
• “Tetris”
12-76
Check State Activity by Using the in Operator
For example, this chart has two parallel states: Place and Tracker. The transitions in
Tracker check the state activity in Place and keep the substates synchronized. A
change of active substate in Place causes a corresponding change of active substate in
Tracker.
• If R becomes the active substate in Place, then Moved_Right becomes the active
substate in Tracker.
• If L becomes the active substate in Place, then Moved_Left becomes the active
substate in Tracker.
The in Operator
To check if a state is active in a given time step during chart execution, use the in
operator:
in(S)
The in operator takes a qualified state name S and returns a Boolean output. If state S is
active, in returns a value of 1. Otherwise, in returns a value of 0.
You can use the in operator in state actions and in transitions that originate from states.
12-77
12 Use Actions in Charts
The search begins at the hierarchy level where the qualified state name appears:
• For a state action, the starting point is the state containing the action.
• For a transition label, the starting point is the parent of the transition source.
The resolution process searches each level of the chart hierarchy for a path to the state. If
a state matches the path, the process adds that state to the list of possible matches. Then,
the process continues the search one level higher in the hierarchy. The resolution process
stops after it searches the chart level of the hierarchy. If a unique match exists, the in
operator checks if the matching state is active. Otherwise, the resolution process fails.
Simulation stops and you see an error message.
This flow chart illustrates the different stages in the process for checking state activity.
12-78
Check State Activity by Using the in Operator
12-79
12 Use Actions in Charts
To improve the chances of finding a unique search result when resolving qualified data
names:
This chart contains parallel states A and B that have identical substates A1 and A2. The
condition in(A1.Y) guards the transition from P to Q in A.A2 and in B.A2. Stateflow
resolves each qualified state name as the local copy of the substate Y:
• In the state A, the condition in(A1.Y) checks the activity of state A.A1.Y.
• In the state B, the condition in(A1.Y) checks the activity of state B.A1.Y.
12-80
Check State Activity by Using the in Operator
This table lists the different stages in the resolution process for the transition condition in
state A.A2.
The search ends with a single match found. Because the resolution algorithm localizes the
scope of the search, the in operator guarding the transition in A.A2 detects only the
state A.A1.Y. The in operator guarding the transition in B.A2 detects only the state
B.A1.Y.
To check the state activity of the other copy of Y, use more specific qualified state names:
In this chart, the during action in state A.B contains the expression in(Q.R). Stateflow
cannot resolve the qualified state name Q.R.
12-81
12 Use Actions in Charts
The search ends at the chart level with no match found for Q.R, resulting in an error.
To avoid this error, use a more specific qualified state name. For instance, check state
activity by using the expression in(P.Q.R).
In this chart, the during action in state A.B contains the expression in(Q.R). When
resolving the qualified state name Q.R, Stateflow cannot detect the substate A.B.P.Q.R.
12-82
Check State Activity by Using the in Operator
The search ends with a single match found. The in operator detects only the substate R of
the top-level state Q.
To check the state activity of A.B.P.Q.R, use a more specific qualified state name. For
instance, use the expression in(P.Q.R).
In this chart, the during action in state A.B contains the expression in(P.Q.R).
Stateflow cannot resolve the qualified state name P.Q.R.
The search ends at the chart level with two matches found for P.Q.R, resulting in an
error.
12-83
12 Use Actions in Charts
• To check the substate activity in the top-level state P, use the expression
in(\P.Q.R).
• Rename one of the matching states.
• Enclose the top-level state P in a box or another state. Adding an enclosure prevents
the search process from detecting substates in the top-level state.
See Also
More About
• “State Action Types” on page 12-2
• “Transition Action Types” on page 12-7
• “State Hierarchy” on page 2-14
• “Monitor State Activity Through Active State Data” on page 24-26
12-84
Control Function-Call Subsystems by Using bind Actions
You can bind function-call output events to a state. When you create this type of binding,
the function-call subsystem that is called by the event is also bound to the state. In this
situation, the function-call subsystem is enabled when the state is entered and disabled
when the state is exited.
When you bind a function-call subsystem to a state, you can fine-tune the behavior of the
subsystem when it is enabled and disabled, as described in the following sections:
Although function-call subsystems do not execute while disabled, their output signals are
available to other blocks in the model. If a function-call subsystem is bound to a state, you
can hold its outputs at their values from the previous time step or reset the outputs to
their initial values when the subsystem is disabled. Follow these steps:
1 Double-click the outport block of the subsystem to open the Block Parameters dialog
box.
12-85
12 Use Actions in Charts
Select: To:
held Maintain most recent output value
12-86
Control Function-Call Subsystems by Using bind Actions
Select: To:
reset Reset output to its initial value
3 Click OK to record the settings.
Note Setting Output when disabled is meaningful only when the function-call
subsystem is bound to a state, as described in “Bind a Function-Call Subsystem to a
State” on page 12-85.
If a function-call subsystem is bound to a state, you can hold the subsystem state
variables at their values from the previous time step or reset the state variables to their
initial conditions when the subsystem executes. In this way, the binding state gains full
control of state variables for the function-call subsystem. Follow these steps:
1 Double-click the trigger port of the subsystem to open the Block Parameters dialog
box.
12-87
12 Use Actions in Charts
Select: To:
held Maintain most recent values of the states of the subsystem
that contains the trigger port
12-88
Control Function-Call Subsystems by Using bind Actions
Select: To:
reset Revert to the initial conditions of the states of the
subsystem that contains this trigger port
inherit Inherit this setting from the function-call initiator's parent
subsystem. If the parent of the initiator is the model root,
the inherited setting is held. If the trigger has multiple
initiators, the parents of all initiators must have the same
setting: either all held or all reset.
3 Click OK to record the settings.
Note Setting States when enabling is meaningful only when the function-call
subsystem is bound to a state, as described in “Bind a Function-Call Subsystem to a
State” on page 12-85.
The chart contains two states. Event E binds to state A with the action
bind:E
Event E is defined for the chart with a scope of Output to Simulink and a trigger type
of function-call.
12-89
12 Use Actions in Charts
The function-call subsystem contains a trigger port block, an input port, an output port,
and a simple block diagram. The block diagram increments a counter by 1 at each time
step, using a Unit Delay block.
The Block Parameters dialog box for the trigger port contains these settings:
Setting Sample time type to periodic enables the Sample time field below it, which
defaults to 1. These settings force the function-call subsystem to execute for each time
step specified in the Sample time field while it is enabled. To accomplish this, the state
that binds the calling event for the function-call subsystem must send an event for the
time step coinciding with the specified sampling rate in the Sample time field. States can
send events with entry or during actions at the simulation sample rate.
• For fixed-step sampling, the Sample time value must be an integer multiple of the
fixed-step size.
12-90
Control Function-Call Subsystems by Using bind Actions
To see how a state controls a bound function-call subsystem, begin simulating the model.
• At time t = 0, the default transition to state A occurs. State A executes its bind and
entry actions. The binding action binds event E to state A, enabling the function-call
subsystem and resetting its state variables to 0. The entry action triggers the function-
call subsystem and executes its block diagram. The block diagram increments a
counter by 1 using a Unit Delay block. The Unit Delay block outputs a value of 0 and
holds the new value of 1 until the next call to the subsystem.
• At time t = 1, the next update event from the model tests state A for an outgoing
transition. The transition to state B does not occur because the temporal operator
after(10,tick) allows the transition to be taken only after ten update events are
received. State A remains active and its during action triggers the function-call
subsystem. The Unit Delay block outputs its held value of 1. The subsystem also
increments its counter to produce the value of 2, which the Unit Delay block holds
until the next triggered execution.
• The next eight update events increment the subsystem output by one at each time
step.
• At time t = 10, the transition from state A to state B occurs. Because the binding to
state A is no longer active, the function-call subsystem is disabled, and its output drops
back to 0.
• At time t = 11, the transition from state B to state A occurs. Again, the binding action
enables the function-call subsystem. Subsequent update events increment the
subsystem output by one at each time step until the next transition to state B occurs at
time t = 21.
12-91
12 Use Actions in Charts
12-92
Control Function-Call Subsystems by Using bind Actions
In the chart, E1 binds to state A, but E2 does not. State B sends the triggering event E2 in
its entry action.
When you simulate this model, the output does not reset when the transition from state A
to state B occurs.
12-93
12 Use Actions in Charts
Binding is not recommended when you provide multiple trigger events to a function-call
subsystem through a mux. Muxed trigger events can interfere with event binding and
cause undefined behavior.
12-94
Control Oscillations by Using the duration Operator
When modeling the gear changes of this system, it is important to control the oscillation
that occur. The model sf_car uses parallel state debouncer logic that controls which
gear state is active. For more information about how debouncers work in Stateflow, see
“Reduce Transient Signals by Using Debouncing Logic” on page 26-2.
You can simplify the debouncer logic by using the duration operator. You can see this
simplification in the model sf_car_using_duration. The duration operator evaluates
a condition expression and outputs the length of time that the expression has been true.
When that length of time crosses a known time threshold, the state transitions to a higher
or lower gear.
By removing the parallel state logic and using the duration operator, you can control
oscillations with simpler Stateflow logic. The duration operator is supported only in
Stateflow charts in a Simulink model.
The Stateflow chart shift_logic controls which gear the car is in, given the speed of
the car and how much throttle is being applied. Within shift_logic there are two
parallel states: gear_state and selection_state. gear_state contains four
exclusive states for each gear. selection_state determines whether the car is
downshifting, upshifting, or remaining in its current gear.
12-95
12 Use Actions in Charts
In this Stateflow chart, for the car to move from first gear to second gear, the event UP
must be sent from selection_state to gear_state. The event is sent when the speed
crosses the threshold and remains higher than the threshold for the length of time
determined by TWAIT. When the event UP is sent, gear_state transitions from first to
second.
Within Gear_Logic there are four exclusive states for each gear. The local variables up
and down guard the transitions between each state.
12-96
See Also
In this Stateflow chart, for the car to move from first gear to second gear, the condition
up must be true. The condition up is defined as true if the length of time that the speed
is greater than or equal to the threshold is greater than the length of time that is
specified by TWAIT. The condition down is defined as true if the length of time that the
speed is less than or equal to the threshold is greater than the length of time that is
specified by TWAIT. The operator duration keeps track of the length of time that the
speed has been above or below the threshold. When the up condition is met, the active
state transitions from first to second.
By replacing the parallel state debouncer logic with the duration operator, you can
create a simpler Stateflow chart to model the gear shifting.
See Also
duration
Related Examples
• “Reduce Transient Signals by Using Debouncing Logic” on page 26-2
12-97
12 Use Actions in Charts
12-98
13
•
MATLAB as the action language.
•
C as the action language.
You can change the action language of a chart in the Action Language box of the Chart
properties dialog box. For more information, see “Differences Between MATLAB and C as
Action Language Syntax” on page 13-6.
sfnew -c
To change the default action language of new charts, use these commands.
Command Result
sfpref('ActionLanguage','MATLAB') All new charts created have MATLAB as the
action language, unless otherwise specified
in sfnew.
sfpref('ActionLanguage','C') All new charts created have C as the action
language, unless otherwise specified in
sfnew.
13-2
Modify the Action Language for a Chart
• Increment and decrement operations such as a++ and a--. For example, a++ is
changed to a = a+1.
• Assignment operations such as a += b, a –= b, a *= b, and a /= b. For example,
a += b is changed to a = a+b.
• Evaluation operations such as a != b and !a. For example, a != b is changed to a
~= b.
• Comment markers // and /* */ are changed to %.
• Zero-based indexing.
• Increment and decrement operations such as a++ and a--. For example, a++ is
changed to a = a+1.
• Assignment operations such as a += b, a –= b, a *= b, and a /= b. For example,
a += b is changed to a = a+b.
• Binary operations such as a %% b, a >> b, and a << b. For example, a %% b is
changed to rem(a,b).
• Bitwise operations such as a ^ b, a & b, and a | b. For example, if the chart
property Enable C-bit operations is selected, then a ^ b is changed to
bitxor(a,b).
• C style comment markers. For example, // and /* */ are changed to %.
If the chart contains C constructs that cannot be converted to MATLAB, Stateflow shows a
message in a dialog box. Click on the warnings link to display the warnings in the
Diagnostic Viewer. Choose whether or not to continue with the conversion of supported
syntax. C constructs not converted to MATLAB include:
13-3
13 MATLAB Syntax Support for States and Transitions
Using the same name for data at different levels of the chart hierarchy causes a compile-
time error.
Using the same name for functions at different levels of the chart hierarchy causes a
compile-time error.
Use % to specify comments in states and transitions for consistency with MATLAB. For
example, the following comment is valid:
a(2,5) = 0;
a[2][5] = 0;
13-4
Modify the Action Language for a Chart
Do not use control flow logic in condition actions and transition actions
If you try to use control flow logic in condition actions or transition actions, you get an
error. Use of an if, switch, for, or while statement does not work.
E [x > 0] / {x = x+1;}
E [x > 0] / x = x+1;
The keywords global and persistent are not supported in state actions.
To generate code from your model, use MATLAB language features supported for
code generation
When using MATLAB as the action language, data read without an initial value causes an
error.
13-5
13 MATLAB Syntax Support for States and Transitions
•
MATLAB as the action language.
•
C as the action language.
MATLAB is the default action language syntax for new Stateflow charts. To create a chart
that uses C as the action language, enter:
sfnew -c
13-6
Differences Between MATLAB and C as Action Language Syntax
13-7
13 MATLAB Syntax Support for States and Transitions
13-8
Differences Between MATLAB and C as Action Language Syntax
13-9
13 MATLAB Syntax Support for States and Transitions
See Also
sfnew
13-10
See Also
More About
• “Modify the Action Language for a Chart” on page 13-2
• “Supported Operations for Chart Data” on page 12-14
• “Supported Operations for Vectors and Matrices” on page 17-11
• “Supported Operations for Complex Data” on page 23-4
• “Supported Operations for Fixed-Point Data” on page 22-21
• “Execution Order for Parallel States” on page 3-86
13-11
13 MATLAB Syntax Support for States and Transitions
This tutorial uses the first approach— that is, start by identifying the operating modes of
the system to program the chart.
Design Requirements
This example shows how to build a Stateflow chart using MATLAB as the action language.
The model represents a machine on an assembly line that feeds raw material to other
parts of the line. This feeder behaves as follows:
• At system initialization, check that the three sensor values are normal.
A positive value means the sensor is working correctly. A zero means that the sensor is
not working.
• If all sensor values are normal, transition from "system initialization" to "on".
• If the feeder does not leave initialization mode after 5 seconds, force the feeder into
the failure state.
• After the system turns on, it starts counting the number of parts fed.
• At each time step, if any sensor reading is 2 or greater, the part has moved to the next
station.
• If the alarm signal sounds, force the system into the failure state.
An alarm signal can occur when an operator opens one of the safety doors on the
feeder or a downstream problem occurs on the assembly line, which causes all
upstream feeders to stop.
• If the all-clear signal sounds, resume normal operation and reset the number of parts
fed to zero.
• The feeder LED changes color to match the system operating mode— orange for
"system initialization", green for "on", and red for "failure state".
13-12
Model an Assembly Line Feeder
Attribute Characteristic
Operating modes • System initialization, to perform system checks before
turning on the machine
• On, for normal operation
• System failure, for a recoverable machine failure flagged
by an alarm
Transitions • System initialization to On
• System initialization to Failure state
• On to Failure state
• Failure state to System initialization
Parallel Modes No operating modes run in parallel. Only one mode can be
active at any time.
Default Mode System initialization
Inputs • Three sensor readings to detect if a part has moved to a
downstream assembly station
• An alarm signal that can take one of two values: 1 for on and
0 for off
Outputs • Number of parts that have been detected as fed to a
downstream assembly station
• Color of the LED on the feeder
To implement the model yourself, follow these exercises. Otherwise, you can open the
completed model.
13-13
13 MATLAB Syntax Support for States and Transitions
2 Double-click the SensorSignals block to see the three sensor signals represented
by pulse generator blocks.
The sensors signal indicates when the assembly part is ready to move to the next
station.
3 Double-click the AlarmSignal block to see the step blocks that represent the alarm
signal.
13-14
Model an Assembly Line Feeder
13-15
13 MATLAB Syntax Support for States and Transitions
The upper axis shows the sensor signals. Only two sensor signals appear because two
of the sensors have the same signal. The lower axis shows the alarm signal which
turns the feeder off between the simulation time of 45 to 80 seconds.
5 Open the Stateflow Library by executing sflib at the MATLAB command prompt.
6 Select Chart and drag it into your model.
Tip To create a new model with an empty Stateflow chart which uses MATLAB as the
action language, use the command,sfnew.
7 Delete the connections from the SensorSignals subsystem to the scope and from the
AlarmSignal subsystem to the scope.
8 Rename the label Chart located under the Stateflow chart to Feeder. The model
should now look like this:
• System initialization
• On
• Failure state
13-16
Model an Assembly Line Feeder
Note The MATLAB icon in the lower left corner of the chart indicates that you are
using a Stateflow chart with MATLAB syntax.
2 Click the State Tool icon to bring a state into the chart.
3 Click the upper left corner of the state and type the name, InitializeSystem.
4 Repeat steps 2 and 3 to add two more states named On and FailState.
States perform actions at different phases of their execution cycle from the time they
become active to the time they become inactive. Three basic state actions are:
For example, you can use entry actions to initialize data, during actions to update data,
and exit actions to configure data for the next transition. For more information about
other types of state actions, see “Syntax for States and Transitions”.)
1 Press return after the InitializeSystem state name and add this text to define the
state entry action:
entry:
Light = ORANGE;
13-17
13 MATLAB Syntax Support for States and Transitions
entry:
Light = RED;
entry:
Light = GREEN;
partsFed = 0;
A green LED indicates entry in the On state. The number of parts fed is initialized to
0 each time we enter the On state
4 Add the following code to the On state after the entry action to check if there is a
strong sensor signal and increment the parts fed to the next station:
during:
if(any(sensors >= 2))
partsFed = partsFed + 1;
end
The On state checks the sensor signal to determine if a part is ready to be fed to the
next assembly station. If the sensor signal is strong (the number of sensors that are
on is greater than or equal to 2), then the chart counts the part as having moved on
to the next station.
13-18
Model an Assembly Line Feeder
Based on the description of feeder behavior, specify the rules for transitions between
states:
13-19
13 MATLAB Syntax Support for States and Transitions
a Move the mouse over the lower edge of the InitializeSystem state until the
pointer shape changes to crosshairs.
b Click and drag the mouse to the upper edge of the On state. You then see a
transition from the InitializeSystem state to the On state.
c Double-click the transition to add this condition:
[all(sensors>0)]
This transition condition verifies if all of the sensors have values greater than zero.
3 Repeat these steps to create these remaining transition conditions.
Transition Condition
On to FailState [Alarm == 1]
FailState to InitializeSystem [Alarm == 0]
4 Draw another transition from InitializeSystem to FailState. On this transition,
type the following to create the transition event:
after(5,sec)
If the sensors have not turned on after 5 seconds, this syntax specifies a transition
from InitializeSystem to FailState.
Note The syntax on this transition is an event rather than a transition condition. For
details, refer to“Control Chart Execution by Using Temporal Logic” on page 12-49.
13-20
Model an Assembly Line Feeder
Note The outgoing transitions from InitializeSystem have a small label 1 and 2 to
indicate the order in which transition segments are evaluated. If the numbers from the
figure do not match your model, right click the transition and then change it by clicking
on Execution Order. See “Transition Evaluation Order” on page 3-65 for details.
13-21
13 MATLAB Syntax Support for States and Transitions
Start the simulation of your model. Errors about unresolved symbols appear, along with
the Symbol Wizard.
The Symbol Wizard does not automatically add any data to your chart. It identifies the
unresolved data and infers the class and scope of that data using the inference rules of
MATLAB expressions in Stateflow actions. In the chart:
• Data that is read from but not written to is inferred as input data. However, if the
name of the data is in all uppercase letters, the Symbol Wizard infers the data as a
parameter
• Data that is written to but not read from is inferred as output data.
13-22
Model an Assembly Line Feeder
The Symbol Wizard infers the scope of the input data in your chart. However, you must fix
the data scope for the partsFed Output. Follow these steps:
1 For the partsFed data: in the Data Scope column, select Output from the list
2 To add the data that the Symbol Wizard suggests, click OK.
3 Add initial values for the parameters. At the MATLAB command prompt, enter:
RED = 0;
4 Similarly, at the MATLAB command prompt, add the following initial values for the
remaining parameters:
13-23
13 MATLAB Syntax Support for States and Transitions
Parameter Value
RED 0
ORANGE 1
GREEN 2
5 Return to the model and connect the inputs and outputs to their respective ports.
Double-click the Scope block to verify that the model captures the expected feeder
behavior.
13-24
Model an Assembly Line Feeder
13-25
13 MATLAB Syntax Support for States and Transitions
The upper axis shows the LED signal which varies between orange (1), green (2), and red
(0) to indicate the current operating mode. The lower axis shows the number of parts fed
to the next assembly station, which increases incrementally until the alarm signal turns
the machine off and then resets.
In the previous example, when you use input data to represent an event, the chart wakes
up periodically and verifies whether the conditions on transitions are valid. In this case, if
ALARM == 1, then the transition to the failure state happens at the next time step.
However, creating a Stateflow chart which reacts to input events allows you to react to
the alarm signal when the event is triggered.
For details on when to use an event-based chart, see “Synchronize Model Components by
Broadcasting Events” on page 10-2.
In the event-based approach, the system attributes to consider first are the events, inputs,
and outputs.
In the following table, consider the characteristics of the event-driven Feeder Model that
are different from the system based on transition conditions.
Attributes Characteristics
Events Two asynchronous events: an alarm signal and an all-clear
signal
Inputs Three sensor readings to detect if a part has moved to a
downstream assembly station
13-26
Model an Assembly Line Feeder
The chart now has only one input port on the left and an event triggered input on the top.
For more information on how to create a Stateflow chart activated by events, see
“Activate a Stateflow Chart by Sending Input Events” on page 10-9
When the ALARM signal triggers the chart, the chart responds to the trigger in that time
step. If the current state is On when the alarm is triggered, then the current state
transitions to FailState.
13-27
13 MATLAB Syntax Support for States and Transitions
The scope output for the Event-triggered chart is in the following figure.
13-28
Model an Assembly Line Feeder
The upper axis shows the LED signal which varies between red (0), orange (1), and green
(2) to indicate the current operating mode. The lower axis shows the number of parts fed
13-29
13 MATLAB Syntax Support for States and Transitions
to the next assembly station, which increases incrementally until the alarm signal turns
the machine off and then resets. However, the event-based simulation feeds more parts to
the next assembly station due to clock and solver differences.
13-30
Use C Chart to Model Event-Driven System
Before you start building a chart, you identify system attributes by answering these
questions:
If your system has no operating modes, the system is stateless. If your system has
operating modes, the system is modal.
After identifying your system attributes, you can follow a basic work flow for building
Stateflow charts to model event-driven systems:
13-31
14
• Ease of modeling train-like state machines, where the modal logic involves transitions
from one state to its neighbor
• Concise, compact format for a state machine
• Reduced maintenance of graphical objects
When you add or remove states from a chart, you have to rearrange states, transitions,
and junctions. When you add or remove states from a state transition table, you do not
have to rearrange any graphical objects.
State transition tables support using MATLAB and C as the action language. For more
information about the differences between these action languages, see “Differences
Between MATLAB and C as Action Language Syntax” on page 13-6.
The following state transition table contains the modal logic for maintaining the
temperature of a boiler between two set points:
14-2
State Transition Tables in Stateflow
14-3
14 Tabular Expression of Modal Logic
14-4
State Transition Tables in Stateflow
• Supertransitions
• Parallel (AND) decomposition
• Local events
• Flow charts
• Use of chart-level functions (graphical, truth table, MATLAB, and Simulink)
14-5
14 Tabular Expression of Modal Logic
• Condition
• Condition action
14-6
State Transition Tables in Stateflow
• Destination state
sfnew('-STT')
14-7
14 Tabular Expression of Modal Logic
These properties are the same as those for charts that use MATLAB as the action
language. For a description of each property, see “Specify Properties for Stateflow
Charts” on page 24-3.
14-8
See Also
Stateflow incrementally updates the diagram as well. To see the most up-to-date version
of the underlying diagram, select Chart > View auto-generated diagram.
See Also
State Transition Table
More About
• “State Transition Table Operations” on page 14-10
• “Debug Run-Time Errors in a State Transition Table” on page 14-35
• “Model Bang-Bang Controller by Using a State Transition Table” on page 14-20
14-9
14 Tabular Expression of Modal Logic
To create state transition tables, use the Stateflow Editor. You can insert, edit, and move
rows and columns. You can also add history junctions and set the default state for the
state transition table.
Option Description
State Row Inserts a state at the same level of
hierarchy.
Child State Row Inserts a state as a child of the selected
state.
Default Transition Path Row Inserts a row for specifying conditional
default transition paths.
Inner Transition Path Row Inserts a row for specifying inner
transitions from the selected parent
state to its child states.
To insert a column:
1 Select Chart > Append Transition Column. A new else-if column appears to the
right of the last column.
14-10
State Transition Table Operations
To move a transition cell, click anywhere in the cell and drag the condition, action, and
destination cells as a unit to a new location. The transition cell you displace moves one
cell to the right. If column does not exist, Stateflow creates one. The state transition table
prevents you from moving cells to an invalid destination and alerts you to the problem.
1 Right-click the state in the row you want to copy and select Copy.
2 Right-click the state in the destination row and select Paste.
The new content overwrites the existing content at the destination. The state
transition table prevents you from copying content to an invalid destination.
14-11
14 Tabular Expression of Modal Logic
To redo the effects of the previous operation, select Edit + Redo or press Ctrl+Y
(Command+Y).
Zoom
To zoom in and out of your State Transition Table, select View > Zoom. You can add new
rows to your State Transition Table at the zoom level that is consistent with your chart.
When you save your model, the zoom level is saved.
See Also
More About
• “State Transition Tables in Stateflow” on page 14-2
• “Debug Run-Time Errors in a State Transition Table” on page 14-35
• “View State Reactions by Using a State Transition Matrix” on page 14-13
14-12
View State Reactions by Using a State Transition Matrix
Each row represents a state in the state transition table. Each column represents a
condition or event. To see the reaction of a state to each event or condition, scan across
the cells in a state row. To see how all states respond to an event or condition, scan down
the cells of a column.
14-13
14 Tabular Expression of Modal Logic
The order of the state rows is the same as the state transition table. The order of the
columns is based on the number of states that respond to the condition or event. The
leftmost column is the condition or event that impacts the highest number of state cells.
The rightmost column is the condition or event that impacts the fewest number of states.
The background color of the condition cell is light gray for states that do not react to the
condition in the corresponding column. When a state has no further conditions to the
right of the condition cell to follow, the condition cell is dark gray.
The execution order appears in the upper-right corner of each transition cell. The
execution order is red if it is out of order relative to the event columns. For example, in
the state Warmup, the doneWarmup condition is tested before after(10, sec). Because
the after(10, sec) column is before the doneWarmup column, the execution order for
each corresponding cell is shown in red.
If you change the state transition table, you must regenerate the state transition matrix.
14-14
See Also
If you have too many events and conditions to view at once, you can scroll through the
window horizontally. When you scroll to the right, you continue to see the state names as
an overlay on each row.
For more information about traceability and generated C/C++ code, see “Trace Stateflow
Elements in Generated Code” (Embedded Coder). For more information about traceability
and generated HDL code, see “Navigate Between Simulink Model and HDL Code by
Using Traceability” (HDL Coder).
See Also
More About
• “State Transition Tables in Stateflow” on page 14-2
• “Model Bang-Bang Controller by Using a State Transition Table” on page 14-20
14-15
14 Tabular Expression of Modal Logic
To visualize a flow of logic, you can highlight one transition cell per row in your state
transition table. Highlighting can be used to show the primary flow of logic from one state
to another or the flow that represents an error condition.
The highlighting persists across MATLAB sessions and appears in the autogenerated state
transition diagram and the state transition table.
1 In the transition table editor, right-click the transition cell and select Mark as
primary transition.
For example:
14-16
Highlight Flow of Logic in a State Transition Table
3 To view the flow in the autogenerated state diagram, select Chart > View auto-
generated diagram.
The transitions that represent the flow appear highlighted in the diagram.
14-17
14 Tabular Expression of Modal Logic
See Also
More About
• “State Transition Tables in Stateflow” on page 14-2
• “Model Bang-Bang Controller by Using a State Transition Table” on page 14-20
• “Debug Run-Time Errors in a State Transition Table” on page 14-35
14-18
State Transition Table Diagnostics
You can run diagnostic checks on a state transition table. From the Stateflow editor,
select Chart > Run Diagnostics.
The diagnostics tool statically parses the table to find errors such as:
Each error is reported with a hyperlink to the corresponding object causing the error.
These checks are also performed during simulation.
See Also
More About
• “State Transition Tables in Stateflow” on page 14-2
• “Debug Run-Time Errors in a State Transition Table” on page 14-35
• “Model Bang-Bang Controller by Using a State Transition Table” on page 14-20
14-19
14 Tabular Expression of Modal Logic
Design Requirements
This example shows how to model a bang-bang controller for temperature regulation of a
boiler, using a state transition table. The controller must turn the boiler on and off to meet
the following design requirements:
Operating Modes
14-20
Model Bang-Bang Controller by Using a State Transition Table
Data Requirements
This model contains all required Simulink blocks, except for the bang-bang controller.
14-21
14 Tabular Expression of Modal Logic
2 Delete the five output ports and the single input port.
3 Open the Library Browser by selecting View > Library Browser.
4 In the left pane of the Library Browser, select the Stateflow library, then drag a State
Transition Table block from the right pane into your boiler model.
Now you are ready to add states and hierarchy to the state transition table.
14-22
Model Bang-Bang Controller by Using a State Transition Table
a Right-click the Normal state, select Insert Row > Child State Row, and name
the new state Off.
b Repeat step a two more times to create the child states Warmup and On, in that
order.
By default, when there is ambiguity, the top exclusive (OR) state at every level of
hierarchy becomes active first. For this reason, the Normal and Off states appear
with default transitions. This configuration meets the design requirements for this
model. To set a default state, right-click the state and select Set to default.
14-23
14 Tabular Expression of Modal Logic
14-24
Model Bang-Bang Controller by Using a State Transition Table
1 In the following states, click after the state name, press Enter, and type the specified
entry actions.
14-25
14 Tabular Expression of Modal Logic
Now you are ready to specify the conditions and actions for transitioning from one state
to another state.
14-26
Model Bang-Bang Controller by Using a State Transition Table
if
[ALARM]
Alarm
During simulation:
if
[temp <= reference_low]
Warmup
During simulation, when the current temperature of the boiler drops below 23
degrees Celsius, the boiler starts to warm up.
3 In the Warmup state row, enter:
if else-if
[doneWarmup] [after(10, sec)]
{doneWarmup = true;}
On On
14-27
14 Tabular Expression of Modal Logic
During simulation, the boiler warms up for 10 seconds and then transitions to the On
state.
4 In the On state row, enter:
if
[temp >= reference_high]
Off
During simulation, when the current temperature of the boiler rises above 25 degrees
Celsius, the boiler shuts off.
5 In the Alarm state row, enter:
if
[CLEAR]
Normal
During simulation, when the all-clear condition is true, the boiler returns to normal
mode.
6 Save the state transition table.
14-28
Model Bang-Bang Controller by Using a State Transition Table
Now you are ready to add data definitions using the Symbol Wizard.
14-29
14 Tabular Expression of Modal Logic
Define Data
When you create a state transition table that uses MATLAB syntax, there are language
requirements for C/C++ code generation. One of these requirements is that you define
the size, type, and complexity of all MATLAB variables so that their properties can be
determined at compile time. Even though you have not yet explicitly defined the data in
your state transition table, you can use the Symbol Wizard. During simulation, the Symbol
Wizard alerts you to unresolved symbols, infers their properties, and adds the missing
data to your table.
• The Diagnostic Viewer indicates that you have unresolved symbols in the state
transition table.
• The Symbol Wizard attempts to resolve the missing data. The wizard correctly
infers the scope of all data except for the inputs ALARM and CLEAR.
14-30
Model Bang-Bang Controller by Using a State Transition Table
2 In the Symbol Wizard, correct the scopes of ALARM and CLEAR by selecting Input
from their Scope drop-down lists.
3 When the Model Explorer opens, verify that the Symbol Wizard added all required
data definitions correctly.
Assign: To Port:
reference_low 2
reference_high 1
temp 5
ALARM 3
14-31
14 Tabular Expression of Modal Logic
Assign: To Port:
CLEAR 4
5 Save the state transition table.
6 Close the Diagnostic Viewer and the Model Explorer.
In the Simulink model, the inputs and outputs that you defined appear in the State
Transition Table block. Now you are ready to connect these inputs and outputs to the
Simulink signals and run the model.
As the simulation runs, you can watch the animation in the state transition table
activate different states.
14-32
Model Bang-Bang Controller by Using a State Transition Table
When performing interactive debugging, you can set breakpoints on different states and
view the data values at different points in the simulation. For more information about
debugging, see “Debugging Charts” on page 32-2.
14-33
14 Tabular Expression of Modal Logic
1 In the state transition table, select Chart > View auto-generated diagram.
See Also
More About
• “State Transition Tables in Stateflow” on page 14-2
• “State Transition Table Operations” on page 14-10
• “Debug Run-Time Errors in a State Transition Table” on page 14-35
14-34
Debug Run-Time Errors in a State Transition Table
14-35
14 Tabular Expression of Modal Logic
The table has two states at the highest level in the hierarchy, Power_off and
Power_on. By default, Power_off is active. The event SWITCH toggles the system
between the Power_off and Power_on states. Power_on has three substates:
First, Second, and Third. By default, when Power_on becomes active, First also
becomes active. When Shift equals 1, the system transitions from First to
14-36
Debug Run-Time Errors in a State Transition Table
Second, Second to Third, and Third to First, for each occurrence of the event
SWITCH. Then the pattern repeats.
3 Add two inputs on page 9-2 from Simulink:
• An event called SWITCH with a scope of Input from Simulink and a Rising edge
trigger.
• A data called Shift with a scope of Input from Simulink.
4 In the model view, connect a Sine Wave block as the SWITCH event and a Step block
as the Shift data for your State Transition Table.
In the model, there is an event input and a data input. A Sine Wave block generates a
repeating input event that corresponds with the Stateflow event SWITCH. The Step
block generates a repeating pattern of 1 and 0 that corresponds with the Stateflow
data object Shift. Ideally, the SWITCH event occurs at a frequency that allows at
least one cycle through First, Second, and Third.
1 Right-click the Power_off state, and select Set Breakpoint > On State Entry.
2 Start the simulation.
14-37
14 Tabular Expression of Modal Logic
3
Move to the next step by clicking the Step In button, .
4 To see the data used and the current values, hover your cursor over the different
table cells.
Continue clicking the Step In button and watching the animating states. After each
step, watch the chart animation to see the sequence of execution. Use the tooltips to
see the data values.
Single-stepping shows that the loop from First to Second to Third inside the state
Power_on does not occur. The transition from Power_on to Power_off takes priority.
14-38
Debug Run-Time Errors in a State Transition Table
Now the transition from Power_on to Power_off does not occur until 20 seconds
have passed.
3 Begin simulation.
4 Click the Step In button repeatedly to observe the fixed behavior.
14-39
14 Tabular Expression of Modal Logic
See Also
Related Examples
• “State Transition Tables in Stateflow” on page 14-2
• “State Transition Table Diagnostics” on page 14-19
• “Model Bang-Bang Controller by Using a State Transition Table” on page 14-20
14-40
15
• Faster simulation after making small changes to a chart with many states or levels of
hierarchy.
• Reuse of the same state or subchart across multiple charts and models.
• Ease of team development for people working on different parts of the same chart.
• Manual inspection of generated code for a specific state or subchart in a chart.
An atomic subchart looks opaque and includes the label Atomic in the upper left corner.
If you use a linked atomic subchart from a library, the label Link appears in the upper left
corner.
15-2
Create Reusable Subcomponents by Using Atomic Subcharts
15-3
15 Make States Reusable with Atomic Subcharts
To create a standalone component that allows for faster debugging and code generation
workflows, convert an existing state or subchart into an atomic subchart. In your chart,
right-click a state or a normal subchart and select Group & Subchart > Atomic
Subchart. The label Atomic appears in the upper left corner of the subchart.
The conversion provides the atomic subchart with its own copy of every data object that
the subchart accesses in the chart. Local data is copied as data store memory. The scope
of other data, including input and output data, does not change.
To create a subcomponent for reuse across multiple charts and models, create a link from
a library model. Copy a chart in a library model and paste it to a chart in another model.
If the library chart contains any states, it appears as a linked atomic subchart with the
label Link in the upper left corner.
15-4
Create Reusable Subcomponents by Using Atomic Subcharts
This modeling method minimizes maintenance of similar states. When you modify the
atomic subchart in the library, your changes propagate to the links in all charts and
models.
If the library chart contains only functions and no states, then it appears a linked atomic
box in the chart. For more information, see “Reuse Functions by Using Atomic Boxes” on
page 8-35.
Converting an atomic subchart back to a state or a normal subchart removes all of its
variable mappings. The conversion merges subchart-parented data objects with the chart-
parented data to which they map.
1 If the atomic subchart is a library link, right-click the atomic subchart and select
Library Link > Disable Link.
2 To convert an atomic subchart back to a normal subchart, right-click the atomic
subchart and clear the Group & Subchart > Atomic Subchart check box.
3 To convert the subchart back to a state, right-click the subchart and clear the Group
& Subchart > Subchart check box.
4 If necessary, rearrange graphical objects in your chart.
• The atomic subchart maps a parameter to an expression other than a single variable
name. For example, mapping a parameter data1 to one of these expressions prevents
the conversion of an atomic subchart to a normal subchart:
• 3
• data2(3)
• data2 + 3
• Both of these conditions are true:
• The atomic subchart contains MATLAB functions or truth table functions that use
MATLAB as the action language.
• The atomic subchart does not map each variable to a variable of the same name in
the main chart.
15-5
15 Make States Reusable with Atomic Subcharts
Suppose that you want to test a sequence of changes in a chart that contains many states
or several levels of hierarchy.
If you do not use atomic subcharts, when you make a small change to one part of a chart
and start simulation, recompilation occurs for the entire chart. Because recompiling the
entire chart can take a long time, you decide to make several changes before testing.
However, if you find an error, you must step through all of your changes to identify the
cause of the error.
In contrast, when you modify an atomic subchart, recompilation occurs for only the
subchart and not for the entire chart. Incremental builds for simulation require less time
to recompile. This reduction in compilation time enables you to test each individual
change instead of waiting to test multiple changes at once. By testing each change
individually, you can quickly identify a change that causes an error. For more information,
see “Reduce the Compilation Time of a Chart” on page 15-43.
Suppose that you want to reuse the same state or subchart many times to facilitate large-
scale modeling.
If you do not use atomic subcharts, you have to maintain each copy of a subcomponent
manually. For example, this chart contains two states with a similar structure. The only
difference between the two states is the names of variables. If you make a change in state
A, then you must make the same change in state B.
15-6
Create Reusable Subcomponents by Using Atomic Subcharts
To enable reuse of subcomponents by using linked atomic subcharts, create a single copy
of state A and store it as a chart in a library model. From that library, copy and paste the
atomic subchart twice in your chart. Then update the mapping of subchart variables as
needed.
When you change an atomic subchart in a library, the change propagates to all library
links. For more information, see “Reuse a State Multiple Times in a Chart” on page 15-
34.
Suppose that you want to break a chart into subcomponents because multiple people are
working on different parts of the chart.
15-7
15 Make States Reusable with Atomic Subcharts
Without atomic subcharts, only one person at a time can edit the model. If someone edits
one part of a chart while someone else edits another part of the same chart, you must
merge those changes at submission time.
In contrast, you can store different parts of a chart as linked atomic subcharts. Because
atomic subcharts behave as standalone objects, different people can work on different
parts of a chart without affecting the other parts of the chart. At submission time, no
merge is necessary because the changes exist in separate models. For more information,
see “Divide a Chart into Separate Units” on page 15-45.
Suppose that you want to inspect code generated by Simulink Coder or Embedded Coder
manually for a specific part of a chart.
If you do not use atomic subcharts, you generate code for an entire model in one file. To
find code for a specific part of the chart, you have to look through the entire file.
In contrast, you can specify that the code for an atomic subchart appears in a separate
file. This method of code generation enables unit testing for a specific part of a chart. You
avoid searching through unrelated code and focus only on the code that interests you. For
more information, see “Generate Reusable Code for Unit Testing” on page 15-48.
See Also
More About
• “Encapsulate Modal Logic by Using Subcharts” on page 8-5
• “Map Variables for Atomic Subcharts and Boxes” on page 15-9
• “Modeling an Elevator System Using Atomic Subcharts”
• “Modeling a Redundant Sensor Pair Using Atomic Subcharts”
15-8
Map Variables for Atomic Subcharts and Boxes
To ensure that each variable in your atomic subchart or atomic box maps to the correct
data in the main chart, edit the mapping on the Mappings tab in the Properties dialog
box. For each atomic subchart variable, in the Main chart symbol field, you can select
the name of the corresponding symbol from the drop-down list. Alternatively, you can type
an expression specifying:
• A field of a Stateflow structure. See “Index and Assign Values to Stateflow Structures”
on page 25-8.
• An element of a vector or matrix. See “Supported Operations for Vectors and
Matrices” on page 17-11.
• Any valid combination of structure fields or matrix indices, such as
struct.field(1,2) or struct.field[0][1].
If you leave the Main chart symbol field empty, then Stateflow attempts to map the
atomic subchart variable to a main chart variable with the same name.
You can map a variable in the atomic subchart to a symbol in the main chart that has a
different scope. This table lists the possible mappings.
When you map data store memory in an atomic subchart to local data of enumerated type,
you have two options for specifying the initial value of the data store memory:
• In the Data Properties dialog box, set the Initial value field for the chart-level local
data.
15-9
15 Make States Reusable with Atomic Subcharts
• To apply the default value of the enumerated type, leave the Initial value field empty.
The chart consists of two linked atomic subcharts from the same library.
15-10
Map Variables for Atomic Subcharts and Boxes
Because the symbols in atomic subchart A have the same name as the symbols u1 and y1
in the main chart, they map to the correct variables. The symbols in atomic subchart B do
not map to the correct variables u2 and y2 in the main chart, so you must edit the
mapping.
15-11
15 Make States Reusable with Atomic Subcharts
15-12
Map Variables for Atomic Subcharts and Boxes
When you run the model again, you get these results.
The chart consists of two linked atomic subcharts from the same library. Both atomic
subcharts contain these objects.
15-13
15 Make States Reusable with Atomic Subcharts
If you simulate the model, you get an error because, in each subchart, the input u1 does
not map to any variable in the main chart. To edit the mapping for u1 in each subchart:
When you run the model again, you get these results.
15-14
Map Variables for Atomic Subcharts and Boxes
Indices can be numbers or parameters in the chart. Use of other expressions as indices is
not supported.
For example, this model contains two Sine Wave blocks that supply signals through a
diagonal matrix to a chart.
15-15
15 Make States Reusable with Atomic Subcharts
The chart consists of two linked atomic subcharts from the same library. Both atomic
subcharts contain these objects.
If you simulate the model, you get an error because, in each subchart, the input u1 does
not map to any variable in the main chart. To edit the mapping for u1 in each subchart:
When you run the model again, you get these results.
15-16
Map Variables for Atomic Subcharts and Boxes
For example, this model contains two Sine Wave blocks that supply input signals to a
chart.
15-17
15 Make States Reusable with Atomic Subcharts
The chart consists of two linked atomic subchart from the same library. Both atomic
subcharts contain these objects.
If you simulate the model, you get an error because the parameter T is undefined. To fix
this error, specify an expression for T to evaluate in the mask workspace of the main
chart:
15-18
Map Variables for Atomic Subcharts and Boxes
15-19
15 Make States Reusable with Atomic Subcharts
When you run the model again, you get these results.
15-20
Map Variables for Atomic Subcharts and Boxes
The chart contains two superstates: Active and Inactive. The Active state uses input
events to guard transitions between different substates.
15-21
15 Make States Reusable with Atomic Subcharts
1 Right-click the Active state and select Group & Subchart > Atomic Subchart.
2 Right-click the atomic subchart and select Subchart Mappings.
Under Input Event Mapping, each atomic subchart symbol maps to the correct
input event in the main chart.
The default mappings also follow the rules of using input events in atomic subcharts.
For more information, see “Rules for Using Atomic Subcharts” on page 15-29
15-22
Map Variables for Atomic Subcharts and Boxes
15-23
15 Make States Reusable with Atomic Subcharts
3 Click OK.
15-24
Map Variables for Atomic Subcharts and Boxes
15-25
15 Make States Reusable with Atomic Subcharts
3 Click OK.
See Also
More About
• “Create Reusable Subcomponents by Using Atomic Subcharts” on page 15-2
• “Reuse Functions by Using Atomic Boxes” on page 8-35
• “Index and Assign Values to Stateflow Structures” on page 25-8
• “Supported Operations for Vectors and Matrices” on page 17-11
15-26
Generate Reusable Code for Atomic Subcharts
15-27
15 Make States Reusable with Atomic Subcharts
When you generate code for your model, a separate file stores the code for linked atomic
subcharts from the same library.
When you generate code for your model, a separate file stores the code for the atomic
subchart. For more information, see “Generate Reusable Code for Unit Testing” on page
15-48.
15-28
Rules for Using Atomic Subcharts
Be sure to define data that appears in an atomic subchart explicitly in the main chart. For
instructions on how to define data in a chart, see “Add Data Through the Model Explorer”
on page 9-3.
When you use linked atomic subcharts, map the variables so that data in the subchart
corresponds to the correct data in the main chart. Map subchart variables manually if,
when you add the subchart, the variables do not have the same names as the
corresponding symbols in the main chart. For more information, see “Map Variables for
Atomic Subcharts and Boxes” on page 15-9.
Verify that the size, type, and complexity of variables in a subchart match the settings of
the corresponding variables in the main chart. For more information, see “Map Variables
for Atomic Subcharts and Boxes” on page 15-9.
If your atomic subchart contains a function call to a chart-level function, export that
function by selecting Export Chart Level Functions. Do not export graphical functions
from an atomic subchart that maps variables to variables at the main chart level with a
different scope. For more information, see “Export Stateflow Functions for Reuse” on
page 8-22.
Do not mix edge-triggered and function-call input events in the same atomic
subchart
Input events in an atomic subchart must all use edge-triggered type, or they must all use
function-call type. This restriction is consistent with the behavior for the container chart.
For more information, see “Best Practices for Using Events in Stateflow Charts” on page
10-4.
15-29
15 Make States Reusable with Atomic Subcharts
Do not map multiple input events in an atomic subchart to the same input event
in the container chart
Each input event in an atomic subchart must map to a unique input event in the container
chart. You can verify unique mappings of input events by opening the properties dialog
box for the atomic subchart and checking the Input Event Mapping section of the
Mappings tab.
Do not log signals from atomic subcharts that map variables with different
scopes
If an atomic subchart maps variables to variables at the main chart level with a different
scope, you cannot log signals for the chart.
Each input event in an atomic subchart must map to an input event of the same trigger
type in the container chart.
Moore charts do not have the same simulation behavior as Classic Stateflow charts with
the same constructs.
Do not use outgoing transitions when an atomic subchart uses top-level local
events
You cannot use outgoing transitions from an atomic subchart that uses local events at the
top level of the subchart. Using this configuration causes a simulation error.
If an entry action inside the atomic subchart requires access to a chart input or data
store memory, you might get inaccurate results. To avoid this warning, you can disable
15-30
Rules for Using Atomic Subcharts
Execute (enter) Chart At Initialization or redirect the default transition path away
from the atomic subchart.
If your chart contains atomic subcharts, do not use machine-parented data with the
following properties:
• Imported or exported
• Is 2-D or higher, or uses fixed-point type
Machine-parented data with these properties prevent reuse of generated code and other
code optimizations.
When a data store memory in an atomic subchart maps to chart-level local data, the First
index property of the local data must remain zero. If you change First index to a nonzero
value, an error occurs when you try to update the diagram.
When you use linked atomic subcharts, verify that your settings for super-step semantics
match the settings in the main chart. For more information, see “Super Step Semantics”
on page 3-73.
15-31
15 Make States Reusable with Atomic Subcharts
Atomic subcharts facilitate the reuse of states and subcharts as standalone objects.
• Chart-level data
• Chart-level graphical functions
• Input events
If the state or subchart accesses a chart-level graphical function, the chart must export
that function. For more information, see “Export Stateflow Functions for Reuse” on page
8-22.
Do not export graphical functions from an atomic subchart that maps variables to
variables at the main chart level with a different scope.
Event Broadcasts
The state or subchart that you want to convert to an atomic subchart cannot refer to:
• Local events that are outside the scope of that state or subchart
• Output events
The state or subchart you want to convert can refer to input events.
The state or subchart that you want to convert to an atomic subchart cannot access local
data where the First index property is nonzero. For the conversion process to work, the
First index property of the local data must be zero, which is the default value.
Machine-Parented Data
The state or subchart that you want to convert to an atomic subchart cannot reside in a
chart that uses machine-parented data with the following properties:
15-32
Rules for Using Atomic Subcharts
• Imported or exported
• Is 2-D or higher, or uses a fixed-point type
Machine-parented data with these properties prevent reuse of generated code and other
code optimizations.
To convert a state or subchart to an atomic subchart, your chart must use strong data
typing with Simulink inputs and outputs.
Supertransitions
The state or subchart that you want to convert to an atomic subchart cannot have any
supertransitions crossing the boundary.
You cannot use a masked library chart containing mask parameters as an atomic
subchart.
15-33
15 Make States Reusable with Atomic Subcharts
The top Sine Wave block uses a frequency of 1 radian per second, and the bottom Sine
Wave block uses a frequency of 2 radians per second. The blocks use the same amplitude
(1) and phase shift (0).
In the chart, each state uses saturator logic to convert the input sine wave to an output
square wave of the same frequency. The states perform the same actions and differ only in
the names of input and output data:
15-34
Reuse a State Multiple Times in a Chart
When you run the model, you get the following results:
15-35
15 Make States Reusable with Atomic Subcharts
Suppose that you want to reuse the contents of state A in the chart. You can convert that
state to an atomic subchart and then use multiple linked instances of that subchart in
your chart.
15-36
Reuse a State Multiple Times in a Chart
To convert state A to an atomic subchart, right-click the state and select Group &
Subchart > Atomic Subchart. State A changes to an atomic subchart:
To enable reuse of the atomic subchart you created in “Convert a State to an Atomic
Subchart” on page 15-37, store the atomic subchart in a library:
15-37
15 Make States Reusable with Atomic Subcharts
The atomic subchart appears as a standalone chart with an input and an output. This
standalone property enables you to reuse the contents of the atomic subchart.
Each linked atomic subchart appears opaque and contains the label Link in the
upper-left corner.
15-38
Reuse a State Multiple Times in a Chart
You also see warnings about unused data. These warnings appear because atomic
subchart B uses u1 and y1 instead of u2 and y2. To fix these warnings, you must edit the
mapping of input and output variables:
15-39
15 Make States Reusable with Atomic Subcharts
15-40
Reuse a State Multiple Times in a Chart
The input variable in your atomic subchart now maps to the correct input variable in
the main chart.
4 Under Output Mapping, select y2 from the drop-down list.
The output variable in your atomic subchart now maps to the correct output variable
in the main chart.
5 Click OK.
15-41
15 Make States Reusable with Atomic Subcharts
This change propagates to all linked atomic subcharts in your main chart. You do not have
to update each state individually.
15-42
Reduce the Compilation Time of a Chart
15-43
15 Make States Reusable with Atomic Subcharts
Suppose that you want to reduce the compilation time of the chart for simulation. You can
convert state A to an atomic subchart. Then you can make changes, one by one, to state A
and see how each change affects simulation results. Making one change requires
recompilation of only the atomic subchart and not the entire chart.
Side-by-side animation for the main chart and the atomic subchart occurs.
4 In the atomic subchart, change the state action for Pos to y1 = 2.
5 Restart simulation.
Recompilation occurs only for the atomic subchart and not the entire chart.
15-44
Divide a Chart into Separate Units
15-45
15 Make States Reusable with Atomic Subcharts
Suppose that you want to edit state A separately, while someone else is editing state B.
You can convert state A to an atomic subchart for storage in a library model. After
replacing state A with a linked atomic subchart, you can make changes separately in the
library. These changes propagate automatically to the chart that contains the linked
atomic subchart.
15-46
Divide a Chart into Separate Units
You can now edit state A separately from state B without any merge issues.
15-47
15 Make States Reusable with Atomic Subcharts
15-48
Generate Reusable Code for Unit Testing
Suppose that you want to generate reusable code so that you can perform unit testing on
state A. You can convert that part of the chart to an atomic subchart and then specify a
separate file to store the generated code.
15-49
15 Make States Reusable with Atomic Subcharts
5 Click OK.
1 In the Model Configuration Parameters dialog box, go to the Code Generation >
Symbols pane.
2 Set Subsystem methods to the format scheme $R$N$M$F, where:
To inspect the code for saturator.c, click the hyperlink in the report to see the
following code:
15-50
Generate Reusable Code for Unit Testing
15-51
15 Make States Reusable with Atomic Subcharts
Line 28 shows that the during function generated for the atomic subchart has the name
ex_reuse_states_A_during. This name follows the format scheme $R$N$M$F
specified for Subsystem methods:
Note The line numbers shown can differ from the numbers that appear in your code
generation report.
15-52
16
• Graphical objects grouped by type (box, function, or state) and in alphabetical order
within each group
• Chart data grouped by scope (block output or local) and in alphabetical order within
each group
For example, the following operating point illustrates the hierarchical structure of
chartStateflow objects.
c =
Contains:
The tree structure maps graphical and nongraphical objects to their respective locations
in the chart hierarchy. If name conflicts exist, one or more underscores appear at the end
of a name so that all objects have unique identifiers in the operating point hierarchy.
Stateless flow charts have an empty operating point, because they do not contain states
or persistent data.
For information about using an operating point for other blocks in a Simulink model, see
“Save and Restore Simulation Operating Point” (Simulink).
16-2
See Also
For directions, see “Divide a Long Simulation into Segments” on page 16-4.
See Also
More About
• “Divide a Long Simulation into Segments” on page 16-4
• “Methods for Interacting with the Operating Point of a Chart” on page 16-33
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-3
16 Save and Restore Simulations with Operating Point
For more information, see “Using Operating Points in Stateflow” on page 16-2.
This model simulates for 1400 seconds, but the output that interests you occurs sometime
between t = 400 and 600. You can simulate the model, save the operating point at time t
= 400, and then load that operating point for simulation between t = 400 and 600.
16-4
Divide a Long Simulation into Segments
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Select the Final states check box.
c Enter a name, such as sf_boiler_ctx01.
d Select the Save final operating point check box.
e Click Apply.
Programmatic equivalent
set_param('sf_boiler','SaveFinalState','on', ...
'FinalStateName', ['sf_boiler_ctx01'], ...
'SaveOperatingPoint','on');
Programmatic equivalent
16-5
16 Save and Restore Simulations with Operating Point
set_param('sf_boiler','StartTime','0', ...
'StopTime','400');
4 Start simulation.
When you simulate the model, you save the complete operating point at t = 400 in
the variable sf_boiler_ctx01 in the MATLAB base workspace.
5 Disable saving of an operating point.
This step prevents you from overwriting the operating point you saved in the previous
step.
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Clear the Save final operating point check box.
c Clear the Final states check box.
d Click OK.
Programmatic equivalent
set_param('sf_boiler','SaveOperatingPoint','off', ...
'SaveFinalState','off');
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Select the Initial state check box.
c Enter the variable that contains the operating point of your chart:
sf_boiler_ctx01.
d Click Apply.
Programmatic equivalent
16-6
Divide a Long Simulation into Segments
set_param('sf_boiler','LoadInitialState','on', ...
'InitialState', ['sf_boiler_ctx01']);
2 Define the new stop time for this simulation segment.
You do not need to enter a new start time because the simulation continues from
where it left off.
Programmatic equivalent
set_param('sf_boiler','StopTime','600');
16-7
16 Save and Restore Simulations with Operating Point
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Methods for Interacting with the Operating Point of a Chart” on page 16-33
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-8
Test a Unique Chart Configuration
For more information, see “Using Operating Points in Stateflow” on page 16-2.
16-9
16 Save and Restore Simulations with Operating Point
This model simulates for 30 seconds, but you want to see what happens when the value of
gear changes at t = 10. You can simulate the model, save the operating point at t = 10,
load and modify the operating point, and then simulate again between t = 10 and 20.
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Select the Final states check box.
c Enter a name, such as old_sf_car_ctx01.
d Select the Save final operating point check box.
e Click Apply.
Programmatic equivalent
set_param('old_sf_car','SaveFinalState','on', ...
'FinalStateName', 'old_sf_car_ctx01', ...
'SaveOperatingPoint','on');
16-10
Test a Unique Chart Configuration
Programmatic equivalent
set_param('old_sf_car','StartTime','0', ...
'StopTime','10');
4 Start simulation.
When you simulate the model, you save the complete operating point at t = 10 in the
variable old_sf_car_ctx01 in the MATLAB base workspace.
16-11
16 Save and Restore Simulations with Operating Point
This step prevents you from overwriting the operating point you saved in the previous
step.
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Clear the Save final operating point check box.
c Clear the Final states check box.
d Click OK.
Programmatic equivalent
Programmatic equivalent
16-12
Test a Unique Chart Configuration
Tip If the chart appears highlighted in the model window, you can specify the block
path using gcb:
c = old_sf_car_ctx01.get(gcb);
• Makes a copy of the operating point of your chart, which is stored in the final
state data of the model.
• Provides a root-level handle or reference to the copy of the operating point, which
is a hierarchical tree of graphical and nongraphical chart objects.
Each node in this tree is also a handle to a state, data, or other chart object.
Note Because the entire tree consists of object handles, the following assignment
statements do not work:
• stateCopy = c.state
• dataCopy = c.data
• operatingPointCopy = c
These assignments create copies of the object handles, not operating point values.
The only way to copy operating point values is to use the clone method. For details,
see “Methods for Interacting with the Operating Point of a Chart” on page 16-33
and “Rules for Using the Operating Point of a Chart” on page 16-38.
3 Look at the contents of the operating point.
c =
Contains:
16-13
16 Save and Restore Simulations with Operating Point
The operating point of your chart contains a list of states and data in hierarchical
order.
4 Highlight the states that are active in your chart at t = 10.
Tip To check if a single state is active, you can use the isActive method. For
example, type:
c.gear_state.fourth.isActive
This command returns true (1) when a state is active and false (0) otherwise. For
information on other methods, see “Methods for Interacting with the Operating Point
of a Chart” on page 16-33.
5 Change the active substate of selection_state to downshifting.
16-14
Test a Unique Chart Configuration
c.selection_state.downshifting.setActive;
When you type c.gear at the command prompt, you see a list of data properties
similar to this:
>> c.gear
ans =
16-15
16 Save and Restore Simulations with Operating Point
c.gear.Value = 1;
However, you cannot change the data type or size of gear. Also, you cannot specify a
new value that falls outside the range set by the Minimum and Maximum
parameters. For details, see “Rules for Modifying Data Values” on page 16-38 .
7 Save the modified operating point.
You do not need to enter a new start time because the simulation continues from
where it left off.
Programmatic equivalent
set_param('old_sf_car','StopTime','20');
2 Start simulation.
16-16
See Also
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Methods for Interacting with the Operating Point of a Chart” on page 16-33
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-17
16 Save and Restore Simulations with Operating Point
For more information, see “Using Operating Points in Stateflow” on page 16-2.
The Mode Logic chart monitors the status of actuators for two elevators. Each elevator
has an outer (primary) actuator and an inner (secondary) actuator. In normal operation,
the outer actuators are active and the inner actuators are on standby.
16-18
Test a Chart with Fault Detection and Redundant Logic
When the four actuators are working correctly, the left and right elevators reach steady-
state positions in 3 seconds.
16-19
16 Save and Restore Simulations with Operating Point
Suppose that you want to see what happens at t = 3 when at least one actuator fails. You
can simulate the model, save the operating point at t = 3, load and modify the operating
point, and then simulate again between t = 3 and 10.
16-20
Test a Chart with Fault Detection and Redundant Logic
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Select the Final states check box.
c Enter a name, such as xFinal.
d Select the Save final operating point check box.
e Click Apply.
Programmatic equivalent
set_param('sf_aircraft','SaveFinalState','on', ...
'FinalStateName', ['xFinal'], ...
'SaveOperatingPoint','on');
16-21
16 Save and Restore Simulations with Operating Point
Programmatic equivalent
When you simulate the model, you save the complete operating point at t = 3 in the
variable xFinal in the MATLAB base workspace.
5 Disable saving of an operating point.
This step prevents you from overwriting the operating point you saved in the previous
step.
a Open the Model Configuration Parameters dialog box and go to the Data
Import/Export pane.
b Clear the Save final operating point check box.
c Clear the Final states check box.
d Click OK.
Programmatic equivalent
16-22
Test a Chart with Fault Detection and Redundant Logic
Programmatic equivalent
set_param('sf_aircraft','LoadInitialState','on', ...
'InitialState', ['xFinal']);
2 Define an object handle for the operating point values of the Mode Logic chart.
Tip If the chart appears highlighted in the model window, you can specify the block
path using gcb:
c = xFinal.get(gcb);
• Makes a copy of the operating point of your chart, which is stored in the final
state data of the model.
• Provides a root-level handle or reference to the copy of the operating point, which
is a hierarchical tree of graphical and nongraphical chart objects.
Each node in this tree is also a handle to a state, data, or other chart object.
Note Because the entire tree consists of object handles, the following assignment
statements do not work:
• stateCopy = c.state
• dataCopy = c.data
• operatingPointCopy = c
These assignments create copies of the object handles, not operating point values.
The only way to copy operating point values is to use the clone method. For details,
16-23
16 Save and Restore Simulations with Operating Point
see “Methods for Interacting with the Operating Point of a Chart” on page 16-33
and “Rules for Using the Operating Point of a Chart” on page 16-38.
3 Look at the contents of the operating point.
c =
Contains:
The operating point of your chart contains a list of states, functions, and data in
hierarchical order.
4 Highlight the states that are active in your chart at t = 3.
c.highlightActiveStates;
Active states appear highlighted. By default, the two outer actuators are active and
the two inner actuators are on standby.
16-24
Test a Chart with Fault Detection and Redundant Logic
Tip To check if a single state is active, you can use the isActive method. For
example, type:
c.Actuators.LI.L1.Standby.isActive
This command returns true (1) when a state is active and false (0) otherwise. For
information on other methods, see “Methods for Interacting with the Operating Point
of a Chart” on page 16-33.
5 Change the state activity in the chart to reflect one actuator failure.
Assume that the left outer (LO) actuator fails. To change the state, use this command:
c.Actuators.LO.Isolated.setActive;
16-25
16 Save and Restore Simulations with Operating Point
The setActive method ensures that the chart exits and enters the appropriate
states to maintain state consistency. However, the method does not perform entry
actions for the newly active substate. Similarly, the method does not perform exit
actions for the previously active substate.
6 Save the modified operating point by using this command:
16-26
Test a Chart with Fault Detection and Redundant Logic
You do not need to enter a new start time because the simulation continues from
where it left off.
Programmatic equivalent
set_param('sf_aircraft','StopTime','10');
2 Start simulation.
Chart animation shows that the other three actuators react appropriately to the
failure of the left outer (LO) actuator.
16-27
16 Save and Restore Simulations with Operating Point
16-28
Test a Chart with Fault Detection and Redundant Logic
Assume that the left inner (LI) actuator also fails. To change the state, use this
command:
16-29
16 Save and Restore Simulations with Operating Point
c.Actuators.LI.Isolated.setActive;
2 Save the modified operating point by using this command:
Because of failures in both actuators, the left elevator stops working. The right
elevator maintains a steady-state position.
16-30
Test a Chart with Fault Detection and Redundant Logic
If you modify the operating point of your chart to test the response of the right elevator to
actuator failures, you get similar results.
16-31
16 Save and Restore Simulations with Operating Point
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Methods for Interacting with the Operating Point of a Chart” on page 16-33
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-32
Methods for Interacting with the Operating Point of a Chart
For more information, see “Using Operating Points in Stateflow” on page 16-2.
You can use the following methods to interact with the operating point of a chart. Assume
that ch is a handle to the operating point of your chart, which you obtain using the get
method.
16-33
16 Save and Restore Simulations with Operating Point
For nongraphical
objects, highlights
the object in the
Model Explorer.
Note For
persistent data in
MATLAB
functions, this
method opens the
function editor
and highlights the
persistent data at
the exact line in
the script.
16-34
Methods for Interacting with the Operating Point of a Chart
• If a state is
inactive, no
substates are
active.
• If a state with
parallel
decomposition
is active, all
substates are
active.
• If a state with
exclusive
decomposition
is active, only
one substate is
active.
Chart clone Copies the entire newOperatingPoint = ch.clone
chart operating
point to a new
variable.
Chart highlightActiveState Highlights all ch.highlightActiveStates
s active states in
the Stateflow
Editor.
Chart isStateConsistent Returns true (1) if ch.isStateConsistent
all states pass a
consistency check
and false (0)
otherwise.
16-35
16 Save and Restore Simulations with Operating Point
16-36
See Also
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Divide a Long Simulation into Segments” on page 16-4
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-37
16 Save and Restore Simulations with Operating Point
For more information, see “Using Operating Points in Stateflow” on page 16-2.
• Machine-parented data
• Persistent data in custom C code
• Persistent data in external MATLAB code
• You cannot change the data type or size. Scalar data must remain scalar. Vector and
matrix data must keep the same dimensions. The only exception to this rule is
Stateflow data of ml type (see “ml Data Type” on page 12-37 for details).
• For enumerated data types, you can choose only enumerated values from the type
definition. For other data types, new values must fall within the range that you specify
in the Minimum and Maximum parameters.
• Use one-based indexing to define rows and columns of a matrix.
Suppose that you want to change the value of an element in a 21-by-12 matrix. To
modify the element in the first row and second column, type:
c.state_name.data_name.Value(1,2) = newValue;
16-38
Rules for Using the Operating Point of a Chart
If you want these state actions to occur, you must execute them separately. For
example, if your state actions assign values to data, you must assign the values
explicitly.
• The setActive method tries to maintain state consistency by:
16-39
16 Save and Restore Simulations with Operating Point
Suppose that you obtain a handle to the operating point of your chart using these
commands:
blockpath = 'model/chart';
c = xFinal.get(modelOperatingPoint, blockpath);
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Divide a Long Simulation into Segments” on page 16-4
• “Best Practices for Saving the Operating Point of a Chart” on page 16-41
16-40
Best Practices for Saving the Operating Point of a Chart
For more information, see “Using Operating Points in Stateflow” on page 16-2.
save('sf_car_ctx01.mat', 'sf_car_ctx01')
For example, to reuse the commands in “Divide a Long Simulation into Segments” on
page 16-4, you can store them in a script named
sf_boiler_operatingpoint_commands.m:
% Specify the start and stop times for the simulation segment.
16-41
16 Save and Restore Simulations with Operating Point
set_param('sf_boiler','StartTime','0','StopTime','400');
The start time does not change, but the operating point restore fast forwards the
simulation to the time of the snapshot.
See Also
More About
• “Using Operating Points in Stateflow” on page 16-2
• “Divide a Long Simulation into Segments” on page 16-4
• “Rules for Using the Operating Point of a Chart” on page 16-38
16-42
17
For examples, see “Find Patterns in Data Transmission by Using Vectors” on page 17-16
and “Calculate Motion by Using Matrices” on page 17-18.
• Charts
• Subcharts
• States
• Functions
• Input data
• Output data
• Local data
• Function inputs
• Function outputs
• State actions
• Transition actions
• MATLAB functions
• Truth table functions
• Graphical functions
17-2
Vectors and Matrices in Stateflow Charts
• Simulink functions
• Change detection operators
For more information, see “Supported Operations for Vectors and Matrices” on page 17-
11 and “Rules for Vectors and Matrices in Stateflow Charts” on page 17-3.
If you define a vector or matrix with ml base type, an error message appears when you try
to simulate your model. This base type supports only scalar data.
For more information about this type, see “ml Data Type” on page 12-37.
Use only real numbers to set initial values of vectors and matrices
When you set the initial value for an element of a vector or matrix, use a real number. If
you use a complex number, an error message appears when you try to simulate your
model.
Note You can set values of vectors and matrices to complex numbers after initialization.
You cannot use a vector or matrix as an argument for temporal logic operators, because
time is a scalar quantity.
17-3
17 Vectors and Matrices in Stateflow Charts
For example, suppose that you want to perform standard matrix operations on two square
matrices during simulation. Follow these steps:
17-4
Vectors and Matrices in Stateflow Charts
When you index a vector, you can use the temporalCount operator to avoid using an
extra variable for the index counter. This indexing method works for vectors that contain
real or complex data.
For example, suppose that you want to collect input data in a buffer during simulation.
Follow these steps:
The state Collect_Data stores data in the vector y, which is of size 10. The entry
action assigns the value of input data u to the first element of y. The during action
assigns the next nine values of input data to successive elements of the vector y until
you store ten elements.
2 Add the input data u to the chart.
a In the Stateflow Editor, select Chart > Add Inputs & Outputs > Data Input
From Simulink.
b In the Data properties dialog box, enter u in the Name field.
c Click OK.
3 Add the output data y to the chart.
a In the Stateflow Editor, select Chart > Add Inputs & Outputs > Data Output
To Simulink.
b In the Data properties dialog box, enter y in the Name field.
c Enter 10 in the Size field.
d Click OK.
17-5
17 Vectors and Matrices in Stateflow Charts
Note You do not need to set initial values for this output vector. By default, all
elements initialize to 0.
For information about the temporalCount operator, see “Control Chart Execution by
Using Temporal Logic” on page 12-49.
See Also
More About
• “Add Vector and Matrix Data” on page 17-7
• “Supported Operations for Vectors and Matrices” on page 17-11
• “Convert Scalars to Nonscalars by Using Scalar Expansion” on page 17-9
17-6
Add Vector and Matrix Data
Note Vectors cannot have the base type ml. See “Rules for Vectors and Matrices in
Stateflow Charts” on page 17-3.
4 Set initial values for the vector.
• If initial values of all elements are the same, enter a real number in the Initial
value field. This value applies to all elements of a vector of any size.
• If initial values differ, enter real numbers in the Initial value field. For example,
you can enter:
[1; 3; 5; 7]
Tip If you want to initialize all elements of a vector to 0, do nothing. When no values
are explicitly defined, all elements initialize to 0.
5 Click Apply.
Define a Matrix
Define a matrix in a Stateflow chart as follows:
1 Add data to your chart as described in “Add Stateflow Data” on page 9-2.
2 In the General pane of the Data properties dialog box, enter the dimensions of the
matrix in the Size field.
17-7
17 Vectors and Matrices in Stateflow Charts
3 Specify the name, base type, and other properties for the new data.
Note Matrices cannot have the base type ml. See “Rules for Vectors and Matrices in
Stateflow Charts” on page 17-3.
4 Set initial values for the matrix.
• If initial values of all elements are the same, enter a real number in the Initial
value field. This value applies to all elements of a matrix of any size.
• If initial values differ, enter real numbers in the Initial value field. For example,
you can enter:
[1 2 3; 4 5 6; 7 8 9]
Tip If you want to initialize all elements of a matrix to 0, do nothing. When no values
are explicitly defined, all elements initialize to 0.
5 Click Apply.
See Also
More About
• “Vectors and Matrices in Stateflow Charts” on page 17-2
• “Supported Operations for Vectors and Matrices” on page 17-11
• “Convert Scalars to Nonscalars by Using Scalar Expansion” on page 17-9
17-8
Convert Scalars to Nonscalars by Using Scalar Expansion
A = 1;
Scalar expansion is supported only in Stateflow charts that use C as the action language.
For functions with multiple outputs, the same rules apply except for the case where the
outputs and inputs of the function call are all vectors or matrices. In this case, scalar
expansion does not occur, and an error message alerts you to a size mismatch.
The rules of scalar expansion apply to all functions that you use in Stateflow charts:
• MATLAB functions
• Graphical functions
• Simulink functions
• Truth table functions
17-9
17 Vectors and Matrices in Stateflow Charts
See Also
More About
• “Vectors and Matrices in Stateflow Charts” on page 17-2
• “Add Vector and Matrix Data” on page 17-7
• “Supported Operations for Vectors and Matrices” on page 17-11
17-10
Supported Operations for Vectors and Matrices
•
MATLAB as the action language.
•
C as the action language.
For more information, see “Differences Between MATLAB and C as Action Language
Syntax” on page 13-6.
Indexing Notation
In charts that use MATLAB as the action language, refer to elements of a vector or matrix
by using one-based indexing delimited by parentheses. Separate indices for different
dimensions with commas.
In charts that use C as the action language, refer to elements of a vector or matrix by
using zero-based indexing delimited by brackets. Enclose indices for different dimensions
in their own pair of brackets.
17-11
17 Vectors and Matrices in Stateflow Charts
Binary Operations
This table summarizes the interpretation of all binary operations on vector and matrix
operands according to their order of precedence (1 = highest, 3 = lowest). Binary
operations are left associative so that, in any expression, operators with the same
precedence are evaluated from left to right. Except for the matrix multiplication and
division operators in charts that use MATLAB as the action language, all binary operators
perform element-wise operations.
17-12
Supported Operations for Vectors and Matrices
Assignment Operations
This table summarizes the interpretation of assignment operations on vector and matrix
operands.
17-13
17 Vectors and Matrices in Stateflow Charts
You can assign a value to an individual entry of a vector or matrix by using the syntax
appropriate to the action language of the chart.
In charts that use MATLAB as the action language, you can specify all of the elements of a
vector or matrix in a single statement. For example, this action assigns each element of
the 2-by-3 matrix A to a different value:
A = [1 2 3; 4 5 6];
In charts that use C as the action language, you can use scalar expansion to set all of the
elements of a vector or matrix to the same value. For example, this action sets all of the
elements of the matrix A to 10:
A = 10;
Charts that use MATLAB as the action language do not support scalar expansion. For
more information, see “Convert Scalars to Nonscalars by Using Scalar Expansion” on
page 17-9.
17-14
See Also
See Also
More About
• “Vectors and Matrices in Stateflow Charts” on page 17-2
• “Add Vector and Matrix Data” on page 17-7
• “Convert Scalars to Nonscalars by Using Scalar Expansion” on page 17-9
17-15
17 Vectors and Matrices in Stateflow Charts
For details of how the chart works, see “Detect Valid Transmission Data Using Frame
Synchronization” on page 23-15.
17-16
See Also
See Also
More About
• “Vectors and Matrices in Stateflow Charts” on page 17-2
• “Add Vector and Matrix Data” on page 17-7
• “Supported Operations for Vectors and Matrices” on page 17-11
• “Convert Scalars to Nonscalars by Using Scalar Expansion” on page 17-9
17-17
17 Vectors and Matrices in Stateflow Charts
17-18
Calculate Motion by Using Matrices
17-19
17 Vectors and Matrices in Stateflow Charts
17-20
Calculate Motion by Using Matrices
17-21
17 Vectors and Matrices in Stateflow Charts
4 Click a different spot to specify the initial velocity of the cue ball.
17-22
See Also
See Also
More About
• “Vectors and Matrices in Stateflow Charts” on page 17-2
• “Add Vector and Matrix Data” on page 17-7
• “Supported Operations for Vectors and Matrices” on page 17-11
17-23
18
Stateflow charts exchange variable-size data with other charts and blocks in their models
through MATLAB functions, Simulink functions, and truth tables that use MATLAB as the
action language. You pass variable-size data to these functions as chart-level inputs and
outputs from state actions and transition logic. However, you must perform all
computations with variable-size data inside the functions, not directly in states or
transitions. For more information about the functions that interact with variable-size,
chart-level inputs and outputs, see:
After enabling support at the chart level, you can declare variable-size inputs and outputs.
18-2
Declare Variable-Size Data in Stateflow Charts
For example, this specification declares a variable-size input data that inherits its
Size and Type from the Simulink model. To specify a 2-D matrix where the upper
bounds are 2 for the first dimension and 4 for the second dimension, in the Size field,
enter [2 4] instead.
18-3
18 Variable-Size Data in Stateflow Charts
You can pass the data as inputs and outputs to MATLAB and Simulink functions in your
chart from state actions and transition logic. MATLAB functions can also access the
chart-level, variable-size data directly. For more information, see “Compute Output
Based on Size of Input Signal” on page 18-5.
See Also
More About
• “Compute Output Based on Size of Input Signal” on page 18-5
• “Reuse MATLAB Code by Defining MATLAB Functions” on page 28-2
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Reuse Combinatorial Logic by Defining Truth Tables” on page 27-2
18-4
Compute Output Based on Size of Input Signal
In this model, one Stateflow chart, VarSizeSignalSource, uses temporal logic to generate
a variable-size signal. A second chart, SizeBasedProcessing, computes the output based
on the size of the signal generated by the first chart.
18-5
18 Variable-Size Data in Stateflow Charts
VarSizeSignalSource Chart
The VarSizeSignalSource chart uses temporal logic to transition between three states.
Each state generates a different size output.
18-6
Compute Output Based on Size of Input Signal
The chart works like a source block. It has no input and one variable-size output y.
18-7
18 Variable-Size Data in Stateflow Charts
For variable-size outputs, you must explicitly specify the size and upper bound for each
dimension. In this case, y is a vector whose length has an upper bound of 16.
Because states or transitions cannot read from or write to variable-size data, y does not
appear in any state actions or transition logic. All computations involving variable-size
data must occur in MATLAB functions in the chart.
18-8
Compute Output Based on Size of Input Signal
MATLAB functions access variable-size, chart-level data directly. You do not pass the data
as inputs or outputs to the functions. In this chart, the generateOutput function
constructs the variable-size output vector y as a number sequence based on the input it
receives.
function generateOutput(len)
%#codegen
assert(len<=16);
y = (1:len)';
MATLAB functions must be able to determine the upper bounds of variable-size data at
compile time. In this case, however, the upper bound is len, an input for which the model
computes the value at run time. To provide this information, the assert function
specifies an explicit upper bound for len that matches the upper bound specified for the
chart output y.
SizeBasedProcessing Chart
18-9
18 Variable-Size Data in Stateflow Charts
18-10
Compute Output Based on Size of Input Signal
As in the chart VarSizeSignalSource, variable-size data does not appear in state actions or
transition logic. Instead, states call MATLAB functions to compute the variable-size
output. Transitions call a MATLAB function in a conditional statement to evaluate the
variable-size input.
18-11
18 Variable-Size Data in Stateflow Charts
This function tests whether chart input u, the signal generated by chart
VarSizeSignalSource, is a scalar or vector value:
If input u is a vector, this function outputs the sine of each of its values:
function computeOutput
%#codegen
y = sin(u);
function resetOutput
%#codegen
y = 0;
1 Open the model. The tabs along the top of the Editor canvas enable you to switch
between the Simulink model and the two Stateflow charts.
2 Start simulation from the VarSizeSignalSource chart. The chart animation shows the
active state cycling between the Scalar, VectorPartial, and VectorFull states.
3 Change tabs to view the SizeBasedProcessing chart. The chart animation shows the
active state alternating between the Scalar and Vector states.
4 Change tabs to return to the Simulink model. The display blocks periodically show 1,
8, and 16 values from the variable-size vectors.
See Also
More About
• “Declare Variable-Size Data in Stateflow Charts” on page 18-2
18-12
19
The enumerated data output is restricted to a finite set of values. You can refer to these
values by their names: Red, Yellow, and Green.
19-2
Reference Values by Name by Using Enumerated Data
This MATLAB file defines the enumerated data type BasicColors referenced by the
chart.
Example Description
a = exp Assignment of a to exp, which must evaluate to an enumerated value
a == b Comparison, equality
a != b Comparison, inequality
Prefixed Identifiers
To prevent name conflicts when referring to enumerated values in Stateflow charts, you
can use prefixed identifiers of the form Type.Name. Type is an enumerated data type and
Name is an enumerated value name. For example, suppose that you define three data
types (Colors, Temp, and Code) that contain the enumerated name Red. By using
prefixed notation, you can distinguish Colors.Red from Temp.Red and Code.Red.
19-3
19 Enumerated Data in Charts
Nonprefixed Identifiers
To minimize identifier length when referring to unique enumerated values, you can use
nonprefixed enumerated value names. For example, suppose that the enumerated name
Red belongs only to the data type Colors. You can then refer to this value with the
nonprefixed identifier Red.
If your chart uses data types that contain identical enumerated names (such as
Colors.Red and Temp.Red), use prefixed identifiers to prevent name conflicts.
• Chart
• Subchart
• State
• State actions
• Condition and transition actions
• Vector and matrix indexing
• MATLAB functions
• Graphical functions
• Simulink functions
• Truth Table blocks and truth table functions
If you have Simulink Coderinstalled, you can use enumerated data for simulation and
code generation.
See Also
More About
• “Define Enumerated Data Types” on page 19-6
19-4
See Also
19-5
19 Enumerated Data in Charts
Before you can add enumerated data to a Stateflow chart, you must define an enumerated
data type in a MATLAB class definition file. Create a different file for each enumerated
type.
The classdef section defines an enumerated data type with the name
BasicColors. Stateflow derives the data type from the built-in type
Simulink.IntEnumType. The enumerated data type name must be unique among
data type names and workspace variable names.
19-6
Define Enumerated Data Types
An enumerated type can define any number of values. The enumeration section lists
the set of enumerated values that this data type allows. Each enumerated value
consists of a name and an underlying integer value. Each name must be unique
within its type, but can also appear in other enumerated types. The default value is
the first one in the list, unless you specify otherwise in the methods section of the
definition.
4 (Optional) Customize the data type by using a methods section. The section can
contain these methods:
• getDefaultValue specifies a default enumerated value other than the first one
in the list of allowed values.
• getDescription specifies a description of the data type for code generated by
Simulink Coder.
• getHeaderFile specifies custom header file that contains the enumerated type
definition in code generated by Simulink Coder.
• getDataScope enables exporting or importing the enumerated type definition to
or from a header file in code generated by Simulink Coder.
• addClassNameToEnumNames enhances readability and prevents name conflicts
with identifiers in code generated by Simulink Coder.
For example, this MATLAB file presents a customized definition for the enumerated
data type BasicColors that:
• Specifies that the default enumerated value is the last one in the list of allowed
values.
• Includes a short description of the data type for code generated by Simulink
Coder.
• Imports the definition of the data type from a custom header file to prevent
Simulink Coder from generating the definition.
19-7
19 Enumerated Data in Charts
• Adds the name of the data type as a prefix to each enumeration member name in
code generated by Simulink Coder.
19-8
See Also
retVal = true;
end % function
end % methods
end % classdef
5 Save the file on the MATLAB path. The name of the file must match exactly the name
of the data type. For example, the definition for the data type BasicColors must
reside in a file named BasicColors.m.
Tip To add a folder to the MATLAB search path, type addpath pathname at the
command prompt.
See Also
More About
• “Assign Enumerated Values in a Chart” on page 19-15
• “Model Media Player by Using Enumerated Data” on page 19-20
• “Best Practices for Using Enumerated Data” on page 19-10
• “Use Enumerated Data in Simulink Models” (Simulink)
• “Customize Simulink Enumeration” (Simulink)
19-9
19 Enumerated Data in Charts
To avoid name conflicts, the name of an enumerated data type cannot match the name of
another data type or a variable in the MATLAB base workspace.
Use Same Name for Enumerated Type and Class Definition File
To enable resolution of enumerated data types for Simulink models, the name of the
MATLAB file that contains the type definition must match the name of the data type.
When you update an enumerated data type definition for an open model, the changes do
not take effect immediately. To see the effects of updating a data type definition:
1 Save and close the model.
2 Delete all instances of the data type from the MATLAB base workspace. To find these
instances, type whos at the command prompt.
3 Open the model and start simulation or generate code by using Simulink Coder.
If you use nonprefixed identifiers to refer to enumerated values in a chart, ensure that
each enumerated name belongs to a unique enumerated data type.
19-10
Best Practices for Using Enumerated Data
If an enumerated value uses the same identifier as a data object or a bus field, the chart
does not resolve the identifier correctly. For example, this diagram shows the stages in
which a chart tries to resolve the identifier Colors.Red.
19-11
19 Enumerated Data in Charts
19-12
Best Practices for Using Enumerated Data
If you choose to set an initial value for enumerated data, you must use a prefixed
identifier in the Initial value field of the Property Inspector. For example,
BasicColors.Red is a valid identifier, but Red is not. The initial value must evaluate to a
valid MATLAB expression.
If you add prefixes to enumerated names in the generated code, you enhance readability
and avoid name conflicts with global symbols. For details, see “Use Enumerated Data in
Generated Code” (Simulink Coder).
For enumerated data, leave the Minimum and Maximum fields of the Property Inspector
empty. The chart ignores any values that you enter in these fields.
Whether these fields appear in the Property Inspector depends on which Type field option
you use to define enumerated data.
Because enumerated values are constants, assigning these values to constant data is
redundant and unnecessary. If you try to assign enumerated values to constant data, an
error appears.
19-13
19 Enumerated Data in Charts
See Also
More About
• “Reference Values by Name by Using Enumerated Data” on page 19-2
• “Define Enumerated Data Types” on page 19-6
• “Assign Enumerated Values in a Chart” on page 19-15
• “Model Media Player by Using Enumerated Data” on page 19-20
19-14
Assign Enumerated Values in a Chart
Chart Behavior
This example shows how to build a chart that uses enumerated values to issue a status
keyword.
Execution of State A
19-15
19 Enumerated Data in Charts
Execution of State B
1 To create a Simulink model with an empty chart, at the MATLAB command prompt,
enter sfnew.
2 In the empty chart, add states A and B. At the text prompt, enter the appropriate
action statements.
3 Add a default transition to state A and transitions between states A and B.
4 Double-click each transition. At the text prompt, enter the appropriate condition.
1 To create a file in which to store the data type definition, from the Home tab on the
MATLAB toolstrip, select New > Class.
2 In the MATLAB Editor, enter:
19-16
Assign Enumerated Values in a Chart
1 To resolve the undefined data, in the Symbols window, click the Resolve undefined
symbols icon . The Stateflow Editor assigns an appropriate scope to each symbol
in the chart.
Symbol Scope
color Output Data
y Local Data
GREEN Parameter Data
RED Parameter Data
2 To specify color as enumerated data, in the Property Inspector:
• In the Type field, select Enum: <class name>. Replace <class name> with
TrafficColors, the name of the data type that you defined previously.
• Under Logging, select the Log signal data check box.
3 To set the scope and type of y, in the Property Inspector:
19-17
19 Enumerated Data in Charts
3 To access the logged data in the MATLAB workspace, call the signal logging object
logsout. For example, at the command prompt, enter:
A = table(logsout.getElement('color').Values.Time, ...
logsout.getElement('color').Values.Data);
A.Properties.VariableNames = {'SimulationTime','Color'};
A
19-18
See Also
A =
9×2 table
SimulationTime Color
______________ _____
0 RED
1.6 GREEN
2.8 RED
4 GREEN
5.2 RED
6.4 GREEN
7.6 RED
8.8 GREEN
10 RED
See Also
More About
• “Define Enumerated Data Types” on page 19-6
• “Model Media Player by Using Enumerated Data” on page 19-20
• “Best Practices for Using Enumerated Data” on page 19-10
• “Access Signal Logging Data” on page 32-54
• “View Data with the Simulation Data Inspector” (Simulink)
19-19
19 Enumerated Data in Charts
19-20
Model Media Player by Using Enumerated Data
This model uses two enumerated data types: RadioRequestMode and CdRequestMode.
By grouping related values into separate data types:
19-21
19 Enumerated Data in Charts
In the model, the Display blocks show the default settings of the media player.
19-22
Model Media Player by Using Enumerated Data
2 In the Radio Request section, click CD. The Display blocks for enumerated data RR
and CurrentRadioMode change from OFF to CD.
3 Click Insert Disc. The Display block for enumerated data CdStatus changes from
EMPTY to DISCINSERT to STOP.
4 In the CD Request section, click the PLAY. The Display blocks for enumerated data
CR, MechCmd, and CdStatus change from STOP to PLAY.
5 To see other changes in the Display blocks, use the CD Player Helper to select other
operating modes for the media player.
UserRequest Chart
This chart reads user inputs from the CD Player Helper and stores the information as
output data.
19-23
19 Enumerated Data in Charts
Chart Behavior
The chart calls the function sfcdplayerhelper on the MATLAB path, reads your
interaction with the UI, and stores it as output data.
CdPlayerModeManager Chart
This chart activates the appropriate subcomponent of the media player depending on the
inputs received from the UserRequest chart.
19-24
Model Media Player by Using Enumerated Data
19-25
19 Enumerated Data in Charts
Chart Behavior
At the start of simulation, the ModeManager state becomes active. If the Boolean data
DiscEject is 1 (or true), a transition to the Eject state occurs, followed by a transition
back to the ModeManager state.
In the ON substate, three subcharts represent the operating modes of the media player:
CD player, AM radio, and FM radio. Each subchart corresponds to a different value of
enumerated data RadioReq. The inner transition inside the ON state continually scans for
changes in the value of RadioReq.
19-26
Model Media Player by Using Enumerated Data
CdPlayerBehaviorModel Chart
This chart activates the appropriate operating mode for the CD player depending on the
input received from the CdPlayerBehaviorModel chart.
19-27
19 Enumerated Data in Charts
19-28
See Also
• after temporal logic operator to control timing of transitions during disc insertion
and ejection
Chart Behavior
If the Boolean data DiscInsert is 1 (or true), a transition to the Inserting state
occurs. After a short time delay, a transition to the DiscPresent state occurs.
The DiscPresent state remains active until the data CMD becomes EJECT. At that point,
a transition to the Ejecting state occurs. After a short time delay, a transition to the
Empty state occurs.
Whenever a state transition occurs, the enumerated data CdStatus changes value to
reflect the status of the CD player.
See Also
More About
• “Reference Values by Name by Using Enumerated Data” on page 19-2
19-29
19 Enumerated Data in Charts
19-30
20
To specify a string symbol, set its Type field to string. Stateflow dynamically allocates
memory space for this type of data.
Alternatively, you can create string data with a maximum number of characters. To
specify a string symbol with a buffer size of n characters, set its Type field to
stringtype(n). The text of the string can be shorter than the buffer, but if it exceeds
the buffer size, then the text in the string is truncated. For instance, if the symbol output
in the previous chart is specified as stringtype(10), then its value in the state On is
truncated to "All system". Depending on the configuration parameter String
truncation checking, you can halt simulation and diagnose truncation of string data.
20-2
Manage Textual Information by Using Strings
Note Unlike C or C++, Stateflow interprets escape sequences as literal characters. For
example, the string "\n" contains two characters, backslash and n, and not a newline
character.
s1 = 'hello';
s2 = "good bye";
strcpy(dest,src An alternative way to execute Assigns string data to
) dest = src. s3 and s4:
strcpy(s3,'howdy');
strcpy(s4,"so long");
strcat dest = Concatenates strings Concatenates strings to
strcat(s1,...,s s1,...,sN. form "Stateflow":
N)
s1 = "State";
s2 = "flow";
dest = strcat(s1,s2);
substr dest = Returns the substring of Extracts substring
substr(str,i,n) length n starting at the i-th "Stateflow" from a
character of string str. Use longer string:
zero-based indexing.
str = "Stateflow rule the waves
dest = substr(str,0,9);
20-3
20 String Data in Charts
dest = tostring(1.2345);
dest = tostring(1==1);
Converts enumerated
value to string "RED":
dest = tostring(RED);
20-4
Manage Textual Information by Using Strings
20-5
20 String Data in Charts
If str2double cannot
convert text to a number,
then it returns a NaN value.
str2asci A = Returns array of type uint8 Returns uint8 array
i str2ascii(str,n containing ASCII values for {72,101,108,108,11
) the first n characters in str, 1}:
where n is a positive integer.
Use of variables or A = str2ascii("Hello",5);
expressions for n is not
supported.
20-6
See Also
• Chart
• Subchart
• State
• State actions
• Condition and transition actions
• Graphical functions
• Simulink functions
• Truth table functions that use C as the action language
If you have Simulink Coder installed, you can use string data for simulation and code
generation.
See Also
ascii2str | str2ascii | str2double | strcat | strcmp | strcpy | strlen | substr | tostring
More About
• “Log String Data to the Simulation Data Inspector” on page 20-9
• “Send Messages with String Data” on page 20-14
• “Share String Data with Custom C Code” on page 20-17
• “Simulate a Media Player by Using Strings” on page 20-22
20-7
20 String Data in Charts
20-8
Log String Data to the Simulation Data Inspector
Chart Behavior
During simulation, Sine Wave blocks provide the position of a point moving along a closed
path in terms of latitude and longitude coordinates. The chart examines these coordinates
and assigns the strings q1 and q2 according to the information in this table.
Latitude Longitude q1 q2
positive positive "North" "east"
positive negative "North" "west"
negative positive "South" "east"
negative negative "South" "west"
20-9
20 String Data in Charts
1 To create a Simulink model with an empty chart that uses the C action language, at
the MATLAB command prompt, enter
sfnew -c
2 In the empty chart, place a default transition. A junction appears. Point and drag
from the edge of the junction to add other transitions and junctions.
3 Double-click each transition. At the text prompt, enter the appropriate condition or
action statement.
1 To resolve the undefined data, in the Symbols window, click the Resolve undefined
symbols icon . The Stateflow Editor assigns an appropriate scope to each symbol
in the chart.
Symbol Scope
latitude Input Data
longitude Input Data
q1 Local Data
q2 Local Data
sout Output Data
2 To specify q1 as string data, in the Type field of the Property Inspector, select
string. Repeat that specification for q2 and sout.
20-10
Log String Data to the Simulation Data Inspector
1 In the Simulink model, add two Sine Wave blocks and a Display block. Connect the
blocks to the chart input and output ports.
20-11
20 String Data in Charts
2 In the Simulation Data Inspector, select the check boxes for the latitude,
longitude, and sout signals so that they are displayed on the same set of axes. The
latitude and longitude signals appear as sinusoidal curves. The sout signal is
shown as a transition plot. The value of the string is displayed inside a band and
criss-crossed lines mark the changes in value.
3 To access the logged data in the MATLAB workspace, call the signal logging object
logsout. Stateflow exports the string data sout as a MATLAB string scalar. For
example, at the command prompt, enter:
A = table(logsout.get('latitude').Values.Data, ...
logsout.get('longitude').Values.Data, ...
logsout.get('sout').Values.Data);
A.Properties.VariableNames = {'Latitude','Longitude','QuadrantInfo'};
A([4:8:30],:)
ans =
4×3 table
20-12
See Also
See Also
get | strcat | table
More About
• “Manage Textual Information by Using Strings” on page 20-2
• “Send Messages with String Data” on page 20-14
• “Share String Data with Custom C Code” on page 20-17
• “Simulate a Media Player by Using Strings” on page 20-22
• “Access Signal Logging Data” on page 32-54
• “View State Activity by Using the Simulation Data Inspector” on page 24-33
• “View Data with the Simulation Data Inspector” (Simulink)
20-13
20 String Data in Charts
This model contains two charts that use C as the action language. During simulation, the
Emitter chart reads an input string key from the String Constant block and sends a
message to the Receiver chart. The message data consists of the input string key. The
Receiver chart compares the string with a constant keyword and returns an output string
that grants or denies access.
Emitter Chart
The Emitter chart consists of a single state A. When the state becomes active, it sets the
data for the message M to the input value key and sends the message to the Receiver
chart.
This table lists the scope and type for the symbols in the chart.
20-14
Send Messages with String Data
Receiver Chart
The chart consists of two states joined by a transition. The input message M guards the
transition. If there is a message present and its data value equals the constant string
lock, then the state activity transitions from Off to On. The chart outputs the string
value 'Access Granted'. If there is no message present, or if the data value does not
equal lock, the chart does not take the transition and the output value is 'Access
Denied'.
This table lists the scope and type for the symbols in the chart.
The constant string lock contains a secret password, initially set to 'Open Sesame'.
You can change the value of lock in the Initial value field of the Property Inspector.
20-15
20 String Data in Charts
• If you enter an incorrect password, such as "Abracadabra", then the model displays
the output string "Access Denied".
• If you enter the correct password, in this case, "Open Sesame", then the model
displays the output string "Access Granted".
See Also
send
More About
• “Manage Textual Information by Using Strings” on page 20-2
• “Log String Data to the Simulation Data Inspector” on page 20-9
• “Share String Data with Custom C Code” on page 20-17
• “Simulate a Media Player by Using Strings” on page 20-22
• “Communicate with Stateflow Charts by Sending Messages” on page 11-10
• “View Differences Between Stateflow Messages, Events, and Data” on page 11-2
20-16
Share String Data with Custom C Code
This model contains a Stateflow chart that calls two functions from custom C code.
During simulation, the chart takes as its input a string that contains text representing a
floating-point number in exponential form. The chart consists of three states that:
• Search the input string for leading zeroes, a decimal point, and an e.
• Parse the string into double-precision numbers representing the significand and
exponent parts of the input.
20-17
20 String Data in Charts
• Merge the numeric information into an output string expressing the input in scientific
notation.
For example, if the input string is "0123.456e789", then the chart outputs the string
"0123.456e789 means 1.23456 times ten to the 791th power".
20-18
Share String Data with Custom C Code
You can use the str2ascii operator to convert string data into an array that you can
export from a Stateflow chart to a custom C code function.
1 In the custom code function, declare the input variable as having type char*.
2 In the Stateflow chart, convert the string to an array of type uint8 by calling the
operator str2ascii.
3 Call the custom code function by passing the uint8 array as an input.
For example, in the previous chart, the Search state converts the input string str to the
uint8 array Asrt. The Search state passes this array as an input to the custom code
function searchfun:
extern void searchfun(int* n, char* strin)
{
nout[0] = strspn(strin,"0");
nout[1] = strcspn(strin,".e");
nout[2] = strcspn(strin,"e");
nout[3] = strlen(strin);
}
The Search state calls this function with the command searchfun(n,Astr). The
function populates the integer array n with these values:
• n[0] contains the number of leading zeroes in the input string str.
• n[1] contains the number of characters before the first instance of a decimal point or
e. This result provides the number of characters before the decimal point in str.
• n[2] contains the number of characters before the first instance of e. This result
provides the number of characters in the significand in str.
• n[3] contains the length of the input string str.
The Parse state uses these results to extract the values of the significand and exponent
parts of the input.
You can import string data to a Stateflow chart by passing a pointer to an array of type
uint8 as an input to a custom C function.
1 In the custom code function, declare the input variable containing the pointer as
having type char*.
20-19
20 String Data in Charts
2 Save the output string data from the custom code function at the location indicated
by the pointer.
3 In the Stateflow chart, convert the uint8 array to a string by calling the operator
ascii2str.
For example, in the previous chart, the Merge state consolidates the numeric information
obtained by the Parse state into an output string by calling the custom code function
mergefun:
extern void mergefun(char* strout, char* strin, int in0, double in1, double in2)
{
sprintf(strout, "%s means %1.*f times ten to the %dth power", strin, in0, in1, (int)
}
The Merge state calls the mergefun function with the command
mergefun(Aout,Astr,y0,y1,y2):
• Aout is an array of type uint8 pointing to the output of the custom function.
• Astr is an array of type uint8 corresponding to the input string to the chart.
• y0 is an integer containing the number of digits to the right of the decimal point in the
significand.
• y1 and y2 are double-precision numbers representing the significand and exponent
parts of the input.
The function mergefun calls the C library function sprintf, merging the contents of
Astr, y1, and y2 and storing the result in the memory location indicated by Aout. The
chart uses the operator ascii2str to convert this output to the string sout. In this way,
the model imports the string constructed by the custom code function back into Stateflow.
20-20
See Also
See Also
ascii2str | str2ascii | str2double | strcat | substr
More About
• “Manage Textual Information by Using Strings” on page 20-2
• “Log String Data to the Simulation Data Inspector” on page 20-9
• “Send Messages with String Data” on page 20-14
• “Simulate a Media Player by Using Strings” on page 20-22
• “Reuse Custom Code in Stateflow Charts” on page 30-26
20-21
20 String Data in Charts
20-22
Simulate a Media Player by Using Strings
In the model, the Display blocks show the default settings of the media player:
• The Display block for AlbumName changes from "None" to "Handel's Greatest
Hits".
20-23
20 String Data in Charts
• The Display block for CdStatus changes from "EMPTY" to "Reading: Handel's
Greatest Hits" to "Stopped".
• The String Constant block CR and the Display block for MechCmd change from "STOP"
to "PLAY".
• The Display block for CdStatus changes from "Stopped" to "Playing: Handel's
Greatest Hits".
• Music begins to play.
To see other changes in the Display blocks, use the Media Player Helper to select other
operating modes or to enter a different album name.
ModeManager Chart
This chart activates the appropriate subcomponent of the media player (AM radio, FM
radio, or CD player) depending on the inputs received from the Media Player Helper.
20-24
Simulate a Media Player by Using Strings
Key Features
Chart Behavior
20-25
20 String Data in Charts
At the start of simulation, the NormalOperation state becomes active. If the Boolean
data DiscEject is 1 (or true), a transition to the Eject state occurs, followed by a
transition back to the NormalOperation state.
• If strcmp returns a value of zero, then RadioReq is "OFF" and the Standby substate
is activated.
• If strcmp returns a nonzero value, then RadioReq is not "OFF" and the ON substate is
activated.
In the ON substate, three substates represent the operating modes of the media player:
CD player, AM radio, and FM radio. Each substate corresponds to a different value of
string data RadioReq. The inner transition inside the ON state continually scans for
changes in the value of RadioReq.
• If the value of RadioReq is "CD", then the substate CDMode becomes active, setting
the media player to CD player mode. The ModeManager chart outputs "PLAY",
"REW", "FF", and "STOP" commands to the CdPlayer chart through the string data
MechCmd.
• If the value of RadioReq is "AM", then the substate AMMode becomes active, setting
the media player to AM radio mode. The ModeManager chart outputs a "STOP"
command to the CdPlayer chart through the string data MechCmd.
• If the value of RadioReq is "FM", then the substate FMMode becomes active, setting
the media player to FM radio mode. The ModeManager chart outputs a "STOP"
command to the CdPlayer chart through the string data MechCmd.
CdPlayer Chart
This chart activates the appropriate operating mode for the CD player depending on the
input received from the ModeManager chart.
20-26
Simulate a Media Player by Using Strings
20-27
20 String Data in Charts
Key Features
Chart Behavior
If the Boolean data DiscInsert is 1 (or true), a transition to the Inserting state
occurs. After a short time delay, a transition to the DiscPresent state occurs.
The DiscPresent state remains active until the data CMD becomes "EJECT". At that
point, a transition to the Ejecting state occurs. After a short time delay, a transition to
the Empty state occurs.
Whenever a state transition occurs, the entry action in the new state changes the value of
CdStatus to reflect the status of the CD player. In the FF or REW substates, the during
actions continually change the value of CdStatus to produce a scrolling motion effect.
20-28
See Also
• When the active state is DiscPresent.FF, the value of CdStatus is "Forward >>
AlbumName", where AlbumName scrolls forward across the display.
See Also
after | strcat | strcmp | strcpy | strlen | substr
More About
• “Manage Textual Information by Using Strings” on page 20-2
• “Detect Changes in Data Values” on page 12-69
• “Control Chart Execution by Using Temporal Logic” on page 12-49
• “Access MATLAB Functions and Workspace Data in C Charts” on page 12-32
• “Record and Play Audio” (MATLAB)
• “Simulink Strings” (Simulink)
20-29
21
Continuous-Time Systems in
Stateflow Charts
Simulate hybrid systems that respond to continuous and discrete mode changes by
configuring Stateflow charts for continuous-time modeling. In a Stateflow chart, you can
represent modal logic succinctly and intuitively as a series of states, transitions, or flow
charts. You can also represent state information as continuous local variables with
automatic access to time derivatives.
1 Right-click inside a chart and select Properties from the context menu.
2 In the Chart Properties dialog box, set the Update method field to Continuous.
When you select this option:
21-2
Continuous-Time Modeling in Stateflow
21-3
21 Continuous-Time Systems in Stateflow Charts
During continuous-time simulation, a Stateflow chart updates its mode only in major time
steps. In a minor time step, the chart computes outputs based on the state of the chart
during the last major time step. For more information, see “Minor Time Steps” (Simulink).
When you define local continuous variables, the Stateflow chart provides programmatic
access to their derivatives. The Simulink solver computes the continuous state of the
chart at the current time step based on the values of these variables and their derivatives
at the previous time step. For more information, see “Continuous Versus Discrete Solvers”
(Simulink).
You can choose from different zero-crossing detection algorithms on the Solver pane in
the Model Configuration Parameters dialog box. For more information, see “Zero-Crossing
Algorithms” (Simulink) and “Preventing Excessive Zero Crossings” (Simulink).
21-4
Continuous-Time Modeling in Stateflow
• The number of minor intervals that the Simulink solver uses in each major time step.
• The number of iterations required to stabilize the integration and zero-crossings
algorithms.
By minimizing these side effects, a Stateflow chart can maintain its state at minor time
steps and update its state only during major time steps. Therefore, a Stateflow chart can
compute outputs based on a constant state for continuous time.
During continuous-time simulation, a chart updates its outputs at minor time steps
corresponding to the during actions of the active state. A chart with no states produces
no output. To mimic the behavior of a stateless chart in continuous time, create a single
state that calls a graphical function in its during action.
• State exit actions, which occur before leaving the state at the beginning of the
transition.
• State entry actions, which occur after entering the new state at the end of the
transition.
• Transition actions, which occur during the transition.
• Condition actions on a transition, but only if the transition directly reaches a state. For
example, this chart executes the action n++ even when conditions c2 and c3 are false.
Because there is no state transition, the condition action updates n in a minor time
step and results in an error.
21-5
21 Continuous-Time Systems in Stateflow Charts
Do not write to local continuous data in state during actions because these actions occur
in minor time steps.
In minor time steps, a continuous-time chart executes only state during actions. Because
Simulink models read continuous-time derivatives during minor time steps, compute
derivatives in during actions to provide the most current calculation.
In minor time steps, it is possible that outputs and derivatives do not reflect their most
current values. To provide smooth outputs, compute values from local discrete data, local
continuous data, and chart inputs.
You cannot call Simulink functions during minor time steps. Instead, call Simulink
functions only in actions that occur during major time steps: state entry or exit actions
and transition actions. Calling Simulink functions in state during actions or in transition
conditions results in an error during simulation. For more information, see “Reuse
Simulink Components in Stateflow Charts” on page 29-2.
To prevent mode changes between major time steps, conditions that affect control flow in
during actions depend on discrete variables. Discrete variables do not change value
between major time steps.
21-6
Continuous-Time Modeling in Stateflow
The presence of input events makes a chart behave like a triggered subsystem and unable
to simulate in continuous time. For example, this model generates an error if the chart
uses a continuous update method.
To mimic the behavior of an input event, pass the input signal through a Hit Crossing
block as an input to the continuous-time chart.
When a mode change occurs during continuous-time simulation, the entry action of the
destination state indicates to the Simulink model that a state transition occurred. With an
inner transition, the chart never executes the entry action. For more information, see
“Inner Transitions” on page 3-46.
To implement change detection, Stateflow buffers variables in a way that affects the
behavior of charts between a minor time step and the next major time step.
21-7
21 Continuous-Time Systems in Stateflow Charts
Modifying the operating point of a continuous-time chart is not supported. If you load the
operating point for a continuous-time chart, you cannot modify the activity of states or
any values of local or output chart data. For more information, see “Rules for Using the
Operating Point of a Chart” on page 16-38.
See Also
More About
• “Model a Bouncing Ball in Continuous Time” on page 21-11
• “Store Continuous State Information in Local Variables” on page 21-9
• “Solvers” (Simulink)
• “Zero-Crossing Detection” (Simulink)
21-8
Store Continuous State Information in Local Variables
Note Do not explicitly define variables with the suffix _dot in a chart configured for
continuous-time simulation.
21-9
21 Continuous-Time Systems in Stateflow Charts
See Also
More About
• “Continuous-Time Modeling in Stateflow” on page 21-2
• “Model a Bouncing Ball in Continuous Time” on page 21-11
21-10
Model a Bouncing Ball in Continuous Time
The model sf_bounce contains a chart that updates in continuous-time. Local variables
describe the dynamics of a free-falling ball in terms of position and velocity. During
simulation, the model uses zero-crossing detection to determine when the ball hits the
ground.
You can specify how a ball falls freely under the force of gravity in terms of position p and
velocity v with this system of first-order differential equations.
When p <= 0, the ball hits the ground and bounces. You can model the bounce by
updating the position and velocity of the ball:
In the model, the BouncingBall chart implements modal logic to simulate the continuous
dynamics of free fall and the discrete changes associated with bouncing. In the Chart
properties dialog box, these settings enable the BouncingBall chart to simulate in
continuous time:
21-11
21 Continuous-Time Systems in Stateflow Charts
The BouncingBall chart has two continuous-time variables: p for position and v for
velocity. For each one of these variables:
• Scope is Local.
• Type is double.
• Update Method is Continuous.
To expose the continuous state of the chart to the Simulink model, the BouncingBall chart
has two output variables: p_out and v_out. For each one of these variables:
• Scope is Output.
• Type is double.
• Update Method is Discrete.
21-12
Model a Bouncing Ball in Continuous Time
In the Model Explorer, you can view the continuous-time local variables and the
corresponding outputs in the chart. Implicit derivative variables do not appear in the
Model Explorer or in the Symbols Window.
The BouncingBall chart consists of a single state Falling that numerically solves the
differential equations for free fall. The default transition into the state sets the initial
position to 10 m and the initial velocity to 15 m/s. The during actions in the state:
21-13
21 Continuous-Time Systems in Stateflow Charts
The Falling state has a self-loop transition that models the discontinuity of the bounce
as an instantaneous mode change when the ball suddenly reverses direction. The
condition on the transition determines when the ball hits the ground by checking its
position p <= 0 and velocity v < 0. If the condition is valid, the condition action resets
the position and velocity when the ball hits the ground.
The ball hits the ground when position p is exactly zero. By relaxing the condition, you
increase the tolerance within which the Simulink solver can detect when the position
changes sign. For more information, see “How Blocks Work with Zero-Crossing
Detection” (Simulink).
The second part of the condition helps maintain the efficiency of the Simulink solver by
minimizing the frequency of zero crossings. Without the second check, the condition
remains true after the state transition, resulting in two successive zero crossings.
21-14
Model a Bouncing Ball in Continuous Time
The BouncingBall chart meets the design requirements defined in “Guidelines for
Continuous-Time Simulation” on page 21-5. In particular, the chart:
After you run the model, the scope shows the graphs of position and velocity. The position
graph exhibits the expected bounce pattern.
21-15
21 Continuous-Time Systems in Stateflow Charts
See Also
More About
• “Continuous-Time Modeling in Stateflow” on page 21-2
• “Store Continuous State Information in Local Variables” on page 21-9
21-16
22
Fixed-Point Numbers
Fixed-point numbers represent real numbers by using the encoding scheme:
∼
V ≈ V = SQ + B.
• V is a precise real-world value that you want to approximate with a fixed-point number.
∼
• V is the approximate real-world value that results from the fixed-point representation.
• Q is an integer that encodes the fixed-point number. This value is called the quantized
integer.
• S is a coefficient that determines the precision of the fixed-point representation. This
value is called the slope.
• B is an additive correction called the bias.
The quantized integer Q is the only part of the fixed-point representation that varies in
value. In the generated code, the quantities S and B are constant and appear only as
literal numbers or expressions. If a fixed-point number changes, its quantized integer Q
changes but S and B remain unchanged.
Using fixed-point numbers to represent real numbers with integers involves the loss of
some precision. However, with a suitable choice of S and B, you can minimize this loss to
acceptable levels. For instance, by changing the coding scheme to use S = 0.25 and B =
0.1, you can represent the number V = 15.345 with greater precision as:
Q = round((V – B)/S) = round((15.345 – 0.1)/0.25) = round(60.98) = 61
∼
V = SQ + B = 0.25 ⨉ 61 + 0.1 = 15.35.
22-2
Fixed-Point Data in Stateflow Charts
~
The difference between V and V is always less than the slope S.
• If you select Binary point, the Data Type Assistant displays the Fraction length
field, which specifies the binary point location. Choosing a Fraction length of n
defines a fixed-point encoding with a slope of S = 2-n and a bias of B = 0 .
• If you select Slope and bias, the Data Type Assistant displays fields for entering
the Slope S and Bias B for the fixed-point encoding scheme.
Alternatively, you can specify the encoding for a fixed-point data object directly by using
the fixdt function. In the Property Inspector or the Model Explorer, in the Type field,
enter an expression in one of these formats:
22-3
22 Fixed-Point Data in Stateflow Charts
Conversion Operations
Stateflow charts convert real numbers into fixed-point numbers during data initialization
and as part of casting operations in the application. These conversions compute a
quantized integer Q from a real number input. The type of conversion depends on the
action language for the chart.
In a chart that uses MATLAB as the action language, you define the method for all
conversions through the fixed-point properties for the chart. See “Fixed-Point Properties”
on page 24-9.
For example, if you set the MATLAB Chart fimath property to Same as MATLAB, then
the chart rounds the resulting quantized integer to its nearest integer value.
Charts that use C as the action language employ two methods for converting fixed-point
data:
• Offline conversions initialize data during code generation. Offline conversions are
designed to maximize accuracy. These conversions round the resulting quantized
integer to its nearest integer value. Offline conversions are performed for initialization
of data (variables and constants) in the Stateflow hierarchy and from the MATLAB
workspace.
• Online conversions perform casting operations during run time. Online conversions
are designed to maximize computational efficiency. They are faster and more efficient,
but less precise than offline conversions. Instead of rounding Q to its nearest integer,
online conversions round to the floor (except for division, which can round to 0,
depending on the C compiler).
For example, this table illustrates the difference between offline and online conversions of
real numbers to fixed-point numbers defined with a slope of S = 2-4 and a bias of B = 0.
For each real-world value V, the chart computes a quantized integer Q by rounding (V-
B)/S to the nearest integer (in offline conversion) or to the floor (in online conversion). For
∼
each conversion, V = QS + B is the approximate real-world value resulting from Q.
22-4
Fixed-Point Data in Stateflow Charts
Although fixed-point context-sensitive constants can appear in expressions with any data
types (including integers and floating-point data), their main use is with fixed-point
numbers. The algorithm that interprets the context-sensitive constant computes a type
that provides maximum accuracy without overflow. The algorithm depends on:
• In a casting operation, the constant has the type to which it is being cast.
• In a simple assignment operation of the form a = b:
22-5
22 Fixed-Point Data in Stateflow Charts
22-6
Fixed-Point Data in Stateflow Charts
• Increasing the Word length value for the overflowing fixed-point data. For
example, change the number of bits used to encode the fixed-point data from 16 to
32. This action changes the base integer type for Q from int16 to int32.
• Decreasing the Fraction length value (if using Binary point scaling) or
increasing the Slope value (if using Slope and bias scaling). For example,
decrease the Fraction length value from 4 to 1 (or, equivalently, increase the
Slope value from S = 2-4 = 0.0625 to S = 2-1 = 0.5). This action increases the range
of your fixed-point data but decreases the available precision.
Note If you do not use context-sensitive constants with fixed-point types, noninteger
numeric constants (constants that have a decimal point) can force fixed-point
operations to produce floating-point results.
22-7
22 Fixed-Point Data in Stateflow Charts
• Use the same property values to specify the data in the Stateflow chart and in the
Simulink model. For an example of this method of sharing input data from a Simulink
model using a Gateway In block, see “Model a Bang-Bang Controller by Using Fixed-
Point Inputs” on page 22-10.
For some Simulink blocks, you can specify the type of input or output data directly. For
example, you can specify the fixed-point data type for a Constant block directly in the
Output data type field by using the fixdt function.
• Define the data as Input or Output in the Stateflow chart and instruct the sending or
receiving block in the Simulink model to inherit its type from the chart data. In many
blocks, you can set data types through inheritance from the driving block, or through
back propagation from the next block. You can set the data type of a Simulink block to
match the data type of the Stateflow port to which it connects.
For example, you can set the Constant block to inherit its type from the Stateflow
Input to Simulink port that it supplies. Set the Output data type block parameter
to Inherit via back propagation.
• For each fixed-point data, the chart defines an integer variable for Q in the generated
code. This integer is the only part of a fixed-point number that changes in value. The
available base types for Q are the unsigned integer types uint8, uint16, and
uint32, and the signed integer types int8, int16, and int32. If a fixed-point
number has a slope S = 1 and a bias B = 0, it is equivalent to its quantized integer Q
and behaves exactly as its base integer type.
• The slope S is factored into a coefficient F with 1 ≤ F < 2 and an integer power of two
with exponent E:
S = F ⨉ 2E.
If the fractional slope F is greater than 1, it is converted into a fixed-point number.
Encoding schemes with F > 1 can be computationally expensive, particularly in
multiplication and division operations. Setting F = 1 avoids these computationally
expensive instructions. In this setting, scaling by a power of 2 is implemented as bit
shifts, which are more efficient than multiply instructions. Therefore, using binary-
point-only scaling, in which F = 1 and B = 0, is recommended.
• Operations for fixed-point types are implemented with solutions for the quantized
integer as described in “Arithmetic Operations for Fixed-Point Data” on page 22-32.
22-8
See Also
To generate efficient code, the fixed-point promotion rules choose values for slope and
bias that cancel difficult terms in the solutions. See “Promotion Rules for Fixed-Point
Operations” on page 22-34.
See Also
fixdt | fixptbestexp
More About
• “Fixed-Point Operations in Stateflow Charts” on page 22-32
• “Supported Operations for Fixed-Point Data” on page 22-21
• “Build a Low-Pass Filter by Using Fixed-Point Data” on page 22-15
• “Set Data Properties” on page 9-5
22-9
22 Fixed-Point Data in Stateflow Charts
22-10
Model a Bang-Bang Controller by Using Fixed-Point Inputs
22-11
22 Fixed-Point Data in Stateflow Charts
The Boiler Plant model subsystem simulates the temperature reaction of the boiler to
periods of heating or cooling dictated by the Stateflow block. Depending on the
Boolean value coming from the Controller, a temperature increment (+1 for heating,
–0.1 for cooling) is added to the previous boiler temperature. The resulting boiler
temperature is sent to the digital thermometer subsystem block.
2 In the Boiler Plant model subsystem, double-click the digital thermometer subsystem
block.
Sensor Block
The sensor block converts input boiler temperature (T) to an intermediate analog voltage
output V with a first-order polynomial that gives this output:
V = 0.05 × T + 0.75
ADC Block
22-12
Model a Bang-Bang Controller by Using Fixed-Point Inputs
The ADC subsystem digitizes the analog voltage from the sensor block by multiplying the
analog voltage by 256/5, rounding it to its integer floor, and limiting it to a maximum of
255 (the largest unsigned 8-bit integer value). Using the value for the output V from the
sensor block, the new digital coded temperature output by the ADC block, Tdigital, is given
by this equation:
The Linear fixed point conversion block informs the rest of the model that Tdigital is a fixed-
point number with a slope value of 5/256/0.05 and an intercept value of –0.75/0.05. The
Stateflow block Bang-Bang Controller receives this output and interprets it as a fixed-
point number through the Stateflow data temp, which is scoped as Input from Simulink
and set as an unsigned 8-bit fixed-point data with the same values for S and B set in the
Linear fixed point conversion block.
The values for S and B are determined from the general expression for a fixed-point
number:
V = SQ + B
Therefore,
Since Tdigital is now a fixed-point number, it is now the quantized integer Q of a fixed-point
type. This means that Tdigital = Q of its fixed-point type, which gives this relation:
Since T is the real-world value for the environment temperature, the above equation
implies these relations:
V = T
22-13
22 Fixed-Point Data in Stateflow Charts
and
and
By setting Tdigital to be a fixed-point data as the output of the Linear fixed point conversion
block and the input of the Stateflow block Bang-Bang Controller, the Stateflow chart
interprets and processes this data automatically in an 8-bit environment with no need for
any explicit conversions.
See Also
More About
• “Fixed-Point Data in Stateflow Charts” on page 22-2
• “Fixed-Point Operations in Stateflow Charts” on page 22-32
• “Supported Operations for Fixed-Point Data” on page 22-21
22-14
Build a Low-Pass Filter by Using Fixed-Point Data
The Low-Pass Filter chart is a stateless flow chart that accepts one input and provides one
output. The chart contains these data symbols:
The values of b0, b1, and a1 are the coefficients of the low-pass Butterworth filter.
1 Create a Simulink® model with an empty Stateflow chart by entering sfnew at the
MATLAB® command prompt.
2 In the Stateflow chart, add a flow chart with a single branch that assigns values to y,
x_n1, and y_n1.
22-15
22 Fixed-Point Data in Stateflow Charts
3 Add input, output, local, and parameter data to the chart, as described in “Add
Stateflow Data” on page 9-2.
Before loading the model, MATLAB calls the butter function to compute the values for
the parameters b0, b1, and a1. The function constructs a first-order low-pass Butterworth
filter with a normalized cutoff frequency of (2*pi*Fc/(Fs/2)) radians per second,
where:
The function output B contains the numerator coefficients of the filter in descending
powers of z. The function output A contains the denominator coefficients of the filter in
descending powers of z.
Fs = 1000;
Fc = 50;
[B,A] = butter(1,2*pi*Fc/(Fs/2));
b0 = B(1);
b1 = B(2);
a1 = A(2);
1 In the model window, select File > Model Properties > Model Properties.
2 In the Model Properties dialog box, on the Callbacks tab, select PreLoadFcn.
3 Enter the MATLAB code for the preload function call.
4 Click OK.
To load the parameter values to the MATLAB workspace, save, close, and reopen the
model.
To complete the model, add a Sine Wave block, a Data Type Conversion block, and a
Scope block. Connect and label the blocks according to this diagram.
22-16
Build a Low-Pass Filter by Using Fixed-Point Data
The Sine Wave block outputs a floating-point signal. The block has these settings:
The Data Type Conversion block converts the floating-point signal from the Sine Wave
block to a fixed-point signal. By converting the signal to a fixed-point type, you can
simulate your model using less memory. The block has these settings:
• Output minimum: []
• Output maximum: []
• Output data type: fixdt(1,16,14)
• Lock output data type setting against changes by the fixed-point tools: Off
• Input and output to have equal: Real World Value (RWV)
• Integer rounding mode: Floor
22-17
22 Fixed-Point Data in Stateflow Charts
Scope block
The Scope block has two input ports that connect to the input and output signals for the
Low-Pass Filter chart. To display the two signals separately, select a scope layout with two
rows and one column.
Because none of the blocks in the model have a continuous sample time, use a discrete
solver with these configuration parameters:
When you simulate the model, the Scope block displays two signals. The top signal shows
the fixed-point version of the sine wave input to the chart. The bottom signal corresponds
to the filtered output from the chart. The filter removes high-frequency values from the
signal but allows low-frequency values to pass through the chart unchanged.
22-18
See Also
See Also
Data Type Conversion | Scope | Sine Wave | butter | sfnew
22-19
22 Fixed-Point Data in Stateflow Charts
More About
• “Fixed-Point Data in Stateflow Charts” on page 22-2
• “Fixed-Point Operations in Stateflow Charts” on page 22-32
• “Supported Operations for Fixed-Point Data” on page 22-21
22-20
Supported Operations for Fixed-Point Data
•
MATLAB as the action language.
•
C as the action language.
For more information, see “Differences Between MATLAB and C as Action Language
Syntax” on page 13-6.
Binary Operations
This table summarizes the interpretation of all binary operations on fixed-point operands
according to their order of precedence (0 = highest, 9 = lowest). Binary operations are
left associative so that, in any expression, operators with the same precedence are
evaluated from left to right.
22-21
22 Fixed-Point Data in Stateflow Charts
22-22
Supported Operations for Fixed-Point Data
22-23
22 Fixed-Point Data in Stateflow Charts
22-24
Supported Operations for Fixed-Point Data
Assignment Operations
This table summarizes the interpretation of assignment operations on fixed-point
operands.
In charts that use C as the action language, a simple assignment of the form a = b
calculates an intermediate value for b according to the fixed-point promotion rules. Then
22-25
22 Fixed-Point Data in Stateflow Charts
this intermediate value is cast to the type of a by using an online conversion. See
“Promotion Rules for Fixed-Point Operations” on page 22-34 and “Conversion
Operations” on page 22-4. Simple assignments are most efficient when both types have
equal bias and slopes that either are equal or are both powers of two.
Note Using the special assignment operation := can result in generated code that is less
efficient than the code you generate by using the normal fixed-point promotion rules.
You can use the special assignment operation := to avoid overflow when performing an
arithmetic operation on two fixed-point numbers. For example, consider a chart that
computes the sum a+b where a = 212-1 = 4095 and b = 1.
Suppose that:
• Both inputs are signed 16-bit fixed-point numbers with three fraction bits (type
fixdt(1,16,3)).
• The output c is a signed 32-bit fixed-point number with three fraction bits (type
fixdt(1,32,3)).
• The integer word size for production targets is 16 bits.
22-26
Supported Operations for Fixed-Point Data
Because the target integer size is 16 bits, the simple assignment c = a+b adds the inputs
in 16 bits before casting the sum to 32 bits. The intermediate result is 4096, which, as a
type fixdt(1,16,3) value, results in an overflow.
In contrast, the special assignment c := a+b casts the inputs to 32 bits before
computing the sum. The result of 4096 is safely computed as a type fixdt(1,32,3)
value without an overflow.
You can use the special assignment operation := to obtain a more precise result when
multiplying or dividing two fixed-point numbers. For example, consider a chart that
computes the ratio a/b where a = 2 and b = 3.
Suppose that:
• The input a is a fixed-point number with four fraction bits (type fixdt(1,16,4)).
• The input b is a fixed-point number with three fraction bits (type fixdt(1,16,3)).
• The output c is a signed 16-bit fixed-point number with six fraction bits (type
fixdt(1,16,6)).
The simple assignment c = a/b first calculates an intermediate value for a/b according
to the fixed-point promotion rules. The quantized integer is rounded to the floor:
Sint = Sa/Sb = 2-4/2-3 = 2-1
Qint = Qa/Qb = 32/24 ≈ 1.
The intermediate result is then cast as a signed 16-digit fixed-point number with six
fraction bits:
Sc = 2-6 = 1/64
Qc = SintQint/Sc = 2-1/2-6 = 25 = 32.
∼
Therefore, the approximate real-world value for c is V c = ScQc = 32/64 = 0.5. This result
is not a good approximation of the actual value of 2/3.
In contrast, the special assignment c := a/b calculates a/b directly as a signed 16-digit
fixed-point number with six fraction bits. Again, the quantized integer is rounded to the
floor:
Sc = 2-6 = 1/64
Qc = (SaQa)/(ScSbQb) = 128/3 ≈ 42.
22-27
22 Fixed-Point Data in Stateflow Charts
∼
Therefore, the approximate real-world value for c is V c = ScQc = 42/64 = 0.6563. This
result is a better approximation to the actual value of 2/3.
The model calculates the value of a/b as a floating-point number of type fixdt(1,16,1)
in three different ways:
• A type casting operation in a chart that uses MATLAB as the action language.
• A simple assignment operation in a chart that uses C as the action language.
• A special assignment operation in a chart that uses C as the action language.
22-28
Supported Operations for Fixed-Point Data
The chart at the top of the model computes an intermediate value for a/b. The quantized
integer for the intermediate value is rounded to the nearest integer:
The intermediate value is then cast as a signed 16-digit fixed-point number c with one
fraction bit:
22-29
22 Fixed-Point Data in Stateflow Charts
The middle chart also computes an intermediate value for a/b. In this case, the quantized
integer for the intermediate value is rounded to the floor:
The intermediate value is then cast as a signed 16-digit fixed-point number c with one
fraction bit:
The chart at the bottom of the model uses a special assignment of the form c := a/b.
The value of the division is calculated directly as a signed 16-digit fixed-point number
with one fraction bit. The quantized integer is rounded to the floor:
22-30
See Also
The three results exhibit loss of precision compared to the floating-point answer of 19/24
= 0.7917. To minimize the loss of precision to an acceptable level in your application,
adjust the encoding scheme in your fixed-point data.
See Also
More About
• “Fixed-Point Data in Stateflow Charts” on page 22-2
• “Fixed-Point Operations in Stateflow Charts” on page 22-32
• “Build a Low-Pass Filter by Using Fixed-Point Data” on page 22-15
22-31
22 Fixed-Point Data in Stateflow Charts
c = a <op> b
where a and b are fixed-point numbers and <op> refers to addition, subtraction,
multiplication, or division. The result of the operation is a fixed-point number c of the
form
∼
V c = ScQc + Bc.
The fixed-point type for c determines the slope Sc, the bias Bc, and the number of bits
used to store the quantized integer Qc. For each arithmetic operation, this table lists the
value of the quantized integer Qc in terms of the values of the operands (a and b) and the
fixed-point type for c.
To simplify these expressions and avoid computationally expensive operations, use binary-
point scaling to encode all your fixed-point data. With this setting, the slope is an integer
power of two and the bias is zero. Then, all fixed-point operations consist of integer
arithmetic and bit shifts on the quantized integers.
22-32
Fixed-Point Operations in Stateflow Charts
Note The result of an arithmetic operation depends on the rounding method that
computes the value of the quantized integer Qc. For more information, see “Conversion
Operations” on page 22-4.
For example, suppose that a and b represent the real-world value V = 2.2 in two different
fixed-point encoding schemes:
• a is a fixed-point number with slope Sa = 0.3 and bias Ba = 0.1. The quantized integer
for a is:
Qa = (V – Ba)/Sa = (2.2 – 0.1)/0.3 = 7.
• b is a fixed-point number with slope Sb = 0.7 and bias Bb = 0.1. The quantized integer
for b is:
Qb = (V – Bb)/Sb = (2.2 – 0.1)/0.7 = 3.
To compare these values, the chart first converts them to a common fixed-point type with
slope Scomp = 1.06811 · 10–5 ≈ Sa/28087 ≈ Sb · 2–16 and bias Bcomp = 0.1. (In this case, the
slope Scomp arises from the approximate value of Sa/Sb = 0.3/0.7 ≈ 28087 · 2–16.) In this
common encoding scheme, a and b correspond to these quantized integers:
Qa' = SaQa/Scomp = Qa(Sa/Scomp) ≈ 7 ⨉ 28087 = 196609
Qb' = SbQb/Scomp = Qb(Sb/Scomp) ≈ 3 ⨉ 216 = 196608.
After the conversion, the quantized integers are different. Although a and b represent the
same real-world value, they are not equal as fixed-point numbers.
Note In charts that use C as the action language, comparisons of fixed-point operands
with mismatched biases are not supported.
22-33
22 Fixed-Point Data in Stateflow Charts
• In charts that use MATLAB as the action language, using a in a logical operation is
equivalent to the expression a ~= cast(0,'like',a).
• In charts that use C as the action language, using a in a logical operation is equivalent
to the expression a != 0c, where 0c is a fixed-point context-sensitive constant. See
“Fixed-Point Context-Sensitive Constants” on page 22-5.
For example, suppose that a is a fixed-point number with a slope of Sa = 0.25 and a bias
of Ba = 5.1. Using a in a logical operation is equivalent to testing whether the quantized
integer Qa satisfies the condition
Qa = round((0 – Ba)/Sa) = round(–5.1 / 0.25) = round(–20.4) = –20.
Therefore, a is equivalent to false when its real-world approximation is
∼
V a = SaQa + Ba = 0.25 ⨉ ( –20) + 5.1 = 0.1.
The fixed-point promotion rules determine a result type for an operation c = a <op> b
by selecting the slope Sc, the bias Bc, and the number of bits wc used to store the
quantized integer Qc. These parameters depend on the fixed-point types of the operands a
and b, the operation <op> to be performed, and the action language property for the
chart.
• In a chart that uses MATLAB as the action language, you control the fixed-point
promotion rules through the fixed-point properties for the chart. See “Fixed-Point
Properties” on page 24-9.
• If you set the MATLAB Chart fimath property to Same as MATLAB, then
arithmetic operations follow the default fixed-point promotion rules for MATLAB.
See “Perform Fixed-Point Arithmetic” (Fixed-Point Designer).
• If you specify a chart fimath object with SumMode and ProductMode set to
SpecifyPrecision, then you can define the word length, slope, and bias for all
sums and products explicitly. See “fimath Object Properties” (Fixed-Point
Designer).
• In a chart that uses C as the action language, the fixed-point promotion rules
determine the type for an intermediate value of the result. This intermediate value is
then cast to the type that you specify for c.
22-34
Fixed-Point Operations in Stateflow Charts
For all arithmetic operations, the default number of bits wc used to store the quantized
integer is the larger value between:
• The maximum number of bits in the operand types (wa and wb).
• The number of bits in the integer word size for the target machine (wint).
To set the value of wint, open the Model Configuration Parameters dialog box. On
the Hardware Implementation pane, select Custom Processor from the Device
vendor drop-down list and enter the target integer word size in the int field. For more
information, see “Hardware Implementation Pane” (Simulink).
You can avoid overflow and improve the precision in your floating-point operations by
using the special assignment operation of the form c := a <op> b. The special
assignment operation does not follow the fixed-point promotion rules. Instead, the
chart determines the result of the operation by using the type that you specify for c.
See “Override Fixed-Point Promotion in C Charts” on page 22-25.
By default, charts that use MATLAB as the action language support addition and
subtraction only on fixed-point data defined through binary-point scaling. If either
operand is a signed fixed-point number, then the result is also signed. The choice of word
length accommodates the integer and fraction parts of each operand in addition to a
possible carry bit. The fraction length of the result is equal to the fraction length of the
most precise operand. To perform addition and subtraction on fixed-point data defined by
using either a slope that is not an integer power of two or a nonzero bias, specify a chart
fimath object with SumMode set to SpecifyPrecision.
Charts that use C as the action language support addition and subtraction for operands of
all fixed-point data types. The result is a signed fixed-point number only if both operands
are signed. Mixing signed and unsigned operands can yield unexpected results and is not
recommended. The slope of the result is equal to the slope of the least precise operand.
To simplify calculations and yield efficient code, the biases of the two inputs are added for
an addition operation and subtracted for a subtraction operation.
22-35
22 Fixed-Point Data in Stateflow Charts
Multiplication
By default, charts that use MATLAB as the action language support multiplication only on
fixed-point data defined through binary-point scaling. If either operand is a signed fixed-
point number, then the result is also signed. A full precision product requires a word
length equal to the sum of the word lengths of the operands. The fraction length of a
product is the sum of the fraction lengths of the operands. To perform multiplication on
fixed-point data defined by using either a slope that is not an integer power of two or a
nonzero bias, specify a chart fimath object with ProductMode set to
SpecifyPrecision.
Charts that use C as the action language support multiplication only on fixed-point data
operands defined by nonzero biases. The result is a signed fixed-point number only if both
operands are signed. Mixing signed and unsigned operands can yield unexpected results
and is not recommended. The slope of a product is the product of the slopes of the
operands.
22-36
Fixed-Point Operations in Stateflow Charts
Division
Charts that use MATLAB as the action language support division only on fixed-point data
defined through binary-point scaling. If either operand is a signed fixed-point number,
then the result is also signed. A full precision quotient requires a word length equal to the
maximum number of bits in the operands. The fraction length of a quotient is the
difference of the fraction lengths of the operands.
Charts that use C as the action language support division for fixed-point data operands
defined by nonzero biases. The result is a signed fixed-point number only if both operands
are signed. Mixing signed and unsigned operands can yield unexpected results and is not
recommended. The slope of a quotient is the quotient of the slopes of the operands.
22-37
22 Fixed-Point Data in Stateflow Charts
Unary Minus
The only unary operation that requires a promotion of its result type is the unary minus
operation c = -a. Taking the negative of an unsigned fixed-point number can yield
unexpected results and is not recommended. The word size of the result depends on the
action language property of the chart. The slope of the result is equal to the slope of the
operand. The bias of the result type is the negative of the bias of the operand.
This table summarizes the fixed-point promotion rules for a binary operation between a
fixed-point number and an operand of a different numeric type.
22-38
See Also
See Also
More About
• “Fixed-Point Data in Stateflow Charts” on page 22-2
• “Supported Operations for Fixed-Point Data” on page 22-21
22-39
22 Fixed-Point Data in Stateflow Charts
22-40
23
Complex Data
Note Continuous-time variables of complex type are not supported. For more
information, see “Store Continuous State Information in Local Variables” on page 21-9.
23-2
See Also
• Charts
• Subcharts
• States
• Functions
• Complex vectors
• Complex matrices
• State actions
• Transition actions
• MATLAB functions (see “Reuse MATLAB Code by Defining MATLAB Functions” on
page 28-2)
• Truth table functions (see “Reuse Combinatorial Logic by Defining Truth Tables” on
page 27-2)
• Graphical functions (see “Reuse Logic Patterns by Defining Graphical Functions” on
page 8-16)
• Change detection operators (see “Detect Changes in Data Values” on page 12-69)
See Also
More About
• “Supported Operations for Complex Data” on page 23-4
• “Rules for Using Complex Data in C Charts” on page 23-8
• “Best Practices for Using Complex Data in C Charts” on page 23-11
23-3
23 Complex Data
•
MATLAB as the action language.
•
C as the action language.
For more information, see “Differences Between MATLAB and C as Action Language
Syntax” on page 13-6.
Alternatively, you can define complex data by using the complex operator:
complex(<real_part>,<imag_part>)
<real_part> and <imag_part> are arguments that define the real and imaginary parts
of the complex number, respectively. The two arguments must be real values or
expressions that evaluate to real values. As in the preceding example, this statement
assigns a value of 3+4i to x:
x = complex(3,4);
Charts that use C as the action language do not support complex number notation a +
bi. To define a complex number based on two real values, use the complex operator.
Binary Operations
This table summarizes the interpretation of all binary operations on complex operands
according to their order of precedence (1 = highest, 3 = lowest). Binary operations are
left associative so that, in any expression, operators with the same precedence are
evaluated from left to right.
23-4
Supported Operations for Complex Data
Assignment Operations
This table summarizes the interpretation of assignment operations in Stateflow charts.
23-5
23 Complex Data
real Operator
The real operator returns the value of the real part of a complex number:
real(<complex_expr>)
real(frame(200))
imag Operator
The imag operator returns the value of the imaginary part of a complex number:
imag(<complex_expr>)
imag(frame(200))
23-6
See Also
See Also
complex | i | imag | real
More About
• “Complex Data in Stateflow Charts” on page 23-2
• “Rules for Using Complex Data in C Charts” on page 23-8
• “Best Practices for Using Complex Data in C Charts” on page 23-11
23-7
23 Complex Data
These rules apply when you use complex data in Stateflow charts that use C as the action
language.
C charts do not support complex number notation (a + bi), where a and b are real
numbers. Therefore, you cannot use complex number notation in state actions, transition
conditions and actions, or any statements in C charts.
To define a complex number, use the complex operator as described in “Notation for
Complex Data” on page 23-4.
Math operations such as sin, cos, min, max, and abs do not work with complex data in C
charts. However, you can use MATLAB functions for these operations.
For more information, see “Perform Math Function Operations with a MATLAB Function”
on page 23-11.
Mix complex and real operands only for addition, subtraction, and multiplication
If you mix operands for any other math operations in C charts, an error appears when you
try to simulate your model.
To mix complex and real operands for division, you can use a MATLAB function as
described in “Perform Complex Division with a MATLAB Function” on page 23-12.
Tip Another way to mix operands for division is to use the complex, real, and imag
operators in C charts.
Suppose that you want to calculate y = x1/x2, where x1 is complex and x2 is real. You
can rewrite this calculation as:
y = complex(real(x1)/x2, imag(x1)/x2)
23-8
Rules for Using Complex Data in C Charts
For more information, see “Access Real and Imaginary Parts of a Complex Number” on
page 23-6.
If you define complex data with Constant scope, an error appears when you try to
simulate your model.
Do not define complex data with ml, struct, or boolean base type
If you define complex data with ml, struct, or boolean base type, an error appears
when you try to simulate your model.
When you define the initial value for data that is complex, use only a real value. See
“Additional Properties” on page 9-19 for instructions on setting an initial value in the Data
properties dialog box.
In the Data properties dialog box, do not enter any values in the Minimum or Maximum
field when you define complex data. If you enter a value in either field, an error message
appears when you try to simulate your model.
If you assign complex values to real data types, an error appears when you try to simulate
your model.
Note You can assign both real and complex values to complex data types.
• Graphical functions
• Truth table functions
• MATLAB functions
23-9
23 Complex Data
• Simulink functions
If your C chart passes real values to function inputs of complex type, an error appears
when you try to simulate your model.
You cannot use complex data as an argument for temporal logic operators, because you
cannot define time as a complex number.
See Also
More About
• “Complex Data in Stateflow Charts” on page 23-2
• “Supported Operations for Complex Data” on page 23-4
• “Best Practices for Using Complex Data in C Charts” on page 23-11
23-10
Best Practices for Using Complex Data in C Charts
When you use complex data in Stateflow charts that use C as the action language, follow
these best practices.
A Simple Example
In the following chart, a MATLAB function calculates the absolute value of a complex
number:
The value of comp_num is 1+2i. Calculating the absolute value gives an answer of
2.2361.
Suppose that you want to find the absolute value of a complex number. Follow these
steps:
23-11
23 Complex Data
y = myabs(u)
2 Double-click the function box to open the editor.
3 In the editor, enter the code below:
function y = myabs(u)
%#codegen
y = abs(u);
The function myabs takes a complex input u and returns the absolute value as an
output y.
4 Configure the input argument u to accept complex values.
You cannot pass real values to function inputs of complex type. For details, see “Rules for
Using Complex Data in C Charts” on page 23-8.
A Simple Example
In the following chart, a MATLAB function performs division on two complex operands:
23-12
Best Practices for Using Complex Data in C Charts
The values of comp_num and comp_den are 1+2i and 3+4i, respectively. Dividing these
values gives an answer of 0.44+0.08i.
The function mydiv takes two complex inputs, u1 and u2, and returns the complex
quotient of the two numbers as an output y.
4 Configure the input and output arguments to accept complex values.
a Open the Model Explorer.
b In the Model Hierarchy pane of the Model Explorer, navigate to the MATLAB
function mydiv.
c For each input and output argument, follow these steps:
i In the Contents pane of the Model Explorer, right-click the argument and
select Properties from the context menu.
23-13
23 Complex Data
ii In the Data properties dialog box, select On in the Complexity field and click
OK.
You cannot pass real values to function inputs of complex type. For details, see “Rules for
Using Complex Data in C Charts” on page 23-8.
See Also
More About
• “Complex Data in Stateflow Charts” on page 23-2
• “Supported Operations for Complex Data” on page 23-4
• “Rules for Using Complex Data in C Charts” on page 23-8
23-14
Detect Valid Transmission Data Using Frame Synchronization
Model Structure
The model contains the following components.
The C chart contains the following states, transitions, and MATLAB functions.
23-15
23 Complex Data
The chart accepts a complex input signal I/Q. After synchronizing the data frame, the
chart stores the valid data in a complex output signal frame.
• Complex multiplication
The output signal frame is a vector of complex products between each valid data
point and the phase angle of the carrier wave.
• Indexing into a complex vector
23-16
Detect Valid Transmission Data Using Frame Synchronization
The chart uses the temporalCount operator to index into the complex vector frame.
• MATLAB functions with complex arguments
Simulation Results
The sf_frame_sync_controller model does not produce simulation results. The
purpose of this example is to explain how to process complex data in a chart.
• If the correlation exceeds 50 percent, frame synchronization occurs. The chart stores
220 valid data points in the complex vector frame.
• If the correlation stays below 50 percent after the chart has evaluated 300 data points,
the frame synchronization algorithm resets.
23-17
23 Complex Data
See Also
More About
• “Complex Data in Stateflow Charts” on page 23-2
• “Supported Operations for Complex Data” on page 23-4
• “Rules for Using Complex Data in C Charts” on page 23-8
• “Best Practices for Using Complex Data in C Charts” on page 23-11
23-18
Measure Frequency Response Using a Spectrum Analyzer
A spectrum analyzer is a tool that measures the frequency response (magnitude and
phase angle) of a physical system over a range of frequencies.
Model Structure
23-19
23 Complex Data
Simulation Results
23-20
Measure Frequency Response Using a Spectrum Analyzer
To adjust the scope display, right-click inside the grid and select Autoscale from the
context menu.
• In the magnitude plot, the sharp peak is the response of the Plant block to a resonant
frequency.
• In the phase plot, the angle changes from 0 to –π radians (–180 degrees). Each
complex pole in the Plant block adds –π/2 radians to the phase angle.
23-21
23 Complex Data
This block is a masked chart that uses MATLAB as the action language. To access the
chart, right-click the Sinusoid Generator block and select Mask > Look Under Mask.
23-22
Measure Frequency Response Using a Spectrum Analyzer
23-23
23 Complex Data
This chart unwraps the phase angle output of the Analyzer chart. Unwrapping means
preventing the phase angle from jumping more than π radians or dropping more than –π
radians.
23-24
See Also
• If the phase angle jumps more than π radians, the chart subtracts 2π radians from the
angle.
• If the phase angle drops more than –π radians, the chart adds 2π radians to the angle.
See Also
More About
• “Complex Data in Stateflow Charts” on page 23-2
• “Supported Operations for Complex Data” on page 23-4
• “Rules for Using Complex Data in C Charts” on page 23-8
• “Best Practices for Using Complex Data in C Charts” on page 23-11
23-25
24
Events can be local to the Stateflow block or can be propagated to and from the Simulink
model and sources external to it. Data can be local to the Stateflow block or can be
shared with and passed to the Simulink model and to sources external to the Simulink
model. Messages can be local to the Stateflow block or can be passed through the
Simulink to other Stateflow blocks.
See “Export Stateflow Functions for Reuse” on page 8-22 for more details.
• The MATLAB workspace
See “Access MATLAB Functions and Workspace Data in C Charts” on page 12-32 for
more details.
• Definitions in external code sources
24-2
Specify Properties for Stateflow Charts
• Property Inspector
1 Open the Property Inspector by selecting View > Property Inspector.
2 Click in the chart.
3 In the Property Inspector, edit the chart properties.
• Model Explorer
1 Open the Model Explorer by selecting View > Model Explorer.
2 In the Model Hierarchy pane, select the chart.
3 In the Chart pane, edit the chart properties.
• Chart properties dialog box
1 Right-click in the chart.
2 Select Properties.
3 Edit the chart properties.
Name
Name of the chart (read-only). When you click the chart name hyperlink, the chart opens
in the Stateflow editor.
Machine
Name of the Simulink subsystem (read-only). When you click the machine name
hyperlink, the Machine properties dialog box opens. This property is not available in the
Property Inspector.
24-3
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Action Language
Action language that defines the syntax for state and transition actions in the chart.
Options include:
• MATLAB
• C
The default value is MATLAB. For more information, see “Differences Between MATLAB
and C as Action Language Syntax” on page 13-6.
• Classic
• Mealy
• Moore
Classic charts provide the full set of Stateflow semantics. Mealy and Moore charts use a
subset of these semantics. The default value is Classic. For more information, see
“Overview of Mealy and Moore Machines” on page 7-2.
Update Method
24-4
Specify Properties for Stateflow Charts
Setting Description
Inherited Input from the Simulink model determines when the chart wakes
up during a simulation (default).
If you define input events for the chart, the Stateflow chart is
explicitly triggered by a signal on its trigger port originating from
a connected Simulink block. You can set this trigger input event to
occur in response to a Simulink signal. The Simulink signal can be
Rising, Falling, or Either (rising and falling), or in response
to a Function Call. For more information, see “Activate a
Stateflow Chart by Sending Input Events” on page 10-9.
Sample Time
The time interval at which the Stateflow chart wakes up during simulation. The sample
time can be any nonzero number. The sample time is in the same units as the Simulink
simulation time. Other blocks in the Simulink model can have different sample times. This
option is available only when you set the chart property Update method to Discrete.
24-5
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Specifies that zero-crossing detection is enabled (default). This option is available only
when you set the chart property Update method to Continuous. See “Disable Zero-
Crossing Detection” on page 21-4.
Specifies that the operators &, ^, |, and ~ perform bitwise operations in action statements
(default). If you clear this check box:
This option is available only in charts that use C as the action language. For more
information, see “Supported Operations for Chart Data” on page 12-14.
Specifies that the chart uses explicit ordering of parallel states and transitions (default).
You determine the order in which the chart executes parallel states and tests transitions
originating from a source. This option is available only in charts that use C as the action
language. For more information, see “Execution Order for Parallel States” on page 3-86
and “Evaluate Transitions” on page 3-63.
Extends the scope of functions defined at the root level of the chart to other parts of the
model. This option enables Simulink Caller blocks to call Stateflow functions in the local
hierarchy by using qualified notation chartName.functionName. For more information,
see “Export Stateflow Functions for Reuse” on page 8-22.
Enables Stateflow and Simulink Caller blocks throughout the model to call functions
exported from Stateflow without using qualified notation. This option is available only
when you select the chart property Export Chart Level Functions. For more
information, see “Export Stateflow Functions for Reuse” on page 8-22.
Enables charts to interface directly with signals from Simulink models (default). The chart
accepts only input signals whose data type matches the type of the corresponding
24-6
Specify Properties for Stateflow Charts
Stateflow data object. Otherwise, a type mismatch error occurs. This option is available
only in charts that use C as the action language. For more information, see “Strong Data
Typing with Simulink Inputs and Outputs” on page 9-39.
Note The Use Strong Data Typing with Simulink I/O chart property is provided for
backward compatibility. Clearing this check box can produce unpredictable results and is
not recommended.
Specifies that the chart initializes its state configuration at time 0 instead of at the first
occurrence of an input event. For more information, see “Execution of a Chart at
Initialization” on page 3-42.
Specifies that the chart resets its output values every time that the chart wakes up, not
only at time 0. Output values are reset whenever a chart is triggered by function call,
edge trigger, or clock tick. If you set an initial value for an output data object, the output
resets to that value. Otherwise, the output resets to zero. Select this option to:
Specifies that the chart can take multiple transitions in each time step until it reaches a
stable state. This option is not available when you set the chart property Update method
to Continuous. For more information, see “Super Step Semantics” on page 3-73.
Specifies the maximum number of transitions that the chart can take in each time step.
The chart always takes one transition during a super step, so the value N that you specify
represents the maximum number of additional transitions (for a total of N+1). This option
24-7
24 Define Interfaces to Simulink Models and the MATLAB Workspace
is available only when you select the chart property Enable Super Step Semantics. For
more information, see “Maximum Number of Iterations” on page 3-73.
Specifies how the chart behaves after it reaches the maximum number of transitions in a
time step.
Setting Description
Proceed Chart execution continues to the next time step.
Throw Error Simulation stops and an error message appears. This setting is
valid only for simulation. In generated code, chart execution
always proceeds.
This option is available only when you select the chart property Enable Super Step
Semantics.
Specifies that chart supports input and output data that varies in dimension during
simulation. See “Declare Variable-Size Inputs and Outputs” on page 18-2.
Specifies that integer overflows saturate in the generated code. See “Handle Integer
Overflow for Chart Data” on page 9-45.
Specifies how states behave when function-call input events reenable the chart. Options
include:
• Held
• Reset
See “Control States in Charts Enabled by Function-Call Input Events” on page 10-14.
Specifies that the chart produces active state output. When you enable this option, you
can select one of these activity types to output:
24-8
Specify Properties for Stateflow Charts
• Child activity
• Leaf state activity
See “Monitor State Activity Through Active State Data” on page 24-26.
Fixed-Point Properties
You can set fixed-point properties for the chart in:
Fixed-point properties are available only in charts that use MATLAB as the action
language.
Specifies whether the chart treats inherited fixed-point and integer signals as Fixed-Point
Designer™ fi objects.
Setting Description
Fixed-point The chart treats all fixed-point inputs as fi objects (default).
Fixed-point & The chart treats all fixed-point and integer inputs as fi objects.
Integer
Setting Description
Same as MATLAB Use the same fimath properties as the current default fimath
object in MATLAB.
Specify Other Use your own default fimath object. You can:
24-9
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Additional Properties
You can set additional properties for the chart in:
Description
Description of the chart. You can enter a brief description and comments.
Document Link
Link to online documentation for the chart. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow evaluates the link and displays the documentation.
Machine Properties
The Stateflow machine represents all of the Stateflow blocks in a model (including all
charts, state transition tables, and truth tables). You can specify machine properties in the
Machine properties dialog box.
1 Open the Model Explorer or the Chart properties dialog box for any chart in the
model.
2 In the Machine chart property field, click the machine name link.
3 In the Machine properties dialog box, edit the properties for the Stateflow machine.
Simulink Model
Name of the Simulink model that defines this Stateflow machine (read-only). You change
the model name when you save the model.
Creation Date
24-10
See Also
Creator
Modified
Version
Description
Description of the Stateflow machine. You can enter a brief description and comments.
Document Link
Link to online documentation for the Stateflow machine. You can enter a web URL
address or a MATLAB command that displays documentation in a suitable online format,
such as an HTML file or text in the MATLAB Command Window. When you click the
Document link hyperlink, Stateflow evaluates the link and displays the documentation.
See Also
More About
• “Differences Between MATLAB and C as Action Language Syntax” on page 13-6
• “Overview of Mealy and Moore Machines” on page 7-2
• “Continuous-Time Modeling in Stateflow” on page 21-2
• “Supported Operations for Chart Data” on page 12-14
24-11
24 Define Interfaces to Simulink Models and the MATLAB Workspace
The Input from Simulink event has an Either edge-trigger type. If you define more than
one Input from Simulink event, the Simulink model determines the sample times to be
24-12
Implement Interfaces to Simulink Models
consistent with various rates of all the incoming signals. The outputs of a triggered
Stateflow block are held after the execution of the block.
• Set the chart property Update method to Discrete and enter a Sample Time
value. See “Update Method” on page 24-4.
• Add and define input data either in the Stateflow Editor by selecting Chart > Add
Inputs & Outputs > Data Input from Simulink or in the Model Explorer. See
“Share Input and Output Data with Simulink” on page 9-23.
Simulink determines the chart sample time to be consistent with the rate of the incoming
data signal.
The Sample Time you set in the Chart properties dialog box takes precedence over the
sample time of any input data.
You specify a discrete sample rate to have Simulink trigger a Stateflow block that does
use an explicit trigger port. You can specify a sample time for the chart in the Chart
properties dialog box. Simulink then calls the Stateflow block at a defined, regular sample
time.
The outputs of a sampled Stateflow block are held after the execution of the block.
24-13
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Simulink can trigger a Stateflow block that does not use an explicit trigger port or a
specified discrete sample time. In this case, the Simulink calls the Stateflow block at a
sample time determined by the model.
In this example, the chart contains two Input from Simulink data objects. Simulink
determines the sample times to be consistent with the rates of both incoming signals.
The outputs of an inherited trigger Stateflow block are held after the execution of the
block.
24-14
Implement Interfaces to Simulink Models
programmed function-call subsystem and a Stateflow block in the model. Use the
following steps to connect the Stateflow block to the function-call subsystem and trigger
it during simulation.
1 In your chart, select Chart > Add Inputs & Outputs > Event Output To Simulink.
The Event properties dialog box appears with a default name of event and a Scope
of Output to Simulink.
2 Set Trigger to Function Call.
3 Name the event appropriately and click OK to close the dialog box.
An output port with the name of the event you add appears on the right side of the
Stateflow block.
4 Connect the output port on the Stateflow block for the function-call output event to
the input trigger port of the subsystem.
Avoid placing any other blocks in the connection lines between the Stateflow block
and the function-call subsystem.
Note You cannot connect a function-call output event from a chart to a Demux block
to trigger multiple subsystems.
5 To execute the function-call subsystem, include an event broadcast of the function-
call output event in the actions of the chart.
For examples of using function-call output events, see “Activate a Simulink Block by Using
Function Calls” on page 10-25.
• The chart has an Output to Simulink event with the trigger type set to Either. See
“Activate a Simulink Block by Sending Output Events” on page 10-21.
• The Simulink block connected to the edge-triggered Output to Simulink event has
its own trigger type set to the equivalent edge trigger.
24-15
24 Define Interfaces to Simulink Models and the MATLAB Workspace
For examples of using edge-triggered output events, see “Activate a Simulink Block by
Using Edge Triggers” on page 10-21.
24-16
Reuse Charts in Models with Chart Libraries
As with other Simulink block libraries, you can specialize each instance of chart library
blocks in your model to use different data types, sample times, and other properties.
Library instances that inherit the same properties can reuse generated code.
For more information about Simulink block libraries, see “Libraries” (Simulink).
24-17
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Polymorphic logic is logic that can process data with different properties, such as
type, size, and complexity.
2 Configure the charts to inherit the properties you want to specialize.
For an example using MATLAB Function blocks, see “Create Custom Block Libraries”
(Simulink).
24-18
Customize Properties of Library Blocks
24-19
24 Define Interfaces to Simulink Models and the MATLAB Workspace
24-20
MATLAB Workspace Interfaces
To delete all the existing variables from the workspace, enter clear all at the MATLAB
command line. See the MATLAB documentation for more information.
• You can access MATLAB data or MATLAB functions using the ml namespace operator
or the ml function.
See “Access MATLAB Functions and Workspace Data in C Charts” on page 12-32 for
more information.
• You can use the MATLAB workspace to initialize chart data at the beginning of a
simulation.
See “Enter Expressions and Parameters for Data Properties” on page 9-20.
• You can save chart data to the workspace at the end of a simulation.
See “Save Data to the MATLAB Base Workspace” on page 9-25 for more information.
24-21
24 Define Interfaces to Simulink Models and the MATLAB Workspace
You decide which parameters to change through the mask user interface. You can provide
meaningful descriptions of these parameters. For example, in the model sf_car, the
shift_logic chart has a mask through which you can adjust the parameter TWAIT. To
open the Mask Parameters dialog box, double-click the Stateflow chart. This dialog box
contains a parameter description "Delay before gear change (tick)" and a box to
edit the value. This value is tied to the parameter TWAIT inside the mask. When you edit
the value in this box, Stateflow assigns the new value to TWAIT during simulation.
You can create other types of user interfaces for the mask parameters, such as check
boxes, context menus, and option buttons.
You can create masks on Stateflow blocks accessible from the Simulink library: charts,
state transition tables, and truth tables. You cannot mask atomic subcharts, states, or any
other objects within a chart.
24-22
Create a Mask to Share Parameters with Simulink
image('shift_logic.svg')
3 Click Apply.
For example, the chart shift_logic has a parameter TWAIT. To add TWAIT as a
parameter to the mask:
24-23
24 Define Interfaces to Simulink Models and the MATLAB Workspace
TWAIT
5 Click Apply.
6 Click OK.
24-24
See Also
See Also
More About
• “Share Parameters with Simulink and the MATLAB Workspace” on page 9-26
• “Masking Fundamentals” (Simulink)
• “Mask Editor Overview” (Simulink)
• “Draw Mask Icon” (Simulink)
24-25
24 Define Interfaces to Simulink Models and the MATLAB Workspace
For self-activity of a chart or state, the data value is true when active and false when
inactive. For child and leaf state activity, the data is an enumerated type. Stateflow can
define the enumeration class or you can create the definition manually. For more
information, see “Define State Activity Enumeration Type” on page 24-28.
You can enable active state data for a Stateflow chart, state, state transition table, or
atomic subchart. This table lists the activity types supported by each kind of Stateflow
object.
24-26
Monitor State Activity Through Active State Data
• Property Inspector
• Self activity
• Child activity
• Leaf state activity
Data Name
Name of the active state data object. For more information, see “Rules for Naming
Stateflow Objects” on page 2-4.
24-27
24 Define Interfaces to Simulink Models and the MATLAB Workspace
Enum Name
Name of the enumerated data type for the active state data object. This property applies
only to child and leaf state activity.
Specifies whether you define the enumerated data type manually. This property applies
only to child and leaf state activity. For more information, see “Define State Activity
Enumeration Type” on page 24-28.
To access active state data inside a Stateflow chart, change the scope to Local in the
Symbols window or in the Model Explorer. For more information, see “Set Data
Properties” on page 9-5.
You can specify information for code generation by binding the local active state data to a
Simulink.Signal object. Modify the properties of the object through the CoderInfo
property. For more information, see Simulink.CoderInfo.
24-28
Monitor State Activity Through Active State Data
The enumeration data type definition contains one literal for each state name plus an
extra literal to indicate that no substate is active. For example, in the model sf_car, the
state gear_state contains four child states that correspond to the gears in a car: first,
second, third, fourth. The model specifies the child activity data type with this
enumeration class definition:
classdef gearType < Simulink.IntEnumType
enumeration
None(0),
first(1),
second(2),
third(3),
fourth(4)
end
...
end
For more information, see “Define Enumerated Data Types” on page 19-6.
The base storage type for automatically created enumerations defaults to Native
Integer. For a smaller memory footprint, in the Optimization pane of the Configuration
Parameters dialog box, change the value of the Base storage type for automatically
24-29
24 Define Interfaces to Simulink Models and the MATLAB Workspace
created enumerations field. For more information, see “Base storage type for
automatically created enumerations” (Simulink Coder).
During simulation, a scope connected to the active state output data shows the
enumerated values for the leaf states A1, A2, and B.
24-30
See Also
See Also
Simulink.Signal | Simulink.CoderInfo
24-31
24 Define Interfaces to Simulink Models and the MATLAB Workspace
More About
• “Simplify Stateflow Charts by Incorporating Active State Output” on page 24-37
• “View State Activity by Using the Simulation Data Inspector” on page 24-33
• “Check State Activity by Using the in Operator” on page 12-77
• “Rules for Naming Stateflow Objects” on page 2-4
• “Define State Activity Enumeration Type” on page 24-28
• “Base storage type for automatically created enumerations” (Simulink Coder)
24-32
View State Activity by Using the Simulation Data Inspector
To log a signal with the Simulation Data Inspector, highlight the signal line that you want
to log. Right-click the gear signal and choose Log Selected Signals from the context
menu. A logging badge appears next to the gear signal, indicating that the data from that
signal is logged when the model is run.
24-33
24 Define Interfaces to Simulink Models and the MATLAB Workspace
24-34
View State Activity by Using the Simulation Data Inspector
1 In your Stateflow chart, select the states whose activity you want to log.
2 On the Simulink Editor toolbar, click the Simulation Data Inspector drop-down and
select Logging for selected states > Self state activity.
After running one or more simulations with signals marked for logging, click Simulation
Data Inspector button on the Simulink editor toolbar and view your data. Multiple
runs show up in the Inspect pane and can be viewed together. To choose which signals
you want to plot, use the check boxes next to the signal names.
24-35
24 Define Interfaces to Simulink Models and the MATLAB Workspace
See Also
More About
• “Monitor State Activity Through Active State Data” on page 24-26
• “Simplify Stateflow Charts by Incorporating Active State Output” on page 24-37
• Simulation Data Inspector
• “Inspect Simulation Data” (Simulink)
• “Compare Simulation Data” (Simulink)
24-36
Simplify Stateflow Charts by Incorporating Active State Output
In the legacy model old_sf_car, the Stateflow chart shift_logic tracks child state
activity in gear_state by updating the value of the output data gear.
By incorporating active state data, the model sf_car avoids manual data updates
reflecting chart activity. Instead, the chart outputs child state activity automatically
through the active state output gear.
24-37
24 Define Interfaces to Simulink Models and the MATLAB Workspace
24-38
Simplify Stateflow Charts by Incorporating Active State Output
24-39
24 Define Interfaces to Simulink Models and the MATLAB Workspace
See Also
More About
• “Monitor State Activity Through Active State Data” on page 24-26
• “View State Activity by Using the Simulation Data Inspector” on page 24-33
• “Manage Data, Events, and Messages in the Symbols Window” on page 33-2
24-40
Specify Units for Stateflow Data
To display the units on the Simulink lines in the model, select Display > Signals and
Ports > Port Units.
Consistency Checking
Stateflow checks the consistency of the signal line unit from Simulink with the unit
setting for the corresponding input or output data in the Stateflow block. If the units do
not match, Stateflow displays a warning during model update.
See Also
More About
• “Unit Specification in Simulink Models” (Simulink)
24-41
25
• Inputs and outputs that access Simulink bus signals from Stateflow charts, Truth Table
blocks, and MATLAB Function blocks.
• Local data in Stateflow charts, truth tables, graphical functions, MATLAB functions,
and boxes.
• Temporary data in Stateflow graphical functions, truth tables, and MATLAB functions.
For example, in the model sf_bus_demo, a Stateflow chart receives a bus input signal by
using the structure inbus and outputs a bus signal from the structure outbus. The input
signal comes from the Simulink Bus Creator block COUNTERBUSCreator, which bundles
signals from two other Bus Creator blocks. The output structure outbus connects to a
Simulink Bus Selector block. Both inbus and outbus derive their type from the
Simulink.Bus object COUNTERBUS.
The elements of a Stateflow structure data type are called fields. Fields can be any
combination of individual signals, muxed signals, vectors, and other structures (also
called substructures). Each field has its own data type. The data type does not have to
match the type of any other field in the structure. For example, in the model
sfbus_demo, each of the structures inbus and outbus has two fields:
25-2
Access Bus Signals Through Stateflow Structures
• Input
• Output
• Local
• Parameter
• Temporary
4 Set the Type property for the structure. Depending on its scope, a Stateflow
structure can have one of these data types.
25-3
25 Structures and Bus Signals in Stateflow Charts
Type Description
Inherit: Same as This option is available for input structures only. The input structure
Simulink inherits its data type from the Simulink bus signal in your model that
connects to it. The Simulink bus signal must be a nonvirtual bus. For
more information, see “Virtual and Nonvirtual Buses” on page 25-6.
If the input signal comes from a Bus Creator block, in the Bus Creator
dialog box, specify an appropriate bus object for Output data type
field. When you specify the bus object, Simulink verifies that the
properties of the Simulink.Bus object in the base workspace match
the properties of the Simulink bus signal.
Bus: <object In the Type field, replace <object name> with the name of the
name> Simulink.Bus object that defines the Stateflow structure.
For input or output structures, you are not required to specify the bus
signal in your Simulink model that connects to the Stateflow structure.
If you do specify a bus signal, its properties must match the
Simulink.Bus object that defines the Stateflow structure.
<date type In the Type field, replace <data type expression> with an
expression> expression that evaluates to a data type. For example:
25-4
Access Bus Signals Through Stateflow Structures
For example, in the sfbus_demo model, the input structure inbus and the output
structure outbus derive their type through a type specification of the form Bus:
COUNTERBUS.
25-5
25 Structures and Bus Signals in Stateflow Charts
Stateflow charts support only nonvirtual buses. Stateflow input structures can accept
virtual bus signals and convert them to nonvirtual bus signals. Stateflow input structures
cannot inherit properties from virtual bus signals. If the input to a chart is a virtual bus,
set the Type property of the input structure through a type specification of the form Bus:
<object name>.
Debug Structures
To debug a Stateflow structure, open the Stateflow Breakpoints and Watch window and
examine the values of structure fields during simulation. To view the values of structure
fields at the command line, use dot notation to index into the structure. For more
25-6
See Also
information, see “Watch Stateflow Data Values” on page 32-36 and “Index Substructures
and Fields” on page 25-8.
See Also
Simulink.Bus
Related Examples
• “Interface Simulink Bus Signals and Integrate Custom C Code”
More About
• “Index and Assign Values to Stateflow Structures” on page 25-8
• “Integrate Custom Structures in Stateflow Charts” on page 25-11
• “Add Stateflow Data” on page 9-2
• “Derive Data Types from Other Data Objects” on page 9-37
• “Watch Stateflow Data Values” on page 32-36
• “Create Bus Objects with the Bus Editor” (Simulink)
• “Virtual and Nonvirtual Buses” (Simulink)
25-7
25 Structures and Bus Signals in Stateflow Charts
For example, the C chart in this model contains an input structure in, an output structure
out, and a local structure subbus.
25-8
Index and Assign Values to Stateflow Structures
The fields of the input structure in and the output structure out have the same name as
the elements of Simulink.Bus object BusObject that defines them: sb, a, b, and c. The
field of the local structure subbus has the same name ele as the element of
Simulink.Bus object SubBus. This table lists how the Stateflow chart resolves symbols
in dot notation for indexing the fields of these structures.
Note In this example, the Stateflow chart uses brackets and zero-based indexing for
vectors and arrays because C is the action language for the chart. For more information,
see “Differences Between MATLAB and C as Action Language Syntax” on page 13-6.
• To assign one structure to another structure, define both structures from the same
Simulink.Bus object in the base workspace.
• To assign one structure to a substructure of a different structure (or vice versa), define
the structure and substructure from the same Simulink.Bus object.
• To assign a field of one structure to a field of another structure, the fields must have
the same type and size. You can define the Stateflow structures from different
Simulink.Bus objects.
This table presents valid and invalid structure assignments based on the structure
specifications for the previous example.
25-9
25 Structures and Bus Signals in Stateflow Charts
See Also
Simulink.Bus
More About
• “Access Bus Signals Through Stateflow Structures” on page 25-2
• “Identify Data by Using Dot Notation” on page 9-50
25-10
Integrate Custom Structures in Stateflow Charts
...
typedef struct {
int input;
} SIGNALBUS;
typedef struct {
int upper_saturation_limit;
int lower_saturation_limit;
25-11
25 Structures and Bus Signals in Stateflow Charts
} LIMITBUS;
typedef struct {
SIGNALBUS inputsignal;
LIMITBUS limits;
} COUNTERBUS;
...
2 In the Bus Editor, define a Simulink.Bus object that matches each custom structure
typedef declaration. In the Header file field of each Simulink.Bus object, enter
the name of the header file that contains the matching typedef declaration.
• To include custom code for simulation, see “Access Custom C Code in Nonlibrary
Charts” on page 30-5.
• To include custom code for code generation, see “Integrate External Code by
Using Model Configuration Parameters” (Simulink Coder).
4 Build and run your model.
25-12
Integrate Custom Structures in Stateflow Charts
For more information, see “Index Substructures and Fields” on page 25-8.
For instance, the model sfbus_demo contains a custom C function counterbusFcn that
takes structure pointers as arguments. The custom header file contains this function
declaration:
The chart passes the addresses to the Stateflow structures counterbus_struct and
outbus by using this function call:
The function reads the value of the chart input u2 and the local structure
counterbus_struct. It writes to the chart output y2 and the output structure outbus.
25-13
25 Structures and Bus Signals in Stateflow Charts
See Also
Simulink.Bus
Related Examples
• “Interface Simulink Bus Signals and Integrate Custom C Code”
More About
• “Access Bus Signals Through Stateflow Structures” on page 25-2
• “Index and Assign Values to Stateflow Structures” on page 25-8
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “Integrate External Code by Using Model Configuration Parameters” (Simulink
Coder)
• “Identify Data by Using Dot Notation” on page 9-50
25-14
26
If you model a controller in a Stateflow chart, you do not want your switch logic to
overwork the controller by turning it on and off in response to every transient signal it
receives. To avoid this, design a Stateflow controller that uses temporal logic to debounce
your input signals and determine whether a switch is actually on or off.
26-2
Reduce Transient Signals by Using Debouncing Logic
26-3
26 Stateflow Design Patterns
The initial state for this model is Off. Using the duration operator, you can control what
state the model is in based on how long the switch signal, sw, has been greater or less
than zero. Once sw has been greater than or equal to zero for longer than 0.1 seconds,
the switch moves from state Off to state On. Then, if sw has been less than zero for
longer than 0.01 seconds, the switch moves from state On to state Off.
State Logic
The debouncer has two states, On and Off. The duration operator controls which state
is active. The logic works as described in this table.
26-4
Reduce Transient Signals by Using Debouncing Logic
The scope shows how the debouncer isolates transient signals from the noisy input
signal.
26-5
26 Stateflow Design Patterns
26-6
Reduce Transient Signals by Using Debouncing Logic
26-7
26 Stateflow Design Patterns
The debouncer design uses the after(n, sec) statement to implement absolute-time
temporal logic. The keyword sec defines simulation time that has elapsed since activation
of a state.
State Logic
The debouncer chart contains an intermediate state called Debounce. The Debounce state
isolates transient inputs by checking whether the signals retain their positive or negative
values, or fluctuate between zero crossings over a prescribed period. The logic works as
shown in this table.
26-8
Reduce Transient Signals by Using Debouncing Logic
The scope shows how the debouncer isolates transient signals from the noisy input
signal.
26-9
26 Stateflow Design Patterns
26-10
See Also
The Error Generator block in the sf_debouncer model generates a pulse signal every
0.001 second. Therefore, to convert the absolute-time temporal logic specified in the
Debouncer chart to event-based logic, multiply the n argument by 1000, as follows.
See Also
duration
More About
• “Operators for Absolute-Time Temporal Logic” on page 12-56
• “Operators for Event-Based Temporal Logic” on page 12-50
• “Define Chart Behavior by Using Implicit Events” on page 10-33
26-11
26 Stateflow Design Patterns
See Also
Related Examples
• “Schedule Simulink Algorithms by Using Stateflow”
More About
• “Control Chart Execution by Using Temporal Logic” on page 12-49
26-12
Schedule Execution of Simulink Subsystems
Types of Schedulers
You can implement the following types of schedulers using Stateflow charts.
Scheduler Description
Design Pattern
Ladder logic Schedules multiple Simulink subsystems to execute in a single time
scheduler on step
page 26-14
Loop scheduler Schedules one Simulink subsystem to execute multiple times in a single
on page 26-18 time step
Temporal logic Schedules Simulink subsystems to execute at specific times
scheduler on
page 26-22
26-13
26 Stateflow Design Patterns
26-14
Schedule Multiple Subsystems in a Single Step
In a given time step, the Stateflow chart broadcasts a series of function-call output events
to trigger the execution of three function-call subsystems — A1, A2, and A3 — in the
Simulink model in an order determined by the ladder logic scheduler. Here is the
sequence of activities during each time step:
1 The Simulink model activates the Stateflow chart Edge to Function at a rising edge of
the 1-millisecond pulse generator.
2 The Edge to Function chart broadcasts the function-call output event call to
activate the Stateflow chart Ladder Logic Scheduler.
26-15
26 Stateflow Design Patterns
3 The Ladder Logic Scheduler chart broadcasts function-call output events to trigger
the function-call subsystems A1, A2, and A3, based on the values of inputs u1 and u2
(see “Flow Chart Determines Order of Execution” on page 26-16).
The Ladder Logic Scheduler chart uses Stateflow flow charting capabilities to implement
the logic that schedules the execution of the Simulink function-call subsystems. The chart
contains a Stateflow flow chart that resembles a ladder diagram. Each rung in the ladder
represents a rule or condition that determines whether to execute one of the Simulink
function-call subsystems. The flow logic evaluates each condition sequentially, which has
the effect of scheduling the execution of multiple subsystems within the same time step.
The chart executes each subsystem by using the send action to broadcast a function-call
output event (see “Directed Local Event Broadcast Using send” on page 12-45).
Here is the sequence of activities that occurs in the Ladder Logic Scheduler chart in each
time step:
The subsystem connected to A2 executes. This subsystem outputs its input value
unchanged. Control returns to the next condition in the Ladder Logic Scheduler.
4 If u1 and u2 are positive, send function-call output event A3 to the Simulink model.
26-16
Schedule Multiple Subsystems in a Single Step
The scope shows how output y changes, depending on which subsystems the Ladder
Logic Scheduler chart calls during each time step.
Tip If you keep the chart closed, the simulation runs much faster. For other tips, see
“Speed Up Simulation” on page 30-17.
26-17
26 Stateflow Design Patterns
26-18
Schedule A Subsystem Multiple Times in a Single Step
In a given time step, the Stateflow chart broadcasts a function-call output event to trigger
the execution of the function-call subsystem A1 multiple times in the Simulink model.
Here is the sequence of activities during each time step:
1 The Simulink model activates the Stateflow chart Edge to Function at a rising edge of
the 1-millisecond pulse generator.
2 The Edge to Function chart broadcasts the function-call output event call to
activate the Stateflow chart Looping Scheduler.
3 The Looping Scheduler chart broadcasts a function-call output event from a for loop
to trigger the function-call subsystem A1 multiple times (see “Flow Chart Implements
For Loop” on page 26-19).
The Looping Scheduler chart uses Stateflow flow charting capabilities to implement a for
loop for broadcasting an event multiple times in a single time step. The chart contains a
Stateflow flow chart that uses a local data variable i to control the loop. At each iteration,
26-19
26 Stateflow Design Patterns
the chart updates output y and issues the send action to broadcast a function-call output
event that executes subsystem A1. Subsystem A1 uses the value of y to recompute its
output and send the value back to the Looping Scheduler chart.
In this example, the Looping Scheduler chart executes the for loop 10 times in each time
step. During each iteration:
26-20
Schedule A Subsystem Multiple Times in a Single Step
26-21
26 Stateflow Design Patterns
26-22
Schedule Subsystems to Execute at Specific Times
In the FastScheduler state, the every operator schedules function calls as follows:
• Sends A1 every time the function-call output event call wakes up the chart
• Sends A2 at half the base rate
• Sends A3 at one-quarter the base rate
The SlowScheduler state schedules function calls less frequently — at 8, 16, and 32 times
slower than the base rate. The chart switches between fast and slow executions after
every 100 invocations of the call event.
26-23
26 Stateflow Design Patterns
26-24
Implement Dynamic Test Vectors
For example, suppose you want to test an automatic car transmission controller in the
situation where a car is coasting. To achieve a coasting state, a driver accelerates until
the transmission shifts into the highest gear, then eases up on the gas pedal. To test this
scenario, you could generate a signal that represents this behavior, as in the following
Signal Builder block.
26-25
26 Stateflow Design Patterns
However, this approach has limitations. The signal changes value based on time, but
cannot respond dynamically to changes in the system that are not governed by time
alone. For example, how does the signal know when the transmission shifts into the
highest gear? In this case, the signal assumes that the shift always occurs at time 5
26-26
Implement Dynamic Test Vectors
because it cannot test for other deterministic conditions such as the speed of the vehicle.
Moreover, you cannot change the signal based on outputs from the model.
By contrast, you can use Stateflow charts to develop test vectors that use conditional
logic to evaluate and respond to changes in system state as they occur. For example, to
test the coasting scenario, the chart can evaluate an output that represents the gear
range and reduce speed only after the transmission shifts to the highest gear. That is, the
car slows down as a direct result of the gear shift and not at a predetermined time.
The chart models the dynamic relationship between the brake and throttle to test four
driving scenarios. Each scenario is represented by a state.
26-27
26 Stateflow Design Patterns
26-28
Implement Dynamic Test Vectors
In some of these scenarios, the throttle changes in response to time; in other cases, it
responds to gear selection, an output of the Stateflow chart Shift_logic. The Shift_logic
chart determines the gear value based on the speed of the vehicle.
The Dynamic Test Vectors chart represents each test case as an exclusive (OR) state.
Each state manipulates brake and throttle values in a unique way, based on the time and
gear inputs to the chart.
The chart determines which test to execute from the value of a constant signal case,
output from the Signal Builder block. Each test case corresponds to a unique signal value.
The Dynamic Test Vectors chart uses conditions on transitions to test time and gear level,
and then adjusts brake and throttle accordingly for each driving scenario. Stateflow
charts provide many constructs for testing system state and responding to changes,
including:
• Conditional logic (see “State Action Types” on page 12-2 and “Transition Action
Types” on page 12-7)
• Temporal logic (see “Control Chart Execution by Using Temporal Logic” on page 12-
49)
• Change detection operators (see “Detect Changes in Data Values” on page 12-69)
• MATLAB functions (see “Access MATLAB Functions and Workspace Data in C Charts”
on page 12-32)
The model uses a Signal Builder block to provide an interface for selecting test scenarios
to simulate.
26-29
26 Stateflow Design Patterns
26-30
Implement Dynamic Test Vectors
To Test: Do This:
One case Click the tab that corresponds to the
driving scenario you want to test and click
the Start simulation button:
All cases and produce a model coverage Click the Run all and produce coverage
report (requires a Simulink Coverage™ button:
software license)
The Signal Builder block sends to the Dynamic Test Vectors chart one or more constant
signal values that correspond to the driving scenarios you select. The chart uses these
values to activate the appropriate test cases.
The scope shows the interaction between speed and throttle for the selected
scenario.
26-31
26 Stateflow Design Patterns
26-32
Implement Dynamic Test Vectors
26-33
26 Stateflow Design Patterns
You can use truth tables to map fault conditions of a system directly to their consequent
actions. For example, the model sf_aircraft maps the fault conditions and actions
using a truth table. For details on this model, see “Fault Detection Control Logic in an
Aircraft Elevator Control System”.
The fault detection system for the aircraft elevator control system has these
requirements.
Condition Action
Hydraulic pressure 1 failure While there are no other failures, turn off
the left outer actuator.
Hydraulic pressure 2 failure While there are no other failures, turn off
the left inner actuator and the right inner
actuator.
Hydraulic pressure 3 failure While there are no other failures, turn off
the right outer actuator.
Actuator position failure While there are no other failures, isolate
that specific actuator.
Hydraulic pressure 1 and left outer While there are no other failures, turn off
actuator failures the left outer actuator
Hydraulic pressure 2 and left inner actuator While there are no other failures, turn off
failures the left inner actuator.
Hydraulic pressure 3 and right outer While there are no other failures, turn off
actuator failures the right outer actuator
Multiple failures on left hydraulics and Isolate the left outer actuator and the left
actuators inner actuator.
Multiple failures on right hydraulics and Isolate the right outer actuator and the
actuators right inner actuator.
26-34
Map Fault Conditions to Actions by Using Truth Tables
Condition Action
Intermittent actuator failures If an actuator has been switched on and off
five times during operation, isolate that
specific actuator.
Logic to satisfy these requirements is constructed using two truth tables in the chart
Mode Logic; one for the right elevator (R_switch), and one for the left elevator
(L_switch). This truth table is for the left elevator.
26-35
26 Stateflow Design Patterns
26-36
Map Fault Conditions to Actions by Using Truth Tables
The first requirement indicates that if a failure is only detected in the hydraulic pressure
1 system, turn off the left outer actuator. This requirement is represented in the decision
D1 in the truth table. If there is low pressure in the hydraulic system 1, then D1 specifies
that action 2 is performed. Action 2 sends an event go_off to the left actuator,
Actuators.LO.
Similarly, the other requirements are mapped to the appropriate actions in the truth
table. For example, if the left outer actuator fails, D3 causes action 3. Action 3 sends the
event go_isolated to Actuators.LO to isolate the left actuator.
The truth tables are called at entry(en) and during(du) actions for the chart so that fault
checks execute at each time step.
26-37
26 Stateflow Design Patterns
There are two elevators in the system, each with an outer and inner actuator. The
Actuators state has a corresponding substate for each of the four actuators. An actuator
has five modes: Passive, Active, Standby, Off, and Isolated. By default, the outer
actuators are on, and the inner actuators are on standby. If a fault is detected in the outer
actuators, the system responds to maintain stability by turning the outer actuators off and
activating the inner actuators.
26-38
Design for Isolation and Recovery in a Chart
26-39
26 Stateflow Design Patterns
The go_off event instructs the failing actuator to transition to the Off state until the
condition is resolved. The event go_isolated causes the failing actuator to transition to
Isolated. Transitions to the Isolated state are from the superstate L1, which contains
all the other operating modes. This state has no outgoing transitions, so that once an
actuator has entered Isolated it remains there. Intermittent failures that cause an
actuator to fail 5 or more times, also cause a transition to Isolated. The variable fails
logs the number of failures for an actuator by incrementing each time a transition occurs
out of Off.
For example, one requirement of the system is if one outer actuator fails, then the other
outer actuator must move to standby and the inner actuators take over. Consequently,
there is a transition from each Active state to Standby, and vice versa.
26-40
Design for Isolation and Recovery in a Chart
For the inner left actuator (LI ), the transition to Active inside the L1 superstate is
conditionally based on [!LO_act()|RI_act()]. This causes the left inner actuator to
turn on if the outer actuator (LO) has failed, or the right inner actuator (RI) has turned
on.
26-41
26 Stateflow Design Patterns
Another consequence if LO fails and moves out of Active is a transition that occurs in the
right outer actuator (RO). The RO state transitions inside the L1 superstate from Active
to Standby. This satisfies the requirement of the outer actuators and inner actuators to
work in symmetry.
26-42
27
You can add a Truth Table block directly to your Simulink model. You can also define a
truth table function in a Stateflow chart, state, or subchart. The location of the function
determines the set of states and transitions that can call the function.
• If you want to call the function only within one state or subchart and its substates, put
your truth table function in that state or subchart. That function overrides any other
functions of the same name in the parents and ancestors of that state or subchart.
• If you want to call the function anywhere in that chart, put your truth table function at
the chart level.
• If you want to call the function from any chart in your model, put your truth table at
the chart level and enable exporting of chart-level functions. For more information, see
“Export Stateflow Functions for Reuse” on page 8-22.
For example, this truth table function has the name ttable. It takes three arguments (x,
y, and z) and returns one output value (r).
27-2
Reuse Combinatorial Logic by Defining Truth Tables
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), F
(false), or - (true or false). Each of the decision columns combines an outcome for each
condition with a logical AND into a compound condition, which is referred to as a
decision.
You evaluate a truth table one decision at a time, starting with Decision 1. The Default
Decision covers all possible remaining decisions. If one of the decisions is true, you
perform its action, and then the truth table execution is complete.
Pseudocode Description
if ((x == 1) & !(y == 1) & !(z == 1)) If Decision 1 is true, then set r=1.
r = 1;
If Decision 2 is true, then set r=2.
elseif (!(x == 1) & (y == 1) & !(z == 1))
r = 2;
If Decision 3 is true, then set r=3.
elseif (!(x == 1) & !(y == 1) & (z == 1))
r = 3;
else If all other decisions are false, then Default
r = 4; Decision is true. Set r=4.
endif
27-3
27 Truth Table Functions for Decision-Making Logic
3 Program the truth table function. For more information, see “Program a Truth Table”
on page 27-11.
4 In the Model Explorer, expand the chart object and select the truth table function.
The arguments and return values of the function signature appear as data items that
belong to your function. Arguments have the scope Input. Return values have the
scope Output.
5 In the Data properties dialog box for each argument and return value, specify the
data properties, as described in “Set Data Properties” on page 9-5.
6 Create any additional data items required by your function. For more information, see
“Add Data Through the Model Explorer” on page 9-3.
Your function can access its own data or data belonging to parent states or the chart.
The data items in the function can have one of these scopes:
• Local — Local data persists from one function call to the next function call. Valid
for C charts only.
• Constant — Constant data retains its initial value through all function calls.
• Parameter — Parameter data retains its initial value through all function calls.
• Temporary — Temporary data initializes at the start of every function call. Valid
for C charts only.
In charts that use C as the action language, define temporary data when you want to use
data that is only valid while a function executes. For example, you can designate a loop
counter to have Temporary scope if the counter value does not need to persist after the
function completes.
In charts that use MATLAB as the action language, you do not need to define temporary
function data. If you use an undefined variable, Stateflow creates a temporary variable.
The variable is available to the rest of the function.
You can initialize your function data (other than arguments and return values) from the
MATLAB workspace. For more information, see “Initialize Data from the MATLAB Base
Workspace” on page 9-24.
27-4
Reuse Combinatorial Logic by Defining Truth Tables
You can specify multiple return values and multiple input arguments. Each return value
and input argument can be a scalar, vector, or matrix of values. For functions with only
one return value, omit the brackets in the signature label.
You can use the same variable name for both arguments and return values. For example,
a function with this signature label uses the variables y1 and y2 as both inputs and
outputs:
If you export this function to C code, y1 and y2 are passed by reference (as pointers), and
u is passed by value. Passing inputs by reference reduces the number of times that the
generated code copies intermediate data, resulting in more optimal code.
The syntax for a call to a truth table function is the same as the function signature, with
actual arguments replacing the formal ones specified in a signature. If the data types of
an actual and formal argument differ, a function casts the actual argument to the type of
the formal argument.
Tip If the formal arguments of a function signature are scalars, verify that inputs and
outputs of function calls follow the rules of scalar expansion. For more information, see
“How Scalar Expansion Works for Functions” on page 17-9.
27-5
27 Truth Table Functions for Decision-Making Logic
Name
Function name. Click the function name link to bring your function to the foreground in
its native chart.
Label
Signature label for your function. For more information, see “Declare Function Arguments
and Return Values” on page 27-4.
Underspecification
Controls the level of diagnostics for underspecification in your truth table function. For
more information, see “Correct Overspecified and Underspecified Truth Tables” on page
27-44.
Overspecification
Controls the level of diagnostics for overspecification in your truth table function. For
more information, see “Correct Overspecified and Underspecified Truth Tables” on page
27-44.
Action Language
Controls the action language for your Stateflow truth table function. Choose between
MATLAB or C. For more information, see “Language Options for Stateflow Truth Tables”
on page 27-8.
Description
Function description. You can enter brief descriptions of functions in the hierarchy.
27-6
See Also
Document Link
Link to online documentation for the function. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow displays the documentation.
See Also
More About
• “Represent Combinatorial Logic Using Truth Tables” on page 27-10
• “Program a Truth Table” on page 27-11
• “Language Options for Stateflow Truth Tables” on page 27-8
• “Reusable Functions in Charts” on page 2-46
• “Export Stateflow Functions for Reuse” on page 8-22
• “Reuse Functions by Using Atomic Boxes” on page 8-35
27-7
27 Truth Table Functions for Decision-Making Logic
C Truth Tables
Using C truth tables, you can specify conditions and actions with C as the action
language. C truth tables support basic C constructs and provide access to MATLAB
functions by using the ml namespace operator or ml function. To use C as the action
language for your truth table, it must be inside a Stateflow C action language chart.
• MATLAB as the action language provides a richer syntax for specifying control flow
logic in truth table actions. It provides for loops, while loops, nested if statements,
and switch statements.
• You can call MATLAB functions directly in truth table actions. Also, you can call library
functions (for example, MATLAB sin and fft functions) and generate code for these
functions by using Simulink Codersoftware.
• You can create temporary or persistent variables during simulation or in code directly
without having to define them in the Model Explorer.
• You have access to better debugging tools. You can set breakpoints on lines of code,
step through code, and watch data values tool tips.
• You can use persistent variables in truth table actions. You can define data that
persists across multiple calls to the truth table function during simulation.
27-8
Language Options for Stateflow Truth Tables
Note If you do not have the option to change the action language, your truth table is a
MATLAB truth table.
27-9
27 Truth Table Functions for Decision-Making Logic
27-10
Program a Truth Table
By default, a truth table contains a Condition Table and an Action Table, each with one
row. The Condition Table contains a single decision column, D1, and a single action row.
27-11
27 Truth Table Functions for Decision-Making Logic
You enter conditions in the Condition column of the Condition Table. For each condition
that you enter, you can enter an optional description in the Description column. To enter
conditions for the truth table ttable:
1 Click the row on the Condition Table that you want to append.
2
Click the Append Row button on the side panel twice.
The truth table appends two rows to the bottom of the Condition Table.
3 Click and drag the bar that separates the Condition Table and the Action Table
panes down to enlarge the Condition Table pane.
4 In the Condition Table, click the top cell of the Description column.
Condition descriptions are optional, but appear as comments in the generated code
for the truth table.
6 To select the next cell on the right in the Condition column, press the right arrow.
7 In the first cell of the Condition column, enter:
XEQ1:
This text is an optional label that you can include with the condition. Each label must
begin with an alphabetic character ([a-z][A-Z]) followed by any number of
alphanumeric characters ([a-z][A-Z][0-9]) or an underscore (_).
8 Press Enter and this text:
x == 1
27-12
Program a Truth Table
This text is the actual condition. Each condition that you enter must evaluate to zero
(false) or nonzero (true). You can use optional brackets in the condition (for example,
[x == 1]).
In truth table conditions, you can use data that passes to the truth table function
through its arguments. The preceding condition tests whether the argument x is
equal to 1. You can also use data defined for parent objects of the truth table,
including the chart.
9 Repeat the preceding steps to enter the other two conditions.
27-13
27 Truth Table Functions for Decision-Making Logic
Pressing the space bar toggles through the possible values of F, T, and -. You can
also enter these characters directly. Pressing 1 sets the value to T, while pressing 0
sets the value to F. Pressing x sets the value to -.
5 Press the down arrow key to advance to the next cell down in the D1 column.
In the decision columns, you can use the arrow keys to advance to another cell in any
direction. You can also use the right and left arrow keys to advance left or right in
these cells.
6 Enter the remaining values for the decision columns:
27-14
Program a Truth Table
During execution of the truth table, decision testing occurs in left-to-right order. The
order of testing for individual condition outcomes within a decision is undefined. Truth
tables evaluate the conditions for each decision in top-down order (first condition 1, then
condition 2, and so on). Because this implementation is subject to change in the future, do
not rely on a specific evaluation order.
The last decision column in ttable, D4, is the default decision for this truth table. The
default decision covers any decisions not tested for in preceding decision columns to the
27-15
27 Truth Table Functions for Decision-Making Logic
left. You enter a default decision as the last decision column on the right with an entry of
- for all conditions in the decision. This entry represents any outcome for the condition, T
or F.
In the preceding example, the default decision column, D4, specifies these decisions:
Tip The default decision column must be the last column on the right in the Condition
Table.
In “Enter Truth Table Decisions” on page 27-14, you entered decisions in the truth table.
The next step is to enter actions you want to occur for each decision in the Action Table.
Later, you assign these actions to their decisions in the Actions row of the Condition
Table.
This section describes how to program truth table actions with these topics:
• “Set Up the Action Table” on page 27-17 — Shows you how to set up the Action Table
in truth table ttable.
• “Program Actions Using C Expressions” on page 27-18 — Provides sample code to
program actions in ttable. Follow this section if you selected C as the language for
this truth table.
• “Program Actions Using MATLAB Expressions” on page 27-21 — Provides sample
MATLAB code to program actions in ttable. Follow this section if you selected
MATLAB as the language for this truth table.
27-16
Program a Truth Table
27-17
27 Truth Table Functions for Decision-Making Logic
3 Program the actions using the language you selected for the truth table.
Follow this procedure to program your actions using C as the action language:
1 Click the top cell in the Description column of the Action Table.
set r to 1
Action descriptions are optional, but appear as comments in the generated code for
the truth table.
3 Press the right arrow key to select the next cell on the right, in the Action column.
4 Enter the following text:
A1:
You begin an action with an optional label followed by a colon (:). Later, you enter
these labels in the Actions row of the Condition Table to specify an action for each
decision column. Like condition labels, action labels must begin with an alphabetic
character ([a-z][A-Z]) followed by any number of alphanumeric characters ([a-z]
[A-Z][0-9]) or an underscore (_).
5 Press Enter and enter the following text:
r=1;
In truth table actions, you can use data that passes to the truth table function
through its arguments and return value. The preceding action, r=1, sets the value of
the return value r. You can also specify actions with data defined for a parent object
of the truth table, including the chart. Truth table actions can also broadcast or send
events that are defined for the truth table, or for a parent, such as the chart itself.
27-18
Program a Truth Table
Tip If you omit the semicolon at the end of an action, the result of the action echoes
to the MATLAB Command Window when the action executes during simulation. Use
this echoing option as a debugging tool.
6 Enter the remaining actions in the Action Table, as shown:
27-19
27 Truth Table Functions for Decision-Making Logic
Now you are ready to assign actions to decisions, as described in “Assign Truth Table
Actions to Decisions” on page 27-24.
27-20
Program a Truth Table
If you selected MATLAB as the action language, you can write MATLAB code to program
your actions. Using this code, you can add control flow logic and call MATLAB functions
directly. In the following procedure, you program an action in the truth table ttable,
using the following features of MATLAB syntax:
• Persistent variables
• if ... else ... end control flows
• for loop
1 Click the top cell in the Description column of the Action Table.
Action descriptions are optional, but appear as comments in the generated code for
the truth table.
3 Press the right arrow key to select the next cell on the right, in the Action column.
4 Enter the following text:
A1:
You begin an action with an optional label followed by a colon (:). Later, you enter
these labels in the Actions row of the Condition Table to specify an action for each
decision column. Like condition labels, action labels must begin with an alphabetic
character ([a-z][A-Z]) followed by any number of alphanumeric characters ([a-z]
[A-Z][0-9]) or an underscore (_).
5 Press Enter and enter the following text:
27-21
27 Truth Table Functions for Decision-Making Logic
coder.extrinsic('plot');
if isempty(counter)
% Initialize counter to be zero
counter = 0;
else
% Otherwise, increment counter
counter = counter + 1;
end
if isempty(values)
% Values is a vector of 1 to cycle
values = zeros(1, cycle);
for i = 1:cycle
values(i) = i;
end
In truth table actions, you can use data that passes to the truth table function
through its arguments and return value. The preceding action sets the return value r
equal to the next value of the vector values. You can also specify actions with data
defined for a parent object of the truth table, including the chart. Truth table actions
can also broadcast or send events that are defined for the truth table, or for a parent,
such as the chart itself.
Note If you omit the semicolon at the end of an action, the result of the action
echoes to the MATLAB Command Window when the action executes during
simulation. Use this echoing option as a debugging tool.
6 Enter the remaining actions in the Action Table, as shown:
27-22
Program a Truth Table
27-23
27 Truth Table Functions for Decision-Making Logic
27-24
Program a Truth Table
The following rules apply when you assign actions to decisions in a truth table:
• You specify actions for decisions by entering a row number or a label in the Actions
row cell of a decision column.
If you use a label specifier, the label must appear with the action in the Action Table.
• You must specify at least one action for each decision.
Actions for decisions are not optional. Each decision must have at least one action
specifier that points to an action in the Action Table. If you want to specify no action
for a decision, specify a row that contains no action statements.
• You can specify multiple actions for a decision with multiple specifiers separated by a
comma, semicolon, or space.
For example, for the decision column D1, you can specify A1,A2,A3 or 1;2;3 to
execute the first three actions when decision D1 is true.
• You can mix row number and label action specifiers interchangeably in any order.
The following example uses both row and label action specifiers.
27-25
27 Truth Table Functions for Decision-Making Logic
• You can specify the same action for more than one decision, as shown:
27-26
Program a Truth Table
• Row number action specifiers in the Actions row of the Condition Table
automatically adjust to changes in the row order of the Action Table.
This section describes how to assign actions to decisions in the truth table ttable. In
this example, the Actions row cell for each decision column contains a label specified for
each action in the Action Table. Follow these steps:
27-27
27 Truth Table Functions for Decision-Making Logic
1 Click the bottom cell in decision column D1, the first cell of the Actions row of the
Condition Table.
2 Enter the action specifier A1 for decision column D1.
27-28
Program a Truth Table
Now you are ready to perform the final step in programming a truth table.
27-29
27 Truth Table Functions for Decision-Making Logic
Use this procedure to add initial and final actions that display diagnostic messages in the
MATLAB Command Window before and after execution of the truth table ttable:
1 In the truth table, right-click row 1 of the Action Table and select Insert Row.
27-30
Program a Truth Table
27-31
27 Truth Table Functions for Decision-Making Logic
Although the initial and final actions for the preceding truth table example appear in the
first and last rows of the Action Table, you can enter these actions in any row. You can
also assign initial and final actions to decisions by using the action specifier INIT or
FINAL in the Actions row of the Condition Table.
27-32
Debug Run-Time Errors in a Truth Table
For example, if you change the action for decision column D4 to an action that does
not exist, you get an error message in the Diagnostic Viewer.
Truth table diagnostics run automatically when you start simulation of the model with a
new or modified truth table. If no errors exist, the diagnostic window does not appear and
simulation starts immediately.
With truth tables, you can set these different breakpoint types:
• Condition tested
• Decision tested
• Decision valid
• Action executed
27-33
27 Truth Table Functions for Decision-Making Logic
After simulation stops at a breakpoint, you can continue chart execution on the Stateflow
Editor toolbar, at the MATLAB command prompt, or by selecting a keyboard shortcut.
From a statement in a
function containing another
function call, advance to the
first executable statement in
the second function.
Otherwise, continue
simulation to the next
breakpoint. (See Continue.)
Step Forward Exit debug mode and pause
simulation before next time
step.
Stop dbquit Exit debug mode and stop Ctrl+Shift+T
simulation.
27-34
Debug Run-Time Errors in a Truth Table
Condition Breakpoints
To set a breakpoint when a condition is tested, right-click the condition cell and select Set
Breakpoint (Condition Tested). A red badge appears on the far left of the table next to
the number of the condition. When you run the model, the simulation pauses when the
condition is tested. Stateflow highlights the condition row being tested. Place your cursor
over the data in the truth table to see its current value.
27-35
27 Truth Table Functions for Decision-Making Logic
27-36
Debug Run-Time Errors in a Truth Table
Decision Breakpoints
To set a breakpoint when a decision is tested, right-click the top of the decision column
and select Set Breakpoint (Decision Tested). A red badge appears on the top of the
decision column next to the number of the decision. When you run the model, the
simulation pauses when the decision is tested. Stateflow highlights the decision column
being tested. Place your cursor over the data in the truth table to see its current value.
27-37
27 Truth Table Functions for Decision-Making Logic
27-38
Debug Run-Time Errors in a Truth Table
To set a breakpoint when a decision is valid, right-click the action cell at the bottom of the
decision column and select Set Breakpoint (Decision Valid). A red badge appears on
the top of the cell next to the action number. When you run the model, the simulation
pauses when the action is valid. Stateflow highlights the valid decision. Place your cursor
over the data in the truth table to see its current value.
If there is more than one action to take when a decision is valid, the breakpoint is set for
the first executable. In truth tables that use MATLAB as the action language, you can set
a breakpoint on any line of executable code by setting breakpoints in the generated
content. See “Debugging Generated Truth Table Content” on page 27-43.
27-39
27 Truth Table Functions for Decision-Making Logic
27-40
Debug Run-Time Errors in a Truth Table
Action Breakpoints
To set a breakpoint when a action is executed, right-click the action cell and select Set
Breakpoint (Action Executed). A red badge appears on the far left of the table next to
the number of the action. When you run the model, the simulation pauses when the action
is executed. Stateflow highlights the action row being tested. Place your cursor over the
data in the truth table to see its current value.
If there is more than one action within the action cell, the breakpoint is set for the first
action. In truth tables that use MATLAB as the action language, you can set a breakpoint
on any line of executable code by setting breakpoints in the generated content. See
“Debugging Generated Truth Table Content” on page 27-43.
27-41
27 Truth Table Functions for Decision-Making Logic
27-42
See Also
Edit Breakpoints
Click the breakpoint to open the Edit Breakpoint dialog box. From this window you can
disable the breakpoint by unchecking Enable Breakpoint.
When you add a condition to a breakpoint, the breakpoint pauses the simulation only
when its associated condition is true.
For truth tables that use MATLAB as the action language, content is generated as
MATLAB code. To set a breakpoint in the code, click the breakpoint alley next to the
executable line where you want simulation to pause. See “Debug a MATLAB Program”
(MATLAB). When you add an element to your truth table that changes the generated
content, all breakpoints are regenerated.
For truth tables that use C as the action language, content is generated as a graphical
function. To set a breakpoint in the graphical function, right-click the transition where
you want to set a breakpoint and select Set Breakpoint. When you add an element to
your truth table that changes the generated content, all breakpoints are regenerated if
you recompile your truth table.
See Also
More About
• “View Generated Content for Stateflow Truth Tables” on page 27-55
• “Debugging a MATLAB Function Block” (Simulink)
27-43
27 Truth Table Functions for Decision-Making Logic
27-44
Correct Overspecified and Underspecified Truth Tables
27-45
27 Truth Table Functions for Decision-Making Logic
The decision in column D3 (-TT) specifies the decisions FTT and TTT. These decisions are
duplicates of decisions D1 (FTT) and D2 (TTT and TFT). Therefore, column D3 is an
overspecification.
The following example shows the Condition Table of a truth table that appears to be
overspecified, but is not.
27-46
Correct Overspecified and Underspecified Truth Tables
27-47
27 Truth Table Functions for Decision-Making Logic
In this case, the decision D4 specifies two decisions (TTT and FTT). FTT also appears in
decision D1, but TTT is not a duplicate. Therefore, this Condition Table is not
overspecified.
27-48
Correct Overspecified and Underspecified Truth Tables
27-49
27 Truth Table Functions for Decision-Making Logic
Complete coverage of the conditions in the preceding truth table requires a Condition
Table with every possible decision:
27-50
Correct Overspecified and Underspecified Truth Tables
27-51
27 Truth Table Functions for Decision-Making Logic
A possible workaround is to specify an action for all other possible decisions through a
default decision, named DA:
27-52
Correct Overspecified and Underspecified Truth Tables
27-53
27 Truth Table Functions for Decision-Making Logic
The last decision column is the default decision for the truth table. The default decision
covers any remaining decisions not tested in the preceding decision columns. See “The
Default Decision Column” on page 27-15 for an example and more complete description of
the default decision column for a Condition Table.
27-54
View Generated Content for Stateflow Truth Tables
In the following example, a C truth table has three conditions, four decisions and actions,
and initial and final actions.
27-55
27 Truth Table Functions for Decision-Making Logic
27-56
View Generated Content for Stateflow Truth Tables
Stateflow software generates a graphical function for the preceding truth table. The top
half of the flow chart looks like this:
The temporary data for storing conditions is based on the labels that you enter for the
conditions. If you do not specify the labels, temporary data variables appear.
27-57
27 Truth Table Functions for Decision-Making Logic
In the bottom half of the flow chart, the stored values for conditions determine which
decision is true and what action to perform. Each decision appears as a fork from a
connective junction with one of two possible paths:
The action appears as a condition action that leads to the FINAL action and
termination of the flow chart.
27-58
View Generated Content for Stateflow Truth Tables
• A transition segment that flows to the next fork for an evaluation of the next decision
This implementation continues from the first decision through the remaining decisions in
left-to-right column order. When a decision match occurs, the action for that decision
executes as a condition action of its transition segment. After the action executes, the
flow chart performs the final action for the truth table and terminates. Therefore, only
one action results from a call to a truth table graphical function. This behavior also means
that no data dependencies are possible between different decisions.
• Nested functions are independent of one another. Variables are local to each function
and not subject to naming conflicts.
• Nested functions can access all data from the main truth table function.
The generated content appears in the function editor, which provides tools for simulation
and debugging.
Here is the generated content for the MATLAB truth table described in “Program Actions
Using MATLAB Expressions” on page 27-21:
27-59
27 Truth Table Functions for Decision-Making Logic
function A1()
% Action #1, "A1"
% Maintain a counter and a circular vector of length 6.
% Every time this action is called,
% output t takes the next value of the vector.
if isempty(counter)
% Initialize counter to be zero
counter = 0;
else
% Otherwise, increment counter
counter = counter + 1;
end
if isempty(values)
% Values is a vector of 1 to cycle
values = zeros(1, cycle);
for i = 1:cycle
values(i) = i;
end
27-60
View Generated Content for Stateflow Truth Tables
function A2()
% Action #2, "A2"
% set r to 2
r=2;
%==================================
function A3()
% Action #3, "A3"
% set r to 3
r=3;
%==================================
function A4()
% Action #4, "A4"
% set r to 4
r=4;
27-61
27 Truth Table Functions for Decision-Making Logic
To create truth tables, use the Stateflow Editor. You can insert, edit, and move rows and
columns. You can also diagnose the truth table for syntax errors and view the auto-
generated code for the truth table.
Edit Tables
The default Condition Table and the default Action Table have one empty row. Click a
cell to edit its text contents. To move horizontally between cells, use the up and down
arrow keys.
To display only one of the two tables, double-click the header of the table that you want to
display. To revert to the display of both tables, double-click the header of the displayed
table.
27-62
Truth Table Operations
Cells for the numbered rows in decision columns like D1 can take values of T, F, or -.
After you select one of these cells, you can use the space bar to step through the T, F, and
- values. In these cells you can use the left, right, up, and down arrow keys to advance to
another cell in any direction.
Note To select multiple rows or columns that you want to move, hold down the Ctrl key.
27-63
27 Truth Table Functions for Decision-Making Logic
To redo the effects of the preceding operation, select Edit > Redo or press Ctrl+Y
(Command+Y).
27-64
28
• Matrix-oriented calculations
• Data analysis and visualization
This type of function is useful for coding algorithms that are more easily expressed by
using MATLAB instead of the graphical Stateflow constructs. MATLAB functions also
provide optimizations for generating efficient, production-quality C code for embedded
applications.
A MATLAB function can reside anywhere in a chart, state, or subchart. The location of the
function determines the set of states and transitions that can call the function.
• If you want to call the function only within one state or subchart and its substates, put
your MATLAB function in that state or subchart. That function overrides any other
functions of the same name in the parents and ancestors of that state or subchart.
• If you want to call the function anywhere in that chart, put your MATLAB function at
the chart level.
• If you want to call the function from any chart in your model, put your MATLAB
function at the chart level and enable exporting of chart-level functions. For more
information, see “Export Stateflow Functions for Reuse” on page 8-22.
For example, this MATLAB function has the name stdevstats. It takes an argument
vals and returns an output value stdevout.
To compute the standard deviation of the values in vals, the function uses this code.
28-2
Reuse MATLAB Code by Defining MATLAB Functions
len = length(vals);
stdevout = sqrt(sum(((vals-avg(vals,len)).^2))/len);
Your function can access its own data or data belonging to parent states or the chart.
The data items in the function can have one of these scopes:
• Local — Local data persists from one function call to the next function call. Valid
for C charts only.
• Constant — Constant data retains its initial value through all function calls.
• Parameter — Parameter data retains its initial value through all function calls.
• Temporary — Temporary data initializes at the start of every function call. Valid
for C charts only.
In charts that use C as the action language, define temporary data when you want to use
data that is only valid while a function executes. For example, you can designate a loop
28-3
28 MATLAB Functions in Stateflow Charts
counter to have Temporary scope if the counter value does not need to persist after the
function completes.
In charts that use MATLAB as the action language, you do not need to define temporary
function data. If you use an undefined variable, Stateflow creates a temporary variable.
The variable is available to the rest of the function.
You can initialize your function data (other than arguments and return values) from the
MATLAB workspace. For more information, see “Initialize Data from the MATLAB Base
Workspace” on page 9-24.
You can specify multiple return values and multiple input arguments. Each return value
and input argument can be a scalar, vector, or matrix of values. For functions with only
one return value, omit the brackets in the signature label.
You can use the same variable name for both arguments and return values. For example,
a function with this signature label uses the variables y1 and y2 as both inputs and
outputs:
[y1, y2, y3] = f(y1, u, y2)
If you export this function to C code, y1 and y2 are passed by reference (as pointers), and
u is passed by value. Passing inputs by reference reduces the number of times that the
generated code copies intermediate data, resulting in more optimal code.
The syntax for a call to a MATLAB function is the same as the function signature, with
actual arguments replacing the formal ones specified in a signature. If the data types of
an actual and formal argument differ, a function casts the actual argument to the type of
the formal argument.
28-4
Reuse MATLAB Code by Defining MATLAB Functions
Tip If the formal arguments of a function signature are scalars, verify that inputs and
outputs of function calls follow the rules of scalar expansion. For more information, see
“How Scalar Expansion Works for Functions” on page 17-9.
Name
Function name. Click the function name link to open your function in the MATLAB editor.
Label
Signature label for your function. For more information, see “Declare Function Arguments
and Return Values” on page 28-4.
Specifies whether integer overflows saturate in the generated code. For more
information, see “Handle Integer Overflow for Chart Data” on page 9-45.
Defines the fimath properties for the MATLAB function. The fimath properties specified
are associated with all fi and fimath objects constructed in the MATLAB function.
Choose one of these options:
28-5
28 MATLAB Functions in Stateflow Charts
• Same as MATLAB — The function uses the same fimath properties as the current
global fimath. The edit box appears dimmed and displays the current global fimath
in read-only form. For more information on the global fimath and fimath objects,
see the Fixed-Point Designer documentation.
• Specify Other — Specify your own fimath object by one of these methods:
Description
Function description. You can enter brief descriptions of functions in the hierarchy.
Document Link
Link to online documentation for the function. You can enter a web URL address or a
MATLAB command that displays documentation in a suitable online format, such as an
HTML file or text in the MATLAB Command Window. When you click the Document link
hyperlink, Stateflow displays the documentation.
See Also
More About
• “Program a MATLAB Function in a Chart” on page 28-7
• “Reusable Functions in Charts” on page 2-46
• “Export Stateflow Functions for Reuse” on page 8-22
• “Reuse Functions by Using Atomic Boxes” on page 8-35
28-6
Program a MATLAB Function in a Chart
Build Model
Follow these steps:
A text field with a flashing cursor appears in the middle of each MATLAB function.
5 Label each function as shown:
28-7
28 MATLAB Functions in Stateflow Charts
You must label a MATLAB function with its signature. Use the following syntax:
You can specify multiple return values and multiple input arguments, as shown in the
syntax. Each return value and input argument can be a scalar, vector, or matrix of
values.
Note For MATLAB functions with only one return value, you can omit the brackets in
the signature label.
6 In the chart, draw a default transition into a terminating junction with this condition
action:
{
mean = meanstats(invals);
stdev = stdevstats(invals);
}
28-8
Program a MATLAB Function in a Chart
Tip If the formal arguments of a function signature are scalars, verify that inputs and
outputs of function calls follow the rules of scalar expansion. For more information,
see “How Scalar Expansion Works for Functions” on page 17-9.
7 In the chart, double-click the function meanstats to edit its function body in the
editor.
8 In the function editor, select Tools > Model Explorer to open the Model Explorer.
28-9
28 MATLAB Functions in Stateflow Charts
The function meanstats is highlighted in the Model Hierarchy pane. The Contents
pane displays the input argument vals and output argument meanout. Both are
scalars of type double by default.
9 Double-click the vals row under the Size column to set the size of vals to 4.
10 Back in the chart, double-click the function stdevstats and repeat the previous two
steps.
11 Back in the Model Hierarchy pane of the Model Explorer, select Chart and add the
following data:
You should now see the following data in the Model Explorer.
After you add the data invals, mean, and stdev to the chart, the corresponding
input and output ports appear on the Stateflow block in the model.
28-10
Program a MATLAB Function in a Chart
12 Connect the Constant and Display blocks to the ports of the Chart block and save the
model.
This header is taken from the function label in the chart. You can edit the header
directly in the editor, and your changes appear in the chart after you close the editor.
3 On the line after the function header, enter:
%#codegen
28-11
28 MATLAB Functions in Stateflow Charts
len = length(vals);
The variable len is an example of implicitly declared local data. It has the same size
and type as the value assigned to it — the value returned by the function length, a
scalar double. To learn more about declaring variables, see “Data Definition Basics”
(MATLAB Coder).
The MATLAB function treats implicitly declared local data as temporary data, which
exists only when the function is called and disappears when the function exits. You
can declare local data for a MATLAB function in a chart to be persistent by using the
persistent construct.
6 Enter this line to calculate the value of meanout:
meanout = avg(vals,len);
The function meanstats stores the mean of vals in the Stateflow data meanout.
Because these data are defined for the parent Stateflow chart, you can use them
directly in the MATLAB function.
The MATLAB function uses the functions avg and sum to compute the value of mean.
sum is a function supported for code generation. avg is a local function that you
define later. When resolving function names, MATLAB functions in your chart look for
local functions first, followed by functions supported for code generation.
28-12
Program a MATLAB Function in a Chart
Note If you call a function that the MATLAB function cannot resolve as a local
function or a function for code generation, you must declare the function to be
extrinsic.
7 Now enter this statement:
coder.extrinsic('plot');
8 Enter this line to plot the input values in vals against their vector index.
plot(vals,'-+');
Recall that you declared plot to be an extrinsic function because it is not supported
for code generation. When the MATLAB function encounters an extrinsic function, it
sends the call to the MATLAB workspace for execution during simulation.
9 Now, define the local function avg, as follows:
function mean = avg(array,size)
mean = sum(array)/size;
The header for avg defines two arguments, array and size, and a single return
value, mean. The local function avg calculates the average of the elements in array
by dividing their sum by the value of argument size.
The complete code for the function meanstats looks like this:
function meanout = meanstats(vals)
%#codegen
len = length(vals);
meanout = avg(vals,len);
coder.extrinsic('plot');
plot(vals,'-+');
28-13
28 MATLAB Functions in Stateflow Charts
len = length(vals);
stdevout = sqrt(sum(((vals-avg(vals,len)).^2))/len);
28-14
Connect Structures in MATLAB Functions to Simulink Bus Signals
You can also create structures as local and persistent variables in top-level functions and
local functions of MATLAB functions.
Follow these rules when defining structures for MATLAB functions in Stateflow charts:
• For each structure input or output in a MATLAB function, you must define a
Simulink.Bus object in the base workspace to specify its type to the Simulink signal.
• MATLAB structures cannot inherit their type from Simulink signals.
• MATLAB functions support nonvirtual buses only (see “Virtual and Nonvirtual Buses”
(Simulink)).
• Structures cannot have scopes defined as Constant.
When you create structure inputs in MATLAB functions, the function determines the type,
size, and complexity of the structure from the Simulink input signal. When you create
structure outputs, you must define their type, size, and complexity in the MATLAB
function.
28-15
28 MATLAB Functions in Stateflow Charts
You can connect MATLAB structure inputs and outputs to any Simulink bus signal,
including:
• Simulink blocks that output bus signals — such as Bus Creator blocks
• Simulink blocks that accept bus signals as input — such as Bus Selector and Gain
blocks
• S-Function blocks
• Other MATLAB functions
To define structure inputs and outputs for MATLAB functions in Stateflow charts, follow
these steps:
1 Create a Simulink bus object in the base workspace to specify the properties of the
structure you will create in the MATLAB function.
For information about how to create Simulink bus objects, see “Create Bus Objects
with the Bus Editor” (Simulink).
2 Open the Model Explorer and follow these steps:
a In the Model Hierarchy pane, select the MATLAB function in your chart.
b Add a data object, as described in “Add Data Through the Model Explorer” on
page 9-3.
The Model Explorer adds a data object and opens a Properties dialog box in its
right-hand Dialog pane.
c In the Properties dialog box, enter the following information in the General tab
fields:
28-16
Connect Structures in MATLAB Functions to Simulink Bus Signals
You can define structures as local or persistent variables inside MATLAB functions. For
details, see “Structures” (MATLAB Coder).
28-17
28 MATLAB Functions in Stateflow Charts
The editor automatically checks your function code for errors and recommends
corrections.
2 In the Stateflow Editor, select Code > C/C++ Code > Build Model.
If there are no errors or warnings, the Builder window appears and reports success.
Otherwise, it lists errors. For example, if you change the name of local function avg
to a nonexistent local function aug in meanstats, errors appear in the Diagnostic
Viewer.
3 The diagnostic message provides details of the type of error and a link to the code
where the error occurred. The diagnostic message also contains a link to a diagnostic
report that provides links to your MATLAB functions and compile-time type
information for the variables and expressions in these functions. If your model fails to
build, this information simplifies finding sources of error messages and aids
understanding of type propagation rules. For more information about this report, see
“MATLAB Function Reports” (Simulink).
4 In the diagnostic message, click the link after the function name meanstats to
display the offending line of code.
28-18
Debug a MATLAB Function in a Chart
described in “Check MATLAB Functions for Syntax Errors” on page 28-18. If no errors are
found, the simulation of your model begins.
Follow these steps to simulate and debug the meanstats function during run-time
conditions:
1 In the function editor, click the dash (-) character in the left margin of this line:
len = length(vals);
A small red ball appears in the margin of this line, indicating that you have set a
breakpoint.
2 Start simulation for the model.
If you get any errors or warnings, make corrections before you try to simulate again.
Otherwise, simulation pauses when execution reaches the breakpoint you set. A small
green arrow in the left margin indicates this pause.
3 To advance execution to the next line, select Step.
Notice that this line calls the local function avg. If you select Step here, execution
advances past the execution of the local function avg. To track execution of the lines
in the local function avg, select Step In instead.
4 To advance execution to the first line of the called local function avg, select Step In.
Once you are in the local function, you can advance through one line at a time with
the Step tool. If the local function calls another local function, use the Step In tool to
step into it. To continue through the remaining lines of the local function and go back
to the line after the local function call, select Step Out.
5 Select Step to execute the only line in avg.
When avg finishes its execution, you see a green arrow pointing down under its last
line.
6 Select Step to return to the function meanstats.
28-19
28 MATLAB Functions in Stateflow Charts
You can display the value for any data in the MATLAB function in this way, no matter
where it appears in the function. For example, you can display the values for the
vector vals by placing your pointer over it as an argument to the function length,
or as an argument in the function header.
You can also report the values for MATLAB function data in the MATLAB Command
Window during simulation. When you reach a breakpoint, the debug>> command
prompt appears in the MATLAB Command Window (you may have to press Enter to
see it). At this prompt, you can inspect data defined for the function by entering the
name of the data, as shown in this example:
debug>> len
len =
4
debug>>
As another debugging alternative, you can display the execution result of a function
line by omitting the terminating semicolon. If you do, execution results appear in the
MATLAB Command Window during simulation.
8 To leave the function until it is called again and the breakpoint is reached, select
Continue.
At any point in a function, you can advance through the execution of the remaining
lines of the function with the Continue tool. If you are at the end of the function,
selecting Step does the same thing.
9 Click the breakpoint to remove it and select Quit Debugging to complete the
simulation.
In the model, the computed values of mean and stdev now appear in the Display
blocks.
28-20
Debug a MATLAB Function in a Chart
Specify a Range
To specify a range for input and output data, follow these steps:
1 In the Model Explorer, select the MATLAB function input or output of interest.
The Data properties dialog box opens in the Dialog pane of the Model Explorer.
2 In the Data properties dialog box, click the General tab and enter a limit range, as
described in “Limit Range Properties” on page 9-10.
28-21
28 MATLAB Functions in Stateflow Charts
function stats(vals)
%#codegen
len = length(vals);
mean = avg(vals, len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
coder.extrinsic('plot');
plot(vals,'-+');
Note in this example that the MATLAB function can call any of these types of functions:
28-22
MATLAB Functions in a Stateflow Chart
• Local functions
Local functions are defined in the body of the MATLAB function. In this example, avg
is a local function.
• Stateflow functions
Graphical, truth table, and other MATLAB functions can be called from a MATLAB
function in a chart.
• MATLAB toolbox functions that support code generation
Toolbox functions for code generation are a subset of the functions that you can call in
the MATLAB workspace. These functions generate C code for building targets that
conform to the memory and data type requirements of embedded environments. In
this example, length, sqrt, and sum are examples of toolbox functions for code
generation.
• MATLAB toolbox functions that do not support code generation
You can also call extrinsic functions on the MATLAB path that do not generate code.
These functions execute only in the MATLAB workspace during simulation of the
model.
• Simulink Design Verifier functions
Simulink Design Verifier software provides MATLAB functions for property proving
and test generation.
• sldv.prove
• sldv.assume
• sldv.test
• sldv.condition
28-23
28 MATLAB Functions in Stateflow Charts
To learn how to define and use enumerated data in Stateflow charts, see “Define
Enumerated Data Types” on page 19-6.
To learn how to declare variable-size data at the chart level, see “Declare Variable-Size
Inputs and Outputs” on page 18-2.
In C charts, define temporary data when you want to use data that is only valid while a
function executes. In charts that use MATLAB as the action language, you do not need to
define temporary function data in the Model Explorer. If a variable is used and not
previously defined, then it is automatically created. The variable is available to the rest of
the function.
28-24
Define Data in MATLAB Functions
You can define temporary data in graphical, truth table, and MATLAB functions in your
chart. For example, you can designate a loop counter to have Temporary scope if the
counter value does not need to persist after the function completes.
The Model Explorer adds a default definition for the data in the Stateflow hierarchy,
with a scope set to Temporary by default.
4 Change other properties of the data if necessary, as described in “Set Data
Properties” on page 9-5.
28-25
28 MATLAB Functions in Stateflow Charts
28-26
29
• Defining a function that requires Simulink blocks, such as lookup tables (see “About
Lookup Table Blocks” (Simulink))
• Scheduling execution of multiple controllers
You can call Simulink functions defined inside of a Stateflow chart from the same chart.
You can also call functions defined by a Simulink Function block in the model.
• If you want to call the function within only one state or subchart and its substates, put
your Simulink function in that state or subchart. That function overrides any other
functions of the same name in the parents and ancestors of that state or subchart.
• If you want to call the function anywhere in that chart, put your Simulink function at
the chart level.
29-2
Reuse Simulink Components in Stateflow Charts
The function f contains a block diagram that increments a counter by 1 each time the
function executes.
At each time step, the function f is called twice, which causes the counter to increment
by 2. Because all call sites share the value of this counter, the data y and y1 increment by
2 at each time step.
Note This behavior also applies to external function-call subsystems in a Simulink model.
For more information, see “Using Function-Call Subsystems” (Simulink).
This rule applies to continuous-time charts because you cannot call functions during
minor time steps. You can call Simulink functions in state entry or exit actions and
transition actions. However, if you try to call Simulink functions in state during actions
or transition conditions, an error message appears when you simulate your model.
29-3
29 Simulink Functions in Stateflow Charts
If you select Execute (enter) Chart At Initialization in the Chart properties dialog box,
you cannot call Simulink functions in default transitions that execute the first time that
the chart awakens. Otherwise, an error message appears when you simulate your model.
Use only alphanumeric characters or underscores when naming input and output
ports for a Simulink function
This rule ensures that the names of input and output ports are compatible with identifier
naming rules of Stateflow charts.
For Simulink functions inside a Stateflow chart, the output ports do not support
discontiguous signals. If your function contains a block that outputs a discontiguous
signal, insert a Signal Conversion block between the discontiguous output and the output
port. This action ensures that the output signal is contiguous.
Blocks that can output a discontiguous signal include the Bus Creator block and the Mux
block. For the Bus Creator block, the output is discontiguous only if you clear the Output
as nonvirtual bus check box — that is, if the Bus Creator block outputs a virtual bus. If
you select Output as nonvirtual bus, the output signal is contiguous and no conversion
is necessary.
For more information, see Bus Creator, Mux, and Signal Conversion.
If you try to export Simulink functions, an error appears when you simulate your model.
To avoid this behavior, clear the Export Chart Level Functions check box in the Chart
properties dialog box.
If you try to use the Model Explorer to rename a Simulink function, the change does not
appear in the chart. Edit the name in the Symbols window or click the function box in the
Stateflow Editor to rename the function.
29-4
See Also
This restriction prevents violations of Moore semantics during chart execution. For more
information, see “Design Considerations for Moore Charts” on page 7-11.
If you try to generate HDL code for charts that contain Simulink functions, an error
message appears when you simulate your model. HDL code generation does not support
Simulink functions.
The input ports of Simulink functions cannot inherit their sizes and data types. The output
ports of a Simulink Function block in Simulink cannot inherit their sizes and data types.
Therefore, you must set sizes and types explicitly when the inputs and outputs are not
scalar data of type double.
The output ports of a Simulink function defined inside a chart can inherit sizes and data
types based on connections inside the subsystem. Therefore, you can specify sizes and
types of these outputs as inherited.
Tip To minimize updates required for changes in input port properties, you can specify
sizes and data types as parameters.
Verify that function-call expressions have inputs and outputs of correct size
If the formal arguments of a function signature are scalars, verify that inputs and outputs
of function calls follow the rules of scalar expansion. For more information, see “How
Scalar Expansion Works for Functions” on page 17-9.
See Also
Simulink Function
29-5
29 Simulink Functions in Stateflow Charts
More About
• “Export Stateflow Functions for Reuse” on page 8-22
• “Simulink Functions Overview” (Simulink)
• “Using Simulink Function Blocks and Exported Stateflow Functions” (Simulink)
• “Share Functions Across Simulink and Stateflow” on page 29-7
29-6
Share Functions Across Simulink and Stateflow
This example shows a model calling functions across Simulink® and Stateflow®. The
slexPrinterExample model has three computer clients sharing a printer. Each computer
creates print jobs by calling the Simulink function addPrintJob.
In this example, the Stateflow chart communicates with the model by:
open_system('slexPrinterExample');
Each computer client invokes the printer server with a call to the Simulink function,
addPrintJob. The addPrintJob function calls the Stateflow graphical function
queuePrintJob to add the print job to the work load. The chart processes the work and
calls the Simulink function printerInk to model usage of printer ink.
29-7
29 Simulink Functions in Stateflow Charts
The function printerInk is defined in a Simulink Function block at the top level of the
model. The function interface printerInk(work) defines one input argument. The
Simulink Function, printerInk, also interacts with the model with signal lines through the
inport ink and outport ink'. The state Busy matches the function signature for
printerInk(work) by passing one input argument.
In the chart Queuing and Processing Incoming Jobs, the properties Export Chart
Level Functions and Treat Exported Functions as Globally Visible are selected.
These properties allow the Simulink function addPrintJob to call the chart graphical
function, queuePrintJob.
See Also
Simulink Function
More About
• “Export Stateflow Functions for Reuse” on page 8-22
• “Simulink Functions Overview” (Simulink)
• “Model Reference Basics” (Simulink)
29-8
Why Use a Simulink Function in a Stateflow Chart?
In this section...
“Advantages of Using Simulink Functions in a Stateflow Chart” on page 29-9
“Benefits of Using a Simulink Function to Access Simulink Blocks” on page 29-9
“Benefits of Using a Simulink Function to Schedule Execution of Multiple Controllers” on
page 29-12
You define a function-call subsystem in the Simulink model (see “Using Function-Call
Subsystems” (Simulink). Use an output event in a Stateflow chart to call the subsystem,
as shown.
29-9
29 Simulink Functions in Stateflow Charts
You place one or more Simulink blocks in a Simulink function of a Stateflow chart. Use a
function call to execute the blocks in that function, as shown.
29-10
Why Use a Simulink Function in a Stateflow Chart?
29-11
29 Simulink Functions in Stateflow Charts
For more information, see “Improve Chart Design by Using Simulink Functions” on page
29-26.
You define each controller as a function-call subsystem block and use output events in a
Stateflow chart to schedule execution of the subsystems, as shown in the
sf_temporal_logic_scheduler model.
29-12
Why Use a Simulink Function in a Stateflow Chart?
You define each controller as a Simulink function in a Stateflow chart and use function
calls to schedule execution of the subsystems, as shown in the
sf_temporal_logic_scheduler_with_sl_fcns model.
29-13
29 Simulink Functions in Stateflow Charts
29-14
See Also
See Also
More About
• “Benefits of Using a Simulink Function to Access Simulink Blocks” on page 29-9
• “Benefits of Using a Simulink Function to Schedule Execution of Multiple
Controllers” on page 29-12
• “Schedule Execution of Multiple Controllers” on page 29-36
29-15
29 Simulink Functions in Stateflow Charts
2 Move your pointer to the location for the new Simulink function in your chart and
click to insert the function box.
Tip You can also drag the function from the toolbar.
3 Enter the function signature.
The function signature specifies a name for your function and the formal names for
the arguments and return values. A signature has this syntax:
where simfcn is the name of your function, a_1, a_2, ..., a_n are formal names for
the arguments, and r_1, r_2, ..., r_n are formal names for the return values.
Note This syntax is the same as what you use for graphical functions, truth tables,
and MATLAB functions. You can define arguments and return values as scalars,
vectors, or matrices of any data type.
4 Click outside the function box.
The following example shows a Simulink function that has the name sim_fcn, which
takes three arguments (a, b, and c) and returns two values (x and y).
29-16
Define a Simulink Function in a Stateflow Chart
Note You can also create and edit a Simulink function by using API methods.
The contents of the subsystem appear: input and output ports that match the function
signature and a single function-call trigger port.
2 Add Simulink blocks to the subsystem.
3 Connect the input and output ports to each block.
The following example shows the subsystem elements for a Simulink function.
29-17
29 Simulink Functions in Stateflow Charts
For example, you can specify a size of [2 3] for a 2-by-3 matrix and a data type
of uint8.
2 Click OK.
Note An input port of a Simulink function cannot inherit size or data type. Therefore, you
define the size and data type of an input that is not scalar data of type double. However,
an output port can inherit size and data type.
See Also
More About
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Why Use a Simulink Function in a Stateflow Chart?” on page 29-9
• “Share Functions Across Simulink and Stateflow” on page 29-7
29-18
Bind a Simulink Function to a State
• Function calls can occur only in state actions and on transitions within the state and
its substates.
• When the state is entered, the function is enabled.
• When the state is exited, the function is disabled.
For example, the following Stateflow chart shows a Simulink function that binds to a
state.
29-19
29 Simulink Functions in Stateflow Charts
Because the function queue resides in state A1, the function binds to that state.
• State A1 and its substates A2 and A3 can call queue, but state B1 cannot.
• When state A1 is entered, queue is enabled.
• When state A1 is exited, queue is disabled.
1 In the Simulink function, double-click the trigger port to open the Block Parameters
dialog box.
2 Select an option for States when enabling.
29-20
Bind a Simulink Function to a State
The function queue contains a block diagram that increments a counter by 1 each time
the function executes.
The Block Parameters dialog box for the trigger port appears as follows.
29-21
29 Simulink Functions in Stateflow Charts
In the dialog box, setting Sample time type to periodic enables the Sample time
field, which defaults to 1. These settings tell the function to execute for each time step
specified in the Sample time field while the function is enabled.
29-22
Bind a Simulink Function to a State
Note If you use a fixed-step solver, the value in the Sample time field must be an integer
multiple of the fixed-step size. This restriction does not apply to variable-step solvers. (For
more information, see “Solvers” (Simulink).)
1 The default transition to state A1 occurs, which includes setting local data u1 to 1.
2 When A1 is entered, the function queue is enabled.
3 Function calls to queue occur until the condition after(5, sec) is true.
4 The transition from state A1 to B1 occurs.
5 When A1 is exited, the function queue is disabled.
6 After two more seconds pass, the transition from B1 to A1 occurs.
7 Steps 2 through 6 repeat until the simulation ends.
29-23
29 Simulink Functions in Stateflow Charts
When state A1 becomes inactive at t = 5, the Simulink function holds the counter value.
When A1 is active again at t = 7, the counter has the same value as it did at t = 5.
Therefore, the output y1 continues to increment over time.
29-24
See Also
When state A1 becomes inactive at t = 5, the Simulink function does not hold the counter
value. When A1 is active again at t = 7, the counter resets to zero. Therefore, the output
y1 resets too.
See Also
More About
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Why Use a Simulink Function in a Stateflow Chart?” on page 29-9
29-25
29 Simulink Functions in Stateflow Charts
• The chart broadcasts the output event CALC_TH to trigger the function-call subsystem.
29-26
Improve Chart Design by Using Simulink Functions
• The subsystem uses lookup tables to interpolate two values for the shift_logic chart.
• The subsystem outputs (up_th and down_th) feed directly into the chart as inputs.
You can replace a function-call subsystem with a Simulink function in a chart when:
Open the model old_sf_car. If you simulate the model, you see these results in the two
scopes.
29-27
29 Simulink Functions in Stateflow Charts
29-28
Improve Chart Design by Using Simulink Functions
1 In the Simulink model, right-click the Threshold Calculation block in the lower left
corner and select Cut from the context menu.
29-29
29 Simulink Functions in Stateflow Charts
29-30
Improve Chart Design by Using Simulink Functions
Tip To change the font size of a function, right-click the function box and select a
new size from the Font Size menu.
5 Expand the border of selection_state to include the new function.
29-31
29 Simulink Functions in Stateflow Charts
Note The function resides in this state instead of the chart level because no other
state in the chart requires the function outputs up_th and down_th. See “Bind a
Simulink Function to a State” on page 29-19.
6 Rename the Simulink function from Threshold_Calculation to calc_threshold
by entering [down_th, up_th] = calc_threshold(gear, throttle) in the
function box.
In the Model Explorer, change the scope of chart-level data up_th and down_th to Local
because calculations for those data now occur inside the chart.
29-32
Improve Chart Design by Using Simulink Functions
In the Stateflow Editor, change the during action in selection_state to call the
Simulink function calc_threshold.
Because the function calc_threshold takes throttle as an input, you must define
that data as a chart input. (For details, see “Add Stateflow Data” on page 9-2.)
Using port 1 prevents signal lines from overlapping in the Simulink model.
29-33
29 Simulink Functions in Stateflow Charts
2 In the Simulink model, add a signal line for throttle between the inport of the
Engine block and the inport of the shift_logic chart.
1 In the Model Explorer, delete the function-call output event CALC_TH because the
Threshold Calculation block no longer exists.
2 Delete any dashed signal lines from your model.
If you simulate the new model, the results match those of the original design.
29-34
See Also
See Also
More About
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Define a Simulink Function in a Stateflow Chart” on page 29-16
29-35
29 Simulink Functions in Stateflow Charts
29-36
Schedule Execution of Multiple Controllers
• The chart broadcasts the output events A1, A2, and A3 to trigger the function-call
subsystems.
• The subsystems A1, A2, and A3 execute at different rates defined by the chart.
• The subsystem outputs feed directly into the chart.
You can replace function-call subsystems with Simulink functions inside a chart when:
Note To skip the conversion steps, you can access the new model directly.
29-37
29 Simulink Functions in Stateflow Charts
Open the sf_temporal_logic_scheduler model. If you simulate the model, you see
this result in the scope.
For more information, see “Schedule Subsystems to Execute at Specific Times” on page
26-22.
Follow these steps to add Simulink functions to the Temporal Logic Scheduler chart.
29-38
Schedule Execution of Multiple Controllers
1 In the Simulink model, right-click the A1 block in the lower right corner and select
Cut from the context menu.
29-39
29 Simulink Functions in Stateflow Charts
Tip To change the font size of a function, right-click the function box and select a
new size from the Font Size menu.
5 Rename the Simulink function from A1 to f1 by entering y = f1(u) in the function
box.
6 Repeat steps 1 through 5 for these cases:
29-40
Schedule Execution of Multiple Controllers
Note The new functions reside at the chart level because both states
FastScheduler and SlowScheduler require access to the function outputs.
In the Model Explorer, change the scope of chart-level data y to Local because the
calculation for that data now occurs inside the chart.
In the Stateflow Editor, you can replace event broadcasts in state actions with function
calls.
1 Edit the state actions in FastScheduler and SlowScheduler to call the Simulink
functions f1, f2, and f3.
29-41
29 Simulink Functions in Stateflow Charts
du: y = u1-y2;
For the on every state actions of FastScheduler and SlowScheduler, define three
data. (For details, see “Add Stateflow Data” on page 9-2.)
Tip To flip the Scope block, right-click and select Rotate & Flip > Flip Block from
the context menu.
1 In the Model Explorer, delete output events A1, A2, and A3 and input data u2 because
the function-call subsystems no longer exist.
29-42
See Also
If you simulate the new model, the results match those of the original design.
See Also
More About
• “Reuse Simulink Components in Stateflow Charts” on page 29-2
• “Define a Simulink Function in a Stateflow Chart” on page 29-16
29-43
30
Build Targets
See Also
More About
• “Speed Up Simulation” on page 30-17
• “Set Up Your Own Target Compiler”
30-2
Access Custom C++ Code in Stateflow Charts
1 Add a C function wrapper to your custom code. This wrapper function executes the C
++ code that you are including.
int my_c_function_wrapper()
{
.
.
.
//C++ code
.
.
.
return result;
}
2 Create a header file that prototypes the C function wrapper in the previous step.
int my_c_function_wrapper();
The value _cplusplus exists if your compiler supports C++ code. The extern "C"
wrapper specifies C linkage with no name mangling.
30-3
30 Build Targets
For information on setting simulation options using the command-line API, see
“Command-Line API to Set Simulation and Code Generation Parameters” on page 30-19.
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “C++ Code Generation and Integration in Stateflow”
30-4
Access Custom C Code in Nonlibrary Charts
30-5
30 Build Targets
Follow the guidelines in “Specify Relative Paths to Your Custom Code” on page 30-
24.
• Source file — Enter code lines to include at the top of a generated source code
file. These code lines appear at the top of the generated model.c source file,
outside of any function.
For example, you can include extern int declarations for global variables.
• Header file — Enter code lines to include at the top of the generated model.h
header file that declares custom functions and data in the generated code. These
30-6
Access Custom C Code in Nonlibrary Charts
code lines appear at the top of all generated source code files and are visible to all
generated code.
Note When you include a custom header file, you must enclose the file name in
double quotes. For example, #include ''sample_header.h'' is a valid
declaration for a custom header file.
Since the code you specify in this option appears in multiple source files that link
into a single binary, limitations exist on what you can include. For example, do not
include a global variable definition such as int x; or a function body such as
void myfun(void)
{
...
}
These code lines cause linking errors because their symbol definitions appear
multiple times in the source files of the generated code. You can, however, include
extern declarations of variables or functions such as extern int x; or extern
void myfun(void);.
• Initialize function — Enter code statements that execute once at the start of
simulation. Use this code to invoke functions that allocate memory or perform
other initializations of your custom code.
• Terminate function — Enter code statements that execute at the end of
simulation. Use this code to invoke functions that free memory allocated by the
custom code or perform other cleanup tasks.
• Include directories — Enter a space-separated list of the folder paths that
contain custom header files that you include either directly (see Header file
option) or indirectly in the compiled target.
• Source files — Enter a list of source files to compile and link into the target. You
can separate source files with a comma, a space, or a new line.
• Libraries — Enter a space-separated list of static libraries that contain custom
object code to link into the target.
4 Click OK.
Tip If you want to rebuild the target to include custom code changes, select Code > C/C
++ Code > Build Model in the Stateflow Editor.
30-7
30 Build Targets
For information on setting simulation options using the command-line API, see
“Command-Line API to Set Simulation and Code Generation Parameters” on page 30-19.
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “Include Custom C Code Functions and Structures”
• “Share String Data with Custom C Code” on page 20-17
• “Integrate Custom Structures in Stateflow Charts” on page 25-11
30-8
Access Custom C Code in Library Charts
1 In the Stateflow Editor, select Simulation > Debug > Simulation Target For
MATLAB & Stateflow.
30-9
30 Build Targets
2 Select Use local custom code settings (do not inherit from main model).
This step ensures that each library model retains its own custom code settings during
simulation.
3 Specify your custom code in the subpanes.
Follow the guidelines in “Specify Relative Paths to Your Custom Code” on page 30-
24.
Note See “Task 1: Include Custom C Code in the Simulation Target” on page 30-5 for
descriptions of the custom code options.
30-10
See Also
4 Click OK.
For information on setting simulation options using the command-line API, see
“Command-Line API to Set Simulation and Code Generation Parameters” on page 30-19.
Note You cannot simulate only the Stateflow blocks in a library model. You must first
create a link to the library block in your main model and then simulate the main model.
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “Include Custom C Code Functions and Structures”
• “Share String Data with Custom C Code” on page 20-17
• “Integrate Custom Structures in Stateflow Charts” on page 25-11
30-11
30 Build Targets
To integrate custom C code that applies to all charts for simulation, perform the tasks
that follow.
30-12
Access Custom C Code in All Charts in Model
Follow the guidelines in “Specify Relative Paths to Your Custom Code” on page 30-
24.
Note See “Task 1: Include Custom C Code in the Simulation Target” on page 30-5 for
descriptions of the custom code options.
4 Click OK.
By default, settings in the Simulation Target pane for the main model apply to all
charts contributed by library models.
30-13
30 Build Targets
Tip If you want to rebuild the target to include custom code changes, select Code > C/C
++ Code > Build Model in the Stateflow Editor.
1 In the Stateflow Editor, select Simulation > Debug > Simulation Target For
MATLAB & Stateflow.
2 Clear the Use local custom code settings (do not inherit from main model)
check box.
This step ensures that library charts inherit the custom code settings of your main
model.
3 Click OK.
For information on setting simulation options using the command-line API, see
“Command-Line API to Set Simulation and Code Generation Parameters” on page 30-19.
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “Include Custom C Code Functions and Structures”
• “Share String Data with Custom C Code” on page 20-17
• “Integrate Custom Structures in Stateflow Charts” on page 25-11
30-14
Access Custom Code Variables and Functions in Stateflow Charts
By right clicking on the Stateflow object that uses your custom code, you can access your
custom code variable. After right clicking on the object, hover over Explore. Your custom
code variable appears, denoted by (C variable). Clicking the C variable allows you to
access the custom code from MATLAB.
30-15
30 Build Targets
external code from MATLAB code by using coder.ceval, see “Call C/C++ Code from
MATLAB Code” (MATLAB Coder).
By right clicking on the Stateflow object that uses your custom code, you can access your
custom code function. After right clicking on the object, hover over Explore. Your custom
code function appears, denoted by (C function). Clicking the C function allows you to
access the custom code from MATLAB.
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
• “Specify Relative Paths to Your Custom Code” on page 30-24
30-16
Speed Up Simulation
Speed Up Simulation
Some charts do not qualify for JIT mode, such as charts with signal logging.
Stateflow models include debugging support for simulation. To gain optimal performance,
turn off debugging by using this command:
When you run this command, your Stateflow charts do not have debugging support or
run-time error checking.
Note When you turn off debugging, animation is also turned off.
Click OK.
30-17
30 Build Targets
For more information, see “Create Specialized Chart Libraries for Large-Scale Modeling”
on page 24-18.
30-18
Command-Line API to Set Simulation and Code Generation Parameters
object_name = getActiveConfigSet(gcs)
This command returns an object handle to the model settings in the Model
Configuration Parameters dialog box for the current model.
2 To set a parameter for that dialog box, type:
object_name.set_param('parameter_name', value)
This command sets a configuration parameter to the value that you specify.
For example, you can set the Reserved names parameter for simulation by typing:
cp = getActiveConfigSet(gcs)
cp.set_param('SimReservedNameArray', {'abc','xyz'})
Note You can also get the current value of a configuration parameter by typing:
object_name.get_param('parameter_name')
For more information about using get_param and set_param, see the Simulink
documentation.
30-19
30 Build Targets
30-20
Command-Line API to Set Simulation and Code Generation Parameters
30-21
30 Build Targets
30-22
See Also
See Also
More About
• “Recommended Settings Summary for Model Configuration Parameters” (Simulink
Coder)
30-23
30 Build Targets
• You can use the forward slash (/) or backward slash (\) as a file separator, regardless
of whether you are on a UNIX® or PC platform. The makefile generator returns the
path names with the correct platform-specific file separators.
• You can use tokens that evaluate in the MATLAB workspace, if you enclose them with
dollar signs ($...$). For example, consider this path:
$mydir1$\dir1
In this example, mydir1 is a variable that you define in the MATLAB workspace as
'd:\work\source\module1'. In the generated code, this custom include path
appears as:
30-24
See Also
d:\work\source\module1\dir1
• You must enclose paths in double quotes if they contain spaces or other nonstandard
path characters, such as hyphens (-).
See Also
More About
• “Reuse Custom Code in Stateflow Charts” on page 30-26
30-25
30 Build Targets
Stateflow charts call custom code functions by using the same syntax as other reusable
functions:
return_val = function_name(arg1,arg2,...)
Note Do not share fixed-point data between your custom code and your Stateflow chart.
Data returned from custom code must be of type double.
30-26
Reuse Custom Code in Stateflow Charts
See Yes
Speeding Up Speed up
Simulation. simulation?
No
Yes
See
C++ Integrating
C or C++? Custom C++
Code for
Simulation.
No
See Integrating
No Custom C Code
Any library for Nonlibrary
charts? Charts for
Simulation.
Yes
The model contains a Stateflow® chart with an input, which you can set to 0 or 1 by
toggling the manual switch in the model during simulation.
30-27
30 Build Targets
The chart contains two states A and B. In this example, you define two constants named
TRUE and FALSE to guard the transitions between the states in the chart, instead of using
the values 1 and 0. These custom definitions improve the readability of your chart actions.
TRUE and FALSE are not Stateflow data objects.
#define TRUE 1
#define FALSE 0
Because the two custom definitions appear at the top of the generated machine header
file sf_custom_code_global_constants_sfun.h, you can use TRUE and FALSE in all
charts that belong to this model.
30-28
Reuse Custom Code in Stateflow Charts
The model contains a Stateflow chart with an input signal from a Sine Wave block.
30-29
30 Build Targets
The chart contains two states A and B, and three data objects: input_data,
local_data, and out_data. The chart accesses a custom variable named my_global
and calls a custom function named my_function.
30-30
Reuse Custom Code in Stateflow Charts
4 In the Include directories subpane, enter the name of the folder that contains your
custom code files. To access custom code files in a subfolder of the model folder, use
a relative path name of the form .\subfolder_name.
5 In the Source files subpane, enter the name of the source file that contains your
custom code. To access a source file that resides in a subfolder of the model folder,
use a relative path name of the form .\subfolder_name\source_file.c.
In this example, the custom code defines three constants, a variable, and a function by
using these configurations:
30-31
30 Build Targets
The header file also contains declarations for the variable my_global and the function
my_function:
30-32
See Also
Because the custom definitions appear at the top of the generated machine header file
sf_custom_code_constants_vars_fcns_sfun.h, you can access them in all charts
that belong to this model.
See Also
More About
• “Access Custom C Code in Nonlibrary Charts” on page 30-5
• “Access Custom C Code in Library Charts” on page 30-9
• “Access Custom C Code in All Charts in Model” on page 30-12
• “Access Custom C++ Code in Stateflow Charts” on page 30-3
30-33
30 Build Targets
If parsing is unsuccessful, the chart automatically appears with the highlighted object
that causes the first parse error. You can select the error in the diagnostic window to
bring its source chart to the front with the source object highlighted. Any unresolved data
or events in the chart are flagged in the Symbol Wizard.
30-34
Resolve Undefined Symbols in Your Chart
• To define a symbol with the inferred class and scope, click the error icon and select
Fix.
• To define a symbol with a different class or scope, select another combination of class
and scope from the TYPE drop-down list.
• To resolve all of the undefined symbols with their inferred classes and scopes, click the
30-35
30 Build Targets
• To accept a definition with the inferred class and scope, select the check box in front
of the symbol.
• To modify a definition, select a different class or scope from the Class or Scope drop-
down lists.
• To reject a definition, clear the check box in front of the symbol.
After you edit the symbol definitions, add the symbols to the Stateflow hierarchy by
clicking OK.
30-36
Resolve Undefined Symbols in Your Chart
• If you select Import custom code, the parser tries to find unresolved chart symbols
in the custom code. If the custom code does not define these symbols, they appear in
the Symbol Wizard.
• If you do not select Import custom code, the parser considers unresolved data
symbols in the chart as defined in the custom code. If the custom code does not define
these symbols, simulating and generating code from the model results in an error.
The Import custom code option is not available for charts that use MATLAB as the
action language. For more information, see “Import custom code” (Simulink).
30-37
30 Build Targets
See Also
More About
• “Add Stateflow Data” on page 9-2
• “Set Data Properties” on page 9-5
• “Manage Data, Events, and Messages in the Symbols Window” on page 33-2
• “Detect Unused Data in the Symbols Window” on page 33-4
• “Parse Stateflow Charts” on page 30-34
• “Import custom code” (Simulink)
30-38
Call Extrinsic MATLAB Functions in Stateflow Charts
•
MATLAB as the action language.
•
C as the action language.
In charts that use C as the action language, you can call built-in MATLAB functions and
access MATLAB workspace variables by using the ml namespace operator or the ml
function. For more information, see “Access MATLAB Functions and Workspace Data in C
Charts” on page 12-32.
In charts that use MATLAB as the action language, you can call MATLAB functions
supported for code generation directly. To call extrinsic functions that are not supported
for code generation, you must use the coder.extrinsic function. When you declare a
function with coder.extrinisic(function_name), Stateflow creates a call to the
function during simulation. In a Stateflow chart, you only declare coder.extrinsic
once. You cannot declare reserved keywords with coder.extrinsic. For more
information, see “Rules for Naming Stateflow Objects” on page 2-4.
For charts that include atomic subcharts, you must declare functions that are not
supported for code generation with coder.extrinsic separately within the atomic
subchart.
coder.extrinsic Function
To create a call for the extrinsic function heaviside, this model uses
coder.extrinsic.
30-39
30 Build Targets
The chart contains two parallel states, A and B, and one graphical function block, foo.
State A declares the function heaviside, which is not supported for code generation, by
using coder.extrinsic. State B and the graphical function block also use heaviside
without coder.extrinsic.
The input for state A is u1, a sine wave, and the input for state B is u2, a cosine wave. The
graphical function out outputs the value of the heaviside function for the input in.
30-40
Call Extrinsic MATLAB Functions in Stateflow Charts
You only need to declare heaviside once in your chart using coder.extrinsic. After
this you can use the heaviside function anywhere within your chart without
coder.extrinsic. When generating code the functions that you declare using
coder.extrinsic will have a call to the extrinsic function, and that function will not
appear in the generated code.
30-41
30 Build Targets
See Also
coder.extrinsic | heaviside
30-42
See Also
More About
• “Access MATLAB Functions and Workspace Data in C Charts” on page 12-32
• “Generate Code for Global Data” (MATLAB Coder)
• “Functions and Objects Supported for C/C++ Code Generation — Alphabetical List”
(Simulink)
30-43
31
Code Generation
The generated code does not contain code to interface with other blocks in a Simulink
model or the MATLAB base workspace. You cannot generate code only for the Stateflow
blocks in a library model. First create a link to the library block in your main model and
then generate code for the main model.
31-2
Generate C or C++ Code from Stateflow Blocks
• Verify generated code. You can identify which Stateflow object corresponds to a line of
code and track code from different objects that you have or have not reviewed.
• Include comments in code generated for large-scale models. You can identify objects in
generated code and avoid manually entering comments or descriptions.
To enable traceability comments, you must have Embedded Coder or HDL Coder
software. For C/C++ code generation, comments appear in the generated code for
embedded real-time (ert) based targets only. For more information, see “Trace Stateflow
Elements in Generated Code” (Embedded Coder) and “Navigate Between Simulink Model
and HDL Code by Using Traceability” (HDL Coder).
31-3
31 Code Generation
See Also
More About
• “Generate Reusable Code for Unit Testing” on page 15-48
• “Generate Reusable Code for Atomic Subcharts” on page 15-27
• “Select Array Layout for Matrices in Generated Code” on page 31-5
31-4
Select Array Layout for Matrices in Generated Code
By default, the code generator uses column-major layout to flatten the matrix as a one-
dimensional array. The array is stored in memory with this arrangement:
{1, 4, 2, 5, 3, 6}
If you select row-major layout, the code generator flattens the matrix and stores it in
memory with this arrangement:
{1, 2, 3, 4, 5, 6}
If you have Embedded Coder, you can preserve the multidimensionality of Stateflow local
data, prevent its flattening, and implement the matrix as a two-dimensional array with
this arrangement:
Row-major and multidimensional array layout can ease the integration with external code.
For more information, see “Code Generation of Matrices and Arrays” (Simulink Coder)
and “Dimension Preservation of Multidimensional Arrays” (Embedded Coder).
For example, this Stateflow chart contains local data x of size [2 3]. The state actions
index the elements in x by row and column number.
31-5
31 Code Generation
If you generate code, the file sf_matrix_layout.c implements the local data x in
column-major layout with these lines of code:
...
sf_matrix_layout_DW.x[0] = 1.0;
sf_matrix_layout_DW.x[2] = 2.0;
sf_matrix_layout_DW.x[4] = 3.0;
sf_matrix_layout_DW.x[1] = 4.0;
sf_matrix_layout_DW.x[3] = 5.0;
sf_matrix_layout_DW.x[5] = 6.0;
...
The generated code refers to the elements of x by using only one index.
31-6
Select Array Layout for Matrices in Generated Code
The file sf_matrix_layout.c implements the local data x in row-major layout with
these lines of code:
...
sf_matrix_layout_DW.x[0] = 1.0;
sf_matrix_layout_DW.x[1] = 2.0;
sf_matrix_layout_DW.x[2] = 3.0;
sf_matrix_layout_DW.x[3] = 4.0;
sf_matrix_layout_DW.x[4] = 5.0;
sf_matrix_layout_DW.x[5] = 6.0;
...
The generated code refers to the elements of x by using only one index.
• Charts and state transition table blocks that use MATLAB as the action language.
• Charts that contain truth table functions that use MATLAB as the action language.
• Charts that contain MATLAB functions.
• Charts that use custom C code.
• Truth table blocks.
...
sf_matrix_layout_DW.x[0][0] = 1.0;
31-7
31 Code Generation
sf_matrix_layout_DW.x[0][1] = 2.0;
sf_matrix_layout_DW.x[0][2] = 3.0;
sf_matrix_layout_DW.x[1][0] = 4.0;
sf_matrix_layout_DW.x[1][1] = 5.0;
sf_matrix_layout_DW.x[1][2] = 6.0;
...
Multidimensional layout is not available for bus signals containing multidimensional array
data. Multidimensional layout is not supported in:
See Also
More About
• “Generate C or C++ Code from Stateflow Blocks” on page 31-2
• “Use Arrays in Actions” on page 12-44
• “Code Generation of Matrices and Arrays” (Simulink Coder)
• “Interpolation Algorithm for Row-Major Array Layout” (Embedded Coder)
• “Dimension Preservation of Multidimensional Arrays” (Embedded Coder)
31-8
32
Debugging Charts
For Stateflow charts in Simulink models, you can perform most debugging tasks directly
from the Stateflow Editor:
In addition, during simulation, you can display and change the values of Stateflow data in
the MATLAB Command Window.
For information on debugging Stateflow chart objects that you execute in MATLAB, see
“Debug a Standalone Stateflow Chart” on page 34-16.
See Also
More About
• “Set Breakpoints to Debug Charts” on page 32-5
• “Manage Stateflow Breakpoints and Watch Data” on page 32-17
• “Watch Stateflow Data Values” on page 32-36
• “Change Data Values During Simulation” on page 32-41
• “Debug Run-Time Errors in a Chart” on page 32-24
32-2
Animate Stateflow Charts
• Lightning Fast
• Fast
• Medium
• Slow
• None
Lightning Fast animation provides the fastest simulation speed by buffering the
highlights. During Lightning Fast animation, the more recently highlighted objects are
in a bolder, lighter blue. These highlights fade away as simulation time progresses.
The default animation speed, Fast, shows the active highlights at each time step. To add a
delay with each time step, set the animation speed to Medium or Slow.
Maintain Highlighting
To maintain highlighting of active states in the chart after simulation ends, select
Simulation > Stateflow Animation > Maintain Highlighting.
Disable Animation
Animation is enabled by default in Stateflow charts. To turn off animation for a chart, in
the Stateflow editor, select Simulation > Stateflow Animation > None.
32-3
32 Debug and Test Stateflow Charts
executing on a target system. Stateflow software can use the external mode
communication channel to animate chart states. Also, you can designate chart data of
local scope to be test points and view the test point data in floating scopes and signal
viewers.
32-4
Set Breakpoints to Debug Charts
Breakpoints appear as circular red badges. For example, this chart contains breakpoints
on the state On and on the transition from On to Off.
Breakpoints on Charts
To set a breakpoint on a chart, right-click inside the chart and select Set Breakpoint on
Chart Entry. This type of breakpoint stops simulation before entering the chart.
32-5
32 Debug and Test Stateflow Charts
To remove the breakpoint, right-click inside the chart and clear the Set Breakpoint on
Chart Entry option.
To set a breakpoint on a state or transition, right-click the state or transition and select
Set Breakpoint. For states, the default breakpoint is On State Entry and During
State. For transitions, the default breakpoint is When Transition is Valid. To
change the type of breakpoint, click the breakpoint badge and select a different
configuration of breakpoints. For more information, see “Change Breakpoint Types” on
page 32-7.
To remove the breakpoint, right-click the state or transition and select Clear
Breakpoint.
To set a breakpoint on a graphical or truth table function, right-click the function and
select Set Breakpoint During Function Call. This type of breakpoint stops simulation
before calling the function.
To remove the breakpoint, right-click the function and clear the Set Breakpoint During
Function Call option.
32-6
Set Breakpoints to Debug Charts
Breakpoints on Events
To set or clear breakpoints for an event, modify the Debugger Breakpoints properties
through the Property Inspector or the Model Explorer. For more information, see “Set
Properties for an Event” on page 10-6.
32-7
32 Debug and Test Stateflow Charts
To change the type of breakpoint for an object, click the breakpoint badge. In the
Breakpoints dialog box, you can select a different configuration of breakpoints, depending
on the object type.
Clearing all of the check boxes in the Breakpoints dialog box removes the breakpoint.
Clicking the Manage breakpoints link opens the Stateflow Breakpoints and Watch
window. In this window, you can manage conditions for all breakpoints. For each
breakpoint, you can:
32-8
Set Breakpoints to Debug Charts
• Set conditions.
• Enable the breakpoint.
• Disable the breakpoint.
• Clear the breakpoint.
• View the number of times a breakpoint has been encountered during simulation.
For more information, see “Manage Stateflow Breakpoints and Watch Data” on page 32-
17.
For example, this chart contains a breakpoint on entry in the HIGH state, a substate of On.
When simulation stops at the breakpoint, the active state (On) appears highlighted in blue
and the currently executing substate (HIGH) appears highlighted in green.
32-9
32 Debug and Test Stateflow Charts
An execution status badge appears in the graphical object where execution pauses.
Badge Description
Execution stopped before entering a chart or state.
32-10
Set Breakpoints to Debug Charts
To view data values in the chart, point to a chart object. A tooltip displays:
• The value of each data and message that the selected object uses
• Temporal information (in the presence of a temporal logic operator)
For more information, see “Watch Data in the Stateflow Chart” on page 32-36.
32-11
32 Debug and Test Stateflow Charts
After simulation stops at a breakpoint, you can continue chart execution from the
Stateflow Editor toolbar, at the MATLAB command prompt, or by selecting a keyboard
shortcut.
32-12
Set Breakpoints to Debug Charts
From a statement in a
function containing another
function call, advance to the
first executable statement in
the second function.
32-13
32 Debug and Test Stateflow Charts
Otherwise, continue
simulation to the next
breakpoint. (See Continue.)
Step Forward Exit debug mode and pause
simulation before next time
step.
Stop dbquit Exit debug mode and stop Ctrl+Shift+T
simulation.
In state or transition actions containing more than one statement, you can step through
the individual statements one at a time by selecting Step Over. Stateflow highlights each
statement before executing it. To execute a group of statements together, right-click the
last statement in the group and select Run To Cursor.
32-14
See Also
See Also
More About
• “Debugging Charts” on page 32-2
• “Manage Stateflow Breakpoints and Watch Data” on page 32-17
• “Change Data Values During Simulation” on page 32-41
• “Debug Run-Time Errors in a Chart” on page 32-24
32-15
32 Debug and Test Stateflow Charts
See Also
More About
• “Debugging Charts” on page 32-2
• “Manage Stateflow Breakpoints and Watch Data” on page 32-17
• “Change Data Values During Simulation” on page 32-41
• “Debug Run-Time Errors in a Chart” on page 32-24
32-16
Manage Stateflow Breakpoints and Watch Data
This example shows how to set a conditional breakpoint in the model sf_car. It shows
how you can see speed increasing leading up to the car upshifting. First, set a breakpoint
on the transition from steady_state to upshifting of type When Transition is
Tested.
32-17
32 Debug and Test Stateflow Charts
Without a condition on this breakpoint, simulation pauses every time the transition is
tested, even when the value of speed is far below up_th. To inspect the chart just before
the transition is taken, you want the software to pause simulation only when the value of
speed is approaching the value of up_th. When you set the condition speed > up_th-2
on the breakpoint, then simulation pauses only when the value of speed reaches within 2
of the value of up_th.
32-18
Manage Stateflow Breakpoints and Watch Data
When simulation pauses, you can view the values for the variables speed and up_th in
the Watch tab. To add each variable to the Watch tab:
For more information, see “Watch Stateflow Data Values” on page 32-36.
32-19
32 Debug and Test Stateflow Charts
32-20
Manage Stateflow Breakpoints and Watch Data
If all the breakpoints for a graphical object are disabled, its badge changes from red to
gray.
If there is at least one breakpoint enabled for an object, then the breakpoint badge
remains red.
To enable the breakpoint, select the box next to the breakpoint name.
To disable and enable all Stateflow breakpoints, clear or check the box at the top of the
check box column.
32-21
32 Debug and Test Stateflow Charts
breakpoint or watch data. Click the icon that appears to the right of the name.
To add breakpoints and watch data, see “Set Breakpoints to Debug Charts” on page 32-5
and “Watch Stateflow Data Values” on page 32-36.
You can change the format of watch data. Select the gear icon, . From the drop-down
list, choose the desired MATLAB format for each data type.
32-22
Manage Stateflow Breakpoints and Watch Data
For more information on the floating point and integer formats, see format. For more
information on fixed-point formats, see storedInteger and double.
You can save a snapshot of the breakpoints and watch data list, and then reload it at any
point in the current or subsequent MATLAB session. To save a snapshot, click the save
icon, , and name the snapshot file. To restore a snapshot, click the restore icon, ,
and choose the snapshot file.
32-23
32 Debug and Test Stateflow Charts
32-24
Debug Run-Time Errors in a Chart
3 In your chart, add an event Switch with a scope of Input from Simulink and a
Rising edge trigger.
4 Add a data Shift with a scope of Input from Simulink.
The chart has two states at the highest level in the hierarchy, Power_off and Power_on.
By default, Power_off is active. The event Switch toggles the system between the
Power_off and Power_on states. Power_on has three substates: First, Second, and
Third. By default, when Power_on becomes active, First also becomes active. When
Shift equals 1, the system transitions from First to Second, Second to Third, Third
to First, for each occurrence of the event Switch, and then the pattern repeats.
In the model, there is an event input and a data input. A Sine Wave block generates a
repeating input event that corresponds with the Stateflow event Switch. The Step block
generates a repeating pattern of 1 and 0 that corresponds with the Stateflow data object
Shift. Ideally, the Switch event occurs at a frequency that allows at least one cycle
through First, Second, and Third.
32-25
32 Debug and Test Stateflow Charts
Because you specified a breakpoint on chart entry, execution stops at that point.
3
Click the Step In button, .
After each step, watch the chart animation to see the sequence of execution.
Single-stepping shows that the chart does not exhibit the desired behavior. The
transitions from First to Second to Third inside the state Power_on are not occurring
because the transition from Power_on to Power_off takes priority. The output display of
code coverage also confirms this observation.
32-26
Debug Run-Time Errors in a Chart
Now the transition from Power_on to Power_off does not occur until simulation
time is greater than 20.0.
3 Begin simulation again.
4 Click the Step In button repeatedly to observe the new behavior.
32-27
32 Debug and Test Stateflow Charts
State Inconsistencies
In a Stateflow chart, states are inconsistent if they violate one of these rules:
• An active state with exclusive (OR) decomposition and at least one substate has
exactly one active substate.
• All substates of an active state with parallel (AND) decomposition are active.
• All substates of an inactive state are inactive regardless of the state decomposition.
While you edit your chart, the Stateflow editor displays potential causes for state
inconsistencies by highlighting objects in red or orange. For more information, see
“Detect Modeling Errors During Edit Time” on page 3-28.
One type of state inconsistency occurs when all of these conditions are true:
For example, this chart has a state inconsistency because there is no default transition to
indicate which substate becomes active first.
32-28
Detect Common Modeling Errors During Chart Simulation
Adding an unconditional default transition to one of the states resolves the state
inconsistency.
At compile time, Stateflow charts detect state inconsistencies caused by the omission of
an unconditional default transition. To control the level of diagnostic action, open the
Model Configuration Parameters dialog box. In the Diagnostics > Stateflow pane, for
the diagnostic No unconditional default transitions, you can select error, warning,
or none. The default setting is error. For more information, see “No unconditional
default transitions” (Simulink).
32-29
32 Debug and Test Stateflow Charts
• An integer or fixed-point operation overflows the numeric capacity of its result type.
See “Handle Integer Overflow for Chart Data” on page 9-45 and “Fixed-Point
Operations in Stateflow Charts” on page 22-32.
• The value of a data object is outside the range of the values specified by the Initial
value, Minimum, and Maximum properties. See “Initial Value” on page 9-9 and
“Limit Range Properties” on page 9-10.
For example, this chart contains local data a that has a Minimum value of 0 and a
Maximum value of 2. The entry action in state A initializes a to 1. The during action
increments the value of a by 1. After two time steps, the value of a exceeds its specified
range, resulting in a data range violation.
At run time, Stateflow charts detect data range violations. To control the level of
diagnostic action, open the Model Configuration Parameters dialog box. In the
Diagnostics > Data Validity pane, you can select error, warning, or none for these
diagnostics:
For more information, see “Simulation range checking” (Simulink), “Wrap on overflow”
(Simulink), and “Saturate on overflow” (Simulink).
32-30
Detect Common Modeling Errors During Chart Simulation
Cyclic Behavior
Cyclic behavior occurs when a step or sequence of steps is repeated indefinitely during
chart simulation.
For example, the actions in this chart produce an infinite cycle of recursive event
broadcasts.
The event broadcasts in states A and B occur in condition actions, so the transitions do
not take place until the chart processes the resulting events. The substates A.A1 and
B.B1 remain active, so new event broadcasts continue to trigger the transitions and the
process repeats indefinitely.
Because undirected local event broadcasts can cause unwanted recursive behavior, use of
the send operator to broadcast directed local events is recommended. For more
information, see “Broadcast Local Events to Synchronize Parallel States” on page 12-45.
32-31
32 Debug and Test Stateflow Charts
During chart simulation, Stateflow charts use cycle detection algorithms to detect a class
of infinite recursions caused by event broadcasts. Enable cycle detection through the
Simulation > Debug > MATLAB & Stateflow Error Checking Options > Detect
Cycles check box. Cyclic behavior checking is selected by default.
Stateflow charts also detect undirected local event broadcasts. To control the level of
diagnostic action, open the Model Configuration Parameters dialog box. In the
Diagnostics > Stateflow pane, for the Undirected event broadcasts diagnostic, you
can select error, warning, or none. The default setting is warning. For more
information, see “Undirected event broadcasts” (Simulink).
Stateflow cycle detection is limited to cases of recursion due to event broadcasts and does
not extend to other types of cyclic behavior.
For instance, Stateflow cannot detect the infinite cycle in this flow chart. In this example,
the default transition initializes the local data i to 0. The next transition segment
increments i. The transition to the terminating junction is valid only when the condition
[i < 0] is true. Because this condition is never true, an infinite cycle results.
The model sf_cycle_error_fix provides suggestions for fixing cyclic behavior in flow
charts. At the MATLAB command prompt, enter:
sfhelp('cycle_error');
32-32
See Also
See Also
More About
• “Detect Modeling Errors During Edit Time” on page 3-28
• “Model Configuration Parameters: Stateflow Diagnostics” (Simulink)
32-33
32 Debug and Test Stateflow Charts
However, unwanted recursion can also occur during chart execution. To avoid unwanted
recursion, follow these guidelines:
Suppose that you have functions named f, g, and h in a chart. These functions can be any
combination of graphical functions, truth table functions, MATLAB functions, or Simulink
functions.
• Use directed local event broadcasts with the syntax send(event,state). The event
is a local event in the chart and the state is the destination state that you want to
wake up using the event broadcast.
• If the source of the local event broadcast is a state action, ensure that the destination
state is not an ancestor of the source state in the chart hierarchy.
• If the source of the local event broadcast is a transition, ensure that the destination
state is not an ancestor of the transition in the chart hierarchy.
Also, ensure that the transition does not connect to the destination state.
If you have undirected local event broadcasts in state actions or condition actions in your
chart, a warning appears by default during simulation. Examples of state actions with
undirected local event broadcasts include:
32-34
Guidelines for Avoiding Unwanted Recursion in a Chart
You can control the level of diagnostic action for undirected local event broadcasts in the
Diagnostics > Stateflow pane of the Configuration Parameters dialog box. Set the
Undirected event broadcasts diagnostic to none, warning, or error.
32-35
32 Debug and Test Stateflow Charts
Note If you select the chart properties Export Chart Level Functions and Treat
Exported Functions as Globally Visible, then the tooltip does not display temporal
logic data.
For example, this chart stops execution before entering the second state. Pointing to the
superstate gear displays a tooltip showing the values of:
32-36
Watch Stateflow Data Values
Because the value of duration(speed >= up_threshold) is greater than TWAIT, the
chart takes the transition from first to second.
A chart determines the value of data and temporal logic expressions at different stages of
a time step. For instance, in the previous example, the chart computes temporal
information at the start of each time step and updates speed at the end of each time step.
If you advance through the simulation using the Step Forward option and observe
data at the end of each time step, the temporal information in the tooltip can appear to
lag behind the rest of the data. After observing the value of speed cross the
up_threshold, you must step forward twice before duration(speed >=
up_threshold) becomes nonzero. To avoid this behavior, use the Step Over option
and observe the data at shorter intervals.
32-37
32 Debug and Test Stateflow Charts
function stats(vals)
%#codegen
len = length(vals);
mean = avg(vals, len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
coder.extrinsic('plot');
plot(vals,'-+'); % Breakpoint set at this line
When simulation reaches the breakpoint, you can display Stateflow data in the MATLAB
Command Window.
Command Description
dbstep Advance to next executable line of code.
32-38
Watch Stateflow Data Values
Command Description
dbstep [in/ When debugging MATLAB functions in a chart:
out]
• dbstep [in] advances to the next executable line of code. If
that line contains a call to another function, execution continues
to the first executable line of the function.
• dbstep [out] executes the rest of the function and stops just
after leaving the function.
dbcont Continue execution to next breakpoint.
dbquit (ctrl-c) Stop simulation of the model. Press Enter after this command to
return to the command prompt.
help Display help for command-line debugging.
print var Display the value of the variable var.
...or...
var
var (i) Display the value of the ith element of the vector or matrix var.
var (i:j) Display the value of a submatrix of the vector or matrix var.
save Saves all variables to the specified file. Follows the syntax of the
MATLAB save command. To retrieve variables in the MATLAB base
workspace, use the load command after simulation has ended.
whos Display the size and class (type) of all variables in the scope of the
halted MATLAB function in your chart.
You can issue any other MATLAB command at the debug>> prompt but the results are
executed in the Stateflow workspace. For example, you can issue the MATLAB command
plot(var) to plot the values of the variable var.
To issue a command in the MATLAB base workspace at the debug>> prompt, use the
evalin command with the first argument 'base' followed by the second argument
command, for example, evalin('base','whos').
32-39
32 Debug and Test Stateflow Charts
To add active state data and truth table data to the watch list, from the Model Explorer,
open the Data Properties dialog box. Select Add to Watch Window.
You can choose the display format for each data type. For more information, see “Format
Watch Display” on page 32-22.
32-40
Change Data Values During Simulation
data_name = new_value
To change data values directly in the Symbols Window, see “Manage Data, Events, and
Messages in the Symbols Window” on page 33-2.
For a list of data that you cannot change, see “Data That Is Read-Only During Simulation”
on page 32-44. You cannot change message data values at the command line.
Suppose that, after the debug>> prompt appears, you enter whos at the prompt and see
the following data:
If you try to enter airflow = 2, you get an error message because MATLAB interprets
that expression as the assignment of a double value to data of uint8 type. For
reference, see “Cases When Casting Is Necessary” on page 32-45.
32-41
32 Debug and Test Stateflow Charts
Multidimensional Example
Suppose that, after the debug>> prompt appears, you enter whos at the prompt and see
the following data:
One-based indexing applies when you change values of Stateflow data while the chart is
in debug mode.
Variable-Size Example
Suppose that, after the debug>> prompt appears, you enter whos at the prompt and see
the following data:
Changing the dimensions of variable-size data works only when the new size does not
exceed the dimension bounds.
32-42
Change Data Values During Simulation
Fixed-Point Example
Suppose that, after the debug>> prompt appears, you enter whos at the prompt and see
the following data:
Both y_n1 and x_n1 have signed fixed-point types, with a word length of 16. y_n1 has a
fraction length of 10 and x_n1 has a fraction length of 12.
For more information about using fi objects, see the Fixed-Point Designer
documentation.
Enumerated Example
Suppose that, after the debug>> prompt appears, you enter whos at the prompt and see
the following data:
32-43
32 Debug and Test Stateflow Charts
You must include the enumerated type explicitly in the assignment. Otherwise, an error
appears at the debug>> prompt.
You cannot change data of the following scopes while the chart is in debug mode:
• Constant
• Input
• Data type
• Size
However, for variable-size data, you can change the dimensions of the data as long as the
size falls within the dimension bounds. For example, varsizedData = ones(5,7); is a
valid assignment for a variable-size 10-by-10 array.
• Do not assign a value that falls outside the range of values that the fixed-point type
can represent. Avoid selecting a value that causes overflow.
• Sign, word length, fraction length, slope, and bias cannot change.
32-44
Change Data Values During Simulation
When you change a data value, you must explicitly cast values for data of the following
built-in types:
• single
• int32
• int16
• int8
• uint32
• uint16
• uint8
• my_data1 = uint8(2)
• my_data2 = single(5.3)
Casting is not necessary when you change the value of data that is of type double.
32-45
32 Debug and Test Stateflow Charts
A Stateflow® test point is a signal that you can observe during simulation, for example,
by using a Floating Scope block. You can designate states or local data with these
properties as test points:
You can specify individual data or states as test points by setting their TestPoint property
via the Stateflow API, in the Property Inspector, or in the Model Explorer.
You can monitor individual Stateflow test points with a floating scope during model
simulation. You can also log test point values into MATLAB workspace objects.
You can also use active state output to view or log state activity data in Simulink®. For
more information, see “Monitor State Activity Through Active State Data” on page 24-26.
Set Test Points for Stateflow States and Data with the Property Inspector
You can explicitly set individual states, local data, and output data as test points in the
Model Explorer. The following procedure shows how to set individual test points for
Stateflow states and data.
32-46
Monitor Test Points in Stateflow Charts
In the Stateflow chart, state A and its substate X are entered on the first tic event. State
A and substate X stay active until 10 tic events have occurred, and then state B is
entered. On the next event, state A and substate X are entered and the cycle continues.
The data data belongs to substate X. The entry and during actions for substate X
increment data while X is active for 10 tic events. When state B is entered, data
reinitializes to zero, and then the cycle repeats.
3. Select state A. Then, in the Logging section of the Property Inspector, select Test
Point.
6. Select the data data. Then, in the Logging section of the Property Inspector, select
Test Point.
You can also log these test points. For instructions, see “Log Multiple Signals” on page
32-52.
Monitor Data Values and State Self Activity Using a Floating Scope
In this section, you configure a Floating Scope block to monitor a data value and the self
activity of a state.
32-47
32 Debug and Test Stateflow Charts
4. In the Model hierarchy pane, select the chart and in the List contents, select the
signals.
32-48
Monitor Test Points in Stateflow Charts
32-49
32 Debug and Test Stateflow Charts
When state A.X is active, the signal value is 1. When that state is inactive, the signal value
is 0. Because this value can be very low or high compared to other data, you might want
to add a second Floating Scope block to compare the activity signal with other data.
See Also
More About
• “Test Points” (Simulink)
32-50
Log Simulation Output for States and Data
1 Enable signal logging for the chart and choose a logging format. See “Enable Signal
Logging” on page 32-51.
2 Configure states and data for signal logging. See “Configure States and Data for
Logging” on page 32-52.
3 Simulate the chart.
4 Access the logged data. See “Access Signal Logging Data” on page 32-54.
• Array
• Structure
• Structure with time
• Dataset
The default setting is Dataset. For more information, see “Time, State, and Output
Data Format” (Simulink).
6 Click OK.
32-51
32 Debug and Test Stateflow Charts
Configure logging properties for one state or data object at a time through the Property
Inspector, the Model Explorer, or the properties dialog box for the state or data object.
Select the Logging tab and modify properties as needed. For more information, see
“Logging Properties” on page 9-18.
Configure logging properties for multiple states and data objects through the Stateflow
Signal Logging dialog box. Select which chart objects to log from a list of all states, local,
and output data. For more information, see “Logging Properties” on page 9-18.
32-52
Log Simulation Output for States and Data
Configure logging properties for states and data objects programmatically from the
command line. To enable logging for a states or data object, get a handle for the object
and set its LoggingInfo.DataLogging property to 1. For more information on the
Stateflow Programmatic Interface, see “Logging Properties”.
32-53
32 Debug and Test Stateflow Charts
4 Enable logging for the Dining_area state and the service data:
diningState.LoggingInfo.DataLogging = 1;
serviceData.LoggingInfo.DataLogging = 1;
5 Change the logging name of the Dining_area state to the custom name Dining
Room:
% Enable custom naming
diningState.LoggingInfo.NameMode = 'Custom';
When you simulate the model, the Simulation Data Inspector icon is highlighted to
indicate that it has new simulation data.
1
To open the Simulation Data Inspector, click the icon .
2 Inspect and compare the signals logged during simulation. See Simulation Data
Inspector.
32-54
Log Simulation Output for States and Data
1 To access the signal logging object, at the MATLAB command prompt, enter:
logsout
logsout =
Name BlockPath
___________ ________________________________
1 [1x1 State] Dining Room sf_semantics_hotel_checkin/Hotel
2 [1x1 Data ] service sf_semantics_hotel_checkin/Hotel
2 To access logged elements, use the get method. You can access logged elements by
name, index, or block path.
diningLog =
Stateflow.SimulationData.State
Package: Stateflow.SimulationData
Properties:
Name: 'Dining Room'
BlockPath: [1×1 Simulink.SimulationData.BlockPath]
Values: [1×1 timeseries]
serviceLog = logsout.get('service')
serviceLog =
Stateflow.SimulationData.Data
Package: Stateflow.SimulationData
Properties:
Name: 'service'
BlockPath: [1×1 Simulink.SimulationData.BlockPath]
Values: [1×1 timeseries]
3 To access the logged data and time of each logged element, use the Values.Data
and Values.Time properties. For example:
32-55
32 Debug and Test Stateflow Charts
T1 = table(diningLog.Values.Time,diningLog.Values.Data);
T1.Properties.VariableNames = {'Time','Data'}
T1 =
6×2 table
Time Data
__________ ____
0 0
1.8607e+06 1
1.9653e+06 0
1.9653e+06 1
1.9653e+06 0
2.2912e+06 1
T2 = table(serviceLog.Values.Time,serviceLog.Values.Data);
T2.Properties.VariableNames = {'Time','Data'}
T2 =
6×2 table
Time Data
__________ ____
1.7076e+06 0
1.8607e+06 1
1.9653e+06 2
1.9653e+06 3
1.9653e+06 4
2.2912e+06 5
• View logged data in a figure window by using the plot function.
X = serviceLog.Values.Time;
Y = serviceLog.Values.Data;
plot(X,Y,'-o')
xlabel('Time')
ylabel('Data')
32-56
Log Simulation Output for States and Data
A = [double(diningLog.Values.Time) double(diningLog.Values.Data)];
xlswrite('dining_log.xls',A);
A[1][1] = 1;
A[1][2] = 1;
produces two different changes in the logged data. In contrast, updating a matrix A in a
single command
A = 1;
produces a single change in the logged data, even though the command implies A[i][j]
= 1 for all values of i and j.
32-57
32 Debug and Test Stateflow Charts
If you log state activity or data from a chart with Fast Restart enabled, any run after the
first run duplicates the first logged data points. When you run algorithms that process
these data points, you must account for this duplication.
See Also
Simulink.SimulationData.Dataset | get | plot | table | xlswrite
More About
• “Configure a Signal for Logging” (Simulink)
• “Logging and Accessibility Options” (Simulink)
• “Export Signal Data Using Signal Logging” (Simulink)
32-58
Log Data in Library Charts
As with other Simulink block libraries, you can specialize each instance of chart library
blocks in your model to use different data types, sample times, and other properties.
Library instances that inherit the same properties can reuse generated code.
For more information about Simulink block libraries, see “Libraries” (Simulink).
32-59
32 Debug and Test Stateflow Charts
Each instance inherits logging properties from the library chart. For example:
32-60
Log Data in Library Charts
The selector clears all DataLogging check boxes for the model.
c Enable logging only for the Fail and FailOnce states in Sensor1:
Select DataLogging for these two signals. Leave DataLogging cleared for the
OK signal.
d Append the text Sensor1 to the logging names for Fail and FailOnce:
Double-click the logging names for signals Fail and FailOnce, and rename
them LogFailSensor1 and LogFailOnceSensor1, respectively.
3 Open the model sf_atomic_sensor_pair. This model contains two instances of the
library chart.
4 Create a ModelLoggingInfo object for the model.
This object contains a vector Signals that stores all logged signals.
32-61
32 Debug and Test Stateflow Charts
mi = Simulink.SimulationData.ModelLoggingInfo. ...
createFromModel('sf_atomic_sensor_pair')
mi =
Simulink.SimulationData.ModelLoggingInfo
Package: Simulink.SimulationData
Properties:
Model: 'sf_atomic_sensor_pair'
LoggingMode: 'OverrideSignals'
LogAsSpecifiedByModels: {}
Signals: [1x6 Simulink.SimulationData.SignalLoggingInfo]
The Signals vector contains the signals marked for logging in the library chart:
To create block paths for the signals Fail, FailOnce, and OK in the atomic subchart
Sensor1 in the RedundantSensors chart:
To get the index for the signals Fail, FailOnce, and OK:
failidx = mi.findSignal(failPath);
failOnceidx = mi.findSignal(failOncePath);
OKidx = mi.findSignal(OKPath);
32-62
See Also
b Append the text Sensor1 to the logging names for Fail and FailOnce:
% Enable custom naming
mi.Signals(failidx).LoggingInfo.NameMode = 1;
mi.Signals(failOnceidx).LoggingInfo.NameMode = 1;
See Also
Simulink.SimulationData.BlockPath |
Simulink.SimulationData.ModelLoggingInfo
32-63
32 Debug and Test Stateflow Charts
• Simulation
• Logging
• Code generation
• Animation
• Debugging
• Active state output
When you explicitly comment out a Stateflow object with Comment Out, the object
appears gray with a badge . The software implicitly comments out some associated
objects. Implicitly commented objects also appear gray, but do not have a badge. For
example, if you explicitly comment out a state or junction, all incoming and outgoing
32-64
Commenting Stateflow Objects in a Chart
transitions are implicitly commented out. In this image of sf_car, the state
steady_state is explicitly commented. The transitions in and out of steady_state are
implicitly commented.
32-65
32 Debug and Test Stateflow Charts
To uncomment an object, right-click the commented object and select Uncomment. All
implicitly commented objects are restored as well. Implicitly commented objects cannot
be uncommented directly.
Add a note to the commented object by clicking the badge . Point to a badge to see the
associated comments. You cannot add notes to implicitly commented objects.
32-66
33
• “Manage Data, Events, and Messages in the Symbols Window” on page 33-2
• “Use the Model Explorer with Stateflow Objects” on page 33-13
• “Use the Search and Replace Tool” on page 33-19
33 Explore and Modify Charts
33-2
Manage Data, Events, and Messages in the Symbols Window
The rows in the Symbols window display object hierarchy. Expand an object in the window
to see data, events, and messages parented by that object. By default, all the
nongraphical objects in a chart are listed in the window. To view only the objects that are
used at the current level of hierarchy and below, select the icon. To search for
specific symbols, type in the Filter search box .
33-3
33 Explore and Modify Charts
Object Icon
Data
Event
Message
2 In the row for the new object, under TYPE, choose the object type.
3 Edit the name of the object.
4 For input and output objects, under PORT, choose a port number.
5 To view the object in the Property Inspector, right-click the object and select
Inspect.
6 In the Property Inspector, modify the object properties.
After you add objects through the Symbols window, the objects appear as unused until
you reference them in your Stateflow design.
In the Symbols window, you can modify the name, type, and port number of Stateflow
objects. Edit the name of objects in the NAME field. When you rename an object, select
Shift+Enter to rename all instances of the object throughout the state machine. To
change the type or port number of an object, click the corresponding field and select from
the available options. To delete an object from the state machine, right-click the object
and select Delete. To either undo or redo these changes, use the Edit menu.
33-4
Manage Data, Events, and Messages in the Symbols Window
• Machine-parented data
• Inputs and outputs of MATLAB functions
• Data of parameter scope in a chart that contains atomic subcharts
To control when the objects and symbols are highlighted, select the preference button
33-5
33 Explore and Modify Charts
For Stateflow to highlight symbols in the Symbols window that an object uses, select
Highlight used symbols. For Stateflow to highlight objects in the chart that use an
symbol, select Highlight uses on diagram. With Highlight uses on diagram you can
choose to highlight:
For example, open the model sf_tetris2 and double-click the chart TetrisLogic. In
the Symbols window, when you select constant ARENA_HEIGHT, the states and functions
that use ARENA_HEIGHT are highlighted. If the chart does not use an object, the symbol
33-6
Manage Data, Events, and Messages in the Symbols Window
To see the uses of the constant ARENA_HEIGHT, open the function freeze.
33-7
33 Explore and Modify Charts
You can also select a graphical object such as a state, transition, or function in the chart
and view the symbols that the object uses. For example, in the chart TetrisLogic,
expand the symbol MainArea in the Symbols window. If you select the state
FreezeShape in the chart, then the local data shape and the function freeze() are
highlighted in the Symbols window. This highlighting indicates that those objects are used
inside the state FreezeShape.
33-8
Manage Data, Events, and Messages in the Symbols Window
When in debugging mode, the values of each data are displayed in the VALUE column of
the Symbols window. Stateflow updates the values periodically when the simulation is
running. The value column highlights changes to data values as the changes occur. When
the debugger is stopped at a breakpoint, you can update the initial value or change the
value of a symbols in either the command prompt or the Symbols window.
33-9
33 Explore and Modify Charts
For bus elements, you can change the value of a symbols in either the command prompt
or the Symbols window.
In the Symbols window multidimensional arrays appear as the data type and size of the
array. If the array does not exceed more than 100 elements, hover over the symbol to
view the elements. For arrays that contain more than 100 elements, view the elements by
using the command prompt.
When simulation is paused, hover over messages in the canvas to view payloads in the
queue. This is similar to the hover functionality on the canvas. For other non-scalar
objects, the size and data type appear. To see these values, use the Watch window. See
“Watch Stateflow Data Values” on page 32-36 and “Manage Stateflow Breakpoints and
Watch Data” on page 32-17.
33-10
Manage Data, Events, and Messages in the Symbols Window
Additional limitations:
33-11
33 Explore and Modify Charts
• When you modify the code in a MATLAB function, the changes are not updated in the
Symbols window until after you save the MATLAB function.
• You cannot undo or redo changes to input and output for MATLAB functions.
• You cannot recover deleted data, events, or messages from a state transition table.
• You cannot undo scope changes to data parented by graphical functions, MATLAB
functions, and truth tables.
• You cannot undo renaming an object for truth tables.
• When you delete data for objects contained in a Simulink based state, the object
remains in your Simulink based state and the data symbol is shown as undefined in the
Symbols window.
See Also
More About
• “Resolve Undefined Symbols in Your Chart” on page 30-35
• “Add Stateflow Data” on page 9-2
• “Set Data Properties” on page 9-5
33-12
Use the Model Explorer with Stateflow Objects
33-13
33 Explore and Modify Charts
The main window has two panes: a Model Hierarchy pane on the left and a Contents
pane on the right. When you open the Model Explorer, the Stateflow object you are
editing appears highlighted in the Model Hierarchy pane and its objects appear in the
Contents pane. This example shows how the Model Explorer appears when opened from
the chart.
The Model Hierarchy pane displays the elements of all loaded Simulink models, which
includes Stateflow charts. A preceding plus (+) character for an object indicates that you
can expand the display of its child objects by double-clicking the entry or by clicking the
plus (+). A preceding minus (-) character for an object indicates that it has no child
objects.
Clicking an entry in the Model Hierarchy pane selects that entry and displays its child
objects in the Contents pane. A hypertext link to the currently selected object in the
Model Hierarchy pane appears after the Contents of: label at the top of the Contents
pane. Click this link to display that object in its native editor. In the preceding example,
clicking the link sfbus_demo/Chart displays the contents of the chart in its editor.
33-14
Use the Model Explorer with Stateflow Objects
Each type of object, whether in the Model Hierarchy or Contents pane, appears with an
adjacent icon. Subcharted objects (states, boxes, or graphical functions) appear altered
with shading.
The display of child objects in the Contents pane includes properties for each object,
most of which are directly editable. You can also access the properties dialog box for an
object from the Model Explorer. See “Set Properties for Chart Objects in the Model
Explorer” on page 33-15 for more details.
1 Right-click the object row in the Contents pane of the Model Explorer and select
Rename.
33-15
33 Explore and Modify Charts
• For text properties, such as the Name property, a text editing field with the
current text value overlays the displayed value. Edit the field and press the Enter
key or click anywhere outside the edit field to apply the changes.
• For properties with enumerated entries, such as the Scope, Trigger, or Type
properties, select from a drop-down combo box that overlays the displayed value.
• For Boolean properties (properties that are set on or off), select or clear the box
that appears in place of the displayed value.
To set all the properties for an object displayed in the Model Hierarchy or Contents
pane of the Model Explorer:
To display the properties dialog box dynamically for the selected object in the Model
Hierarchy or Contents pane of the Model Explorer:
The properties dialog box for the selected object appears in the far right pane of the
Model Explorer.
Note If you move an object to a level in the hierarchy that does not support the Scope
property for that object, the Scope automatically changes to Local.
1 Select the data or event to move in the Contents pane of the Model Explorer.
You can select a contiguous block of items by highlighting the first (or last) item in
the block and then using Shift + click for highlighting the last (or first) item.
33-16
Use the Model Explorer with Stateflow Objects
2 Click and drag the highlighted objects from the Contents pane to a new location in
the Model Hierarchy pane to change its parent.
A shadow copy of the selected objects accompanies the mouse cursor during
dragging. If no parent is chosen or the parent chosen is the current parent, the
mouse cursor changes to an X enclosed in a circle, indicating an invalid choice.
If you select Cut, the selected items are deleted and then copied to the clipboard for
copying elsewhere. If you select Copy, the selected items are left unchanged.
You can also right-click a single selection and select Cut or Copy from the context
menu. The Model Explorer also uses the keyboard equivalents of Ctrl+X (Cut) and
Ctrl+C (Copy) on a computer running the UNIX or Windows operating system.
3 Select a new parent object in the Model Hierarchy pane of the Model Explorer.
4 Select Edit > Paste. The cut items appear in the Contents pane of the Model
Explorer.
You can also paste the cut items by right-clicking an empty part of the Contents pane
and selecting Paste from the context menu. The Model Explorer also uses the
keyboard equivalent of Ctrl+V (Paste) on a computer running the UNIX or Windows
operating system.
Change the Port Order of Input and Output Data and Events
Input data, output data, input events, and output events each have numerical sequences
of port index numbers. You can change the order of indexing for event or data objects
with a scope of Input to Simulink or Output to Simulink in the Contents pane of the
Model Explorer as follows:
1 Select one of the input or output data or event objects.
2 Click the Port property for the object.
3 Enter a new value for the Port property for the object.
The remaining objects in the affected sequence are automatically assigned a new
value for their Port property.
33-17
33 Explore and Modify Charts
You can also select Edit > Cut or Ctrl+X from the keyboard to delete an object.
33-18
Use the Search and Replace Tool
1 Open a chart.
2 Select Edit > Find & Replace in Chart.
The Search & Replace dialog box contains the following fields:
• Search for
33-19
33 Explore and Modify Charts
Enter search pattern text in the Search for text box. You can select the interpretation
of the search pattern with the Match case check box and the Match options field
(unlabeled and just to the right of the Search in field).
• Match case
If you select this check box, the search is case sensitive and the Search & Replace tool
finds only text matching the search pattern exactly.
• Replace with
Specify the text to replace the text found when you select any of the Replace buttons
(Replace, Replace all, Replace all in this object). See “Use Replace Buttons” on
page 33-28.
• Preserve case
This option modifies replacement text. For an understanding of this option, see
“Replacing with Case Preservation” on page 33-27.
• Search in
By default, the Search & Replace tool searches for and replaces text only within the
current Stateflow chart that you are editing in the Stateflow Editor. You can select to
search the machine owning the current Stateflow chart or any other loaded machine
or chart by accessing this selection box.
• Match options
This field is unlabeled and just to the right of the Search in field. You can modify the
meaning of your search text by entering one of the selectable search options. See
“Refine Searches” on page 33-21.
• Object types and Field types
Under the Search in field are the selection boxes for Object types and Field types.
These selections further refine your search and are described below.
• Search and Replace buttons
These are described in “Use the Search Button and View Area” on page 33-24 and
“Use Replace Buttons” on page 33-28.
• View Area
The bottom half of the Search & Replace dialog box displays the result of a search.
This area is described in “A Breakdown of the View Area” on page 33-26.
33-20
Use the Search and Replace Tool
Refine Searches
Enter search pattern text in the Search for text box. You can use one of the following
settings to further refine the meaning of the text entered.
Match case
By selecting the Match case option, you enable case-sensitive searching. In this case, the
Search & Replace tool finds only text matching the search pattern exactly.
By clearing the Match case option, you enable case-insensitive searching. In this case,
search pattern characters entered in lower- or uppercase find matching text with the
same sequence of base characters in lower- or uppercase. For example, the search
entry"AnDrEw" finds the matching text "andrew" or "Andrew" or "ANDREW".
Preserve case
This option modifies replacement text and not search text. For details, see “Replacing
with Case Preservation” on page 33-27.
Contains word
Select this option to specify that the search pattern text is a whole word expression used
in a Stateflow chart with no specific beginning and end delimiters. In other words, find
the specified text in any setting.
Suppose that you have a state with this label and entry action:
throt_fail
entry: fail_state[THROT] = 1;
Searching for the text fail with the Contains word option finds two occurrences of
fail.
Select this option to specify that the search pattern in the Search for field is a whole
word expression used in a Stateflow chart with beginning and end delimiters consisting of
a blank space or a character that is not alphanumeric and not an underscore character
(_).
In the previous example of a state named throt_fail, if Match whole word is selected,
searching for fail finds no text within that state. However, searching for "fail_state"
33-21
33 Explore and Modify Charts
does find the text "fail_state" as part of the second line since it is delimited by a
space at the beginning and a left square bracket ([) at the end.
Regular expression
Set the Match options field to Regular expression to search for text that varies from
character to character within defined limits.
A regular expression is text composed of letters, numbers, and special symbols that
defines one or more candidates. Some characters have special meaning when used in a
regular expression, while other characters are interpreted as themselves. Any other
character appearing in a regular expression is ordinary, unless a back slash (\) character
precedes it.
If the Match options field is set to Regular expression in the previous example of a
state named throt_fail, searching for "fail_" matches the "fail_" text that is part
of the second line, character for character. Searching with the regular expression "\w*_"
also finds the text "fail_". This search uses the regular expression shorthand "\w" that
represents any part-of-word character, an asterisk (*) that represents any number of any
characters, and an underscore (_) that represents itself.
For a list of regular expression meta characters, see “Regular Expressions” (MATLAB).
Search in
You can select a whole machine or individual chart for searching in the Search in field.
By default, the current chart in which you opened the Search & Replace tool is selected.
A list of the currently loaded machines appears with the current machine expanded
to reveal its Stateflow charts.
2 Select a machine.
33-22
Use the Search and Replace Tool
This list contains the previously selected machine expanded to reveal its Stateflow
charts.
2 Select a chart from the expanded machine.
Object Types
Note You cannot search in state transition tables with this tool.
Field Types
Machines, charts, data, and events have valid Name fields. States have a Name defined
as the top line of their labels. You can search and replace text belonging to the Name
field of a state in this sense. However, if the Search & Replace tool finds matching text in
a state's Name field, the rest of the label is subject to later searches for the specified text
whether or not the label is chosen as a search target.
Note The Name field of machines and charts is an invalid target for the Search &
Replace tool. Use the Simulink model window to change the names of machines and
charts.
Labels
33-23
33 Explore and Modify Charts
Click Search to initiate a single-search operation. If an object match is made, its text
fields appear in the Viewer pane in the middle of the Search & Replace dialog box. If the
object is graphical (state, transition, junction, chart), the matching object appears
highlighted in a Portal pane below the Viewer pane.
33-24
Use the Search and Replace Tool
33-25
33 Explore and Modify Charts
The view area of the Search & Replace dialog box displays matching text and its
containing object, if viewable. In the previous example, taken from the sf_pool model, a
search for the word "friction" finds the Description field for the state
TotalDynamics. The resulting view area consists of these parts:
Icon
Displays an icon appropriate to the object containing the matching text. These icons are
identical to the icons in the Model Explorer that represent Stateflow objects displayed in
“View Stateflow Objects in the Model Explorer” on page 33-13.
Full Path Name of Containing Object
This area displays the full path name for the object that contains the matching text:
This area displays the matching text as a highlighted part of all search-qualified text fields
for the owner object. If other occurrences exist in these fields, they too are highlighted,
but in lighter shades.
To invoke the properties dialog box for the owner object, double-click anywhere in the
Viewer pane.
Portal
This area contains a graphic display of the object that contains the matching text. That
object appears highlighted.
To display the highlighted object in the Stateflow Editor, double-click anywhere in the
Portal pane.
If you specify an entire machine as your search scope in the Search in field, the Search
& Replace tool starts searching at the beginning of the first chart of the model, regardless
of the Stateflow chart that appears in the Stateflow Editor when you begin your search.
33-26
Use the Search and Replace Tool
After searching the first chart, the Search & Replace tool continues searching each chart
in model order until all charts for the model have been searched.
If you specify a Stateflow chart as your search scope, the Search & Replace tool begins
searching at the beginning of the chart. The Search & Replace tool continues searching
the chart until all the chart objects have been searched.
The search order when searching an individual chart for matching text is equivalent to a
depth-first search of the Model Explorer. Starting at the highest level of the chart, the
Model Explorer hierarchy is traversed downward from parent to child until an object with
no child is encountered. At this point, the hierarchy is traversed upward through objects
already searched until an unsearched sibling is found and the process repeats.
If you choose the Preserve case option, matching text is replaced based on one of these
conditions:
• Whisper
Matching text has only lowercase characters. Matching text is replaced entirely with
the lowercase equivalent of all replacement characters. For example, if the
replacement text is "ANDREW", the matching text "bill" is replaced by "andrew".
• Shout
Matching text has only uppercase characters. Matching text is replaced entirely with
the uppercase equivalent of all replacement characters. For example, if the
replacement text is "Andrew", the matching text "BILL" is replaced by "ANDREW".
• Proper
Matching text has uppercase characters in the first character position of each word.
Matching text is replaced entirely with the case equivalent of all replacement
characters. For example, if the replacement text is "andrew johnson", the matching
text "Bill Monroe" is replaced by "Andrew Johnson".
• Sentence
33-27
33 Explore and Modify Charts
Matching text has an uppercase character in the first character position of a sentence
with all other sentence characters in lowercase. Matching text is replaced in like
manner, with the first character of the sentence given an uppercase equivalent and all
other sentence characters set to lowercase. For example, if the replacement text is
"andrew is tall.", the matching text "Bill is tall." is replaced by "Andrew
is tall.".
If the matching text does not follow any of these patterns, then the text and case
replacement match the user input.
Replace
When you select the Replace button, the current instance of text matching the text in the
Search for field is replaced by the text you entered in the Replace with field. The
Search & Replace tool then searches for the next occurrence of the Search for text.
Replace all
When you select the Replace all button, all instances of text matching the Search for
field are replaced by the text entered in the Replace with field. Replacement starts at the
point of invocation to the end of the current Stateflow chart. If you initially skip through
some search matches with the Search button, these matches are also skipped when you
select the Replace all button.
When you select the Replace all in this object button, all instances of text matching the
Search for field are replaced by text you entered in the Replace with field everywhere
in the current Stateflow object regardless of previous searches.
– Informational Messages
33-28
Use the Search and Replace Tool
– Warnings
No Matches Found
Search Completed
The object types and field types that you selected are incompatible.
The matching object is not editable by replacement due to one of these problems.
Problem Solution
A simulation is running. Stop the simulation.
You are editing a locked library block. Unlock the library.
The current object or its parent has been Unlock the object or its parent.
manually locked.
The following warnings appear if the Search & Replace tool must find the object again
and its matching text field. If the original matching object is deleted or changed before an
ensuing search or replacement, the Search & Replace tool cannot continue.
If you search for text, find it, and then delete the containing object, this warning appears
if you continue to search.
33-29
33 Explore and Modify Charts
If you search for text, find it, and then delete the containing object, this warning appears
if you perform a replacement.
If you search for text, find it, and then change the object containing the text, this warning
appears if you perform a replacement.
If you search for text, find it, and then change the Search for field, this warning appears
if you perform a replacement.
33-30
34
With standalone charts, you can create MATLAB applications such as:
• MATLAB App Designer user interfaces that use mode logic to manage the behavior of
widgets. See “Design Human-Machine Interface Logic by Using Stateflow Charts” on
page 34-28.
• Communication protocols and data stream processing applications that use sequential
logic. See “Model a Communications Protocol by Using Chart Objects” on page 34-
34.
• Data Acquisition Toolbox™ or Instrument Control Toolbox™ applications that use
timer-based logic to monitor and control external tasks. See “Implement a Financial
Strategy by Using Stateflow” on page 34-38.
These applications can be shared and executed without requiring a Stateflow license. For
more information, see “Share Standalone Charts” on page 34-4.
edit chart.sfx
If the file chart.sfx does not exist, the Stateflow editor opens an empty chart with the
name chart. Otherwise, the editor opens the chart defined by the sfx file.
After you save a standalone chart, the help function displays information about executing
it in MATLAB:
help chart.sfx
34-2
Create Stateflow Charts for Execution as MATLAB Objects
chartObject = chart('data1',value1,'data2',value2)
To display chart information, such as the syntax for execution, the values of the chart
data, and the list of active states, use the disp function:
disp(chartObject)
step(chartObject,'data1',value1,'data2',value2)
event_name(chartObject,'data1',value1,'data2',value2)
If your chart has graphical or MATLAB functions, you can call them directly in the
MATLAB Command Window. Calling a chart function does not execute the standalone
chart.
function_name(chartObject,u1,u2)
You can execute a standalone chart without opening the Stateflow Editor. If the chart is
open, then the Stateflow Editor highlights active states and transitions through chart
animation.
For the purposes of debugging and unit testing, you can execute a standalone chart
directly from the Stateflow editor. During execution, you enter data values and broadcast
events from the user interface. For more information, see “Execute and Unit Test
Stateflow Chart Objects” on page 34-9.
You can execute a standalone chart from a MATLAB script, a Simulink model, or an App
Designer user interface. For more information, see:
34-3
34 Standalone Stateflow Charts for Execution in MATLAB
• “Execute Stateflow Chart Objects Through Scripts and Models” on page 34-21
• “Design Human-Machine Interface Logic by Using Stateflow Charts” on page 34-28
If your collaborators have Stateflow, they can open, edit, and execute your standalone
charts. During execution, chart animation and debugging is supported. Run-time error
messages contain hyperlinks to the state or transition in the chart where the error occurs.
If your collaborators do not have Stateflow, they can execute your standalone charts as
MATLAB objects without opening the Stateflow editor. Chart animation and debugging is
not supported. Run-time error messages do not contain hyperlinks to the chart.
• Private properties that contain the internal state variables for the standalone chart.
• A step function that calls the various operations implementing the chart semantics.
A chart object can have other properties and functions that correspond to the various
elements present in the chart.
When you create a chart object, you can specify chart behavior by including these
configuration options as name-value pairs.
34-4
Create Stateflow Charts for Execution as MATLAB Objects
In the Stateflow Editor, you can use the Symbols window to specify initial values for chart
data. When you create a chart object, chart data is initialized in alphabetical order
according to its scope. Constant data is initialized first. Local data is initialized last.
If you use an expression to specify an initial value, then the chart attempts to resolve the
expression by:
For example, suppose that you specify an initial value for the local data x by using the
expression y. Then:
• If the chart has a constant called y, y is initialized before x. The local data x is
assigned the same initial value as y.
34-5
34 Standalone Stateflow Charts for Execution in MATLAB
• If the chart has a local data called y, x is initialized before y. The local data x is
assigned to an empty array. If the configuration option -
warningOnUninitializedData is set to true, a warning occurs.
• If the chart has no data named y, x is initialized by calling the function y. If the file
y.m is not on the search path, this error occurs:
Stateflow does not search the MATLAB workspace to resolve initial values, so this error
occurs even if there is a variable called y in the MATLAB workspace.
• Classic chart semantics with MATLAB as the action language. You can use the full
functionality of MATLAB, including those functions that are restricted for code
generation in Simulink. See “Execute Stateflow Chart Objects Through Scripts and
Models” on page 34-21.
Note In standalone Stateflow charts, the operating system command symbol ! is not
supported. To execute operating system commands, use the function system.
• Exclusive (OR) and Parallel (AND) state decomposition with hierarchy. See “State
Decomposition” on page 2-16 and “State Hierarchy” on page 2-14.
• Flow charts, graphical functions, and MATLAB functions. See “Reusable Components
in Charts”.
• Chart local and constant data without restriction to type. See “Execute and Unit Test
Stateflow Chart Objects” on page 34-9.
• Input events. See “Design Human-Machine Interface Logic by Using Stateflow Charts”
on page 34-28.
• Temporal logic operators:
34-6
Create Stateflow Charts for Execution as MATLAB Objects
For more information, see “Design Human-Machine Interface Logic by Using Stateflow
Charts” on page 34-28.
Note In standalone Stateflow charts, absolute time temporal logic is not supported in
transitions with conditions.
• Function getActiveStates to access the states that are active during execution of
the chart. To store the active states as a cell array, enter:
states = getActiveStates(chartObject)
• Function matlab.internal.getcode.sfxfile that generates the code
implementing the standalone chart as a MATLAB object. To store the code as a
character string code, enter:
code = matlab.internal.getcode.sfxfile('chart.sfx')
code = matlab.internal.getcode.sfxfile('chart.sfx',true)
Other limitations:
34-7
34 Standalone Stateflow Charts for Execution in MATLAB
See Also
disp | edit | help
More About
• “Execute and Unit Test Stateflow Chart Objects” on page 34-9
• “Execute Stateflow Chart Objects Through Scripts and Models” on page 34-21
• “Design Human-Machine Interface Logic by Using Stateflow Charts” on page 34-28
• “Implement a Financial Strategy by Using Stateflow” on page 34-38
• “Model a Communications Protocol by Using Chart Objects” on page 34-34
34-8
Execute and Unit Test Stateflow Chart Objects
This example shows how to execute this chart from the Stateflow editor and in the
MATLAB Command Window.
edit sf_chart.sfx
2
In the Symbols window, enter a value of u = 1 and click the Run icon . The editor
creates a Stateflow chart object my_sf_chart and executes the default transition.
The chart:
34-9
34 Standalone Stateflow Charts for Execution in MATLAB
The chart animation highlights the active state A. The Symbols window displays the
values u = 1, x = 1, and y = 1. The chart maintains its current state and local data
until the next execution command.
3
Click the Run icon again. Because the value of u does not satisfy the condition
[u<0] to transition out of state A, this state remains active and the values of x and y
increase to 2. The Symbols window now displays the values u = 1, x = 2, and y = 2.
4
In the Symbols window, enter a value of u = −1 and click the Run icon . The
negative data value triggers the transition to state B. The Symbols window displays
the values u = −1, x = 1, and y = 3.
5 You can modify the value of any chart data in the Symbols window. For example,
enter a value of x = 3. The chart will use this data value in the next time execution
step.
34-10
Execute and Unit Test Stateflow Chart Objects
6
Enter a value of u = 2 and click the Run icon . The chart transitions back to state
A. The Symbols window displays the values u = 2, x = 4, and y = 5.
7 To stop the chart animation and remove the Stateflow chart object my_sf_chart
from the MATLAB workspace, click the Stop icon .
To interrupt the execution and step through each action in the chart, add breakpoints
before you execute the chart. For more information, see “Debug a Standalone Stateflow
Chart” on page 34-16.
1 Open the chart in the Stateflow editor. In the MATLAB Command Window, enter:
edit sf_chart.sfx
2 Create the Stateflow chart object by using the name of the sfx file for the standalone
chart as a function. Specify the initial value for the data u as a name-value pair.
s = sf_chart('u',1)
Stateflow Chart
Execution Function
y = step(s)
Local Data
u : 1
x : 1
y : 1
Active States: {'A'}
34-11
34 Standalone Stateflow Charts for Execution in MATLAB
This command creates the chart object s, executes the default transition, and
initializes the values of x and y. The Stateflow editor animates the chart and
highlights the active state A.
3 To execute the chart, call the step function. For example, suppose that you call the
step function with a value of u = 1:
step(s,'u',1)
disp(s)
Stateflow Chart
Execution Function
y = step(s)
Local Data
u : 1
x : 2
y : 2
Active States: {'A'}
Because the value of u does not satisfy the condition [u<0] to transition out of state
A, this state remains active and the values of x and y increase to 2.
step(s,'u',-1)
disp(s)
34-12
Execute and Unit Test Stateflow Chart Objects
Stateflow Chart
Execution Function
y = step(s)
Local Data
u : -1
x : 1
y : 3
Active States: {'B'}
The negative data value triggers the transition to state B. The value of x decreases to
1 and the value of y increases to 3.
5 To access the value of any chart data, use dot notation. For example, you can assign a
value of 3 to the local data x by entering:
s.x = 3
Stateflow Chart
Execution Function
y = step(s)
Local Data
u : -1
x : 3
y : 3
Active States: {'B'}
The standalone chart will use this data value in the next time execution step.
6 Execute the chart with a value of u = 2:
step(s,'u',2)
disp(s)
Stateflow Chart
34-13
34 Standalone Stateflow Charts for Execution in MATLAB
Execution Function
y = step(s)
Local Data
u : 2
x : 4
y : 5
Active States: {'A'}
The chart transitions back to state A and modifies the values of x and y.
7 To stop the chart animation, delete the Stateflow chart object s from the MATLAB
workspace:
delete(s)
See Also
delete | disp | edit
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “Debug a Standalone Stateflow Chart” on page 34-16
• “Execute Stateflow Chart Objects Through Scripts and Models” on page 34-21
34-14
See Also
34-15
34 Standalone Stateflow Charts for Execution in MATLAB
You can execute a standalone chart in the MATLAB Command Window or through the
Stateflow editor. To enable debugging, set a breakpoint in the standalone chart or in a
MATLAB script that executes the chart. Breakpoints interrupt the execution of a chart.
While execution is stopped, you can step through each action in the chart, view data
values, and interact with the MATLAB workspace to examine the state of the chart.
Note When debugging a standalone chart that you execute from a MATLAB script, first
open the Stateflow editor. Attempting to debug a standalone chart before opening the
Stateflow editor at least once can produce unexpected results.
• To add a breakpoint on a chart, right-click inside the chart and select Set Breakpoint
on Chart Entry. This type of breakpoint interrupts the execution before the chart is
entered. To remove the breakpoint, right-click inside the chart and clear the Set
Breakpoint on Chart Entry option.
• To add a breakpoint on a state, right-click the state and select Set Breakpoint. This
type of breakpoint interrupts the execution before the chart performs the entry and
during actions for the state. To remove the breakpoint, right-click the state and select
Clear Breakpoint.
• To add a breakpoint on a transition, right-click the transition and select Set
Breakpoint. This type of breakpoint interrupts the execution when the transition
becomes valid. To remove the breakpoint, right-click the transition and select Clear
Breakpoint.
34-16
Debug a Standalone Stateflow Chart
Breakpoints appear as circular red badges. For example, this chart contains breakpoints
on the state A and on the transition from A to B.
To remove all of the breakpoints in a chart, right-click inside the chart and select Clear
All Breakpoints In Chart.
For example, when the execution stops at the breakpoint in state A, the border of the
state and the first statement in the state entry action appear highlighted in green.
An execution status badge appears in the graphical object where execution pauses.
Badge Description
Execution stopped before entering a chart or state.
34-17
34 Standalone Stateflow Charts for Execution in MATLAB
Badge Description
Execution stopped before taking a valid transition.
You can continue the execution from the Stateflow editor, at the debugging prompt, or by
selecting a keyboard shortcut.
34-18
Debug a Standalone Stateflow Chart
From a statement in a
function containing another
function call, advance to the
first executable statement in
the second function.
Otherwise, continue
execution to the next
breakpoint. (See the
Continue option.)
Stop dbquit Exit debug mode and Ctrl+Shift+T
interrupt the execution.
In state or transition actions containing more than one statement, you can step through
the individual statements one at a time by selecting Step Over. The Stateflow Editor
highlights each statement before executing it.
34-19
34 Standalone Stateflow Charts for Execution in MATLAB
To test the behavior of your chart, in the Symbols window, you can change the value of a
data object during execution. Alternatively, at the debugging prompt, enter the new value
by using the name this in place of the chart object name. For instance, to change the
value of the local data x, enter:
this.x = 7
See Also
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “Execute and Unit Test Stateflow Chart Objects” on page 34-9
• “Debugging Charts” on page 32-2
34-20
Execute Stateflow Chart Objects Through Scripts and Models
This example shows how to execute a standalone Stateflow chart by using a MATLAB
script or a Simulink model.
34-21
34 Standalone Stateflow Charts for Execution in MATLAB
The chart begins with a potential change configuration consisting entirely of the lowest-
value coins, specified by an index of 1. At each execution step, the state exchange
modifies this configuration in one of two ways:
• The substate move_up exchanges some lowest-value coins for a coin with a higher
value, specified by the index i.
• The substate move_down exchanges all of the coins with the value specified by the
index i for lowest-value coins. Then move_up exchanges some lowest-value coins for a
coin with a value specified by the index i+1 or higher.
A potential change configuration is valid when the number of cents represented by the
lowest-value coins is divisible by the value of that type of coin. When the chart encounters
a new valid configuration, it increments tally and appends the new configuration to
tabula.
34-22
Execute Stateflow Chart Objects Through Scripts and Models
When no more coin exchanges are possible, the state stop becomes active. This state
prints the results of the computation, transforms the contents of tabula to a table, and
sets the value of done to true.
chartObj = sf_change('x',27,'--warningOnUninitializedData',false);
while ~chartObj.done
step(chartObj);
end
disp(chartObj.tabula)
When you run this script, the standalone chart calculates the number of ways to make
change for 27 cents by using standard American coins:
sf_change_script
.............
There are 13 ways to make change for 27 cents.
Pennies Nickels Dimes Quarters
_______ _______ _____ ________
27 0 0 0
22 1 0 0
17 2 0 0
12 3 0 0
7 4 0 0
2 5 0 0
17 0 1 0
12 1 1 0
7 2 1 0
2 3 1 0
7 0 2 0
34-23
34 Standalone Stateflow Charts for Execution in MATLAB
2 1 2 0
2 0 0 1
To determine the number of ways to make change for a different amount, or to use a
different system of currency, change the values of x and coinValues. For example, to
use British currency, initialize coinValues to [1 2 5 10 20 25 50].
• Initialize creates a local chart object chartObj that implements the change-
counting algorithm for the input value x.
• Execute calls the step function to execute the standalone chart and stores the result
as the output data tally.
34-24
Execute Stateflow Chart Objects Through Scripts and Models
• Finish displays the results of the algorithm in the Diagnostic Viewer window and sets
the value of the output data done to true.
When both charts reach their respective Finish state, the simulation of the model stops
and the Display blocks show the final values of the two tallies.
The chart MATLAB syntax uses MATLAB as the action language. To execute the
standalone Stateflow chart, this chart must follow these guidelines:
• The local variable chartObj that contains the handle to the chart object has type
Inherit: From definition in chart.
• Before creating the chart object, the Initialize state calls the coder.extrinsic
function to declare sf_change as an extrinsic function that is restricted for code
generation in Simulink. See “Call Extrinsic MATLAB Functions in Stateflow Charts” on
page 30-39.
• The Execute and Finish states access the local data for the standalone chart by
calling the get function.
When you simulate this chart with an input of x = 27, the Display block Olde English
shows a tally of 4. The Diagnostic Viewer window shows these results:
34-25
34 Standalone Stateflow Charts for Execution in MATLAB
3 2 0
3 0 1
The chart C syntax uses C as the action language. To execute the standalone Stateflow
chart, this chart must follow these guidelines:
• The local variable chartObj that contains the handle to the chart object has type ml.
• The Initialize state calls the ml function to create the chart object.
• The Execute and Finish states use the ml namespace operator to access the step,
get, and displ functions to execute the standalone chart, access its local data, and
display the results of the algorithm.
For more information, see “Access MATLAB Functions and Workspace Data in C Charts”
on page 12-32.
When you simulate this chart with an input of x = 27, the Display block Modern
American shows a tally of 13. The Diagnostic Viewer window shows these results:
34-26
See Also
7 2 1
4 4 1
1 6 1
5 1 2
2 3 2
3 0 3
0 2 3
See Also
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “Execute and Unit Test Stateflow Chart Objects” on page 34-9
• “Call Extrinsic MATLAB Functions in Stateflow Charts” on page 30-39
• “Access MATLAB Functions and Workspace Data in C Charts” on page 12-32
34-27
34 Standalone Stateflow Charts for Execution in MATLAB
You can execute a standalone Stateflow chart by invoking its input events and using
temporal operators. The event- and timer-driven execution workflow is suitable for
designing the logic underlying human-machine interfaces (HMIs) and graphical user
interfaces (UIs).
• When you use the MATLAB App Designer, callback functions from the interface
widgets invoke events in the chart.
• In the Stateflow chart, temporal operators and local data control the properties of the
user interface.
For more information on how to use MATLAB to create graphical user interfaces, see “App
Designer” (MATLAB).
34-28
Design Human-Machine Interface Logic by Using Stateflow Charts
The file sf_lamp_logic.sfx defines a standalone Stateflow chart that implements the
logic for the user interface. The chart has input events (ON, OFF, BLINKING, and SOLID)
and local data (delay and app). The actions in the chart control which widgets are
accessible from each state. For instance, the actions in the Off state cause the Lamp
widget, the Mode option buttons, and the Blink Rate slider in the user interface to appear
dimmed.
34-29
34 Standalone Stateflow Charts for Execution in MATLAB
In the On state, the substates Solid and Blinking denote the two modes of operation.
To implement a blinking lamp, the chart relies on the temporal logic operator after.
When the chart enters the state Blinking.Off, the expression after(delay,sec) on
the outgoing transition creates a MATLAB timer object that executes the chart after a
number of seconds. The chart then transitions to the state Blinking.On and creates
another timer object to trigger the transition back to Blinking.Off. While the chart
continually transitions between the two states, you can adjust the rate of blinking by
changing the value of the local data delay or transition out of blinking mode by invoking
the input events SOLID or OFF.
34-30
Design Human-Machine Interface Logic by Using Stateflow Charts
The history junction in the On state preserves information on the most recently active
substate so that the user interface returns to the previous mode of operation when you
turn on the lamp.
34-31
34 Standalone Stateflow Charts for Execution in MATLAB
1 In the App Designer window, create a private property lampLogic to store the
handle to the Stateflow chart object.
properties (Access = private)
lampLogic
end
2 Create a StartupFcn callback function that creates the chart object and sets its
local data app to the user interface handle. Assign the chart object handle to the
lampLogic private property.
% Code that executes after component creation
function StartupFcn(app)
app.lampLogic = sf_lamp_logic('delay',0.5,'app',app);
end
3 Create a CloseRequestFcn callback function that deletes the chart object when you
close the user interface.
% Close request function: UIFigure
function UIFigureCloseRequest(app, event)
delete(app.lampLogic);
delete(app);
end
4 For each one of the user interface widgets, add a callback function that invokes the
appropriate event on the standalone chart.
34-32
See Also
BLINKING(app.lampLogic);
end
end
function BlinkRateSliderValueChanged(app,event)
app.lampLogic.delay = 0.5/app.BlinkRateSlider.Value;
end
When you run the user interface, you can observe the effects of adjusting the control
widgets on the chart canvas and on the lamp widget.
See Also
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “History Junctions” on page 2-44
• “Activate a Stateflow Chart by Sending Input Events” on page 10-9
• “Control Chart Execution by Using Temporal Logic” on page 12-49
• “App Designer” (MATLAB)
34-33
34 Standalone Stateflow Charts for Execution in MATLAB
• A 770-ms pulse (77 consecutive ones) to mark the beginning and end of a frame of
data and to ensure system synchronization.
34-34
Model a Communications Protocol by Using Chart Objects
To track the length of a pulse through several execution steps, the chart uses the count
operator. This operator simplifies the design of the chart by eliminating the need for a
manual counter. For example, the condition [count(pulse)==17] guards the outgoing
transition from the substate NewFrame. This condition becomes true when the data
pulse is one for 17 consecutive execution steps. In this case, the chart transitions to the
CouldBeA substate. If this transition is followed by an input of zero, then the chart
registers the reception of symbol A and transitions back to the NewFrame substate.
34-35
34 Standalone Stateflow Charts for Execution in MATLAB
Otherwise, the chart transitions to the SearchForB state from which the condition
[count(pulse)==29] searches for an additional 29 ones to mark symbol B.
function sendPulse(f,n)
% Send a pulse of n ones and one zero to chart object f.
for i = 1:n
step(f,'pulse',1)
printDot(1)
end
printDot(0)
step(f,'pulse',0)
function printDot(x)
persistent k
if isempty(k)
k = 1;
end
if x == 0
fprintf('\n');
k = 1;
elseif k == 50
fprintf('.\n');
k = 1;
else
34-36
See Also
fprintf('.');
k = k+1;
end
end
end
Running the script produces these results in the MATLAB Command Window:
sf_frame_Tester
..................................................
...........................
frame
.................
A
...............................................
B
.....................................
error
...............................................
B
.................
A..................................................
...........................
frame
See Also
count
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “Execute and Unit Test Stateflow Chart Objects” on page 34-9
• “Execute Stateflow Chart Objects Through Scripts and Models” on page 34-21
• “State Decomposition” on page 2-16
• “Control Chart Execution by Using Temporal Logic” on page 12-49
34-37
34 Standalone Stateflow Charts for Execution in MATLAB
• "Buy" when the value of the stock drops K standard deviations below the moving
average.
• "Sell" when the value of the stock rises K standard deviations above the moving
average.
• "Hold" when the value of the stock is within K standard deviations of the moving
average.
The file sf_stock_watch.sfx defines a standalone Stateflow chart that implements this
financial strategy. The chart consists of two outer states in parallel decomposition.
• The StockTicker subchart records the current price of a stock. The subchart hides
the details for calculating stock prices. To access real-time market data from financial
data providers, one possible implementation involves the use of the Datafeed
Toolbox™. For details, see “Datafeed Toolbox”.
• The FinancialAdvisor state uses the last N stock prices to compute high and low
bands. Depending on the current price relative to these bands, the state generates
"buy," "sell," or "hold" instructions. The action on every(1,sec) creates a
MATLAB® timer to execute the chart every second. See “Control Chart Execution by
Using Temporal Logic” on page 12-49.
34-38
Implement a Financial Strategy by Using Stateflow
34-39
34 Standalone Stateflow Charts for Execution in MATLAB
34-40
See Also
w = sf_stock_watch('-warningOnUninitializedData',false);
The chart continues to run until you delete the chart object w from the MATLAB
workspace:
delete(w);
See Also
More About
• “Create Stateflow Charts for Execution as MATLAB Objects” on page 34-2
• “Execute and Unit Test Stateflow Chart Objects” on page 34-9
• “State Decomposition” on page 2-16
• “Control Chart Execution by Using Temporal Logic” on page 12-49
• “Datafeed Toolbox”
34-41
34 Standalone Stateflow Charts for Execution in MATLAB
Data Acquisition Toolbox provides functionality for acquiring measurement data from a
DAQ device or audio soundcard. For certain applications, an analog-triggered acquisition
that starts capturing or logging data based on a condition in the analog signal being
measured is recommended. Software-analog triggered acquisition enables you to capture
only a segment of interest out of a continuous stream of measurement data. For example,
you can capture an audio recording when the signal level passes a certain threshold.
This example app, created by using App Designer and Stateflow, shows how to implement
these operations:
34-42
Analog Trigger App by Using Stateflow Charts
By default, the app opens in design mode in App Designer. To run the app click the Run
button or execute the app from the command line:
AnalogTriggerAppStateflow
Requirements
34-43
34 Standalone Stateflow Charts for Execution in MATLAB
When creating an app that has complex logic, consider the various states that correspond
to the operating modes of the app. You can use a Stateflow chart to visualize and organize
these app states. Use transitions between states to implement the control logic of your
app. For example, the file AnalogTriggerAppChart.sfx defines the Stateflow chart
that controls the logic for this app. The chart can transition between states based on an
action in the app UI or on a data-driven condition. For example, if you click the Start
button, the chart transitions from the Configuration state to the Acquisition state.
If the value of the signal crosses the specified trigger level, the chart transitions from the
LookingForTrigger state to the CapturingData state.
34-44
Analog Trigger App by Using Stateflow Charts
34-45
34 Standalone Stateflow Charts for Execution in MATLAB
To establish a bidirectional connection between the MATLAB app and the Stateflow chart,
in the startupFcn function of your app, create a chart object and store its handle in an
app property.
app.Chart = AnalogTriggerAppChart('app',app);
The app uses this handle to trigger state transitions in the chart. For example, when you
click Start, the StartButtonPushed app callback function calls the
acquisitionStart input event for the chart. This event triggers the transition from the
Configuration state to the Acquisition state.
To evaluate transition conditions that are not events in the chart, the app calls the step
function for the chart object. For example, while acquiring data from the device, the
dataAvailable_Callback app function periodically calls the step function. When the
trigger condition is detected, the chart transitions from the LookingForTrigger State
to the CapturingData state.
In the Stateflow chart, store the app object handle as chart local data. To share public
properties and call public functions of the app, the Stateflow chart can use this handle in
state actions, transition conditions, or transition actions.
See Also
Chart
More About
• “Design Human-Machine Interface Logic by Using Stateflow Charts” on page 34-28
34-46
A
Enter a Chart
The set of default flow paths execute (see “Execute a Set of Flow Charts” on page A-4).
If this action does not cause a state entry and the chart has parallel decomposition, then
each parallel state becomes active (see “Enter a State” on page A-2).
If executing the default flow paths does not cause state entry, a state inconsistency error
occurs.
Enter a State
1 If the parent of the state is not active, perform steps 1 through 4 for the parent.
2 If this state is a parallel state, check that all siblings with a higher (that is, earlier)
entry order are active. If not, perform steps 1 through 5 for these states first.
Parallel (AND) states are ordered for entry based on whether you use explicit
ordering (default) or implicit ordering. For details, see “Explicit Ordering of Parallel
States” on page 3-86 and “Implicit Ordering of Parallel States” on page 3-88.
A-2
Summary of Chart Semantic Rules
a If the state contains a history junction and there was an active child of this state
at some point after the most recent chart initialization, perform the entry actions
for that child. Otherwise, execute the default flow paths for the state.
b If this state has children that are parallel states (parallel decomposition),
perform entry steps 1 through 5 for each state according to its entry order.
c If this state has only one child substate, the substate becomes active when the
parent becomes active, regardless of whether a default transition is present.
Entering the parent state automatically makes the substate active. The presence
of any inner transition has no effect on determining the active substate.
6 If this state is a parallel state, perform all entry steps for the sibling state next in
entry order if one exists.
7 If the transition path parent is not the same as the parent of the current state,
perform entry steps 6 and 7 for the immediate parent of this state.
A-3
A Summary of Chart Semantic Rules
States
Step 1 is repeated with the set of outgoing segments from the junction.
3 After testing all outgoing transition segments at a junction, backtrack the incoming
transition segment that brought you to the junction and continue at step 2, starting
with the next transition segment after the backtrack segment. The set of flow charts
finishes execution when testing of all starting transitions is complete.
A-4
Summary of Chart Semantic Rules
1 If the receiver of the event is active, then it executes (see “Execute an Active Chart”
on page A-2 and “Execute an Active State” on page A-3). (The event receiver is the
parent of the event unless a direct event broadcast occurs using the send()
function.)
A-5
B
Semantic Examples
B Categories of Semantic Examples
B-2
Categories of Semantic Examples
B-3
B Transition Between Exclusive States
1 When an event occurs, state S1 checks for an outgoing transition with a matching
event specified.
2 If a transition with a matching event is found, the condition for that transition
([condition]) is evaluated.
3 If the condition is true, condition_action is executed.
4 If there is a valid transition to the destination state, the transition is taken.
5 State S1 is exited.
6 The transition_action is executed when the transition is taken.
7 State S2 is entered.
B-4
Transition Between Exclusive States
Initially, the chart is asleep. State On and state Off are OR states. State On is active.
Event E_one occurs and awakens the chart, which processes the event from the root
down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition from state On to state Off is detected.
2 State On exit actions (exitOn()) execute and complete.
3 State On is marked inactive.
4 The event E_one is broadcast as the transition action.
This second event E_one is processed, but because neither state is active, it has no
effect. If the second broadcast of E_one resulted in a valid transition, it would
preempt the processing of the first broadcast of E_one. See “Early Return Logic for
Event Broadcasts” on page 3-93.
5 State Off is marked active.
6 State Off entry actions (entOff()) execute and complete.
7 The chart goes back to sleep.
This sequence completes the execution of the Stateflow chart associated with event
E_one when state On is initially active.
B-5
B Transition Between Exclusive States
Using the same example, what happens when the next event, E_one, occurs while state
Off is active?
Initially, the chart is asleep. State Off is active. Event E_one occurs and awakens the
chart, which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
This sequence completes the execution of the Stateflow chart associated with the second
event E_one when state Off is initially active.
Using the same example, what happens when a third event, E_two, occurs?
B-6
Transition Between Exclusive States
Notice that the event E_two is not used explicitly in this example. However, its
occurrence (or the occurrence of any event) does result in behavior. Initially, the chart is
asleep and state On is active.
Event E_two is processed from the root of the chart down through the hierarchy of
the chart.
2 The chart root checks to see if there is a valid transition as a result of E_two. There
is none.
3 State On during actions (durOn()) execute and complete.
4 The chart goes back to sleep.
This sequence completes the execution of the Stateflow chart associated with event
E_two when state On is initially active.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
B-7
B Transition Between Exclusive States
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
Initially, the chart is asleep. State A.A1 is active. Condition C_one is true. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. There
is a valid transition from state A.A1 to state B.B1. (Condition C_one is true.)
2 State A during actions (durA()) execute and complete.
3 State A.A1 exit actions (exitA1()) execute and complete.
4 State A.A1 is marked inactive.
5 State A exit actions (exitA()) execute and complete.
6 State A is marked inactive.
7 The transition action, A, is executed and completed.
8 State B is marked active.
9 State B entry actions (entB()) execute and complete.
10 State B.B1 is marked active.
11 State B.B1 entry actions (entB1()) execute and complete.
12 The chart goes back to sleep.
B-8
Transition Between Exclusive States
This sequence completes the execution of this Stateflow chart associated with event
E_one.
B-9
B Control Chart Execution by Using Condition Actions
Initially, the chart is asleep. State A is active. Conditions C_one and C_two are false.
Event E_one occurs and awakens the chart, which processes the event from the root
down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition segment from state A to a connective junction is detected. The condition
action A_one is detected on the valid transition segment and is immediately executed
and completed. State A is still active.
2 Because the conditions on the transition segments to possible destinations are false,
none of the complete transitions is valid.
3 State A during actions (durA()) execute and complete.
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A is initially active.
B-10
Control Chart Execution by Using Condition Actions
Initially, the chart is asleep. State A is active. Condition C_one is true. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition from state A to state B is detected. The condition C_one is true. The
condition action A_one is detected on the valid transition and is immediately
executed and completed. State A is still active.
2 State A exit actions (ExitA()) execute and complete.
3 State A is marked inactive.
4 The transition action A_two is executed and completed.
5 State B is marked active.
6 State B entry actions (entB()) execute and complete.
7 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A is initially active.
B-11
B Control Chart Execution by Using Condition Actions
See “For-Loop Construct” on page B-31 to see the behavior of this example.
B-12
Control Chart Execution by Using Condition Actions
See “Broadcast Events in Condition Actions” on page B-46 to see the behavior of this
example.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
B-13
B Control Chart Execution by Using Condition Actions
Initially, the chart is asleep. State On is active. Event E_one occurs and awakens the
chart, which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
Steps 1 through 5 continue to execute in a cyclical manner. The transition label indicating
a trigger on the same event as the condition action broadcast event results in
unrecoverable cyclic behavior. This sequence never completes when event E_one is
broadcast and state On is active.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
B-14
See Also
See Also
More About
• “Transition Action Types” on page 12-7
• “Broadcast Local Events to Synchronize Parallel States” on page 12-45
• “Supported Operations for Chart Data” on page 12-14
B-15
B Control Chart Execution by Using Default Transitions
Initially, the chart is asleep. State A is active. Event E_one occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart 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 The transition action, A, is executed and completed.
5 State B is marked active.
6 State B entry actions (entB()) execute and complete.
7 State B detects a valid default transition to state B.B1.
8 State B.B1 is marked active.
9 State B.B1 entry actions (entB1()) execute and complete.
10 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A is initially active.
B-16
Control Chart Execution by Using Default Transitions
For this example, initially, the chart is asleep. State B.B1 is active. Condition [C_two] is
true. An event occurs and awakens the chart, which processes the event from the root
down through the hierarchy:
1 State B checks to see if there is a valid transition as a result of any event. There is
none.
2 State B during actions (durB()) execute and complete.
3 State B1 checks to see if there is a valid transition as a result of any event. There is
none.
4 State B1 during actions (durB1()) execute and complete.
This sequence completes the execution of this Stateflow chart associated with the
occurrence of any event.
B-17
B Control Chart Execution by Using Default Transitions
Initially, the chart is asleep. State A is active. A history junction records the fact that state
B4 is the previously active substate of superstate B. Event E_one occurs and awakens the
chart, which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
The history junction indicates that substate B.B4 was the last active substate, which
becomes the destination of the transition.
B-18
Control Chart Execution by Using Default Transitions
This sequence completes the execution of this Stateflow chart associated with event
E_one.
Initially, the chart is asleep. State A is active. Event E_one occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
B-19
B Control Chart Execution by Using Default Transitions
There is a valid transition from state A to superstate B. The transition is valid if event
E_one or E_two occurs.
2 State A exit actions execute and complete (exitA()).
3 State A is marked inactive.
4 State B is marked active.
5 State B entry actions execute and complete (entB()).
6 State B detects a valid default transition to state B.B1. The default transition is valid
as a result of E_one.
7 State B.B1 is marked active.
8 State B.B1 entry actions execute and complete (entB1()).
9 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A is initially active.
B-20
Process Events in States Containing Inner Transitions
This example shows the behavior of an inner transition. The chart uses implicit ordering
of outgoing transitions (see “Implicit Ordering” on page 3-65).
Initially, the chart is asleep. State A is active. Condition [C_one] is false. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A
potentially valid transition from state A to state B is detected. However, the transition
is not valid, because [C_one] is false.
2 State A during actions (durA()) execute and complete.
3 State A checks its children for a valid transition and detects a valid inner transition.
4 State A remains active. The inner transition action A_two is executed and completed.
Because it is an inner transition, state A's exit and entry actions are not executed.
5 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one.
B-21
B Process Events in States Containing Inner Transitions
Using the previous example, this example shows what happens when a second event
E_one occurs. The chart uses implicit ordering of outgoing transitions (see “Implicit
Ordering” on page 3-65).
Initially, the chart is asleep. State A is still active. Condition [C_one] is true. Event
E_one occurs and awakens the chart, which processes the event from the root down
through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
The transition from state A to state B is now valid because [C_one] is true.
2 State A exit actions (exitA()) execute and complete.
3 State A is marked inactive.
4 The transition action A_one is executed and completed.
5 State B is marked active.
6 State B entry actions (entB()) execute and complete.
7 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one.
Using the previous example, this example shows what happens when a third event,
E_two, occurs. The chart uses implicit ordering of outgoing transitions (see “Implicit
Ordering” on page 3-65).
B-22
Process Events in States Containing Inner Transitions
Initially, the chart is asleep. State B is now active. Condition [C_two] is false. Event
E_two occurs and awakens the chart, which processes the event from the root down
through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_two.
A potentially valid transition from state B to state A is detected. The transition is not
valid because [C_two] is false. However, active state B has a valid self-loop
transition.
2 State B exit actions (exitB()) execute and complete.
3 State B is marked inactive.
4 The self-loop transition action, A_four, executes and completes.
5 State B is marked active.
6 State B entry actions (entB()) execute and complete.
7 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_two. This example shows the difference in behavior between inner and self-loop
transitions.
B-23
B Process Events in States Containing Inner Transitions
This example shows the behavior of an inner transition to a connective junction for the
first event. The chart uses implicit ordering of outgoing transitions (see “Implicit
Ordering” on page 3-65).
Initially, the chart is asleep. State A1 is active. Condition [C_two] is true. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition at the root level as a result of
E_one. There is no valid transition.
2 State A during actions (durA()) execute and complete.
3 State A checks itself for valid transitions and detects that there is a valid inner
transition to a connective junction.
The conditions are evaluated to determine whether one of the transitions is valid.
Because implicit ordering applies, the segments labeled with a condition are
evaluated before the unlabeled segment. The evaluation starts from a 12 o'clock
position on the junction and progresses in a clockwise manner. Because [C_two] is
true, the inner transition to the junction and then to state A.A2 is valid.
4 State A.A1 exit actions (exitA1()) execute and complete.
5 State A.A1 is marked inactive.
B-24
Process Events in States Containing Inner Transitions
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A1 is active and condition [C_two] is true.
Continuing the previous example, this example shows the behavior of an inner transition
to a junction when a second event E_one occurs. The chart uses implicit ordering of
outgoing transitions (see “Implicit Ordering” on page 3-65).
Initially, the chart is asleep. State A2 is active. Condition [C_two] is true. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition at the root level as a result of
E_one. There is no valid transition.
2 State A during actions (durA()) execute and complete.
3 State A checks itself for valid transitions and detects a valid inner transition to a
connective junction.
The conditions are evaluated to determine whether one of the transitions is valid.
Because implicit ordering applies, the segments labeled with a condition are
B-25
B Process Events in States Containing Inner Transitions
evaluated before the unlabeled segment. The evaluation starts from a 12 o'clock
position on the junction and progresses in a clockwise manner. Because [C_two] is
true, the inner transition to the junction and then to state A.A2 is valid.
4 State A.A2 exit actions (exitA2()) execute and complete.
5 State A.A2 is marked inactive.
6 State A.A2 is marked active.
7 State A.A2 entry actions (entA2()) execute and complete.
8 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one when state A2 is active and condition [C_two] is true. For a state with a valid
inner transition, an active substate can be exited and reentered immediately.
Initially, the chart is asleep. State A.A1 is active. History information exists because
superstate A is active. Event E_one occurs and awakens the chart, which processes the
event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. There
is no valid transition.
2 State A during actions execute and complete.
B-26
Process Events in States Containing Inner Transitions
3 State A checks itself for valid transitions and detects that there is a valid inner
transition to a history junction. Based on the history information, the last active state,
A.A1, is the destination state.
4 State A.A1 exit actions execute and complete.
5 State A.A1 is marked inactive.
6 State A.A1 is marked active.
7 State A.A1 entry actions execute and complete.
8 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one when there is an inner transition to a history junction and state A.A1 is active. For
a state with a valid inner transition, an active substate can be exited and reentered
immediately.
B-27
B Represent Multiple Paths by Using Connective Junctions
1 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. Since
condition_2 is true, a valid state-to-state transition from S1 to S2 exists.
5 State S1 exit actions execute and complete.
6 State S1 is marked inactive.
7 The transition action transition_action executes and completes.
8 The completed state-to-state transition from S1 to S2 occurs.
B-28
Represent Multiple Paths by Using Connective Junctions
Initially, the chart is asleep. State A is active. Condition [C_two] is true. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one.
A valid transition segment from state A to the connective junction exists. Because
implicit ordering applies, the transition segments beginning from a 12 o'clock
position on the connective junction are evaluated for validity. The first transition
segment, labeled with condition [C_one], is not valid. The next transition segment,
labeled with the condition [C_two], is valid. The complete transition from state A to
state C is valid.
2 State A exit actions (exitA()) execute and complete.
3 State A is marked inactive.
4 State C is marked active.
5 State C entry actions (entC()) execute and complete.
B-29
B Represent Multiple Paths by Using Connective Junctions
This sequence completes the execution of this Stateflow chart associated with event
E_one.
Self-Loop Transition
This example shows the behavior of a self-loop transition using a connective junction. The
chart uses implicit ordering of outgoing transitions (see “Implicit Ordering” on page 3-
65).
Initially, the chart is asleep. State A is active. Condition [C_one] is false. Event E_one
occurs and awakens the chart, which processes the event from the root down through the
hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition segment from state A to the connective junction exists. Because implicit
ordering applies, the transition segment labeled with a condition is evaluated for
validity. Because the condition [C_one] is not valid, the complete transition from state
A to state B is not valid. The transition segment from the connective junction back to
state A is valid.
2 State A exit actions (exitA()) execute and complete.
3 State A is marked inactive.
B-30
Represent Multiple Paths by Using Connective Junctions
This sequence completes the execution of this Stateflow chart associated with event
E_one.
For-Loop Construct
This example shows the behavior of a for loop using a connective junction. The chart
uses implicit ordering of outgoing transitions (see “Implicit Ordering” on page 3-65).
Initially, the chart is asleep. State A is active. Event E_one occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. There
is a valid transition segment from state A to the connective junction. The transition
segment condition action, i = 0, executes and completes. Of the two transition
B-31
B Represent Multiple Paths by Using Connective Junctions
segments leaving the connective junction, the transition segment that is a self-loop
back to the connective junction evaluates next for validity. That segment takes
priority in evaluation because it has a condition, whereas the other segment is
unlabeled. This evaluation behavior reflects implicit ordering of outgoing transitions
in the chart.
2 The condition [i < 10] evaluates as true. The condition actions i++ and a call to
func1 execute and complete until the condition becomes false. Because a connective
junction is not a final destination, the transition destination is still unknown.
3 The unconditional segment to state B is now valid. The complete transition from state
A to state B is valid.
4 State A exit actions (exitA()) execute and complete.
5 State A is marked inactive.
6 State B is marked active.
7 State B entry actions (entB()) execute and complete.
8 The chart goes back to sleep.
This sequence completes the execution of this chart associated with event E_one.
B-32
Represent Multiple Paths by Using Connective Junctions
Initially, the chart is asleep. State A.A1 is active. The condition [C_one()] is initially
true. Event E_one occurs and awakens the chart, which processes the event from the root
down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. There
is no valid transition.
2 State A checks itself for valid transitions and detects a valid inner transition to a
connective junction.
3 The next possible segments of the transition are evaluated. Only one outgoing
transition exists, and it has a condition action defined. The condition action executes
and completes.
4 The next possible segments are evaluated. Two outgoing transitions exist: a
conditional self-loop transition and an unconditional transition segment. Because
implicit ordering applies, the conditional transition segment takes precedence. Since
the condition [C_one()] is true, the self-loop transition is taken. Since a final
transition destination has not been reached, this self-loop continues until [C_one()]
is false.
This sequence completes the execution of this Stateflow chart associated with event
E_one.
B-33
B Represent Multiple Paths by Using Connective Junctions
Initially, the chart is asleep. State A is active. Event E_two occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_two. A valid
transition segment exists from state A to the connective junction. Because implicit
ordering applies, evaluation of segments with equivalent label priority begins from a
12 o'clock position on the connective junction and progresses clockwise. The first
transition segment, labeled with event E_one, is not valid. The next transition
segment, labeled with event E_two, is valid. The complete transition from state A to
state C is valid.
2 State A exit actions (exitA()) execute and complete.
3 State A is marked inactive.
4 State C is marked active.
5 State C entry actions (entC()) execute and complete.
6 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_two.
B-34
Represent Multiple Paths by Using Connective Junctions
Conflicting transitions are two equally valid paths from the same source in a Stateflow
chart during simulation. In the case of a conflict, the chart evaluates equally valid
transitions based on ordering mode in the chart: explicit or implicit.
• For explicit ordering (the default mode), evaluation of conflicting transitions occurs
based on the order you specify for each transition. For details, see “Explicit Ordering”
on page 3-65.
• For implicit ordering in C charts, evaluation of conflicting transitions occurs based on
internal rules described in “Implicit Ordering” on page 3-65.
For implicit ordering, the chart evaluates multiple outgoing transitions with equal label
priority in a clockwise progression starting from the twelve o'clock position on the state.
In this case, the transition from state A to state B occurs.
For explicit ordering, the chart resolves the conflict by evaluating outgoing transitions in
the order that you specify explicitly. For example, if you right-click the transition from
B-35
B Represent Multiple Paths by Using Connective Junctions
state A to state C and select Execution Order > 1 from the context menu, the chart
evaluates that transition first. In this case, the transition from state A to state C occurs.
The default transition to state A assigns data a equal to 1 and data b equal to 10. The
during action of state A increments a and decrements b during each time step. The
transition from state A to state B is valid if the condition [a > 4] is true. The transition
from state A to state C is valid if the condition [b < 7] is true. During simulation, there
is a time step where state A is active and both conditions are true. This issue is a
transition conflict.
Initially, the chart is asleep. State A is active. Event E_one occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition segment exists from state A to the connective junction and from the
junction to state C.
2 State A exit actions (exitA()) execute and complete.
3 State A is marked inactive.
4 State C is marked active.
5 State C entry actions (entC()) execute and complete.
B-36
Represent Multiple Paths by Using Connective Junctions
This sequence completes the execution of this Stateflow chart associated with event
E_one.
Initially, the chart is asleep. State B is active. Event E_one occurs and awakens the chart,
which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. A valid
transition segment exists from state B to the connective junction and from the
junction to state C.
2 State B exit actions (exitB()) execute and complete.
3 State B is marked inactive.
4 State C is marked active.
5 State C entry actions (entC()) execute and complete.
6 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one.
B-37
B Represent Multiple Paths by Using Connective Junctions
Initially, state A is active and conditions c1, c2, and c3 are true:
1 The chart root checks to see if there is a valid transition from state A.
There is a valid transition segment marked with the condition c1 from state A to a
connective junction.
2 Condition c1 is true and action a1 executes.
3 Condition c3 is true and action a3 executes.
4 Condition c4 is not true and control flow backtracks to state A.
5 The chart root checks to see if there is another valid transition from state A.
There is a valid transition segment marked with the condition c2 from state A to a
connective junction.
6 Condition c2 is true and action a2 executes.
7 Condition c3 is true and action a3 executes.
8 Condition c4 is not true and control flow backtracks to state A.
9 The chart goes to sleep.
The preceding example shows the unexpected behavior of executing both actions a1 and
a2. Another unexpected behavior is the execution of action a3 twice. To resolve this
problem, consider adding unconditional transitions to terminating junctions.
B-38
Represent Multiple Paths by Using Connective Junctions
The terminating junctions allow flow to end if either c3 or c4 is not true. This design
leaves state A active without executing unnecessary actions.
B-39
B Control Chart Execution by Using Event Actions in a Superstate
Initially, the chart is asleep. State A.A1 is active. Event E_three occurs and awakens the
chart, which processes the event from the root down through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_three. No
valid transition exists.
2 State A during actions (durA()) execute and complete.
3 State A executes and completes the on event E_three action (A_one).
4 State A checks its children for valid transitions. No valid transitions exist.
5 State A1 during actions (durA1()) execute and complete.
6 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_three.
B-40
Undirected Broadcast Events in Parallel States
Initially, the chart is asleep. Parallel substates A.A1.A1a and A.A2.A2a are active. Event
E_one occurs and awakens the chart, which processes the event from the root down
through the hierarchy:
B-41
B Undirected Broadcast Events in Parallel States
1 The chart root checks to see if there is a valid transition at the root level as a result of
E_one. No valid transition exists.
2 State A during actions (durA()) execute and complete.
3 The children of state A are parallel (AND) states. Because implicit ordering applies,
the states are evaluated and executed from left to right and top to bottom. State
A.A1 is evaluated first. State A.A1 during actions (durA1()) execute and complete.
State A.A1 executes and completes the on E_one action and broadcasts event
E_two. The during and on event_name actions are processed based on their order
of appearance in the state label:
a The broadcast of event E_two awakens the chart a second time. The chart root
checks to see if there is a valid transition as a result of E_two. No valid transition
exists.
b State A during actions (durA()) execute and complete.
c State A checks its children for valid transitions. No valid transitions exist.
d State A's children are evaluated starting with state A.A1. State A.A1 during
actions (durA1()) execute and complete. State A.A1 is evaluated for valid
transitions. There are no valid transitions as a result of E_two within state A1.
e State A1a's during actions (durA1a()) execute.
f State A.A2 is evaluated. State A.A2 during actions (durA2()) execute and
complete. State A.A2 checks for valid transitions. State A.A2 has a valid
transition as a result of E_two from state A.A2.A2a to state A.A2.A2b.
g State A.A2.A2a exit actions (exitA2a()) execute and complete.
h State A.A2.A2a is marked inactive.
i State A.A2.A2b is marked active.
j State A.A2.A2b entry actions (entA2b()) execute and complete.
4 The processing of E_one continues once the on event broadcast of E_two has been
processed. State A.A1 checks for any valid transitions as a result of event E_one. A
valid transition exists from state A.A1.A1a to state A.A1.A1b.
5 State A.A1.A1a executes and completes exit actions (exitA1a).
6 State A.A1.A1a is marked inactive.
7 State A.A1.A1b is marked active.
8 State A.A1.A1b entry actions (entA1b()) execute and complete.
9 Parallel state A.A2 is evaluated next. State A.A2 during actions (durA2()) execute
and complete. There are no valid transitions as a result of E_one.
B-42
Undirected Broadcast Events in Parallel States
State A.A2.A2b is now active as a result of the processing of the on event broadcast
of E_two.
11 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one and the on event broadcast to a parallel state of event E_two. The final chart
activity is that parallel substates A.A1.A1b and A.A2.A2b are active.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
B-43
B Undirected Broadcast Events in Parallel States
Initially, the chart is asleep. Parallel substates A.A1.A1a and A.A2.A2a are active. Event
E_one occurs and awakens the chart, which processes the event from the root down
through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. There
is no valid transition.
2 State A during actions (durA()) execute and complete.
3 State A's children are parallel (AND) states. Because implicit ordering applies, the
states are evaluated and executed from left to right and top to bottom. State A.A1 is
evaluated first. State A.A1during actions (durA1()) execute and complete.
B-44
Undirected Broadcast Events in Parallel States
4 State A.A1 checks for any valid transitions as a result of event E_one. There is a
valid transition from state A.A1.A1a to state A.A1.A1b.
5 State A.A1.A1a executes and completes exit actions (exitA1a).
6 State A.A1.A1a is marked inactive.
1 The transition action that broadcasts event E_two executes and completes:
a The broadcast of event E_two now preempts the transition from state A1a to
state A1b that event E_one triggers.
b The broadcast of event E_two awakens the chart a second time. The chart root
checks to see if there is a valid transition as a result of E_two. No valid transition
exists.
c State A during actions (durA()) execute and complete.
d State A's children are evaluated starting with state A.A1. State A.A1during
actions (durA1()) execute and complete. State A.A1 is evaluated for valid
transitions. There are no valid transitions as a result of E_two within state A1.
e State A.A2 is evaluated. State A.A2 during actions (durA2()) execute and
complete. State A.A2 checks for valid transitions. State A.A2 has a valid
transition as a result of E_two from state A.A2.A2a to state A.A2.A2b.
f State A.A2.A2a exit actions (exitA2a()) execute and complete.
g State A.A2.A2a is marked inactive.
h State A.A2.A2b is marked active.
i State A.A2.A2b entry actions (entA2b()) execute and complete.
State A.A2.A2b is now active as a result of the processing of event broadcast E_two.
5 The chart goes back to sleep.
B-45
B Undirected Broadcast Events in Parallel States
This sequence completes the execution of this Stateflow chart associated with event
E_one and the event broadcast on a transition action to a parallel state of event E_two.
The final chart activity is that parallel substates A.A1.A1b and A.A2.A2b are active.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
B-46
Undirected Broadcast Events in Parallel States
Initially, the chart is asleep. Parallel substates A.A1.A1a and A.A2.A2a are active. Event
E_one occurs and awakens the chart, which processes the event from the root down
through the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of E_one. No
valid transition exists.
2 State A during actions (durA()) execute and complete.
3 State A's children are parallel (AND) states. Because implicit ordering applies, the
states are evaluated and executed from top to bottom, and from left to right. State
A.A1 is evaluated first. State A.A1 during actions (durA1()) execute and complete.
4 State A.A1 checks for any valid transitions as a result of event E_one. A valid
transition from state A.A1.A1a to state A.A1.A1b exists. A valid condition action
B-47
B Undirected Broadcast Events in Parallel States
also exists. The condition action event broadcast of E_two executes and completes.
State A.A1.A1a is still active:
a The broadcast of event E_two awakens the Stateflow chart a second time. The
chart root checks to see if there is a valid transition as a result of E_two. There
is no valid transition.
b State A during actions (durA()) execute and complete.
c State A's children are evaluated starting with state A.A1. State A.A1 during
actions (durA1()) execute and complete. State A.A1 is evaluated for valid
transitions. There are no valid transitions as a result of E_two within state A1.
d State A1a during actions (durA1a()) execute.
e State A.A2 is evaluated. State A.A2 during actions (durA2()) execute and
complete. State A.A2 checks for valid transitions. State A.A2 has a valid
transition as a result of E_two from state A.A2.A2a to state A.A2.A2b.
f State A.A2.A2a exit actions (exitA2a()) execute and complete.
g State A.A2.A2a is marked inactive.
h State A.A2.A2b is marked active.
i State A.A2.A2b entry actions (entA2b()) execute and complete.
5 State A.A1.A1a executes and completes exit actions (exitA1a).
6 State A.A1.A1a is marked inactive.
7 State A.A1.A1b is marked active.
8 State A.A1.A1b entry actions (entA1b()) execute and complete.
9 Parallel state A.A2 is evaluated next. State A.A2 during actions (durA2()) execute
and complete. There are no valid transitions as a result of E_one.
10 State A.A2.A2b during actions (durA2b()) execute and complete.
State A.A2.A2b is now active as a result of the processing of the condition action
event broadcast of E_two.
11 The chart goes back to sleep.
This sequence completes the execution of this Stateflow chart associated with event
E_one and the event broadcast on a condition action to a parallel state of event E_two.
The final chart activity is that parallel substates A.A1.A1b and A.A2.A2b are active.
Tip Avoid using undirected local event broadcasts, which can cause unwanted recursive
behavior in your chart. Use the send operator for directed local event broadcasts. For
B-48
Undirected Broadcast Events in Parallel States
more information, see “Broadcast Local Events to Synchronize Parallel States” on page
12-45.
You can set the diagnostic level for detecting undirected local event broadcasts. In the
Model Configuration Parameters dialog box, go to the Diagnostics > Stateflow pane and
set the Undirected event broadcasts diagnostic to none, warning, or error. The
default setting is warning.
B-49
B Broadcast Local Events in Parallel States
Initially, the chart is asleep. Parallel substates A.A1 and B.B1 are active, which implies
that parallel (AND) superstates A and B are also active. The condition [data1==1] is
true. The event E_one belongs to the chart and is visible to both A and B.
After waking up, the chart checks for valid transitions at every level of the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of the event.
There is no valid transition.
2 State A checks for any valid transitions as a result of the event. Because the condition
[data1==1] is true, there is a valid transition from state A.A1 to state A.A2.
B-50
Broadcast Local Events in Parallel States
a The broadcast of event E_one reaches state B. Because state B is active, that
state receives the event broadcast and checks to see if there is a valid transition.
There is a valid transition from B.B1 to B.B2.
b State B.B1 exit actions (exitB1()) execute and complete.
c State B.B1 becomes inactive.
d State B.B2 becomes active.
e State B.B2 entry actions (entB2()) execute and complete.
4 State A.A1 exit actions (exitA1()) execute and complete.
5 State A.A1 becomes inactive.
6 State A.A2 becomes active.
7 State A.A2 entry actions (entA2()) execute and complete.
B-51
B Broadcast Local Events in Parallel States
The only differences from the chart in “Directed Event Broadcast Using Send” on page B-
50 are:
• The event E_one belongs to state B and is visible only to that state.
• The action send(E_one,B) is now send(B.E_one).
Using a qualified event name is necessary because E_one is not visible to state A.
After waking up, the chart checks for valid transitions at every level of the hierarchy:
1 The chart root checks to see if there is a valid transition as a result of the event.
There is no valid transition.
2 State A checks for any valid transitions as a result of the event. Because the condition
[data1==1] is true, there is a valid transition from state A.A1 to state A.A2.
3 The action send(B.E_one) executes and completes:
a The broadcast of event E_one reaches state B. Because state B is active, that
state receives the event broadcast and checks to see if there is a valid transition.
There is a valid transition from B.B1 to B.B2.
B-52
See Also
This sequence completes execution of a chart with a directed event broadcast using a
qualified event name to a parallel state.
See Also
send
More About
• “Broadcast Local Events to Synchronize Parallel States” on page 12-45
B-53
Glossary
API (application Format you can use to access and communicate with an
programming interface) application program from a programming or script
environment.
atomic subchart Graphical object that enables you to reuse states and
subcharts across multiple charts. For more information,
see “When to Use Atomic Subcharts” on page 15-6.
Glossary-1
Glossary
Glossary-2
Glossary
events Events drive chart execution. All events that affect the
chart must be defined. The occurrence of an event causes
the status of states in a chart to be evaluated. The
broadcast of an event can trigger a transition to occur or
an action to execute. Events are broadcast in a top-down
manner starting from the event's parent in the hierarchy.
flow chart Set of decision flow paths that start from a transition
segment that, in turn, starts from a state or a default
transition segment.
flow subgraph Set of decision flow paths that start on the same transition
segment.
Glossary-3
Glossary
inner transitions Transition that does not exit the source state. Inner
transitions are useful when defined for superstates with
exclusive (OR) decomposition. Use of inner transitions can
greatly simplify chart layout.
Glossary-4
Glossary
only when all charts in the library model are free of parse
and compile errors.
MATLAB function A chart function that works with a subset of the MATLAB
programming language.
Model Explorer Use to add, remove, and modify data, event, and target
objects in the Stateflow hierarchy. See “Use the Model
Explorer with Stateflow Objects” on page 33-13 for more
information.
notation Defines a set of objects and the rules that govern the
relationships between those objects. Stateflow chart
notation provides a way to communicate the design
information in a Stateflow chart.
Glossary-5
Glossary
Simulink function A chart function that you fill with Simulink blocks and call
in the actions of states and transitions. This function
provides an efficient model design and improves
readability by minimizing the graphical and nongraphical
objects required in a model. In a Stateflow chart, this
function acts like a function-call subsystem block of a
Simulink model.
Glossary-6
Glossary
Stateflow Finder Use to display a list of objects based on search criteria you
specify. You can directly access the properties dialog box
of any object in the search output display by clicking that
object.
Glossary-7
Glossary
truth table function A chart function that specifies logical behavior with
conditions, decisions, and actions. Truth tables are easier
to program and maintain than graphical functions.
Glossary-8