0% found this document useful (0 votes)
493 views1,436 pages

StateFlow UserGuide

User Guide for Stateflow

Uploaded by

miraj_cuet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
493 views1,436 pages

StateFlow UserGuide

User Guide for Stateflow

Uploaded by

miraj_cuet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1436

Stateflow

User's Guide

R2017a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

Technical support: www.mathworks.com/support/contact_us

Phone: 508-647-7000

The MathWorks, Inc.


3 Apple Hill Drive
Natick, MA 01760-2098

Stateflow User's Guide


COPYRIGHT 19972017 by The MathWorks, Inc.
The software described in this document is furnished under a license agreement. The software may be used
or copied only under the terms of the license agreement. No part of this manual may be photocopied or
reproduced in any form without prior written consent from The MathWorks, Inc.
FEDERAL ACQUISITION: This provision applies to all acquisitions of the Program and Documentation
by, for, or through the federal government of the United States. By accepting delivery of the Program
or Documentation, the government hereby agrees that this software or documentation qualifies as
commercial computer software or commercial computer software documentation as such terms are used
or defined in FAR 12.212, DFARS Part 227.72, and DFARS 252.227-7014. Accordingly, the terms and
conditions of this Agreement and only those rights specified in this Agreement, shall pertain to and
govern the use, modification, reproduction, release, performance, display, and disclosure of the Program
and Documentation by the federal government (or other entity acquiring for or through the federal
government) and shall supersede any conflicting contractual terms or conditions. If this License fails
to meet the government's needs or is inconsistent in any respect with federal procurement law, the
government agrees to return the Program and Documentation, unused, to The MathWorks, Inc.
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
May 1997 First printing New
January 1999 Second printing Revised for Version 2.0 (Release 11)
September 2000 Third printing Revised for Version 4.0 (Release 12))
June 2001 Fourth printing Revised for Version 4.1 (Release 12.1)
July 2002 Fifth printing Revised for Version 5.0 (Release 13)
January 2003 Online only Revised for Version 5.1 (Release 13SP1)
June 2004 Online only Revised for Version 6.0 (Release 14)
October 2004 Online only Revised for Version 6.1 (Release 14SP1)
March 2005 Online only Revised for Version 6.21 (Release 14SP2)
September 2005 Online only Revised for Version 6.3 (Release 14SP3)
March 2006 Online only Revised for Version 6.4 (Release 2006a)
September 2006 Online only Revised for Version 6.5 (Release 2006b)
March 2007 Online only Revised for Version 6.6 (Release 2007a)
September 2007 Online only Revised for Version 7.0 (Release 2007b)
March 2008 Online only Revised for Version 7.1 (Release 2008a)
October 2008 Online only Revised for Version 7.2 (Release 2008b)
March 2009 Online only Revised for Version 7.3 (Release 2009a)
September 2009 Online only Revised for Version 7.4 (Release 2009b)
March 2010 Online only Revised for Version 7.5 (Release 2010a)
September 2010 Online only Revised for Version 7.6 (Release 2010b)
April 2011 Online only Revised for Version 7.7 (Release 2011a)
September 2011 Online only Revised for Version 7.8 (Release 2011b)
March 2012 Online only Revised for Version 7.9 (Release 2012a)
September 2012 Online only Revised for Version 8.0 (Release 2012b)
March 2013 Online only Revised for Version 8.1 (Release 2013a)
September 2013 Online only Revised for Version 8.2 (Release 2013b)
March 2014 Online only Revised for Version 8.3 (Release 2014a)
October 2014 Online only Revised for Version 8.4 (Release 2014b)
March 2015 Online only Revised for Version 8.5 (Release 2015a)
September 2015 Online only Revised for Version 8.6 (Release 2015b)
October 2015 Online only Rereleased for Version 8.5.1 (Release
2015aSP1)
March 2016 Online only Revised for Version 8.7 (Release 2016a)
September 2016 Online only Revised for Version 8.8 (Release 2016b)
March 2017 Online only Revised for Version 8.9 (Release 2017a)
Contents

Stateflow Chart Concepts


1
Finite State Machine Concepts . . . . . . . . . . . . . . . . . . . . . . . . 1-2
What Is a Finite State Machine? . . . . . . . . . . . . . . . . . . . . . . 1-2
Finite State Machine Representations . . . . . . . . . . . . . . . . . . 1-2
Stateflow Chart Representations . . . . . . . . . . . . . . . . . . . . . . 1-2
Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3
Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-3

Stateflow Charts and Simulink Models . . . . . . . . . . . . . . . . . 1-4


The Simulink Model and the Stateflow Machine . . . . . . . . . . 1-4
Overview of Defining Stateflow Block Interfaces to Simulink
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-4

Stateflow Chart Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6

Stateflow Hierarchy of Objects . . . . . . . . . . . . . . . . . . . . . . . . 1-8

Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-10

Stateflow Chart Notation


2
Overview of Stateflow Objects . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Nongraphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3

Rules for Naming Stateflow Objects . . . . . . . . . . . . . . . . . . . . 2-4


Characters You Can Use . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Restriction on Name Length . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Keywords to Avoid When Naming Chart Objects . . . . . . . . . . 2-4

v
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
What Is a State? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
State Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
State Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
State Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-10

State Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15


State Hierarchy Example . . . . . . . . . . . . . . . . . . . . . . . . . . 2-15
Objects That a State Can Contain . . . . . . . . . . . . . . . . . . . . 2-16

State Decomposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17


Exclusive (OR) State Decomposition . . . . . . . . . . . . . . . . . . 2-17
Parallel (AND) State Decomposition . . . . . . . . . . . . . . . . . . 2-17

Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
What Is a Transition? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-19
Transition Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-20
Transition Label Notation . . . . . . . . . . . . . . . . . . . . . . . . . . 2-21
Valid Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-23

Transition Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-24


Transitions to and from Exclusive (OR) States . . . . . . . . . . 2-24
Transitions to and from Junctions . . . . . . . . . . . . . . . . . . . . 2-24
Transitions to and from Exclusive (OR) Superstates . . . . . . 2-25
Transitions to and from Substates . . . . . . . . . . . . . . . . . . . 2-26

Self-Loop Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-28

Inner Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-30


Before Using an Inner Transition . . . . . . . . . . . . . . . . . . . . 2-30
After Using an Inner Transition to a Connective Junction . . 2-32
Using an Inner Transition to a History Junction . . . . . . . . . 2-33

Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-35


What Is a Default Transition? . . . . . . . . . . . . . . . . . . . . . . . 2-35
Drawing Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . 2-35
Label Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . 2-35
Default Transition Examples . . . . . . . . . . . . . . . . . . . . . . . . 2-36

Connective Junctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-40


What Is a Connective Junction? . . . . . . . . . . . . . . . . . . . . . 2-40
Flow Chart Notation with Connective Junctions . . . . . . . . . 2-40

vi Contents
History Junctions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-46
What Is a History Junction? . . . . . . . . . . . . . . . . . . . . . . . . 2-46
History Junctions and Inner Transitions . . . . . . . . . . . . . . . 2-47

Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-48
What Is a Box? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-48
Example of Using a Box . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-48

When to Use Reusable Functions in Charts . . . . . . . . . . . . . 2-49

Stateflow Chart Semantics


3
What Do Semantics Mean for Stateflow Charts? . . . . . . . . . . 3-2
What Are Chart Semantics? . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Common Graphical and Nongraphical Constructs . . . . . . . . . 3-3
References for Chart Semantics . . . . . . . . . . . . . . . . . . . . . . 3-7

How Chart Constructs Interact During Execution . . . . . . . . 3-8


Overview of the Example Model . . . . . . . . . . . . . . . . . . . . . . 3-8
Model of the Check-In Process for a Hotel . . . . . . . . . . . . . . . 3-8
How the Chart Interacts with Simulink Blocks . . . . . . . . . . 3-12
Phases of Chart Execution . . . . . . . . . . . . . . . . . . . . . . . . . 3-13

Modeling Guidelines for Stateflow Charts . . . . . . . . . . . . . . 3-32

Modeling Rules That Stateflow Detects During Edit Time . 3-34


Object contains a syntax error . . . . . . . . . . . . . . . . . . . . . . 3-35
Dangling transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-35
Unreachable state . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-36
Transition shadowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-36
Invalid default transition path . . . . . . . . . . . . . . . . . . . . . . 3-37
Default transition is missing . . . . . . . . . . . . . . . . . . . . . . . . 3-38
Unexpected backtracking . . . . . . . . . . . . . . . . . . . . . . . . . . 3-38
Transition loops outside natural parent . . . . . . . . . . . . . . . 3-39
Transition action precedes a condition action along this path 3-40
Invalid transitions crossing into graphical function . . . . . . . 3-41
Invalid transitions crossing out of graphical function . . . . . 3-41

vii
How Events Drive Chart Execution . . . . . . . . . . . . . . . . . . . 3-43
How Stateflow Charts Respond to Events . . . . . . . . . . . . . . 3-43
Sources for Stateflow Events . . . . . . . . . . . . . . . . . . . . . . . . 3-43
How Charts Process Events . . . . . . . . . . . . . . . . . . . . . . . . 3-44

Types of Chart Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-46


Lifecycle of a Stateflow Chart . . . . . . . . . . . . . . . . . . . . . . . 3-46
Execution of an Inactive Chart . . . . . . . . . . . . . . . . . . . . . . 3-46
Execution of an Active Chart . . . . . . . . . . . . . . . . . . . . . . . 3-47
Execution of a Chart with Super Step Semantics . . . . . . . . 3-47
Execution of a Chart at Initialization . . . . . . . . . . . . . . . . . 3-55

Process for Grouping and Executing Transitions . . . . . . . . 3-57


Transition Flow Chart Types . . . . . . . . . . . . . . . . . . . . . . . 3-57
Order of Execution for a Set of Flow Charts . . . . . . . . . . . . 3-58

Evaluation Order for Outgoing Transitions . . . . . . . . . . . . . 3-60


What Does Ordering Mean for Outgoing Transitions? . . . . . 3-60
Detection of Transition Shadowing . . . . . . . . . . . . . . . . . . . 3-61
Explicit Ordering of Outgoing Transitions . . . . . . . . . . . . . . 3-61
Implicit Ordering of Outgoing Transitions . . . . . . . . . . . . . . 3-64
What Happens When You Switch Between Explicit and Implicit
Ordering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-69
Transition Testing Order in Multilevel State Hierarchy . . . 3-69

Process for Entering, Executing, and Exiting States . . . . . 3-74


Steps for Entering a State . . . . . . . . . . . . . . . . . . . . . . . . . 3-74
Steps for Executing an Active State . . . . . . . . . . . . . . . . . . 3-75
Steps for Exiting an Active State . . . . . . . . . . . . . . . . . . . . 3-75
State Execution Example . . . . . . . . . . . . . . . . . . . . . . . . . . 3-76

Execution Order for Parallel States . . . . . . . . . . . . . . . . . . . 3-78


Ordering for Parallel States . . . . . . . . . . . . . . . . . . . . . . . . 3-78
Explicit Ordering of Parallel States . . . . . . . . . . . . . . . . . . . 3-79
Implicit Ordering of Parallel States . . . . . . . . . . . . . . . . . . 3-80
Order Maintenance for Parallel States . . . . . . . . . . . . . . . . 3-81
Execution Priorities in Restored States . . . . . . . . . . . . . . . . 3-83
Switching Between Explicit and Implicit Ordering . . . . . . . 3-84
Execution Order of Parallel States in Boxes and Subcharts . 3-84

Early Return Logic for Event Broadcasts . . . . . . . . . . . . . . 3-85


Guidelines for Proper Chart Behavior . . . . . . . . . . . . . . . . . 3-85
How Early Return Logic Works . . . . . . . . . . . . . . . . . . . . . . 3-85

viii Contents
Example of Early Return Logic . . . . . . . . . . . . . . . . . . . . . . 3-86

Create Stateflow Charts


4
Basic Approach for Modeling Event-Driven Systems . . . . . . 4-2
Identify System Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Select a State Machine Type . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Specify State Actions and Transition Conditions . . . . . . . . . . 4-3
Define Persistent Data to Store State Variables . . . . . . . . . . 4-3
Simplify State Actions and Transition Conditions with Function
Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-4
Check That Your System Representation Is Complete . . . . . . 4-4

Represent Operating Modes Using States . . . . . . . . . . . . . . . 4-5


Create a State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Move and Resize States . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Create Substates and Superstates . . . . . . . . . . . . . . . . . . . . . 4-6
Group States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-6
Specify Substate Decomposition . . . . . . . . . . . . . . . . . . . . . . 4-8
Specify Activation Order for Parallel States . . . . . . . . . . . . . 4-9
Change State Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Label States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-15

Transition Between Operating Modes . . . . . . . . . . . . . . . . . 4-18


Create a Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-18
Label Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-19
Move Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20
Change Transition Arrowhead Size . . . . . . . . . . . . . . . . . . . 4-21
Create Self-Loop Transitions . . . . . . . . . . . . . . . . . . . . . . . . 4-22
Create Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . . 4-22
Change Transition Properties . . . . . . . . . . . . . . . . . . . . . . . 4-22

Stateflow Editor Operations . . . . . . . . . . . . . . . . . . . . . . . . . 4-26


Stateflow Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-26
Undo and Redo Editor Operations . . . . . . . . . . . . . . . . . . . . 4-31
Specify Colors and Fonts in a Chart . . . . . . . . . . . . . . . . . . 4-31
Content Preview for Stateflow Objects . . . . . . . . . . . . . . . . 4-34
Intelligent Tab Completion for Stateflow Charts . . . . . . . . . 4-35
Differentiate Elements of Action Language Syntax . . . . . . . 4-36

ix
Select and Deselect Graphical Objects . . . . . . . . . . . . . . . . . 4-38
Cut and Paste Graphical Objects . . . . . . . . . . . . . . . . . . . . 4-38
Copy Graphical Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39
Comment Out Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39
Format Chart Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-39
Generate a Model Report . . . . . . . . . . . . . . . . . . . . . . . . . . 4-54

Model Logic Patterns and Iterative Loops Using


Flow Charts
5
What Is a Flow Chart? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2

Difference Between Flow Charts and State Transition


Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-3

When to Use Flow Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-4

Create Flow Charts with the Pattern Wizard . . . . . . . . . . . . 5-5


Why Use the Pattern Wizard? . . . . . . . . . . . . . . . . . . . . . . . . 5-5
How to Create Reusable Flow Charts . . . . . . . . . . . . . . . . . . 5-5
Insert a Logic Pattern Using the Pattern Wizard . . . . . . . . . 5-7
Save and Reuse Flow Chart Patterns . . . . . . . . . . . . . . . . . 5-10
MAAB-Compliant Patterns from the Pattern Wizard . . . . . . 5-12
Create and Reuse a Custom Pattern with the Pattern
Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-21

Draw and Customize Flow Charts By Hand . . . . . . . . . . . . . 5-29


How to Draw a Flow Chart . . . . . . . . . . . . . . . . . . . . . . . . . 5-29
How to Change Connective Junction Size . . . . . . . . . . . . . . 5-29
How to Modify Junction Properties . . . . . . . . . . . . . . . . . . . 5-29

Best Practices for Creating Flow Charts . . . . . . . . . . . . . . . 5-31

x Contents
Build Mealy and Moore Charts
6
Overview of Mealy and Moore Machines . . . . . . . . . . . . . . . . 6-2
Semantics of Mealy and Moore Machines . . . . . . . . . . . . . . . 6-2
Model with Mealy and Moore Machines . . . . . . . . . . . . . . . . 6-3
Default State Machine Type . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Availability of Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-3
Advantages of Mealy and Moore Charts . . . . . . . . . . . . . . . . 6-3

Create Mealy and Moore Charts . . . . . . . . . . . . . . . . . . . . . . . 6-5

Model a Vending Machine Using Mealy Semantics . . . . . . . . 6-6


Open the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-6
Logic of the Mealy Vending Machine . . . . . . . . . . . . . . . . . . . 6-6
Design Rules in Mealy Vending Machine . . . . . . . . . . . . . . . 6-7

Design Considerations for Mealy Charts . . . . . . . . . . . . . . . . 6-8


Mealy Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-8
Design Rules for Mealy Charts . . . . . . . . . . . . . . . . . . . . . . . 6-8

Design Considerations for Moore Charts . . . . . . . . . . . . . . . 6-11


Moore Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-11
Design Rules for Moore Charts . . . . . . . . . . . . . . . . . . . . . . 6-11

Model a Traffic Light Using Moore Semantics . . . . . . . . . . . 6-16


Open the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-16
Logic of the Moore Traffic Light . . . . . . . . . . . . . . . . . . . . . 6-16
Design Rules in Moore Traffic Light . . . . . . . . . . . . . . . . . . 6-18

Effects of Changing the Chart Type . . . . . . . . . . . . . . . . . . . 6-19

Debug Mealy and Moore Charts . . . . . . . . . . . . . . . . . . . . . . 6-20

Techniques for Streamlining Chart Design


7
Record State Activity Using History Junctions . . . . . . . . . . . 7-2
What Is a History Junction? . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

xi
Create a History Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2
Change History Junction Size . . . . . . . . . . . . . . . . . . . . . . . . 7-3
Change History Junction Properties . . . . . . . . . . . . . . . . . . . 7-3

Encapsulate Modal Logic Using Subcharts . . . . . . . . . . . . . . 7-5


What Is a Subchart? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-5
Create a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Rules of Subchart Conversion . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Convert a State to a Subchart . . . . . . . . . . . . . . . . . . . . . . . . 7-6
Manipulate Subcharts as Objects . . . . . . . . . . . . . . . . . . . . . 7-8
Open a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-8
Edit a Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9
Navigate Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-9

Move Between Levels of Hierarchy Using Supertransitions 7-10


What Is a Supertransition? . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Draw a Supertransition Into a Subchart . . . . . . . . . . . . . . . 7-12
Draw a Supertransition Out of a Subchart . . . . . . . . . . . . . 7-17
Label Supertransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21

Define a Graphical Function . . . . . . . . . . . . . . . . . . . . . . . . . 7-23


Create a Graphical Function . . . . . . . . . . . . . . . . . . . . . . . . 7-23
Program a Graphical Function . . . . . . . . . . . . . . . . . . . . . . 7-24
Define Graphical Function Data . . . . . . . . . . . . . . . . . . . . . 7-24

Manage Large Graphical Functions . . . . . . . . . . . . . . . . . . . 7-27

Call Graphical Functions in States and Transitions . . . . . . 7-29


Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29

Specify Graphical Function Properties . . . . . . . . . . . . . . . . 7-30

Reuse Logic Patterns Using Graphical Functions . . . . . . . . 7-32


What Is a Graphical Function? . . . . . . . . . . . . . . . . . . . . . . 7-32
Why Use a Graphical Function in a Stateflow Chart? . . . . . 7-32
Where to Use a Graphical Function . . . . . . . . . . . . . . . . . . 7-32
Limitations Using Events in Graphical Functions . . . . . . . . 7-33

Export Stateflow Functions for Reuse . . . . . . . . . . . . . . . . . 7-34


Why Export Chart-Level Functions? . . . . . . . . . . . . . . . . . . 7-34
How to Export Chart-Level Functions . . . . . . . . . . . . . . . . . 7-34
Rules for Exporting Chart-Level Functions . . . . . . . . . . . . . 7-35

xii Contents
Export Chart-Level Functions . . . . . . . . . . . . . . . . . . . . . . . 7-35

Group Chart Objects Using Boxes . . . . . . . . . . . . . . . . . . . . . 7-41


When to Use Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41
Semantics of Stateflow Boxes . . . . . . . . . . . . . . . . . . . . . . . 7-41
Rules for Using Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-41
Draw and Edit a Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-42
Examples of Using Boxes . . . . . . . . . . . . . . . . . . . . . . . . . . 7-44

Reuse Functions with an Atomic Box . . . . . . . . . . . . . . . . . . 7-48


What Is an Atomic Box? . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-48
Rationale for Using an Atomic Box . . . . . . . . . . . . . . . . . . . 7-48
How to Reuse Functions with an Atomic Box . . . . . . . . . . . 7-48
Example of Reusing a Timer Function Multiple Times . . . . 7-49

Add Descriptive Comments in a Chart . . . . . . . . . . . . . . . . . 7-54


Create Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-54
Change Note Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-54
Change Note Font and Color . . . . . . . . . . . . . . . . . . . . . . . . 7-54
TeX Instructions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-55

Define Data
8
Add Stateflow Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Add Data from the Stateflow Editor . . . . . . . . . . . . . . . . . . . 8-2
Add Data Through the Model Explorer . . . . . . . . . . . . . . . . . 8-3

Detect Unused Data in the Symbols Window . . . . . . . . . . . . . 8-4

Set Data Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6


Stateflow Data Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-6
Set Properties in the Logging Section . . . . . . . . . . . . . . . . . 8-19
Set Properties in the Description Pane . . . . . . . . . . . . . . . . 8-20
Enter Expressions and Parameters for Data Properties . . . . 8-20

Share Data with Simulink and MATLAB Workspace . . . . . 8-23


Share Input Data with Simulink . . . . . . . . . . . . . . . . . . . . . 8-23
Share Output Data with Simulink . . . . . . . . . . . . . . . . . . . 8-23
Share Simulink Parameters with Charts . . . . . . . . . . . . . . . 8-24

xiii
Initialize Data from the MATLAB Base Workspace . . . . . . . 8-25
Save Data to the MATLAB Workspace . . . . . . . . . . . . . . . . 8-26

About Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-27

How Charts Work with Local and Global Data Stores . . . . 8-28

Access Data Store Memory from a Chart . . . . . . . . . . . . . . . 8-29


Bind a Stateflow Data Object to Data Store Memory . . . . . . 8-29
Use the Stateflow Editor to Bind a Data Object . . . . . . . . . . 8-29
Use the Model Explorer to Bind a Data Object . . . . . . . . . . 8-29
Resolve Data Store Bindings . . . . . . . . . . . . . . . . . . . . . . . . 8-30
Read and Write Global Data Programmatically . . . . . . . . . . 8-30

Diagnostics for Sharing Data Between Charts and Simulink


Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32
Errors to Check For . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32
When to Enable Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . 8-32
When to Disable Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . 8-32
How to Set Diagnostics for Shared Data . . . . . . . . . . . . . . . 8-32

Create a Global Data Store Across Multiple Models . . . . . . 8-34

Best Practices for Using Data Stores in Charts . . . . . . . . . . 8-35


When Binding to Data Stores in Charts . . . . . . . . . . . . . . . 8-35
When Enforcing Writes Before Reads in Unconnected Blocks 8-35

Type Stateflow Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36


What Is Data Type? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-36
Specify Data Type with the Property Inspector . . . . . . . . . . 8-36
Specify Data Type with the Data Type Assistant . . . . . . . . . 8-36
Built-In Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Inherit Data Types from Simulink Objects . . . . . . . . . . . . . 8-40
Derive Data Types from Previously Defined Data . . . . . . . . 8-40
Type Data by Using an Alias . . . . . . . . . . . . . . . . . . . . . . . 8-41
Strong Data Typing with Simulink I/O . . . . . . . . . . . . . . . . 8-42

Size Stateflow Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44


Methods for Sizing Stateflow Data . . . . . . . . . . . . . . . . . . . 8-44
How to Specify Data Size . . . . . . . . . . . . . . . . . . . . . . . . . . 8-45
Inherit Input or Output Size from Simulink Signals . . . . . . 8-45
Guidelines for Sizing Data with Numeric Values . . . . . . . . . 8-45
Guidelines for Sizing Data with MATLAB Expressions . . . . 8-46

xiv Contents
Examples of Valid Data Size Expressions . . . . . . . . . . . . . . 8-47
Name Conflict Resolution for Variables in Size Expressions . 8-47
Best Practices for Sizing Stateflow Data . . . . . . . . . . . . . . . 8-47

Handle Integer Overflow for Chart Data . . . . . . . . . . . . . . . 8-49


When Integer Overflow Can Occur . . . . . . . . . . . . . . . . . . . 8-49
Support for Handling Integer Overflow in Charts . . . . . . . . 8-49
Effect of Integer Promotion Rules on Saturation . . . . . . . . . 8-51
Impact of Saturation on Error Checks . . . . . . . . . . . . . . . . . 8-52

Define Temporary Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-53


When to Define Temporary Data . . . . . . . . . . . . . . . . . . . . . 8-53
How to Define Temporary Data . . . . . . . . . . . . . . . . . . . . . 8-53

Identify Data Using Dot Notation . . . . . . . . . . . . . . . . . . . . . 8-54


What Is Dot Notation? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-54
Resolution of Qualified Data Names with Dot Notation . . . . 8-55
Best Practices for Using Dot Notation in Qualified Data
Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-56

Resolve Data Properties from Simulink Signal Objects . . . 8-59


About Explicit Signal Resolution . . . . . . . . . . . . . . . . . . . . . 8-59
Inherited Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-59
Enable Signal Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . 8-60
A Simple Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-60

Best Practices for Using Data in Charts . . . . . . . . . . . . . . . . 8-63


Avoid inheriting output data properties from Simulink
blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-63
Restrict use of machine-parented data . . . . . . . . . . . . . . . . 8-63

Transfer Data Across Models . . . . . . . . . . . . . . . . . . . . . . . . . 8-65


Copy Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-65
Move Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-65

Define Events
9
How Events Work in Stateflow Charts . . . . . . . . . . . . . . . . . . 9-2
What Is an Event? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2

xv
When to Use Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Types of Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Where You Can Use Events . . . . . . . . . . . . . . . . . . . . . . . . . 9-3
Diagnostic for Detecting Unused Events . . . . . . . . . . . . . . . . 9-3

Define Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-5


Add Events with the Stateflow Editor . . . . . . . . . . . . . . . . . . 9-5
Add Events with the Model Explorer . . . . . . . . . . . . . . . . . . 9-5

Set Properties for an Event . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7


Access Event Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7
Property Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-7

Activate a Stateflow Chart Using Input Events . . . . . . . . . . . 9-9


What Is an Input Event? . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-9
Activate a Stateflow Chart Using Edge Triggers . . . . . . . . . . 9-9
Activate a Stateflow Chart Using Function Calls . . . . . . . . 9-10
Association of Input Events with Control Signals . . . . . . . . 9-11

Control States When Function-Call Inputs Reenable


Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-13
Set Behavior for a Reenabled Chart . . . . . . . . . . . . . . . . . . 9-13
Behavior When the Parent Is the Model Root . . . . . . . . . . . 9-13
Behavior When the Chart Is Inside a Model Block . . . . . . . 9-17

Activate a Simulink Block Using Output Events . . . . . . . . . 9-20


What Is an Output Event? . . . . . . . . . . . . . . . . . . . . . . . . . 9-20
Activate a Simulink Block Using Edge Triggers . . . . . . . . . 9-20
Activate a Simulink Block Using Function Calls . . . . . . . . . 9-28
Association of Output Events with Output Ports . . . . . . . . . 9-31
Access Simulink Subsystems Triggered By Output Events . 9-32

Control Chart Execution Using Implicit Events . . . . . . . . . 9-33


What Are Implicit Events? . . . . . . . . . . . . . . . . . . . . . . . . . 9-33
Keywords for Implicit Events . . . . . . . . . . . . . . . . . . . . . . . 9-33
Transition Between States Using Implicit Events . . . . . . . . 9-34
Execution Order of Transitions with Implicit Events . . . . . . 9-35

Count Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38


When to Count Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38
How to Count Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-38
Collect and Store Input Data in a Vector . . . . . . . . . . . . . . 9-38

xvi Contents
Best Practices for Using Events in Stateflow Charts . . . . . 9-40

Messages
10
How Messages Work in Stateflow Charts . . . . . . . . . . . . . . . 10-2

View Differences Between Stateflow Messages, Events, and


Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-3

Stateflow Message Syntax in Charts . . . . . . . . . . . . . . . . . . 10-11


Access the Data in a Message . . . . . . . . . . . . . . . . . . . . . . 10-11
Send a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-11
Guard a Transition or Action with a Message . . . . . . . . . . 10-12
Receive a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-14
Discard a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-15
Forward a Message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-16
Determine if a Message Is Valid . . . . . . . . . . . . . . . . . . . . 10-18
Check the Length of the Queue . . . . . . . . . . . . . . . . . . . . . 10-19

Queuing Behavior of Stateflow Messages . . . . . . . . . . . . . . 10-21

Lifetime of a Stateflow Message . . . . . . . . . . . . . . . . . . . . . 10-23

Limitations for Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-24

Define Messages in a Stateflow Chart . . . . . . . . . . . . . . . . . 10-25


Types of Messages in a Chart . . . . . . . . . . . . . . . . . . . . . . 10-25
Define Message Inputs and Outputs . . . . . . . . . . . . . . . . . 10-25

Set Message Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-27

Work with Message Viewer . . . . . . . . . . . . . . . . . . . . . . . . . 10-30


Visualize Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-31
Redisplay of Information in Message Viewer . . . . . . . . . . . 10-37
Time in Message Viewers . . . . . . . . . . . . . . . . . . . . . . . . . 10-37
Navigation in Message Viewers . . . . . . . . . . . . . . . . . . . . . 10-38
Function Calls in Message Viewer . . . . . . . . . . . . . . . . . . . 10-39

xvii
Use Actions in Charts
11
State Action Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Entry Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4
Exit Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4
During Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-4
Bind Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-5
On Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-6

Transition Action Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-8


Event or Message Triggers . . . . . . . . . . . . . . . . . . . . . . . . . 11-9
Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-10
Condition Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-11
Transition Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-11

Execution of Actions in States and Transitions . . . . . . . . . 11-12

Combine State Actions to Eliminate Redundant Code . . . 11-16


State Actions You Can Combine . . . . . . . . . . . . . . . . . . . . 11-16
Why Combine State Actions . . . . . . . . . . . . . . . . . . . . . . . 11-16
How to Combine State Actions . . . . . . . . . . . . . . . . . . . . . 11-16
Order of Execution of Combined Actions . . . . . . . . . . . . . . 11-17
Rules for Combining State Actions . . . . . . . . . . . . . . . . . . 11-18

Supported Operations on Chart Data . . . . . . . . . . . . . . . . . 11-19


Binary and Bitwise Operations . . . . . . . . . . . . . . . . . . . . . 11-19
Unary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Unary Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Assignment Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-22
Pointer and Address Operations . . . . . . . . . . . . . . . . . . . . 11-23
Type Cast Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-24
Replace Operators with Application Implementations . . . . 11-25

Supported Symbols in Actions . . . . . . . . . . . . . . . . . . . . . . . 11-27


Boolean Symbols, true and false . . . . . . . . . . . . . . . . . . . . 11-27
Comment Symbols, %, //, /* . . . . . . . . . . . . . . . . . . . . . . . . 11-28
Hexadecimal Notation Symbols, 0xFF . . . . . . . . . . . . . . . . 11-28
Infinity Symbol, inf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-28
Line Continuation Symbol, ... . . . . . . . . . . . . . . . . . . . . . . 11-29
Literal Code Symbol, $ . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-29
MATLAB Display Symbol, ; . . . . . . . . . . . . . . . . . . . . . . . . 11-29
Single-Precision Floating-Point Number Symbol, F . . . . . . 11-29

xviii Contents
Time Symbol, t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-29

Call C Functions in C Charts . . . . . . . . . . . . . . . . . . . . . . . . 11-31


Call C Library Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 11-31
Call the abs Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32
Call min and max Functions . . . . . . . . . . . . . . . . . . . . . . . 11-32
Replacement of Math Library Functions with Application
Implementations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-33
Call Custom C Code Functions . . . . . . . . . . . . . . . . . . . . . 11-33

Access Built-In MATLAB Functions and Workspace Data 11-38


Call MATLAB Functions in Stateflow . . . . . . . . . . . . . . . . 11-38
ml Namespace Operator . . . . . . . . . . . . . . . . . . . . . . . . . . 11-38
ml Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-39
ml Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-41
Which ml Should I Use? . . . . . . . . . . . . . . . . . . . . . . . . . . 11-41
ml Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-43
How Charts Infer the Return Size for ml Expressions . . . . 11-45

Use Arrays in Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-50


Array Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-50
Arrays and Custom Code . . . . . . . . . . . . . . . . . . . . . . . . . 11-50

Broadcast Events to Synchronize States . . . . . . . . . . . . . . 11-52


Directed Event Broadcasting . . . . . . . . . . . . . . . . . . . . . . . 11-52
Directed Local Event Broadcast Using send . . . . . . . . . . . 11-52
Directed Local Event Broadcast Using Qualified Event
Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-53
Diagnostic for Detecting Undirected Local Event
Broadcasts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-55

Control Chart Execution Using Temporal Logic . . . . . . . . 11-56


What Is Temporal Logic? . . . . . . . . . . . . . . . . . . . . . . . . . . 11-56
Rules for Using Temporal Logic Operators . . . . . . . . . . . . 11-56
Operators for Event-Based Temporal Logic . . . . . . . . . . . . 11-57
Examples of Event-Based Temporal Logic . . . . . . . . . . . . . 11-59
Notations for Event-Based Temporal Logic . . . . . . . . . . . . 11-61
Operators for Absolute-Time Temporal Logic . . . . . . . . . . . 11-63
Define Time Delays with Temporal Logic . . . . . . . . . . . . . 11-64
Examples of Absolute-Time Temporal Logic . . . . . . . . . . . 11-66
Run a Model That Uses Absolute-Time Temporal Logic . . . 11-67
Absolute-Time Temporal Logic in Conditionally Executed
Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-67

xix
How Sample Time Affects Chart Execution . . . . . . . . . . . . 11-70
Best Practices for Absolute-Time Temporal Logic . . . . . . . 11-71

Detect Changes in Data Values . . . . . . . . . . . . . . . . . . . . . . 11-74


Types of Data Value Changes That You Can Detect . . . . . 11-74
Run a Model That Uses Change Detection . . . . . . . . . . . . 11-75
How Change Detection Works . . . . . . . . . . . . . . . . . . . . . . 11-76
Change Detection Operators . . . . . . . . . . . . . . . . . . . . . . . 11-79
Chart with Change Detection . . . . . . . . . . . . . . . . . . . . . . 11-84

Check State Activity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-86


When to Check State Activity . . . . . . . . . . . . . . . . . . . . . . 11-86
How to Check State Activity . . . . . . . . . . . . . . . . . . . . . . . 11-86
The in Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-86
How Checking State Activity Works . . . . . . . . . . . . . . . . . 11-87
State Resolution for Identically Named Substates . . . . . . . 11-89
Best Practices for Checking State Activity . . . . . . . . . . . . . 11-91

Control Function-Call Subsystems Using Bind Actions . . 11-95


What Are Bind Actions? . . . . . . . . . . . . . . . . . . . . . . . . . . 11-95
Bind a Function-Call Subsystem to a State . . . . . . . . . . . . 11-95
Model That Binds a Function-Call Subsystem to a State . 11-100
Behavior of a Bound Function-Call Subsystem . . . . . . . . 11-103
Why Avoid Muxed Trigger Events with Binding . . . . . . . 11-110

Simplify Stateflow Chart Using the duration Operator . 11-113


Control Oscillation with Parallel State Logic . . . . . . . . . . 11-113
Control Oscillation with the duration Operator . . . . . . . . 11-114

MATLAB Syntax Support for States and Transitions


12
Modify the Action Language for a Chart . . . . . . . . . . . . . . . 12-2
Icons for Action Language Syntax . . . . . . . . . . . . . . . . . . . . 12-2
Change the Default Action Language . . . . . . . . . . . . . . . . . 12-2
C to MATLAB Syntax Conversion . . . . . . . . . . . . . . . . . . . . 12-3
Rules for Using MATLAB as the Action Language . . . . . . . 12-3

Action Language Auto Correction . . . . . . . . . . . . . . . . . . . . . 12-6

xx Contents
Differences Between MATLAB and C as Action Language
Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-7

Model Event-Driven System . . . . . . . . . . . . . . . . . . . . . . . . . 12-10


Typical Approaches to Chart Programming . . . . . . . . . . . . 12-10
Design Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10
Identify System Attributes . . . . . . . . . . . . . . . . . . . . . . . . 12-11
Build the Model Yourself or Use the Supplied Model . . . . . 12-12
Add a Stateflow Chart to the Feeder Model . . . . . . . . . . . . 12-12
Add States to Represent Operating Modes . . . . . . . . . . . . 12-15
Implement State Actions . . . . . . . . . . . . . . . . . . . . . . . . . . 12-16
Specify Transition Conditions . . . . . . . . . . . . . . . . . . . . . . 12-18
Define Data for Your System . . . . . . . . . . . . . . . . . . . . . . 12-21
Verify the System Representation . . . . . . . . . . . . . . . . . . . 12-23
Alternative Approach: Event-Based Chart . . . . . . . . . . . . . 12-25
Feeder Chart Activated by Input Events . . . . . . . . . . . . . . 12-25

Tabular Expression of Modal Logic


13
What Is a State Transition Table? . . . . . . . . . . . . . . . . . . . . . 13-2

Differences Between State Transition Tables and Charts . 13-5

Anatomy of a State Transition Table . . . . . . . . . . . . . . . . . . 13-6

Create State Transition Table and Specify Properties . . . . 13-8


How to Create a New State Transition Table . . . . . . . . . . . 13-8
Properties for State Transition Tables . . . . . . . . . . . . . . . . . 13-8

Generate Diagrams from State Transition Tables . . . . . . . 13-10

View State Reactions with State Transition Matrix . . . . . 13-11


What is a State Transition Matrix? . . . . . . . . . . . . . . . . . . 13-11
Create a State Transition Matrix . . . . . . . . . . . . . . . . . . . 13-11
Filter by State Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-12
Traceability To State Transition Table . . . . . . . . . . . . . . . 13-13

Highlight Flow of Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-14

xxi
State Transition Table Operations . . . . . . . . . . . . . . . . . . . 13-16
Insert Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . 13-16
Move Rows and Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-17
Copy Rows and Transition Cells . . . . . . . . . . . . . . . . . . . . 13-17
Set Default State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-17
Add History Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-17
Print State Transition Tables . . . . . . . . . . . . . . . . . . . . . . 13-17
Select and Clear Table Elements . . . . . . . . . . . . . . . . . . . . 13-18
Undo and Redo Edit Operations . . . . . . . . . . . . . . . . . . . . 13-18
Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-18

Rules for Using State Transition Tables . . . . . . . . . . . . . . . 13-19

State Transition Table Diagnostics . . . . . . . . . . . . . . . . . . . 13-20

Model Bang-Bang Controller with State Transition Table 13-21


Why Use State Transition Tables? . . . . . . . . . . . . . . . . . . 13-21
Design Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-22
Identify System Attributes . . . . . . . . . . . . . . . . . . . . . . . . 13-22
Build the Controller or Use the Supplied Model . . . . . . . . 13-23
Create a New State Transition Table . . . . . . . . . . . . . . . . 13-23
Add States and Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . 13-25
Specify State Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-26
Specify Transition Conditions and Actions . . . . . . . . . . . . 13-29
Define Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-31
Connect the Transition Table and Run the Model . . . . . . . 13-33
View the Graphical Representation . . . . . . . . . . . . . . . . . . 13-35

Debug Run-Time Errors in a State Transition Table . . . . . 13-37


Create the Model and the State Transition Table . . . . . . . 13-37
Debug the State Transition Table . . . . . . . . . . . . . . . . . . . 13-39
Correct the Run-Time Error . . . . . . . . . . . . . . . . . . . . . . . 13-40

Make States Reusable with Atomic Subcharts


14
What Is an Atomic Subchart? . . . . . . . . . . . . . . . . . . . . . . . . . 14-2

When to Use Atomic Subcharts . . . . . . . . . . . . . . . . . . . . . . . 14-4

xxii Contents
Benefits of Using Atomic Subcharts . . . . . . . . . . . . . . . . . . . 14-5
Comparison of Modeling Methods . . . . . . . . . . . . . . . . . . . . 14-5
Comparison of Simulation Methods . . . . . . . . . . . . . . . . . . . 14-6
Comparison of Editing Methods . . . . . . . . . . . . . . . . . . . . . 14-7
Comparison of Code Generation Methods . . . . . . . . . . . . . . 14-7

Restrictions for Converting to Atomic Subcharts . . . . . . . 14-11


Rationale for Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . 14-11
Access to Data, Graphical Functions, and Events . . . . . . . 14-11
Use of Event Broadcasts . . . . . . . . . . . . . . . . . . . . . . . . . . 14-11
Access to Local Data with a Nonzero First Index . . . . . . . . 14-12
Use of Machine-Parented Data . . . . . . . . . . . . . . . . . . . . . 14-12
Use of Strong Data Typing with Simulink Inputs and
Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-12
Use of Supertransitions . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-12
Use of Masked Library Chart . . . . . . . . . . . . . . . . . . . . . . 14-12

Convert to and from Atomic Subcharts . . . . . . . . . . . . . . . 14-13


Convert a State or Subchart to an Atomic Subchart . . . . . 14-13
Convert an Atomic Subchart to a State or Subchart . . . . . 14-16
Restrictions for Converting an Atomic Subchart to a State or
Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-16

Map Variables for Atomic Subcharts . . . . . . . . . . . . . . . . . 14-18


How to Map Variables in an Atomic Subchart . . . . . . . . . . 14-18
Map Input and Output Data for an Atomic Subchart . . . . . 14-19
Map Data Store Memory for an Atomic Subchart . . . . . . . 14-22
Map Parameter Data for an Atomic Subchart . . . . . . . . . . 14-25
Map Input Events for an Atomic Subchart . . . . . . . . . . . . 14-29

Generate Reusable Code for Atomic Subcharts . . . . . . . . . 14-34


How to Generate Reusable Code for Linked Atomic
Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-34
How to Generate Reusable Code for Unlinked Atomic
Subcharts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-35

Rules for Using Atomic Subcharts . . . . . . . . . . . . . . . . . . . . 14-36

Reuse a State Multiple Times in a Chart . . . . . . . . . . . . . . 14-39


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-39
Edit a Model to Use Atomic Subcharts . . . . . . . . . . . . . . . 14-41
Run the New Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-46
Propagate a Change in the Library Chart . . . . . . . . . . . . . 14-46

xxiii
Reduce the Compilation Time of a Chart . . . . . . . . . . . . . . 14-48
Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-48
Edit a Model to Use Atomic Subcharts . . . . . . . . . . . . . . . 14-49

Divide a Chart into Separate Units . . . . . . . . . . . . . . . . . . . 14-50


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-50
Edit a Model to Use Atomic Subcharts . . . . . . . . . . . . . . . 14-51

Generate Reusable Code for Unit Testing . . . . . . . . . . . . . 14-53


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-53
Convert a State to an Atomic Subchart . . . . . . . . . . . . . . . 14-54
Specify Code Generation Parameters . . . . . . . . . . . . . . . . . 14-55
Generate Code for Only the Atomic Subchart . . . . . . . . . . 14-56

Save and Restore Simulations with SimState


15
What Is a SimState? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2

Benefits of Using a Snapshot of the Simulation State . . . . . 15-4


Division of a Long Simulation into Segments . . . . . . . . . . . 15-4
Test of a Chart Response to Different Settings . . . . . . . . . . 15-4

Divide a Long Simulation into Segments . . . . . . . . . . . . . . . 15-5


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5
Define the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6
Load the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-7
Simulate the Specific Segment . . . . . . . . . . . . . . . . . . . . . . 15-8

Test a Unique Chart Configuration . . . . . . . . . . . . . . . . . . . 15-10


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-10
Define the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-11
Load the SimState and Modify Values . . . . . . . . . . . . . . . 15-14
Test the Modified SimState . . . . . . . . . . . . . . . . . . . . . . . . 15-18

Test a Chart with Fault Detection and Redundant Logic . 15-20


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-20
Define the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-23
Modify SimState Values for One Actuator Failure . . . . . . . 15-24
Test the SimState for One Failure . . . . . . . . . . . . . . . . . . 15-28

xxiv Contents
Modify SimState Values for Two Actuator Failures . . . . . . 15-31
Test the SimState for Two Failures . . . . . . . . . . . . . . . . . . 15-32

Methods for Interacting with the SimState of a Chart . . . 15-34

Rules for Using the SimState of a Chart . . . . . . . . . . . . . . . 15-37


Limitations on Values You Can Modify . . . . . . . . . . . . . . . 15-37
Rules for Modifying Data Values . . . . . . . . . . . . . . . . . . . . 15-37
Rules for Modifying State Activity . . . . . . . . . . . . . . . . . . . 15-38
Restriction on Continuous-Time Charts . . . . . . . . . . . . . . . 15-38
No Partial Loading of a SimState . . . . . . . . . . . . . . . . . . . 15-38
Restriction on Copying SimState Values . . . . . . . . . . . . . . 15-39
SimState Limitations That Apply to All Blocks in a Model . 15-39

Best Practices for Using the SimState of a Chart . . . . . . . 15-40


Use MAT-Files to Save a SimState for Future Use . . . . . . 15-40
Use Scripts to Save SimState Commands for Future Use . . 15-40

Vectors and Matrices in C Charts


16
How Vectors and Matrices Work in C Charts . . . . . . . . . . . . 16-2
When to Use Vectors and Matrices . . . . . . . . . . . . . . . . . . . 16-2
Where You Can Use Vectors and Matrices . . . . . . . . . . . . . 16-2

Define Vectors and Matrices . . . . . . . . . . . . . . . . . . . . . . . . . 16-4


Define a Vector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4
Define a Matrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-4

Scalar Expansion for Converting Scalars to Nonscalars . . 16-6


What Is Scalar Expansion? . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
How Scalar Expansion Works for Functions . . . . . . . . . . . . 16-6

Assign and Access Vector and Matrix Values . . . . . . . . . . . . 16-8


Notation for Vectors and Matrices . . . . . . . . . . . . . . . . . . . . 16-8
Assign and Access Values of Vectors . . . . . . . . . . . . . . . . . . 16-8
Assign and Access Values of Matrices . . . . . . . . . . . . . . . . . 16-9
Assign Values of a Vector or Matrix Using Scalar
Expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-9

xxv
Operations For Vectors and Matrices in C Charts . . . . . . . 16-11
Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-11
Unary Operations and Actions . . . . . . . . . . . . . . . . . . . . . 16-11
Assignment Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-12

Rules for Vectors and Matrices in C Charts . . . . . . . . . . . . 16-13

Best Practices for Vectors and Matrices in C Charts . . . . 16-14


Perform Matrix Multiplication and Division Using MATLAB
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-14
Index a Vector Using the temporalCount Operator . . . . . . 16-15

Find Pattern in Data Transmission Using Vectors . . . . . . 16-17


Storage of Complex Data in a Vector . . . . . . . . . . . . . . . . . 16-18
Scalar Expansion of a Vector . . . . . . . . . . . . . . . . . . . . . . . 16-18

Calculate Motion Using Matrices . . . . . . . . . . . . . . . . . . . . . 16-19


How the Model Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-19
Storage of Two-Dimensional Data in Matrices . . . . . . . . . . 16-19
Calculation of Two-Dimensional Dynamics of Each Ball . . 16-20
Run the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-22

Variable-Size Data in Stateflow Charts


17
What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2

How Charts Implement Variable-Size Data . . . . . . . . . . . . . 17-3

Enable Support for Variable-Size Data . . . . . . . . . . . . . . . . . 17-4

Declare Variable-Size Inputs and Outputs . . . . . . . . . . . . . . 17-5

Compute Output Based on Size of Input Signal . . . . . . . . . 17-7


About the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-7
Chart: VarSizeSignalSource . . . . . . . . . . . . . . . . . . . . . . . . 17-8
Chart: size_based_processing . . . . . . . . . . . . . . . . . . . . . . . 17-11
Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-15

Rules for Using Variable-Size Data in Stateflow Charts . . 17-16

xxvi Contents
Enumerated Data in Charts
18
What Is Enumerated Data? . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2

Benefits of Using Enumerated Data in a Chart . . . . . . . . . . 18-3

Where to Use Enumerated Data . . . . . . . . . . . . . . . . . . . . . . 18-4

Elements of an Enumerated Data Type Definition . . . . . . . 18-5

Define Enumerated Data in a Chart . . . . . . . . . . . . . . . . . . . 18-8


Tasks for Defining Enumerated Data in a Chart . . . . . . . . . 18-8
Define an Enumerated Data Type in a File . . . . . . . . . . . . . 18-8
Add Enumerated Data to a Chart . . . . . . . . . . . . . . . . . . . . 18-9

Ensure That Changes in Data Type Definition Take Effect 18-11

Notation for Enumerated Values in Charts . . . . . . . . . . . . 18-12


Nonprefixed Notation for Enumerated Values . . . . . . . . . . 18-12
Prefixed Notation for Enumerated Values . . . . . . . . . . . . . 18-12

Enumerated Data Operations in Charts . . . . . . . . . . . . . . . 18-14

Rules for Using Enumerated Data in a Chart . . . . . . . . . . 18-15

Best Practices for Using Enumerated Data in a Chart . . . 18-18

Model CD Player Using Enumerated Data . . . . . . . . . . . . . 18-20


Overview of CD Player Model . . . . . . . . . . . . . . . . . . . . . . 18-20
Benefits of Using Enumerated Types in This Model . . . . . . 18-22
Run the CD Player Model . . . . . . . . . . . . . . . . . . . . . . . . . 18-22
How the UserRequest Chart Works . . . . . . . . . . . . . . . . . . 18-25
How the CdPlayerModeManager Chart Works . . . . . . . . . 18-25
How the CdPlayerBehaviorModel Chart Works . . . . . . . . . 18-29

Assign Enumerated Values in a Chart . . . . . . . . . . . . . . . . 18-32


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-32
Build the Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-32
View Results for Simulation . . . . . . . . . . . . . . . . . . . . . . . 18-35
How the Chart Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-38

xxvii
Continuous-Time Systems in Stateflow Charts
19
Continuous-Time Modeling in Stateflow . . . . . . . . . . . . . . . 19-2
What Is Continuous-Time Modeling? . . . . . . . . . . . . . . . . . . 19-2
When to Use Stateflow Charts for Continuous-Time
Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-3
Model Continuous-Time with Zero-Crossing Detection . . . . . 19-3
When to Disable Zero-Crossing Detection . . . . . . . . . . . . . . 19-4

Model Hybrid Systems with Model Logic . . . . . . . . . . . . . . . 19-5

Configure a Stateflow Chart to Update in Continuous


Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-6

Define Continuous-Time Variables . . . . . . . . . . . . . . . . . . . . 19-9


Purpose of Continuous-Time Variables . . . . . . . . . . . . . . . . 19-9
Implicit Time Derivatives . . . . . . . . . . . . . . . . . . . . . . . . . . 19-9
Rules for Using Continuous-Time Variables . . . . . . . . . . . . 19-9
How to Define Continuous-Time Variables . . . . . . . . . . . . 19-10
Expose Continuous States to a Simulink Model . . . . . . . . . 19-10

Model a Bouncing Ball in Continuous Time . . . . . . . . . . . . 19-11


Dynamics of a Bouncing Ball . . . . . . . . . . . . . . . . . . . . . . . 19-11
Model the Bouncing Ball . . . . . . . . . . . . . . . . . . . . . . . . . . 19-12

Design Considerations for Continuous-Time Modeling in


Stateflow Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-22
Rationale for Design Considerations . . . . . . . . . . . . . . . . . 19-22
Summary of Rules for Continuous-Time Modeling . . . . . . . 19-22

Fixed-Point Data in Stateflow Charts


20
What Is Fixed-Point Data? . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Fixed-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-2
Fixed-Point Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-3

xxviii Contents
How Fixed-Point Data Works in Stateflow Charts . . . . . . . 20-5
How Stateflow Software Defines Fixed-Point Data . . . . . . . 20-5
Specify Fixed-Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-6
Rules for Specifying Fixed-Point Word Length . . . . . . . . . . 20-7
Fixed-Point Context-Sensitive Constants . . . . . . . . . . . . . . . 20-7
Tips for Using Fixed-Point Data . . . . . . . . . . . . . . . . . . . . . 20-8
Detect Overflow for Fixed-Point Types . . . . . . . . . . . . . . . 20-10
Share Fixed-Point Data with Simulink Models . . . . . . . . . 20-10

Use Fixed-Point Chart Inputs . . . . . . . . . . . . . . . . . . . . . . . 20-12


Run the Fixed-Point "Bang-Bang Control" Model . . . . . . . 20-12
Explore the Fixed-Point "Bang-Bang Control" Model . . . . . 20-13

Use Fixed-Point Parameters and Local Data . . . . . . . . . . . 20-17


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-17
Build the Fixed-Point Butterworth Filter . . . . . . . . . . . . . 20-17
Define the Model Callback Function . . . . . . . . . . . . . . . . . 20-18
Add Other Blocks to the Model . . . . . . . . . . . . . . . . . . . . . 20-19
Set Model Configuration Parameters . . . . . . . . . . . . . . . . . 20-21
Run the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20-21

Operations with Fixed-Point Data . . . . . . . . . . . . . . . . . . . . 20-23


Supported Operations with Fixed-Point Operands . . . . . . . 20-23
Promotion Rules for Fixed-Point Operations . . . . . . . . . . . 20-25
Assignment (=, :=) Operations . . . . . . . . . . . . . . . . . . . . . . 20-30
Fixed-Point Conversion Operations . . . . . . . . . . . . . . . . . . 20-37
Automatic Scaling of Stateflow Fixed-Point Data . . . . . . . 20-38

Complex Data in C Charts


21
How Complex Data Works in C Charts . . . . . . . . . . . . . . . . . 21-2
What Is Complex Data? . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
When to Use Complex Data . . . . . . . . . . . . . . . . . . . . . . . . 21-2
Where You Can Use Complex Data . . . . . . . . . . . . . . . . . . . 21-2
How You Can Use Complex Data . . . . . . . . . . . . . . . . . . . . 21-3

Define Complex Data Using the Editor . . . . . . . . . . . . . . . . . 21-4

xxix
Complex Data Operations for Charts That Support C
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-7
Binary Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-7
Unary Operations and Actions . . . . . . . . . . . . . . . . . . . . . . 21-7
Assignment Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-8

Define Complex Data Using Operators . . . . . . . . . . . . . . . . . 21-9


Why Use Operators for Complex Numbers? . . . . . . . . . . . . . 21-9
Define a Complex Number . . . . . . . . . . . . . . . . . . . . . . . . . 21-9
Access Real and Imaginary Parts of a Complex Number . . . 21-9
Work with Vector Arguments . . . . . . . . . . . . . . . . . . . . . . 21-11

Rules for Using Complex Data in C Charts . . . . . . . . . . . . 21-12

Best Practices for Using Complex Data in C Charts . . . . . 21-15


Perform Math Function Operations with a MATLAB
Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-15
Perform Complex Division with a MATLAB Function . . . . 21-16

Detect Valid Transmission Data Using Frame


Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-19

Measure Frequency Response Using a Spectrum Analyzer 21-23

Define Interfaces to Simulink Models and the


MATLAB Workspace
22
Overview of Stateflow Block Interfaces . . . . . . . . . . . . . . . . 22-2
Stateflow Block Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2

Specify Chart Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3


About Chart Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-3
Set Properties for a Single Chart . . . . . . . . . . . . . . . . . . . . 22-3
Set Properties for All Charts in the Model . . . . . . . . . . . . . 22-10

Set Stateflow Block Update Method . . . . . . . . . . . . . . . . . . 22-12

Implement Interfaces to Simulink Models . . . . . . . . . . . . . 22-14


Define a Triggered Stateflow Block . . . . . . . . . . . . . . . . . . 22-14

xxx Contents
Define a Sampled Stateflow Block . . . . . . . . . . . . . . . . . . . 22-15
Define an Inherited Stateflow Block . . . . . . . . . . . . . . . . . 22-15
Define a Continuous Stateflow Block . . . . . . . . . . . . . . . . . 22-16
Define Function-Call Output Events . . . . . . . . . . . . . . . . . 22-16
Define Edge-Triggered Output Events . . . . . . . . . . . . . . . . 22-17

When to Use Chart Libraries . . . . . . . . . . . . . . . . . . . . . . . . 22-18

Create Specialized Chart Libraries for Large-Scale


Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-19

Properties You Can Specialize Across Instances of Library


Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-20

Limitations of Library Charts . . . . . . . . . . . . . . . . . . . . . . . 22-21

MATLAB Workspace Interfaces . . . . . . . . . . . . . . . . . . . . . . 22-22


About the MATLAB Workspace . . . . . . . . . . . . . . . . . . . . . 22-22
Examine the MATLAB Workspace . . . . . . . . . . . . . . . . . . 22-22
Interface the MATLAB Workspace with Charts . . . . . . . . . 22-22

About Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-23

Mask Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-24

Look Under a Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-26

Mask a Stateflow Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-27


Create Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-27
Change the Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-27
Add a Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-27
View the New Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-28
Edit the Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-29

About Active State Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-30


State Activity Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-30
Active State Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-30
Leaf State Activity and Parallel States . . . . . . . . . . . . . . . 22-31

When to Use Active State Output Data . . . . . . . . . . . . . . . . 22-34

Set Active State Data as Local . . . . . . . . . . . . . . . . . . . . . . . 22-35

xxxi
Limitations for Active State Data . . . . . . . . . . . . . . . . . . . . 22-36

Use Active State Output Data . . . . . . . . . . . . . . . . . . . . . . . 22-37

Change the Active State Port Name . . . . . . . . . . . . . . . . . . 22-40

Define State Activity Enum Name and Type . . . . . . . . . . . 22-41

Units in Stateflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-43


Units for Input and Output Data . . . . . . . . . . . . . . . . . . . 22-43
Consistency Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-43
Units for Stateflow Limitations . . . . . . . . . . . . . . . . . . . . . 22-43

Structures and Bus Signals in Stateflow Charts


23
About Stateflow Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 23-2
What Is a Stateflow Structure? . . . . . . . . . . . . . . . . . . . . . . 23-2
What You Can Do with Structures . . . . . . . . . . . . . . . . . . . 23-2

Connect Structures in Charts to External Bus Signals . . . . 23-3


Structure Definitions in sfbus_demo Stateflow Chart . . . . . 23-4
Structure Definitions in sfbus_demo Stateflow Graphical
Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-4
Simulink Bus Objects Define Stateflow Structures . . . . . . . 23-5

Rules for Defining Structure Data Types in Charts . . . . . . 23-8

Define Stateflow Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 23-9


Define Structure Inputs and Outputs . . . . . . . . . . . . . . . . . 23-9
Define Local Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-12
Define Structures of Parameter Scope . . . . . . . . . . . . . . . . 23-13
Define Temporary Structures . . . . . . . . . . . . . . . . . . . . . . 23-14
Define Structure Types with Expressions . . . . . . . . . . . . . 23-15

Structure Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-17


Index Sub-Structures and Fields . . . . . . . . . . . . . . . . . . . . 23-17
Guidelines for Assignment of Values . . . . . . . . . . . . . . . . . 23-19
Get Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-20

xxxii Contents
Integrate Custom Structures in Stateflow Charts . . . . . . . 23-22

Debug Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-26

Stateflow Design Patterns


24
Debounce Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
Why Debounce Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
The Debouncer Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
Key Behaviors of Debouncer Chart . . . . . . . . . . . . . . . . . . . 24-3
Run the Debouncer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-5

Schedule Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-8

Schedule Execution of Simulink Subsystems . . . . . . . . . . . . 24-9


When to Implement Schedulers . . . . . . . . . . . . . . . . . . . . . . 24-9
Types of Schedulers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-9

Schedule Multiple Subsystems in a Single Step . . . . . . . . . 24-10


Key Behaviors of Ladder Logic Scheduler . . . . . . . . . . . . . 24-11
Run the Ladder Logic Scheduler . . . . . . . . . . . . . . . . . . . . 24-12

Schedule One Subsystem in a Single Step . . . . . . . . . . . . . 24-14


Key Behaviors of Loop Scheduler . . . . . . . . . . . . . . . . . . . 24-15
Run the Loop Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . 24-15

Schedule Subsystems to Execute at Specific Times . . . . . . 24-17


Key Behaviors of Temporal Logic Scheduler . . . . . . . . . . . 24-18
Run the Temporal Logic Scheduler . . . . . . . . . . . . . . . . . . 24-18

Implement Dynamic Test Vectors . . . . . . . . . . . . . . . . . . . . 24-20


When to Implement Test Vectors . . . . . . . . . . . . . . . . . . . 24-20
A Dynamic Test Vector Chart . . . . . . . . . . . . . . . . . . . . . . 24-22
Key Behaviors of the Chart and Model . . . . . . . . . . . . . . . 24-24
Run the Model with Stateflow Test Vectors . . . . . . . . . . . . 24-26

Map Fault Conditions to Actions in Truth Tables . . . . . . . 24-29

xxxiii
Design for Isolation and Recovery in a Chart . . . . . . . . . . 24-32
Mode Logic for the Elevator Actuators . . . . . . . . . . . . . . . 24-32
States for Failure and Isolation . . . . . . . . . . . . . . . . . . . . . 24-33
Transitions for Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . 24-34

Truth Table Functions for Decision-Making Logic


25
What Is a Truth Table? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2
Where to Use a Truth Table . . . . . . . . . . . . . . . . . . . . . . . . 25-3

Language Options for Stateflow Truth Tables . . . . . . . . . . . 25-4


C Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-4
MATLAB Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-4
Select a Language for Stateflow Truth Tables . . . . . . . . . . . 25-5
Migration from C to MATLAB Truth Tables . . . . . . . . . . . . 25-5

Represent Combinatorial Logic Using Truth Tables . . . . . . 25-6

Build Model with Stateflow Truth Table . . . . . . . . . . . . . . . 25-7


Add a Stateflow Block that Calls a Truth Table Function . . 25-7

Program a Truth Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-19


Open a Truth Table for Editing . . . . . . . . . . . . . . . . . . . . . 25-19
Select an Action Language . . . . . . . . . . . . . . . . . . . . . . . . 25-21
Enter Truth Table Conditions . . . . . . . . . . . . . . . . . . . . . . 25-21
Enter Truth Table Decisions . . . . . . . . . . . . . . . . . . . . . . . 25-23
Enter Truth Table Actions . . . . . . . . . . . . . . . . . . . . . . . . 25-26
Assign Truth Table Actions to Decisions . . . . . . . . . . . . . . 25-36
Add Initial and Final Actions . . . . . . . . . . . . . . . . . . . . . . 25-41

Debug a Truth Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-44


Check Truth Tables for Errors . . . . . . . . . . . . . . . . . . . . . 25-44
Debug a Truth Table During Simulation . . . . . . . . . . . . . . 25-44

Correct Overspecified and Underspecified Truth Tables . 25-60


Example of an Overspecified Truth Table . . . . . . . . . . . . . 25-60
Example of an Underspecified Truth Table . . . . . . . . . . . . 25-64

xxxiv Contents
How Stateflow Generates Content for Truth Tables . . . . . 25-69
Types of Generated Content . . . . . . . . . . . . . . . . . . . . . . . 25-69
View Generated Content . . . . . . . . . . . . . . . . . . . . . . . . . . 25-69
How Stateflow Software Generates Graphical Functions for
Truth Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-69
How Stateflow Software Generates MATLAB Code for Truth
Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-73

Truth Table Editor Operations . . . . . . . . . . . . . . . . . . . . . . 25-76


Add or Modify Stateflow Data . . . . . . . . . . . . . . . . . . . . . . 25-76
Append Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . 25-76
Compact the Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-76
Delete Text, Rows, and Columns . . . . . . . . . . . . . . . . . . . . 25-77
Diagnose the Truth Table . . . . . . . . . . . . . . . . . . . . . . . . . 25-77
View Generated Content . . . . . . . . . . . . . . . . . . . . . . . . . . 25-77
Edit Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-77
Insert Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . 25-78
Move Rows and Columns . . . . . . . . . . . . . . . . . . . . . . . . . 25-78
Print Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-78
Select and Deselect Table Elements . . . . . . . . . . . . . . . . . 25-79
Undo and Redo Edit Operations . . . . . . . . . . . . . . . . . . . . 25-79
View the Stateflow Chart for the Truth Table . . . . . . . . . . 25-79

MATLAB Functions in Stateflow Charts


26
MATLAB Functions in a Chart . . . . . . . . . . . . . . . . . . . . . . . 26-2

Why Use a MATLAB Function in a Chart? . . . . . . . . . . . . . . 26-3

Where to Use a MATLAB Function . . . . . . . . . . . . . . . . . . . . 26-4

MATLAB Functions in a Stateflow Chart . . . . . . . . . . . . . . . 26-5

Build Model with MATLAB Function in a Chart . . . . . . . . . 26-7

Specify MATLAB Function Properties in a Chart . . . . . . . 26-12


Set MATLAB Function Properties . . . . . . . . . . . . . . . . . . . 26-12

Program a MATLAB Function in a Chart . . . . . . . . . . . . . . 26-17

xxxv
Debug a MATLAB Function in a Chart . . . . . . . . . . . . . . . . 26-20
Check MATLAB Functions for Syntax Errors . . . . . . . . . . 26-20
Run-Time Debugging for MATLAB Functions in Charts . . 26-21
Check for Data Range Violations . . . . . . . . . . . . . . . . . . . . 26-23

Connect Structures in MATLAB Functions to Bus Signals in


Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-24
About Structures in MATLAB Functions . . . . . . . . . . . . . . 26-24
Define Structures in MATLAB Functions . . . . . . . . . . . . . 26-24

Define Enumerated Data in MATLAB Functions . . . . . . . . 26-27

Declare Variable-Size Data in MATLAB Functions . . . . . . 26-28

Enhance Readability of Generated Code for MATLAB


Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-29

Simulink Functions in Stateflow Charts


27
Simulink Functions in Stateflow . . . . . . . . . . . . . . . . . . . . . . 27-2
What Is a Simulink Function? . . . . . . . . . . . . . . . . . . . . . . 27-2
Where to Define a Simulink Function in a Chart . . . . . . . . . 27-2
Rules for Using Simulink Functions in Stateflow Charts . . . 27-3

Share Functions Across Simulink and Stateflow . . . . . . . . . 27-6

Why Use a Simulink Function in a Stateflow Chart? . . . . . 27-8


Advantages of Using Simulink Functions in a Stateflow
Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8
Benefits of Using a Simulink Function to Access Simulink
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8
Benefits of Using a Simulink Function to Schedule Execution of
Multiple Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-11

Basic Approach to Defining Simulink Functions in Stateflow


Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-15
Task 1: Add a Function to the Chart . . . . . . . . . . . . . . . . . 27-15
Task 2: Define the Subsystem Elements of the Simulink
Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-16

xxxvi Contents
Task 3: Configure the Function Inputs . . . . . . . . . . . . . . . 27-16

How a Simulink Function Binds to a State . . . . . . . . . . . . 27-18


Bind Behavior of a Simulink Function . . . . . . . . . . . . . . . 27-18
Control Subsystem Variables When the Simulink Function Is
Disabled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-20
Example of Binding a Simulink Function to a State . . . . . 27-20

How a Simulink Function Behaves When Called from


Multiple Sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-26

Define a Function That Uses Simulink Blocks . . . . . . . . . . 27-27


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-27
Edit a Model to Use a Simulink Function . . . . . . . . . . . . . 27-28
Run the New Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-35

Schedule Execution of Multiple Controllers . . . . . . . . . . . 27-36


Goal of the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-36
Edit a Model to Use Simulink Functions . . . . . . . . . . . . . . 27-37
Run the New Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-43

Build Targets
28
Code Generation for Stateflow Blocks . . . . . . . . . . . . . . . . . 28-2
Code Generation for Rapid Prototyping and Production Code
Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-2

Choose a Procedure to Simulate a Model . . . . . . . . . . . . . . . 28-3


Guidelines for Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . 28-3
Choose the Right Procedure for Simulation . . . . . . . . . . . . . 28-3

Integrate Custom C/C++ Code for Simulation . . . . . . . . . . . 28-5


Integrate Custom C++ Code for Simulation . . . . . . . . . . . . . 28-5
Integrate Custom C Code for Nonlibrary Charts for
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-6
Integrate Custom C Code for Library Charts for Simulation 28-9
Integrate Custom C Code for All Charts for Simulation . . . 28-11
Call External Functions in Charts with MATLAB as the Action
Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-13

xxxvii
Start Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-13

Speed Up Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-14


Performance of Model Update . . . . . . . . . . . . . . . . . . . . . . 28-14
Disable Simulation Target Options That Impact Execution
Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-14
Keep Charts Closed to Speed Up Simulation . . . . . . . . . . . 28-15
Keep Scope Blocks Closed to Speed Up Simulation . . . . . . 28-15
Use Library Charts in Your Model . . . . . . . . . . . . . . . . . . 28-15

Generate C/C++ Code for Rapid Prototyping or Production


Deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-16

Optimize Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-17

Command-Line API to Set Simulation and Code Generation


Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-18
How to Set Parameters at the Command Line . . . . . . . . . . 28-18
Simulation Parameters for Nonlibrary Models . . . . . . . . . . 28-19
Simulation Parameters for Library Models . . . . . . . . . . . . 28-21

Specify Relative Paths for Custom Code . . . . . . . . . . . . . . 28-23


Why Use Relative Paths? . . . . . . . . . . . . . . . . . . . . . . . . . 28-23
Search Relative Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23
Path Syntax Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23

Share Data Using Custom C Code . . . . . . . . . . . . . . . . . . . . 28-25


Use Custom Code to Define Global Constants . . . . . . . . . . 28-25
Use Custom Code to Define Global Constants, Variables, and
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-27

Parse Stateflow Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-31


How the Stateflow Parser Works . . . . . . . . . . . . . . . . . . . . 28-31
Calling the Stateflow Parser . . . . . . . . . . . . . . . . . . . . . . . 28-31

Resolve Undefined Symbols in Your Chart . . . . . . . . . . . . 28-32


Search for Undefined Symbols . . . . . . . . . . . . . . . . . . . . . . 28-32
Resolve Undefined Data in the Symbols Window . . . . . . . . 28-33
Define Chart Symbols with the Symbol Wizard . . . . . . . . . 28-33
Rules for Inferring the Scope of Unresolved Symbols . . . . . 28-34
Inference of Size, Type, and Complexity . . . . . . . . . . . . . . 28-35

Traceability of Stateflow Objects in Generated Code . . . . 28-37

xxxviii Contents
Call Extrinsic Functions in a Stateflow Chart . . . . . . . . . . 28-38

Debug and Test Stateflow Charts


29
Basic Approach to Debugging Charts . . . . . . . . . . . . . . . . . . 29-2

Animate Stateflow Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-3


Set Animation Speeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-3
Maintain Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-3
Disable Animation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-3
Animate Stateflow Charts as Generated Code Executes on a
Target System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-4

Set Breakpoints to Debug Charts . . . . . . . . . . . . . . . . . . . . . 29-5


Types of Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-5
Set a Breakpoint for a Stateflow Object . . . . . . . . . . . . . . . 29-7
Visual Indication of Execution at Breakpoints . . . . . . . . . . . 29-8

Manage Stateflow Breakpoints and Watch Data . . . . . . . . 29-12


Set Conditions on Breakpoints . . . . . . . . . . . . . . . . . . . . . 29-12
Disable and Enable Breakpoints . . . . . . . . . . . . . . . . . . . . 29-15
View Breakpoint Hits . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-16
Clear Breakpoints and Watch Data . . . . . . . . . . . . . . . . . . 29-16
Format Watch Display . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-17
Save and Restore Breakpoints and Watch Data . . . . . . . . . 29-18

Control Chart Execution from the Stateflow Editor . . . . . 29-19

Debug Run-Time Errors in a Chart . . . . . . . . . . . . . . . . . . . 29-21


Create the Model and the Stateflow Chart . . . . . . . . . . . . 29-21
Debug the Stateflow Chart . . . . . . . . . . . . . . . . . . . . . . . . 29-23
Correct the Run-Time Error . . . . . . . . . . . . . . . . . . . . . . . 29-23

Common Modeling Errors Stateflow Can Detect . . . . . . . . 29-25


State Inconsistencies in a Chart . . . . . . . . . . . . . . . . . . . . 29-25
Conflicting Transitions in a Chart . . . . . . . . . . . . . . . . . . . 29-26
Data Range Violations in a Chart . . . . . . . . . . . . . . . . . . . 29-28
Cyclic Behavior in a Chart . . . . . . . . . . . . . . . . . . . . . . . . 29-29

xxxix
Guidelines for Avoiding Unwanted Recursion in a Chart . 29-33

Watch Stateflow Data Values . . . . . . . . . . . . . . . . . . . . . . . . 29-35


Watch Data in the Stateflow Breakpoints and Watch
Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-35
Watch Data in the Stateflow Chart . . . . . . . . . . . . . . . . . . 29-35
Watch Stateflow Data in the MATLAB Command Window 29-37

Change Data Values During Simulation . . . . . . . . . . . . . . . 29-39


How to Change Values of Stateflow Data . . . . . . . . . . . . . 29-39
Examples of Changing Data Values . . . . . . . . . . . . . . . . . 29-39
Limitations on Changing Data Values . . . . . . . . . . . . . . . . 29-42

Monitor Test Points in Stateflow Charts . . . . . . . . . . . . . . 29-44


About Test Points in Stateflow Charts . . . . . . . . . . . . . . . 29-44
Set Test Points for Stateflow States and Data with the Model
Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-44
Monitor Data Values and State Self Activity Using a Floating
Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-46

What You Can Log During Chart Simulation . . . . . . . . . . . 29-50


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-50

Basic Approach to Logging States and Data . . . . . . . . . . . 29-51

Enable Signal Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-52

Configure States and Data for Logging . . . . . . . . . . . . . . . 29-53


Properties to Configure for Logging . . . . . . . . . . . . . . . . . . 29-53
Choose a Configuration Method for Logging . . . . . . . . . . . 29-53
Log Individual States and Data . . . . . . . . . . . . . . . . . . . . 29-54
Log Multiple Signals At Once . . . . . . . . . . . . . . . . . . . . . . 29-54
Log Chart Signals Using the Command-Line API . . . . . . . 29-55

Access Signal Logging Data . . . . . . . . . . . . . . . . . . . . . . . . . 29-57


Signal Logging Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-57
Access Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-57

View Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-61

Log Data in Library Charts . . . . . . . . . . . . . . . . . . . . . . . . . 29-62


How Library Log Settings Influence Linked Instances . . . . 29-62
Override Logging Properties in Chart Instances . . . . . . . . 29-62

xl Contents
Override Logging Properties in Atomic Subcharts . . . . . . . 29-62

How Stateflow Logs Multidimensional Data . . . . . . . . . . . 29-67

Limitations on Logging Data . . . . . . . . . . . . . . . . . . . . . . . . 29-68

Commenting Stateflow Objects in a Chart . . . . . . . . . . . . . 29-69


Comment Out a Stateflow Object . . . . . . . . . . . . . . . . . . . 29-69
How Commenting Affects the Chart and Model . . . . . . . . . 29-69
Add Text to a Commented Object . . . . . . . . . . . . . . . . . . . 29-71
Limitations on Commenting Objects . . . . . . . . . . . . . . . . . 29-71

Explore and Modify Charts


30
Manage Stateflow Data, Events, and Messages in the Symbols
Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-2

Add and Modify Data, Events, and Messages in the Symbols


Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-5
Symbols Window Limitations . . . . . . . . . . . . . . . . . . . . . . . 30-5

Trace Data, Events, and Messages with the Symbols


Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-7

Use the Model Explorer with Stateflow Objects . . . . . . . . 30-10


View Stateflow Objects in the Model Explorer . . . . . . . . . . 30-10
Edit Chart Objects in the Model Explorer . . . . . . . . . . . . . 30-11
Add Data and Events in the Model Explorer . . . . . . . . . . . 30-11
Rename Objects in the Model Explorer . . . . . . . . . . . . . . . 30-12
Set Properties for Chart Objects in the Model Explorer . . . 30-12
Move and Copy Data and Events in the Model Explorer . . 30-13
Change the Port Order of Input and Output Data and
Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-14
Delete Data and Events in the Model Explorer . . . . . . . . . 30-14

Use the Search & Replace Tool . . . . . . . . . . . . . . . . . . . . . . 30-15


Open the Search & Replace Tool . . . . . . . . . . . . . . . . . . . . 30-15
Refine Searches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-17
Specify the Search Scope . . . . . . . . . . . . . . . . . . . . . . . . . . 30-19

xli
Use the Search Button and View Area . . . . . . . . . . . . . . . 30-20
Specify the Replacement Text . . . . . . . . . . . . . . . . . . . . . . 30-23
Use Replace Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-24
Search and Replace Messages . . . . . . . . . . . . . . . . . . . . . . 30-24

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

Semantic Examples
B
Categories of Semantic Examples . . . . . . . . . . . . . . . . . . . . . . B-2

Transition to and from Exclusive (OR) States . . . . . . . . . . . . B-4


Label Format for a State-to-State Transition . . . . . . . . . . . . B-4
Transition from State to State with Events . . . . . . . . . . . . . B-5
Transition from a Substate to a Substate with Events . . . . . B-8

Control Chart Execution Using Condition Actions . . . . . . . B-10


Condition Action Behavior . . . . . . . . . . . . . . . . . . . . . . . . . B-10
Condition and Transition Action Behavior . . . . . . . . . . . . . B-11
Create Condition Actions Using a For-Loop . . . . . . . . . . . . B-13
Broadcast Events to Parallel (AND) States Using Condition
Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-14
Avoid Cyclic Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-15

Control Chart Execution Using Default Transitions . . . . . B-17


Default Transition in Exclusive (OR) Decomposition . . . . . . B-17

xlii Contents
Default Transition to a Junction . . . . . . . . . . . . . . . . . . . . . B-18
Default Transition and a History Junction . . . . . . . . . . . . . B-19
Labeled Default Transitions . . . . . . . . . . . . . . . . . . . . . . . . B-20

Process Events Using Inner Transitions . . . . . . . . . . . . . . . B-23


Process Events with an Inner Transition in an Exclusive (OR)
State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-23
Process Events with an Inner Transition to a Connective
Junction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-26
Inner Transition to a History Junction . . . . . . . . . . . . . . . . B-28

Use Connective Junctions to Represent Multiple Paths . . B-30


Label Format for Transition Segments . . . . . . . . . . . . . . . . B-30
If-Then-Else Decision Construct . . . . . . . . . . . . . . . . . . . . . B-31
Self-Loop Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-32
For-Loop Construct . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-33
Flow Chart Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-35
Transition from a Common Source to Multiple Destinations B-36
Transition from Multiple Sources to a Common Destination B-37
Transition from a Source to a Destination Based on a Common
Event . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-38
Backtrack in Flow Charts . . . . . . . . . . . . . . . . . . . . . . . . . . B-39

Control Chart Execution Using Event Actions in a


Superstate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-41

Broadcast Events in Parallel (AND) States . . . . . . . . . . . . . B-42


Broadcast Events in Parallel States . . . . . . . . . . . . . . . . . . B-42
Broadcast Events in a Transition Action with a Nested Event
Broadcast . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . B-45
Broadcast Condition Action Event in Parallel State . . . . . . B-48

Directly Broadcast Events . . . . . . . . . . . . . . . . . . . . . . . . . . . B-52


Directed Event Broadcast Using Send . . . . . . . . . . . . . . . . B-52
Directed Event Broadcast Using Qualified Event Name . . . B-53

Glossary

xliii
1

Stateflow Chart Concepts

Finite State Machine Concepts on page 1-2


Stateflow Charts and Simulink Models on page 1-4
Stateflow Chart Objects on page 1-6
Stateflow Hierarchy of Objects on page 1-8
Bibliography on page 1-10
1 Stateflow Chart Concepts

Finite State Machine Concepts


In this section...
What Is a Finite State Machine? on page 1-2
Finite State Machine Representations on page 1-2
Stateflow Chart Representations on page 1-2
Notation on page 1-3
Semantics on page 1-3

What Is a Finite State Machine?


Stateflow charts can contain sequential decision logic based on state machines. A finite
state machine is a representation of an event-driven (reactive) system. In an event-driven
system, the system makes a transition from one state (mode) to another, if the condition
defining the change is true.

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.

Finite State Machine Representations


Traditionally, designers used truth tables to represent relationships among the inputs,
outputs, and states of a finite state machine. The resulting table describes the logic
necessary to control the behavior of the system under study. Another approach to
designing event-driven systems is to model the behavior of the system by describing it
in terms of transitions among states. The occurrence of events under certain conditions
determine the state that is active. State-transition charts and bubble charts are
graphical representations based on this approach.

Stateflow Chart Representations


A Stateflow chart can contain sequential and combinatorial logic in the form of state
transition diagrams, flow charts, state transition tables, and truth tables. A state
transition diagram is a graphical representation of a finite state machine. States and

1-2
Finite State Machine Concepts

transitions form the basic building blocks of a sequential logic system. Another way to
represent sequential logic is a state transition table, which allows you to enter the state
logic in tabular form. You can also represent combinatorial logic in a chart with flow
charts and truth tables.

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 [1].
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.

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.

Stateflow chart notation consists of these elements:

A set of graphical objects


A set of nongraphical text-based objects
Defined relationships between those objects

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.

1-3
1 Stateflow Chart Concepts

Stateflow Charts and Simulink Models


In this section...
The Simulink Model and the Stateflow Machine on page 1-4
Overview of Defining Stateflow Block Interfaces to Simulink Models on page 1-4

The Simulink Model and the Stateflow Machine


A Stateflow chart functions as a finite state machine within a Simulink model. The
Stateflow machine is the collection of Stateflow blocks in a Simulink model. The
Simulink model and the Stateflow machine work seamlessly together. Running a
simulation automatically executes both the Simulink blocks and the Stateflow charts of
the model.

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 Stateflow
Hierarchy of Objects on page 1-8.

Overview of Defining Stateflow Block Interfaces to Simulink Models


Each Stateflow block corresponds to a single Stateflow chart. The Stateflow block
interfaces to its Simulink model. The Stateflow block can interface to code sources
external to the Simulink model (data, events, custom code).

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:

Defining the Stateflow block update method

1-4
Stateflow Charts and Simulink Models

Defining Output to Simulink events


Adding and defining nonlocal events and nonlocal data within the Stateflow chart
Defining relationships with any external sources

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

Stateflow Chart Objects


Stateflow charts consist of graphical and nongraphical objects:

1-6
Stateflow Chart Objects

To learn how these objects interact, see How Chart Constructs Interact During
Execution on page 3-8.

1-7
1 Stateflow Chart Concepts

Stateflow Hierarchy of Objects


Stateflow machines arrange Stateflow objects in a hierarchy based on containment. That
is, one Stateflow object can contain other 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-8
Stateflow Hierarchy of Objects

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.

You can organize complex charts by defining a containment structure. A hierarchical


design usually reduces the number of transitions and produces neat, manageable charts.

To manage graphical objects, use the Stateflow Editor.


To manage nongraphical objects, use the Symbols window or Model Explorer.

1-9
1 Stateflow Chart Concepts

Bibliography
[1] Hatley, D. J. and I. A. Pirbhai. Strategies for Real-Time System Specification. New
York, NY: Dorset House Publishing, 1988.

1-10
2

Stateflow Chart Notation

Overview of Stateflow Objects on page 2-2


Rules for Naming Stateflow Objects on page 2-4
States on page 2-7
State Hierarchy on page 2-15
State Decomposition on page 2-17
Transitions on page 2-19
Transition Connections on page 2-24
Self-Loop Transitions on page 2-28
Inner Transitions on page 2-30
Default Transitions on page 2-35
Connective Junctions on page 2-40
History Junctions on page 2-46
Boxes on page 2-48
When to Use Reusable Functions in Charts on page 2-49
2 Stateflow Chart Notation

Overview of Stateflow Objects

In this section...
Graphical Objects on page 2-2
Nongraphical Objects on page 2-3

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.

Type of Graphical Object Toolbar Icon


State

Transition Not applicable


History junction

Default transition

Connective junction

Truth table function

Graphical function

MATLAB function

Box

Simulink function

2-2
Overview of Stateflow Objects

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

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.

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 Message Viewer block. For more information, see
How Messages Work in Stateflow Charts on page 10-2.

2-3
2 Stateflow Chart Notation

Rules for Naming Stateflow Objects


In this section...
Characters You Can Use on page 2-4
Restriction on Name Length on page 2-4
Keywords to Avoid When Naming Chart Objects on page 2-4

Characters You Can Use


You can name Stateflow objects with any combination of alphanumeric and underscore
characters. Names cannot begin with a numeric character or contain embedded spaces.

Restriction on Name Length


Name length should comply with the maximum identifier length enforced by Simulink
Coder software. You can set the Maximum identifier length parameter in the
All Parameters tab of the Configuration Parameters dialog box. The default is 31
characters and the maximum length you can specify is 256 characters.

Keywords to Avoid When Naming Chart Objects


You cannot use reserved keywords to name chart objects. These keywords are part of the
action language syntax.

Usage in Action Language Syntax Keywords Syntax References


Boolean symbols true Boolean Symbols, true and
false false on page 11-27

Change detection hasChanged Detect Changes in Data Values


hasChangedFrom on page 11-74

hasChangedTo
Complex data complex Define Complex Data Using
imag Operators on page 21-9

real

2-4
Rules for Naming Stateflow Objects

Usage in Action Language Syntax Keywords Syntax References


Data types boolean Set Data Properties on page
double 8-6

int8
int16
int32
single
uint8
uint16
uint32
Data type operations cast Type Cast Operations on page
fixdt 11-24

type
Explicit events send Broadcast Events to
Synchronize States on page
11-52
Implicit events change Control Chart Execution
chg Using Implicit Events on page
9-33
tick
wakeup
Messages send Stateflow Message Syntax in
forward Charts on page 10-11

discard
isvalid
length
receive
Literal symbols inf Supported Symbols in Actions
t (C charts only) on page 11-27

MATLAB functions and data matlab ml Namespace Operator on


ml page 11-38

2-5
2 Stateflow Chart Notation

Usage in Action Language Syntax Keywords Syntax References


State actions bind State Action Types on page
du 11-2

during
en
entry
ex
exit
on
State activity in Check State Activity on page
11-86
Temporal logic after Control Chart Execution
at Using Temporal Logic on page
11-56
before
every
sec
msec
usec
temporalCount
elapsed
t
duration

2-6
States

States

In this section...
What Is a State? on page 2-7
State Hierarchy on page 2-7
State Decomposition on page 2-9
State Labels on page 2-10

What Is a State?
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.

State Hierarchy Example

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.

2-7
2 Stateflow Chart Notation

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
/Car_done.Car_made.Parts_assembled
/Car_done.Car_made.Painted

Objects That a State Can Contain

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.

2-8
States

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

Exclusive (OR) State Decomposition

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.

Parallel (AND) State Decomposition

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.

2-9
2 Stateflow Chart Notation

The activity within parallel states is essentially independent, as demonstrated in the


following example.

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.

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

2-10
States

exit:exit actions
on event_name:on event_name actions
on message_name:on message_name actions
bind:events

The following example demonstrates the components of a state label.

Each action in the state label appears in the subtopics that follow. For more information
on state actions, see:

Process for Entering, Executing, and Exiting States on page 3-74 Describes
how and when entry, during, exit, and on event_name actions occur.
State Action Types on page 11-2 Gives more detailed descriptions of each
type of state action.

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.

2-11
2 Stateflow Chart Notation

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.

The following example shows how unique naming of states works.

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

2-12
States

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
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 on event_name, or on message_name. In the preceding label


example, state On has an on power_outage action. If state On is active and the event
power_outage occurs, the action handle_outage() is executed.

2-13
2 Stateflow Chart Notation

Bind Action

Preceded by the prefix bind. Events bound to a state can only be broadcast by that state
or its children.

2-14
State Hierarchy

State Hierarchy
In this section...
State Hierarchy Example on page 2-15
Objects That a State Can Contain on page 2-16

To manage multilevel state complexity, use hierarchy in your Stateflow chart. With
hierarchy, you can represent multiple levels of subcomponents in a system.

State Hierarchy Example


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.

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

2-15
2 Stateflow Chart Notation

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

Objects That a State Can Contain


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.

2-16
State Decomposition

State Decomposition
In this section...
Exclusive (OR) State Decomposition on page 2-17
Parallel (AND) State Decomposition on page 2-17

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

Exclusive (OR) State Decomposition


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.

Parallel (AND) State Decomposition


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.

2-17
2 Stateflow Chart Notation

In the following example, when state A is active, A1 and A2 are both active at the same
time.

The activity within parallel states is essentially independent, as demonstrated in the


following example.

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

Transitions

In this section...
What Is a Transition? on page 2-19
Transition Hierarchy on page 2-20
Transition Label Notation on page 2-21
Valid Transitions on page 2-23

What Is a Transition?
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)
object 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-19
2 Stateflow Chart Notation

A default transition is a special type of transition that has no source object. See Default
Transitions on page 2-35 for details.

Transition Hierarchy
Transitions cannot contain other objects the way that states can. However, transitions
are contained by states. A transition's hierarchy is described in terms of the transition's
parent, source, and destination. The parent is the lowest level that contains the source
and destination of the transition. Consider the parents for the transitions in the following
example:

2-20
Transitions

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.

Transition Label Transition Parent Transition Source Transition Destination


switch_off / /Power_on.Low.Heat /Power_off
switch_high /Power_on /Power_on.Low.Heat /Power_on.High
switch_cold /Power_on.Low /Power_on.Low.Heat /Power_on.Low.Cold

Transition Label Notation


A transition is characterized by its label. The label can consist of an event, a message,
a condition, a condition action, and/or a transition action. The ? character is the default
transition label. Transition labels have the following general format:

event_or_message[condition]{condition_action}/transition_action

Each part of the label is optional.

Transition Label Example

Use the following example to understand the parts of a transition label.

2-21
2 Stateflow Chart Notation

Event Trigger

Specifies an event that causes the transition to be taken, provided the condition, if
specified, is true. Specifying an event is optional. The absence of an event or message
indicates that the transition is taken upon the occurrence of any event. Specify multiple
events using the OR logical operator (|).

In the preceding example, the broadcast of event E triggers the transition from On to Off
as long as the condition [off_count==0] is true.
Condition

Specifies a Boolean expression that, when true, validates a transition to be taken for the
specified event or message trigger. Enclose the condition in square brackets ([]). See
Conditions on page 11-10 for information on the condition notation.

In the preceding example, the condition [off_count==0] must evaluate as true for the
condition action to be executed and for the transition from the source to the destination
to be valid.
Condition Action

Follows the condition for a transition and is enclosed in curly braces ({}). It is executed
as soon as the condition is evaluated as true and before the transition destination has
been determined to be valid. If no condition is specified, an implied condition evaluates to
true and the condition action is executed.

In the preceding example, if the condition [off_count==0] is true, the condition action
off_count = off_count + 1; is immediately executed.

2-22
Transitions

Transition Action

Executes after the transition destination has been determined to be valid provided
the condition, if specified, is true. If the transition consists of multiple segments, the
transition action is only executed when the entire transition path to the final destination
is determined to be valid. Precede the transition action with a /.

In the preceding example, if the condition [off_count==0] is true, and the destination
state Off is valid, the transition action Light_off is executed.

Valid Transitions
In most cases, a transition is valid when the source state of the transition is active and
the transition label is valid. Default transitions are 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.

Transition Label Is Valid If...


Event only That event occurs
Event and condition That event occurs and the condition is true
Message only That message occurs
Message and condition That mgssage occurs and the condition is true
Condition only Any event occurs and the condition is true
Action only Any event occurs
Not specified Any event occurs

2-23
2 Stateflow Chart Notation

Transition Connections
In this section...
Transitions to and from Exclusive (OR) States on page 2-24
Transitions to and from Junctions on page 2-24
Transitions to and from Exclusive (OR) Superstates on page 2-25
Transitions to and from Substates on page 2-26

Transitions to and from Exclusive (OR) States


This example shows simple transitions to and from exclusive (OR) states.

The following transition... Is valid when...


B to A State B is active and the event E1 occurs.
A1 to A2 State A1 is active and event E2 occurs.

See Transition to and from Exclusive (OR) States on page B-4 for more
information on the semantics of this notation.

Transitions to and from Junctions


The following chart shows transitions to and from connective junctions.

2-24
Transition Connections

The chart uses temporal logic to determine when the input u equals 1.

If the input equals 1... A transition occurs from...


Before t = 2 Start to Fast
Between t = 2 and t = 5 Start to Good
After t = 5 Start to Slow

For more information about temporal logic, see Control Chart Execution Using
Temporal Logic on page 11-56. For more information on the semantics of this
notation, see Transition from a Common Source to Multiple Destinations on page
B-36.

Transitions to and from Exclusive (OR) Superstates


This example shows transitions to and from an exclusive (OR) superstate and the use of a
default transition.

2-25
2 Stateflow Chart Notation

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.

For more information on the semantics of this notation, see Control Chart Execution
Using Default Transitions on page B-17.

Transitions to and from Substates


The following example shows transitions to and from exclusive (OR) substates.

2-26
Transition Connections

For details on how this chart works, see Key Behaviors of Debouncer Chart on page
24-3. For information on the semantics of this notation, see Transition from a
Substate to a Substate with Events on page B-8.

2-27
2 Stateflow Chart Notation

Self-Loop Transitions
A transition that originates from and terminates on the same state is a self-loop
transition. The following chart contains four self-loop transitions:

See these sections for more information about the semantics of this notation:

Self-Loop Transition on page B-32

2-28
Self-Loop Transitions

For-Loop Construct on page B-33

2-29
2 Stateflow Chart Notation

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:

Before Using an Inner Transition on page 2-30


After Using an Inner Transition to a Connective Junction on page 2-32
Using an Inner Transition to a History Junction on page 2-33

Before Using an Inner Transition


This chart is an example of how you can simplify logic using an inner transition.

2-30
Inner Transitions

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]

2-31
2 Stateflow Chart Notation

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

After Using an Inner Transition to a Connective Junction


This example simplifies the preceding example using an inner transition to a connective
junction.

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.

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:

2-32
Inner Transitions

1 Exit actions for A1 execute and complete.


2 A1 becomes inactive.
3 A1 becomes active.
4 Entry actions for A1 execute and complete.

See Process the First Event with an Inner Transition to a Connective Junction on page
B-26 for more information on the semantics of this notation.

Using an Inner Transition to a History Junction


This example shows an inner transition to a history junction.

State Power_on.High is initially active. When event Reset occurs, the inner transition
to the history junction is valid. Because the inner transition is valid, the currently active
state, Power_on.High, is exited. When the inner transition to the history junction
is processed, the last active state, Power_on.High, becomes active (is reentered). If
Power_on.Low was active under the same circumstances, Power_on.Low would be
exited and reentered as a result. The inner transition in this example is equivalent to
drawing an outer self-loop transition on both Power_on.Low and Power_on.High.

2-33
2 Stateflow Chart Notation

See Use of History Junctions Example on page 2-46 for another example using a
history junction.

See Inner Transition to a History Junction on page B-28 for more information on
the semantics of this notation.

2-34
Default Transitions

Default Transitions

In this section...
What Is a Default Transition? on page 2-35
Drawing Default Transitions on page 2-35
Label Default Transitions on page 2-35
Default Transition Examples on page 2-36

What Is a Default Transition?


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.

Drawing Default Transitions


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 the mouse to the destination object to attach the default transition. In
some cases, it is useful to label default transitions.

A common programming mistake is to create multiple exclusive (OR) states without a


default transition. In the absence of the default transition, there is no indication of which
state becomes active by default. Note that this error is flagged when you simulate the
model with the State Inconsistencies option enabled.

Label Default Transitions


You can label default transitions as you would other transitions. For example, you might
want to specify that one state or another should become active depending upon the event
that has occurred. In another situation, you might want to have specific actions take
place that are dependent upon the destination of the transition.

2-35
2 Stateflow Chart Notation

Tip: When labeling default transitions, ensure that there is at least one valid default
transition. Otherwise, a chart can transition into an inconsistent state.

Default Transition Examples


The following examples show the use of default transitions in Stateflow charts:

Default Transition to a State Example on page 2-36


Default Transition to a Junction Example on page 2-37
Default Transition with a Label Example on page 2-38

Default Transition to a State Example

This example shows a default transition to a state.

2-36
Default Transitions

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 Using Default Transitions on page B-17 for
information on the semantics of this notation.

Default Transition to a Junction Example

This example shows a default transition to a connective junction.

2-37
2 Stateflow Chart Notation

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-18 for information on the semantics
of this notation.

Default Transition with a Label Example

This example shows a default transition with a label.

2-38
Default Transitions

When the chart wakes up, the data p and v initialize to 10 and 15, respectively.

See Labeled Default Transitions on page B-20 for more information on the
semantics of this notation.

2-39
2 Stateflow Chart Notation

Connective Junctions
In this section...
What Is a Connective Junction? on page 2-40
Flow Chart Notation with Connective Junctions on page 2-40

What Is a Connective Junction?


The connective junction enables representation of different possible transition paths for a
single transition. Connective junctions are used to help represent the following:

Variations of an if-then-else decision construct, by specifying conditions on some


or all of the outgoing transitions from the connective junction
A self-loop transition back to the source state if none of the outgoing transitions is
valid
Variations of a for loop construct, by having a self-loop transition from the connective
junction back to itself
Transitions from a common source to multiple destinations
Transitions from multiple sources to a common destination
Transitions from a source to a destination based on common events

Note: An event cannot trigger a transition from a connective junction to a destination


state.

See Use Connective Junctions to Represent Multiple Paths on page B-30 for a
summary of the semantics of connective junctions.

Flow Chart Notation with Connective Junctions


Flow chart notation uses connective junctions to represent common code structures like
for loops and if-then-else constructs without the use of states. And by reducing
the number of states in your Stateflow charts, flow chart notation produces efficient
simulation and generated code that helps optimize memory use.

Flow chart notation uses combinations of the following:

2-40
Connective Junctions

Transitions to and from connective junctions


Self-loops to connective junctions
Inner transitions to 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.

Connective Junction with All Conditions Specified Example

2-41
2 Stateflow Chart Notation

A transition from the Front_desk state to a connective junction is labeled by the


check_in event. Transitions from the connective junction to the destination states are
labeled with conditions. If Front_desk is active when check_in occurs, the transition
from Front_desk to the connective junction occurs first. The transition from the
connective junction to a destination state depends on which of the room_type conditions
is true. If none of the conditions is true, no transition occurs and Front_desk remains
active.

For more information about this chart, see Phases of Chart Execution on page 3-13.
For more information on the semantics of this notation, see If-Then-Else Decision
Construct on page B-31.

Connective Junction with One Unconditional Transition Example

The chart uses temporal logic to determine when the input u equals 1.

If the input equals 1... A transition occurs from...


Before t = 2 Start to Fast
Between t = 2 and t = 5 Start to Good
After t = 5 Start to Slow

For more information about temporal logic, see Control Chart Execution Using
Temporal Logic on page 11-56. For more information on the semantics of this
notation, see If-Then-Else Decision Construct on page B-31.

Connective Junction and For Loops Example

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

2-42
Connective Junctions

chart uses implicit ordering of outgoing transitions (see Implicit Ordering of Outgoing
Transitions on page 3-64).

See For-Loop Construct on page B-33 for information on the semantics of this
notation.

Flow Chart Notation Example

This example shows the use of flow chart notation. The chart uses implicit ordering of
outgoing transitions (see Implicit Ordering of Outgoing Transitions on page 3-64).

2-43
2 Stateflow Chart Notation

See Flow Chart Notation on page B-35 for information on the semantics of this
notation.

Connective Junction from a Common Source to Multiple Destinations Example

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 of Outgoing Transitions on page 3-64).

2-44
Connective Junctions

See Transition from a Common Source to Multiple Destinations on page B-36 for
information on the semantics of this notation.

Connective Junction Common Events Example

This example shows transition segments from multiple sources to a single destination
based on the same event using a connective junction.

See Transition from a Source to a Destination Based on a Common Event on page


B-38 for information on the semantics of this notation.

2-45
2 Stateflow Chart Notation

History Junctions
In this section...
What Is a History Junction? on page 2-46
History Junctions and Inner Transitions on page 2-47

What Is a History Junction?


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.

Use of History Junctions Example

The following example uses a history junction:

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

2-46
History Junctions

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-19 for more information
on the semantics of this notation.

History Junctions and Inner Transitions


By specifying an inner transition to a history junction, you can specify that, based on
a specified event or condition, the active state is to be exited and then immediately
reentered.

See Using an Inner Transition to a History Junction on page 2-33 for an example of this
notation.

See Inner Transition to a History Junction on page B-28 for more information on
the semantics of this notation.

2-47
2 Stateflow Chart Notation

Boxes
In this section...
What Is a Box? on page 2-48
Example of Using a Box on page 2-48

What Is a Box?
A box is a graphical object that organizes other objects in your chart, such as functions
and states.

Example of Using a Box


In this example, the box Heater groups together related states Off and On.

For rules of using boxes and other examples, see Group Chart Objects Using Boxes on
page 7-41.

2-48
When to Use Reusable Functions in Charts

When to Use Reusable Functions in Charts


State actions and transition conditions can be complicated enough that defining them
inline on the state or transition is not feasible. In this case, express the conditions or
actions using one of the following types of Stateflow functions:

Flow chart Encapsulate flow charts containing if-then-else, switch-case, for, while,
or do-while patterns.
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 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 Share Data Using Custom C Code on page 28-25.

2-49
3

Stateflow Chart Semantics

What Do Semantics Mean for Stateflow Charts? on page 3-2


How Chart Constructs Interact During Execution on page 3-8
Modeling Guidelines for Stateflow Charts on page 3-32
Modeling Rules That Stateflow Detects During Edit Time on page 3-34
How Events Drive Chart Execution on page 3-43
Types of Chart Execution on page 3-46
Process for Grouping and Executing Transitions on page 3-57
Evaluation Order for Outgoing Transitions on page 3-60
Process for Entering, Executing, and Exiting States on page 3-74
Execution Order for Parallel States on page 3-78
Early Return Logic for Event Broadcasts on page 3-85
3 Stateflow Chart Semantics

What Do Semantics Mean for Stateflow Charts?


In this section...
What Are Chart Semantics? on page 3-2
Common Graphical and Nongraphical Constructs on page 3-3
References for Chart Semantics on page 3-7

What Are Chart Semantics?


Chart semantics describe execution behavior according to the interaction of graphical and
nongraphical constructs.

Graphical Constructs

Graphical constructs consist of objects that appear graphically in a chart. You use the
object palette in the Stateflow Editor to build graphical constructs (see Stateflow Editor
Operations on page 4-26).

Graphical Constructs Types References


Flow charts Decision logic patterns What Is a Flow Chart? on page
Loop logic patterns 5-2

Functions Graphical functions What Is a Graphical Function?


MATLAB functions on page 7-32

Truth table functions MATLAB Functions in a


Stateflow Chart on page
Simulink functions 26-5
What Is a Truth Table? on
page 25-2
Simulink Functions in
Stateflow on page 27-2
Junctions Connective junctions Connective Junctions on page
History junctions 2-40
History Junctions on page 2-46
States States with exclusive (OR) Exclusive (OR) State
decomposition Decomposition on page 2-9

3-2
What Do Semantics Mean for Stateflow Charts?

Graphical Constructs Types References


States with parallel (AND) Parallel (AND) State
decomposition Decomposition on page 2-9
Substates and superstates Create Substates and
Superstates on page 4-6
Transitions Default transitions Default Transitions on page
Object-to-object transitions 2-35

Inner transitions Transition Connections on


page 2-24
Self-loop transitions

Nongraphical Constructs

Nongraphical constructs appear textually in a chart and often refer to data, events, and
messages. See Add Stateflow Data on page 8-2 ,Define Events on page 9-5,
and Define Messages in a Stateflow Chart on page 10-25 for details. Examples of
nongraphical constructs include:

Conditions and condition actions


Function calls
State actions
Temporal logic statements

Common Graphical and Nongraphical Constructs


The following chart shows commonly used graphical and nongraphical constructs.

3-3
3 Stateflow Chart Semantics

Chart Construct Graphical or Description Reference


Nongraphical?
Condition Nongraphical Boolean expression Transition Label
that specifies that Notation on page 2-21
a transition path is and Conditions on
valid if the expression page 11-10
is true; part of a
transition label
Condition action Nongraphical Action that executes as Transition Label
soon as the condition Notation on page 2-21
evaluates to true; part and Condition Actions
of a transition label on page 11-11
Connective junction Graphical Object that enables Connective Junctions
representation of on page 2-40
different possible
transition paths in a
flow chart
Default transition Graphical Object that specifies Default Transitions
which state to enter on page 2-35
when two or more
exclusive (OR) states
exist at the same level
of hierarchy

3-4
What Do Semantics Mean for Stateflow Charts?

Chart Construct Graphical or Description Reference


Nongraphical?
Flow chart Graphical Construct that models What Is a Flow
logic patterns by using Chart? on page
connective junctions 5-2
and transitions
History junction Graphical Object that remembers History Junctions on
the previously active page 2-46
state at the level of
hierarchy in which it
appears
MATLAB function Graphical Method of performing MATLAB Functions
computations using a in a Chart on page
subset of the MATLAB 26-2
language
State actions Nongraphical Expressions that State Labels on
specify actions to take page 2-10 and State
when a state is active, Action Types on page
such as initializing or 11-2
updating data; part of a
state label
State with exclusive Graphical State where no more Exclusive (OR) State
(OR) decomposition than one substate can Decomposition on page
be active at a time 2-9
State with parallel Graphical State where all Parallel (AND) State
(AND) decomposition substates can be active Decomposition on page
at the same time 2-9
Substate Graphical State that resides Create Substates and
inside another state Superstates on page
4-6
Superstate Graphical State that contains one Create Substates and
or more states Superstates on page
4-6

3-5
3 Stateflow Chart Semantics

Chart Construct Graphical or Description Reference


Nongraphical?
Transition guarded by Graphical Decision path that Transition Action
input event occurs if the chart Types on page
receives a specific event 11-8
broadcast from another
block in the model

For details on how these graphical and nongraphical constructs interact during chart
execution, see How Chart Constructs Interact During Execution on page 3-8.

3-6
What Do Semantics Mean for Stateflow Charts?

References for Chart Semantics


For detailed information on types of chart semantics, see these references.

Topic Reference
How do events affect chart execution? How Events Drive Chart Execution on page
3-43
How does a chart switch between being active Types of Chart Execution on page 3-46
and inactive?
In what order do flow charts execute? Process for Grouping and Executing
Transitions on page 3-57
In what order do outgoing transitions from a Evaluation Order for Outgoing Transitions on
single source execute? page 3-60
What happens when you enter, execute, or exit a Process for Entering, Executing, and Exiting
state? States on page 3-74
How do parallel (AND) states work? Execution Order for Parallel States on page
3-78
How does early return logic affect chart Early Return Logic for Event Broadcasts on
execution? page 3-85

For detailed examples of chart semantics, see AppendixB.

3-7
3 Stateflow Chart Semantics

How Chart Constructs Interact During Execution

In this section...
Overview of the Example Model on page 3-8
Model of the Check-In Process for a Hotel on page 3-8
How the Chart Interacts with Simulink Blocks on page 3-12
Phases of Chart Execution on page 3-13

Overview of the Example Model


The example model shows how common graphical and nongraphical constructs in a chart
interact during execution. These constructs include:

Conditions and condition actions


Exclusive (OR) states
Flow charts
Function calls
History junctions
Parallel (AND) states
State actions
Transitions guarded by input events

For details of the chart semantics, see Phases of Chart Execution on page 3-13.

Model of the Check-In Process for a Hotel


This example uses the hotel check-in process to explain Stateflow chart semantics.
To open the model, type sf_semantics_hotel_checkin at the MATLAB command
prompt.

The model consists of four Manual Switch blocks, one Mux block, one Multiport Switch
block, a Hotel chart, and a Display block.

3-8
How Chart Constructs Interact During Execution

The model uses this To... Because...


block...
Manual Switch Enable toggling between two settings During simulation, you can
during simulation without having to interactively trigger the chart by
pause or restart. sending one of these input events:

Checking in to a hotel
Calling room service
Triggering a fire alarm
Sending an all-clear signal after a
fire alarm

3-9
3 Stateflow Chart Semantics

The model uses this To... Because...


block...
Mux Combine multiple input signals into a A chart can support multiple input
vector. events only if they connect to the
trigger port of a chart as a vector of
inputs.
Multiport Switch Enable selection among more than two This block provides a value for the
inputs. chart input data room_type, where
each room type corresponds to a
number (1, 2, or 3).

A Manual Switch block cannot support


more than two inputs, but a Multiport
Switch block can.
Display Show up-to-date numerical value for During simulation, any change to the
input signal. chart output data fee appears in the
display.

The Hotel chart contains graphical constructs, such as states and history junctions, and
nongraphical constructs, such as conditions and condition actions.

3-10
How Chart Constructs Interact During Execution

For a mapping of constructs to their locations in the chart, see Common Graphical and
Nongraphical Constructs on page 3-3.

3-11
3 Stateflow Chart Semantics

How the Chart Interacts with Simulink Blocks


Chart Initialization

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

Chart Interaction with Other Blocks

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-12
How Chart Constructs Interact During Execution

Phases of Chart Execution


The following sections explain chart execution for each shaded region of the Hotel chart.

Phase: Chart Initialization

This section describes what happens in the Front_desk state just after the chart wakes
up.

3-13
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


1 Your first stop is at the front desk of the At the chart level, the default transition
hotel. to Check_in occurs, making that state
active. Then, the default transition to
Front_desk occurs, making that state
active.

For reference, see Steps for Entering a


State on page 3-74.

3-14
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


2 You leave the front desk after checking in The check_in event guards the outgoing
to the hotel. transition from Front_desk. When the
chart receives an event broadcast for
check_in, the transition becomes valid.

For reference, see How Charts Process


Events on page 3-44.
3 Just before you leave the front desk, you Just before the transition occurs, the exit
pick up your bags to move to your room. action of Front_desk sets the move_bags
local data to 1. Then, Front_desk
becomes inactive.

For reference, see Steps for Exiting an


Active State on page 3-75.

Modeling Guidelines for Chart Initialization. The following guidelines apply to


chart initialization.

Modeling Guideline Why This Guideline Applies Reference


Use exclusive (OR) This guideline ensures proper State Decomposition on
decomposition when no chart execution. For example, page 2-9
two states at a level of the Check_in and Waiting_area Specify Substate
hierarchy can be active at the are exclusive (OR) states, Decomposition on page
same time. because you cannot be inside 4-8
and outside the hotel at the
same time.
Use a default transition to This guideline prevents state Default Transitions on page
mark the first state to become inconsistency errors during 2-35
active among exclusive (OR) chart execution. State Inconsistencies in a
states. Chart on page 29-25
Use events, instead of Since you cannot easily Activate a Stateflow Chart
conditions, to guard transitions quantify the numerical value Using Input Events on page
that depend on occurrences of checking into a hotel, model 9-9
without inherent numerical such an occurrence as an event.
value.

3-15
3 Stateflow Chart Semantics

Modeling Guideline Why This Guideline Applies Reference


Use an exit action to execute Other types of state actions State Action Types on page
a statement once, just before a execute differently and do not 11-2
state becomes inactive. apply:

Entry actions execute once,


just after a state becomes
active.
During actions execute
at every time step (except
the first time step after
a state becomes active).
Execution continues as long
as the chart remains in that
state and no valid outgoing
transitions exist.
On event_name actions
execute only after receiving
an event broadcast.

Phase: Evaluation of Outgoing Transitions from a Single Junction

This section describes what happens after exiting the Front_desk state: the evaluation
of a group of outgoing transitions from a single junction.

3-16
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


1 You can move to one of three types of After the check_in event triggers a
rooms. transition out of Front_desk, three
transition paths are available based on the
type of room you select with the Multiport
Switch block. Transition testing occurs
based on the priority you assign to each
path.

3-17
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


For reference, see Order of Execution for
a Set of Flow Charts on page 3-58.
2 If you choose an executive suite, the base If the room_type input data equals 1, the
fee is 1500. top transition is valid. If this condition
is true, the condition action executes by
setting the fee output data to 1500.

Note: If the top transition is not valid,


control flow backtracks to the central
junction so that testing of the next
transition can occur. This type of
backtracking is intentional.

To learn about unintentional backtracking


and how to avoid it, see Backtrack in
Flow Charts on page B-39 and Best
Practices for Creating Flow Charts on
page 5-31.
3 If you choose a family suite, the base fee is If room_type equals 2, the middle
1000. transition is valid. If this condition is true,
the condition action executes by setting
fee to 1000.
4 If you choose a single room, the base fee is If room_type equals 3, the bottom
500. transition is valid. If this condition is true,
the condition action executes by setting
fee to 500.

What happens if room_type has a value other than 1, 2, or 3?

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.

Modeling Guidelines for Evaluation of Outgoing Transitions. The following


guidelines apply to transition syntax.

3-18
How Chart Constructs Interact During Execution

Modeling Guideline Why This Guideline Applies Reference


Use conditions, instead of Because you can quantify a What Is a Flow Chart? on page
events, to guard transitions type of hotel room numerically, 5-2
that depend on occurrences express the choice of room type
with numerical value. as a condition.
Use condition actions instead Condition actions execute as Transition Action Types on
of transition actions whenever soon as the condition evaluates page 11-8
possible. to true. Transition actions
do not execute until after the
transition path is complete, to a
terminating junction or a state.

Unless an execution delay is


necessary, use condition actions
instead of transition actions.
Use explicit ordering to control You can specify explicit or Evaluation Order for Outgoing
the testing order of a group of implicit ordering of transitions. Transitions on page 3-60
outgoing transitions. By default, a chart uses explicit
ordering. If you switch to
implicit ordering, the transition
testing order can change when
graphical objects move.

Phase: Execution of State Actions for a Superstate

This section describes what happens after you enter the Checked_in state, regardless of
which substate becomes active.

3-19
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


1 After reaching your desired room, you The entry action executes by setting the
finish moving your bags. move_bags local data to 0.
2 If you order room service, your hotel bill If the chart receives an event broadcast for
increases by a constant amount. room_service, these actions occur:

1 The counter for the service local


data increments by 1.

3-20
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


2 A function call to expenses occurs,
which returns the value of the hotel
bill stored by the fee output data.

For reference, see How Charts Process


Events on page 3-44.

Modeling Guidelines for Execution of State Actions. The following guidelines


apply to state actions.

Modeling Guideline Why This Guideline Applies Reference


Use an entry action to execute Other types of state actions State Action Types on page
a statement once, right after a execute differently and do not 11-2
state becomes active. apply:
Use an On event_name or During actions execute at
On message_name action to every time step until there
execute a statement only after is a valid transition out of
receiving an event broadcast or the state.
a message.
Exit actions execute once,
just before a state becomes
inactive.
Use a superstate to enclose This guideline enables reuse Create Substates and
multiple substates that share of state actions that apply Superstates on page 4-6
the same state actions. to multiple substates. You
write the state actions only
once, instead of writing them
separately in each substate.

Phase: Function Call from a State Action

This part of the chart describes how you can perform function calls while a state is active.

3-21
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


1 Based on your room type and the total expenses is a MATLAB function that
number of room service requests, you can takes the total number of room service
track your hotel bill. requests as an input and returns the
current hotel bill as an output.

If you double-click the function box, you


see this script in the function editor:

3-22
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


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.

Modeling Guideline Why This Guideline Applies Reference


Use MATLAB functions MATLAB functions are MATLAB Functions in a Chart
for performing numerical better at handling numerical on page 26-2
computations in a chart. computations than graphical
functions, truth tables, or
Simulink functions.
Use descriptive names in Descriptive function names
function signatures. enhance readability of chart
objects.

Phase: Execution of State with Exclusive Substates

This part of the chart shows how a state with exclusive (OR) decomposition executes.

3-23
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


1 When you reach the executive suite, you When the condition room_type == 1 is
enter the bedroom first. true, the condition action fee = 1500
executes. Completion of that transition
path triggers these state initialization
Note: The executive suite has separate actions:
bedroom and dining areas. Therefore, you
can be in only one area of the suite at any 1 Checked_in becomes active and
time. executes its entry action.

3-24
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


2 Executive_suite becomes active.
3 The default transition to Bedroom
occurs, making that state active.

For reference, see Steps for Entering a


State on page 3-74.
2 When you order room service, you enter When the room_service event
the dining area to eat. occurs, the transition from Bedroom to
Dining_area occurs.
3 When you want the food removed from the When the room_service event occurs,
dining area, you order room service again the transition from Dining_area to
and then return to the bedroom. Bedroom occurs.
4 If you leave the executive suite because of If a transition out of Executive_suite
a fire alarm, you return to your previous occurs, the history junction records
room after the all-clear signal. the last active substate, Bedroom or
Dining_area. For details on how this
transition can occur, see Phase: Events
Guard Transitions Between States on
page 3-28.

Modeling Guidelines for Execution of Exclusive (OR) States. The following


guidelines apply to exclusive (OR) states.

Modeling Guideline Why This Guideline Applies Reference


Use exclusive (OR) This guideline ensures proper State Decomposition on
decomposition when no two chart execution. For example, page 2-9
states at that level of the Bedroom and Dining_area Specify Substate
hierarchy can be active at the are exclusive (OR) states, Decomposition on page
same time. because you cannot be in both 4-8
places at the same time.
If reentry to a state with If you do not record the History Junctions on page
exclusive (OR) decomposition previously active substate, the 2-46
depends on the previously default transition occurs and
active substate, use a history the wrong substate can become
junction. This type of junction active upon state reentry.
records the active substate
when the chart exits the state.

3-25
3 Stateflow Chart Semantics

Modeling Guideline Why This Guideline Applies Reference


For example, if you were eating
when a fire alarm sounded, you
would return to the bedroom
instead of the dining room.

Phase: Execution of State with Parallel Substates

This part of the chart shows how a state with parallel (AND) decomposition executes.

3-26
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


1 When your family reaches the suite, When the condition room_type == 2 is
family members can be in both bedrooms true, the condition action fee = 1000
(for example, parents in the master executes. Completion of that transition
bedroom and children in the second path triggers these state initialization
bedroom). A default room choice does not actions:
apply.
1 Checked_in becomes active and
executes its entry action.
2 Family_suite becomes active.
3 The parallel states wake up in
the order given by the number
in the upper right corner of each
state: Master_bedroom, then
Second_bedroom.

How do I specify the order?

To specify the order:

a Verify that the chart uses explicit


ordering.

In the Chart properties dialog


box, select the User specified
state/transition execution
order check box.
b Right-click in a parallel state
and select a number from the
Execution Order menu.

For reference, see Steps for Entering a


State on page 3-74.
2 You can occupy both rooms at the same Master_bedroom and Second_bedroom
time. remain active at the same time.

Modeling Guidelines for Execution of Parallel (AND) States. The following


guidelines apply to parallel (AND) states.

3-27
3 Stateflow Chart Semantics

Modeling Guideline Why This Guideline Applies Reference


Use parallel (AND) This guideline ensures proper State Decomposition on
decomposition when all states chart execution. For example, page 2-9
at that level of the hierarchy Master_bedroom and Specify Substate
can be active at the same time. Second_bedroom are parallel Decomposition on page
states, because you can occupy 4-8
both rooms at the same time.
Use no history junctions in This guideline prevents parsing History Junctions on page
states with parallel (AND) errors. Since all parallel states 2-46
decomposition. at a level of hierarchy are
active at the same time, history
junctions have no meaning.
Use explicit ordering to control You can specify explicit or Execution Order for Parallel
the execution order of parallel implicit ordering of parallel States on page 3-78
(AND) states. states. By default, a chart
uses explicit ordering. If you
switch to implicit ordering, the
execution order can change
when parallel states move.

Phase: Events Guard Transitions Between States

This part of the chart describes how events can guard transitions between exclusive (OR)
states.

3-28
How Chart Constructs Interact During Execution

Stage Hotel Scenario Chart Behavior


1 If a fire alarm sounds, When the chart receives an event broadcast for fire_alarm,
you leave the hotel and a transition occurs from a substate of Check_in to
move to a waiting area Waiting_area.
outside.
How does this transition occur?

Suppose that Check_in, Checked_in, Executive_suite, and


Dining_area are active when the chart receives fire_alarm.

3-29
3 Stateflow Chart Semantics

Stage Hotel Scenario Chart Behavior


1 States become inactive in ascending order of hierarchy:

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.

How does this transition occur?

Suppose that Check_in, Checked_in, Executive_suite,


and Dining_area were active when the chart received
fire_alarm.

1 Waiting_area becomes inactive.


2 States become active in descending order of hierarchy:

a Check_in
b Checked_in (The default transition does not apply.)
c Executive_suite
d Dining_area (The default transition does not apply.)

Modeling Guidelines for Guarding Transitions. The following guideline discusses


the use of events versus conditions.

Modeling Guideline Why This Guideline Applies Reference


Use events, instead of Because you cannot easily Activate a Stateflow Chart
conditions, to guard transitions quantify the numerical value Using Input Events on page
of a fire alarm or an all- 9-9

3-30
How Chart Constructs Interact During Execution

Modeling Guideline Why This Guideline Applies Reference


that depend on occurrences clear signal, model such an
without numerical value. occurrence as an event.

3-31
3 Stateflow Chart Semantics

Modeling Guidelines for Stateflow Charts


These guidelines promote efficient modeling of charts with events, states, and
transitions.

Use signals of the same data type for input events

When you use multiple input events to trigger a chart, verify that all input signals use
the same data type. Otherwise, simulation stops and an error message appears. For more
information, see Data Types Allowed for Input Events on page 9-11.

Use a default transition to mark the first state to become active among exclusive (OR) states

This guideline prevents state inconsistency errors during chart execution.

Use condition actions instead of transition actions whenever possible

Condition actions execute as soon as the condition evaluates to true. Transition actions
do not execute until after the transition path is complete, to a terminating junction or a
state.

Unless an execution delay is necessary, use condition actions instead of transition


actions.

Use explicit ordering to control the testing order of a group of outgoing transitions

You can specify explicit or implicit ordering of transitions. By default, a chart uses
explicit ordering. If you switch to implicit ordering, the transition testing order can
change when graphical objects move.

Verify intended backtracking behavior in flow charts

If your chart contains unintended backtracking behavior, a warning message appears


with instructions on how to avoid that problem. For more information, see Best
Practices for Creating Flow Charts on page 5-31.

Use a superstate to enclose substates that share the same state actions

When you have multiple exclusive (OR) states that perform the same state actions, group
these states in a superstate and define state actions at that level.

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.

3-32
Modeling Guidelines for Stateflow Charts

Note: You cannot use boxes for this purpose because boxes do not support state actions.

Use MATLAB functions for performing numerical computations in a chart

MATLAB functions are better at handling numerical computations than graphical


functions, truth tables, or Simulink functions.

Use descriptive names in function signatures

Descriptive function names enhance readability of chart objects.

Use history junctions to record state history

If reentry to a state with exclusive (OR) decomposition depends on the previously active
substate, use a history junction. This type of junction records the active substate when
the chart exits the state. If you do not record the previously active substate, the default
transition occurs and the wrong substate can become active upon state reentry.

Do not use history junctions in states with parallel (AND) decomposition

This guideline prevents parsing errors. Since all parallel states at a level of hierarchy are
active at the same time, history junctions have no meaning.

Use explicit ordering to control the execution order of parallel (AND) states

You can specify explicit or implicit ordering of parallel states. By default, a chart uses
explicit ordering. If you switch to implicit ordering, the execution order can change when
parallel states move.

3-33
3 Stateflow Chart Semantics

Modeling Rules That Stateflow Detects During Edit Time

In this section...
Object contains a syntax error on page 3-35
Dangling transitions on page 3-35
Unreachable state on page 3-36
Transition shadowing on page 3-36
Invalid default transition path on page 3-37
Default transition is missing on page 3-38
Unexpected backtracking on page 3-38
Transition loops outside natural parent on page 3-39
Transition action precedes a condition action along this path on page 3-40
Invalid transitions crossing into graphical function on page 3-41
Invalid transitions crossing out of graphical function on page 3-41

The Stateflow editor displays potential errors and warnings by highlighting objects in
red or orange. By fixing these issues when you design your charts, you avoid potential
compile or run-time warnings and errors. To see details and possible fixes, hover your
cursor over the object and click the badge.

To turn off the edit-time checking, clear Display > Error & Warnings. When you
change the diagnostic level of a corresponding configuration parameter, the edit-time
diagnostic level also changes. For example, if you set the Unreachable execution path
configuration parameter on the Diagnostics > Stateflow pane in the Configuration
Parameters dialog box to none, then Stateflow does not highlight transition shadowing
in the editor. Not all edit-time checks have corresponding configuration parameters.

Edit-Time Check Issue Diagnostic Configuration Parameter


Object contains a syntax error No configuration parameter. Always an
error.
Dangling transitions Unreachable execution path
Unreachable state Unreachable execution path
Transition shadowing Unreachable execution path

3-34
Modeling Rules That Stateflow Detects During Edit Time

Edit-Time Check Issue Diagnostic Configuration Parameter


Invalid default transition No configuration parameter. Always an
error.
Default transition is missing No configuration parameter. Always an
error.
Unexpected backtracking Unexpected backtracking
Transition loops outside natural parent Transition outside natural parent
Transition action precedes a condition Transition action specified before condition
action along this path action
Invalid transitions crossing into graphical No configuration parameter. Always an
function error.
Invalid transitions crossing out of graphical No configuration parameter. Always an
function error.

The editor highlights these potential issues.

Object contains a syntax error


The notation for an action or condition in a state or transition does not follow the syntax
rules. Violations are highlighted as errors. See Transition Label Notation on page 2-21
and State Labels on page 2-10.

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

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Unreachable execution path parameter in the Model Configuration Parameters dialog
box.

3-35
3 Stateflow Chart Semantics

Unreachable state
If there is not a valid execution path leading to a state, it is unreachable. Make this state
a reachable destination by connecting the state with a transition from a reachable state
or junction.

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Unreachable execution path parameter in the Model Configuration Parameters dialog
box.

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

3-36
Modeling Rules That Stateflow Detects During Edit Time

transition as a lower evaluation order than any transitions with conditions. See
Evaluation Order for Outgoing Transitions on page 3-60.

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Unreachable execution path parameter in the Model Configuration Parameters dialog
box.

When possible, click Fix for Stateflow to switch the execution orders for the transitions.
You can undo the applied fix from the Edit menu.

Invalid default transition path


An invalid default transition occurs when the execution path for the default transition
exits the parent state. Create a default transition that contains the execution path within
the parent state.

3-37
3 Stateflow Chart Semantics

Default transition is missing


Charts or states with exclusive (OR) decomposition require a default transition to
indicate which state or junction should enter execution by default. See Default
Transitions on page 2-35.

When you click Fix, Stateflow adds a default transition to the upper-left state or
junction.

Unexpected backtracking
Unintended backtracking of control flow can occur at a junction under these conditions:

The junction does not have an unconditional transition path to a state or terminating
junction.
Multiple transition paths lead to that junction.

See Backtrack in Flow Charts on page B-39.

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Unexpected backtracking parameter in the Model Configuration Parameters dialog
box.

3-38
Modeling Rules That Stateflow Detects During Edit Time

When you click Fix, Stateflow adds a transition from the backtracking junction to a
terminating junction. You can undo the applied fix from the Edit menu.

Transition loops outside natural parent


When a transition loops outside of the parent state between the source and destination,
the exit and entry actions of the parent state execute before the destination state
becomes active. Often this behavior is not the behavior that you want. For example:

1 State B is initially active.


2 State B exit actions execute.
3 State A exit actions execute.
4 State A entry actions execute.
5 State C entry actions execute.

To have execution move from state B to state C without exiting and reentering state A,
move the transition so that it is contained within state A.

3-39
3 Stateflow Chart Semantics

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Transition outside natural parent parameter in the Model Configuration Parameters
dialog box.

Transition action precedes a condition action along this path


When there is a transition action on a path with a condition action on a following
transition, the actions do not execute in the order of the transitions. The condition action
executes before the preceding transition action. Condition actions execute when the
associated condition is evaluated as true, whereas transition actions execute only when
the transition path is fully executed.

In this diagram, if ConditionA and ConditionB are true, ConditionAction2


executes before TransitionAction1.

3-40
Modeling Rules That Stateflow Detects During Edit Time

Execution order:

1 Evaluate ConditionA.
2 If true, evaluate ConditionB.
3 If true, execute ConditionAction2.
4 Exit state A.
5 Execute TranstionAction1.
6 Enter state B.

To improve clarity, place the transition action after the last condition action on the path.

Control the level of diagnostic action by setting the Diagnostics > Stateflow >
Transition action specified before condition action parameter in the Model
Configuration Parameters dialog box.

Invalid transitions crossing into graphical function


Transitions cannot have a graphical function as the destination. Call graphical functions
from state actions or transitions.

Invalid transitions crossing out of graphical function


Transitions cannot have a graphical function as the source. Call graphical functions from
state actions or transitions.

More About
What Do Semantics Mean for Stateflow Charts? on page 3-2

3-41
3 Stateflow Chart Semantics

Modeling Guidelines for Stateflow Charts on page 3-32


Stateflow Editor Operations on page 4-26

3-42
How Events Drive Chart Execution

How Events Drive Chart Execution


In this section...
How Stateflow Charts Respond to Events on page 3-43
Sources for Stateflow Events on page 3-43
How Charts Process Events on page 3-44

How Stateflow Charts Respond to Events


Stateflow charts execute only in response to an event in a cyclical manner.

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.

Sources for Stateflow Events


Simulink events awaken Stateflow charts. You can use events to control the processing
of your charts by broadcasting events, as described in Broadcast Events to Synchronize

3-43
3 Stateflow Chart Semantics

States on page 11-52. For examples using event broadcasting and directed event
broadcasting, see:

Directed Event Broadcasting


Broadcast Events to Parallel (AND) States Using Condition Actions on page
B-14
Avoid Cyclic Behavior on page B-15
Broadcast Events in Parallel States on page B-42
Broadcast Events in a Transition Action with a Nested Event Broadcast on page
B-45
Broadcast Condition Action Event in Parallel State on page B-48

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 9-7 for more information.

How Charts Process Events


Stateflow charts process events from the top down through the chart hierarchy:

1 Executes during and on event_name actions for the active state


2 Checks for valid transitions in substates

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 an Active
Chart on page 3-47 and Steps for Executing an Active State on page 3-75).
(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-85.

3-44
How Events Drive Chart Execution

Note: Output edge-trigger event execution in a Simulink model is equivalent to


toggling the value of an output data value between 1 and 0. It is not treated as a
Stateflow event. See Define Edge-Triggered Output Events on page 22-17.

3-45
3 Stateflow Chart Semantics

Types of Chart Execution


In this section...
Lifecycle of a Stateflow Chart on page 3-46
Execution of an Inactive Chart on page 3-46
Execution of an Active Chart on page 3-47
Execution of a Chart with Super Step Semantics on page 3-47
Execution of a Chart at Initialization on page 3-55

Lifecycle of a Stateflow Chart


Stateflow charts go through several stages of 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.

See How Events Drive Chart Execution on page 3-43.

Execution of an Inactive Chart


When a chart is inactive and first triggered by an event from a Simulink model, it first
executes its set of default flow charts (see Order of Execution for a Set of Flow Charts
on page 3-58). If this action does not cause an entry into a state and the chart has
parallel decomposition, then each parallel state becomes active (see Steps for Entering a
State on page 3-74).

If executing the default flow paths does not cause state entry, a state inconsistency error
occurs.

3-46
Types of Chart Execution

Execution of an Active Chart


After a chart has been triggered the first time by the Simulink model, it is an active
chart. When the chart receives another event from the model, it executes again as an
active chart. If the chart has no states, each execution is equivalent to initializing a
chart. Otherwise, the active children execute. Parallel states execute in the same order
that they become active.

Execution of a Chart with Super Step Semantics


What Is Super Step Semantics?

By default, Stateflow charts execute once for each active input event. If no input events
exist, the charts execute once every time step. If you are modeling a system that must
react quickly to inputs, you can enable super step semantics, a Stateflow chart property
(see Enable Super Step Semantics on page 3-48).

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 What Is Maximum Number of Iterations? on page
3-47).

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.

What Is Maximum Number of Iterations?

In a super step, your chart always takes at least one transition. Therefore, when you
set a maximum number of iterations in each super step, the chart takes that number of

3-47
3 Stateflow Chart Semantics

transitions plus 1. For example, if you specify 10 as the maximum number of iterations,
your chart takes 11 transitions in each super step. To set maximum number of iterations
in each super step, see Enable Super Step Semantics on page 3-48.

Enable Super Step Semantics

To enable super step semantics:

1 Right-click inside the top level of a chart and select Properties from the context
menu.
2 In the Chart properties dialog box, select the Enable Super Step Semantics check
box.

Two additional fields appear below that check box.

3-48
Types of Chart Execution

3 Enter a value in the field Maximum Iterations in each Super 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). Try to choose a number that allows the chart to reach a stable state within the

3-49
3 Stateflow Chart Semantics

time step, based on the mode logic of your chart. For more information, see What Is
Maximum Number of Iterations? on page 3-47
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: Selecting Throw Error can help detect infinite loops


in transition cycles (see Detection of Infinite Loops in
Transition Cycles on page 3-54.

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.

Super Step Example

The following model shows how super step semantics differs from default semantics:

In this model, a Constant block outputs a constant value of 20 to input u in a Stateflow


chart. Because the value of u is always 20, each transition in the chart is valid:

3-50
Types of Chart Execution

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-51
3 Stateflow Chart Semantics

How Super Step Semantics Works with Multiple Input Events

When you enable super step semantics for a chart with multiple active input events, the
chart takes all valid transitions for the first active event before it begins processing the
next active event. For example, consider the following model:

3-52
Types of Chart Execution

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-53
3 Stateflow Chart Semantics

In a super step, this chart never transitions to state D because there is no path from state
C to state D.

Detection of Infinite Loops in Transition Cycles

If your chart contains transition cycles, taking multiple transitions in a single time step
can cause infinite loops. Consider the following example:

3-54
Types of Chart Execution

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

Execution of a Chart at Initialization

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 option
to execute at initialization. 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() (Simulink) phase for S-functions.

You select the Execute (enter) Chart At Initialization check box in the Chart
properties dialog box, as described in Specify Chart Properties on page 22-3.

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.

3-55
3 Stateflow Chart Semantics

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.

Execute at initialization is ignored in Stateflow charts that do not contain states.

3-56
Process for Grouping and Executing Transitions

Process for Grouping and Executing Transitions


In this section...
Transition Flow Chart Types on page 3-57
Order of Execution for a Set of Flow Charts on page 3-58

Transition Flow Chart Types


Before executing transitions for an active state or chart, Stateflow software groups
transitions by the following types:

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-57
3 Stateflow Chart Semantics

The inner transition


The outgoing transitions from the junction to state A.A1 and A.A2

In addition, the set of default flow charts for state A includes:

The default transition to the junction


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.

Order of Execution for a Set of Flow Charts


Each flow chart group executes in the order of group priority until a valid transition
appears. The default transition group executes first, followed by the outer transitions
group and then the inner transitions group. Each flow chart group executes as follows:

1 Order the group's transition segments for the active state.

An active state can have several possible outgoing transitions. The chart orders
these transitions before checking them for validity. See Evaluation Order for
Outgoing Transitions on page 3-60.
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:

a Testing of transition segments stops and a transition path forms by backing up


and including the transition segment from each preceding junction back to the
starting transition.
b The states that are the immediate children of the parent of the transition path
exit (see Steps for Exiting an Active State on page 3-75).
c The transition action from the final transition segment of the full transition path
executes.
d The destination state becomes active (see Steps for Entering a State on page
3-74).
6 If the destination is a junction with no outgoing transition segments, do the
following:

3-58
Process for Grouping and Executing Transitions

a Testing stops without any state exits or entries.


7 If the destination is a junction with outgoing transition segments, repeat step 1 for
the set of outgoing segments.
8 After testing all outgoing transition segments at a junction, take the following
actions:

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-59
3 Stateflow Chart Semantics

Evaluation Order for Outgoing Transitions


In this section...
What Does Ordering Mean for Outgoing Transitions? on page 3-60
Detection of Transition Shadowing on page 3-61
Explicit Ordering of Outgoing Transitions on page 3-61
Implicit Ordering of Outgoing Transitions on page 3-64
What Happens When You Switch Between Explicit and Implicit Ordering on page
3-69
Transition Testing Order in Multilevel State Hierarchy on page 3-69

What Does Ordering Mean for Outgoing Transitions?


When multiple transitions originate from a single source (such as a state or junction), a
Stateflow chart must determine in which order to evaluate those transitions. Order of
evaluation depends on:

Explicit ordering

Specify explicitly the evaluation order of outgoing transitions on an individual basis


(see Explicit Ordering of Outgoing Transitions on page 3-61).
Implicit ordering

Override explicit ordering in C charts by letting Stateflow use internal rules to order
transitions (see Implicit Ordering of Outgoing Transitions on page 3-64).

Note: You can order transitions only within their type (inner, outer, or default). For more
information, see Transition Flow Chart Types on page 3-57.

Outgoing transitions are assigned priority numbers based on order of evaluation. The
lower the number, the higher the priority. The priority number appears on each outgoing
transition.

Because evaluation order is a chart property, all outgoing transitions 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 in the same Simulink model.

3-60
Evaluation Order for Outgoing Transitions

Detection of Transition Shadowing


Transition shadowing occurs when a chart contains multiple unconditional transitions
that originate from the same state or the same junction. To avoid transition shadowing,
ensure that no more than one unconditional transition exists for each group of outgoing
transitions from a state or junction.

You can control the behavior of the Stateflow diagnostic that detects transition
shadowing. On the Diagnostics > Stateflow pane of the Configuration Parameters
dialog box, set Unreachable execution path to none, warning, or error. For
information about other diagnostics, see Model Configuration Parameters: Stateflow
Diagnostics (Simulink).

Explicit Ordering of Outgoing Transitions


By default, a Stateflow chart orders outgoing transitions explicitly based on evaluation
priorities you set.

How Explicit Ordering Works

When you open a new Stateflow chart, all outgoing transitions from a source are
automatically numbered in the order you create them, starting with the next available
number for the source.

You can change the order of outgoing transitions by explicitly renumbering them. When
you change a transition number, the Stateflow chart automatically renumbers the other
outgoing transitions for the source by preserving their relative order. This behavior is
consistent with the renumbering rules for Simulink ports.

For example, if you have a source with five outgoing transitions, changing transition 4 to
2 results in the automatic renumbering shown.

3-61
3 Stateflow Chart Semantics

Automatic Renumbering of Transitions During Explicit Reordering

Order Transitions Explicitly

To use explicit ordering for transitions, perform these tasks:

1 Enable Explicit Ordering at the Chart Level on page 3-62


2 Set Evaluation Order for Transitions Individually on page 3-63

Enable Explicit Ordering at the Chart Level

To enable explicit ordering for transitions:

1 Right-click inside the top level of a chart and select Properties from the context
menu.

The Chart properties dialog box appears.


2 Select the User specified state/transition execution order check box.

3-62
Evaluation Order for Outgoing Transitions

3 Click OK.

Set Evaluation Order for Transitions Individually

1 Right-click a transition and select Execution Order.

3-63
3 Stateflow Chart Semantics

Note: If you select Execution Order while the chart is in implicit ordering mode,
the only option available is Enable user-specified execution order for this
chart. This option opens the Chart properties dialog box where you can switch
to explicit ordering mode, as described in Order Transitions Explicitly on page
3-62.

A context menu of available transition numbers appears, with a check mark next to
the current number for this transition.
2 Select the new transition number.

The chart automatically renumbers the other transitions for the source by preserving
the relative transition order.
3 Repeat this procedure to renumber other transitions as needed.

Another way to access the transition order number is through the properties dialog box.

1 Right-click a transition and select Properties.

The properties dialog box for the transition appears.


2 Click in the Execution order box.

A drop-down list of valid transition numbers appears.


3 Select the new transition number and click Apply.

Note: If explicit ordering mode is enabled, the chart assigns the new number to
the current transition and automatically renumbers the other transitions. If the
chart is in implicit ordering mode, an error dialog box appears and the old number is
retained.

Implicit Ordering of Outgoing Transitions


How Implicit Ordering Works

For C charts in implicit ordering mode, a Stateflow chart evaluates a group of outgoing
transitions from a single source based on these factors (in descending order of priority):

1 Hierarchy (see Order by Hierarchy on page 3-65)

3-64
Evaluation Order for Outgoing Transitions

2 Label (see Order by Label on page 3-66)


3 Angular surface position of transition source (see Order by Angular Position of
Source on page 3-66)

Note: Implicit ordering creates a dependency between design layout and evaluation
priority. When you rearrange transitions in your chart, you can accidentally change order
of evaluation and affect simulation results. For more control over your designs, use the
default explicit ordering mode to set evaluation priorities.

Order by Hierarchy

A chart evaluates a group of outgoing transitions in an order based on the hierarchical


level of the parent of each transition. The parent of a transition is the lowest level or
innermost object in the Stateflow hierarchy that contains all parts of the transition,
including any source state or junction and the endpoint object. For a group of outgoing
transitions from a single source, the transition whose parent is at a higher hierarchical
level than the parents of all other outgoing transitions is first in testing order, and so on.

Example of Ordering by Hierarchy

3-65
3 Stateflow Chart Semantics

The parent of the transition from state A1 to state B is the chart.


The parent of the transition from state A1 to state A2 is the state A.
An event occurs while state A1 is active.

Because the chart is at a higher level in the hierarchy than state A, the transition from
state A1 to state B takes precedence over the transition from state A1 to state A2.

Order by Label

A chart evaluates a group of outgoing transitions with equal hierarchical priority based
on the labels, in the following order of precedence:

1 Labels with events and conditions


2 Labels with events
3 Labels with conditions
4 No label

Order by Angular Position of Source

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.

Note: These evaluations proceed in a clockwise direction around the source object.

3-66
Evaluation Order for Outgoing Transitions

Example of Angular Ordering for a Source State

For each outgoing transition from state A, the parent is the chart and the label
contains a condition. Therefore, the outgoing transitions have equal hierarchical and
label priority.
The conditions [C_one == 1] and [C_two == 2] are false, and the condition [C_three
== 3] is true.

The chart evaluates the outgoing transitions from state A in this order.

Phase Chart evaluates transition Condition is... Transition occurs?


to...
1 State B False No
2 State C False No
3 State D True Yes

3-67
3 Stateflow Chart Semantics

Example of Angular Ordering for a Source Junction

For each outgoing transition from the junction, the parent is the chart and the label
contains a condition. Therefore, the outgoing transitions have equal hierarchical and
label priority.
The conditions [C_one == 1] and [C_two == 2] are false, and the conditions [C_three
== 3] and [C_four == 4] are true.
The junction source point for the transition to state E is exactly 12 o'clock.

The chart evaluates the outgoing transitions from the junction in this order.

Phase Chart evaluates transition Condition is... Transition occurs?


to...
1 State B False No
2 State C False No
3 State D True Yes

Since the transition to state D occurs, the chart does not evaluate the transition to state
E.

3-68
Evaluation Order for Outgoing Transitions

Using Implicit Ordering for Transitions

To use implicit ordering for transitions in a C chart, follow these steps:

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.

What Happens When You Switch Between Explicit and Implicit Ordering
If you switch to implicit ordering mode in a C chart after explicitly ordering transitions,
the transition order resets to follow the implicit rules. Similarly, if you switch back to
explicit ordering mode, without changing the chart, you can restore the previous explicit
transition order. All existing transitions in a chart retain their current order numbers
until you explicitly change them.

Note: If you change back to explicit ordering after modifying the chart, you might not be
able to restore the previous explicit transition order.

Transition Testing Order in Multilevel State Hierarchy


How Multilevel Transition Testing Order Works

By default, charts use explicit ordering for transitions. In this mode, you have explicit
control over the testing priority, as described in Explicit Ordering of Outgoing
Transitions on page 3-61.

If you use implicit ordering for transitions, the following testing order applies. For each
group of transitions that originate from the same state, tiebreaking criteria apply in this
order: hierarchy, label, and angular position.

Testing Chart Action Order by Hierarchy Order by Label Order by Angular


Order Position
1 Tests 1 Outer transitions 1 Events and The transition with
transitions 2 Inner transitions conditions the smallest clock

3-69
3 Stateflow Chart Semantics

Testing Chart Action Order by Hierarchy Order by Label Order by Angular


Order Position
that originate 2 Events position has the
from the 3 Conditions highest priority.
highest-level
active state 4 No label A transition with
(superstate). a 12 o'clock source
position has the
2 Tests 1 Outer transitions
lowest priority.
transitions that that cross the border
originate from of the highest-
the next lower- level active state
level active (superstate)
state. 2 Outer transitions
that stay within the
parent of the state
3 Inner transitions
3 Repeats step 2 until transition testing is complete.

The following chart shows the behavior of multilevel transition testing. Assume that the
Super1.Sub1.Subsub1 state is active.

3-70
Evaluation Order for Outgoing Transitions

Because the chart uses implicit ordering, the following transition testing order applies:

This Applies to the label... For this transition...


priority...
1 [a < 0] Super1 to Super2.B
2 [i > 0] Super1 to Super1.Sub1
3 [b > 0] Super1.Sub1 to Super2.A

3-71
3 Stateflow Chart Semantics

This Applies to the label... For this transition...


priority...
4 [i < 0] Super1.Sub1 to Super1
5 [c > 0] Super1.Sub1.Subsub1 to Super2.A
6 [d > 5] Super1.Sub1.Subsub1 to Super1.Sub2
7 [c < 0] Super1.Sub1.Subsub1 to Super1.Sub1.Subsub2

Example Model with Multilevel Transition Testing

Suppose that you open the sf_debouncer model and reach the point in the simulation
where the Debounce.On state is active.

Because the chart uses implicit ordering, the following transition testing order applies:

This priority... Applies to the label... For this transition...


1 after(0.3, sec) Debounce to Off.Fault
2 after(0.1, sec) Debounce.On to On

3-72
Evaluation Order for Outgoing Transitions

This priority... Applies to the label... For this transition...


3 [sw < 0] Debounce.On to
Debounce.Off

Now suppose that the transition from Debounce.On to Debounce.Off occurs.

Because the chart uses implicit ordering, the following transition testing order applies:

This priority... Applies to the label... For this transition...


1 after(0.3, sec) Debounce to Off.Fault
2 after(0.1, sec) Debounce.Off to Off
3 [sw > 0] Debounce.Off to
Debounce.On

For more information on how this model works, see Key Behaviors of Debouncer Chart
on page 24-3.

3-73
3 Stateflow Chart Semantics

Process for Entering, Executing, and Exiting States


In this section...
Steps for Entering a State on page 3-74
Steps for Executing an Active State on page 3-75
Steps for Exiting an Active State on page 3-75
State Execution Example on page 3-76

Steps for Entering a State


A state becomes active in one of these ways:

An incoming transition crosses state boundaries.


An incoming transition ends at the state boundary.
It is the parallel state child of an active state.

A state performs its entry action (if specified) when it becomes active. The state becomes
active before its entry action executes and completes.

The execution steps for entering a state are as follows:

1 If the parent of the state is not active, perform steps 1 through 4 for the parent first.
2 If the state is a parallel state, check if a sibling parallel state previous in entry order
is active. If so, start at step 1 for this parallel state.

Parallel (AND) states are ordered for entry based on whether you use explicit
ordering (default) or implicit ordering. For details, see Explicit Ordering of Parallel
States on page 3-79 and Implicit Ordering of Parallel States on page 3-80.
3 Mark the state active.
4 Perform any entry actions.
5 Enter children, if needed:

a If the state contains a history junction and there is an active child of this state at
some point after the most recent chart initialization, perform the entry actions
for that child. 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.

3-74
Process for Entering, Executing, and Exiting States

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 the state is a parallel state, perform all entry steps for the sibling state next in
entry order.
7 If the transition path parent is not the same as the parent of the current state,
perform entry steps 6 and 7 for the immediate parent of this state.
8 The chart goes to sleep.

Steps for Executing an Active State


When states become active, they perform the following execution steps:

1 Execute the set of outer flow charts (see Order of Execution for a Set of Flow
Charts on page 3-58).

If this action causes a state transition, execution stops.

Note: This step never occurs for parallel states.


2 Perform during actions and valid on event/message name actions.

Note: Stateflow charts process these actions based on their order of appearance in
state labels.
3 Execute the set of inner flow charts.

If this action does not cause a state transition, the active children execute, starting
at step 1. Parallel states execute in the same order that they become active.

Steps for Exiting an Active State


A state becomes inactive in one of these ways:

An outgoing transition originates at the state boundary.


An outgoing transition crosses the state boundary.

3-75
3 Stateflow Chart Semantics

It is a parallel state child of an activated state.

A state performs its exit actions before becoming inactive.

The execution steps for exiting a state are as follows:

1 Sibling parallel states exit starting with the last-entered and progress in reverse
order to the first-entered. See step 2 of Steps for Entering a State on page 3-74.
2 If a state has active children, performs the exit actions of the child states in the
reverse order from when they became active.
3 Perform any exit actions.
4 Mark the state as inactive.

State Execution Example


The following example shows how active and inactive states respond to events.

3-76
Process for Entering, Executing, and Exiting States

Inactive Chart Event Reaction

Inactive charts respond to events as follows:

1 An event occurs and the chart wakes up.


2 The chart checks to see if there is a valid transition as a result of the event.

A valid default transition to state A exists.


3 State A becomes active.
4 State A entry actions (entA()) execute and complete.
5 The chart goes back to sleep.

Sleeping Chart Event Reaction

Sleeping charts respond to events as follows:

1 Event E_one occurs and the chart wakes up.

State A is active from the preceding steps 1 through 5.


2 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 exists.
3 State A exit actions (exitA()) execute and complete.
4 State A becomes inactive.
5 State B becomes active.
6 State B entry actions (entB()) execute and complete.

The chart goes back to sleep.

3-77
3 Stateflow Chart Semantics

Execution Order for Parallel States


In this section...
Ordering for Parallel States on page 3-78
Explicit Ordering of Parallel States on page 3-79
Implicit Ordering of Parallel States on page 3-80
Order Maintenance for Parallel States on page 3-81
Execution Priorities in Restored States on page 3-83
Switching Between Explicit and Implicit Ordering on page 3-84
Execution Order of Parallel States in Boxes and Subcharts on page 3-84

Ordering for Parallel States


Although multiple parallel (AND) states in the same chart execute concurrently, the
Stateflow chart must determine when to activate each one during simulation. This
ordering determines when each parallel state performs the actions that take it through
all stages of execution, as described in Process for Entering, Executing, and Exiting
States on page 3-74.

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

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

3-78
Execution Order for Parallel States

chart. However, you can mix charts with different ordering modes in the same Simulink
model.

Explicit Ordering of Parallel States


By default, a Stateflow chart orders parallel states explicitly based on execution
priorities you set.

How Explicit Ordering Works

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

Order Parallel States Explicitly

To use explicit ordering for parallel states, perform these tasks:

1 Enable Explicit Ordering at the Chart Level on page 3-79


2 Set Execution Order for Parallel States Individually on page 3-80

Enable Explicit Ordering at the Chart Level

To enable explicit ordering for parallel states, follow these steps:

1 Right-click inside the top level of the chart and select Properties from the context
menu.

The Chart properties dialog box appears.

3-79
3 Stateflow Chart Semantics

2 Select the User specified state/transition execution order check box.


3 Click OK.

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

Set Execution Order for Parallel States Individually

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.

Implicit Ordering of Parallel States


Rules of Implicit Ordering for Parallel States

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.

3-80
Execution Order for Parallel States

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.

Order Parallel States Implicitly


To use implicit ordering for parallel states, follow these steps:

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.

Order Maintenance for Parallel States


Whether you use explicit or implicit ordering, a chart tries to reconcile execution
priorities when you remove, renumber, or add parallel states. In these cases, a chart
reprioritizes the parallel states to:

Fill in gaps in the sequence so that ordering is contiguous


Ensure that no two states have the same priority
Preserve the intended relative priority of execution

3-81
3 Stateflow Chart Semantics

How a Chart Preserves Relative Priorities in Explicit Mode

For explicit ordering, a chart preserves the user-specified priorities. Consider this
example of explicit ordering:

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:

1 Change the priority of top-level state b to 3.


2 Add a top-level state g.
3 Remove substate e.

3-82
Execution Order for Parallel States

The chart preserves the priority set explicitly for top-level state b, but renumbers all
other parallel states to preserve their prior relative order.

How a Chart Preserves Relative Priorities in Implicit Mode

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:

Execution Priorities in Restored States


There are situations in which you need to restore a parallel state after you remove
it from a Stateflow chart. In implicit ordering mode, a chart reassigns the execution
priority based on where you restore the state. If you return the state to its original
location in the chart, you restore its original priority.

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 by... And restore the state by... What is the priority?
Deleting, cutting, dragging Using the undo command The original priority is
outside the boundaries restored.
of the parent state, or
dragging so its boundaries
overlap the parent state

3-83
3 Stateflow Chart Semantics

If you remove a state by... And restore the state by... What is the priority?
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
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.

Switching Between Explicit and Implicit Ordering


If you switch to implicit mode after explicitly ordering parallel states, the Stateflow chart
resets execution order to follow implicit rules of geometry. However, if you switch from
implicit to explicit mode, the chart does not restore the original explicit execution order.

Execution Order of Parallel States in Boxes and Subcharts


When you group parallel states inside a box, the states retain their relative execution
order. In addition, the Stateflow chart assigns the box its own priority based on the
explicit or implicit ordering rules that apply. This priority determines when the chart
activates the parallel states inside the box.

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-84
Early Return Logic for Event Broadcasts

Early Return Logic for Event Broadcasts


In this section...
Guidelines for Proper Chart Behavior on page 3-85
How Early Return Logic Works on page 3-85
Example of Early Return Logic on page 3-86

Guidelines for Proper Chart Behavior


These guidelines ensure proper chart behavior in event-driven systems:

When a state is active, its parent should also be active.


A state (or chart) with exclusive (OR) decomposition must never have more than one
active child.
If a parallel state is active, siblings with higher priority must also be active.

How Early Return Logic Works


Stateflow charts run on a single thread. Therefore, charts must interrupt current activity
to process events. Activity based on an event broadcast from a state or transition action
can conflict with the current activity. Charts resolve these conflicts by using early return
logic for event broadcasts as follows:

Action Type Early Return Logic


Entry If the state is no longer active at the end of the event broadcast, the
chart does not perform remaining steps for entering a state.
Exit If the state is no longer active at the end of the event broadcast, the
chart does not perform remaining exit actions or transitions from
state to state.
During If the state is no longer active at the end of the event broadcast, the
chart does not perform remaining steps for executing an active state.
Condition If the origin state of the inner or outer flow chart or parent state of
the default flow chart are no longer active at the end of the event
broadcast, the chart does not perform remaining steps for executing the
flow chart.

3-85
3 Stateflow Chart Semantics

Action Type Early Return Logic


Transition If the parent of the transition path is not active or if that parent
has an active child the chart does not perform remaining transition
actions and state entry actions.

Example of Early Return Logic

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.

Event F interrupts the transition from A to B.


4 The chart root checks to see if there is a valid transition out of the active state A as a
result of event F.
5 A valid transition to state C exists.
6 State A executes its exit action.
7 State A becomes inactive.
8 State C becomes active.
9 State C executes and completes its entry action.

3-86
Early Return Logic for Event Broadcasts

State C is now the only active child 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 child of the chart. This behavior
violates the guideline that a state (or chart) with exclusive (OR) decomposition can never
have more than one active child. 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 Events to Synchronize States on page 11-52.

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

Create Stateflow Charts

Basic Approach for Modeling Event-Driven Systems on page 4-2


Represent Operating Modes Using States on page 4-5
Transition Between Operating Modes on page 4-18
Stateflow Editor Operations on page 4-26
4 Create Stateflow Charts

Basic Approach for Modeling Event-Driven Systems


In this section...
Identify System Attributes on page 4-2
Select a State Machine Type on page 4-2
Specify State Actions and Transition Conditions on page 4-3
Define Persistent Data to Store State Variables on page 4-3
Simplify State Actions and Transition Conditions with Function Calls on page 4-4
Check That Your System Representation Is Complete on page 4-4

Identify System Attributes


Before you build the Stateflow chart, identify your system attributes by answering these
questions:

1 What are your interfaces?

a What are the event triggers to which your system reacts?


b What are the inputs to your system?
c What are the outputs from your system?
2 Does your system have any operating modes?

a If the answer is yes, what are the operating modes?


b Between which modes can you transition? Are there any operating modes that
run in parallel?

If your system has no operating modes, the system is stateless. If your system has
operating modes, the system is modal.

Select a State Machine Type


After identifying your system attributes, the first step is to create a new chart. For more
information, see sfnew. Select one of the following state machine types:

Classic The default machine type. Provides the full set of semantics for MATLAB
charts and C charts.

4-2
Basic Approach for Modeling Event-Driven Systems

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 Chart Constructs Interact During Execution on
page 3-8, Differences Between MATLAB and C as Action Language Syntax on page
12-7, and Overview of Mealy and Moore Machines on page 6-2.

Specify State Actions and Transition Conditions


After you create an empty chart, answer the following questions:

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 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 11-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-18.
4 Implement the transition conditions by adding transition labels that use the
appropriate syntax. See Transition Action Types on page 11-8.

Define Persistent Data to Store State Variables


After adding state actions and transition conditions to your chart, determine if the chart
requires any local or persistent data to store state variables. If so, follow these steps:

1 Add local data to the appropriate level of the chart hierarchy. See Add Stateflow
Data on page 8-2.

You can also use the Symbol Wizard to add data to your chart. See Define Chart
Symbols with the Symbol Wizard on page 28-33.
2 Specify the type, size, complexity, and other data properties. See Set Data
Properties on page 8-6.

4-3
4 Create Stateflow Charts

Simplify State Actions and Transition Conditions with Function Calls


State actions and transition conditions can be complex enough that defining them inline
on the state or transition is not feasible. In this case, express the actions or conditions
using one of the following types of Stateflow functions:

Flow chart Encapsulate flow charts containing if-then-else, switch-case, for, while,
or do-while patterns.
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:

Reuse Logic Patterns Using Graphical Functions on page 7-32


MATLAB Functions in a Chart on page 26-2
Simulink Functions in Stateflow on page 27-2
What Is a Truth Table? on page 25-2

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 Share Data Using Custom C Code on page 28-25.

Check That Your System Representation Is Complete


Does your Stateflow chart fully express the logical or event-driven components of your
system?

If the answer is yes, you are done.


If the answer is no, you can create a separate chart or add hierarchy to your current
chart.

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

Represent Operating Modes Using States


In this section...
Create a State on page 4-5
Move and Resize States on page 4-6
Create Substates and Superstates on page 4-6
Group States on page 4-6
Specify Substate Decomposition on page 4-8
Specify Activation Order for Parallel States on page 4-9
Change State Properties on page 4-9
Label States on page 4-15

Create a State
You create states by drawing them in the editor for a particular chart (block). Follow
these steps:

1 Select the State tool:

2 Move your pointer into the drawing area.

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.

A text cursor appears in place of the question mark.


5 Enter a name for the state and click outside of the state when finished.

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

Move and Resize States


To move a state, do the following:

1 Click and drag the state.


2 Release it in a new position.

To resize a state, do the following:

1 Place your pointer over a corner of the state.

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.

Create Substates and Superstates


A substate is a state that can be active only when another state, called its parent, is
active. States that have substates are known as superstates. To create a substate, click
the State tool and drag a new state into the state you want to be the superstate. A
Stateflow chart creates the substate in the specified parent state. You can nest states in
this way to any depth. To change a substate's parentage, drag it from its current parent
in the chart and drop it in its new parent.

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 Using Subcharts on page 7-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.

4-6
Represent Operating Modes Using States

How to Group a 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.

When to Ungroup a State

You must ungroup a state before performing these actions:

Selecting objects inside the state


Moving other graphical objects into the state

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.

How to Ungroup a State

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

Specify Substate Decomposition


You specify whether a superstate contains parallel (AND) states or exclusive (OR) states
by setting its decomposition. A state whose substates are all active when it is active has
parallel (AND) decomposition. A state in which only one substate is active when it is
active has exclusive (OR) decomposition. An empty state's decomposition is exclusive.

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.

The appearance of a superstate's substates indicates the superstate's decomposition.


Exclusive substates have solid borders, parallel substates, dashed borders. A parallel
substate also contains a number in its upper right corner. The number indicates the
activation order of the substate relative to its sibling substates.

4-8
Represent Operating Modes Using States

Specify Activation Order for Parallel States


You can specify activation order by using one of two methods: explicit or implicit
ordering.

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-79 and
Implicit Ordering of Parallel States on page 3-80.

Note: The activation order of a parallel state appears in its upper right corner.

Change State Properties


Use the State dialog box to view and change the properties for a state. To access the
State dialog box:

1 Right-click the state and select Properties.

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

Properties You Can Set in the General Pane

The General pane of the State properties dialog box appears as shown.

4-9
4 Create Stateflow Charts

You can set these properties in the General pane.

Property Description
Name Stateflow chart name; read-only; click this hypertext link to
bring the state to the foreground.
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-78.

4-10
Represent Operating Modes Using States

Property Description
Create data for Select this option to create state activity data. See About
monitoring Active State Data on page 22-30.
Function Inline Select one of these options to control the inlining of state
Option functions in generated code:

Auto

Inlines state functions based on an internal heuristic.


Inline

Always inlines state functions in the parent function, as


long as the function is not part of a recursion. See Inline
State Functions in Generated Code (Simulink Coder)
Function

Creates separate static functions for each state.


Label The label for the state, which includes the name of the state
and its associated actions. See Label States on page 4-15.

Properties You Can Set in the Logging Pane

The Logging pane of the State properties dialog box appears as shown.

4-11
4 Create Stateflow Charts

You can set these properties in the Logging pane.

Property Description
Log self activity Saves the self activity value to the MATLAB workspace
during simulation.
Test point Designates the state as a test point that can be monitored
with a floating scope during model simulation. You can also

4-12
Represent Operating Modes Using States

Property Description
log test point values into MATLAB workspace objects. See
Monitor Test Points in Stateflow Charts on page 29-44.
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.

Properties You Can Set in the Documentation Pane

The Documentation pane of the State properties dialog box appears as shown.

4-13
4 Create Stateflow Charts

You can set these properties in the Documentation pane.

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

State labels have the following general format.

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

The italicized entries in this format have the following meanings:

Keyword Entry Description


Not applicable name A unique reference to the state with optional slash
entry or en entry actions Actions executed when a particular state is entered
as the result of a transition taken to that state
during or du during actions Actions that are executed when a state receives an
event while it is active with no valid transition away
from the state
exit or ex exit actions Actions executed when a state is exited as the result
of a transition taken away from the state
bind data or events Binds the specified data or events to this state.
Bound data can be changed only by this state or its
children, but can be read by other states. Bound
events can be broadcast only by this state or its
children.
on A specified event or message
event_or_message_name

and and

on event_name Actions executed when a state is active and the


actions specified event occurs or message is present.

For more information, see How Events Work


in Stateflow Charts on page 9-2 and How

4-15
4 Create Stateflow Charts

Keyword Entry Description


Messages Work in Stateflow Charts on page
10-2

Enter the Name

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.

An editing cursor appears. You are now free to type a 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.

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.

4-16
Represent Operating Modes Using States

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:
on ev1: action1(); on ev2: action2();

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.

4-17
4 Create Stateflow Charts

Transition Between Operating Modes


In this section...
Create a Transition on page 4-18
Label Transitions on page 4-19
Move Transitions on page 4-20
Change Transition Arrowhead Size on page 4-21
Create Self-Loop Transitions on page 4-22
Create Default Transitions on page 4-22
Change Transition Properties on page 4-22

Create a Transition
Follow these steps to create transitions between states and junctions:

1 Place your pointer on or close to the border of a source state or junction.

The pointer changes to crosshairs.


2 Click and drag a transition to a destination state or junction.
3 Release on the border of the destination state or junction.

Attached transitions obey the following rules:

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:

Create Self-Loop Transitions on page 4-22


Create Default Transitions on page 4-22

4-18
Transition Between Operating Modes

Label Transitions
Transition labels contain syntax that accompanies the execution of a transition. The
following topics discuss creating and editing transition labels:

Edit Transition Labels on page 4-19


Transition Label Format on page 4-19

For more information on transition concepts, see Transition Label Notation on page
2-21.

For more information on transition label contents, see Transition Action Types on page
11-8.

Edit Transition Labels

Label unlabeled transitions as follows:

1 Select (left-click) the transition.

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.

You can now type a 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.

Transition Label Format

Transition labels have the following general format:


event_or_message [condition]{condition_action}/transition_action

Specify, as appropriate, relevant names for event_or_message, condition,


condition_action, and transition_action.

Label Field Description


event_or_message The event or message that causes the transition to be
evaluated.
condition Defines what, if anything, has to be true for the condition
action and transition to take place.

4-19
4 Create Stateflow Charts

Label Field Description


condition_action If the condition is true, the action specified executes and
completes.
transition_action This action executes after the source state for the transition
is exited but before the destination state is entered.

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:

Bow the Transition Line on page 4-20


Move Transition Attach Points on page 4-21
Move Transition Labels on page 4-21

In addition, transitions move along with the movements of states and junctions.

Bow the Transition Line

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-20
Transition Between Operating Modes

The result is a bowed transition line. Repeat the preceding steps to move the transition
back into its original shape or into another shape.

Move Transition Attach Points

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.

Move Transition Labels

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.

Change Transition Arrowhead Size


The arrowhead size is a property of the destination object. Changing one of the incoming
arrowheads of an object causes all incoming arrowheads to that object to be adjusted to
the same size. The arrowhead size of any selected transitions, and any other transitions
ending at the same object, is adjusted.

To adjust arrowhead size:

4-21
4 Create Stateflow Charts

1 Select the transitions whose arrowhead size you want to change.


2 Place your pointer over a selected transition and right-click to select Arrowhead
Size.
3 Select an arrowhead size from the menu.

Create Self-Loop Transitions


A self-loop transition is a transition whose source and destination are the same state or
junction. To create a self-loop transition:

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.

For the semantics of self-loops, see Self-Loop Transitions on page 2-28.

Create Default Transitions


A default transition is a transition with a destination (a state or a junction), but no
apparent source object.

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

Default transitions can be labeled just like other transitions. See Label Default
Transitions on page 2-35 for an example.

Change Transition Properties


Use the Transition properties dialog box to view and change the properties for a
transition. To access the dialog box for a particular transition:

1 Right-click the transition and select Properties.

4-22
Transition Between Operating Modes

The Transition properties dialog box appears.

4-23
4 Create Stateflow Charts

4-24
Transition Between Operating Modes

The following transition properties appear in the dialog box:

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

4-25
4 Create Stateflow Charts

Stateflow Editor Operations


In this section...
Stateflow Editor on page 4-26
Undo and Redo Editor Operations on page 4-31
Specify Colors and Fonts in a Chart on page 4-31
Content Preview for Stateflow Objects on page 4-34
Intelligent Tab Completion for Stateflow Charts on page 4-35
Differentiate Elements of Action Language Syntax on page 4-36
Select and Deselect Graphical Objects on page 4-38
Cut and Paste Graphical Objects on page 4-38
Copy Graphical Objects on page 4-39
Comment Out Objects on page 4-39
Format Chart Objects on page 4-39
Generate a Model Report on page 4-54

Stateflow Editor
Use the Stateflow Editor to draw, zoom, modify, print, and save a chart shown in the
window.

Opening a Stateflow chart displays the chart in the Stateflow Editor.

To open a new Stateflow chart in the Stateflow Editor:

1 At the MATLAB command prompt, enter:

Command Result
sfnew Creates an 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.

4-26
Stateflow Editor Operations

Command Result
stateflow Creates an empty chart with the default
action language and displays the
Stateflow block library.

The Simulink Editor opens, with an empty chart.


2 Double-click the chart object.

The Stateflow Editor opens.

The Stateflow Editor window includes the following sections:

Title bar

4-27
4 Create Stateflow Charts

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
tool of the toolbar by placing your pointer over it until an identifying tool tip appears.
The toolbar also contains buttons for navigating a chart's subchart hierarchy (see
Navigate Subcharts on page 7-9).
Object palette

4-28
Stateflow Editor Operations

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.
Double-click the icon and then click multiple times in the drawing area to make
copies of the object.
Explorer bar

4-29
4 Create Stateflow Charts

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 shortcut 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-30
Stateflow Editor Operations

Undo and Redo Editor Operations


You can undo and redo operations that you perform in a chart. When you undo an
operation, you reverse the last edit operation that you performed. After you undo
operations in the chart, you can also redo them one at a time.

To undo an operation in the chart, select Edit > Undo.


To redo an operation in the chart, select Edit > Redo.

You can undo and redo many operations you complete on Stateflow objects in the
Symbols or Property Inspector windows.

Exceptions for Undo

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.

To understand subcharting, see Encapsulate Modal Logic Using Subcharts on page


7-5.
You cannot undo the drawing of a supertransition or the splitting of an existing
transition.

Splitting of an existing transition refers to the redirection of the source or destination


of a transition segment that is part of a supertransition. For a description of
supertransitions, see Draw a Supertransition Into a Subchart on page 7-12and
Draw a Supertransition Out of a Subchart on page 7-17.
You cannot undo any changes made to the chart using the Stateflow API.

For a description of the Stateflow API, see Programmatic Interface.

Note: When you perform one of the preceding operations, the undo and redo buttons
are disabled from undoing and redoing any prior operations.

Specify Colors and Fonts in a Chart


You can specify the color and font for items in a chart, for a single item or all items in the
chart.

4-31
4 Create Stateflow Charts

Change Fonts for a Single Item

You can change the font for a single item as follows:

1 Right-click the item.


2 In the context menu, select the font type, style, and size from Format > Font Style.

Colors & Fonts Dialog Box

The Colors & Fonts dialog box helps you specify a color scheme for the chart as a whole,
or colors and label fonts for different types of objects in a chart.

To display the Colors & Fonts dialog box, in the Stateflow Editor, select File > Stateflow
Preferences > Style.

The drawing area of the dialog box displays examples of the types of objects whose colors
and font labels you can specify. The examples use the colors and label fonts specified by

4-32
Stateflow Editor Operations

the current color scheme for the chart. To choose another color scheme, select the scheme
from the dialog box's Schemes menu. The dialog box displays the selected color scheme.
Click Apply to apply the selected scheme to the chart or OK to apply the scheme and
dismiss the dialog box.

To make the selected scheme the default scheme for all charts, select Make this the
"Default" scheme from the dialog box's Options menu.

To modify the current scheme, position your pointer over the example of the type of object
whose color or label font you want to change. Then left-click to change the object's color or
right-click to change the object's font. If you left-click, a color chooser dialog box appears.

Use the dialog box to select a new color for the selected object type.

If the selected object is a label and you right-click, a font selection dialog box appears.

4-33
4 Create Stateflow Charts

Use the font selector to choose a new font for the selected label.

To save changes to the default color scheme, select Save defaults to disk from the
Colors & Fonts dialog box's Options menu.

Note: Choosing Save defaults to disk has no effect if the modified scheme is not the
default scheme.

Content Preview for Stateflow Objects


When a chart is closed, you can preview the content of Stateflow charts in Simulink.
You can see an outline of the contents of a chart. During simulation you can see chart
animation. When a chart is open, you can preview the content of subcharts and Simulink
functions.

4-34
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 Hierarchical Items (Simulink).

Note: In order to see the content preview, you may need to enlarge the Stateflow chart or
object.

Intelligent Tab Completion for Stateflow Charts


Stateflow tab completion provides context-sensitive editing assistance. Tab completion
helps you avoid typographical errors. It also helps you quickly select syntax-appropriate

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

Additionally, you can:

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.

Differentiate Elements of Action Language Syntax


You can use color highlighting to differentiate the following syntax elements:

Keyword
Comment
Event
Message
Function
String
Number

Syntax highlighting is a user preference, not a model preference.

Default Syntax Highlighting

The following chart illustrates the default highlighting for language elements.

4-36
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-37. To disable
syntax highlighting, see Enable and Disable Syntax Highlighting on page 4-37.

Edit Syntax Highlighting

1 In the Stateflow Editor, select File > Stateflow Preferences > Syntax
Highlighting.

The Syntax Highlight Preferences dialog box appears.


2 Click the color that you want to change, choose an alternative from the color palette,
and click Apply.
3 Click OK to close the Syntax Highlight Preferences dialog box.

Enable and Disable Syntax Highlighting

1 In the Stateflow Editor, select File > Stateflow Preferences > Syntax
Highlighting.

4-37
4 Create Stateflow Charts

The Syntax Highlight Preferences dialog box appears.


2 Select or clear Enable syntax highlighting and click OK.

Select and Deselect Graphical Objects


Once an object is in the drawing area, to make any changes or additions to that object,
select it.

To select an object, click anywhere inside of the object.


To select multiple adjacent objects, click and drag a selection box so that the box
encompasses or touches the objects that you want to select, and then release the
mouse button.

All objects or portions of objects within the box become selected.


To select multiple separate objects, simultaneously press the Shift key and click an
object or box a group of objects.

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-31 for more
information).

Cut and Paste Graphical Objects


You can cut objects from the drawing area or cut and then paste them as many times as
you like. You can cut and paste objects from one chart to another. The chart retains a
selection list of the most recently cut objects. The objects are pasted in the drawing area
location closest to the current pointer location.

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-38
Stateflow Editor Operations

Copy Graphical Objects


To copy and paste an object in the drawing area, select the objects and right-click and
drag them to the desired location in the drawing area. This operation also updates the
chart's clipboard.

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.

Comment Out Objects


To Comment Out a Stateflow object, right-click the selected object and select Comment
Out. For more information, see Commenting Stateflow Objects in a Chart on page
29-69.

Format Chart Objects


To enhance readability of objects in a chart, in the Stateflow Editor you can use
commands in the Chart > Arrange menu. These commands include options for:

Alignment
Distribution
Resizing

You can align, distribute, or resize these chart objects:

States
Functions
Boxes

4-39
4 Create Stateflow Charts

Junctions

Align, Distribute, and Resize Chart Objects

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-78 and Evaluation Order for Outgoing Transitions on page 3-60.
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-40
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-41

Options for Distributing Chart Objects

This option... Distributes selected objects so that...


Distribute Horizontally The center-to-center horizontal distance between
any two objects is the same.

Note: The horizontal space for distribution is the


distance between the left edge of the leftmost
object and the right edge of the rightmost

4-41
4 Create Stateflow Charts

This option... Distributes selected objects so that...


object. If the total width of the objects you select
exceeds the horizontal space available, objects
can overlap after distribution.
Distribute Vertically The center-to-center vertical distance between
any two objects is the same.

Note: The vertical space for distribution is the


distance between the top edge of the highest
object and the bottom edge of the lowest object. If
the total height of the objects you select exceeds
the vertical space available, objects can overlap
after distribution.
Even Horizontal Gaps The horizontal white space between any two
objects is the same.

Note: The space restriction for Distribute


Horizontally applies.
Even Vertical Gaps The vertical white space between any two objects
is the same.

Note: The space restriction for Distribute


Vertically applies.

Example of Aligning Chart Objects

Suppose that you open the sf_pool model and see a chart with multiple MATLAB
functions.

4-42
Stateflow Editor Operations

To align the three MATLAB functions on the right:

1 Type sf_pool at the MATLAB command prompt to open the model. Double-click the
Pool block to open the chart.

Tip: Expand the Stateflow Editor to see the entire chart.


2 Click the function isAnyBallGoingToStop.
3 Shift-click the function isAnyBallNewlyPocketed.
4 Shift-click the function getBallInteraction.

4-43
4 Create Stateflow Charts

This object is the reference (or anchor) for aligning the three functions. Brackets
appear around the function.

5 Select Chart > Arrange > Align Right.

This step aligns the right edges of the three functions based on the right edge of
getBallInteraction.

4-44
Stateflow Editor Operations

Example of Distributing Chart Objects

Suppose that you open the sf_frame_sync_controller model and see a chart with
three states.

4-45
4 Create Stateflow Charts

To distribute the three states vertically:

1 Type sf_frame_sync_controller at the MATLAB command prompt to open the


model.

Tip: Double-click the Frame Sync Controller block to open the chart.
2 Select the three states in any order.

Shift-click to select more than one state.

4-46
Stateflow Editor Operations

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

Example of Resizing Chart Objects

Suppose that you open the sf_clutch 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:

1 Type sf_clutch at the MATLAB command prompt to open the model.


2 In the Friction Mode chart, select the three graphical functions by drawing a box
around them.
3 Set detectSlip as the reference object to use for resizing.

Right-click the function to mark it with brackets.

4-48
Stateflow Editor Operations

4 Select Chart > Arrange > Match Size.

This step ensures that the three functions are the same size.

4-49
4 Create Stateflow Charts

5 Adjust the function boxes to correct the format:

a To align the functions, select Chart > Arrange > Align Left.

4-50
Stateflow Editor Operations

b To distribute the functions evenly in terms of vertical spacing, select Chart >
Arrange > Even Vertical Gaps.

4-51
4 Create Stateflow Charts

Automatic Chart Formatting

With Arrange Automatically, Stateflow arranges your charts to:

Expand states and transitions to fit their label strings.


Resize similar states to be the same size.
Align states if they were slightly misaligned.

4-52
Stateflow Editor Operations

Straightens transitions.
Repositions horizontal transition labels to the midpoint.

To format your chart, select Chart > Arrange > Arrange Automatically.

In this example, the chart has:

1 State actions that are outside of the boundary for state A.


2 A transition condition that overlaps state B.
3 A transition that is not horizontal.

After the layout has been automatically arranged:

1 The state actions are contained within state A.


2 The transition condition does not overlap into state B.
3 The lower transition is horizontal.

4-53
4 Create Stateflow Charts

Generate a Model Report


The Print Details report is an extension of the Print Details report in the Simulink
model window. It provides a report of Stateflow and Simulink objects relative to the chart
currently in view from which you select the report.

To generate a model report on chart objects:

1 Open the chart or subchart for which you want a report.


2 In the editor, select File > Print > Print Details.

The Print Details dialog box appears.

4-54
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-56 and Report Format on page 4-56.
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.

The HTML report appears in your default browser.

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-55
4 Create Stateflow Charts

System Report Options

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 general top-down format of the Print Details report is as follows:

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

Model Logic Patterns and Iterative


Loops Using Flow Charts

What Is a Flow Chart? on page 5-2


Difference Between Flow Charts and State Transition Diagrams on page 5-3
When to Use Flow Charts on page 5-4
Create Flow Charts with the Pattern Wizard on page 5-5
Draw and Customize Flow Charts By Hand on page 5-29
Best Practices for Creating Flow Charts on page 5-31
5 Model Logic Patterns and Iterative Loops Using Flow Charts

What Is a Flow Chart?


A flow chart is a graphical construct that models logic patterns by using connective
junctions and transitions. The junctions provide decision branches between alternate
transition paths. You can use flow charts to represent decision and iterative loop logic.

Here is an example of a flow chart that models simple if-else logic:

This flow chart models the following code:


if (u > 0)
{
y = 1;
}
else
{
y = 0;
}

5-2
Difference Between Flow Charts and State Transition Diagrams

Difference Between Flow Charts and State Transition Diagrams


A flow chart is used for combinatorial design. It is a stateless flow chart because it
cannot maintain its active state between updates. As a result, a flow chart always begins
executing from a default transition and ends at a terminating junction (a junction that
has no valid outgoing transitions).

By contrast, a state transition diagram is used for sequential design. It stores its current
state in memory to preserve local data and activity between updates. As a result, state
diagrams can begin executing where they left off in the previous time step, making them
suitable for modeling reactive or supervisory systems that depend on history. In these
kinds of systems, the current result depends on a previous result.

Related Examples
Create Flow Charts with the Pattern Wizard on page 5-5

More About
States on page 2-7
Transitions on page 2-19

5-3
5 Model Logic Patterns and Iterative Loops Using Flow Charts

When to Use Flow Charts


Use flow charts to represent combinatorial logic in graphical functions or between states
in a chart. A best practice is to encapsulate flow charts in graphical functions to create
modular, reusable decision and loop logic that you can call anywhere in a chart. For
more information about graphical functions, see Reuse Logic Patterns Using Graphical
Functions on page 7-32.

5-4
Create Flow Charts with the Pattern Wizard

Create Flow Charts with the Pattern Wizard

In this section...
Why Use the Pattern Wizard? on page 5-5
How to Create Reusable Flow Charts on page 5-5
Insert a Logic Pattern Using the Pattern Wizard on page 5-7
Save and Reuse Flow Chart Patterns on page 5-10
MAAB-Compliant Patterns from the Pattern Wizard on page 5-12
Create and Reuse a Custom Pattern with the Pattern Wizard on page 5-21

Why Use the Pattern Wizard?


The Pattern Wizard is a utility that generates common flow chart patterns for use in
graphical functions and charts. Although you can also create flow charts by hand, the
Pattern Wizard offers several advantages:

Generates common logic and iterative loop patterns automatically


Generates patterns that comply with guidelines from the MathWorks Automotive
Advisory Board (MAAB)
Promotes consistency in geometry and layout across patterns
Facilitates storing and reusing patterns from a central location
Provides ability to insert patterns in existing flow graph

Note: The Pattern Wizard is only used for flow charts, and cannot be used to save states
and subcharts. Atomic subcharts can be used to reuse states and subcharts.

How to Create Reusable Flow Charts


When you create flow charts with the Pattern Wizard, you can save them to a central
location where you can retrieve them for reuse. To create reusable flow charts that
comply with MAAB guidelines:

1 Open a chart.

5-5
5 Model Logic Patterns and Iterative Loops Using Flow Charts

How do I create and open a new Stateflow chart?

a Type sfnew or stateflow at the MATLAB command prompt.

A model opens, containing an empty chart.


b Double-click the chart to open it.
2 Select a flow chart pattern:

To Create: Select: Reference


if decision patterns Chart > Add Pattern in Decision Logic Patterns
Chart > Decision in Flow Charts on page
5-12
for-, while-, and Chart > Add Pattern in Iterative Loop Patterns
do-while-loop patterns Chart > Loop in Flow Charts on page
5-16
switch patterns Chart > Add Pattern in Switch Patterns in Flow
Chart > Switch Charts on page 5-17

The Stateflow Patterns dialog box appears.


3 Enter a description of your pattern (optional).
4 Specify conditions and actions (optional).

You can also add or change conditions and actions directly in the chart.
5 Click OK.

The pattern appears in your chart. The geometry and layout comply with MAAB
guidelines.
6 Customize the pattern as desired.

For example, you may want to add or change flow charts, conditions, or actions. See
Create and Reuse a Custom Pattern with the Pattern Wizard on page 5-21.
7 Save the pattern to a central location as described in Save and Reuse Flow Chart
Patterns on page 5-10.

You can now retrieve your pattern directly from the editor to reuse in graphical functions
and charts. See How to Add Flow Chart Patterns in Graphical Functions on page
5-11 and How to Add Flow Chart Patterns in Charts on page 5-11.

5-6
Create Flow Charts with the Pattern Wizard

Insert a Logic Pattern Using the Pattern Wizard


Using the Pattern Wizard, you can add loop or decision logic extensions to a previously
created pattern in a flow chart. Select an eligible vertical transition, and then select
Chart > Insert Pattern on Selection. After you select one of the decision or loop
patterns, the Pattern Wizard places the new pattern below the action along the
transition path.

When you create logic extensions, the following rules apply:

Select only one exactly vertical transition to extend at a time.


Select a vertical transition that has a destination junction.
Extend only a flow chart that was created by the Pattern Wizard.
Extend only a flow chart that has junctions and transitions in the chart, not other
objects.
Do not extend a pattern that has been custom-created or modified.
You cannot choose a custom pattern as the extension.

If your selection is not eligible, 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 editor.

Insert a Pattern

In this example, you add an if-else pattern into a while-loop body.

1 Open a chart.
2 Select Chart > Add Pattern in Chart > Loop > While.

5-7
5 Model Logic Patterns and Iterative Loops Using Flow Charts

3 Enter a description of your pattern (optional).


4 Specify conditions and actions (optional).

You can also add or change conditions and actions directly in the chart.
5 Click OK.

The while pattern appears in your chart.

6 Select the vertical transition labeled {action1}.


7 Select Chart > Insert Pattern on Selection > Decision > If-Else.
8 Click OK.

The if-else pattern is added to the while-loop below {action1}.

5-8
Create Flow Charts with the Pattern Wizard

5-9
5 Model Logic Patterns and Iterative Loops Using Flow Charts

Save and Reuse Flow Chart Patterns


Using the Pattern Wizard, you can save flow chart patterns in a central location, then
easily retrieve and reuse them in Stateflow graphical functions and charts. The Pattern
Wizard lets you access all saved patterns from the editor.

Guidelines for Creating a Pattern Folder

The Pattern Wizard uses a single, flat folder for saving and retrieving flow chart
patterns. Follow these guidelines when creating your pattern folder:

Store all flow charts at the top level of the pattern folder; do not create subfolders.
Make sure all flow chart files have a .mdl or .slx extension.

How to Save Flow Chart Patterns for Easy Retrieval

1 Create a folder for storing your patterns according to Guidelines for Creating a
Pattern Folder on page 5-10.
2 In your chart, select flow charts with the patterns you want to save.
3 Select Chart > Save Pattern.

The Pattern Wizard displays a message that prompts you to choose a folder for
storing custom patterns.

The Pattern Wizard stores your flow charts in the pattern folder as a model file.
The patterns that you save in this folder appear in a drop-down list when you select
Chart > Add Pattern in Chart > Custom, as described in How to Add Flow Chart
Patterns in Graphical Functions on page 5-11 and How to Add Flow Chart
Patterns in Charts on page 5-11.
4 Click OK to dismiss the message.

The Browse For Folder dialog box appears.


5 Select the designated folder (or create a new folder) and click OK.

The Save Pattern As dialog box appears.


6 Enter a name for your pattern and click Save.

The Pattern Wizard saves your pattern as a model file in the designated folder.

5-10
Create Flow Charts with the Pattern Wizard

How to Change Your Pattern Folder

1 Rename your existing pattern folder.


2 Add a pattern as described in How to Add Flow Chart Patterns in Graphical
Functions on page 5-11 or How to Add Flow Chart Patterns in Charts on page
5-11.

The Pattern Wizard prompts you to choose a folder.


3 Follow the instructions in How to Save Flow Chart Patterns for Easy Retrieval on
page 5-10.

How to Add Flow Chart Patterns in Graphical Functions

1 Add a graphical function to your chart.

See Create a Graphical Function on page 7-23.


2 Make the graphical function into a subchart by right-clicking in the function box and
selecting Group & Subchart > Subchart.

The function box turns gray.


3 Double-click the subcharted graphical function to open it.
4 In the menu bar, select Chart > Add Pattern in Function > Custom.

The Select a Custom Pattern dialog box appears, displaying all of your saved
patterns.

Why does my dialog box not display any patterns?

You have not saved any patterns for the Pattern Wizard to retrieve. See Save and
Reuse Flow Chart Patterns on page 5-10.
5 Select a pattern from the list in the dialog box and click OK.

The pattern appears in the graphical function, which expands to fit the flow chart.
6 Define all necessary inputs, outputs, and local data in the graphical function and the
chart that calls it.

How to Add Flow Chart Patterns in Charts

1 In the menu bar, select Chart > Add Pattern in Chart > Custom.

5-11
5 Model Logic Patterns and Iterative Loops Using Flow Charts

The Select a Custom Pattern dialog box appears, displaying all of your saved
patterns.
2 Select a pattern from the list in the dialog box and click OK.

The pattern appears in the chart.


3 Adjust the chart by hand to:

Connect the flow charts to the appropriate transitions.


Ensure that there is only one default transition for exclusive (OR) states at each
level of hierarchy.
Define all necessary inputs, outputs, and local data.

MAAB-Compliant Patterns from the Pattern Wizard


The Pattern Wizard generates MAAB-compliant flow charts.

Decision Logic Patterns in Flow Charts

The Pattern Wizard generates the following MAAB-compliant decision logic patterns:

if

5-12
Create Flow Charts with the Pattern Wizard

if-else

if-elseif

5-13
5 Model Logic Patterns and Iterative Loops Using Flow Charts

if-elseif-else

5-14
Create Flow Charts with the Pattern Wizard

if-elseif-elseif-else

5-15
5 Model Logic Patterns and Iterative Loops Using Flow Charts

Nested if

Iterative Loop Patterns in Flow Charts

The Pattern Wizard generates the following MAAB-compliant iterative loop patterns:

for

5-16
Create Flow Charts with the Pattern Wizard

while

do-while

Switch Patterns in Flow Charts

The Pattern Wizard generates the following MAAB-compliant switch patterns:

5-17
5 Model Logic Patterns and Iterative Loops Using Flow Charts

switch with two cases and default

5-18
Create Flow Charts with the Pattern Wizard

switch with three cases and default

5-19
5 Model Logic Patterns and Iterative Loops Using Flow Charts

switch with four cases and default

5-20
Create Flow Charts with the Pattern Wizard

Create and Reuse a Custom Pattern with the Pattern Wizard


This example shows how to create, modify, and save a custom flow chart pattern for
iterating over the upper triangle of a two-dimensional matrix. In the upper triangle, the
row index i is always less than or equal to column index j. This flow chart pattern uses
nested for-loops to ensure that i never exceeds j.

Create the Upper Triangle Iterator Pattern

1 Open a new (empty) chart.


2 Select Chart > Add Pattern in Chart > Loop > For.
3 In the Stateflow Patterns dialog box, enter the initializer, loop test, and counting
expressions for iterating through the first dimension of the matrix, as follows:

Do not specify an action yet. You will add another loop for iterating the second
dimension of the matrix.
4 Click OK.

The Pattern Wizard generates the first iterative loop in your chart.

5-21
5 Model Logic Patterns and Iterative Loops Using Flow Charts

This pattern:

Conforms to all best practices for creating flow charts, as described in Best
Practices for Creating Flow Charts on page 5-31.
Provides the correct syntax for conditions and condition actions.
5 Add the second loop:

a Expand the editor window so the chart can accommodate a second pattern.
b Select the vertical transition labelled {action1}.
c Select Chart > Insert Pattern on Selection > Loop > For.
d Enter the initializer, loop test, and counting expressions for the second iterator
j, and a placeholder for an action to retrieve each element in the upper triangle
as follows:

5-22
Create Flow Charts with the Pattern Wizard

e Click OK. The Pattern Wizard adds the second loop to the first loop.

5-23
5 Model Logic Patterns and Iterative Loops Using Flow Charts

6 Save your chart.

Save your pattern to a central location for reuse (see Save the Upper Triangle Iterator
Pattern for Reuse on page 5-24).

Save the Upper Triangle Iterator Pattern for Reuse

1 Create a folder for storing flow chart patterns, as described in Guidelines for
Creating a Pattern Folder on page 5-10.
2 Open the chart that contains the custom pattern.
3 In the chart, select the flow chart with the pattern that you want to save.
4 In the editor, select Chart > Save Pattern and take one of these actions.

5-24
Create Flow Charts with the Pattern Wizard

If you have... Then Pattern Wizard... Action


Not yet designated the Prompts you to create or Select the folder you just
pattern folder select a pattern folder created. See How to Save
Flow Chart Patterns for
Easy Retrieval on page
5-10.
Already designated the Prompts you to save your Name your pattern and
pattern folder pattern to the designated click Save.
folder

The Pattern Wizard automatically saves your pattern as a model file under the name
that you specify.

Add the Upper Triangle Iterator Pattern to a Graphical Function

1 Open a new chart.


2 Drag a graphical function into the chart from the object palette.
3 Enter the following function signature:

function y = ut_iterator(u, numrow, numcol)

The function takes three inputs.

Input Description
u 2-D matrix
numrow Number of rows in the matrix
numcol Number of columns in the matrix
4 Right-click inside the function and select Group & Subchart > Subchart.

The function looks like this graphic.

5-25
5 Model Logic Patterns and Iterative Loops Using Flow Charts

5 Double-click to open the subcharted function and select Chart > Add Pattern in
Function > Custom.

The Select a Custom Pattern dialog box opens, listing all the patterns that you have
saved in your pattern folder.

5-26
Create Flow Charts with the Pattern Wizard

6 Select your upper triangle iterator pattern and click OK.

The Pattern Wizard adds your custom pattern to the graphical function.

5-27
5 Model Logic Patterns and Iterative Loops Using Flow Charts

Before calling this function from a chart, be sure to modify data names, types, and sizes
as necessary and substitute an appropriate action.

5-28
Draw and Customize Flow Charts By Hand

Draw and Customize Flow Charts By Hand


In this section...
How to Draw a Flow Chart on page 5-29
How to Change Connective Junction Size on page 5-29
How to Modify Junction Properties on page 5-29

How to Draw a Flow Chart


You can draw and customize flow charts manually by using connective junctions as
branch points between alternate transition paths:

1 Open a chart.
2 From the editor toolbar, drag one or more connective junctions into the chart using
the Connective Junction tool:

3 Add transition paths between junctions.


4 Label the transitions.
5 Add a default transition to the junction where the flow chart should start.

How to Change Connective Junction Size


To change the size of connective junctions:

1 Select one or more connective junctions.


2 Right-click one of the selected junctions and select Junction Size from the drop-
down menu.

A menu of junction sizes appears.


3 Select a junction size.

How to Modify Junction Properties


To modify the properties of a connective junction:

5-29
5 Model Logic Patterns and Iterative Loops Using Flow Charts

1 Right-click a connective junction and select Properties from the drop-down menu.

The Connective Junction dialog box appears.

2 Edit the fields in the dialog as desired.

Field Description
Parent Parent of the connective junction (read-only). Click the
hypertext link to bring the parent to the foreground.
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.
3 Click Apply to save changes.

5-30
Best Practices for Creating Flow Charts

Best Practices for Creating Flow Charts


Follow these best practices to create efficient, accurate flow charts:

Use only one default transition

Flows charts should have a single entry point.

Provide only one terminating junction

Multiple terminating junctions reduce readability of a flow chart.

Converge all transition paths to the terminating junction

This guideline ensures that execution of a flow chart always reaches the termination
point.

Provide an unconditional transition from every junction except the terminating junction

This guideline ensures that unintended backtracking behavior does not occur in a flow
chart. If unintended backtracking occurs during simulation, a warning message appears.

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.

Unintended backtracking can occur at a junction under these conditions:

The junction does not have an unconditional transition path to a state or terminating
junction.
Multiple transition paths lead to that junction.

Use condition actions to process updates, not transition actions

Flow charts test transitions, but do not execute them (and, therefore, never execute
transition actions).

The following example illustrates these best practices:

5-31
5 Model Logic Patterns and Iterative Loops Using Flow Charts

5-32
6

Build Mealy and Moore Charts

Overview of Mealy and Moore Machines on page 6-2


Create Mealy and Moore Charts on page 6-5
Model a Vending Machine Using Mealy Semantics on page 6-6
Design Considerations for Mealy Charts on page 6-8
Design Considerations for Moore Charts on page 6-11
Model a Traffic Light Using Moore Semantics on page 6-16
Effects of Changing the Chart Type on page 6-19
Debug Mealy and Moore Charts on page 6-20
6 Build Mealy and Moore Charts

Overview of Mealy and Moore Machines


In this section...
Semantics of Mealy and Moore Machines on page 6-2
Model with Mealy and Moore Machines on page 6-3
Default State Machine Type on page 6-3
Availability of Output on page 6-3
Advantages of Mealy and Moore Charts on page 6-3

Semantics of Mealy and Moore Machines


Mealy and Moore are often considered the basic, industry-standard paradigms for
modeling finite-state machines. Generally in state machine models, the next state is a
function of the current state and its inputs, as follows:

X (n + 1) = f ( X (n),u)

In this equation:

X(n) Represents the state at time step n


X(n+1) Represents the state at the next time step n+1
u Represents inputs

State is a combination of local data and chart activity. Therefore, computing state means
updating local data and making transitions from a currently active state to a new state.
State persists from one time step to another.

In this context, Mealy and Moore machines each have well-defined semantics.

Type of Semantics Applications


Machine
Mealy Output is a function of inputs and Clocked synchronous machines
state: where state transitions occur on
clock edges
y = g ( X , u)

6-2
Overview of Mealy and Moore Machines

Type of Semantics Applications


Machine
Moore Output is a function only of state: Clocked synchronous machines
where outputs are modified at clock
y = g ( X) edges

You can create charts that implement pure Mealy or Moore semantics as a subset of
Stateflow chart semantics (see Create Mealy and Moore Charts on page 6-5).
Mealy and Moore charts can be used in simulation and code generation with Embedded
Coder, Simulink Coder, and HDL Coder software, which are available separately.

Model with Mealy and Moore Machines


Stateflow software ships with a model that shows how to use Mealy and Moore machines
for sequence recognition in signal processing. To open the model, enter sf_seqrec at the
MATLAB prompt.

Default State Machine Type


When you create a Stateflow chart, the default type is a hybrid state machine model that
combines the semantics of Mealy and Moore charts with the extended Stateflow chart
semantics. This default chart type is called Classic.

Availability of Output
Mealy machines compute output on transitions, while Moore machines compute outputs
in states. Therefore, Mealy charts can compute output earlier than Moore charts
that is, at the time the chart's default path 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). By contrast, Moore
machines can compute outputs only after the default path executes. Until then, outputs
take the default values.

Advantages of Mealy and Moore Charts


Mealy and Moore charts offer the following advantages over Classic Stateflow charts:

6-3
6 Build Mealy and Moore Charts

You can verify the Mealy and Moore charts you create to ensure that they 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, both 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. Therefore, 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 error with an algebraic loop.

More About
Design Considerations for Mealy Charts on page 6-8
Design Considerations for Moore Charts on page 6-11

6-4
Create Mealy and Moore Charts

Create Mealy and Moore Charts


To create a new Mealy or Moore chart, follow these steps:

1 Add a new Chart block to a Simulink model; then double-click the block to open the
Stateflow Editor.
2 Right-click in an empty area of the chart and select Properties.

The Chart Properties dialog box opens.


3 From the State Machine Type drop-down menu, select Mealy or Moore.
4 Click OK.

The chart icon updates to display the selected chart type:

Mealy Moore

5 Design your chart according to the guidelines for the chart type (see Design
Considerations for Mealy Charts on page 6-8 and Design Considerations for
Moore Charts on page 6-11.

6-5
6 Build Mealy and Moore Charts

Model a Vending Machine Using Mealy Semantics


The following chart uses Mealy semantics to model a vending machine.

Open the Model


To open the model of a Mealy vending machine, type sf_mealy_vending_machine at
the MATLAB command prompt.

Logic of the Mealy Vending Machine


In this example, the vending machine requires 15 cents to release a can of soda. The
purchaser can insert a nickel or a dime, one at a time, to purchase the soda. The chart

6-6
Model a Vending Machine Using Mealy Semantics

behaves like a Mealy machine because its output soda depends on both the input coin
and current state, as follows:

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

In active state got_nickel. A nickel was received.

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

In active state got_dime. A dime was received.

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

Design Rules in Mealy Vending Machine


This example of a Mealy vending machine illustrates the following Mealy design rules:

The chart computes outputs in condition actions.


There are no state actions or transition actions.
The chart defines chart inputs (coin) and outputs (soda).
The value of the input coin determines the output whether or not soda is released.

6-7
6 Build Mealy and Moore Charts

Design Considerations for Mealy Charts


In this section...
Mealy Semantics on page 6-8
Design Rules for Mealy Charts on page 6-8

Mealy Semantics
To ensure that output is a function of input and state, Mealy state machines enforce the
following semantics:

Outputs never depend on previous outputs.


Outputs never depend on the next state.
Chart wakes up periodically based on a system clock.

Note: A chart provides one time base for input and clock (see Calculate Output and
State Using One Time Base on page 6-10).
Chart must compute outputs whenever there is a change on the input port.
Chart must compute outputs only in transitions, not in states.

Design Rules for Mealy Charts


To conform to the Mealy definition of a state machine, you must ensure that a Mealy
chart computes outputs every time there is a change on the input port. As a result, you
must follow a set of design rules for Mealy charts.

Compute Outputs in Condition Actions Only on page 6-8


Do Not Use State Actions or Transition Actions on page 6-9
Restrict Use of Data on page 6-9
Restrict Use of Events on page 6-9
Calculate Output and State Using One Time Base on page 6-10

Compute Outputs in Condition Actions Only

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.

6-8
Design Considerations for Mealy Charts

Do Not Use State Actions or Transition Actions

You cannot use state actions or transition actions in Mealy charts. This restriction
enforces Mealy semantics by:

Preventing you from computing output without considering changes on the input port
Ensuring that output depends on current state and not next state

Restrict Use of Data

You can define inputs, outputs, local data, parameters, and constants in Mealy charts,
but other data restrictions apply:

Restrict Machine-Parented Data on page 6-9


Do Not Define Data Store Memory on page 6-9

Restrict Machine-Parented Data

Machine-parented data is data that you define for a Stateflow machine, which is the
collection of all Stateflow blocks in a Simulink model. The Stateflow machine is the
highest level of the Stateflow hierarchy. When 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 DSM objects can
be modified by objects external to the chart. A Stateflow chart uses data store memory
to share data with a Simulink model. Data store memory acts as global data that can be
modified by other blocks and models in the Simulink hierarchy that contains the chart.
Mealy charts should not access data that can change unpredictably.

Restrict Use of Events

Limit the use of events in Mealy charts as follows:

Do: Do Not:
Use input events to trigger the chart Broadcast any type of event

6-9
6 Build Mealy and Moore Charts

Do: Do Not:
Use event-based temporal logic to guard Use local events to guard transitions
transitions
You cannot use local events in Mealy charts
You can use event-based temporal logic because they are not deterministic. These
in Mealy charts because it behaves events can occur while the chart computes
synchronously (see Operators for Event- outputs and, therefore, violate Mealy
Based Temporal Logic on page 11-57). semantics that require charts to compute
Think of the change in value of a temporal outputs whenever input changes.
logic condition as an event that the chart
schedules internally. Therefore, at each Use implicit events such as
time step, the chart retains its notion of chg(data_name), en(state_name), or
state because it knows how many ticks ex(state_name).
remain before the temporal event executes.

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

Calculate Output and State Using One Time Base

You can use one time base for clock and input, as determined by the Simulink solver (see
Solvers (Simulink)). 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.

6-10
Design Considerations for Moore Charts

Design Considerations for Moore Charts


In this section...
Moore Semantics on page 6-11
Design Rules for Moore Charts on page 6-11

Moore Semantics
In Moore charts, output is a function of current state only. At every time step, a Moore
chart wakes up, computes its outputs, and then evaluates its inputs to reconfigure itself
for the next time step. For example, after evaluating its inputs, the Moore chart might
take transitions to a new configuration of active states, also called next state. However,
the Moore chart must always compute its outputs before changing state.

To ensure that output is a function only of state, Moore state machines enforce the
following semantics:

Outputs depend only on the current state, not inputs.


Outputs do not depend on previous outputs.
Chart must compute outputs only in states, not in transitions.
Chart must compute outputs before updating state.

Design Rules for Moore Charts


To conform to the Moore definition of a state machine, you must ensure that every time a
Moore chart wakes up, it computes outputs from the current set of active states without
regard to input. Therefore, you must follow a set of design rules for Moore charts.

Compute Outputs in State Actions, Not on Transitions on page 6-12


Restrict Data Scope on page 6-12
Do Not Use Inputs to Compute Outputs on page 6-13
Do Not Use coder.extrinsic to Call Extrinsic Functions on page 6-13
Do Not Use Actions on Transitions on page 6-13
Do Not Use a Pure Flow Graph on page 6-14
Do Not Use Simulink Functions on page 6-14

6-11
6 Build Mealy and Moore Charts

Do Not Export Functions on page 6-14


Do Not Disable Inlining on page 6-14
Do Not Enable Super Step Semantics on page 6-14
Do Not Use Messages on page 6-14
Restrict Use of Events on page 6-14
Do Not Use Moore Charts for Modeling Systems with Continuous-Time on page
6-15

Compute Outputs in State Actions, Not on Transitions

To ensure that outputs depend solely on current state, you must compute outputs in state
actions, subject to the following restrictions:

Combine Actions on page 6-12


Do Not Label State Actions on page 6-12

You cannot define actions on transitions because transitions almost always depend on
inputs. For example, if you compute outputs in a condition action on a transition, the
chart updates outputs whenever there is a change on the input, which is a violation of
Moore semantics.
Combine Actions

For Classic charts, you can define different types of actions in states (see State Action
Types on page 11-2). In Moore charts, you can include only one action per state. The
action for a state 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 en,du, or ex.

Restrict Data Scope

In Moore charts, these data restrictions apply:

Restrict Machine-Parented Data on page 6-13


Do Not Define Data Store Memory on page 6-13

6-12
Design Considerations for Moore Charts

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 modify DSM objects. A Stateflow chart uses data store memory to share data
with a Simulink model. Data store memory acts as global data. Other blocks and models
in the Simulink hierarchy that contains the chart can modify DSM. Moore charts must
not access data that can change unpredictably.

Do Not Use Inputs to Compute Outputs

In Moore charts, outputs cannot depend on inputs. Therefore, using an input to


contribute directly or indirectly to the computation of an output triggers an error.

Do Not Use coder.extrinsic to Call Extrinsic Functions

When calling extrinsic functions with coder.extrinsic, it is not possible to enforce


that the outputs depend only on the current state. Therefore, calling an extrinsic function
with coder.extrinsic in a Moore chart triggers an error.

Do Not Use Actions on Transitions

You cannot define condition actions or transition actions in Moore charts.

These transitions are not valid in a Moore chart.

6-13
6 Build Mealy and Moore Charts

Here, each transition tests input u in a condition, but modifies output y in a condition
action, based on the value of the input. This construct violates Moore semantics and
triggers an error. Similarly, you cannot use transition actions in Moore charts.

Do Not Use a Pure Flow Graph

Because Moore charts cannot have condition or transition actions, use states to produce
actions.

Do Not Use Simulink Functions

You cannot use Simulink functions in Moore charts. This restriction prevents violations
of Moore semantics during chart execution.

Do Not Export Functions

You cannot exports functions in a Moore chart.

Do Not Disable Inlining

Moore chart semantics require inlining. Do not force inlining off.

Do Not Enable Super Step Semantics

You cannot use super step semantics in a Moore chart.

Do Not Use Messages

You cannot use messages in a Moore chart.

Restrict Use of Events

Limit the use of events in Moore charts:

Valid: Do Not Use:


Use only one input event to trigger the Broadcast any type of event.
chart.
Use event-based temporal logic to guard Use local events to guard transitions.
transitions.
You cannot use local events in Moore charts
You can use event-based temporal logic because they are not deterministic. These
in Moore charts because the logic behaves events can occur while the chart computes

6-14
Design Considerations for Moore Charts

Valid: Do Not Use:


synchronously (see Operators for Event- outputs and, therefore, violate Moore
Based Temporal Logic on page 11-57). semantics.
Think of the change in value of a temporal
logic condition as an event that the chart Use implicit events such as
schedules internally. Therefore, at each chg(data_name), en(state_name), or
time step, the chart retains its notion ex(state_name).
of state because it knows how many
ticks remain before the temporal event
executes.

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

Do Not Use Moore Charts for Modeling Systems with Continuous-Time

In Moore charts, you cannot set the update method to Continuous. For modeling
systems with continuous-time in Stateflow, use Classic or Mealy charts.

6-15
6 Build Mealy and Moore Charts

Model a Traffic Light Using Moore Semantics


The following chart uses Moore semantics to model a traffic light:

Open the Model


To open the model of a Moore traffic light, type sf_moore_traffic_light at the
MATLAB command prompt.

Logic of the Moore Traffic Light


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.

6-16
Model a Traffic Light Using Moore Semantics

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, as follows:

When initial state Stop is active. Traffic light is red for North-South, green for
East-West.

Sets output y1 = RED (North-South) based on current state.


Sets output y2 = GREEN (East-West) based on current state.
After 20 clock ticks, active state becomes StopForTraffic.

In active state StopForTraffic. Traffic light has been red for North-South, green for
East-West for at least 20 clock ticks.

Sets output y1 = RED (North-South) based on current state.


Sets output y2 = GREEN (East-West) based on current state.
Checks sensor.
If sensor indicates cars are waiting ([sens] is true) in the North-South direction,
active state becomes StopToGo.

In active state StopToGo. Traffic light must reverse traffic flow in response to
sensor.

Sets output y1 = RED (North-South) based on current state.


Sets output y2 = YELLOW (East-West) based on current state.
After 3 clock ticks, active state becomes Go.

In active state Go. Traffic light has been red for North-South, yellow for East-West
for 3 clock ticks.

Sets output y1 = GREEN (North-South) based on current state.


Sets output y2 = RED (East-West) based on current state.
After 10 clock ticks, active state becomes GoToStop.

In active state GoToStop. Traffic light has been green for North-South, red for East-
West for 10 clock ticks.

6-17
6 Build Mealy and Moore Charts

Sets output y1 = YELLOW (North-South) based on current state.


Sets output y2 = RED (East-West) based on current state.
After 3 clock ticks, active state becomes Stop.

Design Rules in Moore Traffic Light


This example of a Moore traffic light illustrates the following Moore design rules:

The chart computes outputs in state actions.


The chart tests inputs in conditions on transitions.
The chart uses temporal logic, but no asynchronous events.
The chart defines chart inputs (sens) and outputs (y1 and y2).

6-18
Effects of Changing the Chart Type

Effects of Changing the Chart Type


The 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 type usually requires
you to redesign your chart to achieve equivalent behavior that is, where both charts
produce the same sequence of outputs given the identical sequence of inputs. To assist
you, diagnostic messages appear at compile time (see Debug Mealy and Moore Charts
on page 6-20). In some cases, however, there may be no way to translate specific
behaviors without violating chart definitions.

Here is 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 confirms to Mealy semantic rules, the Mealy
chart exhibits equivalent behavior, provided that output is defined at
every time step.
Moore Classic State actions in the Moore chart behave as entry actions because
they are not labeled. Therefore, the Classic chart will not exhibit
behavior that is equivalent to the original Moore chart. Requires
redesign.
Classic Moore Actions that are unlabeled in the Classic chart ( entry actions by
default) behave as during and exit actions. Therefore, the Moore
chart will not exhibit behavior that is equivalent to the original
Classic chart. Requires redesign.
Mealy Moore Converting between these two types does not produce equivalent
Moore Mealy behavior because Mealy and Moore rules about placement of actions
are mutually exclusive. Requires redesign.

6-19
6 Build Mealy and Moore Charts

Debug Mealy and Moore Charts


At compile time, informative diagnostic messages appear to help you:

Design Mealy and Moore charts from scratch


Redesign legacy Classic charts to conform to Mealy and Moore semantics
Redesign charts to convert between Mealy and Moore types

For example, recall the Mealy vending machine chart described in Model a Vending
Machine Using Mealy Semantics on page 6-6.

If you change the chart type to Moore and rebuild, you get the following diagnostic
message:

6-20
Debug Mealy and Moore Charts

Stateflow Moore chart cannot have condition or transition actions.

This message indicates that you cannot define actions on transitions. Without actions,
you cannot compute outputs on transitions in Moore charts (see Do Not Use Actions on
Transitions on page 6-13). According to Moore semantics, you must instead compute
outputs in state actions (see Design Rules for Moore Charts on page 6-11).

In the Mealy chart, each condition action computes output (whether or not soda is
released) based on input (the coin received). Each state represents one of the three
possible coin inputs: nickel, dime, or no coin. The Mealy chart computes the output as it
transitions to the next state. When you move this logic out of transitions and into state
actions in the Moore chart, you need more states. The reason is that in the Moore chart,
each state must represent not only coins received, but also the soda release condition.
The Moore chart must compute output according to the active state before considering
input. As a result, there will be a delay in releasing soda, even if the machine receives
enough money to cover the cost.

The equivalent vending machine, designed as a Moore chart, is as follows.

6-21
6 Build Mealy and Moore Charts

The semantics of the two charts differ as follows:

Mealy Vending Machine Moore Vending Machine


Uses 3 states Uses 5 states

6-22
Debug Mealy and Moore Charts

Mealy Vending Machine Moore Vending Machine


Computes outputs in condition actions Computes outputs in state actions
Updates output based on input Updates output before evaluating input,
requiring an extra time step to produce the
soda

For this vending machine, Mealy is a better modeling paradigm because there is no
delay in releasing soda once sufficient coins are received. By contrast, the Moore vending
machine requires an extra time step to pass before producing soda. Since the Moore
vending machine accepts a nickel, a dime, or no coin in a given time step, it is possible
that the soda will be produced in a time step in which a coin is accepted toward the next
purchase. In this situation, the delivery of a soda may appear to be in response to this
coin, but actually occurs because the vending machine received the purchase price in
previous time steps.

6-23
7

Techniques for Streamlining Chart


Design

Record State Activity Using History Junctions on page 7-2


Encapsulate Modal Logic Using Subcharts on page 7-5
Move Between Levels of Hierarchy Using Supertransitions on page 7-10
Define a Graphical Function on page 7-23
Manage Large Graphical Functions on page 7-27
Call Graphical Functions in States and Transitions on page 7-29
Specify Graphical Function Properties on page 7-30
Reuse Logic Patterns Using Graphical Functions on page 7-32
Export Stateflow Functions for Reuse on page 7-34
Group Chart Objects Using Boxes on page 7-41
Reuse Functions with an Atomic Box on page 7-48
Add Descriptive Comments in a Chart on page 7-54
7 Techniques for Streamlining Chart Design

Record State Activity Using History Junctions

In this section...
What Is a History Junction? on page 7-2
Create a History Junction on page 7-2
Change History Junction Size on page 7-3
Change History Junction Properties on page 7-3

What Is a History Junction?


A history junction records the activity of substates inside superstates. Use a history
junction in a chart or superstate to indicate that its last active substate becomes active
when the chart or superstate becomes active.

Create a History Junction


To create a history junction, do the following:

1 In the editor toolbar, click the History Junction icon:

2 Move your pointer into the chart.


3 Click to place a history junction inside the state whose last active substate it records.

To create multiple history junctions, do the following:

1 In the editor toolbar, double-click the History Junction icon.

The button is now in multiple-object mode.


2 Click anywhere in the drawing area to place a history junction.
3 Move to and click another location to create an additional history junction.
4 Click the History Junction icon or press the Esc key to cancel the operation.

To move a history junction to a new location, click and drag it to the new position.

7-2
Record State Activity Using History Junctions

Change History Junction Size


To change the size of junctions:

1 Select the history junctions whose size you want to change.


2 Right-click one of the junctions and select Junction Size.
3 Select a size from the list of junction sizes.

Change History Junction Properties


To edit the properties for a junction:

1 Right-click a junction and select Properties.

The History Junction dialog box appears.

2 Edit the fields in the properties dialog box.

7-3
7 Techniques for Streamlining Chart Design

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

Apply to save the changes


Cancel to cancel any changes
OK to save the changes and close the dialog box
Help to display the Stateflow online help in an HTML browser window

7-4
Encapsulate Modal Logic Using Subcharts

Encapsulate Modal Logic Using Subcharts


In this section...
What Is a Subchart? on page 7-5
Create a Subchart on page 7-6
Rules of Subchart Conversion on page 7-6
Convert a State to a Subchart on page 7-6
Manipulate Subcharts as Objects on page 7-8
Open a Subchart on page 7-8
Edit a Subchart on page 7-9
Navigate Subcharts on page 7-9

What Is a Subchart?
A subchart is a graphical object that can contain anything a top-level chart can, including
other subcharts. A subchart, or a subcharted state, is a superstate of the states that it
contains. You can nest subcharts to any level in your chart design.

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 Using
Supertransitions on page 7-10 for more information.

Subcharts define a containment hierarchy within a top-level chart. A subchart or top-


level chart is the parent of the states it contains at the first level and an ancestor of all
the subcharts contained by its children and their descendants at lower levels.

Some subcharts can become atomic units if they meet certain modeling requirements.
For more information, see Restrictions for Converting to Atomic Subcharts on page
14-11.

7-5
7 Techniques for Streamlining Chart Design

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.

To convert a new or existing state, box, or graphical function to 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.

Rules of Subchart Conversion


When you convert a box to a subchart, the subchart retains the attributes of a box. For
example, the position of the resulting subchart determines its activation order in the
chart if implicit ordering is enabled (see Group Chart Objects Using Boxes on page
7-41 for more information).

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.

Convert a State to a Subchart


Suppose that you have the following chart:

7-6
Encapsulate Modal Logic Using Subcharts

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.

7-7
7 Techniques for Streamlining Chart Design

Manipulate Subcharts as Objects


Subcharts also act as individual objects. You can move, copy, cut, paste, relabel, and
resize subcharts as you would states and boxes. You can also draw transitions to and
from a subchart and any other state or subchart at the same or different levels in the
chart hierarchy (see Move Between Levels of Hierarchy Using Supertransitions on page
7-10).

Open a Subchart
Opening a subchart allows you to view and change its contents. To open a subchart, do
one of the following:

Double-click anywhere in the box that represents the subchart.

7-8
Encapsulate Modal Logic Using Subcharts

Select the box representing the subchart and press the Enter key.

Edit a Subchart
After you open a subchart (see Open a Subchart on page 7-8), 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.

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 Using Supertransitions on page
7-10 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 subchart's parent 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.

7-9
7 Techniques for Streamlining Chart Design

Move Between Levels of Hierarchy Using Supertransitions

In this section...
What Is a Supertransition? on page 7-10
Draw a Supertransition Into a Subchart on page 7-12
Draw a Supertransition Out of a Subchart on page 7-17
Label Supertransitions on page 7-21

What Is a Supertransition?
A supertransition is a transition between different levels in a chart, for example,
between a state in a top-level chart and a state in one of its subcharts, or between states
residing in different subcharts at the same or different levels in a chart. You can create
supertransitions that span any number of levels in your chart, for example, from a state
at the top level to a state that resides in a subchart several layers deep in the chart.

The point where a supertransition enters or exits a subchart is called a slit. Slits divide
a supertransition into graphical segments. For example, the following chart shows a
supertransition leaving the On subchart:

7-10
Move Between Levels of Hierarchy Using Supertransitions

The same supertransition appears inside the subchart as follows:

7-11
7 Techniques for Streamlining Chart Design

In this example, supertransition [Heater.On.warm()] goes from NORM in the On


subchart to the Off state in the parent chart. Both segments of the supertransition have
the same label.

Draw a Supertransition Into a Subchart


Use the following steps to draw a supertransition from an object outside a subchart to an
object inside the subchart.

7-12
Move Between Levels of Hierarchy 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.

1 Position your cursor over the border of the state.

The cursor assumes the crosshairs shape.

2 Drag the mouse just inside the border of the subchart.

A supertransition appears, extending from the source state into the subchart with its
arrowhead penetrating a slit in the subchart.

7-13
7 Techniques for Streamlining Chart Design

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.
3 Double-click the subchart to open it.

The tip of the arrowhead of the supertransition appears highlighted in red, entering
the subchart.

7-14
Move Between Levels of Hierarchy Using Supertransitions

4 Position your cursor over the arrowhead.

The cursor becomes an arrow.


5 Drag the cursor to the desired position in the subchart.

7-15
7 Techniques for Streamlining Chart Design

6 Release the cursor.

The supertransition terminates in the desired location.

7-16
Move Between Levels of Hierarchy Using Supertransitions

Draw a Supertransition Out of a Subchart


Use the following steps to draw a supertransition out of a subchart.

1 Draw an inner transition segment from the source object anywhere just outside the
border of the subchart

A slit appears as shown.

7-17
7 Techniques for Streamlining Chart Design

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.

7-18
Move Between Levels of Hierarchy Using Supertransitions

3 Position your cursor over the arrowhead.

The cursor becomes an arrow.


4 Drag the cursor to the desired position in the chart.

The parent of the subchart appears.

7-19
7 Techniques for Streamlining Chart Design

5 Release the cursor to complete the connection.

7-20
Move Between Levels of Hierarchy 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

7-21
7 Techniques for Streamlining Chart Design

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.

7-22
Define a Graphical Function

Define a Graphical Function

Create a Graphical Function


Use these steps to create a graphical function in your chart:

1 Click the graphical function icon in the editor toolbar:

2 Move your pointer to the location for the new graphical function in your chart and
click to insert the function box.
3 Enter the function signature.

The function signature specifies a name for your function and the formal names for
its arguments and return values. A signature has this syntax:

[r1, r2,..., rn] = func(a1,a2,..., an)

where func is the name of your function, a1, a2, ..., an are formal names for its
arguments, and r1, r2, ..., rn are formal names for its return values.

Note: You can define arguments and return values as scalars, vectors, or 2-D
matrices of any data type.
4 Click outside of the function box.

The following signature is for a graphical function that has the name f1, which takes
three arguments (a, b, and c) and returns three values (x, y, and z).

7-23
7 Techniques for Streamlining Chart Design

Note: In the chart, you can change the signature of your graphical function at any time.
After you edit the signature, the Model Explorer updates to reflect the changes.

Program a Graphical Function


To program a graphical function, follow these steps:

1 Click the default transition icon in the editor toolbar:

2 Move your pointer inside the function box in your chart and click to insert the
default transition and its terminating junction.
3 Enter transition conditions and actions for your graphical function. If necessary, add
connective junctions and transitions to your function.

Note: Connective junctions and transitions are the only graphical elements you can
use in a graphical function. Because a graphical function must execute completely
when you call it, you cannot use states.

This function box shows a flow chart that returns different products of its arguments.

Define Graphical Function Data


You must define the data in your graphical function:

1 Open the Model Explorer.


2 Expand the chart object in the Model Explorer, so that you can see the return values
and arguments of the function signature as data items that belong to your graphical
function.

7-24
Define a Graphical Function

The Scope column in the Model Explorer indicates the role of each argument or
return value. Arguments have the scope Input, and return values have the scope
Output.
3 For each function argument and return value, right-click the data row in the Model
Explorer and select Properties from the context menu.
4 In the Data properties dialog box for each argument and return value, specify the
data properties.

These rules apply:

Each argument and return value can be a scalar or matrix of values.


Arguments cannot have initial values.
5 Create any additional data items that your function must have to process its
programming.

Your function can access its own data or data belonging to parent states or the chart.
The data items that you create for the function itself can have one of these scopes:

Local

Local data persists from one function call to the next. Valid for C charts only.
Temporary

Temporary data initializes at the start of every function call. Valid for C charts
only. In charts that use MATLAB as the action language, you do not need to

7-25
7 Techniques for Streamlining Chart Design

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

Constant data retains its initial value through all function calls.

Note: You can initialize your function data (other than arguments and return
values) from the MATLAB workspace. However, you can save only local items to this
workspace.

7-26
Manage Large Graphical Functions

Manage Large Graphical Functions


You can make your graphical function as large as you want, as shown below.

However, if your function grows too large, you can hide its contents by right-clicking
inside the function box and selecting Group & Subchart > Subchart from the context
menu. This option makes your graphical function opaque.

7-27
7 Techniques for Streamlining Chart Design

To access the programming of your subcharted graphical function, double-click the


function box. This action dedicates the entire chart window to programming your
function.

To access your original chart, click the Back button .

7-28
Call Graphical Functions in States and Transitions

Call Graphical Functions in States and Transitions

Syntax
Syntax for a function call is the same as that of a function signature, with actual
arguments replacing the formal ones specified in a signature. If the data types of the
actual and formal argument differ, a function casts the actual argument to the type of
the formal argument. See Create a Graphical Function on page 7-23 for information
about syntax for a function signature.

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

Example
In this example, a state entry action calls a graphical function that returns three
products.

7-29
7 Techniques for Streamlining Chart Design

Specify Graphical Function Properties


You can set general properties for your graphical function through its properties dialog
box:

1 Right-click your graphical function box.


2 Select Properties from the context menu.

The properties dialog box for your graphical function appears.

The fields in the General tab of the properties dialog box are:

Field Description
Name Click this read-only function name to bring your function to the
foreground in its native chart.

7-30
Specify Graphical Function Properties

Field Description
Function Inline Select one of these options to control the inlining of your
Option function in generated code:

Auto
Decides whether or not to inline your function based on an
internal calculation.
Inline
Inlines your function as long as you do not export it to other
charts, and it is not part of a recursion. (A recursion exists
if your function calls itself directly or indirectly through
another function call.)
Function
Does not inline your function.
Label Specify the signature label for your function in this field.
See Create a Graphical Function on page 7-23 for more
information.

The fields in the Documentation tab of the properties dialog box are:

Field Description
Description Enter a 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.

7-31
7 Techniques for Streamlining Chart Design

Reuse Logic Patterns Using Graphical Functions


In this section...
What Is a Graphical Function? on page 7-32
Why Use a Graphical Function in a Stateflow Chart? on page 7-32
Where to Use a Graphical Function on page 7-32
Limitations Using Events in Graphical Functions on page 7-33

What Is a Graphical Function?


A graphical function in a Stateflow chart is a graphical element that helps you reuse
control-flow logic and iterative loops. This function is a program you write with flow
charts using connective junctions and transitions. You create a graphical function, fill it
with a flow chart, and call the function in the actions of states and transitions.

Why Use a Graphical Function in a Stateflow Chart?


This function helps you to:

Create modular, reusable logic that you can call anywhere in your chart.
Track simulation behavior visually during chart animation.

Where to Use a Graphical Function


A graphical function can reside anywhere in a chart, state, or subchart. The location of
a function determines its scope, that is, the set of states and transitions that can call the
function. Follow these guidelines:

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 graphical functions. For
instructions, see Export Stateflow Functions for Reuse on page 7-34.

7-32
Reuse Logic Patterns Using Graphical Functions

Limitations Using Events in Graphical Functions


If an event broadcast inside a graphical function causes the active state to change, do
not broadcast the event inside of the graphical function. The behavior of broadcasting an
event in a graphical function that causes an exit from the active state is unpredictable.

7-33
7 Techniques for Streamlining Chart Design

Export Stateflow Functions for Reuse

In this section...
Why Export Chart-Level Functions? on page 7-34
How to Export Chart-Level Functions on page 7-34
Rules for Exporting Chart-Level Functions on page 7-35
Export Chart-Level Functions on page 7-35

Why Export Chart-Level Functions?


When you export chart-level functions, you extend the scope of your functions to other
parts of the model. For an example, see Share Functions Across Simulink and Stateflow
on page 27-6. You can export these functions:

Graphical
Truth table
MATLAB

How to Export Chart-Level Functions


1 Open the chart where your function resides.
2 In the Property Inspector, open the Advanced section.
3 Select Export Chart Level Functions.
4 If your function resides in a library chart, link that chart to your main model.

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.

7-34
Export Stateflow Functions for Reuse

Rules for Exporting Chart-Level Functions


Link library charts to your main model to export chart-level functions from libraries

You must perform this step to export functions from library charts. Otherwise, a
simulation error occurs.

Do not export chart-level functions that contain unsupported inputs or outputs

You cannot export a chart-level function when inputs or outputs have any of the
following properties:

Fixed-point data type with word length greater than 32 bits


Variable size

Do not export Simulink functions

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.

Do not export functions across model reference boundaries

You cannot export functions from a referenced model and call the functions from a parent
model.

Export Chart-Level Functions


This example describes how to export functions in library charts to your main model.

1 Create these objects:

Add a model named main_model, with a chart named modChart.

Add a library model named lib1, with a chart named lib1Chart.

7-35
7 Techniques for Streamlining Chart Design

Add a library model named lib2, with a chart named lib2Chart.

2 Create these graphical functions in the library charts:

For lib1Chart, add this graphical function.

For lib2Chart, add this graphical function.

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
7-36
Export Stateflow Functions for Reuse

Type to double
3 For modChart, add a graphical function and a default transition with a lib1_func
action.

4 For each chart, follow these steps:

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.
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.
7-37
7 Techniques for Streamlining Chart Design

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:

a Select Add > Data.


b In the Name column, enter x.
c In the Initial Value column, enter 0.
d Use the default settings for other properties of x.
e Select Add > Data.
f In the Name column, enter y.
g In the Initial Value column, enter 1.
h Use the default settings for other properties of y.

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 options section, make these changes:

a For Type, select Fixed-step.


b For Solver, select Discrete (no continuous states).
c For Fixed-step size, enter 1.
d Click OK.

This step ensures that when you simulate your model, a discrete solver is used. For
more information, see Solvers (Simulink).

What Happens During Simulation

When you simulate the model, these actions take place during each time step.

Phase The object... Calls the graphical Which...


function...
1 modChart lib1_func Reads two input
arguments x and y

7-38
Export Stateflow Functions for Reuse

Phase The object... Calls the graphical Which...


function...
2 lib1_func lib2_func Passes the two input
arguments
3 lib2_func mod_func Adds x and y and
assigns the sum to x

How to View the Simulation Results

To view the simulation results, add a scope to your model. Follow these steps:

1 Open the Simulink Library Browser.


2 From the Simulink/Sinks Library, select the Scope block and add it to main_model.
3 Open the Model Explorer.
4 In the Model Hierarchy pane, navigate to modChart.
5 Add the output data z to the chart:

a Select Add > Data.


b In the Name column, enter z.
c In the Scope column, select Output.
d Use the default settings for other properties.
6 For modChart, update the default transition action to read as follows:

{x = lib1_func(x,y); z = x;}
7 In the model, connect the outport from modChart to the inport of the Scope block.

7-39
7 Techniques for Streamlining Chart Design

8 Double-click the Scope block to open the display.


9 Start simulation.
10 After the simulation ends, right-click in the scope display and select Autoscale.

The results look something like this:

7-40
Group Chart Objects Using Boxes

Group Chart Objects Using Boxes


In this section...
When to Use Boxes on page 7-41
Semantics of Stateflow Boxes on page 7-41
Rules for Using Boxes on page 7-41
Draw and Edit a Box on page 7-42
Examples of Using Boxes on page 7-44

When to Use Boxes


Use a Stateflow box to organize graphical objects in your chart.

Semantics of Stateflow Boxes


Visibility of Graphical Objects in Boxes

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

Activation Order of Parallel States

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

Note: To specify activation order explicitly on a state-by-state basis, select User


specified state/transition execution order in the Chart properties dialog box. This
option is selected by default when you create a new chart. For details, see Explicit
Ordering of Parallel States on page 3-79.

Rules for Using Boxes


When you use a box, these rules apply:

7-41
7 Techniques for Streamlining Chart Design

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 Using
Subcharts on page 7-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.

Draw and Edit a Box


Create a Box

You create boxes in your chart by using the box tool shown below.

7-42
Group Chart Objects Using Boxes

1 Click the Box tool.


2 Move your pointer into the drawing area.
3 Click in any location to create a box.

The new box appears with a question mark (?) name in its upper left corner.
4 Click the question mark label.

7-43
7 Techniques for Streamlining Chart Design

5 Enter a name for the box and then click outside of the box.

Delete a Box

To delete a box, click to select it and press the Delete key.

Examples of Using Boxes


Group Functions Using a Box

This chart shows a box named Status that groups together MATLAB functions.

Chart execution takes place as follows:

1 The state Cold activates first.


2 Upon entry, the state Cold invokes the function Status.msgCold.

This function displays a status message that the temperature is cold.

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

7-44
Group Chart Objects Using Boxes

This function displays a status message that the temperature is warm.

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.

Group States Using a Box

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

7-45
7 Techniques for Streamlining Chart Design

The main ideas of this chart are:

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.

7-46
Group Chart Objects Using Boxes

Note: Because the substates Status.Temp.Cold and Status.Temp.Warm reside


inside a box, the argument of the in operator must include the box name Status.
If you omit this prefix, an error message appears. For information about the in
operator, see Check State Activity on page 11-86.

7-47
7 Techniques for Streamlining Chart Design

Reuse Functions with an Atomic Box


In this section...
What Is an Atomic Box? on page 7-48
Rationale for Using an Atomic Box on page 7-48
How to Reuse Functions with an Atomic Box on page 7-48
Example of Reusing a Timer Function Multiple Times on page 7-49

What Is an Atomic Box?


An atomic box behaves in the same way as a regular Stateflow box but with a few
differences:

You can reuse an atomic box across multiple charts and models.
An atomic box cannot contain states, only functions (graphical, truth table, MATLAB,
and Simulink).

Use an atomic box to reuse functions in the same way that you use an atomic subchart
to reuse states. For more information about atomic subcharts, see What Is an Atomic
Subchart? on page 14-2.

Rationale for Using an Atomic Box


Suppose that you have a library model that contains a set of functions for use in multiple
charts in a model. The functions reside in the library model to enable easier configuration
management.

Models that use these functions can appear as referenced blocks in a top model. However,
when the functions are exported functions of a Stateflow chart, you can use only one
instance of that referenced block per top model. For a complete list of model referencing
limitations, see Limitations on All Model Referencing (Simulink).

With atomic boxes, you can avoid the limitation due to exported functions. You can reuse
models with these functions multiple times as referenced blocks in a top model.

How to Reuse Functions with an Atomic Box


To reuse functions across multiple models:

7-48
Reuse Functions with an Atomic Box

1 Create a library model with an atomic box that contains the function you want to
reuse.
2 Create a separate model with multiple charts.

a In each chart that calls the function, add a linked atomic box.
b Write each call to the function using the full path:

linked_box_name.function_name

Using the full path for the function call has the following advantages:

Makes clear the dependency on the function in the linked atomic box
Avoids pollution of the global namespace
Does not affect efficiency of the generated code
3 Reuse that model multiple times as referenced blocks in a top model.

Because there are no exported functions in the charts, you can use more than one
instance of that referenced block in the top model.

Example of Reusing a Timer Function Multiple Times


Suppose that you want to reuse a timer function that returns the simulation time in C
charts. The following procedure shows how you can:

Call the timer function from multiple locations in a model.


Reuse that model multiple times in another model.

Note: For charts that use MATLAB as the action language, use the function
getSimulationTime().

1 Store the timer function you want to reuse in a library model.

a Create a new library named libTimerUtils.


b Add a chart named TimerUtils to the library:

7-49
7 Techniques for Streamlining Chart Design

c In your chart, add the following graphical function:

The function GetTime returns one output tout that corresponds to simulation
time t. For more information about literal symbols you can use in your chart,
see Supported Symbols in Actions on page 11-27.
d Save libTimerUtils.
2 Develop a separate model with multiple charts that use the timer function.

a Create a new model named ex_timer_function_calls.


b Add two charts, Chart1 and Chart2, to the model.
c In each chart, add two states, two transitions, and a linked atomic box:

7-50
Reuse Functions with an Atomic Box

To add the linked atomic box, copy the TimerUtils library chart and paste it
below state A. Name the linked atomic box as Time.

When you copy and paste a library chart that contains only functions and no
states, you get a linked atomic box. If the library chart contains any states, you
get a linked atomic subchart.
d In Chart1, add the following state action and transition condition:

Upon entry to state A, the call to GetTime returns the simulation time. The
transition from state A to B occurs when more than 5 seconds of simulation time
passes.
e In Chart2, add the following state action and transition condition:

7-51
7 Techniques for Streamlining Chart Design

Upon entry to state A, the call to GetTime returns the simulation time. The
transition from state A to B occurs when more than 7 seconds of simulation time
passes.
f In each chart, add local data with the following properties:

Property Value
Name t0
Scope Local
Type double
g In each chart, open the State properties dialog box for B and select Create data
for monitoring:. Click OK.

This step adds an output data named B that is Boolean. The value is 1 when
state B is active and 0 otherwise. For more information, see About Active State
Data on page 22-30.
h In your model, add two Outport blocks, Out1 and Out2. Then connect each block
to the corresponding output of each chart.

Your model should look something like this:

i Save ex_timer_function_calls.
3 Reuse the timer function in multiple referenced blocks of a top model.

a Create a new model named ex_modelref_utility_functions.


b Add two Model blocks that reference ex_timer_function_calls.

7-52
Reuse Functions with an Atomic Box

c Add four Outport blocks and connect them as follows:

d Save ex_modelref_utility_functions.

7-53
7 Techniques for Streamlining Chart Design

Add Descriptive Comments in a Chart


In this section...
Create Notes on page 7-54
Change Note Properties on page 7-54
Change Note Font and Color on page 7-54
TeX Instructions on page 7-55

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 Return key to start a new line.
3 After you finish typing, click outside the note text.

Change Note Properties


You can use the Note properties dialog box to edit note properties.

You can specify the layout of the note, including:

Borders
Text alignment and word wrap
Text color and background color
Margins between the text and the borders of the note

Change Note Font and Color


To change font and color for your chart notes, follow the procedures described in the
section Specify Colors and Fonts in a Chart on page 4-31.

You can also change your note text to bold or italic:

1 Right-click the note text and select Font Style.


2 In the submenu, select Bold or Italic.

7-54
Add Descriptive Comments in a Chart

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.

1 Right-click the text of a note and select Enable TeX Commands.


2 Click the note text.
3 Replace the existing note text with the following expression.

\it{\omega_N = e^{(-2\pii)/N}}
4 Click outside the note.

The note in your chart looks something like this:

7-55
8

Define Data

Add Stateflow Data on page 8-2


Detect Unused Data in the Symbols Window on page 8-4
Set Data Properties on page 8-6
Share Data with Simulink and MATLAB Workspace on page 8-23
About Data Stores on page 8-27
How Charts Work with Local and Global Data Stores on page 8-28
Access Data Store Memory from a Chart on page 8-29
Diagnostics for Sharing Data Between Charts and Simulink Blocks on page 8-32
Create a Global Data Store Across Multiple Models on page 8-34
Best Practices for Using Data Stores in Charts on page 8-35
Type Stateflow Data on page 8-36
Size Stateflow Data on page 8-44
Handle Integer Overflow for Chart Data on page 8-49
Define Temporary Data on page 8-53
Identify Data Using Dot Notation on page 8-54
Resolve Data Properties from Simulink Signal Objects on page 8-59
Best Practices for Using Data in Charts on page 8-63
Transfer Data Across Models on page 8-65
8 Define Data

Add Stateflow Data


In this section...
Add Data from the Stateflow Editor on page 8-2
Add Data Through the Model Explorer on page 8-3

Add data when you want to store values that are visible at a specific level of the
Stateflow hierarchy.

You can store and retrieve data that resides internally in the Stateflow workspace and
externally in the Simulink model or application that embeds the chart. Actions in your
chart can refer to internal and external data.

You can use data defined in a Stateflow chart by multiple Stateflow objects in the chart.
These objects can be states, transition, MATLAB functions, and truth tables. Stateflow
data is not available to Simulink functions within Stateflow.

Add Data from the Stateflow Editor


From the Stateflow editor, you can add data via the Symbols window or through menus.

To open the Symbols window, select View > Symbols. To add data in the Symbols
window:

1
Click the Create Data icon .
2 In the row for the new data, under TYPE, click the icon and choose:

Input Data
Local Data
Output Data
Constant
Data Store Memory
Parameter
Temporary
3 Edit the name of the data.

8-2
Add Stateflow Data

4 For input and output data, click the PORT field and choose a port number.

To add data through menus, select one of these options:

Scope Menu Option


Input Chart > Add Inputs & Outputs > Data Input From Simulink
Output Chart > Add Inputs & Outputs > Data Output To Simulink
Local Chart > Add Other Elements > Local Data
Constant Chart > Add Other Elements > Constant
Parameter Chart > Add Other Elements > Parameter
Data Store Chart > Add Other Elements > Data Store Memory
Memory

You can edit properties for data in the Property Inspector or Data properties dialog box.

Add Data Through the Model Explorer


Add machine or state-parented data through the Model Explorer.

1 In the Stateflow Editor, select View > Model Explorer.


2 In the Model ExplorerModel Hierarchy pane, select the object in the Stateflow
hierarchy where you want to make the new data visible.

The object you select becomes the parent of the new data.
3 In the Model Explorer, select Add > Data.

The Model Explorer adds a default definition for the data in the hierarchy. The data
definition appears in a new row in the Model Explorer.
4 Change the properties of the data.

More About
Set Data Properties on page 8-6

8-3
8 Define Data

Detect Unused Data in the Symbols Window


The Symbols window indicates unused data, messages, functions, and events with a
yellow warning icon. To delete unused objects, right-click the object in the Symbols
window and select Delete. By removing objects that have no effect on simulation, you
can reduce the size of your model. In this chart, after you add data, it first appears as
unused. After you reference data in the chart, the warning sign disappears.

The following types of unused data are not detected:

Machine-parented data
Inputs and outputs of MATLAB functions
Data of parameter scope in a chart that contains atomic subcharts

More About
Trace Data, Events, and Messages with the Symbols Window on page 30-7
Unused data, events, messages, and functions (Simulink)

8-4
Detect Unused Data in the Symbols Window

Resolve Undefined Data in the Symbols Window on page 28-33


Set Data Properties on page 8-6

8-5
8 Define Data

Set Data Properties

In this section...
Stateflow Data Properties on page 8-6
Set Properties in the Logging Section on page 8-19
Set Properties in the Description Pane on page 8-20
Enter Expressions and Parameters for Data Properties on page 8-20

You can specify data properties in either the Property Inspector or the Data properties
dialog box in the Model Explorer.

Property Inspector

1 Open the Symbols window by selecting View > Symbols.


2 Open the Property Inspector by selecting View > Property Inspector.
3 Select the data in the Symbols window.
4 Edit the data properties in the Property Inspector window.
Model Explorer

1 Open the Model Explorer by selecting View > Model Explorer.


2 Double-click the data object in the Contents pane.
3 Edit the data properties in the data properties dialog box.

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.

Stateflow Data Properties


Name

Name of the data object. For more information, see Rules for Naming Stateflow Objects
on page 2-4.

8-6
Set Data Properties

Scope

Location where data resides in memory, relative to its parent. You can set scope to one of
these values.

Scope Value 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 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 parameter.

To learn how to use Simulink block parameters with charts,


see Share Simulink Parameters with Charts on page
8-24.
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 via an input
port on the Stateflow block. See Share Output Data with
Simulink on page 8-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 via an output port on
the Stateflow block. See Share Output Data with Simulink on
page 8-23.
Data Store Memory Data object that binds to a Simulink data store, which is a
signal that functions like a global variable. All blocks in a
model can access that signal. This binding allows the chart to
read and write the Simulink data store, sharing global data
with the model. The Stateflow object must have the same name
as the Simulink data store. See Access Data Store Memory
from a Chart on page 8-29.
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, as described in
Define Temporary Data on page 8-53.

8-7
8 Define Data

Scope Value Description


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.

Port

Index of the port associated with the data object. This property applies only to input and
output data. See Share Output Data with Simulink on page 8-23.

Data must resolve to signal object

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

For more information, see Resolve Data Properties from Simulink Signal Objects on
page 8-59.

This option appears only if you set the model configuration parameter Signal
resolution to a value other than None.

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

8-8
Set Data Properties

use a multidimensional array. The number of dimensions equals the length of the vector
and the size of each dimension 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 which it is bound. For all other scopes, size can be scalar, vector, or a matrix of n-
dimensions.

For more information, see Size Stateflow Data on page 8-44.

Variable size

Option that specifies whether the data object changes dimensions during simulation.
When you enable the chart property Support variable-size arrays, this option is
available only for input and output data. For more information, see Variable-Size Data.

Complexity

Option that specifies whether the data object accepts complex values. You can choose one
of these settings.

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.

For more information, see How Complex Data Works in C Charts on page 21-2.

Type

Type of data object. Specify the data type by:

From the Type drop-down list, select a built-in type.


In the Data properties dialog box, use the Data Type Assistant to specify a data
Mode and then specify the data type based on that mode. To display the Data Type

Assistant, click the Show data type assistant button . The Data Type
Assistant is available only in the Data properties dialog box. It is not available in the
Symbols window.

8-9
8 Define Data

In the Type field, enter an expression that evaluates to a data type.

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.

To ensure that a data type definition is valid for fixed-point data, use one of the two
options.

For more information, see Type Stateflow Data on page 8-36.

Lock data type setting against changes by the fixed-point tools

Prevents replacement of the current fixed-point type with a type that the Fixed-Point
Tool (Fixed-Point Designer) or Fixed-Point Advisor (Fixed-Point Designer) chooses.
For methods on autoscaling fixed-point data, see Choosing a Range Collection Method
(Fixed-Point Designer).

Unit (e.g., m, m/s^2, N*m)

For input and output data, you can specify physical units. See Units in Stateflow on
page 22-43.

Initial value

Initial value of the data object. If you do not specify a value, the default is 0.0. The
options for initializing values depend on the scope of the data object.

Scope What to Specify for Initial Value


Local Expression or parameter defined in the Stateflow hierarchy,
MATLAB workspace, or Simulink masked subsystem
Constant Constant value or expression. The expression is evaluated when
you update the chart, and the resulting value is used as a constant
for running the chart.
Parameter You cannot enter a value. The chart inherits the initial value from
the parameter.
Input You cannot enter a value. The chart inherits the initial value from
the Simulink input signal on the designated port.

8-10
Set Data Properties

Scope What to Specify for Initial Value


Output Expression or parameter defined in the Stateflow hierarchy,
MATLAB workspace, or Simulink masked subsystem.
Data Store Memory You cannot enter a value. The chart inherits the initial value from
the Simulink data store to which it resolves.

For more information, see Initialize Data from the MATLAB Base Workspace on page
8-25 and Share Simulink Parameters with Charts on page 8-24.

Limit range properties

Range of acceptable values for this data object. Stateflow software uses this range
to validate the data object during simulation. To establish the range, specify these
properties:

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 you can set for Minimum is -inf. The largest value you can set for
Maximum is inf.

Note: A Simulink model uses the Limit range properties to calculate best-precision
scaling for fixed-point data types. Specify a minimum or maximum value before you
select Calculate Best-Precision Scaling in the General pane. For more information,
see Calculate Best-Precision Scaling on page 8-14.

For more information on entering values for Limit range properties, see Enter
Expressions and Parameters for Data Properties on page 8-20.

Add to Watch Window

Option for watching the data values in the Stateflow Breakpoints and Watch window (see
Watch Stateflow Data Values on page 29-35).

Fixed-Point Data Properties

Properties that apply to fixed-point data. These fixed-point properties are available only
in the Data properties dialog box.

8-11
8 Define Data

When the Data Type Assistant Mode is Fixed point the Data Type Assistant displays
fields for specifying additional information about your fixed-point data.

If the Scaling is Slope and bias rather than Binary point, the Data Type Assistant
displays a Slope field and a Bias field rather than a Fraction length field.

8-12
Set Data Properties

You can use the Data Type Assistant to set these fixed-point properties:

Signedness

Specify whether you want the fixed-point data to be Signed or Unsigned. Signed data
can represent positive and negative values, but unsigned data represents positive values
only. The default setting is Signed.

Word length

Specify 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 bit size
is 16.

For chart-level data of the following scopes, word length can be any integer from 0
through 128.

Input
Output
Parameter
Data Store Memory
For other Stateflow data, word length can be any integer from 0 through 32.

Scaling

Specify the method for scaling your fixed-point data to avoid overflow conditions and
minimize quantization errors. The default method is Binary point scaling. You can
select one of two scaling modes.

Scaling Mode Description


Binary If you select this mode, the Data Type Assistant displays the Fraction
point length field, which specifies the binary point location.

Binary points can be positive or negative integers. A positive integer


moves the binary point left of the rightmost bit by that amount. For
example, an entry of two sets the binary point in front of the second bit
from the right. A negative integer moves the binary point further right of
the rightmost bit by that amount, as in this example:

8-13
8 Define Data

Scaling Mode Description

The default binary point is 0.


Slope and If you select this mode, the Data Type Assistant displays fields for
bias entering the Slope and Bias.

Slope can be any positive real number. The default slope is 1.0. Bias
can be any real number. The default bias is 0.0. You can enter slope and
bias as expressions that contain parameters you define in the MATLAB
workspace.

Note: Use binary-point scaling whenever possible to simplify the implementation of


fixed-point data in generated code. Operations with fixed-point data that use binary-
point scaling are performed with simple bit shifts and eliminate expensive code
implementations required for separate slope and bias values.

For more information about fixed-point scaling, see Scaling (Fixed-Point Designer).

Data type override

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

Calculate Best-Precision Scaling

Calculate best-precision values for Binary point and Slope and bias scaling,
based on the Limit range properties that you specify in the General tab of the Data
properties dialog box.

To automatically calculate best precision scaling values:

1 In the Data properties dialog box, click the General tab.

8-14
Set Data Properties

2 Specify Limit range properties.


3 Click Calculate Best-Precision Scaling.

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.

Show Fixed-Point Details

Option in the Data properties dialog box when you specify a fixed-point data type. To see
information about the fixed-point data type that is defined in the Data Type Assistant,
use the Fixed-point details section. Click the expander next to Fixed-point details in
the Data Type Assistant.

8-15
8 Define Data

8-16
Set Data Properties

The rows labeled Minimum and Maximum show the same values that appear in the
corresponding Minimum and Maximum fields in the Limit range section. See Signal
Ranges (Simulink) and Specify Minimum and Maximum Values for Block Parameters
(Simulink).

The rows labeled Representable minimum, Representable maximum, and


Precision show the minimum value, maximum value, and precision that can be
represented by the fixed-point data type currently displayed in the Data Type Assistant.

The values displayed by the Fixed-point details subpane do not automatically update
if you click Calculate Best-Precision Scaling, or change the range limits, the values
that define the fixed-point data type, or anything elsewhere in the model. To update the
values shown in the Fixed-point details subpane, click Refresh Details. The Data
Type Assistant then updates or recalculates all values and displays the results.

Clicking Refresh Details does not change anything in the model; it changes only the
display. Click OK or Apply to put the displayed values into effect. If the value of a
field cannot be known without first compiling the model, the Fixed-point details
subpane shows the value as Unknown. If errors occur when you click Refresh Details,
the subpane shows an error flag on the left of the applicable row and a description of the
error on the right. For example, the next figure shows two errors.

8-17
8 Define Data

The row labeled Minimum shows the error Cannot evaluate because evaluating the
expression MySymbol, specified in the Minimum field of the Limit range section,
cannot 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.

8-18
Set Data Properties

To correct this error, define MySymbol in the base workspace to provide a numeric value.
If you click Refresh Details, the value of MySymbol appears in place of the unevaluated
text. The error indicator and description are deleted.

To correct the overflow error for Maximum, change the fixed-point data type so that it can
represent the maximum value you specify.

Decrease the value in the Maximum field of the Limit range section.
Increase Word length.
Decrease Fraction length.

Set Properties in the Logging Section


You can set these properties in the Logging section.

Log signal data

Saves the data value to the MATLAB workspace during simulation.

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 (see Test Points (Simulink)). Data objects can be test
points if:

Scope is Local.
Parent is not a Stateflow machine.
Data type is not ml.

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.

Limit data points to last

Limits the amount of data logged to the most recent samples.

Decimation

Limits the amount of data logged by skipping samples. For example, a decimation factor
of 2 saves every other sample.

8-19
8 Define Data

Set Properties in the Description Pane


For C charts, in the Data properties dialog box, you can set these properties in the
Description pane.

Save final value to base workspace

Option that assigns the value of the data item to a variable of the same name in the base
workspace at the end of simulation (see Model Workspaces (Simulink)).

First index

Index of the first element of the data array. The default value is 0.

Units

Units of measurement that you want to associate with the data object. The unit in this
field resides with the data object in the Stateflow hierarchy.

Description

Description of the data object.

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
HTML file or text in the MATLAB Command Window. When you click the Document
link hyperlink at the bottom of the properties dialog box, Stateflow software evaluates
the link and displays the documentation.

Enter Expressions and Parameters for Data Properties


In the Data properties dialog box, you can enter expressions as values for these
properties.

Size on page 8-8


Type on page 8-9
Initial value on page 8-10
Minimum and Maximum (see Limit range properties on page 8-11)

8-20
Set Data Properties

Fixed-Point Data Properties on page 8-11

Expressions can contain a mix of parameters, constants, arithmetic operators, and calls
to MATLAB functions.

Default Data Property Values

When you leave an expression or parameter field blank, Stateflow software 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
1 (scalar), for other data objects

Use Parameters in Expressions

You can include parameters in expressions. A parameter is a constant that you can:

Define in the MATLAB workspace (see Initialize Data from the MATLAB Base
Workspace on page 8-25)
Derive from a Simulink block parameter that you define and initialize in the parent
masked subsystem (see Share Simulink Parameters with Charts on page 8-24)

You can mix both types of parameters in an expression.

Use Constants in Expressions

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.

8-21
8 Define Data

Use Arithmetic Operators in Expressions

In the Data properties dialog box, you can use these arithmetic operators in expressions.

+

*
/

Call Functions in Expressions

In fields that accept expressions, you can call functions that return property values of
other variables defined in the Stateflow hierarchy, MATLAB workspace, or Simulink
masked subsystem. For example, these functions can return appropriate values for
specified fields in the Data properties dialog box.

Function Returns For Field


Stateflow function Type of input data Data type
type
MATLAB function Smallest element or Minimum
min elements of input array
MATLAB function Largest element or elements Maximum
max of input array
Simulink function Simulink.NumericType Data type
fixdt object that describes a fixed-
point or floating-point data
type

More About
Type Stateflow Data on page 8-36
Size Stateflow Data on page 8-44
Identify Data Using Dot Notation on page 8-54
Best Practices for Using Data in Charts on page 8-63

8-22
Share Data with Simulink and MATLAB Workspace

Share Data with Simulink and MATLAB Workspace


In this section...
Share Input Data with Simulink on page 8-23
Share Output Data with Simulink on page 8-23
Share Simulink Parameters with Charts on page 8-24
Initialize Data from the MATLAB Base Workspace on page 8-25
Save Data to the MATLAB Workspace on page 8-26

Share Input Data with Simulink


Data flows from Simulink into a chart via input ports on the chart.

To add input data to a chart:

1 Add a data object to the chart, as described in Add Data from the Stateflow Editor
on page 8-2.

Note: Add the data to the chart itself, not to any other object in the chart.
2 In the Symbols window, set the TYPE to Input Data.

An input port appears on the block in the model.

You can change port assignments by editing the value in the PORT field.
3 Set the data type of the input data, as described in Type Stateflow Data on page
8-36.
4 Set the size of the input data, as described in Size Stateflow Data on page 8-44.

Note: You cannot type or size Stateflow input data to accept frame-based data from
Simulink.

Share Output Data with Simulink


Data flows from a chart into Simulink via output ports on the chart.

8-23
8 Define Data

To add output data to a chart:

1 Add a data object to the chart, as described in Add Data from the Stateflow Editor
on page 8-2.

Note: Add data to the chart itself, not to any other object in the chart.
2 In the Symbols window, set the TYPE property to Output Data.

An output port appears on the block in the model.

You assign outputs to ports in the order in which you add the data. For example, you
assign the third output to output port 3. You can change port assignments by editing
the value in the PORT field.
3 Set the type of the output data, as described in Type Stateflow Data on page
8-36.
4 Set the size of the output data, as described in Size Stateflow Data on page
8-44.

Share Simulink Parameters with Charts


When to Share Simulink Parameters

Share Simulink parameters with charts to maintain consistency with your Simulink
model. By using parameters, you can also avoid hard-coding data sizes and types.

You can use parameters defined in a Stateflow chart in multiple Stateflow objects in the
chart, such as states, MATLAB functions and truth tables.

How to Share Simulink Parameters

To share Simulink parameters for a masked subsystem with a chart, follow these steps:

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
parameter (see Add Stateflow Data on page 8-2).
3 Set the scope of the data object to Parameter.

A chart defines data of scope Parameter as a constant. You cannot change a


parameter value during model execution.

8-24
Share Data with Simulink and MATLAB Workspace

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

Initialize Data from the MATLAB Base Workspace


For C charts, you can initialize data from the MATLAB base workspace. Initialization
requires that you define data in both the MATLAB base workspace and the Stateflow
hierarchy as follows:

1 Define and initialize a variable in the MATLAB workspace.


2 In the Stateflow hierarchy, define a data object with the same name as the MATLAB
variable (see Add Stateflow Data on page 8-2).
3 Set the scope of the Stateflow data object to Parameter.

When simulation starts, data resolution occurs. During this process, the Stateflow data
object gets its initial value from the associated MATLAB variable. For example, if the
variable is an array, each element of the Stateflow array initializes to the same value as
the corresponding element of the MATLAB array.

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

Time of Initialization

Data parent and scope control initialization time for Stateflow data objects.

Data Parent Scope When Initialized


Machine Local, Exported Start of simulation
Imported Not applicable
Chart Input Not applicable
Output, Local Start of simulation or when
chart reinitializes as part of an
enabled Simulink subsystem
State with History Junction Local Start of simulation or when
chart reinitializes as part of an
enabled Simulink subsystem

8-25
8 Define Data

Data Parent Scope When Initialized


State without History Junction Local State activation
Function (graphical, truth table, and Input, Output Function-call invocation
MATLAB functions) Local Start of simulation or when
chart reinitializes as part of an
enabled Simulink subsystem

Save Data to the MATLAB Workspace


For C charts, you can instruct the chart to save the final value of a data object at the end
of simulation in the MATLAB base workspace (not as a masked subsystem parameter)
for all scopes except Constant and Parameter.

Use one of these techniques:

In the Description pane of the Data properties dialog box, select Save final value
to base workspace.
In the Contents pane of the Model Explorer, follow these steps:

1 Select the row of the data object.


2 Select the check box in the SaveToWorkspace column.

8-26
About Data Stores

About Data Stores


You can use an interface to direct charts to access global variables in Simulink models. A
Simulink model implements global variables as data stores, created either as data store
memory blocks or as instances of Simulink.Signal objects. Data stores enable multiple
Simulink blocks to share data without the need for explicit I/O connections to pass data
from one block to another. Stateflow charts share global data with Simulink models by
reading from and writing to data store memory symbolically.

You can use data stores with buses, but not with arrays of buses. For more information
about using data stores with buses, see "Using Data Stores with Buses and Arrays of
Buses" (Simulink).

8-27
8 Define Data

How Charts Work with Local and Global Data Stores


Charts can interface with local and global data stores. Local data stores, often
implemented as data store memory blocks, are visible to all blocks in one model. To
interact with local data stores, a chart must reside in the model where you define the
local data store:

Global data stores have a broader scope, which crosses model reference boundaries. To
interact with global data stores, a chart must reside either in the top model where
the global data store is defined or in any model that the top model references. You
implement global data stores as Simulink signal objects.

8-28
Access Data Store Memory from a Chart

Access Data Store Memory from a Chart


To access global data in a Simulink model from a chart, you must bind a Stateflow data
object to a Simulink data store either a data store memory block or a signal object (see
Bind a Stateflow Data Object to Data Store Memory on page 8-29). After you create
the binding, the Stateflow data object becomes a symbolic representation of Simulink
data store memory. You can then use this symbolic object to store and retrieve global
data (see Read and Write Global Data Programmatically on page 8-30).

Bind a Stateflow Data Object to Data Store Memory


To bind a Stateflow data object to Simulink data store memory, you must create a data
object in the Stateflow hierarchy with the same name as the data store and with scope
set to Data Store Memory. The Stateflow data object inherits all properties from
the data store to which you bind the object. Follow guidelines for specifying data store
properties in Best Practices for Using Data Stores in Charts on page 8-35.

Note: You cannot edit properties that the data object inherits from the data store.

Use the Stateflow Editor to Bind a Data Object


In the Stateflow Editor, follow these steps:

1 Select Chart > Add Other Elements > Data Store Memory.

The properties dialog box for the new data object appears with scope property set to
Data Store Memory.
2 In the Name field of the Data properties dialog box, enter the name of the Simulink
data store to which you want to bind.
3 Click OK.

Use the Model Explorer to Bind a Data Object


In the Model Explorer, follow these steps:

1 Select Add > Data.

8-29
8 Define Data

The Model Explorer adds a data object to the chart.


2 Double-click the new data object to open its properties dialog box, and enter the
following information in the General pane:

Field What to Specify


Name Enter the name of the Simulink data store memory block to which you
want to bind.
Scope Select Data Store Memory from the drop-down menu.
3 Click OK.

Resolve Data Store Bindings


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.

Read and Write Global Data Programmatically


You can use the Stateflow data object that you bind to Simulink data store memory to
store and retrieve global data in states and transitions. Think of this object as a global
variable that you reference by its symbolic name the same name as the data store
to which you bind the object. When you store numeric values in this variable, you are
writing to Simulink data store memory. Similarly, when you retrieve numeric values
from this variable, you are reading from the data store memory.

The following chart reads from and writes to a data store memory block called myglobal.

8-30
Access Data Store Memory from a Chart

8-31
8 Define Data

Diagnostics for Sharing Data Between Charts and Simulink Blocks

Errors to Check For


Multiple reads and writes can occur unintentionally in the same time step. To detect
these situations, you can configure data store memory blocks to generate errors or
warnings for these conditions:

Read before write


Write after write
Write after read

Note: These diagnostics are available only for data store memory blocks used within a
single Simulink model, not for data stores created from Simulink signal objects. In other
words, these diagnostics do not work for global data stores that cross model reference
boundaries.

When to Enable Diagnostics


Enable diagnostics on data store memory blocks to ensure the validity of data that
multiple unconnected blocks share while running at different rates. In this scenario, you
can detect conditions when writes do not occur before reads in the same time step. To
prevent these violations, see Best Practices for Using Data Stores in Charts on page
8-35.

When to Disable Diagnostics


If you use a data store memory block as a persistent global storage area for accumulating
values across time steps, disable diagnostics to avoid generating unnecessary warnings.

How to Set Diagnostics for Shared Data


To set diagnostics on data store memory blocks, follow these steps:

1 Double-click the data store memory block in your Simulink model to open its Block
Parameters dialog box.

8-32
Diagnostics for Sharing Data Between Charts and Simulink Blocks

2 Click the Diagnostics tab.


3 Enable diagnostics by selecting warning or error from the drop-down menu for
each condition you want to detect.
4 Click OK.

8-33
8 Define Data

Create a Global Data Store Across Multiple Models


To create read/write references to a global data store that you can share across multiple
models:

1 Define data store memory objects that reside in each chart that shares the data.

a Use the Model Explorer to add a data object to each chart, as described in Add
Data Through the Model Explorer on page 8-3.
b Give each data object the same name.
c Set the scope of each data object to Data Store Memory.
2 Verify that your models do not contain any Data Store Memory blocks.

However, you can include Data Store Read and Data Store Write blocks.
3 Create a Simulink.Signal object in the MATLAB base workspace.

a In the Model Explorer, navigate to Simulink Root > Base Workspace in the
Model Hierarchy pane.
b Select Add > Simulink Signal.
c Give the object the same name as the data store memory objects in your charts.
4 Verify that these settings apply to the Simulink.Signal object:

a Set Data type to an explicit data type.

The data type cannot be auto.


b Set Dimensions to be fully specified.

The signal dimensions cannot be 1, or inherited.


c Set Complexity to be fully specified.

The complexity cannot be Auto.


d Set Storage class to ExportedGlobal.

8-34
Best Practices for Using Data Stores in Charts

Best Practices for Using Data Stores in Charts

When Binding to Data Stores in Charts


When you bind a Stateflow data object to a data store, the Stateflow object inherits all
properties from the data store. To ensure that properties propagate correctly when you
access data stores, follow these guidelines to create data stores:

Specify a data type other than auto.


Minimize the use of automatic-mode properties.

When Enforcing Writes Before Reads in Unconnected Blocks


To enforce writes before reads when unconnected blocks share global data in charts,
follow these guidelines:

Segregate reads into separate blocks from writes.


Assign priorities to blocks so that your model invokes write blocks before read blocks.

For instructions on how to set block execution order, see Control and Display the
Sorted Order (Simulink).

8-35
8 Define Data

Type Stateflow Data

In this section...
What Is Data Type? on page 8-36
Specify Data Type with the Property Inspector on page 8-36
Specify Data Type with the Data Type Assistant on page 8-36
Built-In Data Types on page 8-39
Inherit Data Types from Simulink Objects on page 8-40
Derive Data Types from Previously Defined Data on page 8-40
Type Data by Using an Alias on page 8-41
Strong Data Typing with Simulink I/O on page 8-42

What Is Data Type?


The term data type refers to the way computers represent numbers in memory. The type
determines the amount of storage allocated to data, the method of encoding a data value
as a pattern of binary digits, and the operations available for manipulating the data.

Specify Data Type with the Property Inspector


To specify the data type in the editor:

1 Open the Symbols and Property Inspector windows from the View menu.
2 Select the data object row in the Symbols window.
3 In the Property Inspector, enter the data type directly in the Type field, or select it
from the Type drop-down list.

Specify Data Type with the Data Type Assistant


To specify the type of a Stateflow data object with the Data Type Assistant:

1 Open the Data properties dialog box.


2 Click the Data Type Assistant button.

8-36
Type Stateflow Data

3 Choose a Mode in the Data Type Assistant section of the dialog box.

You can choose from these modes for each scope.

Scope Data Type Modes


Inherit Built in Fixed point Enumerated Expression Bus Object
Local For charts yes yes yes yes yes
that use
MATLAB as
the action
language,
yes
Constant yes yes yes
Parameter yes yes yes yes yes yes
Input yes yes yes yes yes yes
Output yes yes yes yes yes yes
Data Store yes
Memory
4 Based on the mode you select, specify a data type.

Mode What To Specify


Inherit You cannot specify a value. You inherit the data type based on the scope you
select for the data object:

For charts that use MATLAB as the action language, if scope is Local, you
infer the data type from the context of the MATLAB code in the chart.
If scope is Input, you inherit the data type from the Simulink input signal on
the designated input port (see Share Output Data with Simulink on page
8-23).
If scope is Output, you inherit the data type from the Simulink output signal
on the designated output port (see Share Output Data with Simulink on
page 8-23).

Note: Avoid inheriting data types from output signals. See Avoid inheriting
output data properties from Simulink blocks on page 8-63.
8-37
8 Define Data

Mode What To Specify


If scope is Parameter, you inherit the data type from the associated
parameter, which you can define in a Simulink model or the MATLAB
workspace (see Share Data with Simulink and MATLAB Workspace on
page 8-23).
If scope is Data Store Memory, you inherit the data type from the Simulink
data store to which you bind the data object (see Access Data Store Memory
from a Chart on page 8-29).
Built in Select a data type from the drop-down list of supported data types, as described
in Built-In Data Types on page 8-39.
Fixed point Specify the following information about the fixed-point data:

Whether the data is signed or unsigned


Word length
Scaling mode

For information on how to specify these fixed-point data properties, see Fixed-
Point Data Properties on page 8-11.
Enumerated Specify the class name for the enumerated data type. For more information, see
Define Enumerated Data in a Chart on page 18-8.
Expression Enter an expression that evaluates to a data type in the Type field. You can use
these expressions:

Alias type from the MATLAB workspace, as described in Type Data by


Using an Alias on page 8-41
type operator to specify the type of previously defined data, as described in
Derive Data Types from Previously Defined Data on page 8-40
fixdt function to create a Simulink.NumericType object that describes a
fixed-point or floating-point data type

For more information on how to build expressions in the Data properties dialog
box, see Enter Expressions and Parameters for Data Properties on page 8-20.

8-38
Type Stateflow Data

Mode What To Specify


Bus object In the Bus object field, enter the name of a Simulink.Bus object to associate
with the Stateflow bus object structure. You must define the bus object in the
base workspace. If you have not yet defined a bus object, click Edit to create or
edit a bus object in the Bus Editor.

Note: You can also inherit bus object properties from Simulink signals.
5 Click Apply to save the data type settings.

Note: The Data Type Assistant is available only with the Data properties dialog box. It is
not available with the Symbols window.

Built-In Data Types


You can choose from these built-in data types:

Data Type Description


double 64-bit double-precision floating point
single 32-bit single-precision floating point
int32 32-bit signed integer
int16 16-bit signed integer
int8 8-bit signed integer
uint32 32-bit unsigned integer
uint16 16-bit unsigned integer
uint8 8-bit unsigned integer
boolean Boolean (1 = true; 0 = false)
ml Typed internally with the MATLAB array mxArray.
The ml data type provides Stateflow data with the
benefits of the MATLAB environment, including
the ability to assign the Stateflow data object to
a MATLAB variable or pass it as an argument to
a MATLAB function. See ml Data Type on page
11-43.

8-39
8 Define Data

Data Type Description


Note: ml data cannot have a scope outside the
Stateflow hierarchy; that is, it cannot have a scope of
Input to Simulink or Output to Simulink.

Inherit Data Types from Simulink Objects


Stateflow data objects of scope Input, Output, Parameter, and Data Store Memory
can inherit their data types from Simulink objects, as follows:

Scope: Can inherit type from:


Input Simulink input signal connected to corresponding input port in
chart
Output Simulink output signal connected to corresponding output port in
chart

Note: Avoid inheriting data types from output signals. See Avoid
inheriting output data properties from Simulink blocks on page
8-63.
Parameter Corresponding MATLAB workspace variable or Simulink
parameter in a masked subsystem
Data Store Memory Corresponding Simulink data store

To configure these objects to inherit data types, create the corresponding objects in the
Simulink model, and then select Inherit: Same as Simulink from the Type drop-
down list in the Data properties dialog box. For more information, see Specify Data Type
with the Data Type Assistant on page 8-36.

To determine the data types that the objects inherit, build the Simulink model and look
at the Compiled Type column for each Stateflow data object in the Model Explorer.

Derive Data Types from Previously Defined Data


You can use the type operator to derive data types from previously defined Stateflow
data. In the following example, the expression type(inbus) specifies the data type
of the Stateflow structure counterbus_struct, where inbus is defined by the

8-40
Type Stateflow Data

Simulink.Bus object COUNTERBUS. Therefore, the structure counterbus_struct also


derives its data type from the bus object COUNTERBUS.

After you build your model, the Compiled Type column of the Model Explorer shows the
type of each data object in the compiled simulation application. For more information, see
type Operator on page 11-25.

Type Data by Using an Alias


You can specify the type of Stateflow data by using a Simulink data type alias (see
Simulink.AliasType in the Simulink Reference documentation). Suppose that you
define a data type alias named MyFloat as follows:

MyFloat = Simulink.AliasType;
MyFloat.BaseType = 'single';

In the following example, the data y has the same type as MyFloat.

8-41
8 Define Data

After you build your model, the Compiled Type column of the Model Explorer shows the
type used in the compiled simulation application.

Strong Data Typing with Simulink I/O

By default, inputs to and outputs from charts are of type double. Input signals from
Simulink models convert to the type of the corresponding input data objects in charts.
Likewise, the data output objects convert to double before they are exported as output
signals to Simulink models.

To interface directly with signals of data types other than double without the need for
conversion, select Use Strong Data Typing with Simulink I/O in the chart properties.
The chart accepts input signals of any data type that Simulink supports, as long as the
data type of the input signal matches the type of the corresponding Stateflow data object.
Otherwise, you receive a type mismatch error.

Note: For fixed-point data, select Use Strong Data Typing with Simulink I/O to flag
mismatches between input or output fixed-point data in charts and their counterparts in
Simulink models.

8-42
Type Stateflow Data

More About
Specify Chart Properties on page 22-3
About Data Types in Simulink (Simulink)

8-43
8 Define Data

Size Stateflow Data


In this section...
Methods for Sizing Stateflow Data on page 8-44
How to Specify Data Size on page 8-45
Inherit Input or Output Size from Simulink Signals on page 8-45
Guidelines for Sizing Data with Numeric Values on page 8-45
Guidelines for Sizing Data with MATLAB Expressions on page 8-46
Examples of Valid Data Size Expressions on page 8-47
Name Conflict Resolution for Variables in Size Expressions on page 8-47
Best Practices for Sizing Stateflow Data on page 8-47

Methods for Sizing Stateflow Data


You can specify the size of Stateflow data by:

Inheriting the size from a Simulink signal


Using numeric values
Using MATLAB expressions

Support for a sizing method depends on the scope of your data:


Scope of Data Method for Sizing Data
Inherit the Size Use Numeric Values Use MATLAB
Expressions
Local No Yes Yes
Constant No Yes Yes
Parameter No Yes Yes
Input Yes Yes Yes
Output Yes Yes Yes
Data store memory Yes No No

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.

8-44
Size Stateflow Data

How to Specify Data Size


Specify the size of Stateflow data by setting the Size property in the Property Inspector
or the Data properties dialog box. To specify the size of Stateflow data using API
commands, set the Props.Array.Size property to a numeric value or a MATLAB
expression that represents a scalar, vector, matrix, or n-dimensional array. For more
information on using the API, see Stateflow.Data Properties.

Inherit Input or Output Size from Simulink Signals


To configure Stateflow input and output data to inherit size from the corresponding
Simulink input and output signals, enter 1 in the Size field of the data properties. This
default setting applies to input and output data that you add to your chart. After you
build your model, the Compiled Size column of the Model Explorer displays the actual
size that the compiled simulation application uses.

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.

Guidelines for Sizing Data with Numeric Values


When you specify data size using numeric values in the Size field of the Data properties
dialog box, follow these guidelines:

Dimensionality What to Specify in the Dialog Box Equivalent API Command


Scalar 1 (or leave the field blank) data_handle.Props.Array.Size =
'1';
data_handle.Props.Array.Size =
'';
Vector The number of elements in the row or data_handle.Props.Array.Size =
column vector 'number_of_elements';

8-45
8 Define Data

Dimensionality What to Specify in the Dialog Box Equivalent API Command


Matrix An expression of the format data_handle.Props.Array.Size =
[r c], where: '[r c]';

r is the number of rows


c is the number of columns
N-dimensional An expression of the format data_handle.Props.Array.Size
array [Size_of_dim1 Size_of_dim2 = '[Size_of_dim1 Size_of_dim2
... Size_of_dimN], where: ... Size_of_dimN];

Size_of_dim1 is the size of the


first dimension
Size_of_dim2 is the size of the
second dimension
Size_of_dimN is the size of the N-
th dimension

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

Guidelines for Sizing Data with MATLAB Expressions


When you specify data size using MATLAB expressions, follow the same guidelines
that apply to sizing with numeric values (see Guidelines for Sizing Data with Numeric
Values on page 8-45). The following guidelines also apply.

Expressions that specify the size of a dimension:

Can contain a mix of numeric values, variables, arithmetic operators, parameters,


and calls to MATLAB functions.
Must evaluate to a positive integer value.
To specify inherited data size, you must enter 1 in the Size field or set the
Props.Array.Size property for the data to 1. Expressions cannot evaluate to a
value of 1.
If the expression contains an enumerated value, you must include the type prefix for
consistency with MATLAB naming rules.

8-46
Size Stateflow Data

For example, Colors.Red is valid but Red is not.


You cannot size Stateflow input data with an expression that accepts frame-based
data from Simulink.

Examples of Valid Data Size Expressions


The following examples are valid MATLAB expressions for sizing data in your chart:

K+3, where K is a chart-level Stateflow data


N/2, where N is a variable in the MATLAB base workspace
2*Colors.Red, where Red is an enumerated value of type Colors
[fi(2,1,16,2) fi(4,1,16,2)], which specifies a data size of [2 4] using a
signed fixed-point type with word length of 16 and fraction length of 2

Name Conflict Resolution for Variables in Size Expressions


When multiple variables with identical names exist in a model, the variable with the
highest priority applies:

1 Mask parameters
2 Model workspace
3 MATLAB base workspace
4 Stateflow data

Best Practices for Sizing Stateflow Data


Avoid use of variables that can lead to naming conflicts

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.

Avoid use of size(u) expressions

Instead of using a size(u) expression, use a MATLAB expression that evaluates


directly to the size of Stateflow data.

8-47
8 Define Data

More About
Stateflow Data Properties on page 8-6

8-48
Handle Integer Overflow for Chart Data

Handle Integer Overflow for Chart Data

In this section...
When Integer Overflow Can Occur on page 8-49
Support for Handling Integer Overflow in Charts on page 8-49
Effect of Integer Promotion Rules on Saturation on page 8-51
Impact of Saturation on Error Checks on page 8-52

When Integer Overflow Can Occur


For some arithmetic operations, a processor might need to take an n-bit fixed-point value
and store it in m bits, where m n. If m < n, the reduced range of the value can cause an
overflow for an arithmetic operation. Some processors identify this overflow as Inf or
NaN. Other processors, especially digital signal processors (DSPs), handle overflows by
saturating or wrapping the value.

For more information about saturation and wrapping for integer overflow, see
Saturation and Wrapping (Fixed-Point Designer).

Support for Handling Integer Overflow in Charts


For charts, you can control whether or not saturation occurs for integer overflow. Use the
chart property, Saturate on integer overflow, to control overflow handling.

8-49
8 Define Data

Check Box When to Use This Setting Overflow Handling Example of the Result
Selected Overflow is possible Overflows saturate to An overflow associated
for data in your chart either the minimum or with a signed 8-bit integer
and you want explicit maximum value that the saturates to 128 or +127
saturation protection in data type can represent. in the generated code.
the generated code.
Cleared You want to optimize The handling of overflows The number 130 does not
efficiency of the generated depends on the C fit in a signed 8-bit integer
code. compiler that you use for and wraps to 126 in the
generating code. generated code.

Arithmetic operations for which you can enable saturation protection are:

Unary minus: a

8-50
Handle Integer Overflow for Chart Data

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

Keep the following considerations in mind when you select Saturate on integer
overflow:

Saturation applies to all intermediate operations, not just the output or final result.
The code generator can detect cases when overflow is not possible. In these cases, the
generated code does not include saturation protection.

Effect of Integer Promotion Rules on Saturation


Charts use ANSI C rules for integer promotion.

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:
y = (u1 + u2) - u3;

Based on integer promotion rules, that expression is equivalent to the following


statements:
uint8_T u1, u2, u3, y;
int32_T tmp, result;
tmp = (int32_T) u1 + (int32_T) u2;
result = tmp - (int32_T) u3;
y = (uint8_T) result;

For each calculation, the following data types and saturation limits apply.

8-51
8 Define Data

Calculation Data Type Saturation Limits


tmp int32 (MIN_INT32, MAX_INT32)
result int32 (MIN_INT32, MAX_INT32)
y uint8 (MIN_UINT8, MAX_UINT8)

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.

Impact of Saturation on Error Checks


Suppose that you set Wrap on overflow in the Diagnostics: Data Validity pane of
the Model Configuration Parameters dialog box to error or warning. When you select
Saturate on integer overflow, Stateflow does not flag cases of integer overflow during
simulation. However, Stateflow continues to flag the following situations:

Out-of-range data violations based on minimum and maximum range checks


Division-by-zero operations

8-52
Define Temporary Data

Define Temporary Data


In this section...
When to Define Temporary Data on page 8-53
How to Define Temporary Data on page 8-53

When to Define Temporary Data


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.

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.

How to Define Temporary Data


To define temporary data for a Stateflow function, follow these steps:

1 Open the Model Explorer.


2 In the Model Explorer, select the graphical, truth table, or MATLAB function that
will use temporary data.
3 Select Add > Data.

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

8-53
8 Define Data

Identify Data Using Dot Notation


In this section...
What Is Dot Notation? on page 8-54
Resolution of Qualified Data Names with Dot Notation on page 8-55
Best Practices for Using Dot Notation in Qualified Data Names on page 8-56

What Is Dot Notation?


Dot notation is a way to identify data and functions at a specific level of the chart
hierarchy. A qualified data or function name uses dot notation to specify the path to the
parent state for that data or function.

For example, you can specify qualified data names in state actions and transitions by
using dot notation.

In this chart, data resides in the state aa. The qualified data names in state actions and
transitions use dot notation to refer to this data.

In state a, the entry action contains the qualified data name aa.data.
In state b, the entry action contains the qualified data name a.aa.data.
In the default transition, the action contains the qualified data name a.aa.data.

8-54
Identify Data Using Dot Notation

Resolution of Qualified Data Names with Dot Notation


During simulation, the chart searches for data that matches the qualified data name
with dot notation. These rules apply:

The chart does not do an exhaustive search of all data.


The chart does not stop searching after finding one match. The search continues until
it reaches the chart level.

Display an
error
message.

Process for Resolving Qualified Data Names

8-55
8 Define Data

The flow chart describes the following search process.

Stage Action
1 The search begins at the level of the hierarchy where the qualified data name
appears.

For a state action, that state is the starting point.


For a transition label, the parent of the source object is the starting point.
2 The chart searches at that level of the hierarchy for a path to the data. If the
chart finds a match, it adds that path to the list of possible matches.
3 The chart moves up to the next highest level of the hierarchy. At that level,
the chart searches for a path to the data. If the chart finds a match, it adds
that path to the list of possible matches.
4 The previous step repeats until the search reaches the chart level.
5 At the chart level, one more search occurs for a path to the data. If a match
exists, that path becomes part of the list of possible matches. Then, the search
ends.
6 After the search ends, one of the following occurs:

If a unique match exists, the statement containing the qualified data name
executes.
If no matches or multiple matches exist, an error message appears.

Best Practices for Using Dot Notation in Qualified Data Names


These examples show how to avoid problems when using dot notation in qualified data
names.

Use a Specific Path in the Qualified Data Name

Be specific when defining the path to the data.

8-56
Identify Data Using Dot Notation

Suppose that state aa contains data. In state b, the entry action contains aa.data, a
qualified data name that the chart cannot resolve. The following search process occurs:

Stage Action Finds a Match?


1 Chooses state b as the starting point and searches No
at that level for an object aa that contains data.
2 Moves up to the next level of the hierarchy and No
searches at the chart level for an object aa that
contains data.

The search ends, and an error message appears because no match exists for aa.data.

To avoid this error, use a specific path for the qualified data name in the entry action of
state b:

en: a.aa.data+=1;

Use Unique State Names

Use unique names when you name the states in a chart.

8-57
8 Define Data

Suppose that both states named aa contain a data object named data. In state a, the
entry action contains two instances of aa.data that the chart cannot resolve. The
following search process occurs:

Stage Action Finds a Match?


1 Chooses state a as the starting point and searches Yes
at that level for an object aa that contains data.
2 Moves up to the next level of the hierarchy and Yes
searches at the chart level for an object aa that
contains data.

The search ends, and an error message appears because multiple matches exist for
aa.data.

To avoid this error, perform one of these corrective actions:

Rename one of the two states named aa.


Use a more specific path for the qualified data names in the entry action of state a:

en: y+=a.aa.data, a.aa.data+=1;


Enclose the outer state aa in a box or another state. Adding an enclosure prevents the
search process from detecting that outer state.

8-58
Resolve Data Properties from Simulink Signal Objects

Resolve Data Properties from Simulink Signal Objects

In this section...
About Explicit Signal Resolution on page 8-59
Inherited Properties on page 8-59
Enable Signal Resolution on page 8-60
A Simple Example on page 8-60

About Explicit Signal Resolution


Stateflow local and output data in charts can explicitly inherit properties from
Simulink.Signal objects in the model workspace or base workspace. This process is
called signal resolution and requires that the resolved signal have the same name as the
chart output or local data.

For information about Simulink signal resolution, see Symbol Resolution (Simulink)
and Symbol Resolution Process (Simulink) in the Simulink documentation.

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
Control Data Representation by Applying Custom Storage Classes (Embedded
Coder).

8-59
8 Define Data

Enable Signal Resolution


To enable explicit signal resolution, follow these steps:

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.


3 Add output or local data to a chart.
4 Enter a name for your data that matches the name of the Simulink.Signal object.
5 In the data properties, select the Data must resolve to signal object check box.

After you select this check box, the dialog box removes or grays out the properties
that your data inherits from the signal. For a list of properties that your data can
inherit during signal resolution, see Inherited Properties on page 8-59.

A Simple Example
The following model shows how a chart resolves local and output data to
Simulink.Signal objects.

8-60
Resolve Data Properties from Simulink Signal Objects

In the base workspace, there are three Simulink.Signal objects with these properties:

Name Data Type Dimensions Storage Class


y1 double 1 SimulinkGlobal
y2 uint32 [2 2] Auto
local single 1 ExportedGlobal

The chart contains three data objects two outputs and a local variable that will
resolve to a signal with the same name, as follows:

When you build the model, each data object inherits the properties of the identically
named signal:

8-61
8 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>/Chart' */

8-62
Best Practices for Using Data in Charts

Best Practices for Using Data in Charts


In this section...
Avoid inheriting output data properties from Simulink blocks on page 8-63
Restrict use of machine-parented data on page 8-63

Avoid inheriting output data properties from Simulink blocks


Stateflow output data should not inherit properties from output signals, because the
values back propagate from Simulink blocks and can be unpredictable.

Restrict use of machine-parented data


Avoid using machine-parented data. The presence of machine-parented data in a model
prevents reuse of generated code and other code optimizations. This type of data is also
incompatible with many Simulink and Stateflow features.

For example, the following features do not support machine-parented data:

Enumerated data
Simulink functions
Chart SimState
Implicit change events
Detection of unused data
Model referencing (see Limitations on All Model Referencing (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 8-29.

More About
Simulink Functions in Stateflow on page 27-2
What Is Enumerated Data? on page 18-2

8-63
8 Define Data

What Is a SimState? on page 15-2


Keywords for Implicit Events on page 9-33
Detect Unused Data in the Symbols Window on page 8-4

8-64
Transfer Data Across Models

Transfer Data Across Models


In this section...
Copy Data Objects on page 8-65
Move Data Objects on page 8-65

Copy Data Objects


When you copy a chart from one Simulink model to another, all data objects in the chart
hierarchy are copied except those that the Stateflow machine parents. However, you can
use the Model Explorer to transfer individual data objects from machine to machine.

To copy a data object, follow these steps:

1 In the Contents pane of the Model Explorer, rightclick 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.

Move Data Objects


To move a data object, click the object in the Contents pane of the Model Explorer and
drag it to the destination Stateflow machine in the Model Hierarchy pane.

8-65
9

Define Events

How Events Work in Stateflow Charts on page 9-2


Define Events on page 9-5
Set Properties for an Event on page 9-7
Activate a Stateflow Chart Using Input Events on page 9-9
Control States When Function-Call Inputs Reenable Charts on page 9-13
Activate a Simulink Block Using Output Events on page 9-20
Control Chart Execution Using Implicit Events on page 9-33
Count Events on page 9-38
Best Practices for Using Events in Stateflow Charts on page 9-40
9 Define Events

How Events Work in Stateflow Charts


In this section...
What Is an Event? on page 9-2
When to Use Events on page 9-2
Types of Events on page 9-3
Where You Can Use Events on page 9-3
Diagnostic for Detecting Unused Events on page 9-3

What Is an Event?
An event is a Stateflow object that can trigger actions in one of these objects:

A Simulink triggered subsystem


A Simulink function-call subsystem
A Stateflow chart

When to Use Events


Use events when you want to:

Activate a Simulink triggered subsystem (see Activate a Simulink Block Using Edge
Triggers on page 9-20)
Activate a Simulink function-call subsystem (see Activate a Simulink Block Using
Function Calls on page 9-28)
Trigger actions in parallel states of a Stateflow chart (see Broadcast Events to
Synchronize States on page 11-52)

Although Stateflow software does not limit the number of events you can use in a
chart, the underlying C compiler enforces a theoretical limit of (2^31)-1 events for the
generated code.

When should I use conditions instead of events?

Use conditions on transitions when you want to:

Represent conditional statements, for example, x < 1 or x == 0

9-2
How Events Work in Stateflow Charts

Represent a change of input value from a Simulink block

For more information about using conditions on transitions, see Transition Action
Types on page 11-8.

Types of Events
An explicit event is an event that you define and can have one of the following scopes.

Scope Description
Local Event that can occur anywhere in a Stateflow machine but is
visible only in the parent object (and descendants of the parent).
See Directed Event Broadcasting on page 11-52.
Input from Simulink Event that occurs in a Simulink block but is broadcast to a
Stateflow chart. See Activate a Stateflow Chart Using Input
Events on page 9-9.
Output to Simulink Event that occurs in a Stateflow chart but is broadcast to a
Simulink block. See Activate a Simulink Block Using Output
Events on page 9-20.

An implicit event is a built-in event that broadcasts automatically during chart execution
(see Control Chart Execution Using Implicit Events on page 9-33).

Where You Can Use Events


You can define explicit events at these levels of the Stateflow hierarchy.

An event you define in a... Is visible to...


Chart The chart and all states and substates
Subchart The subchart and all states and substates
State The state and all substates

Diagnostic for Detecting Unused Events


If you have unused events in your chart, a warning message appears during simulation
with a list of events you can remove. By removing objects that have no effect on

9-3
9 Define Events

simulation, you can reduce the size of your model. This diagnostic checks for usage of
Stateflow events, except for the following types:

Function-call input events


Edge-triggered input events

After you select an event for removal, a dialog box confirms your choice. In this dialog
box, you can specify that other deletions occur without confirmation. If you prevent the
confirmation dialog box from appearing, you can reenable it at any time by typing at the
command prompt:
sfpref('showDeleteUnusedConfGui', 1)

You can control the level of diagnostic action for unused events in the Diagnostics
> Stateflow pane of the Model Configuration Parameters dialog box. For more
information, see the documentation for the Unused data, events, messages, and
functions (Simulink) diagnostic.

9-4
Define Events

Define Events
In this section...
Add Events with the Stateflow Editor on page 9-5
Add Events with the Model Explorer on page 9-5

Add Events with the Stateflow Editor


From the Stateflow editor, you can add events via the Symbols window or through
menus.

To open the Symbols window, select View > Symbols. To add events in the Symbols
window:

1
Click the Create Event icon .
2 In the row for the new event, under TYPE, click the icon and choose:

Input Event
Local Event
Output Event
3 Edit the name of the event.
4 For input and output event, click the PORT field and choose a port number.

To add events through menus, select one of these scopes.

Scope Menu Option


Input Chart > Add Inputs & Outputs > Event Input From Simulink
Output Chart > Add Inputs & Outputs > Event Output To Simulink
Local Chart > Add Other Elements > Local Event

Specify properties for the new event as described in Set Properties for an Event on page
9-7.

Add Events with the Model Explorer


1 In the Stateflow Editor, select View > Model Explorer.

9-5
9 Define Events

2 In the Model Explorer, on the Model Hierarchy pane, select the object in the
Stateflow hierarchy where you want the new event to be visible.

The object you select becomes the parent of the event.


3 In the Model Explorer, select Add > Event.

The Model Explorer adds a default definition for the new event in the hierarchy and
displays an entry row for the new event in the Contents pane.
4 Change the properties of the event that you add in one of these ways:

Right-click the event row and select Properties to open the Event properties
dialog box.
To set specific properties such as Name, Scope, and Port, click individual cells
in the entry row.

More About
Set Properties for an Event on page 9-7
How Events Work in Stateflow Charts on page 9-2

9-6
Set Properties for an Event

Set Properties for an Event


In this section...
Access Event Properties on page 9-7
Property Fields on page 9-7

Access Event Properties


You can specify event properties in either the Property Inspector or the Event properties
dialog box in the Model Explorer.

Property Inspector

1 Open the Symbols window by selecting View > Symbols.


2 In the Symbols window, right-click the event and select Inspect.
3 In the Property Inspector window, edit the event properties.
Model Explorer

1 Double-click the event in the Contents pane.


2 Edit the event properties in the Model Explorer Event properties dialog box.

Property Fields
Name

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.

Scope

Scope of the event. The scope specifies where the event occurs relative to the parent
object. For information about types of scope, see Types of Events on page 9-3.

Port

Property that applies to input and output events.

For input events, port is the index of the input signal that triggers the event.

9-7
9 Define Events

For output events, port is the index of the signal that outputs this event.

You assign input and output events to ports in the order in which you add the events. For
example, you assign the first input event to input port 1 and the third output event to
output port 3.

You can change port assignments in the Model Explorer or the Event properties dialog
box. When you change the number of one port, the numbers of other ports adjust
automatically to preserve the relative order. See Association of Input Events with
Control Signals on page 9-11 and Association of Output Events with Output Ports
on page 9-31.

Trigger

Type of signal that triggers an input or output event. See Activate a Stateflow Chart
Using Input Events on page 9-9 or Activate a Simulink Block Using Output
Events on page 9-20.

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.

Scope of Event Available Breakpoints


Start of Broadcast End of Broadcast
Local Yes Yes
Input Yes No
Output No No

Description

Description of this event. You can enter brief descriptions of events in the hierarchy.

Document Link

Link to online documentation for events in a Stateflow chart. To document a particular


event, set the Document Link property to a web URL address or MATLAB expression
that displays documentation in a suitable online format (for example, an HTML file or
text in the MATLAB Command Window). When you click the blue Document Link text,
the chart evaluates the expression.

9-8
Activate a Stateflow Chart Using Input Events

Activate a Stateflow Chart Using Input Events


In this section...
What Is an Input Event? on page 9-9
Activate a Stateflow Chart Using Edge Triggers on page 9-9
Activate a Stateflow Chart Using Function Calls on page 9-10
Association of Input Events with Control Signals on page 9-11

What Is an Input Event?


An input event occurs outside a chart but is visible only in that chart. This type of event
allows other Simulink blocks, including other Stateflow charts, to notify a specific chart
of events that occur outside it.

You can activate a Stateflow chart via a change in control signal (an edge-triggered input
event) or a function call from a Simulink block (a function-call input event). The sections
that follow describe when and how to use each type of input event.

Note: You cannot mix edge-triggered and function-call input events in a Stateflow chart.
If you try to mix these input events, an error message appears during simulation.

Activate a Stateflow Chart Using Edge Triggers


An edge-triggered input event causes a Stateflow chart to execute during the current
time step of simulation. This type of input event works only when a change in control
signal acts as a trigger.

When to Use an Edge-Triggered Input Event

Use an edge-triggered input event to activate a chart when your model requires chart
execution at regular (or periodic) intervals.

How to Define an Edge-Triggered Input Event

To define an edge-triggered input event:

1 Add an event to the Stateflow chart, as described in Define Events on page 9-5.

9-9
9 Define Events

Note: You must add an input event to the chart and not to one of its objects.
2 Set the Scope property for the event to Input from Simulink.

A single trigger port appears at the top of the Stateflow block in the Simulink model.
3 Set the Trigger property to one of these edge triggers.

Edge Trigger Type Description


Rising Rising edge trigger, where the control signal changes from
either zero or a negative value to a positive value.
Falling Falling edge trigger, where the control signal changes from
a positive value to either zero or a negative value.
Either Either rising or falling edge trigger.

In all cases, the signal must cross 0 to be a valid edge trigger. For example, a signal
that changes from -1 to 1 is a valid rising edge, but a signal that changes from 1to2
is not valid.

Example of Using an Edge-Triggered Input Event

The model sf_loop_scheduler shows how to use an edge-triggered input event to


activate a Stateflow chart at regular intervals. For information on running this model
and how it works, see Schedule One Subsystem in a Single Step on page 24-14.

Activate a Stateflow Chart Using Function Calls


A function-call input event causes a Stateflow chart to execute during the current time
step of simulation.

Note: When you use this type of input event, you must also define a function-call output
event for the block that calls the Stateflow chart.

When to Use a Function-Call Input Event

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.

9-10
Activate a Stateflow Chart Using Input Events

How to Define a Function-Call Input Event

To define a function-call input event:

1 Add an event to the Stateflow chart, as described in Define Events on page 9-5.

Note: You must add an input event to the chart and not to one of its objects.
2 Set the Scope property for the event to Input from Simulink.

A single trigger port appears at the top of the Stateflow block in the Simulink model.
3 Set the Trigger property to Function call.

Example of Using a Function-Call Input Event

The model sf_loop_scheduler shows how to use a function-call input event to


activate a Stateflow chart. For information on running this model and how it works, see
Schedule One Subsystem in a Single Step on page 24-14.

Association of Input Events with Control Signals


When you define one or more input events for a chart, a single trigger port to the chart
block appears. External Simulink blocks can trigger the input events via a signal or
vector of signals connected to the trigger port. The Port property of an input event
associates the event with a specific element of a control signal vector that connects to the
trigger port (see Port on page 9-7).

The number of the port that you assign to the input event acts as an index into the
control signal vector. For example, the first element of the signal vector triggers the
input event assigned to input port 1, the fourth element triggers the input event assigned
to input port 4, and so on. You assign port numbers in the order in which you add the
events. However, you can change these assignments by setting the Port property of an
event to the index of the signal that you use to trigger the event.

Data Types Allowed for Input Events

For multiple input events to a trigger port, the data types of all signals must be identical.
If you use signals of different data types as input events, an error message appears when
you try to simulate your model.

For example, you can mux two input signals of type double to use as input events to a
chart.

9-11
9 Define Events

However, you cannot mux two input signals of different data types, such as boolean and
double.

Behavior of Edge-Triggered Input Events

At any given time step, input events are checked in ascending order based on their port
numbers. The chart awakens once per valid event. For edge-triggered input events,
multiple edges can occur in the same time step, which wake the chart more than once in
that time step. In this situation, events occur (and wake the chart) in an ascending order
based on their port numbers.

Behavior of Function-Call Input Events

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 can be valid in a single time
step.

9-12
Control States When Function-Call Inputs Reenable Charts

Control States When Function-Call Inputs Reenable Charts

In this section...
Set Behavior for a Reenabled Chart on page 9-13
Behavior When the Parent Is the Model Root on page 9-13
Behavior When the Chart Is Inside a Model Block on page 9-17

Set Behavior for a Reenabled Chart


If you define a function-call input event for a chart, you can control the behavior of states
when this event reenables the chart:

1 Open the Chart properties dialog box.


2 For States When Enabling, select one of these options:

Held Maintain most recent values of the states.


Reset Revert to the initial values of the states.
Inherit Inherit this setting from the parent subsystem.

If... The inherited setting is...


The parent of the chart is the model Held
root
The chart is inside a Model block Reset

For more information, see Model


Reference (Simulink).

For new charts, the default setting is Held.

Behavior When the Parent Is the Model Root


When the parent of your chart is the model root, the following types of behavior can occur
when a function-call input event reenables the chart.

9-13
9 Define Events

The chart... When you set the States When Enabling


property to...
Maintains the most recent values of the Inherit or Held
states
Reverts to the initial values of the states Reset

What Happens When the Setting Is Inherit or Held

In the following model, the Caller chart uses the event E to wake up and execute the
Callee chart.

The Caller chart contains two states, A and B.

When you bind E to A:

Entering A enables the Callee chart.


Exiting A disables the Callee chart.
Reentering A reenables the Callee chart.

Each time the Callee chart executes, the output data y increments by one.

9-14
Control States When Function-Call Inputs Reenable Charts

In the Chart properties dialog box for Callee, States When Enabling is Inherit.
Because the parent of this chart is the model root, the chart maintains the most recent
values of all states when reenabled.

During simulation, Callee maintains the most recent value of its state when the
function-call input event reenables the chart at t = 20 and 40.

The key behaviors are:

Time Interval Caller Chart Callee Chart


0 10 State A is active and enables State A executes by
Callee. incrementing y.

9-15
9 Define Events

Time Interval Caller Chart Callee Chart


10 20 State B is active and State A does not execute.
disables Callee.
20 30 State A is active and State A executes by
reenables Callee. incrementing y.
30 40 State B is active and State A does not execute.
disables Callee.
40 50 State A is active and State A executes by
reenables Callee. incrementing y.

If States When Enabling is Held, the output is the same.

What Happens When the Setting Is Reset

Suppose that the States When Enabling property is Reset for Callee. During
simulation, Callee reverts to the initial value of its state when the function-call input
event reenables the chart at t = 20 and 40.

9-16
Control States When Function-Call Inputs Reenable Charts

Behavior When the Chart Is Inside a Model Block


When your chart is inside a Model block, the following types of behavior can occur when a
function-call input event reenables the chart.

The chart... When you set the States When Enabling


property to...
Maintains the most recent values of the Held
states
Reverts to the initial values of the states Inherit or Reset

What Happens When the Setting Is Inherit or Reset

The following model contains a Model block and a scope. (For more information about
using Model blocks, see For more information, see Model Reference (Simulink)..)

The Model block contains the Caller and Callee charts from Behavior When the
Parent Is the Model Root on page 9-13.

In the Chart properties dialog box for Callee, States When Enabling is Inherit.
Because this chart is inside a Model block, the chart reverts to the initial values of all
states when reenabled.

9-17
9 Define Events

During simulation, Callee reverts to the initial value of its state when the function-call
input event reenables the chart at t = 20 and 40.

The key behaviors are:

Time Interval Caller Chart Callee Chart


0 10 State A is active and enables State A executes by
Callee. incrementing y.
10 20 State B is active and State A does not execute.
disables Callee.
20 30 State A is active and State A executes by
reenables Callee. incrementing y.
30 40 State B is active and State A does not execute.
disables Callee.
40 50 State A is active and State A executes by
reenables Callee. incrementing y.

9-18
Control States When Function-Call Inputs Reenable Charts

If States When Enabling is Reset, the output is the same.

What Happens When the Setting Is Held

Suppose that the States When Enabling property is Held for Callee. During
simulation, Callee maintains the most recent value of its state when the function-call
input event reenables the chart at t = 20 and 40.

9-19
9 Define Events

Activate a Simulink Block Using Output Events


In this section...
What Is an Output Event? on page 9-20
Activate a Simulink Block Using Edge Triggers on page 9-20
Activate a Simulink Block Using Function Calls on page 9-28
Association of Output Events with Output Ports on page 9-31
Access Simulink Subsystems Triggered By Output Events on page 9-32

What Is an Output Event?


An output event is an event that occurs in a Stateflow chart but is visible in Simulink
blocks outside the chart. This type of event allows a chart to notify other blocks in a
model about events that occur in the chart.

You use output events to activate other blocks in the same model. You can define
multiple output events in a chart, where each output event maps to an output port (see
Port on page 9-7).

Note: Output events must be scalar.

Activate a Simulink Block Using Edge Triggers


An edge-triggered output event activates a Simulink block to execute during the current
time step of simulation. This type of output event works only when a change in control
signal acts as a trigger.

When to Use an Edge-Triggered Output Event

Use an edge-triggered output event to activate a Simulink subsystem when your model
requires subsystem execution at regular (or periodic) intervals.

How to Define an Edge-Triggered Output Event

To define an edge-triggered output event:

1 Add an event to the Stateflow chart, as described in Define Events on page 9-5.

9-20
Activate a Simulink Block Using Output Events

2 Set the Scope property for the event to Output to Simulink.

For each output event you define, an output port appears on the Stateflow block.
3 Set the Trigger property of the output event to Either Edge.

Note: Unlike edge-triggered input events, you cannot specify a Rising or Falling
edge trigger.

Example of Using an Edge-Triggered Output Event

The following model shows how to use an edge-triggered output event to activate
triggered subsystems at regular intervals.

The chart contains the edge-triggered output event e1 and the local data a, which
switches between 0 and 1 during simulation.

9-21
9 Define Events

In a chart, the Trigger property of an edge-triggered output event is always Either


Edge. However, Simulink triggered subsystems can have a Rising, Falling, or
Either Edge trigger. This model shows the difference between triggering a rising edge
subsystem and an either edge subsystem.

The output event e1 triggers On... When the data a switches...


the...
Either edge subsystem Every event broadcast From 0 to 1, or from 1 to 0
Rising edge subsystem Every other event broadcast From 0 to 1

When you simulate the model, the scope shows these results.

Queuing Behavior for Broadcasting an Edge-Triggered Output Event Multiple Times

If a chart tries to broadcast the same edge-triggered output event multiple times in a
single time step, the chart dispatches only one of these broadcasts in the present time
step. However, the chart queues up any pending broadcasts for dispatch that is, one at

9-22
Activate a Simulink Block Using Output Events

a time in successive time steps. Each time the chart wakes up in successive time steps,
if any pending broadcasts exist for the output event, the chart signals the edge-triggered
subsystem for execution. Based on the block sorted order of the Simulink model, the
edge-triggered subsystem executes. (For details, see Control and Display the Sorted
Order (Simulink).)

Note: For information on what happens for function-call output events, see Interleaving
Behavior for Broadcasting a Function-Call Output Event Multiple Times on page
9-29.

Queue Edge-Triggered Output Event Broadcasts

In this model, the chart Caller uses the edge-triggered output event output_cmd to
activate the chart Callee.

The chart Caller tries to broadcast the same edge-triggered output event four times in a
single time step, as shown.

9-23
9 Define Events

Each time the chart Callee is activated, the output data y increments by one.

When you simulate the model, you see this output in the scope.

At t = 1, the chart Caller dispatches only one of the four output events. Therefore, the
chart Callee executes once during that time step. However, the chart Caller queues up
the other three event broadcasts for future dispatch that is, one at a time for t = 2,
3, and 4. Each time Caller wakes up in successive time steps, it activates Callee for
execution. Therefore, the action y++ occurs once per time step at t = 1, 2, 3, and 4. During
simulation, Callee executes based on the block sorted order of the Simulink model.

Approximate a Function Call Using Queuing Behavior

When you cannot use a function-call output event, such as for HDL code generation, you
can approximate a function call by using:

9-24
Activate a Simulink Block Using Output Events

An edge-triggered output event


An enabled subsystem
Two consecutive event broadcasts

Note: While you can approximate a function call, a subtle difference in execution
behavior exists. Execution of a function-call subsystem occurs during execution of the
chart action that provides the trigger. However, execution of an enabled subsystem
occurs after execution of that chart action is complete.

In the following model, the chart Caller uses the edge-triggered output event
output_cmd to activate the enabled subsystem. The scope shows the value of the output
event during simulation.

The chart Caller broadcasts the edge-triggered output event using a send action.

9-25
9 Define Events

When you simulate the model, you see the following output in the scope. The simulation
runs for 40 seconds.

When simulation starts, the value of output_cmd is 0. At t = 20, the chart dispatches
output_cmd. Because this value changes to 1, the enabled subsystem becomes active
and executes during that time step. Because no other event broadcasts occur, the enabled

9-26
Activate a Simulink Block Using Output Events

subsystem continues to execute at every time step until simulation ends. Therefore, the
Display block shows a final value of 40.

To approximate a function call, add a second event broadcast in the same action.

When you simulate the model, you see the following output in the scope. The simulation
runs for 40 seconds.

9-27
9 Define Events

When simulation starts, the value of output_cmd is 0. At t = 20, the chart dispatches
output_cmd. Because this value changes to 1, the enabled subsystem becomes active
and executes during that time step. The chart also queues up the second event for
dispatch at the next time step. At t = 21, the chart dispatches the second output event,
which changes the value of output_cmd to 0. Therefore, the enabled subsystem stops
executing and the Display block shows a final value of 20.

The queuing behavior of consecutive edge-triggered output events enables you to


approximate a function call with an enabled subsystem.

Activate a Simulink Block Using Function Calls


A function-call output event activates a Simulink block to execute during the current
time step of simulation. This type of output event works only on blocks that you can
trigger with a function call.

When to Use a Function-Call Output Event

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.

How to Define a Function-Call Output Event

To define a function-call output event:

1 Add an event to the chart, as described in Define Events on page 9-5.


2 Set the Scope property for the event to Output to Simulink.

For each output event you define, an output port appears on the Stateflow block.
3 Set the Scope property of the output event to Function call.

Example of Using a Function-Call Output Event

The model sf_loop_scheduler shows how to use a function-call output event to activate a
Simulink block. For information on running this model and how it works, see Schedule
One Subsystem in a Single Step on page 24-14.

9-28
Activate a Simulink Block Using Output Events

The function-call output event... Of the chart... Activates...


call Edge to Function The chart Looping Scheduler
A1 Looping Scheduler The function-call subsystem A1

Interleaving Behavior for Broadcasting a Function-Call Output Event Multiple Times

If a chart tries to broadcast the same function-call output event multiple times 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 function-call initiator so
that output from the function-call subsystem is available right away in the function-call
initiator. (For details, see Function-Call Subsystems (Simulink).)

9-29
9 Define Events

Note: For information on what happens for edge-triggered output events, see Queuing
Behavior for Broadcasting an Edge-Triggered Output Event Multiple Times on page
9-22.

Interleave Function-Call Output Event Broadcasts

In this model, the chart Caller uses the function-call output event output_cmd to
activate the chart Callee.

The chart Caller tries to broadcast the same function-call output event four times in a
single time step, as shown.

Each time the chart Callee is activated, the output data y increments by one.

When you simulate the model, you see this output in the scope.

9-30
Activate a Simulink Block Using Output Events

At t = 1, the chart Caller dispatches all four output events. Therefore, the chart Callee
executes four times during that time step. Therefore, the action y++ also occurs four
times in that time step. During simulation, execution of Callee is interleaved with
execution of Caller so that output from Callee is available right away.

Association of Output Events with Output Ports


The Port property associates an output event with an output port on the chart block that
owns the event. This property specifies the position of the output port relative to others.

All output ports appear sequentially from top to bottom. Output data ports appear
sequentially above output event ports on the right side of a chart block. As you add
output events, their default Port properties appear sequentially at the end of the current
port list.

You can change the default port assignment of an event by resetting its Port property.
When you change the Port property for an output event, the ports for the remaining
output events automatically renumber, preserving the original order. For example,

9-31
9 Define Events

assume you have three output events, OE1, OE2, and OE3, which associate with the
output ports 4, 5, and 6, respectively. If you change the Port property for OE2 to 6, the
ports for OE1 and OE3 renumber to 4 and 5, respectively.

Access Simulink Subsystems Triggered By Output Events


To access the Simulink subsystem associated with a Stateflow output event:

1 In your chart, right-click the state or transition that contains the event of interest
and select Explore.
2 Select the desired event.

The Simulink subsystem associated with the event appears.

9-32
Control Chart Execution Using Implicit Events

Control Chart Execution Using Implicit Events


In this section...
What Are Implicit Events? on page 9-33
Keywords for Implicit Events on page 9-33
Transition Between States Using Implicit Events on page 9-34
Execution Order of Transitions with Implicit Events on page 9-35

What Are Implicit Events?


Implicit events are built-in events that occur when a chart executes:

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.

Keywords for Implicit Events


To reference implicit events, action statements use this syntax:

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.

Implicit Event Meaning


change(data_name) or Specifies and implicitly generates a local event when
chg(data_name) Stateflow software writes a value to the variable data_name.

9-33
9 Define Events

Implicit Event Meaning


The variable data_name cannot be machine-parented data.
This implicit event works only with data that is at the chart
level or lower in the hierarchy. For machine-parented data,
use change detection operators to determine when the data
value changes. For more information, see Detect Changes in
Data Values on page 11-74.
enter(state_name) or Specifies and implicitly generates a local event when the
en(state_name) specified state_name is entered.
exit(state_name) or Specifies and implicitly generates a local event when the
ex(state_name) specified state_name is exited.
tick Specifies and implicitly generates a local event when the
chart of the action being evaluated awakens.
wakeup Same as the tick keyword.

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.

Transition Between States Using Implicit Events


This example illustrates use of implicit tick events.

9-34
Control Chart Execution 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 Using Temporal
Logic on page 11-56.

Execution Order of Transitions with Implicit Events


Suppose that:

Your chart contains parallel states.

9-35
9 Define Events

In multiple parallel states, the same implicit event is used to guard a transition from
one substate to another.

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:

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:

9-36
Control Chart Execution 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 on page 11-86.

9-37
9 Define Events

Count Events

In this section...
When to Count Events on page 9-38
How to Count Events on page 9-38
Collect and Store Input Data in a Vector on page 9-38

When to Count Events


Count events when you want to keep track of explicit or implicit events in your chart.

How to Count Events


You can count occurrences of explicit and implicit events using the temporalCount
operator. For information about the syntax of this operator, see Operators for Event-
Based Temporal Logic on page 11-57.

Collect and Store Input Data in a Vector


The following model collects and stores input data in a vector during chart simulation:

The chart contains two states and one MATLAB function:

9-38
Count Events

Stage 1: Observation of Input Data

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.

Stage 2: Storage of Input Data

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.

Stage 3: Display of Data Stored in the Vector

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 Control Chart Execution
Using Implicit Events on page 9-33.

9-39
9 Define Events

Best Practices for Using Events in Stateflow Charts


Use the send command to broadcast explicit events in actions

In state actions (entry, during, exit, and on event_name) and condition actions,
use the send command to broadcast explicit events. Using this command enhances
readability of a chart and ensures that explicit events are not mistaken for data. See
Directed Event Broadcasting on page 11-52 for details.

Do not mix edge-triggered input events and function-call input events in a chart

If you mix input events that use edge triggers and function calls, the chart detects this
violation during parsing, or simulation. An error message appears and chart execution
stops.

Avoid using the enter implicit event to check state activity

Use the in operator instead of the enter implicit event to check state activity. See
Check State Activity on page 11-86 for details.

9-40
10

Messages

How Messages Work in Stateflow Charts on page 10-2


View Differences Between Stateflow Messages, Events, and Data on page 10-3
Stateflow Message Syntax in Charts on page 10-11
Queuing Behavior of Stateflow Messages on page 10-21
Lifetime of a Stateflow Message on page 10-23
Limitations for Messages on page 10-24
Define Messages in a Stateflow Chart on page 10-25
Set Message Properties on page 10-27
Work with Message Viewer on page 10-30
10 Messages

How Messages Work in Stateflow Charts


In Stateflow, you can use messages to communicate within and between Stateflow charts.
From a chart, you send and forward messages that can hold data. After you send a
message, an input or local queue for a chart receives it. The message is held in the queue
until the chart evaluates the message.

The first time a chart transition or action evaluates a message, the chart determines if
the message is present in the queue. If the message is present in the queue, then the
chart removes it from the queue. This message is valid until it is forwarded, or until the
end of the time step. While the message is valid, other transitions or actions can access
the message data. While the message is valid, another transition or action that evaluates
the message will not remove another message from the queue. The chart destroys all
valid messages at the end of the current time step. You access message data by reading it
or writing to it.

When a chart receives a message, it does not trigger the chart to wake up. Events trigger
a chart to wake up. If the receiver chart cannot immediately respond to the event, then
the event is lost. Messages are queued at the message input port until the chart wakes
up. When the chart wakes up, it can respond to the messages in the input queue.

Message lines connect input and output ports in Simulink. You can create local
messages. A local message has its own queue with the same queue properties as the
message input port.

To visualize the interchange of messages during simulation, view the Message Viewer
block.

Related Examples
View Differences Between Stateflow Messages, Events, and Data on page
10-3
Work with Message Viewer on page 10-30

More About
Lifetime of a Stateflow Message on page 10-23
Stateflow Message Syntax in Charts on page 10-11

10-2
View Differences Between Stateflow Messages, Events, and Data

View Differences Between Stateflow Messages, Events, and Data


This example shows the difference in behavior of a Stateflow message compared to events
or data.

Sender Charts

This model has three sender charts, DataSender, EventSender, and MessageSender.
Each sender chart has one state, A. In the entry action of state A, each chart assigns an
output data value to 1, sends a function-call event, or sends a message.

10-3
10 Messages

Receiver Charts

For each of the sender charts, there is a corresponding receiving chart. Each receiver
chart has a state diagram with states A0, A1, A2, and A3. Each receiver chart has
a transition from A0 to A1 after 3 seconds. The data, event, or message from the
corresponding sender chart guards the transitions between A1, A2, and A3.

10-4
View Differences Between Stateflow Messages, Events, and Data

Scope Output

Each receiver chart has active state output enabled, with the output port connected to
a scope. On the scope output, you see which states are active for each time step. This
output highlights the difference in behavior between output data, event, and message.

10-5
10 Messages

10-6
View Differences Between Stateflow Messages, Events, and Data

Behavior of Data

In the entry action of chart DataSender, the output data M is assigned a value of 1. M
connects as input to the chart DataReceiver. M holds this assigned value throughout
the simulation. Because there is no input event, the chart DataReceiver executes once
every time step. In chart DataReceiver, initially state A0 is active. At t=3, the chart
takes the transition to A1. On the scope, you see the state change from A0 to A1. In the
next time step, t=4, the transition tests if M equals 1. This condition is true, so the chart
takes the transition to A2. At t=5, M still equals 1. The chart transitions from A2 to A3.

After data is assigned a value, it remains valid. Therefore, each time a transition
evaluates M, you see DataReceiver transition to a new state.

10-7
10 Messages

Behavior of Event

The chart EventSender uses the syntax send(M) to send an event as an entry action in
state A. This function-call event is an input event to wake up the chart EventReceiver.
The chart EventReceiver executes only when the input event M wakes the chart up.
When event M wakes up chart EventReceiver, state A0 is active. The chart checks for a
valid transition from state A0. The transition from A0 is based on absolute-time temporal
logic, and is not valid at t=0. A0 remains as the active state, and the chart goes back to
sleep. The chart EventReceiver does not wake up again, because chart EventSender
only sends event M once. On the scope, you see that EventReceiver never transitions
out of A0.

Because events do not remain valid across time steps, the chart has only one chance to
respond to the event. When EventSender sent the event, EventReceiver was not in
a state to respond to it. The ability for EventReceiver to transition in response to the
event is lost.

10-8
View Differences Between Stateflow Messages, Events, and Data

Behavior of Message

The chart MessageSender uses the syntax send(M) to send one message through the
message output port. The message goes in the message input receiving queue for the
chart, MessageReceiver. The message waits until MessageReceiver evaluates it.
Because there is no input event, the chart MessageReceiver executes once every time
step. In MessageReceiver, initially, state A0 is active. The chart transitions to state
A1 at t=3. In the next time step, t=4, the transition determines if M is present. The
chart removes M from the receiver input queue. Because M is valid, the chart takes the
transition to A2. The chart destroys M at the end of the time step t=4. At t=5, another
message is not present in the queue, so the chart does not transition to A3. A2 remains
the active state.

10-9
10 Messages

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
across time steps. If the number of messages the chart receives overflows the input
queue, then a message overflow error occurs.

More About
How Messages Work in Stateflow Charts on page 10-2
Queuing Behavior of Stateflow Messages on page 10-21
Stateflow Message Syntax in Charts on page 10-11

10-10
Stateflow Message Syntax in Charts

Stateflow Message Syntax in Charts


In this section...
Access the Data in a Message on page 10-11
Send a Message on page 10-11
Guard a Transition or Action with a Message on page 10-12
Receive a Message on page 10-14
Discard a Message on page 10-15
Forward a Message on page 10-16
Determine if a Message Is Valid on page 10-18
Check the Length of the Queue on page 10-19

Access the Data in a Message


Stateflow messages have a data field. You can read or write to the message data of a
valid message with dot notation syntax. For example, for message M, access the data with
this syntax:

M.data

Set the data type in the Message properties dialog box.

Do not access message data for messages that are still in the queue. See Lifetime of a
Stateflow Message on page 10-23.

Send a Message
To send a message, use this syntax:

send(message_name)

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. If the message is local, then the
message goes in the local message queue.

In this example, M is a message with scope Output. On entry to state A, the chart sends a
message from message output port M, with a data value of 3.

10-11
10 Messages

In a single time step, you can send multiple messages through an output port or to a local
queue. If you send a message without assigning a value to the message data, Stateflow
initializes the message data to 0.

Guard a Transition or Action with a Message


The first time the chart evaluates a transition that a message guards or a message on
action, the chart determines if the message is present in the message input or local
queue. If the message is present, the chart removes the message from the queue. This
message is valid until the chart forwards it, until it is discarded, or until the end of the

10-12
Stateflow Message Syntax in Charts

time step. While the message is valid, another transition or action that evaluates the
message does not remove another message from the queue. While the message is valid,
other transitions or actions can access the message data.

In this example, the transition checks the message queue M. If there is a message present
in the queue, the chart removes it from the queue. If the data value of the valid message
is equal to 3, then the chart takes the transition from state A to state B. If there was no
message present, or if the data value is not equal to 3, then the chart does not take the
transition.

Note: The message is removed from the queue whether the transition is taken or not.

In this example, when the chart executes state A, the chart checks the message queue
M. If there is a message present, the chart removes it from the queue. If the message
data value is equal to 3, then the chart executes the if statement action. If there is no
message present, the chart does not execute the if statement.

10-13
10 Messages

Receive a Message
To receive a message, use this syntax:

receive(message_name)

This keyword is equivalent to on M or message guard M on transitions. If a valid message


M exists, receive(M) returns true. If a valid message does not exist, the chart removes
a message from its associated queue, and receive(M) returns true. If receive(M)
removes a message from the queue, the length of the queue drops by one.

In this example, when the chart executes state A, the chart checks the message queue
M. If there is a message present, the chart removes it from the queue. If the message
data value is equal to 3, then the chart executes the if statement action. If there is no
message present, the chart does not execute the if statement.

10-14
Stateflow Message Syntax in Charts

Discard a Message
To discard a message, use this syntax:

discard(message_name)

To discard a message, it must be valid. After you discard a message, you can remove the
next message from the queue within the same time step.

In this example, when the chart executes state A, on entry the chart checks the message
queue M. If there is a message present, the chart removes it from the queue. The chart
then checks if a message was received. If receive(M) returns true, the chart then
checks if the message data value is equal to 3. If the message data value is equal to 3, the
message is discarded.

10-15
10 Messages

Forward a Message
Forward an Input Message

You can forward a message from an input message queue to an output port. A message
line connects the output port to a receiving chart input port in Simulink.

In this example, in state A, Stateflow determines if a message is present at input port


M_in. If a message is present, then 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. If there is another reference to the message queue, the chart
determines whether there is another message available for use in the queue.

10-16
Stateflow Message Syntax in Charts

After a chart forwards a message, if there is another reference to the same message
queue, then the chart looks for another message on the queue.

Forward a Local Message

You can forward messages to and from local message queues. In this example, if a
message is present at input port M_in, then in state A, Stateflow forwards the message to
the local message queue, M_local. After a 0.3 sec delay, on the transition from state
A to B, the chart determines if a message is present on M_local. The chart removes the
message from the M_local message queue and forwards it to the output port M_out.

10-17
10 Messages

Determine if a Message Is Valid


To determine if a message is valid, use this syntax:

isvalid(message_name)

A message is valid if the chart had removed it from the queue, but it has not been
forwarded or discarded. Use isvalid(M) to check if a message is valid in a Simulink
model that contains more than one Stateflow chart.

In this example, the chart first executes state A. When the chart executes state B, it first
checks to see if message M is valid using isvalid(M). If message M is valid, then the

10-18
Stateflow Message Syntax in Charts

chart executes the if statement action. If message M is not valid, the chart does not
execute the if statement.

Check the Length of the Queue


To check the length of a message queue, use this syntax:

length(message_name)

Use length(M) to determine the number of messages in the queue associated with M.

In this example, the chart first executes state A. The queue associated with message
M has been set to a number larger than 75. Once the length of the message queue
associated with M becomes equal to 75, an action within the second if statement is taken.

10-19
10 Messages

Related Examples
Define Messages in a Stateflow Chart on page 10-25
Set Message Properties on page 10-27

10-20
Queuing Behavior of Stateflow Messages

Queuing Behavior of Stateflow Messages


When you send a message, the message goes into the Input or Local message queue.
The queue type determines the order in which messages are removed from the queue. In
the Message properties dialog box, set the queue type for each input and local message
object to:

FIFO (First In, First Out) (default)


LIFO (Last In, First Out)
Priority

If Queue type is Priority, choose:

Ascending The order of the message removed is based on an ascending order of


the message data value.
Descending The order of the message removed is based on a descending order of
the message data value.

Messages of scope Input and Local have a queue capacity. If the number of incoming
messages exceeds the queue capacity, then a message overflow occurs. Set the diagnostic
action by setting the message queue property Queue overflow diagnostic.

Error (default)
Warning
None

Set the queue capacity high enough so that incoming messages do not overflow the
queue. To check the length of the queue, use length.

Note: The maximum queue length is 2^161.

To add messages to the Stateflow Breakpoints and Watch window, select Add to Watch
Window while viewing the message in the Property Inspector. When the simulation
pauses, you can view message queues and message data values. To visualize the
interchange of messages, use a Message Viewer block in your model.

Related Examples
Work with Message Viewer on page 10-30

10-21
10 Messages

Lifetime of a Stateflow Message on page 10-23


View Differences Between Stateflow Messages, Events, and Data on page 10-3
Watch Stateflow Data Values on page 29-35

10-22
Lifetime of a Stateflow Message

Lifetime of a Stateflow Message


A Stateflow message has a finite lifetime. The lifetime begins when you send a message
with the syntax send(message_name). An input or local message queue receives the
message. The message remains in the queue until the first time that a transition or
action evaluates it, or it is evaluated with receive(M). When the message is evaluated
or received, it becomes valid. The message is valid until:

The chart forwards it to another queue.


The end of the current time step.
The message is discarded.

While a message is valid, other transitions and actions can guard conditions with the
message and access the message data. When you forward a message, the message
continues its lifetime in the receiving queue.

At the end of a time step, a chart destroys any remaining valid messages. You can
destroy a message during a time step by using discard. To check if a message is valid,
use isvalid.

If the receiving queue is full, a message overflow occurs. Set the diagnostic action by
setting the message queue property Queue overflow diagnostic.

To view the interchange of messages during simulation, add a Message Viewer block. In
this block, you see when messages for a model are:

Sent
Received
Forwarded
Dropped
Destroyed
Discarded

Related Examples
Work with Message Viewer on page 10-30
Stateflow Message Syntax in Charts on page 10-11

10-23
10 Messages

Limitations for Messages


You cannot use messages in:

Moore charts
Atomic subcharts
Breakpoint condition expressions
Model reference inputs and outputs

More About
Stateflow Message Syntax in Charts on page 10-11
How Messages Work in Stateflow Charts on page 10-2

10-24
Define Messages in a Stateflow Chart

Define Messages in a Stateflow Chart


In this section...
Types of Messages in a Chart on page 10-25
Define Message Inputs and Outputs on page 10-25

Types of Messages in a Chart


From the Stateflow editor, you can define three scopes for a message.

Scope Description
Input from Simulink Message that is received from another Stateflow chart through
Simulink. Each input message has a receiving queue.
Output to Simulink Message that is sent from a Stateflow through an output port in
Simulink to another chart.
Local Message that is local to the Stateflow chart. A local message has
a receiving queue with the same properties as a message input.
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.

To learn about message properties, see .

Define Message Inputs and Outputs


From the Stateflow editor, you can add messages via the Symbols window or through
menus. To open the Symbols window, select View > Symbols. To add messages in the
Symbols window:

1
Click the Create Message icon .
2 In the row for the new message, under TYPE, click the icon and choose:

Input Message
Local Message
Output Message

10-25
10 Messages

3 Edit the name of the message.


4 For input and output messages, click the PORT field and choose a port number.

To add messages through menus, select one of these options:

Scope Menu Option


Input Chart > Add Inputs & Outputs > Message Input from
Simulink
Output Chart > Add Inputs & Outputs > Message Output to Simulink
Local Chart > Add Other Elements > Local Message

Connect message input and output ports in Simulink with a message line.

More About
Set Message Properties on page 10-27
How Messages Work in Stateflow Charts on page 10-2

10-26
Set Message Properties

Set Message Properties


Set and modify the properties of a message in the Property Inspector, or a Message
properties dialog box.

You can set these properties on a message.

Message Input Port Properties Description


Name Name of the message object.
Scope You can set scope to one of these values:

LocalMessage is defined in the


current chart only.
Input Message is defined as an
input port on the chart. You can send a
message from another chart through this
input port.
OutputMessage is defined as an
output port on the chart. You can send
a message from this chart through this
output port.
Port Index of the port associated with an input or
output message queue.
Size Size of the message data.
Complexity Specifies if the message data accepts
complex values. You can choose one of these
settings:

OffDoes not accept complex values.


OnAccepts complex values.
InheritedInherits the complexity
setting from Simulink.
Type Type of message data.

Select a built-in type from the Type


drop-down list.

10-27
10 Messages

Message Input Port Properties Description


In the Messages properties dialog box,
use the Data Type Assistant to specify a
data Mode. Then specify the data type
based on that mode.

Note: Click the Show data type

assistant button to display


the Data Type Assistant.
Add to Watch Window Watch the message in the Stateflow
Breakpoints and Watch window. You can
view message queues and message data
values when simulation is paused.
Queue capacity For messages of scope Input and Local.
Set the length of the queue high enough so
that incoming messages do not overflow the
queue and to prevent message from being
dropped.
Queue overflow diagnostic Set the diagnostic action for a queue
overflow:

Error (default)
Warning
None
Queue type For messages of scope Input and Local.

Choose the type of queue. The order of


messages received is:

FIFO First in, first out.


LIFO Last in, first out.
Priority This queue type enables the
Priority order property parameter.

10-28
Set Message Properties

Message Input Port Properties Description


Priority order If Queue type is Priority order, choose:

Ascending Order of message received


is based on an ascending order of the
message data value.
Descending Order of message
received is based on a descending order
of the message data value.

More About
Rules for Naming Stateflow Objects on page 2-4
Watch Stateflow Data Values on page 29-35
Size Stateflow Data on page 8-44
Type Stateflow Data on page 8-36

10-29
10 Messages

Work with Message Viewer


The Message Viewer window has:

A navigation toolbar, which contains:

The model hierarchy path


Toggle button to select an automatic or manual layout
Toggle button to chose to show or hide inactive lifelines
Buttons for saving and restoring information in the viewer, setting parameters on
the block, and accessing the Message Viewer documentation
A header pane, which contains the lifeline headers.
A message pane, which displays the messages.

To see the interchange of messages between Stateflow charts during simulation, add a
Message Viewer block to the model. You can visualize the movement of entities between
blocks when simulating SimEvents models. The Message Viewer block also displays
function calls and calls from MATLAB Function blocks. For more information on function
calls, see Function Calls in Message Viewer on page 10-39.

The Message Viewer block uses a Message Viewer window that acts like a sequence
diagram showing how blocks interact using messages.

The Message Viewer enables you to view event data related to Stateflow chart execution
and the exchange of messages between Stateflow charts. The Message Viewer shows
where messages are created and sent, forwarded, received, and destroyed at different
times during model execution. You can also view the movement of entities between
SimEvents blocks. All SimEvents blocks that can store entities appear as lifelines on the
Message Viewer. Entities moving between these blocks appear as lines with arrows. The
Message Viewer also enables you to view calls to Simulink Function blocks and Stateflow
MATLAB functions.

This topic uses the Stateflow example sf_msg_traffic_light to show you how to use
the Message Viewer.

You can add one or more Message Viewer blocks to the top level of a model or any
subsystem. If you place a Message Viewer block in a subsystem that does not have
messages, the Message Viewer informs you that no messages are available to display. A
viewer can be inactive if, for example, it is in a subsystem that has been commented out.
In such a case, the Message Viewer displays that it is inactive.

10-30
Work with Message Viewer

Visualize Messages
Consider this subsystem, Traffic Light1:

10-31
10 Messages

Traffic Light1 contains two Stateflow charts.

Controller
Ped Button Sensor

The charts in this subsystems use messages to exchange data. As messages pass through
the system, you can view them in a Message Viewer.

Add a Message Viewer block from the Stateflow library to a subsystem or model whose
messages you want to see. When you open a Message Viewer block and simulate the
model:

1 Observe the contents of the Message Viewer.

10-32
Work with Message Viewer

The header (top) pane of a Message Viewer shows the lifeline headers. In this
example, the lifelines are the two Traffic Light blocks and the GUI. Lifeline headers
show the name of the corresponding blocks in the model that generate or act on
messages. The top of the lifeline is a header, which corresponds to a block in the
model. Gray headers with straight edges correspond to subsystems. Yellow headers
with rounded edges correspond to Stateflow charts. In the header pane, the lifeline
hierarchy corresponds to the model hierarchy. When the model is paused or stopped,
you can expand and close lifelines.

In the message pane, a thick gray lifeline indicates that you can expand the lifeline
to see the children in the lifeline. Clicking a lifeline name opens the corresponding
block in the model. Messages between lifelines display in the message pane. Message
lines are arrows from the sender to the receiver. For more information on navigation
in the message page, see Navigation in Message Viewers on page 10-38.
2 To show the children of a lifeline, click the expander under a parent lifeline .

10-33
10 Messages

3 Hide the children lifelines by clicking the Lifeline Stack

.
4 Make a lifeline the root of focus for the viewer. Hover over the bottom left corner of
the lifeline header and click the arrow. Alternatively, use the navigation toolbar at
the top of a Message Viewer. A Message Viewer displays the current root lifeline
path and shows its child lifelines.

10-34
Work with Message Viewer

Any external sending and receiving events display in the diagram gutter . To
highlight the associated block in the model, click the gutter.

You can use the navigation toolbar to move the current root up and down the lifeline
hierarchy. To move up the current root one level, hit the Esc key.

This graphic also illustrates how the Message Viewer displays masked subsystems.
The Traffic Lamp 1, Ped Lamp 1, Traffic Lamp 2, and PED Lamp 2 are masked
subsystems. The Message Viewer displays masked subsystems as white blocks.

10-35
10 Messages

5 To show the children of a masked subsystem, hover over the bottom left corner of the
masked and subsystem and click the arrow.

The child lifeline displays.

6 Activations that correspond to executions of the lifeline are at the start and end of
each message line.

If a message line is not completely shown, hover over the line. You can also, hover
over a truncated message label to see it in its entirety. In this example, the send
time of the commIn message line is not visible. To see it, hover over the message
line.

If you hover over an activation that represents a function call, the function prototype
is displayed in the tool tip.

If you hover over partially shown activation symbols, the times for any truncated
activations also appear.

10-36
Work with Message Viewer

7 A Message Viewer shows the interactions (hops) that a message or function call
goes through in its lifetime. It also shows message and function call payloads. To
highlight the hops for a message and display its payload, click the corresponding
message line. See the result in the payload inspector to the right. Use Search Up
and Down buttons to move through the hops.

Redisplay of Information in Message Viewer


A Message Viewer block saves the order and states of lifelines between simulation runs.
Similarly, when you close and reopen a Message Viewer, it preserves the last open
lifeline state. To save a particular viewer state with the block, click in the navigation

toolbar. Saving the model saves the state information across sessions. Use to load the
saved settings.

Time in Message Viewers


A Message Viewer shows message events vertically, ordered in time. Multiple events
in Simulink can happen at the same time. Conversely, there can be long periods of
times during simulation with no events. As a consequence, time in the message pane is
nonlinear. Each time grid row, bordered by two blue lines, contains events that occur at
the same simulation time. The time strip gives the times of the events in that grid row.

The time ruler shows linear simulation time. To show messages in that simulation time
range, use the scroll wheel or drag the time slider up and down the time ruler.

10-37
10 Messages

Time Grid
Time Strip

Time Ruler

Time Slider

To navigate to the beginning and end of the simulation, click the Go to first event
and Go to last event buttons.
To zoom the ruler, hold the space bar and use the mouse wheel. This action increases
and decreases the amount of time ruler space the slider occupies.
The time ruler covers the whole simulation time. To see the entire simulation
duration on the time ruler, click the Fit to view button .
To reset the zoom to 100%, hold Ctrl + 0.

Navigation in Message Viewers


To scroll in the header and message panes, use the mouse wheel. In addition,

The header pane has a vertical scroll bar.


The message page has a horizontal scroll bar at the bottom that scrolls both panes.

To pan in the message pane, move the mouse while holding down either the middle
mouse button or space bar. This action moves both panes.

You can scale the view in two ways:

Fit all lifeline headers to window Press the space bar.


Zoom by a fixed increment to a predefined minimum or maximum value Press
Ctrl- or Ctrl+. Alternatively, hold the space bar and use the mouse wheel.

10-38
Work with Message Viewer

Zooming does not scale the navigation toolbar or time ruler.

Function Calls in Message Viewer


The Message Viewer block displays these function calls and replies to them.

Function Call Type Support


Calls to Simulink Function blocks Fully supported
Calls to Stateflow graphical or Stateflow Scoped Select the Export chart
MATLAB functions level functions chart option. Use
the chartName.functionName dot
notation.
Global Select the Treat exported
functions as globally visible
chart option. You do not need the dot
notation.

The Message Viewer block does not display these function calls:

Function calls connected to function-call subsystems.

For an example of functions calls in Message Viewer, see slexPrinterExample.


The Message Viewer displays function calls with solid lines terminated with solid
arrows and a label with the format function_name(argument_list). Replies to
function calls display as dashed lines with open arrows and a label with the format
[argument_list]=function_name.

See Also
Message Viewer | Message Viewer | Message Viewer

10-39
10 Messages

More About
How Messages Work in Stateflow Charts on page 10-2

10-40
11

Use Actions in Charts

State Action Types on page 11-2


Transition Action Types on page 11-8
Execution of Actions in States and Transitions on page 11-12
Combine State Actions to Eliminate Redundant Code on page 11-16
Supported Operations on Chart Data on page 11-19
Supported Symbols in Actions on page 11-27
Call C Functions in C Charts on page 11-31
Access Built-In MATLAB Functions and Workspace Data on page 11-38
Use Arrays in Actions on page 11-50
Broadcast Events to Synchronize States on page 11-52
Control Chart Execution Using Temporal Logic on page 11-56
Detect Changes in Data Values on page 11-74
Check State Activity on page 11-86
Control Function-Call Subsystems Using Bind Actions on page 11-95
Simplify Stateflow Chart Using the duration Operator on page 11-113
11 Use Actions in Charts

State Action Types


States can have different action types, which include entry, during, exit, bind, and,
on actions. The actions for states are assigned to an action type using label notation with
this general format:

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

For example, different state action types appear in the following chart.

After you enter the name in the state label, enter a carriage return and specify the
actions for the state. The order you use to enter action types in the label does not matter.

11-2
State Action Types

If you do not specify the action type explicitly for a statement, the chart treats that
statement as an entry action.

This table summarizes the different state action types.

State Action Abbreviation Description


entry en Executes when the state becomes
active
exit ex Executes when the state is active and
a transition out of the state occurs
during du Executes when the state is active and
a specific event occurs
bind none Binds an event or data object so that
only that state and its children can
broadcast the event or change the
data value
on event_name none Executes when the state is active and
it receives a broadcast of event_name
on message_name none Executes when a message
message_name is available.
on after(n, event_name) none Executes when the state is active
and after it receives n broadcasts of
event_name
on before(n, event_name) none Executes when the state is active
and before it receives n broadcasts of
event_name
on at(n, event_name) none Executes when the state is active and
it receives exactly n broadcasts of
event_name
on every(n, event_name) none Executes when the state is active and
upon receipt of every n broadcasts of
event_name

For a full description of entry, exit, during, bind, and on actions, see the sections
that follow. For more information about the after, before, at, and every temporal
logic operators, see Control Chart Execution Using Temporal Logic on page 11-56.

11-3
11 Use Actions in Charts

In the preceding table, the temporal logic operators use the syntax of event-based
temporal logic. For absolute-time temporal logic, the operators use a different syntax. For
details, see Operators for Absolute-Time Temporal Logic on page 11-63.

Entry Actions
Entry actions are preceded by the prefix entry or en for short, followed by a required
colon (:), followed by one or more actions. Separate multiple actions with a carriage
return, semicolon (;), or a comma (,). 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 entry actions only.

Entry actions for a state execute when the state is entered (becomes active). In the
preceding example in State Action Types on page 11-2, the entry action id = x+y
executes when the state A is entered by the default transition.

For a detailed description of the semantics of entering a state, see Steps for Entering a
State on page 3-74 and State Execution Example on page 3-76.

Exit Actions
Exit actions are preceded by the prefix exit or ex for short, followed by a required colon
(:), followed by one or more actions. Separate multiple actions with a carriage return,
semicolon (;), or a comma (,).

Exit actions for a state execute when the state is active and a transition out of the state
occurs.

For a detailed description of the semantics of exiting a state, see Steps for Exiting an
Active State on page 3-75 and State Execution Example on page 3-76.

During Actions
During actions are preceded by the prefix during or du for short, followed by a required
colon (:), followed by one or more actions. Separate multiple actions with a carriage
return, semicolon (;), or a comma (,).

During actions for a state execute when the state is active and an event occurs and no
valid transition to another state is available.

11-4
State Action Types

For a detailed description of the semantics of executing an active state, see Steps for
Executing an Active State on page 3-75 and State Execution Example on page 3-76.

Bind Actions
Bind actions are preceded by the prefix bind, followed by a required colon (:), followed
by one or more events or data. Separate multiple data/events with a carriage return,
semicolon (;), or a comma (,).

Bind actions bind the specified data and events to a state. Data bound to a state can be
changed by the actions of that state or its children. Other states and their children are
free to read the bound data, but they cannot change it. Events bound to a state can be
broadcast only by that state or its children. Other states and their children are free to
listen for the bound event, but they cannot send it.

Bind actions apply to a chart whether the binding state is active or not. In the preceding
example in State Action Types on page 11-2, 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. The following example shows a few of these error
conditions:

11-5
11 Use Actions in Charts

State Action Reason for Parse Error


bind: id in state B Only one state can change the data id,
which binds to state A
entry: time_out in state C Only one state can broadcast the event
time_out, which binds to state A

Binding a function-call event to a state also binds the function-call subsystem that it
calls. In this case, 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 Using Bind Actions on page 11-95.

On Actions
On actions are preceded by the prefix on, followed by a unique event, event_name, or
message, message_name, followed by one or more actions. Separate multiple actions
with a carriage return, semicolon (;), or a comma (,). You can specify actions for more
than one event or message by adding additional on lines for different events or messages.

11-6
State Action Types

For example, if you want different events to trigger different actions, enter multiple
on event_name action statements in the state's label, each specifying the action for a
particular event or set of events:
on ev1: action1();
on ev2: action2();

On actions execute when the state is active and the event event_name or message
message_name is received by the state. This action coincides with execution of during
actions for the state.

For a detailed description of the semantics of executing an active state, see Steps for
Executing an Active State on page 3-75.

Related Examples
Combine State Actions to Eliminate Redundant Code on page 11-16

11-7
11 Use Actions in Charts

Transition Action Types


In State Action Types on page 11-2, you see how you can attach actions to the label
for a state. You can also attach actions to a transition on its label. Transitions can have
different action types, which include event or message triggers, conditions, condition
actions, and transition actions. The action types follow the label notation with this
general format:

event_or_message trigger[condition]{condition_action}/{transition_action}

The following example shows typical transition label syntax:

Transition Event Trigger Condition Condition Action Transition Action


State A to state event1 temp > 50 func1() None
C
State A to state event2 None None data1 = 5
B

11-8
Transition Action Types

Event or Message Triggers


In transition label syntax, event or message triggers appear first as the name of an
event or message. They have no distinguishing special character to separate them from
other actions in a transition label. In the example in Transition Action Types on page
11-8, both transitions from state A have event triggers. The transition from state A
to state B has the event trigger event2 and the transition from state A to state C has the
event trigger event1.

11-9
11 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 11-8, 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 on page 11-86)

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 Using Temporal Logic on
page 11-56)
The condition expression can call a graphical function, truth table function, or
MATLAB function that returns a numeric value.

For example, [test_function(x, y) < 0] is a valid condition expression.

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.

11-10
Transition Action Types

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 11-8,
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.

Note: If a condition is guarded by an event, it is checked only if the event trigger is


active. If a condition is guarded by a message, it is checked only if the message is present.

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
11-8, 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 Action Language Auto Correction on page
12-6.

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.

11-11
11 Use Actions in Charts

Execution of Actions in States and Transitions


The following chart shows how different constructs interact during simulation:

When you simulate the model, you get the following results:

11-12
Execution of Actions in States and Transitions

The following actions occur in the TransAction state:

11-13
11 Use Actions in Charts

Time What Happens in the TransAction State


0.0 State TA becomes active.
In TA, the entry action executes by setting the value of outVal to 0.
0.1 The transition from TA to junction J1 occurs, because the path is unconditional.
Evaluation of the condition between J1 and J2 occurs, which returns true.
The transition action does not execute, because the full transition path from J1 to TB is
not complete.
Evaluation of the condition between J2 and TB occurs, which returns false. Therefore,
execution returns to J1.
The transition from J1 to J3 occurs, because the path is unconditional.
Evaluation of the condition between J3 and TB occurs, which returns false. Therefore,
execution returns to TA.
In TA, the during action executes by decrementing the value of outVal by 1.
0.2 The execution pattern from t = 0.1 repeats for each time step.
1.0
1.1 The transition from TA to junction J1 occurs, because the path is unconditional.
Evaluation of the condition between J1 and J2 occurs, which returns true.
The transition action does not execute, because the full transition path from J1 to TB is
not complete.
Evaluation of the condition between J2 and TB occurs, which returns false. Therefore,
execution returns to J1.
The transition from J1 to J3 occurs, because the path is unconditional.
Evaluation of the condition between J3 and TB occurs, which returns true.
State TB becomes active.
Because the transition from J3 to TB is now complete, the transition action executes by
setting the value of outVal to 0.

The following actions occur in the CondAction state:

Time What Happens in the CondAction State


0.0 State CA becomes active.
In CA, the entry action executes by setting the value of outVal_2 to 0.

11-14
Execution of Actions in States and Transitions

Time What Happens in the CondAction State


0.1 The transition from CA to junction J1 occurs, because the path is unconditional.
Evaluation of the condition between J1 and J2 occurs, which returns true.
The condition action executes by decrementing the value of outVal_2 by 2.
Evaluation of the condition between J2 and CB occurs, which returns false. Therefore,
execution returns to J1.
The transition from J1 to J3 occurs, because the path is unconditional.
Evaluation of the condition between J3 and CB occurs, which returns false. Therefore,
execution returns to CA.
In CA, the during action executes by decrementing the value of outVal_2 by 1.
0.2 The execution pattern from t = 0.1 repeats for each time step.
0.3
0.4 The transition from CA to junction J1 occurs, because the path is unconditional.
Evaluation of the condition between J1 and J2 occurs, which returns true.
The condition action executes by decrementing the value of outVal_2 by 2.
Evaluation of the condition between J2 and CB occurs, which returns false. Therefore,
execution returns to J1.
The transition from J1 to J3 occurs, because the path is unconditional.
Evaluation of the condition between J3 and CB occurs, which returns true.
The condition action executes by setting the value of outVal_2 to 0.
State CB becomes active.

More About
State Action Types on page 11-2
Transition Action Types on page 11-8

11-15
11 Use Actions in Charts

Combine State Actions to Eliminate Redundant Code


In this section...
State Actions You Can Combine on page 11-16
Why Combine State Actions on page 11-16
How to Combine State Actions on page 11-16
Order of Execution of Combined Actions on page 11-17
Rules for Combining State Actions on page 11-18

State Actions You Can Combine


You can combine entry, during, and exit actions that execute the same tasks in a
state.

Why Combine State Actions


By combining state actions that execute the same tasks, you eliminate redundant code.
For example:

Separate Actions Equivalent Combined Actions


entry: entry: y = 0;
y = 0; entry, during: y=y+1;
y=y+1;
during: y=y+1;
en: en, du, ex: fcn1();
fcn1(); en: fcn2();
fcn2();
du: fcn1();
ex: fcn1();

Combining state actions this way produces the same chart execution behavior
(semantics) and generates the same code as the equivalent separate actions.

How to Combine State Actions


Combine a set of entry, during, and/or exit actions that perform the same task as a
comma-separated list in a state. Here is the syntax:

11-16
Combine State Actions to Eliminate Redundant Code

entry, during, exit: task1; task2;...taskN;

You can also use the equivalent abbreviations:


en, du, ex: task1; task2;...taskN;

Valid Combinations

You can use any combination of the three actions. For example, the following
combinations are valid:

en, du:
en, ex:
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.

Order of Execution of Combined Actions


States execute combined actions in the same order as they execute separate actions:

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:

11-17
11 Use Actions in Charts

This state... Executes actions in this order...


1 en: y = 0;
2 en: y=y+1;
3 du: y=y+1;

1 en: y=y+1;
2 en: y = 0;
3 du: y=y+1;

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;

Rules for Combining State Actions


Do not combine multiple actions of the same type.
Do not create data, events, or messages that have the same name as the action
keywords: entry, en, during, du, exit, ex.

More About
State Action Types on page 11-2

11-18
Supported Operations on Chart Data

Supported Operations on Chart Data


In this section...
Binary and Bitwise Operations on page 11-19
Unary Operations on page 11-22
Unary Actions on page 11-22
Assignment Operations on page 11-22
Pointer and Address Operations on page 11-23
Type Cast Operations on page 11-24
Replace Operators with Application Implementations on page 11-25

Binary and Bitwise Operations


The table below summarizes the interpretation of all binary operators in C charts. These
operators work with the following order of precedence (0 = highest, 10 = lowest). Logical
binary operators with the same precedence evaluate from left to right. The order of
evaluation for other operators is unspecified. For example, the order in which foo() and
bar() are evaluated is unspecified in the assignment below.
A = foo() > bar();

For more predictable results, it is good coding practice to split expressions that depend on
the order of evaluation into multiple statements.

You can specify that the binary operators &, ^, |, &&, and || are interpreted as bitwise
operators in Stateflow generated C code for a chart or for all the charts in a model. See
these individual operators in the table below for specific binary or bitwise operator
interpretations.

Example Precedence Description


a ^ b 0 Operand a raised to power b

Enabled when you clear Enable C-bit


operations in the Chart properties dialog
box. See Specify Chart Properties on page
22-3.
a * b 1 Multiplication

11-19
11 Use Actions in Charts

Example Precedence Description


a / b 1 Division
a %% b 1 Remainder
a + b 2 Addition
a - b 2 Subtraction
a >> b 3 Shift operand a right by b bits. Noninteger
operands for this operator are first cast to
integers before the bits are shifted.
a << b 3 Shift operand a left by b bits. Noninteger
operands for this operator are first cast to
integers before the bits are shifted.
a > b 4 Comparison of the first operand greater than the
second operand
a < b 4 Comparison of the first operand less than the
second operand
a >= b 4 Comparison of the first operand greater than or
equal to the second operand
a <= b 4 Comparison of the first operand less than or
equal to the second operand
a == b 5 Comparison of equality of two operands
a ~= b 5 Comparison of inequality of two operands
a != b 5 Comparison of inequality of two operands
a <> b 5 Comparison of inequality of two operands

11-20
Supported Operations on Chart Data

Example Precedence Description


a & b 6 One of the following:

Bitwise AND of two operands

Enabled when you select Enable C-bit


operations in the Chart properties dialog
box (default). See Specify Chart Properties
on page 22-3.
Logical AND of two operands

Enabled when you clear Enable C-bit


operations in the Chart properties dialog
box.
a ^ b 7 Bitwise XOR of two operands

Enabled when you select Enable C-bit


operations in the Chart properties dialog box
(default). See Specify Chart Properties on page
22-3.
a | b 8 One of the following:

Bitwise OR of two operands

Enabled when you select Enable C-bit


operations in the Chart properties dialog
box (default). See Specify Chart Properties
on page 22-3.
Logical OR of two operands

Enabled when you clear Enable C-bit


operations in the Chart properties dialog
box.
a && b 9 Logical AND of two operands
a || b 10 Logical OR of two operands

11-21
11 Use Actions in Charts

Unary Operations
The following unary operators are supported in C charts. Unary operators have higher
precedence than the binary operators, except for the power operator a ^ b. The power
operator has the highest level of precedence. The operators are evaluated right to left
(right associative).

Example Description
~a Logical NOT of a

Complement of a (if bitops is enabled)


!a Logical NOT of a
-a Negative of a

Unary Actions
The following unary actions are supported in C charts.

Example Description
a++ Increment a
a-- Decrement a

Assignment Operations
The following assignment operations are supported in C charts.

Example Description
a = expression Simple assignment
a := expression Used primarily with fixed-point numbers. See Assignment
(=, :=) Operations on page 20-30 for a detailed description.
a += expression Equivalent to a = a + expression
a -= expression Equivalent to a = a - expression
a *= expression Equivalent to a = a * expression
a /= expression Equivalent to a = a / expression

11-22
Supported Operations on Chart Data

The following assignment operations are supported in C charts when Enable C-bit
operations is selected in the properties dialog box for the chart. See Specify Chart
Properties on page 22-3.

Example Description
a |= expression Equivalent to a = a | expression (bit operation). See
operation a | b in Binary and Bitwise Operations on page
11-19.
a &= expression Equivalent to a = a & expression (bit operation). See
operation a & b in Binary and Bitwise Operations on page
11-19.
a ^= expression Equivalent to a = a ^ expre