Print Preview C:\TEMP\Apdf_2541_3068\home\AppData\Local\PTC\Arbortext\Editor\.aptcache\ae384hih/tf384yff Simulink User's Guide

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 2839

DownloadPrint Preview - C:\TEMP\Apdf_2541_3068\home\AppData\Local\PTC\Arbortext\Editor\.aptcache\ae384hih/tf384yff Simulink User's Guide
Open PDF In BrowserView PDF
Simulink®
User’s Guide

R2012b

How to Contact MathWorks

Web
Newsgroup
www.mathworks.com/contact_TS.html Technical Support
www.mathworks.com

comp.soft-sys.matlab

suggest@mathworks.com
bugs@mathworks.com
doc@mathworks.com
service@mathworks.com
info@mathworks.com

Product enhancement suggestions
Bug reports
Documentation error reports
Order status, license renewals, passcodes
Sales, pricing, and general information

508-647-7000 (Phone)
508-647-7001 (Fax)
The MathWorks, Inc.
3 Apple Hill Drive
Natick, MA 01760-2098
For contact information about worldwide offices, see the MathWorks Web site.
Simulink® User’s Guide
© COPYRIGHT 1990–2012 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

November 1990
December 1996
January 1999
November 2000
July 2002
April 2003
April 2004
June 2004
October 2004
March 2005
September 2005
March 2006
March 2006
September 2006
March 2007
September 2007
March 2008
October 2008
March 2009
September 2009
March 2010
September 2010
April 2011
September 2011
March 2012
September 2012

First printing
Second printing
Third printing
Fourth printing
Fifth printing
Online only
Online only
Sixth printing
Seventh printing
Online only
Eighth printing
Online only
Ninth printing
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only

New for Simulink 1
Revised for Simulink 2
Revised for Simulink 3 (Release 11)
Revised for Simulink 4 (Release 12)
Revised for Simulink 5 (Release 13)
Revised for Simulink 5.1 (Release 13SP1)
Revised for Simulink 5.1.1 (Release 13SP1+)
Revised for Simulink 5.0 (Release 14)
Revised for Simulink 6.1 (Release 14SP1)
Revised for Simulink 6.2 (Release 14SP2)
Revised for Simulink 6.3 (Release 14SP3)
Revised for Simulink 6.4 (Release 2006a)
Revised for Simulink 6.4 (Release 2006a)
Revised for Simulink 6.5 (Release 2006b)
Revised for Simulink 6.6 (Release 2007a)
Revised for Simulink 7.0 (Release 2007b)
Revised for Simulink 7.1 (Release 2008a)
Revised for Simulink 7.2 (Release 2008b)
Revised for Simulink 7.3 (Release 2009a)
Revised for Simulink 7.4 (Release 2009b)
Revised for Simulink 7.5 (Release 2010a)
Revised for Simulink 7.6 (Release 2010b)
Revised for Simulink 7.7 (Release 2011a)
Revised for Simulink 7.8 (Release 2011b)
Revised for Simulink 7.9 (Release 2012a)
Revised for Simulink 8.0 (Release 2012b)

Contents
Introduction to Simulink
Simulink Basics

1
Start the Simulink Software . . . . . . . . . . . . . . . . . . . . . . . .
Open the MATLAB Software . . . . . . . . . . . . . . . . . . . . . . . .
Open the Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . .
Open the Simulink Editor . . . . . . . . . . . . . . . . . . . . . . . . . .

1-2
1-2
1-2
1-3

Open a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Happens When You Open a Model . . . . . . . . . . . . . . .
Open an Existing Model . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Models with Different Character Encodings . . . . . . . . . . . .
Avoid Initial Model Open Delay . . . . . . . . . . . . . . . . . . . . . .

1-4
1-4
1-4
1-5
1-5

Load a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-7

Save a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Tell If a Model Needs Saving . . . . . . . . . . . . . . . . . .
Save a Model for the First Time . . . . . . . . . . . . . . . . . . . . . .
Model Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save a Previously Saved Model . . . . . . . . . . . . . . . . . . . . . .
What Happens When You Save a Model? . . . . . . . . . . . . . .
Saving Models in the SLX File Format . . . . . . . . . . . . . . . .
Saving Models with Different Character Encodings . . . . . .
Export a Model to a Previous Simulink Version . . . . . . . . .
Save from One Earlier Simulink Version to Another . . . . .

1-8
1-8
1-9
1-9
1-9
1-9
1-10
1-13
1-14
1-15

Simulink Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Editor Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Undoing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Window Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-17
1-17
1-21
1-21

.....................

1-23

Zoom and Pan Block Diagrams

v

Update a Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . .
Updating the Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Updates the Diagram . . . . . . . . . . . . . . . . . . . .
Update Diagram at Edit Time . . . . . . . . . . . . . . . . . . . . . . .

1-25
1-25
1-25
1-25

Copy Models to Third-Party Applications . . . . . . . . . . . .

1-27

Print a Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print Interactively or Programmatically . . . . . . . . . . . . . . .
Systems to Print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Title Block Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Paper Size and Orientation . . . . . . . . . . . . . . . . . . . . . . . . .
Diagram Positioning and Sizing . . . . . . . . . . . . . . . . . . . . . .
Tiled Printing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print Sample Time Legend . . . . . . . . . . . . . . . . . . . . . . . . . .

1-28
1-28
1-28
1-30
1-31
1-31
1-32
1-35

Generate a Model Report . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Report Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Printing Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-36
1-37
1-38

End a Simulink Session . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1-40

Keyboard and Mouse Shortcuts for Simulink . . . . . . . . .
Model Viewing Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Editing Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Line Editing Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Label Editing Shortcuts . . . . . . . . . . . . . . . . . . . . . .
Annotation Editing Shortcuts . . . . . . . . . . . . . . . . . . . . . . .

1-41
1-41
1-41
1-43
1-43
1-43

Simulink Demos Are Now Called Examples . . . . . . . . . .

1-44

Simulation Stepping

2
Simulation Stepping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Simulation Stepping . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Stepper Graphical Cues . . . . . . . . . . . . . . . . . .
Current Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

vi

Contents

2-2
2-2
2-5
2-9

Step Through a Simulation . . . . . . . . . . . . . . . . . . . . . . . . .
Configure Simulation Stepping . . . . . . . . . . . . . . . . . . . . . .
Forward and Backward Stepping . . . . . . . . . . . . . . . . . . . . .
Conditional Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . .

2-12
2-12
2-12
2-18

How Simulink Works

3
How Simulink Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-2

Modeling Dynamic Systems . . . . . . . . . . . . . . . . . . . . . . . . .
Block Diagram Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Custom Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Systems and Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-3
3-3
3-4
3-5
3-5
3-9
3-9
3-9
3-10
3-11
3-16
3-16
3-17

Simulating Dynamic Systems . . . . . . . . . . . . . . . . . . . . . . .
Model Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Link Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Loop Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Zero-Crossing Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Algebraic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

3-18
3-18
3-19
3-19
3-21
3-23
3-39

vii

Modeling Dynamic Systems
Creating a Model

4

viii

Contents

Create an Empty Model . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Model Template . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-2
4-2

Populate a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Copy Blocks to Your Model . . . . . . . . . . . . . . . . . . . . . . . . . .
Browse Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Copy Blocks to Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-4
4-4
4-4
4-5
4-5

Select Modeling Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select Multiple Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-6
4-6
4-6

Specify Block Diagram Colors . . . . . . . . . . . . . . . . . . . . . .
Set Block Diagram Colors Interactively . . . . . . . . . . . . . . .
Platform Differences for Custom Colors . . . . . . . . . . . . . . .
Choose a Custom Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Define a Custom Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify Colors Programmatically . . . . . . . . . . . . . . . . . . . . .

4-8
4-8
4-9
4-9
4-10
4-11

Connect Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Automatically Connect Blocks . . . . . . . . . . . . . . . . . . . . . . .
Manually Connect Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . .
Disconnect Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-12
4-12
4-15
4-21

Align, Distribute, and Resize Groups of Blocks . . . . . . .

4-22

Annotate Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add and Edit Annotations . . . . . . . . . . . . . . . . . . . . . . . . . .
Summary of Annotations Properties Dialog Box . . . . . . . . .
Annotation Callback Functions . . . . . . . . . . . . . . . . . . . . . .
Associate Click Functions with Annotations . . . . . . . . . . . .
Annotations API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
TeX Formatting Commands in Annotations . . . . . . . . . . . .
Create Annotations Programmatically . . . . . . . . . . . . . . . .

4-23
4-23
4-28
4-29
4-30
4-32
4-32
4-34

Create a Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Subsystem Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Two Ways to Create a Subsystem . . . . . . . . . . . . . . . . . . . .
Create a Subsystem by Adding the Subsystem Block . . . . .
Create a Subsystem by Grouping Existing Blocks . . . . . . .
Subsystem Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Navigate Model Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . .
Label Subsystem Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Control Access to Subsystems . . . . . . . . . . . . . . . . . . . . . . .
Interconvert Subsystems and Block Diagrams . . . . . . . . . .
Empty Subsystems and Block Diagrams . . . . . . . . . . . . . . .

4-36
4-36
4-36
4-37
4-37
4-39
4-39
4-42
4-42
4-43
4-43

Control Flow Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Equivalent C Language Statements . . . . . . . . . . . . . . . . . .
Conditional Control Flow Logic . . . . . . . . . . . . . . . . . . . . . .
While and For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-44
4-44
4-44
4-47

Callback Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What You Can Do with Callback Functions . . . . . . . . . . . .
Callback Tracing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Model Callback Functions . . . . . . . . . . . . . . . . . . . .
Create Block Callback Functions . . . . . . . . . . . . . . . . . . . . .
Port Callback Parameters . . . . . . . . . . . . . . . . . . . . . . . . . .
Callback Function Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-54
4-54
4-55
4-55
4-58
4-63
4-64

Model Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Workspace Differences from MATLAB
Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Troubleshooting Memory Issues . . . . . . . . . . . . . . . . . . . . . .
Simulink.ModelWorkspace Data Object Class . . . . . . . . . .
Change Model Workspace Data . . . . . . . . . . . . . . . . . . . . . .
Specify Data Sources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-67

Symbol Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Symbol Resolution Process . . . . . . . . . . . . . . . . . . . . . . . . . .
Numeric Values with Symbols . . . . . . . . . . . . . . . . . . . . . . .
Other Values with Symbols . . . . . . . . . . . . . . . . . . . . . . . . .
Limit Signal Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Explicit and Implicit Symbol Resolution . . . . . . . . . . . . . . .

4-76
4-76
4-76
4-78
4-78
4-79
4-80

.........................

4-81

Consult the Model Advisor

4-67
4-68
4-68
4-69
4-72

ix

About the Model Advisor . . . . . . . . . . . . . . . . . . . . . . . . . . .
Start the Model Advisor . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview of the Model Advisor Window . . . . . . . . . . . . . . .
Overview of the Model Advisor Dashboard . . . . . . . . . . . . .
Run Model Advisor Checks . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Checks Using Model Advisor Dashboard . . . . . . . . . . .
Highlight Model Advisor Analysis Results . . . . . . . . . . . . .
Fix a Warning or Failure . . . . . . . . . . . . . . . . . . . . . . . . . . .
Revert Changes Using Restore Points . . . . . . . . . . . . . . . . .
View and Save Model Advisor Reports . . . . . . . . . . . . . . . .
Run the Model Advisor Programmatically . . . . . . . . . . . . .
Check Support for Libraries . . . . . . . . . . . . . . . . . . . . . . . . .
Model Advisor Limitations . . . . . . . . . . . . . . . . . . . . . . . . . .
Consult the Upgrade Advisor . . . . . . . . . . . . . . . . . . . . . . . .

4-81
4-82
4-85
4-87
4-88
4-91
4-93
4-95
4-99
4-101
4-104
4-104
4-105
4-105

Manage Model Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Simulink Helps You Manage Model Versions . . . . . . .
Model File Change Notification . . . . . . . . . . . . . . . . . . . . . .
Specify the Current User . . . . . . . . . . . . . . . . . . . . . . . . . . .
Manage Model Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .
Log Comments History . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Version Information Properties . . . . . . . . . . . . . . . . . . . . . .

4-107
4-107
4-108
4-110
4-110
4-117
4-119

Model Discretizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is the Model Discretizer? . . . . . . . . . . . . . . . . . . . . . .
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Discretize a Model from the Model Discretizer GUI . . . . . .
View the Discretized Model . . . . . . . . . . . . . . . . . . . . . . . . .
Discretize Blocks from the Simulink Model . . . . . . . . . . . .
Discretize a Model from the MATLAB Command
Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4-122
4-122
4-122
4-122
4-132
4-135
4-146

Working with Sample Times

5

x

Contents

What Is Sample Time? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-2

Specify Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Designate Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-3
5-3

Specify Block-Based Sample Times Interactively . . . . . . . .
Specify Port-Based Sample Times Interactively . . . . . . . . .
Specify Block-Based Sample Times Programmatically . . .
Specify Port-Based Sample Times Programmatically . . . . .
Access Sample Time Information Programmatically . . . . .
Specify Sample Times for a Custom Block . . . . . . . . . . . . .
Determining Sample Time Units . . . . . . . . . . . . . . . . . . . . .
Change the Sample Time After Simulation Start Time . . .

5-6
5-6
5-7
5-8
5-8
5-8
5-8
5-8

View Sample Time Information . . . . . . . . . . . . . . . . . . . . .
View Sample Time Display . . . . . . . . . . . . . . . . . . . . . . . . . .
Sample Time Legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-9
5-9
5-10

Print Sample Time Information . . . . . . . . . . . . . . . . . . . . .

5-13

Types of Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Discrete Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Continuous Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fixed in Minor Step . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inherited Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Constant Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variable Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Triggered Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Asynchronous Sample Time . . . . . . . . . . . . . . . . . . . . . . . . .

5-14
5-14
5-15
5-15
5-15
5-16
5-17
5-18
5-18

Block Compiled Sample Time

......................

5-20

Sample Times in Subsystems

.......................

5-21

Sample Times in Systems . . . . . . . . . . . . . . . . . . . . . . . . . . .
Purely Discrete Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Hybrid Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-22
5-22
5-25

Resolve Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . .

5-28

How Propagation Affects Inherited Sample Times . . . .
Process for Sample Time Propagation . . . . . . . . . . . . . . . . .
Simulink Rules for Assigning Sample Times . . . . . . . . . . .

5-29
5-29
5-29

Monitor Backpropagation in Sample Times . . . . . . . . . .

5-31

xi

Referencing a Model

6

xii

Contents

Overview of Model Referencing . . . . . . . . . . . . . . . . . . . . .
About Model Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . .
Referenced Model Advantages . . . . . . . . . . . . . . . . . . . . . . .
Masking Model Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Models That Use Model Referencing . . . . . . . . . . . . . . . . . .
Model Referencing Resources . . . . . . . . . . . . . . . . . . . . . . . .

6-2
6-2
6-5
6-6
6-7
6-7

Create a Model Reference . . . . . . . . . . . . . . . . . . . . . . . . . .

6-8

Convert a Subsystem to a Referenced Model . . . . . . . . .
Conversion Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select Subsystems to Convert . . . . . . . . . . . . . . . . . . . . . . .
Prepare the Model for Conversion . . . . . . . . . . . . . . . . . . . .
Run a Conversion Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Connect the Model Block and Perform Other
Post-Conversion Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . .
Convert a Masked Subsystem . . . . . . . . . . . . . . . . . . . . . . .

6-12
6-12
6-12
6-13
6-16

Referenced Model Simulation Modes . . . . . . . . . . . . . . . .
Simulation Modes for Referenced Models . . . . . . . . . . . . . .
Specify the Simulation Mode . . . . . . . . . . . . . . . . . . . . . . . .
Mixing Simulation Modes . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Normal Mode for Multiple Instances of Referenced
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accelerating a Freestanding or Top Model . . . . . . . . . . . . .

6-21
6-21
6-23
6-23

View a Model Reference Hierarchy . . . . . . . . . . . . . . . . . .
Display Version Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-35
6-35

Model Reference Simulation Targets . . . . . . . . . . . . . . . .
Simulation Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Build Simulation Targets . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Target Output File Control . . . . . . . . . . . . . . . .
Parallel Building for Large Model Reference Hierarchies . .

6-37
6-37
6-38
6-39
6-42

Simulink Model Referencing Requirements . . . . . . . . . .
About Model Referencing Requirements . . . . . . . . . . . . . . .

6-45
6-45

6-18
6-19

6-25
6-33

Name Length Requirement . . . . . . . . . . . . . . . . . . . . . . . . .
Configuration Parameter Requirements . . . . . . . . . . . . . . .
Model Structure Requirements . . . . . . . . . . . . . . . . . . . . . .

6-45
6-45
6-50

Parameterize Model References . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Global Nontunable Parameters . . . . . . . . . . . . . . . . . . . . . .
Global Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . .
Using Model Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-52
6-52
6-53
6-53
6-53

Conditional Referenced Models . . . . . . . . . . . . . . . . . . . . .
Kinds of Conditional Referenced Models . . . . . . . . . . . . . . .
Working with Conditional Referenced Models . . . . . . . . . .
Create Conditional Models . . . . . . . . . . . . . . . . . . . . . . . . . .
Reference Conditional Models . . . . . . . . . . . . . . . . . . . . . . .
Simulate Conditional Models . . . . . . . . . . . . . . . . . . . . . . . .
Generate Code for Conditional Models . . . . . . . . . . . . . . . .
Requirements for Conditional Models . . . . . . . . . . . . . . . . .

6-59
6-59
6-60
6-61
6-63
6-64
6-64
6-65

Protected Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-67

Use Protected Model in Simulation . . . . . . . . . . . . . . . . . .

6-68

Inherit Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Sample-Time Inheritance Works for Model Blocks . .
Conditions for Inheriting Sample Times . . . . . . . . . . . . . . .
Determining Sample Time of a Referenced Model . . . . . . .
Blocks That Depend on Absolute Time . . . . . . . . . . . . . . . .
Blocks Whose Outputs Depend on Inherited Sample
Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-70
6-70
6-70
6-71
6-71

Refresh Model Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

6-74

S-Functions with Model Referencing . . . . . . . . . . . . . . . .
S-Function Support for Model Referencing . . . . . . . . . . . . .
Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
S-Functions with Accelerator Mode Referenced Models . . .
Using C S-Functions in Normal Mode Referenced
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Protected Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulink Coder Considerations . . . . . . . . . . . . . . . . . . . . . .

6-75
6-75
6-75
6-76

6-73

6-77
6-77
6-77

xiii

Buses in Referenced Models . . . . . . . . . . . . . . . . . . . . . . . .

6-78

Signal Logging in Referenced Models . . . . . . . . . . . . . . . .

6-79

Model Referencing Limitations . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Limitations on All Model Referencing . . . . . . . . . . . . . . . . .
Limitations on Normal Mode Referenced Models . . . . . . . .
Limitations on Accelerator Mode Referenced Models . . . . .
Limitations on PIL Mode Referenced Models . . . . . . . . . . .

6-80
6-80
6-80
6-83
6-84
6-87

Creating Conditional Subsystems

7

xiv

Contents

About Conditional Subsystems . . . . . . . . . . . . . . . . . . . . . .

7-2

Enabled Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Enabled Subsystems? . . . . . . . . . . . . . . . . . . . . .
Creating an Enabled Subsystem . . . . . . . . . . . . . . . . . . . . .
Blocks that an Enabled Subsystem Can Contain . . . . . . . .
Using Blocks with Constant Sample Times in Enabled
Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7-4
7-4
7-5
7-11

Triggered Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Triggered Subsystems? . . . . . . . . . . . . . . . . . . . .
Using Model Referencing Instead of a Triggered
Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating a Triggered Subsystem . . . . . . . . . . . . . . . . . . . . .
Blocks That a Triggered Subsystem Can Contain . . . . . . .

7-20
7-20

Triggered and Enabled Subsystems . . . . . . . . . . . . . . . . .
What Are Triggered and Enabled Subsystems? . . . . . . . . .
Creating a Triggered and Enabled Subsystem . . . . . . . . . .
A Sample Triggered and Enabled Subsystem . . . . . . . . . . .
Creating Alternately Executing Subsystems . . . . . . . . . . . .

7-24
7-24
7-25
7-26
7-27

Function-Call Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . .

7-30

7-15

7-22
7-22
7-23

Conditional Execution Behavior . . . . . . . . . . . . . . . . . . . .
What Is Conditional Execution Behavior? . . . . . . . . . . . . . .
Propagating Execution Contexts . . . . . . . . . . . . . . . . . . . . .
Behavior of Switch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Execution Contexts . . . . . . . . . . . . . . . . . . . . . .
Disabling Conditional Execution Behavior . . . . . . . . . . . . .
Displaying Execution Context Bars . . . . . . . . . . . . . . . . . . .

7-32
7-32
7-34
7-35
7-36
7-37
7-37

Modeling Variant Systems

8
Working with Variant Systems . . . . . . . . . . . . . . . . . . . . . .
Overview of Variant Systems . . . . . . . . . . . . . . . . . . . . . . . .
Workflow for Implementing Variant Systems . . . . . . . . . . .

8-2
8-2
8-3

Set Up Model Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Variants Block Overview . . . . . . . . . . . . . . . . . . . . . .
Example of a Model Variants Block . . . . . . . . . . . . . . . . . . .
Configuring the Model Variants Block . . . . . . . . . . . . . . . .
Disabling and Enabling Model Variants . . . . . . . . . . . . . . .
Parameterizing Model Variants . . . . . . . . . . . . . . . . . . . . . .
Requirements, Limitations, and Tips for Model Variants . .
Model Variants Example . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-5
8-5
8-7
8-9
8-12
8-12
8-13
8-14

Set Up Variant Subsystems . . . . . . . . . . . . . . . . . . . . . . . . .
Variant Subsystem Block Overview . . . . . . . . . . . . . . . . . . .
Example of a Variant Subsystem Block . . . . . . . . . . . . . . . .
Configuring the Variant Subsystem Block . . . . . . . . . . . . .
Disabling and Enabling Subsystem Variants . . . . . . . . . . .
Variant Subsystem Block Requirements . . . . . . . . . . . . . . .
Variant Subsystem Example . . . . . . . . . . . . . . . . . . . . . . . .

8-15
8-15
8-17
8-20
8-23
8-23
8-24

Set Up Variant Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Control Variables . . . . . . . . . . . . . . . . . . . . . . . . . .
Saving Variant Components . . . . . . . . . . . . . . . . . . . . . . . . .
Example Variant Control Variables . . . . . . . . . . . . . . . . . . .
Using Enumerated Types for Variant Control Variable
Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-25
8-25
8-26
8-26
8-27

xv

Select the Active Variant . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is an Active Variant? . . . . . . . . . . . . . . . . . . . . . . . . .
Selecting the Active Variant for Simulation . . . . . . . . . . . .
Checking and Opening the Active Variant . . . . . . . . . . . . .
Overriding Variant Conditions . . . . . . . . . . . . . . . . . . . . . . .

8-29
8-29
8-29
8-30
8-30

About Variant Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Variant Object? . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Variant Objects . . . . . . . . . . . . . . . . . . . . . . . . . . .
Reusing Variant Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variant Condition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-32
8-32
8-32
8-33
8-34

Code Generation of Variants . . . . . . . . . . . . . . . . . . . . . . . .

8-36

Variant System Reference . . . . . . . . . . . . . . . . . . . . . . . . . .
Custom Storage Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

8-37
8-37
8-37

Exploring, Searching, and Browsing Models

9

xvi

Contents

Model Explorer Overview . . . . . . . . . . . . . . . . . . . . . . . . . .
What You Can Do Using the Model Explorer . . . . . . . . . . .
Opening the Model Explorer . . . . . . . . . . . . . . . . . . . . . . . . .
Model Explorer Components . . . . . . . . . . . . . . . . . . . . . . . .
The Main Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Customizing the Model Explorer Interface . . . . . . . . . . . . .
Basic Steps for Using the Model Explorer . . . . . . . . . . . . . .
Focusing on Specific Elements of a Model or Chart . . . . . .

9-2
9-2
9-2
9-3
9-4
9-5
9-5
9-6
9-7

Model Explorer: Model Hierarchy Pane . . . . . . . . . . . . .
What You Can Do with the Model Hierarchy Pane . . . . . .
Simulink Root . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Base Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configuration Preferences . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Nodes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Partial or Whole Model Hierarchy Contents . .
Displaying Linked Library Subsystems . . . . . . . . . . . . . . . .

9-9
9-9
9-10
9-10
9-11
9-11
9-12
9-13

Displaying Masked Subsystems . . . . . . . . . . . . . . . . . . . . . .
Linked Library and Masked Subsystems . . . . . . . . . . . . . .
Displaying Node Contents . . . . . . . . . . . . . . . . . . . . . . . . . .
Navigating to the Block Diagram . . . . . . . . . . . . . . . . . . . . .
Working with Configuration Sets . . . . . . . . . . . . . . . . . . . . .
Expanding Model References . . . . . . . . . . . . . . . . . . . . . . . .
Cutting, Copying, and Pasting Objects . . . . . . . . . . . . . . . .

9-14
9-14
9-14
9-15
9-15
9-15
9-17

Model Explorer: Contents Pane . . . . . . . . . . . . . . . . . . . . .
Contents Pane Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Displayed in the Contents Pane . . . . . . . . . . . . . . . . .
Link to the Currently Selected Node . . . . . . . . . . . . . . . . . .
Horizontal Scrolling in the Object Property Table . . . . . . .
Working with the Contents Pane . . . . . . . . . . . . . . . . . . . . .
Editing Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-19
9-19
9-22
9-22
9-23
9-24
9-25

Control Model Explorer Contents Using Views . . . . . . .
Using Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Customizing Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Managing Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-26
9-26
9-29
9-30

Organize Data Display in Model Explorer . . . . . . . . . . . .
Layout Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sorting Column Contents . . . . . . . . . . . . . . . . . . . . . . . . . . .
Grouping by a Property . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Changing the Order of Property Columns . . . . . . . . . . . . . .
Adding Property Columns . . . . . . . . . . . . . . . . . . . . . . . . . .
Hiding or Removing Property Columns . . . . . . . . . . . . . . . .
Marking Nonexistent Properties . . . . . . . . . . . . . . . . . . . . .

9-36
9-36
9-36
9-37
9-41
9-42
9-43
9-45

Filter Objects in the Model Explorer . . . . . . . . . . . . . . . .
Controlling the Set of Objects to Display . . . . . . . . . . . . . . .
Using the Row Filter Option . . . . . . . . . . . . . . . . . . . . . . . .
Filtering Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-46
9-46
9-46
9-48

Workspace Variables in Model Explorer . . . . . . . . . . . . .
Finding Variables That Are Used by a Model or Block . . . .
Finding Blocks That Use a Specific Variable . . . . . . . . . . .
Finding Unused Workspace Variables . . . . . . . . . . . . . . . . .
Editing Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . .
Exporting Workspace Variables . . . . . . . . . . . . . . . . . . . . . .
Importing Workspace Variables . . . . . . . . . . . . . . . . . . . . . .

9-52
9-52
9-55
9-56
9-58
9-60
9-62

xvii

Search Using Model Explorer . . . . . . . . . . . . . . . . . . . . . . .
Searching in the Model Explorer . . . . . . . . . . . . . . . . . . . . .
The Search Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Showing and Hiding the Search Bar . . . . . . . . . . . . . . . . . .
Search Bar Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search Button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Refining a Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-63
9-63
9-64
9-64
9-64
9-66
9-68
9-69

Model Explorer: Property Dialog Pane . . . . . . . . . . . . . .
What You Can Do with the Dialog Pane . . . . . . . . . . . . . . .
Showing and Hiding the Dialog Pane . . . . . . . . . . . . . . . . .
Editing Properties in the Dialog Pane . . . . . . . . . . . . . . . . .

9-70
9-70
9-70
9-70

Finder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Find Model Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filter Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Search Criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9-73
9-73
9-75
9-76

Model Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About the Model Browser . . . . . . . . . . . . . . . . . . . . . . . . . . .
Navigating with the Mouse . . . . . . . . . . . . . . . . . . . . . . . . .
Navigating with the Keyboard . . . . . . . . . . . . . . . . . . . . . . .
Showing Library Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Showing Masked Subsystems . . . . . . . . . . . . . . . . . . . . . . . .

9-80
9-80
9-82
9-82
9-82
9-82

Model Dependency Viewer . . . . . . . . . . . . . . . . . . . . . . . . .
About Model Dependency Views . . . . . . . . . . . . . . . . . . . . .
Opening the Model Dependency Viewer . . . . . . . . . . . . . . .
Manipulating a Dependency View . . . . . . . . . . . . . . . . . . . .
Browsing Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Saving a Dependency View . . . . . . . . . . . . . . . . . . . . . . . . . .
Printing a Dependency View . . . . . . . . . . . . . . . . . . . . . . . .

9-83
9-83
9-88
9-89
9-95
9-95
9-95

View Linked Requirements in Models and Blocks . . . . 9-96
Overview of Requirements Features in Simulink . . . . . . . . 9-96
Highlighting Requirements in a Model . . . . . . . . . . . . . . . . 9-97
Viewing Information About a Requirements Link . . . . . . . 9-99
Navigating to Requirements from a Model . . . . . . . . . . . . . 9-100
Filtering Requirements in a Model . . . . . . . . . . . . . . . . . . . 9-101

xviii

Contents

Managing Model Configurations

10
About Model Configurations . . . . . . . . . . . . . . . . . . . . . . . .

10-2

Multiple Configuration Sets in a Model . . . . . . . . . . . . . .

10-3

Share a Configuration for Multiple Models . . . . . . . . . . .

10-4

....

10-6

Manage a Configuration Set . . . . . . . . . . . . . . . . . . . . . . . .
Create a Configuration Set in a Model . . . . . . . . . . . . . . . .
Create a Configuration Set in the Base Workspace . . . . . .
Open a Configuration Set in the Configuration Parameters
Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Activate a Configuration Set . . . . . . . . . . . . . . . . . . . . . . . .
Set Values in a Configuration Set . . . . . . . . . . . . . . . . . . . .
Copy, Delete, and Move a Configuration Set . . . . . . . . . . . .
Save a Configuration Set . . . . . . . . . . . . . . . . . . . . . . . . . . .
Load a Saved Configuration Set . . . . . . . . . . . . . . . . . . . . . .
Copy Configuration Set Components . . . . . . . . . . . . . . . . . .

10-12
10-12
10-12

Manage a Configuration Reference . . . . . . . . . . . . . . . . . .
Create and Attach a Configuration Reference . . . . . . . . . . .
Resolve a Configuration Reference . . . . . . . . . . . . . . . . . . .
Activate a Configuration Reference . . . . . . . . . . . . . . . . . . .
Manage Configuration Reference Across Referenced
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change Parameter Values in a Referenced Configuration
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save a Referenced Configuration Set . . . . . . . . . . . . . . . . . .
Load a Saved Referenced Configuration Set . . . . . . . . . . . .
Why is the Build Button Not Available for a Configuration
Reference? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10-18
10-18
10-19
10-21

About Configuration Sets . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Configuration Set? . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Freestanding Configuration Set? . . . . . . . . . . . .
Model Configuration Preferences . . . . . . . . . . . . . . . . . . . . .

10-26
10-26
10-27
10-28

Share a Configuration Across Referenced Models

10-13
10-13
10-14
10-14
10-15
10-16
10-16

10-22
10-23
10-23
10-24
10-25

xix

About Configuration References . . . . . . . . . . . . . . . . . . . .
What Is a Configuration Reference? . . . . . . . . . . . . . . . . . .
Why Use Configuration References? . . . . . . . . . . . . . . . . . .
Unresolved Configuration References . . . . . . . . . . . . . . . . .
Configuration Reference Limitations . . . . . . . . . . . . . . . . . .
Configuration References for Models with Older Simulation
Target Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10-29
10-29
10-29
10-30
10-31

Model Configuration Command Line Interface . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Load and Activate a Configuration Set at the Command
Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save a Configuration Set at the Command Line . . . . . . . . .
Create a Freestanding Configuration Set at the Command
Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create and Attach a Configuration Reference at the
Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Attach a Configuration Reference to Multiple Models at the
Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Get Values from a Referenced Configuration Set . . . . . . . .
Change Values in a Referenced Configuration Set . . . . . . .
Obtain a Configuration Reference Handle . . . . . . . . . . . . .
Use refresh When Replacing a Referenced Configuration
Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

10-33
10-33

10-31

10-34
10-35
10-36
10-37
10-38
10-39
10-39
10-40
10-41

Configuring Models for Targets with Multicore
Processors

11

xx

Contents

Introduction to Concurrent Execution . . . . . . . . . . . . . .
About Configuring Models for Concurrent Execution . . . . .
Supported Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Helpful Terms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Software Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-2
11-2
11-3
11-3
11-4

Design Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modeling for Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-5
11-5
11-9

Modeling Process for Concurrent Execution . . . . . . . . . 11-11
Configure Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-12
Creating a Concurrent Execution Configuration Set . . . . . 11-12
Creating and Propagating a Configuration Reference . . . . 11-13
Baseline Analysis Using Configuration Defaults . . . . . . 11-17
Customize Concurrent Execution Settings . . . . . . . . . . .
Configuring Data Transfer Communications . . . . . . . . . . .
Configuring Periodic Tasks . . . . . . . . . . . . . . . . . . . . . . . . .
Configuring Aperiodic Triggers and Tasks . . . . . . . . . . . . .
Mapping Blocks to Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-19
11-19
11-21
11-22
11-24

Interpret Simulation Results . . . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Default Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sample Configured Model with Multiple Target Tasks . . .
How Simulink Determines Data Transfer Requirements . .

11-26
11-26
11-27
11-28
11-31

Build and Download to a Multicore Target . . . . . . . . . . .
Generating Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configuring Embedded Coder for Native Threads
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Build and Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Profile and Evaluate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

11-32
11-32
11-42
11-43
11-44

Concurrent Execution Example Model . . . . . . . . . . . . . . 11-45
Modeling Concurrent Execution on Multi-Core Targets . . . 11-45
Command-Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-55

Modeling Best Practices

12
General Considerations when Building Simulink
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12-2

xxi

Avoiding Invalid Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Shadowed Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Building Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

12-2
12-4
12-6

Model a Continuous System . . . . . . . . . . . . . . . . . . . . . . . .

12-8

Best-Form Mathematical Models . . . . . . . . . . . . . . . . . . . .
Series RLC Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Solving Series RLC Using Resistor Voltage . . . . . . . . . . . .
Solving Series RLC Using Inductor Voltage . . . . . . . . . . . .

12-11
12-11
12-12
12-13

Model a Simple Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-15
Componentization Guidelines . . . . . . . . . . . . . . . . . . . . . .
Componentization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Componentization Techniques . . . . . . . . . . . . . . . . . . . . . . .
General Componentization Guidelines . . . . . . . . . . . . . . . .
Summary of Componentization Techniques . . . . . . . . . . . .
Subsystems Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Libraries Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Referencing Summary . . . . . . . . . . . . . . . . . . . . . . . .

12-17
12-17
12-17
12-18
12-19
12-21
12-25
12-29

Modeling Complex Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-36
Modeling Physical Systems . . . . . . . . . . . . . . . . . . . . . . . . . 12-37
Modeling Signal Processing Systems . . . . . . . . . . . . . . . . 12-38

Managing Projects

13

xxii

Contents

Organize Large Modeling Projects . . . . . . . . . . . . . . . . . .
What Are Simulink Projects? . . . . . . . . . . . . . . . . . . . . . . . .
Get Started with Your Project . . . . . . . . . . . . . . . . . . . . . . .

13-2
13-2
13-2

Try Simulink Project Tools with the Airframe
Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13-4

Explore the Airframe Project . . . . . . . . . . . . . . . . . . . . . . . .
Set Up the Project Files and Open the Simulink Project
Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View, Search, and Sort Project Files . . . . . . . . . . . . . . . . . .
Automate Project Startup and Shutdown Tasks . . . . . . . . .
Open and Run Frequently Used Files . . . . . . . . . . . . . . . . .
Review Changes in Modified Files . . . . . . . . . . . . . . . . . . . .
Run Project Integrity Checks . . . . . . . . . . . . . . . . . . . . . . . .
Run Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . .
Commit Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Upgrade Model Files to SLX and Preserve Revision
History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Source Control and Project Information . . . . . . . . . . .

13-4
13-5
13-5
13-7
13-9
13-10
13-12
13-12
13-15
13-15
13-21

Create a New Simulink Project . . . . . . . . . . . . . . . . . . . . .
Create a New Project to Manage Existing Files . . . . . . . . .
Add Files to the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a New Project from an Archived Project . . . . . . . . .
Open Recent Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change the Project Name, Root, Description, and Startup
Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13-23
13-23
13-26
13-28
13-29

Analyze Project Dependencies . . . . . . . . . . . . . . . . . . . . . .
What Is Dependency Analysis? . . . . . . . . . . . . . . . . . . . . . .
Choose Files and Run Dependency Analysis . . . . . . . . . . . .
Check Dependencies Results and Resolve Problems . . . . .
Investigate Dependencies Graph . . . . . . . . . . . . . . . . . . . . .
Options for Analyzing Model Dependencies . . . . . . . . . . . .

13-32
13-32
13-33
13-35
13-38
13-43

Manage Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Choose Views of Files to Manage . . . . . . . . . . . . . . . . . . . . .
Group and Sort File Views . . . . . . . . . . . . . . . . . . . . . . . . . .
Search and Filter File Views . . . . . . . . . . . . . . . . . . . . . . . .
Work with Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Back Out Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Label Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13-44
13-44
13-45
13-46
13-47
13-49
13-49

Automate Project Startup and Run Frequent Tasks . . .
Create Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Shortcuts to Find and Run Frequent Tasks . . . . . . . . .
Automate Startup Tasks with Shortcuts . . . . . . . . . . . . . . .
Automate Shutdown Tasks with Shortcuts . . . . . . . . . . . . .

13-52
13-52
13-53
13-54
13-57

13-30

xxiii

Run Batch Functions on Project Files . . . . . . . . . . . . . . . 13-58
Use Source Control with Projects . . . . . . . . . . . . . . . . . . .
About Source Control with Projects . . . . . . . . . . . . . . . . . . .
Add a Project to Source Control . . . . . . . . . . . . . . . . . . . . . .
View or Change Project Source Control . . . . . . . . . . . . . . . .
Register Model Files with Source Control Tools . . . . . . . . .
Subversion Integration with Projects . . . . . . . . . . . . . . . . .
Write a Source Control Adapter with the SDK . . . . . . . . . .

13-60
13-60
13-61
13-68
13-70
13-70
13-75

Retrieve and Check Out Files Under Source Control . .
Retrieve a Working Copy of a Project from Source
Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Refresh Status of Project Files . . . . . . . . . . . . . . . . . . . . . . .
Update Revisions of Project Files . . . . . . . . . . . . . . . . . . . . .
Check Out Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13-76

Review Changes and Commit Modified Files . . . . . . . . .
View Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Review Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Precommit Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Commit Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Revert Local Changes and Release Locks . . . . . . . . . . . . . .
Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Work with Derived Files in Projects . . . . . . . . . . . . . . . . . .

13-89
13-89
13-91
13-93
13-94
13-94
13-95
13-96

Use Templates to Create Standard Project Settings . . .
Use Templates for Standard Project Setup . . . . . . . . . . . . .
Create a Template from Your Current Project . . . . . . . . . .
View and Validate Templates . . . . . . . . . . . . . . . . . . . . . . . .
Create a New Project Using a Template . . . . . . . . . . . . . . .
Import New Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

13-97
13-97
13-97
13-99
13-100
13-100
13-101

13-76
13-81
13-84
13-86

Archive Projects in Zip Files . . . . . . . . . . . . . . . . . . . . . . . . 13-103
Analyze Model Dependencies . . . . . . . . . . . . . . . . . . . . . . .
What Are Model Dependencies? . . . . . . . . . . . . . . . . . . . . . .
Generate Manifests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command-Line Dependency Analysis . . . . . . . . . . . . . . . . .
Edit Manifests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

xxiv

Contents

13-104
13-104
13-105
13-112
13-114

Compare Manifests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Export Files in a Manifest . . . . . . . . . . . . . . . . . . . . . . . . . .
Scope of Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . .
Best Practices for Dependency Analysis . . . . . . . . . . . . . . .
Use the Model Manifest Report . . . . . . . . . . . . . . . . . . . . . .

13-117
13-118
13-120
13-123
13-124

Simulating Dynamic Systems
Running Simulations

14
.................................

14-2

Control Execution of a Simulation . . . . . . . . . . . . . . . . . .
Start a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pause or Stop a Simulation . . . . . . . . . . . . . . . . . . . . . . . . .
Use Blocks to Stop or Pause a Simulation . . . . . . . . . . . . . .

14-3
14-3
14-5
14-5

Specify Simulation Start and Stop Time . . . . . . . . . . . . .

14-8

Choose a Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Solver? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Choosing a Solver Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Choosing a Fixed-Step Solver . . . . . . . . . . . . . . . . . . . . . . . .
Choosing a Variable-Step Solver . . . . . . . . . . . . . . . . . . . . .
Choosing a Jacobian Method for an Implicit Solver . . . . . .

14-9
14-9
14-10
14-13
14-17
14-24

Simulation Basics

Interact with a Running Simulation . . . . . . . . . . . . . . . . . 14-31
Save and Restore Simulation State as SimState . . . . . .
Overview of the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restore the SimState . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change the States of a Block within the SimState . . . . . . .
SimState Interface Checksum Diagnostic . . . . . . . . . . . . . .
Limitations of the SimState . . . . . . . . . . . . . . . . . . . . . . . . .
Using SimState within S-Functions . . . . . . . . . . . . . . . . . .

14-32
14-32
14-33
14-35
14-37
14-37
14-38
14-38

xxv

Diagnose Simulation Errors . . . . . . . . . . . . . . . . . . . . . . . .
Response to Run-Time Errors . . . . . . . . . . . . . . . . . . . . . . .
Simulation Diagnostics Viewer . . . . . . . . . . . . . . . . . . . . . .
Create Custom Simulation Error Messages . . . . . . . . . . . .

14-39
14-39
14-39
14-41

Running a Simulation Programmatically

15

xxvi

Contents

About Programmatic Simulation . . . . . . . . . . . . . . . . . . . .

15-2

Run Simulation Using the sim Command . . . . . . . . . . . .
Single-Output Syntax for the sim Command . . . . . . . . . . .
Examples of Implementing the sim Command . . . . . . . . . .
Calling sim from within parfor . . . . . . . . . . . . . . . . . . . . . . .
Backwards Compatible Syntax . . . . . . . . . . . . . . . . . . . . . .

15-3
15-3
15-4
15-5
15-5

Control Simulation using the set_param Command . . .
Run Simulation from an S-Function . . . . . . . . . . . . . . . . . .

15-7
15-7

Run Parallel Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview of Calling sim from within parfor . . . . . . . . . . . .
sim in parfor with Rapid Accelerator Mode . . . . . . . . . . . . .
Workspace Access Issues . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resolving Workspace Access Issues . . . . . . . . . . . . . . . . . . .
Data Concurrency Issues . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resolving Data Concurrency Issues . . . . . . . . . . . . . . . . . . .

15-8
15-8
15-9
15-10
15-11
15-12
15-13

Error Handling in Simulink Using MSLException . . . .
Error Reporting in a Simulink Application . . . . . . . . . . . . .
The MSLException Class . . . . . . . . . . . . . . . . . . . . . . . . . . .
Methods of the MSLException Class . . . . . . . . . . . . . . . . . .
Capturing Information about the Error . . . . . . . . . . . . . . . .

15-15
15-15
15-15
15-15
15-15

Visualizing and Comparing Simulation Results

16
View Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Scope Blocks, Signal Viewers, Test Points and
Data Logging? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Scope Block and Scope Signal Viewer Differences . . . . . . .
Why Use Signal Generators and Signal Viewers Instead of
Source Blocks and Scope Blocks? . . . . . . . . . . . . . . . . . . .

16-2
16-2
16-3
16-4

Signal Viewer Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
About Signal Viewers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Attaching a Signal Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Adding Signals to a Signal Viewer . . . . . . . . . . . . . . . . . . . . 16-8
Displaying a Signal Viewer . . . . . . . . . . . . . . . . . . . . . . . . . 16-9
Saving Data to MATLAB Workspace . . . . . . . . . . . . . . . . . . 16-10
Plotting the Viewer Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-10
Scope Signal Viewer Tasks . . . . . . . . . . . . . . . . . . . . . . . . . 16-11
Adding a Legend to a Scope Signal Viewer . . . . . . . . . . . . . 16-11
Creating a Multiple Axes Scope Signal Viewer . . . . . . . . . . 16-11
Scope Signal Viewer Characteristics . . . . . . . . . . . . . . . .
Scope Signal Viewer Toolbar . . . . . . . . . . . . . . . . . . . . . . . .
Scope Signal Viewer Context Menu . . . . . . . . . . . . . . . . . . .
Scope Signal Viewer Parameters Dialog Box . . . . . . . . . . .
Line Styles with Scope Signal Viewer . . . . . . . . . . . . . . . . .
Parameter Settings and Performance with Scope Signal
Viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16-14
16-14
16-15
16-16
16-19
16-20

Signal Generator Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-21
Attaching a Signal Generator. . . . . . . . . . . . . . . . . . . . . . . . 16-21
Removing a Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-22
Signal and Scope Manager . . . . . . . . . . . . . . . . . . . . . . . . .
About the Signal & Scope Manager . . . . . . . . . . . . . . . . . . .
Opening the Signal and Scope Manager . . . . . . . . . . . . . . .
Changing Generator or Viewer Parameters . . . . . . . . . . . .
Adding Signals to a Viewer . . . . . . . . . . . . . . . . . . . . . . . . .
Removing a Generator or Viewer from a Simulink Model . .
Viewing Test Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16-23
16-23
16-24
16-25
16-25
16-25
16-26

xxvii

Signal Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About the Signal Selector . . . . . . . . . . . . . . . . . . . . . . . . . . .
Select signals for object . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Model Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inputs/Signals List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

16-27
16-27
16-28
16-28
16-28

Inspecting and Comparing Logged Signal Data

17
Inspect Signal Data with Simulation Data Inspector . .

17-2

Requirements for Recording Data . . . . . . . . . . . . . . . . . . .

17-4

Record Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17-5

Import Logged Signal Data . . . . . . . . . . . . . . . . . . . . . . . . .
Import Signal Data from the Base Workspace . . . . . . . . . .
Import Signal Data from a MAT-File . . . . . . . . . . . . . . . . .

17-7
17-7
17-9

Load Previously Recorded Data from a MAT-file

. . . . . 17-10

Inspect Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a View of Multiple Plots . . . . . . . . . . . . . . . . . . . . . .
Explore Signal Data in a Multiple Plot View . . . . . . . . . . .
Replace a Run in a View . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Copy a View in the Inspect Signals Tab . . . . . . . . . . . . . . .
Delete a View in the Inspect Signals Tab . . . . . . . . . . . . . .
Export a View in the Inspect Signals Tab . . . . . . . . . . . . . .
Import a View in the Inspect Signals Tab . . . . . . . . . . . . . .

17-11
17-11
17-11
17-13
17-16
17-17
17-20
17-21
17-22
17-22

Compare Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-23
Comparison of One Signal From Multiple
Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-25

xxviii

Contents

Compare All Logged Signal Data From Multiple
Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-28
Create Simulation Data Inspector Report . . . . . . . . . . . . 17-32
Export Results in the Simulation Data Inspector
Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-34
Save Data to a MAT-File . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-34
How the Simulation Data Inspector Tool Aligns
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-35
Inspect Signals: Aligning Signals for Replacing a Run . . . 17-35
Compare Runs: Aligning Signals for Comparing Signal
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-36
How the Simulation Data Inspector Tool Compares
Time Series Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-37
How Tolerances Are Applied . . . . . . . . . . . . . . . . . . . . . . . . 17-37
Customize the Simulation Data Inspector Interface . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Open the Simulation Data Inspector Tool . . . . . . . . . . . . . .
Why Is the Simulation Data Inspector Tool Empty? . . . . .
Add/Delete a Column in the Signal Browser Table . . . . . . .
Modify Grouping in Signal Browser Table . . . . . . . . . . . . .
Rename a Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify the Line Configuration . . . . . . . . . . . . . . . . . . . . . . .
Select a Run or Signal Option in the Signal Browser
Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Run Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modify a Plot in the Simulation Data Inspector Tool . . . . .
Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17-38
17-38
17-39
17-39
17-40
17-42
17-44
17-45
17-46
17-49
17-49
17-51

Limitations of the Simulation Data Inspector Tool . . . . 17-54
Record and Inspect Signal Data Programmatically . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Import/Export Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Comparison Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

17-55
17-55
17-55
17-56
17-57
17-57

xxix

Create a Run in the Simulation Data Inspector . . . . . . . . .
Compare Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Compare Runs of Simulation Data . . . . . . . . . . . . . . . . . . .
Record Data During Parallel Simulations . . . . . . . . . . . . . .

17-57
17-58
17-58
17-60

Analyzing Simulation Results

18
Viewing Output Trajectories . . . . . . . . . . . . . . . . . . . . . . .
Viewing and Exporting Simulation Data . . . . . . . . . . . . . . .
Using the Scope Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Return Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using the To Workspace Block . . . . . . . . . . . . . . . . . . . . . . .
Using the Simulation Data Inspector Tool . . . . . . . . . . . . .

18-2
18-2
18-2
18-3
18-3
18-4

Linearizing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Linearizing Models . . . . . . . . . . . . . . . . . . . . . . . . . . .
Linearization with Referenced Models . . . . . . . . . . . . . . . .
Linearization Using the ’v5’ Algorithm . . . . . . . . . . . . . . . .

18-5
18-5
18-7
18-9

Finding Steady-State Points . . . . . . . . . . . . . . . . . . . . . . . . 18-11

Improving Simulation Performance and
Accuracy

19

xxx

Contents

About Improving Performance and Accuracy . . . . . . . .

19-2

Speed Up Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19-3

Comparing Performance . . . . . . . . . . . . . . . . . . . . . . . . . . .
Performance of the Simulation Modes . . . . . . . . . . . . . . . . .
Measure Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19-5
19-5
19-7

Improve Acceleration Mode Performance . . . . . . . . . . . . 19-9
Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-9
C Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-10
Improve Simulation Accuracy . . . . . . . . . . . . . . . . . . . . . . 19-11

Performance Advisor

20
Consult the Performance Advisor . . . . . . . . . . . . . . . . . . .
About the Performance Advisor . . . . . . . . . . . . . . . . . . . . . .
Prepare to Use Performance Advisor . . . . . . . . . . . . . . . . . .
Start the Performance Advisor . . . . . . . . . . . . . . . . . . . . . . .
Overview of the Performance Advisor Window . . . . . . . . . .
Performance Advisor Workflow . . . . . . . . . . . . . . . . . . . . . .
Create Baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Performance Advisor Checks . . . . . . . . . . . . . . . . . . . .
View and Save Performance Advisor Reports . . . . . . . . . . .
Understand Performance Advisor Analysis Results . . . . . .
Fix a Warning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Review the Actions Taken . . . . . . . . . . . . . . . . . . . . . . . . . .
Save Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Performance Advisor Limitations . . . . . . . . . . . . . . . . . . . .

20-2
20-2
20-3
20-3
20-3
20-6
20-6
20-8
20-11
20-14
20-16
20-16
20-17
20-17

Simulink Debugger

21
Introduction to the Debugger . . . . . . . . . . . . . . . . . . . . . . .

21-2

Debugger Graphical User Interface . . . . . . . . . . . . . . . . .
Displaying the Graphical Interface . . . . . . . . . . . . . . . . . . .
Toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Breakpoints Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Loop Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Outputs Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sorted List Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21-3
21-3
21-4
21-5
21-6
21-7
21-8

xxxi

Status Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

21-9

Debugger Command-Line Interface . . . . . . . . . . . . . . . . .
Controlling the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . .
Method ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing the MATLAB Workspace . . . . . . . . . . . . . . . . . . .

21-10
21-10
21-10
21-10
21-11

Debugger Online Help

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-12

Start the Simulink Debugger . . . . . . . . . . . . . . . . . . . . . . . 21-13
Starting from a Model Window . . . . . . . . . . . . . . . . . . . . . . 21-13
Starting from the Command Window . . . . . . . . . . . . . . . . . 21-13
Start a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-15
Run a Simulation Step by Step . . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Data Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Stepping Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Continuing a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . .
Running a Simulation Nonstop . . . . . . . . . . . . . . . . . . . . . .

21-17
21-17
21-18
21-19
21-20
21-20

Set Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Unconditional Breakpoints . . . . . . . . . . . . . . . . . . .
Setting Conditional Breakpoints . . . . . . . . . . . . . . . . . . . . .

21-22
21-22
21-22
21-25

Display Information About the Simulation . . . . . . . . . . .
Display Block I/O . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Algebraic Loop Information . . . . . . . . . . . . . . . . . .
Display System States . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Solver Information . . . . . . . . . . . . . . . . . . . . . . . . .

21-28
21-28
21-30
21-31
21-32

Display Information About the Model . . . . . . . . . . . . . . . 21-33
Display Model’s Sorted Lists . . . . . . . . . . . . . . . . . . . . . . . . 21-33
Display a Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-34

xxxii

Contents

Accelerating Models

22
What Is Acceleration? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-2

How Acceleration Modes Work . . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Normal Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accelerator Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rapid Accelerator Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-3
22-3
22-3
22-4
22-5

Code Regeneration in Accelerated Models . . . . . . . . . . .
Structural Changes That Cause Rebuilds . . . . . . . . . . . . . .
Determining If the Simulation Will Rebuild . . . . . . . . . . . .

22-7
22-7
22-7

Choosing a Simulation Mode . . . . . . . . . . . . . . . . . . . . . . .
Simulation Mode Tradeoffs . . . . . . . . . . . . . . . . . . . . . . . . .
Comparing Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-11
22-11
22-12
22-14

Design Your Model for Effective Acceleration . . . . . . . .
Select Blocks for Accelerator Mode . . . . . . . . . . . . . . . . . . .
Select Blocks for Rapid Accelerator Mode . . . . . . . . . . . . . .
Control S-Function Execution . . . . . . . . . . . . . . . . . . . . . . .
Accelerator and Rapid Accelerator Mode Data Type
Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Behavior of Scopes and Viewers with Rapid Accelerator
Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Factors Inhibiting Acceleration . . . . . . . . . . . . . . . . . . . . . .

22-16
22-16
22-17
22-17

Perform Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Customize the Build Process . . . . . . . . . . . . . . . . . . . . . . . .
Run Acceleration Mode from the User Interface . . . . . . . . .
Making Run-Time Changes . . . . . . . . . . . . . . . . . . . . . . . . .

22-22
22-22
22-23
22-25

Interact with the Acceleration Modes
Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Why Interact Programmatically? . . . . . . . . . . . . . . . . . . . . .
Build Accelerator Mode MEX-files . . . . . . . . . . . . . . . . . . . .
Control Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

22-26
22-26
22-26
22-26

22-18
22-18
22-19

xxxiii

Simulate Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-27
Customize the Acceleration Build Process . . . . . . . . . . . . . . 22-28
Run Accelerator Mode with the Simulink Debugger . .
Advantages of Using Accelerator Mode with the
Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Run the Debugger . . . . . . . . . . . . . . . . . . . . . . . . . .
When to Switch Back to Normal Mode . . . . . . . . . . . . . . . .

22-29

Capture Performance Data . . . . . . . . . . . . . . . . . . . . . . . . .
What Is the Profiler? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How the Profiler Works . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enabling the Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Save Simulink Profiler Results . . . . . . . . . . . . . . . .

22-31
22-31
22-31
22-33
22-36

22-29
22-29
22-30

Managing Blocks
Working with Blocks

23
About Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Blocks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Tool Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Virtual Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-2
23-2
23-2
23-2

Add Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ways to Add Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add Blocks by Browsing or Searching with the Library
Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Copy Blocks from a Model . . . . . . . . . . . . . . . . . . . . . . . . . .
Add Frequently Used Blocks . . . . . . . . . . . . . . . . . . . . . . . .
Add Blocks Programmatically . . . . . . . . . . . . . . . . . . . . . . .

23-4
23-4
23-5
23-5
23-6
23-8

Edit Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-9
Copy Blocks in a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-9
Copy Blocks Between Windows . . . . . . . . . . . . . . . . . . . . . . 23-10
Move Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-11
Delete Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-13

xxxiv

Contents

Comment Out Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-14
Set Block Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Properties Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . .
General Block Properties . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Annotation Properties . . . . . . . . . . . . . . . . . . . . . . . .
Block Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Block Annotations Programmatically . . . . . . . . . . .

23-15
23-15
23-16
23-17
23-19
23-21

Change the Appearance of a Block . . . . . . . . . . . . . . . . . .
Change a Block Orientation . . . . . . . . . . . . . . . . . . . . . . . . .
Resize a Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Parameters Beneath a Block . . . . . . . . . . . . . . .
Drop Shadows . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Manipulate Block Names . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify Block Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-22
23-22
23-24
23-25
23-25
23-26
23-28

Display Port Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Port Value Data Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Value for a Port . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Control the Port Value Display . . . . . . . . . . . . . . . . . . . . . .
Displayed Value When No Data Is Available . . . . . . . . . . .
Port Value Display Limitations . . . . . . . . . . . . . . . . . . . . . .

23-29
23-29
23-30
23-31
23-32
23-33

Control and Displaying the Sorted Order . . . . . . . . . . . .
What Is Sorted Order? . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display the Sorted Order . . . . . . . . . . . . . . . . . . . . . . . . . . .
Sorted Order Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How Simulink Determines the Sorted Order . . . . . . . . . . .
Assign Block Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rules for Block Priorities . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Priority Violations . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-35
23-35
23-35
23-36
23-45
23-47
23-48
23-51

Access Block Data During Simulation . . . . . . . . . . . . . . .
About Block Run-Time Objects . . . . . . . . . . . . . . . . . . . . . .
Access a Run-Time Object . . . . . . . . . . . . . . . . . . . . . . . . . .
Listen for Method Execution Events . . . . . . . . . . . . . . . . . .
Synchronizing Run-Time Objects and Simulink
Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

23-53
23-53
23-53
23-54
23-55

Configure a Block for Code Generation . . . . . . . . . . . . . . 23-57

xxxv

Working with Block Parameters

24
...........................

24-2

Set Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display a Block Parameter Dialog Box . . . . . . . . . . . . . . . .

24-4
24-4

Specify Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . .
About Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Workspace Variables in Parameter Expressions . . . . .
Resolve Variable References in Block Parameter
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Parameter Objects to Specify Parameter Values . . . . .
Determine Parameter Data Types . . . . . . . . . . . . . . . . . . . .

24-6
24-6
24-6

About Block Parameters

24-7
24-7
24-7

Check Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-9
About Value Checking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-9
Blocks That Perform Parameter Range Checking . . . . . . . 24-9
Specify Ranges for Parameters . . . . . . . . . . . . . . . . . . . . . . . 24-10
Perform Parameter Range Checking . . . . . . . . . . . . . . . . . . 24-11
Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-13
About Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 24-13
Tune a Block Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-13
Inline Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14
About Inlined Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 24-14
Specify Some Parameters as Noninline . . . . . . . . . . . . . . . . 24-14
Structure Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Structure Parameters . . . . . . . . . . . . . . . . . . . . . . . .
Define Structure Parameters . . . . . . . . . . . . . . . . . . . . . . . .
Referencing Structure Parameters . . . . . . . . . . . . . . . . . . .
Structure Parameter Arguments . . . . . . . . . . . . . . . . . . . . .
Tunable Structure Parameters . . . . . . . . . . . . . . . . . . . . . .
Parameter Structure Limitations . . . . . . . . . . . . . . . . . . . .

xxxvi

Contents

24-16
24-16
24-17
24-17
24-18
24-19
24-20

Working with Lookup Tables

25
About Lookup Table Blocks . . . . . . . . . . . . . . . . . . . . . . . . .

25-2

Anatomy of a Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . .

25-4

Lookup Tables Block Library . . . . . . . . . . . . . . . . . . . . . . .

25-5

Guidelines for Choosing a Lookup Table . . . . . . . . . . . . . 25-7
Data Set Dimensionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-7
Data Set Numeric and Data Types . . . . . . . . . . . . . . . . . . . 25-7
Data Accuracy and Smoothness . . . . . . . . . . . . . . . . . . . . . . 25-8
Dynamics of Table Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-8
Efficiency of Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-8
Summary of Lookup Table Block Features . . . . . . . . . . . . . 25-10
Enter Breakpoints and Table Data . . . . . . . . . . . . . . . . . .
Entering Data in a Block Parameter Dialog Box . . . . . . . .
Entering Data in the Lookup Table Editor . . . . . . . . . . . . .
Entering Data Using Inports of the Lookup Table Dynamic
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

25-11
25-11
25-13

Characteristics of Lookup Table Data . . . . . . . . . . . . . . .
Sizes of Breakpoint Data Sets and Table Data . . . . . . . . . .
Monotonicity of Breakpoint Data Sets . . . . . . . . . . . . . . . . .
Representation of Discontinuities in Lookup Tables . . . . .
Formulation of Evenly Spaced Breakpoints . . . . . . . . . . . .

25-18
25-18
25-19
25-20
25-22

Methods for Estimating Missing Points . . . . . . . . . . . . . .
About Estimating Missing Points . . . . . . . . . . . . . . . . . . . .
Interpolation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Extrapolation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Rounding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example Output for Lookup Methods . . . . . . . . . . . . . . . . .

25-23
25-23
25-23
25-24
25-25
25-26

Edit Existing LookupTables . . . . . . . . . . . . . . . . . . . . . . . .
When to Use the Lookup Table Editor . . . . . . . . . . . . . . . . .
Layout of the Lookup Table Editor . . . . . . . . . . . . . . . . . . .
Browsing Lookup Table Blocks . . . . . . . . . . . . . . . . . . . . . .

25-28
25-28
25-28
25-29

25-16

xxxvii

Editing Table Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Table Data of Standard Format . . . . . . . . . .
Working with Table Data of Nonstandard Format . . . . . . .
Importing Data from an Excel Spreadsheet . . . . . . . . . . . .
Adding and Removing Rows and Columns in a Table . . . .
Displaying N-Dimensional Tables in the Editor . . . . . . . . .
Plotting Lookup Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Editing Custom Lookup Table Blocks . . . . . . . . . . . . . . . . .

25-30
25-32
25-36
25-53
25-55
25-56
25-57
25-61

Create a Logarithm Lookup Table . . . . . . . . . . . . . . . . . . . 25-63
Prelookup and Interpolation Blocks . . . . . . . . . . . . . . . . . 25-66
Optimize Generated Code for Lookup Table Blocks . . . 25-67
Remove Code That Checks for Out-of-Range Inputs . . . . . 25-67
Optimize Breakpoint Spacing in Lookup Tables . . . . . . . . . 25-69
Update Lookup Table Blocks to New Versions . . . . . . . .
Comparison of Blocks with Current Versions . . . . . . . . . . .
Compatibility of Models with Older Versions of Lookup
Table Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Update Your Model . . . . . . . . . . . . . . . . . . . . . . . . .
What to Expect from the Model Advisor Check . . . . . . . . . .

25-71
25-71
25-72
25-73
25-74

Lookup Table Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-77

Working with Block Masks

26

xxxviii

Contents

Block Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Are Masks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When to Use Masks? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26-2
26-2
26-2

How Mask Parameters Work . . . . . . . . . . . . . . . . . . . . . . . .

26-4

Mask Code Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mask Code Placement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

26-7
26-7

Drawing Command Execution . . . . . . . . . . . . . . . . . . . . . . .
Initialization Command Execution . . . . . . . . . . . . . . . . . . .
Callback Code Execution . . . . . . . . . . . . . . . . . . . . . . . . . . .

26-7
26-8
26-9

Mask Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-11
Mask a Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-12
Draw Mask Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-15
Create Mask Documentation . . . . . . . . . . . . . . . . . . . . . . . . 26-17
Initialize Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Mask Editor Initialization Pane . . . . . . . . . . . . . . . . . . . . . .
Dialog variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization Commands . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization Command Limitations . . . . . . . . . . . . . . . . . .

26-19
26-19
26-20
26-21
26-21

Best Practices for Masking . . . . . . . . . . . . . . . . . . . . . . . . . 26-22
Use These Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-22
Avoid These Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-22
Considerations for Masking Model Blocks . . . . . . . . . . . 26-23
Referenced Model Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-23
Variable Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-24
Masks on Blocks in User Libraries . . . . . . . . . . . . . . . . . .
About Masks and User-Defined Libraries . . . . . . . . . . . . . .
Masking a Block for Inclusion in a User Library . . . . . . . .
Masking a Block that Resides in a User Library . . . . . . . .
Masking a Block Copied from a User Library . . . . . . . . . . .

26-25
26-25
26-25
26-25
26-26

Promote Underlying Block Parameters to Mask . . . . . . 26-27
Create Custom Interface for Simulink Blocks . . . . . . . . 26-31
Rules for Promoting Parameters . . . . . . . . . . . . . . . . . . . . 26-36
General Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-36
Promotion from directly masked block . . . . . . . . . . . . . . . . 26-36

xxxix

Promotion from child blocks within subsystems . . . . . . . . . 26-37
Links created from masked blocks . . . . . . . . . . . . . . . . . . . . 26-37
Mask Blocks and Promote Parameters . . . . . . . . . . . . . . . 26-38
Mask Built-In Blocks Directly and Within Subsystems . . . 26-38
Create Custom Interface for Multiple Parameters in
Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-38
Operate on Existing Masks . . . . . . . . . . . . . . . . . . . . . . . . .
Change a Block Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Mask Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Look Under Block Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Remove and Cache Mask . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restore Cached Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Permanently Delete Mask . . . . . . . . . . . . . . . . . . . . . . . . . .

26-42
26-42
26-42
26-43
26-43
26-45
26-45

Calculate Values Used Under the Mask . . . . . . . . . . . . . . 26-46
Control Masks Programmatically . . . . . . . . . . . . . . . . . . .
Use Simulink.Mask and Simulink.MaskParameter . . . . .
Use get_param and set_param . . . . . . . . . . . . . . . . . . . . . .
Predefined Masked Dialog Box Parameters . . . . . . . . . . . .
Notes on Mask Parameter Storage . . . . . . . . . . . . . . . . . . .

26-49
26-49
26-50
26-52
26-54

Create Dynamic Mask Dialog Boxes . . . . . . . . . . . . . . . . .
About Dynamic Masked Dialog Boxes . . . . . . . . . . . . . . . . .
Show parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enable parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Masked Block Dialog Box Parameters . . . . . . . . . .
Setting Nested Masked Block Parameters . . . . . . . . . . . . .

26-56
26-56
26-57
26-57
26-57
26-59

Create Dynamic Masked Subsystems . . . . . . . . . . . . . . . .
Allow library block to modify its contents . . . . . . . . . . . . . .
Create Self-Modifying Masks for Library Blocks . . . . . . . .
Evaluate Blocks Under Self-Modifying Mask . . . . . . . . . . .

26-61
26-61
26-61
26-65

How Do I Debug Masks That Use MATLAB Code? . . . . . 26-67
Code Written in Mask Editor . . . . . . . . . . . . . . . . . . . . . . . . 26-67
Code Written Using MATLAB Editor/Debugger . . . . . . . . . 26-67

xl

Contents

Creating Custom Blocks

27
.....................

27-2

Types of Custom Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . .
Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
S-Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

27-3
27-3
27-4
27-4

When to Create Custom Blocks

Comparison of Custom Block Functionality . . . . . . . . . . 27-7
Custom Block Considerations . . . . . . . . . . . . . . . . . . . . . . . . 27-7
Modeling Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-10
Speed and Code Generation Requirements . . . . . . . . . . . . . 27-13
Expanding Custom Block Functionality . . . . . . . . . . . . . 27-17
Create a Custom Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Design a Custom Block . . . . . . . . . . . . . . . . . . . . . .
Defining Custom Block Behavior . . . . . . . . . . . . . . . . . . . . .
Deciding on a Custom Block Type . . . . . . . . . . . . . . . . . . . .
Placing Custom Blocks in a Library . . . . . . . . . . . . . . . . . . .
Adding a Graphical User Interface to a Custom Block . . . .
Adding Block Functionality Using Block Callbacks . . . . . .

27-18
27-18
27-20
27-21
27-27
27-28
27-37

Custom Block Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Custom Blocks from Masked Library Blocks . . . .
Creating Custom Blocks from MATLAB Functions . . . . . .
Creating Custom Blocks from S-Functions . . . . . . . . . . . . .

27-43
27-43
27-43
27-44

Working with Block Libraries

28
About Block Libraries and Linked Blocks . . . . . . . . . . . .
Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Benefits of Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . .
Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

28-2
28-2
28-2
28-2

xli

Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

28-2

Create and Work with Linked Blocks . . . . . . . . . . . . . . . .
About Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Linked Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Update a Linked Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modify Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Find a Linked Block’s Prototype . . . . . . . . . . . . . . . . . . . . .
Find Linked Blocks in a Model . . . . . . . . . . . . . . . . . . . . . . .

28-4
28-4
28-4
28-5
28-6
28-7
28-7

Work with Library Links . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Library Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Lock Links to Blocks in a Library . . . . . . . . . . . . . . . . . . . .
Disable Links to Library Blocks . . . . . . . . . . . . . . . . . . . . . .
Restore Disabled or Parameterized Links . . . . . . . . . . . . . .
Check and Set Link Status Programmatically . . . . . . . . . .
Break a Link to a Library Block . . . . . . . . . . . . . . . . . . . . . .
Fix Unresolved Library Links . . . . . . . . . . . . . . . . . . . . . . .

28-8
28-8
28-9
28-11
28-12
28-16
28-18
28-19

Create Block Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create a Sublibrary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Modify and Lock Libraries . . . . . . . . . . . . . . . . . . . . . . . . . .
Make Backward-Compatible Changes to Libraries . . . . . .

28-20
28-20
28-21
28-21
28-22

Add Libraries to the Library Browser . . . . . . . . . . . . . . .
Display a Library in the Library Browser . . . . . . . . . . . . . .
Example of a Minimal slblocks.m File . . . . . . . . . . . . . . . . .
Add More Descriptive Information in slblocks.m . . . . . . . .

28-32
28-32
28-32
28-33

Using the MATLAB Function Block

29

xlii

Contents

Integrate MATLAB Algorithm in Model . . . . . . . . . . . . . .
Defining Local Variables for Code Generation . . . . . . . . . .

29-4
29-4

What Is a MATLAB Function Block? . . . . . . . . . . . . . . . . .
Calling Functions in MATLAB Function Blocks . . . . . . . . .

29-6
29-6

Why Use MATLAB Function Blocks? . . . . . . . . . . . . . . . . .

29-8

Create Model That Uses MATLAB Function Block . . . . 29-9
Adding a MATLAB Function Block to a Model . . . . . . . . . . 29-9
Programming the MATLAB Function Block . . . . . . . . . . . . 29-10
Building the Function and Checking for Errors . . . . . . . . . 29-12
Defining Inputs and Outputs . . . . . . . . . . . . . . . . . . . . . . . . 29-14
Code Generation Readiness Tool . . . . . . . . . . . . . . . . . . . .
What Information Does the Code Generation Readiness
Tool Provide? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Summary Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Code Structure Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-16
29-16
29-17
29-18
29-21

Check Code Using the Code Generation Readiness
Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-22
Run Code Generation Readiness Tool at the Command
Line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-22
Run the Code Generation Readiness Tool From the Current
Folder Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-22
Debugging a MATLAB Function Block . . . . . . . . . . . . . . .
How Debugging Affects Simulation Speed . . . . . . . . . . . . .
Enabling and Disabling Debugging . . . . . . . . . . . . . . . . . . .
Debugging the Function in Simulation . . . . . . . . . . . . . . . .
Watching Function Variables During Simulation . . . . . . . .
Checking for Data Range Violations . . . . . . . . . . . . . . . . . .
Debugging Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-23
29-23
29-23
29-23
29-27
29-29
29-29

MATLAB Function Block Editor . . . . . . . . . . . . . . . . . . . .
Customizing the MATLAB Function Block Editor . . . . . . .
MATLAB Function Block Editor Tools . . . . . . . . . . . . . . . .
Editing and Debugging MATLAB Function Block Code . . .
Ports and Data Manager . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-33
29-33
29-33
29-34
29-37

MATLAB Function Reports . . . . . . . . . . . . . . . . . . . . . . . . .
About MATLAB Function Reports . . . . . . . . . . . . . . . . . . . .
Location of MATLAB Function Reports . . . . . . . . . . . . . . . .
Opening MATLAB Function Reports . . . . . . . . . . . . . . . . . .
Description of MATLAB Function Reports . . . . . . . . . . . . .

29-51
29-51
29-51
29-52
29-52

xliii

Viewing Your MATLAB Function Code . . . . . . . . . . . . . . . .
Viewing Call Stack Information . . . . . . . . . . . . . . . . . . . . . .
Viewing the Compilation Summary Information . . . . . . . .
Viewing Error and Warning Messages . . . . . . . . . . . . . . . .
Viewing Variables in Your MATLAB Code . . . . . . . . . . . . .
Keyboard Shortcuts for the MATLAB Function Report . . .
Report Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-52
29-54
29-54
29-54
29-56
29-61
29-62

Type Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . .
About Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . .
Specifying Argument Types . . . . . . . . . . . . . . . . . . . . . . . . .
Inheriting Argument Data Types . . . . . . . . . . . . . . . . . . . . .
Built-In Data Types for Arguments . . . . . . . . . . . . . . . . . . .
Specifying Argument Types with Expressions . . . . . . . . . .
Specifying Simulink Fixed Point Data Properties . . . . . . .

29-64
29-64
29-64
29-66
29-67
29-68
29-68

Size Function Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specifying Argument Size . . . . . . . . . . . . . . . . . . . . . . . . . . .
Inheriting Argument Sizes from Simulink . . . . . . . . . . . . .
Specifying Argument Sizes with Expressions . . . . . . . . . . .

29-72
29-72
29-72
29-73

Add Parameter Arguments . . . . . . . . . . . . . . . . . . . . . . . . . 29-75
Resolve Signal Objects for Output Data . . . . . . . . . . . . . .
Implicit Signal Resolution . . . . . . . . . . . . . . . . . . . . . . . . . .
Eliminating Warnings for Implicit Signal Resolution in the
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Disabling Implicit Signal Resolution for a MATLAB
Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Forcing Explicit Signal Resolution for an Output Data
Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-76
29-76
29-76
29-77
29-77

Types of Structures in MATLAB Function Blocks . . . . . 29-78
Attach Bus Signals to MATLAB Function Blocks . . . . . 29-79
Structure Definitions in Example . . . . . . . . . . . . . . . . . . . . 29-79
Bus Objects Define Structure Inputs and Outputs . . . . . . . 29-79
How Structure Inputs and Outputs Interface with Bus
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-81
Working with Virtual and Nonvirtual Buses . . . . . . . . . . . 29-81

xliv

Contents

Rules for Defining Structures in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-82
Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . 29-83
Create Structures in MATLAB Function Blocks . . . . . . 29-84
Assign Values to Structures and Fields . . . . . . . . . . . . . . 29-86
Initialize a Matrix Using a Non-Tunable Structure
Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-88
Define and Use Structure Parameters . . . . . . . . . . . . . . . 29-91
Defining Structure Parameters . . . . . . . . . . . . . . . . . . . . . . 29-91
FIMATH Properties of Non-Tunable Structure
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-91
Limitations of Structures and Buses in MATLAB
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-93
What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . . 29-94
How MATLAB Function Blocks Implement
Variable-Size Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-95
Enable Support for Variable-Size Data

. . . . . . . . . . . . . . 29-96

Declare Variable-Size Inputs and Outputs . . . . . . . . . . . 29-97
Filter a Variable-Size Signal . . . . . . . . . . . . . . . . . . . . . . . .
About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulink Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Source Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Function Block: uniquify . . . . . . . . . . . . . . . . . . .
MATLAB Function Block: avg . . . . . . . . . . . . . . . . . . . . . . .
Variable-Size Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-98
29-98
29-98
29-99
29-99
29-101
29-102

xlv

Enumerated Types Supported in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-105
Define Enumerated Data Types for MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-106
Add Inputs, Outputs, and Parameters as Enumerated
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-107
Basic Approach for Adding Enumerated Data to
MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . 29-109
Instantiate Enumerated Data in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-110
Control an LED Display . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Class Definition: switchmode . . . . . . . . . . . . . . . . . . . . . . . .
Class Definition: led . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulink Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Function Block: checkState . . . . . . . . . . . . . . . . .
How the Model Displays Enumerated Data . . . . . . . . . . . .

29-111
29-111
29-111
29-112
29-112
29-113
29-114

Operations on Enumerated Data . . . . . . . . . . . . . . . . . . . . 29-115
Using Enumerated Data in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-116
When to Use Enumerated Data . . . . . . . . . . . . . . . . . . . . . . 29-116
Limitations of Enumerated Types . . . . . . . . . . . . . . . . . . . . 29-116
Share Data Globally . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When Do You Need to Use Global Data? . . . . . . . . . . . . . . .
Using Global Data with the MATLAB Function Block . . . .
Choosing How to Store Global Data . . . . . . . . . . . . . . . . . . .
How to Use Data Store Memory Blocks . . . . . . . . . . . . . . . .
How to Use Simulink.Signal Objects . . . . . . . . . . . . . . . . . .
Using Data Store Diagnostics to Detect Memory Access
Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Limitations of Using Shared Data in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

xlvi

Contents

29-117
29-117
29-117
29-118
29-120
29-122
29-124
29-125

Add Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . . .
About Frame-Based Signals . . . . . . . . . . . . . . . . . . . . . . . . .
Supported Types for Frame-Based Data . . . . . . . . . . . . . . .
Adding Frame-Based Data in MATLAB Function Blocks . .
Examples of Frame-Based Signals in MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-126
29-126
29-126
29-127
29-128

Create Custom Block Libraries . . . . . . . . . . . . . . . . . . . . . 29-132
When to Use MATLAB Function Block Libraries . . . . . . . . 29-132
How to Create Custom MATLAB Function Block
Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-132
Example: Creating a Custom Signal Processing Filter Block
Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-133
Code Reuse with Library Blocks . . . . . . . . . . . . . . . . . . . . . 29-145
Debugging MATLAB Function Library Blocks . . . . . . . . . . 29-149
Properties You Can Specialize Across Instances of Library
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-150
Use Traceability in MATLAB Function Blocks . . . . . . . .
Extent of Traceability in MATLAB Function Blocks . . . . .
Traceability Requirements . . . . . . . . . . . . . . . . . . . . . . . . . .
Basic Workflow for Using Traceability . . . . . . . . . . . . . . . .
Tutorial: Using Traceability in a MATLAB Function
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Include MATLAB Code as Comments in Generated
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How to Include MATLAB Code as Comments in the
Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Location of Comments in Generated Code . . . . . . . . . . . . . .
Including MATLAB Function Help Text in the Function
Banner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Limitations of MATLAB Source Code as Comments . . . . .
Enhance Code Readability for MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Requirements for Using Readability Optimizations . . . . . .
Converting If-Elseif-Else Code to Switch-Case
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example of Converting Code for If-Elseif-Else Decision
Logic to Switch-Case Statements . . . . . . . . . . . . . . . . . . .

29-151
29-151
29-151
29-152
29-153

29-156
29-156
29-157
29-160
29-160

29-162
29-162
29-162
29-165

xlvii

Speed Up Simulation with Basic Linear Algebra
Subprograms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
How MATLAB Function Blocks Use the Basic Linear
Algebra Subprograms (BLAS) Library . . . . . . . . . . . . . .
When to Disable BLAS Library Support . . . . . . . . . . . . . . .
How to Disable BLAS Library Support . . . . . . . . . . . . . . . .
Supported Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-171
29-171
29-171
29-172
29-172

Control Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . .
Types of Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . .
When to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . .
How to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . . .

29-173
29-173
29-173
29-174

Track Object Using MATLAB Code . . . . . . . . . . . . . . . . . .
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example: The Kalman Filter . . . . . . . . . . . . . . . . . . . . . . . .
Files for the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tutorial Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Best Practices Used in This Tutorial . . . . . . . . . . . . . . . . . .
Key Points to Remember . . . . . . . . . . . . . . . . . . . . . . . . . . .
Where to Learn More . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-175
29-175
29-176
29-176
29-179
29-181
29-201
29-201
29-201

Filter Audio Signal Using MATLAB Code . . . . . . . . . . . .
Learning Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tutorial Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Example: The LMS Filter . . . . . . . . . . . . . . . . . . . . . . . . . . .
Files for the Tutorial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Tutorial Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

29-203
29-203
29-203
29-204
29-207
29-208

Design Considerations for C/C++ Code
Generation

30

xlviii

Contents

When to Generate Code from MATLAB Algorithms . . .
When Not to Generate Code from MATLAB Algorithms . .

30-2
30-2

Which Code Generation Feature to Use . . . . . . . . . . . . . .

30-4

Prerequisites for C/C++ Code Generation from
MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-6

MATLAB Code Design Considerations for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

30-7
30-8

Expected Differences in Behavior After Compiling
MATLAB Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Why Are There Differences? . . . . . . . . . . . . . . . . . . . . . . . . .
Character Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Order of Evaluation in Expressions . . . . . . . . . . . . . . . . . . .
Termination Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . .
Size of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Floating-Point Numerical Results . . . . . . . . . . . . . . . . . . . .
NaN and Infinity Patterns . . . . . . . . . . . . . . . . . . . . . . . . . .
Code Generation Target . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Class Initial Values . . . . . . . . . . . . . . . . . . . . . . .
Variable-Size Support for Code Generation . . . . . . . . . . . .

30-9
30-9
30-9
30-9
30-10
30-10
30-11
30-11
30-12
30-12
30-12
30-12

MATLAB Language Features Supported for C/C++ Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-13
MATLAB Language Features Not Supported for C/C++
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-14

Functions Supported for Code Generation

31
Functions Supported for Code Generation —
Alphabetical List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31-2

Functions Supported for Code Generation —
Categorical List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Aerospace Toolbox Functions . . . . . . . . . . . . . . . . . . . . . . . .
Arithmetic Operator Functions . . . . . . . . . . . . . . . . . . . . . .
Bit-Wise Operation Functions . . . . . . . . . . . . . . . . . . . . . . .
Casting Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Communications System Toolbox Functions . . . . . . . . . . . .

31-54
31-55
31-55
31-56
31-56
31-57

xlix

Complex Number Functions . . . . . . . . . . . . . . . . . . . . . . . . .
Computer Vision System Toolbox Functions . . . . . . . . . . . .
Data Type Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Derivative and Integral Functions . . . . . . . . . . . . . . . . . . . .
Discrete Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . .
Error Handling Functions . . . . . . . . . . . . . . . . . . . . . . . . . .
Exponential Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filtering and Convolution Functions . . . . . . . . . . . . . . . . . .
Fixed-Point Toolbox Functions . . . . . . . . . . . . . . . . . . . . . . .
Histogram Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Image Processing Toolbox Functions . . . . . . . . . . . . . . . . . .
Input and Output Functions . . . . . . . . . . . . . . . . . . . . . . . .
Interpolation and Computational Geometry . . . . . . . . . . . .
Linear Algebra . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logical Operator Functions . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Compiler Functions . . . . . . . . . . . . . . . . . . . . . . .
Matrix and Array Functions . . . . . . . . . . . . . . . . . . . . . . . . .
Nonlinear Numerical Methods . . . . . . . . . . . . . . . . . . . . . . .
Polynomial Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Relational Operator Functions . . . . . . . . . . . . . . . . . . . . . . .
Rounding and Remainder Functions . . . . . . . . . . . . . . . . . .
Set Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Processing Functions in MATLAB . . . . . . . . . . . . . .
Signal Processing Toolbox Functions . . . . . . . . . . . . . . . . . .
Special Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specialized Math . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Statistical Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Structure Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Trigonometric Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .

31-57
31-58
31-59
31-59
31-60
31-60
31-60
31-61
31-61
31-70
31-70
31-71
31-71
31-71
31-72
31-72
31-73
31-77
31-77
31-77
31-78
31-78
31-79
31-79
31-84
31-84
31-85
31-85
31-86
31-86

System Objects Supported for Code Generation

32
System Objects Supported for Code Generation . . . . . . 32-2
Code Generation for System Objects . . . . . . . . . . . . . . . . . . 32-2
Computer Vision System Toolbox System Objects . . . . . . . 32-2
Communications System Toolbox System Objects . . . . . . . 32-7
DSP System Toolbox System Objects . . . . . . . . . . . . . . . . . . 32-13

l

Contents

Defining MATLAB Variables for C/C++ Code
Generation

33
Variables Definition for Code Generation . . . . . . . . . . . .

33-2

Best Practices for Defining Variables for C/C++ Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Define Variables By Assignment Before Using Them . . . .
Use Caution When Reassigning Variables . . . . . . . . . . . . .
Use Type Cast Operators in Variable Definitions . . . . . . . .
Define Matrices Before Assigning Indexed Variables . . . . .

33-3
33-3
33-6
33-6
33-6

Eliminate Redundant Copies of Variables in Generated
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . .
How to Eliminate Redundant Copies by Defining
Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . .
Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . .
Reassignment of Variable Properties . . . . . . . . . . . . . . . .

33-7
33-7
33-7
33-8
33-9

Define and Initialize Persistent Variables . . . . . . . . . . . . 33-10
Reuse the Same Variable with Different Properties . . .
When You Can Reuse the Same Variable with Different
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When You Cannot Reuse Variables . . . . . . . . . . . . . . . . . . .
Limitations of Variable Reuse . . . . . . . . . . . . . . . . . . . . . . .

33-11
33-11
33-12
33-14

Avoid Overflows in for-Loops . . . . . . . . . . . . . . . . . . . . . . . 33-16
Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . 33-18

li

Defining Data for Code Generation

34
Data Definition for Code Generation . . . . . . . . . . . . . . . .

34-2

Code Generation for Complex Data . . . . . . . . . . . . . . . . .
Restrictions When Defining Complex Variables . . . . . . . . .
Expressions Containing Complex Operands Yield Complex
Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

34-4
34-4

Code Generation for Characters . . . . . . . . . . . . . . . . . . . .

34-6

34-5

Code Generation for Variable-Size Data

35
What Is Variable-Size Data? . . . . . . . . . . . . . . . . . . . . . . . .

35-2

Variable-Size Data Definition for Code Generation . . .

35-3

Bounded Versus Unbounded Variable-Size Data . . . . . .

35-4

Control Memory Allocation of Variable-Size Data . . . . .

35-5

Specify Variable-Size Data Without Dynamic Memory
Allocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Fixing Upper Bounds Errors . . . . . . . . . . . . . . . . . . . . . . . .
Specifying Upper Bounds for Variable-Size Data . . . . . . . .

35-6
35-6
35-6

Variable-Size Data in Code Generation Reports . . . . . .
What Reports Tell You About Size . . . . . . . . . . . . . . . . . . . .
How Size Appears in Code Generation Reports . . . . . . . . .
How to Generate a Code Generation Report . . . . . . . . . . . .

35-10
35-10
35-11
35-11

Define Variable-Size Data for Code Generation . . . . . . . 35-12
When to Define Variable-Size Data Explicitly . . . . . . . . . . 35-12

lii

Contents

Using a Matrix Constructor with Nonconstant
Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-13
Inferring Variable Size from Multiple Assignments . . . . . . 35-13
Defining Variable-Size Data Explicitly Using
coder.varsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-14
C Code Interface for Arrays . . . . . . . . . . . . . . . . . . . . . . . . 35-19
C Code Interface for Statically Allocated Arrays . . . . . . . . 35-19
Troubleshooting Issues with Variable-Size Data . . . . . . 35-20
Diagnosing and Fixing Size Mismatch Errors . . . . . . . . . . . 35-20
Diagnosing and Fixing Errors in Detecting Upper
Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-22
Incompatibilities with MATLAB in Variable-Size
Support for Code Generation . . . . . . . . . . . . . . . . . . . . .
Incompatibility with MATLAB for Scalar Expansion . . . . .
Incompatibility with MATLAB in Determining Size of
Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . . . . .
Incompatibility with MATLAB in Determining Size of
Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Incompatibility with MATLAB in Vector-Vector
Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Incompatibility with MATLAB in Matrix Indexing
Operations for Code Generation . . . . . . . . . . . . . . . . . . .
Dynamic Memory Allocation Not Supported for MATLAB
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35-24
35-24
35-26
35-27
35-28
35-29
35-30

Restrictions on Variable Sizing in Toolbox Functions
Supported for Code Generation . . . . . . . . . . . . . . . . . . . 35-31
Common Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-31
Toolbox Functions with Variable Sizing Restrictions . . . . . 35-32

Code Generation for MATLAB Structures

36
Structure Definition for Code Generation . . . . . . . . . . . .

36-2

liii

Structure Operations Allowed for Code Generation . . .

36-3

Define Scalar Structures for Code Generation . . . . . . . .
Restrictions When Using struct . . . . . . . . . . . . . . . . . . . . .
Restrictions When Defining Scalar Structures by
Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding Fields in Consistent Order on Each Control Flow
Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restriction on Adding New Fields After First Use . . . . . . .

36-4
36-4

Define Arrays of Structures for Code Generation . . . . .
Ensuring Consistency of Fields . . . . . . . . . . . . . . . . . . . . . .
Using repmat to Define an Array of Structures with
Consistent Field Properties . . . . . . . . . . . . . . . . . . . . . . .
Defining an Array of Structures Using Concatenation . . . .

36-7
36-7

Make Structures Persistent . . . . . . . . . . . . . . . . . . . . . . . . .

36-9

36-4
36-4
36-5

36-7
36-8

Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . 36-10
Assign Values to Structures and Fields . . . . . . . . . . . . . . 36-12
Pass Large Structures as Input Parameters . . . . . . . . . . 36-13

Code Generation for Enumerated Data

37

liv

Contents

Enumerated Data Definition for Code Generation . . . .

37-2

Enumerated Types Supported for Code Generation . . .
Enumerated Type Based on Simulink.IntEnumType . . . . .

37-3
37-3

When to Use Enumerated Data for Code Generation . .

37-4

Generate Code for Enumerated Data from MATLAB
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

37-5

Define Enumerated Data for Code Generation . . . . . . .
Naming Enumerated Types for Code Generation . . . . . . . .

37-6
37-7

Instantiate Enumerated Types for Code Generation . .

37-8

Operations on Enumerated Data Allowed for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-9
Assignment Operator, = . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-9
Relational Operators, < > <= >= == ~= . . . . . . . . . . . . . . . . 37-9
Cast Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-10
Indexing Operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-10
Control Flow Statements: if, switch, while . . . . . . . . . . . . . 37-11
Include Enumerated Data in Control Flow
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
if Statement with Enumerated Data Types . . . . . . . . . . . .
switch Statement with Enumerated Data Types . . . . . . . .
while Statement with Enumerated Data Types . . . . . . . . .

37-12
37-12
37-13
37-16

Customize Enumerated Types Based on
Simulink.IntEnumType . . . . . . . . . . . . . . . . . . . . . . . . . . 37-18
Control Names of Enumerated Type Values in
Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-19
Change and Reload Enumerated Data Types . . . . . . . . . 37-21
Restrictions on Use of Enumerated Data in
for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-22
Toolbox Functions That Support Enumerated Types for
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-23

Code Generation for MATLAB Classes

38
MATLAB Classes Definition for Code Generation . . . . .

38-2

lv

Language Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Code Generation Features Not Compatible with Classes . .
Defining Class Properties for Code Generation . . . . . . . . .
Calls to Base Class Constructor . . . . . . . . . . . . . . . . . . . . . .

38-2
38-4
38-5
38-6

Classes That Support Code Generation . . . . . . . . . . . . . .

38-8

Memory Allocation Requirements . . . . . . . . . . . . . . . . . . .

38-9

Generate Code for MATLAB Value Classes . . . . . . . . . . . 38-10
Generate Code for MATLAB Handle Classes and System
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16
MATLAB Classes in Code Generation Reports . . . . . . . .
What Reports Tell You About Classes . . . . . . . . . . . . . . . . .
How Classes Appear in Code Generation Reports . . . . . . .
How to Generate a Code Generation Report . . . . . . . . . . . .

38-19
38-19
38-19
38-21

Troubleshooting Issues with MATLAB Classes . . . . . . . 38-22
Class class does not have a property with name name . . . 38-22

Code Generation for Function Handles

39
Function Handles Definition for Code Generation . . . .

39-2

Define and Pass Function Handles for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

39-3

...

39-5

Function Handle Limitations for Code Generation

lvi

Contents

Defining Functions for Code Generation

40
Specify Variable Numbers of Arguments . . . . . . . . . . . . .

40-2

Supported Index Expressions . . . . . . . . . . . . . . . . . . . . . . .

40-3

Apply Operations to a Variable Number of
Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
When to Force Loop Unrolling . . . . . . . . . . . . . . . . . . . . . . .
Using Variable Numbers of Arguments in a for-Loop . . . .

40-4
40-4
40-5

Implement Wrapper Functions . . . . . . . . . . . . . . . . . . . . .
Passing Variable Numbers of Arguments from One
Function to Another . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

40-7

Pass Property/Value Pairs . . . . . . . . . . . . . . . . . . . . . . . . . .

40-8

40-7

Variable Length Argument Lists for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-10

Calling Functions for Code Generation

41
Resolution of Function Calls in MATLAB Generated
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Key Points About Resolving Function Calls . . . . . . . . . . . .
Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . .
When to Use the Code Generation Path . . . . . . . . . . . . . . .

41-2
41-4
41-4
41-5

Resolution of Files Types on Code Generation Path . . .

41-6

Compilation Directive %#codegen . . . . . . . . . . . . . . . . . . .

41-8

Call Local Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

41-9

lvii

Call Supported Toolbox Functions . . . . . . . . . . . . . . . . . . 41-10
Call MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Declaring MATLAB Functions as Extrinsic Functions . . .
Calling MATLAB Functions Using feval . . . . . . . . . . . . . . .
How MATLAB Resolves Extrinsic Functions During
Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Restrictions on Extrinsic Functions for Code Generation . .
Limit on Function Arguments . . . . . . . . . . . . . . . . . . . . . . .

41-11
41-12
41-16
41-16
41-17
41-19
41-19

Generating Efficient and Reusable Code

42
Unroll for-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42-2

Inline Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

42-3

Eliminate Redundant Copies of Function Inputs . . . . .

42-4

Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . .

42-6

Managing Data
Working with Data

43
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Types Supported by Simulink . . . . . . . . . . . . . . . . . . .
Fixed-Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Support for Data and Numeric Signal Types . . . . . .
Create Signals of a Specific Data Type . . . . . . . . . . . . . . . .

lviii

Contents

43-2
43-2
43-3
43-4
43-6
43-6
43-7
43-7

Specify Block Output Data Types . . . . . . . . . . . . . . . . . . . .
Specify Data Types Using Data Type Assistant . . . . . . . . .
Display Port Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Type Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Typing Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Typecast Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Validate a Floating-Point Embedded Model . . . . . . . . . . . .
Validate a Single-Precision Model . . . . . . . . . . . . . . . . . . . .

43-8
43-15
43-27
43-28
43-28
43-29
43-29
43-30

Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Data Object Classes . . . . . . . . . . . . . . . . . . . . . . . . . .
About Data Object Methods . . . . . . . . . . . . . . . . . . . . . . . . .
Using the Model Explorer to Create Data Objects . . . . . . .
About Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Changing Object Properties . . . . . . . . . . . . . . . . . . . . . . . . .
Handle Versus Value Classes . . . . . . . . . . . . . . . . . . . . . . . .
Comparing Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Saving and Loading Data Objects . . . . . . . . . . . . . . . . . . . .
Using Data Objects in Simulink Models . . . . . . . . . . . . . . .
Creating Persistent Data Objects . . . . . . . . . . . . . . . . . . . .
Data Object Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43-37
43-37
43-38
43-40
43-42
43-42
43-44
43-46
43-46
43-46
43-47
43-47

Define Level-2 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . 43-53
Supported Property Types

. . . . . . . . . . . . . . . . . . . . . . . . . 43-58

Upgrade Level-1 Data Classes . . . . . . . . . . . . . . . . . . . . . . . 43-59
Infrastructure for Extending Simulink Data Classes . .
Disadvantages of Level-1 Data Class Infrastructure . . . . .
Features of Level-2 Data Class Infrastructure . . . . . . . . . .
Other Differences between Level-1 and Level-2 Data
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43-61
43-61
43-61

Define Level-1 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . .
About Packages and Data Classes . . . . . . . . . . . . . . . . . . . .
Define Level-1 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enumerated Property Types . . . . . . . . . . . . . . . . . . . . . . . .
Enabling Custom Storage Classes . . . . . . . . . . . . . . . . . . . .

43-63
43-63
43-64
43-67
43-76
43-79

43-62

lix

Associating User Data with Blocks . . . . . . . . . . . . . . . . . . 43-80
Design Minimum and Maximum . . . . . . . . . . . . . . . . . . . . 43-81
Use of Design Minimum and Maximum . . . . . . . . . . . . . . . 43-81
Valid Values for Design Minimum and Maximum . . . . . . . 43-81

Enumerations and Modeling

44

lx

Contents

About Simulink Enumerations . . . . . . . . . . . . . . . . . . . . . .

44-2

Define Simulink Enumerations . . . . . . . . . . . . . . . . . . . . .
Workflow to Define a Simulink Enumeration . . . . . . . . . . .
Create Simulink Enumeration Class . . . . . . . . . . . . . . . . . .
Customize Simulink Enumeration . . . . . . . . . . . . . . . . . . . .
Save Enumeration in a MATLAB File . . . . . . . . . . . . . . . . .
Change and Reload Enumerations . . . . . . . . . . . . . . . . . . . .
Import Enumerations Defined Externally to MATLAB . . .

44-3
44-3
44-3
44-4
44-7
44-7
44-8

Use Enumerated Data in Simulink Models . . . . . . . . . . .
Simulate with Enumerations . . . . . . . . . . . . . . . . . . . . . . . .
Specify Enumerations as Data Types . . . . . . . . . . . . . . . . .
Get Information About Enumerations . . . . . . . . . . . . . . . . .
Enumeration Value Display . . . . . . . . . . . . . . . . . . . . . . . . .
Instantiate Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . .
Enumerated Values in Computation . . . . . . . . . . . . . . . . . .

44-10
44-10
44-12
44-13
44-13
44-15
44-19

Simulink Constructs that Support Enumerations . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Block Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Class Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logging Enumerated Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Importing Enumerated Data . . . . . . . . . . . . . . . . . . . . . . . .

44-22
44-22
44-22
44-24
44-24
44-24

Simulink Enumeration Limitations . . . . . . . . . . . . . . . . .
Enumerations and Scopes . . . . . . . . . . . . . . . . . . . . . . . . . .
Enumerated Types for Switch Blocks . . . . . . . . . . . . . . . . .
Nonsupport of Enumerations . . . . . . . . . . . . . . . . . . . . . . . .

44-25
44-25
44-25
44-25

Importing and Exporting Simulation Data

45
Using Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Working with Simulation Data . . . . . . . . . . . . . . . . . . . . . .

45-3
45-3

Export Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Approaches for Exporting Signal Data . . . . . . . . . . . . . . . .
Enable Simulation Data Export . . . . . . . . . . . . . . . . . . . . . .
View Logged Simulation Data With the Simulation Data
Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-4
45-4
45-4
45-6

Data Format for Exported Simulation Data . . . . . . . . . .
Data Format for Block-Based Exported Data . . . . . . . . . . .
Data Format for Model-Based Exported Data . . . . . . . . . . .
Signal Logging Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logged Data Store Format . . . . . . . . . . . . . . . . . . . . . . . . . .
State and Output Data Format . . . . . . . . . . . . . . . . . . . . . .

45-8
45-8
45-8
45-8
45-9
45-9

45-7

Limit Amount of Exported Data . . . . . . . . . . . . . . . . . . . . . 45-14
Decimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-14
Limit Data Points to Last . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-14
Control Samples to Export for Variable-Step Solvers . .
Output Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Refine Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Produce Additional Output . . . . . . . . . . . . . . . . . . . . . . . . . .
Produce Specified Output Only . . . . . . . . . . . . . . . . . . . . . .

45-16
45-16
45-16
45-17
45-18

Export Signal Data Using Signal Logging . . . . . . . . . . . .
Signal Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Logging Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Logging Limitations . . . . . . . . . . . . . . . . . . . . . . . . .

45-19
45-19
45-19
45-20

Configure a Signal for Signal Logging . . . . . . . . . . . . . . .
Enable Logging for a Signal . . . . . . . . . . . . . . . . . . . . . . . . .
Specify Logging Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Limit the Data Logged for a Signal . . . . . . . . . . . . . . . . . . .

45-21
45-21
45-23
45-25

lxi

View Signal Logging Configuration . . . . . . . . . . . . . . . . .
Approaches for Viewing the Signal Logging
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Simulink Editor to View Signal Logging
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Signal Logging Selector to View Signal Logging
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Model Explorer to View Signal Logging
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-27

Enable Signal Logging for a Model . . . . . . . . . . . . . . . . . .
Enable and Disable Logging Globally for a Model . . . . . . .
Specify the Signal Logging Data Format . . . . . . . . . . . . . . .
Specify a Name for the Signal Logging Data . . . . . . . . . . . .

45-34
45-34
45-34
45-40

Override Signal Logging Settings . . . . . . . . . . . . . . . . . . .
Benefits of Overriding Signal Logging Settings . . . . . . . . .
Two Interfaces for Overriding Signal Logging Settings . . .
Scope of Signal Logging Setting Overrides . . . . . . . . . . . . .
Signal Logging Selector . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Command-Line Interface for Overriding Signal Logging
Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-41
45-41
45-41
45-42
45-42

Access Signal Logging Data . . . . . . . . . . . . . . . . . . . . . . . . .
View Signal Logging Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Logging Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Logged Signal Data with the Simulation Data
Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programmatically Access Logged Signal Data Saved in
Dataset Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Programmatically Access Logged Signal Data Saved in
ModelDataLogs Format . . . . . . . . . . . . . . . . . . . . . . . . . .

45-53
45-53
45-54

Techniques for Importing Signal Data . . . . . . . . . . . . . . .
Signal Data Import Techniques Summary . . . . . . . . . . . . .
Comparison of Techniques . . . . . . . . . . . . . . . . . . . . . . . . . .
Time and Signal Values for Imported Data . . . . . . . . . . . . .

45-61
45-61
45-62
45-64

45-27
45-28
45-30
45-32

45-48

45-54
45-55
45-57

Import Data to Model a Continuous Plant . . . . . . . . . . . . 45-67
Share Simulation Data Across Models . . . . . . . . . . . . . . . . 45-67
Example of Importing Data to Model a Continuous
Plant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-67

lxii

Contents

Import Data to Test a Discrete Algorithm . . . . . . . . . . . . 45-70
Specify a Signal-Only Structure . . . . . . . . . . . . . . . . . . . . . . 45-70
Example of Importing Data to Test a Discrete Algorithm . . 45-70
Import Data for an Input Test Case . . . . . . . . . . . . . . . . .
Guidelines for Importing a Test Case . . . . . . . . . . . . . . . . .
Example of Test Case Data . . . . . . . . . . . . . . . . . . . . . . . . .
Use From Workspace Block to Import an Input Test
Case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Use Signal Builder Block to Import an Input Test Case . .

45-71
45-71
45-71
45-72
45-73

Import Signal Logging Data . . . . . . . . . . . . . . . . . . . . . . . . 45-75
Import Data to Root-Level Input Ports . . . . . . . . . . . . . .
Root-Level Input Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Enable Data Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Import Bus Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-77
45-77
45-77
45-77
45-80

Import and Map Data to Root-Level Inports . . . . . . . . . .
MAT-File for Import and Mapping . . . . . . . . . . . . . . . . . . . .
Import and Map Signal Data . . . . . . . . . . . . . . . . . . . . . . . .
Import and Map Bus Data . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Custom Mapping File Function . . . . . . . . . . . . . . . .

45-81
45-83
45-85
45-89
45-95

Import MATLAB timeseries Data . . . . . . . . . . . . . . . . . . . . 45-98
Specify Time Dimension . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-98
Models with Multiple Root Inport Blocks . . . . . . . . . . . . . . 45-99
Import Structures of timeseries Objects for Buses . . . .
Define Structure of MATLAB timeseries Objects for a Bus
Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Convert Simulink.TsArray Objects . . . . . . . . . . . . . . . . . . .
Use a Structure of MATLAB timeseries Objects to Import
Bus Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-100
45-100
45-100
45-101

Import Simulink.Timeseries and Simulink.TsArray
Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-104
Use MATLAB Timeseries for New Models . . . . . . . . . . . . . 45-104
Simulink.TsArray Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-104

lxiii

Import Data Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-105
Data Array Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-105
Specify the Input Expression . . . . . . . . . . . . . . . . . . . . . . . . 45-105
Import MATLAB Time Expression Data . . . . . . . . . . . . . . 45-107
Specify the Input Expression . . . . . . . . . . . . . . . . . . . . . . . . 45-107
Import Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
One Structure for All Ports or a Structure for Each Port . .
Specify Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specify Time Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Examples of Specifying Signal and Time Data . . . . . . . . . .

45-108
45-108
45-109
45-109
45-110
45-111

Import and Export States . . . . . . . . . . . . . . . . . . . . . . . . . .
State Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Save State Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Import Initial States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Import and Export State Information for Referenced
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

45-113
45-113
45-113
45-118
45-120

Working with Data Stores

46
About Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Local and Global Data Stores . . . . . . . . . . . . . . . . . . . . . . . .
When to Use a Data Store . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Access Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Configure Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Stores with Buses and Arrays of Buses . . . . . . . . . . .

46-2
46-2
46-3
46-3
46-4
46-5
46-5

Data Stores with Data Store Memory Blocks . . . . . . . . .
Creating the Data Store . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Specifying Data Store Memory Block Attributes . . . . . . . .

46-8
46-8
46-8

Data Stores with Signal Objects . . . . . . . . . . . . . . . . . . . . . 46-12
Creating the Data Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46-12

lxiv

Contents

Local and Global Data Stores . . . . . . . . . . . . . . . . . . . . . . . . 46-12
Specifying Signal Object Data Store Attributes . . . . . . . . . 46-12
Access Data Stores with Simulink Blocks . . . . . . . . . . . .
Writing to a Data Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Reading from a Data Store . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing a Global Data Store . . . . . . . . . . . . . . . . . . . . . . .
Accessing Specific Bus and Matrix Elements . . . . . . . . . . .

46-14
46-14
46-14
46-15
46-16

Data Store Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Local Data Store Example . . . . . . . . . . . . . . . . . . . . . . . . . .
Global Data Store Example . . . . . . . . . . . . . . . . . . . . . . . . .

46-23
46-23
46-23
46-24

Log Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logging Local and Global Data Store Values . . . . . . . . . . .
Supported Data Types, Dimensions, and Complexity for
Logging Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Data Store Logging Limitations . . . . . . . . . . . . . . . . . . . . . .
Logging Data Stores Created with a Data Store Memory
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Logging Icon for the Data Store Memory Block . . . . . . . . .
Logging Data Stores Created with a Simulink.Signal
Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Accessing Data Store Logging Data . . . . . . . . . . . . . . . . . . .

46-26
46-26

Order Data Store Access . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Data Store Access Order . . . . . . . . . . . . . . . . . . . . . .
Ordering Access Using Function Call Subsystems . . . . . . .
Ordering Access Using Block Priorities . . . . . . . . . . . . . . . .

46-31
46-31
46-31
46-35

Data Store Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Data Store Diagnostics . . . . . . . . . . . . . . . . . . . . . . .
Detecting Access Order Errors . . . . . . . . . . . . . . . . . . . . . . .
Detecting Multitasking Access Errors . . . . . . . . . . . . . . . . .
Detecting Duplicate Name Errors . . . . . . . . . . . . . . . . . . . .
Data Store Diagnostics in the Model Advisor . . . . . . . . . . .

46-38
46-38
46-38
46-41
46-43
46-45

46-26
46-27
46-27
46-28
46-28
46-29

Data Stores and Software Verification . . . . . . . . . . . . . . . 46-46

lxv

Managing Signals
Working with Signals

47
Signal Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Line Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Testing Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47-2
47-2
47-3
47-4
47-5
47-6

Signal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Summary of Signal Types . . . . . . . . . . . . . . . . . . . . . . . . . . .
Control Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Composite (Bus) Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47-8
47-8
47-9
47-9

Virtual Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11
About Virtual Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11
Mux Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11
Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Dimensions, Size, and Width . . . . . . . . . . . . . . . . . .
Complex Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initializing Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . .
Viewing Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Displaying Signal Values in Model Diagrams . . . . . . . . . . .
Exporting Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47-15
47-15
47-15
47-16
47-16
47-17
47-17
47-18

Signal Names and Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-19
Signal Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-19
Signal Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-22
Signal Label Propagation . . . . . . . . . . . . . . . . . . . . . . . . . .
Propagated Signal Labels . . . . . . . . . . . . . . . . . . . . . . . . . . .
Blocks That Support Signal Label Propagation . . . . . . . . .
Display Propagated Signal Labels . . . . . . . . . . . . . . . . . . . .
How Simulink Propagates Signal Labels . . . . . . . . . . . . . .

lxvi

Contents

47-24
47-24
47-25
47-25
47-26

Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-34
About Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-34
Simulink Blocks that Support Multidimensional Signals . . 47-35
Determine Output Signal Dimensions . . . . . . . . . . . . . . .
About Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . .
Determining the Output Dimensions of Source Blocks . . .
Determining the Output Dimensions of Nonsource
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal and Parameter Dimension Rules . . . . . . . . . . . . . . .
Scalar Expansion of Inputs and Parameters . . . . . . . . . . . .

47-36
47-36
47-36

Display Signal Sources and Destinations . . . . . . . . . . . .
About Signal Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . .
Highlighting Signal Sources . . . . . . . . . . . . . . . . . . . . . . . . .
Highlighting Signal Destinations . . . . . . . . . . . . . . . . . . . . .
Removing Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resolving Incomplete Highlighting to Library Blocks . . . .

47-41
47-41
47-41
47-42
47-43
47-43

Signal Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Signal Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Blocks That Allow Signal Range Specification . . . . . . . . . .
Specifying Ranges for Signals . . . . . . . . . . . . . . . . . . . . . . .
Checking for Signal Range Errors . . . . . . . . . . . . . . . . . . . .

47-44
47-44
47-44
47-45
47-46

Initialize Signals and Discrete States . . . . . . . . . . . . . . . .
About Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Block Parameters to Initialize Signals and Discrete
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Signal Objects to Initialize Signals and Discrete
States . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Signal Objects to Tune Initial Values . . . . . . . . . . . .
Example: Using a Signal Object to Initialize a Subsystem
Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Initialization Behavior Summary for Signal Objects . . . . .

47-51
47-51

Test Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
What Is a Test Point? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Designating a Signal as a Test Point . . . . . . . . . . . . . . . . . .
Displaying Test Point Indicators . . . . . . . . . . . . . . . . . . . . .

47-58
47-58
47-58
47-60

47-37
47-37
47-38

47-52
47-52
47-53
47-55
47-56

lxvii

Display Signal Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . .
Ports & Signals Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Port Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Design Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal to Object Resolution Indicator . . . . . . . . . . . . . . . . .
Wide Nonscalar Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47-61
47-61
47-62
47-62
47-63
47-64
47-65

Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Builder Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Signal Group Sets . . . . . . . . . . . . . . . . . . . . . . . . .
Editing Waveforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Signal Builder Time Range . . . . . . . . . . . . . . . . . . . . . . . . .
Exporting Signal Group Data . . . . . . . . . . . . . . . . . . . . . . . .
Printing, Exporting, and Copying Waveforms . . . . . . . . . .
Simulating with Signal Groups . . . . . . . . . . . . . . . . . . . . . .
Simulation Options Dialog Box . . . . . . . . . . . . . . . . . . . . . .

47-66
47-66
47-66
47-72
47-102
47-108
47-109
47-109
47-110
47-111

Using Composite Signals

48
About Composite Signals . . . . . . . . . . . . . . . . . . . . . . . . . . .
Composite Signal Terminology . . . . . . . . . . . . . . . . . . . . . . .
Types of Simulink Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . .
View Information about Buses . . . . . . . . . . . . . . . . . . . . . . .
Buses and Muxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bus Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48-2
48-2
48-3
48-3
48-7
48-8
48-8

Virtual and Nonvirtual Buses . . . . . . . . . . . . . . . . . . . . . . .
Virtual and Nonvirtual Buses . . . . . . . . . . . . . . . . . . . . . . .
Choosing Between Virtual and Nonvirtual Buses . . . . . . .
Creating Nonvirtual Buses . . . . . . . . . . . . . . . . . . . . . . . . . .
Nonvirtual Bus Sample Times . . . . . . . . . . . . . . . . . . . . . . .
Automatic Bus Conversion . . . . . . . . . . . . . . . . . . . . . . . . . .
Explicit Bus Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48-10
48-10
48-11
48-12
48-13
48-13
48-13

Create and Access a Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-15

lxviii

Contents

Nest Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-17
Circular Bus Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-18
Bus-Capable Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-19
Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Bus Object Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Associating Bus Objects with Simulink Blocks . . . . . . . . . .

48-20
48-20
48-21
48-21

Bus Object API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-23
Manage Bus Objects with the Bus Editor . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Open the Bus Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Display Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Bus Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Nest Bus Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change Bus Entities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Export Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Import Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Close the Bus Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48-24
48-24
48-25
48-26
48-29
48-32
48-35
48-38
48-42
48-44
48-44

Store and Load Bus Objects . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
MATLAB Data Files (MAT-Files) . . . . . . . . . . . . . . . . . . . .
Database or Other External Source Files . . . . . . . . . . . . . .

48-46
48-46
48-47
48-47

Map Bus Objects to Models . . . . . . . . . . . . . . . . . . . . . . . . . 48-48
Use a Rigorous Naming Convention . . . . . . . . . . . . . . . . . . 48-48
Filter Displayed Bus Objects . . . . . . . . . . . . . . . . . . . . . . . .
Filter by Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Filter by Relationship . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change Filtered Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Clear the Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48-49
48-50
48-51
48-53
48-54

Customize Bus Object Import and Export . . . . . . . . . . . . 48-55
Prerequisites for Customization . . . . . . . . . . . . . . . . . . . . . . 48-56

lxix

Writing a Bus Object Import Function . . . . . . . . . . . . . . . .
Writing a Bus Object Export Function . . . . . . . . . . . . . . . .
Registering Customizations . . . . . . . . . . . . . . . . . . . . . . . . .
Changing Customizations . . . . . . . . . . . . . . . . . . . . . . . . . . .

48-56
48-57
48-58
48-59

Connect Buses to Inports and Outports . . . . . . . . . . . . . .
Connect Buses to Root Level Inports . . . . . . . . . . . . . . . . . .
Connect Buses to Root Level Outports . . . . . . . . . . . . . . . .
Connect Buses to Nonvirtual Inports . . . . . . . . . . . . . . . . . .
Connect Buses to Model, Stateflow, and MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Connect Multi-Rate Buses to Referenced Models . . . . . . . .

48-61
48-61
48-61
48-61

Specify Initial Conditions for Bus Signals . . . . . . . . . . . .
Bus Signal Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create Initial Condition (IC) Structures . . . . . . . . . . . . . . .
Three Ways to Initialize Bus Signals Using Block
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Setting Diagnostics to Support Bus Signal Initialization . .

48-65
48-65
48-67

Combine Buses into an Array of Buses . . . . . . . . . . . . . . .
What Is an Array of Buses? . . . . . . . . . . . . . . . . . . . . . . . . .
Benefits of an Array of Buses . . . . . . . . . . . . . . . . . . . . . . . .
Blocks That Support Arrays of Buses . . . . . . . . . . . . . . . . .
Array of Buses Limitations . . . . . . . . . . . . . . . . . . . . . . . . . .
Define an Array of Buses . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using an Array of Buses in a Model . . . . . . . . . . . . . . . . . . .
Generated Code for an Array of Buses . . . . . . . . . . . . . . . . .
Convert a Model to Use an Array of Buses . . . . . . . . . . . . .

48-77
48-77
48-79
48-80
48-81
48-83
48-86
48-89
48-90

Bus Data Crossing Model Reference Boundaries

48-64
48-64

48-72
48-76

. . . . . 48-93

Buses and Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-94
Avoid Mux/Bus Mixtures . . . . . . . . . . . . . . . . . . . . . . . . . . .
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Using Diagnostics for Mux/Bus Mixtures . . . . . . . . . . . . . .
Using the Model Advisor for Mux/Bus Mixtures . . . . . . . . .
Correcting Buses Used as Muxes . . . . . . . . . . . . . . . . . . . . .
Bus to Vector Block Compatibility Issues . . . . . . . . . . . . . .
Avoiding Mux/Bus Mixtures When Developing Models . . .

lxx

Contents

48-95
48-95
48-96
48-100
48-101
48-103
48-104

Buses in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-105
Composite Signal Limitations . . . . . . . . . . . . . . . . . . . . . . . 48-106

Working with Variable-Size Signals

49
Variable-Size Signal Basics . . . . . . . . . . . . . . . . . . . . . . . . .
About Variable-Size Signals . . . . . . . . . . . . . . . . . . . . . . . . .
Creating Variable-Size Signals . . . . . . . . . . . . . . . . . . . . . .
How Variable-Size Signals Propagate . . . . . . . . . . . . . . . . .
Empty Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Subsystem Initialization of Variable-Size Signals . . . . . . .

49-2
49-2
49-2
49-3
49-4
49-4

Simulink Models Using Variable-Size Signals . . . . . . . . 49-6
Variable-Size Signal Generation and Operations . . . . . . . . 49-6
Variable-Size Signal Length Adaptation . . . . . . . . . . . . . . . 49-10
Mode-Dependent Variable-Size Signals . . . . . . . . . . . . . . . . 49-14
S-Functions Using Variable-Size Signals . . . . . . . . . . . . . 49-20
Level-2 MATLAB S-Function with Variable-Size
Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49-20
C S-Function with Variable-Size Signals . . . . . . . . . . . . . . 49-21
Simulink Block Support for Variable-Size Signals . . . .
Simulink Block Data Type Support . . . . . . . . . . . . . . . . . . .
Conditionally Executed Subsystem Blocks . . . . . . . . . . . . .
Switching Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

49-23
49-23
49-23
49-24

Variable-Size Signal Limitations . . . . . . . . . . . . . . . . . . . . 49-26

lxxi

Customizing Simulink Environment and
Printed Models
Customizing the Simulink User Interface

50
Add Items to Model Editor Menus . . . . . . . . . . . . . . . . . . .
About Adding Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Code for Adding Menu Items . . . . . . . . . . . . . . . . . . . . . . . .
Define Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Register Menu Customizations . . . . . . . . . . . . . . . . . . . . . .
Callback Info Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Debugging Custom Menu Callbacks . . . . . . . . . . . . . . . . . .
Menu Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50-2
50-2
50-2
50-4
50-10
50-11
50-11
50-11

Disable and Hide Model Editor Menu Items . . . . . . . . . .
About Disabling and Hiding Model Editor Menu Items . . .
Example: Disabling the New Model Command on the
Simulink Editor’s File Menu . . . . . . . . . . . . . . . . . . . . . .
Creating a Filter Function . . . . . . . . . . . . . . . . . . . . . . . . . .
Registering a Filter Function . . . . . . . . . . . . . . . . . . . . . . . .

50-16
50-16

Disable and Hide Dialog Box Controls . . . . . . . . . . . . . . .
About Disabling and Hiding Controls . . . . . . . . . . . . . . . . .
Disable a Button on a Dialog Box . . . . . . . . . . . . . . . . . . . .
Write Control Customization Callback Functions . . . . . . .
Dialog Box Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Dialog Box and Widget IDs . . . . . . . . . . . . . . . . . . . . . . . . . .
Register Control Customization Callback Functions . . . . .

50-18
50-18
50-19
50-20
50-20
50-21
50-22

Customize the Library Browser . . . . . . . . . . . . . . . . . . . . .
Reorder Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Disable and Hide Libraries . . . . . . . . . . . . . . . . . . . . . . . . . .
Customize the Library Browser Menu . . . . . . . . . . . . . . . . .

50-24
50-24
50-24
50-25

50-16
50-16
50-17

Registering Customizations . . . . . . . . . . . . . . . . . . . . . . . . 50-27
About Registering User Interface Customizations . . . . . . . 50-27
Customization Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-27

lxxii

Contents

PrintFrame Editor

51
PrintFrame Editor Overview . . . . . . . . . . . . . . . . . . . . . . .
About the Print Frame Editor . . . . . . . . . . . . . . . . . . . . . . .
What PrintFrames Are . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Start the PrintFrame Editor . . . . . . . . . . . . . . . . . . . . . . . .
Help for the PrintFrame Editor . . . . . . . . . . . . . . . . . . . . . .
Close the PrintFrame Editor . . . . . . . . . . . . . . . . . . . . . . . .
Print Frame Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51-2
51-2
51-3
51-6
51-7
51-7
51-7

Design the Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Before You Begin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variable and Static Information . . . . . . . . . . . . . . . . . . . . .
Single Use or Multiple Use Print Frames . . . . . . . . . . . . . .

51-8
51-8
51-8
51-8

Specify the Print Frame Page Setup . . . . . . . . . . . . . . . . .

51-9

Create Borders (Rows and Cells) . . . . . . . . . . . . . . . . . . . .
First Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add and Remove Rows . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Add and Remove Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Resize Rows and Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print Frame Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

51-11
51-11
51-11
51-12
51-12
51-12

Add Information to Cells . . . . . . . . . . . . . . . . . . . . . . . . . . .
Adding Information to Cells . . . . . . . . . . . . . . . . . . . . . . . . .
Text Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Variable Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Multiple Entries in a Cell . . . . . . . . . . . . . . . . . . . . . . . . . . .

51-14
51-14
51-15
51-15
51-16

Change Information in Cells . . . . . . . . . . . . . . . . . . . . . . . .
Align the Information in a Cell . . . . . . . . . . . . . . . . . . . . . .
Edit Text Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Remove and Copy Entries . . . . . . . . . . . . . . . . . . . . . . . . . . .
Change the Font Characteristics . . . . . . . . . . . . . . . . . . . . .

51-18
51-18
51-18
51-19
51-20

Save and Open Print Frames . . . . . . . . . . . . . . . . . . . . . . . 51-22
Save a Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-22
Open a Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-22

lxxiii

Print Block Diagrams with Print Frames . . . . . . . . . . . . 51-23
Create and Use a Print Frame . . . . . . . . . . . . . . . . . . . . . .
About the Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Create the Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Print the Block Diagram with the Print Frame . . . . . . . . .

51-26
51-26
51-27
51-30

Running Models on Target Hardware
About Run on Target Hardware Feature

52
About Run on Target Hardware Feature . . . . . . . . . . . . .

52-2

Work with Arduino Hardware

53
Install Support for Arduino Hardware . . . . . . . . . . . . . . .

53-2

Open Block Libraries for Arduino Hardware . . . . . . . . . 53-10
From the Command Line . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-10
From the Simulink Library Browser . . . . . . . . . . . . . . . . . . 53-11
Run Model on Arduino Hardware . . . . . . . . . . . . . . . . . . . 53-13
Prepare Models That Use Model Reference . . . . . . . . . . . . . 53-14
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-14
Tune and Monitor Models Running on Arduino Mega
2560 Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Your Model in External Mode . . . . . . . . . . . . . . . . . . .
Stop External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

53-15
53-15
53-16
53-18

Use Serial Communications with Arduino Hardware . . 53-19

lxxiv

Contents

Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-19
Transmit Serial Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-20
Receive Serial Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-21
Detect and Fix Task Overruns on Arduino Hardware . . 53-22
Troubleshoot Running Models on Arduino
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-24
Block Produces Zeros in Simulation . . . . . . . . . . . . . . . . . . . 53-24
“Could not automatically set host COM port” . . . . . . . . . . . 53-24
Configure Host COM Port Manually . . . . . . . . . . . . . . . . . 53-26

Work with BeagleBoard Hardware

54
Install Support for BeagleBoard Hardware . . . . . . . . . .

54-2

Replace Firmware on BeagleBoard Hardware . . . . . . . .

54-9

Choose the Type of Serial Cable . . . . . . . . . . . . . . . . . . . . . 54-24
Connect to Serial Port on BeagleBoard Hardware . . . . 54-25
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-29
Configure Network Connection with BeagleBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-30
Get IP Address of BeagleBoard Hardware

. . . . . . . . . . . 54-34

Open Block Library for BeagleBoard Hardware . . . . . . 54-36
Run Model on BeagleBoard Hardware . . . . . . . . . . . . . . . 54-39
Prepare Models That Use Model Reference . . . . . . . . . . . . . 54-40
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-41

lxxv

Tune and Monitor Model Running on BeagleBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Your Simulink Model in External Mode . . . . . . . . . . .
Stop External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

54-42
54-42
54-43
54-45

Detect and Fix Task Overruns on BeagleBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-46

Work with LEGO MINDSTORMS NXT Hardware

55
Install Support for LEGO MINDSTORMS NXT
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

55-2

Replace Firmware on NXT Brick . . . . . . . . . . . . . . . . . . . .

55-7

Open Block Library for LEGO MINDSTORMS NXT
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55-11
Run Model on NXT Brick . . . . . . . . . . . . . . . . . . . . . . . . . . . 55-14
Prepare Models That Use Model Reference . . . . . . . . . . . . . 55-15
Tune Parameters and Monitor Data in a Model Running
on NXT Brick . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Your Simulink Model in External Mode . . . . . . . . . . .
Stop External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Set COM Port Number Manually . . . . . . . . . . . . . . . . . . . . .

55-16
55-16
55-17
55-18
55-19

Detect and Fix Task Overruns on NXT Brick . . . . . . . . . 55-22
Exchange Data Between Two NXT Bricks . . . . . . . . . . . .
Tips for Use Bluetooth Blocks . . . . . . . . . . . . . . . . . . . . . . .
Add Bluetooth Blocks to your Models . . . . . . . . . . . . . . . . .
Configure Bluetooth Slave . . . . . . . . . . . . . . . . . . . . . . . . . .
Configure Bluetooth Master . . . . . . . . . . . . . . . . . . . . . . . . .

lxxvi

Contents

55-23
55-23
55-23
55-27
55-28

Set Up A Bluetooth Connection . . . . . . . . . . . . . . . . . . . . . 55-31

Work with PandaBoard Hardware

56
Install Support for PandaBoard Hardware . . . . . . . . . . .

56-2

Replace Firmware on PandaBoard Hardware . . . . . . . .

56-9

Choose the Type of Serial Cable . . . . . . . . . . . . . . . . . . . . . 56-22
Connect to Serial Port on PandaBoard Hardware . . . . 56-23
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56-27
Configure Network Connection with PandaBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56-28
Get IP Address of PandaBoard Hardware . . . . . . . . . . . . 56-32
Open Block Library for PandaBoard Hardware . . . . . . 56-35
Run Model on PandaBoard Hardware . . . . . . . . . . . . . . . 56-38
Prepare Models That Use Model Reference . . . . . . . . . . . . . 56-39
See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56-40
Tune and Monitor Model Running on PandaBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
About External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Run Your Simulink Model in External Mode . . . . . . . . . . .
Stop External Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

56-41
56-41
56-42
56-44

Detect and Fix Task Overruns on PandaBoard
Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56-45
Access the Linux Desktop Directly Using Desktop
Computer Peripherals . . . . . . . . . . . . . . . . . . . . . . . . . . . 56-46

lxxvii

Access the Linux Desktop Remotely Using VNC . . . . . . 56-48
Configure Wi-Fi on PandaBoard Hardware . . . . . . . . . . 56-50

Examples

A

lxxviii

Contents

Simulink Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-2

How Simulink Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-3

Creating a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-4

Executing Commands From Models . . . . . . . . . . . . . . . . .

A-5

Working with Lookup Tables . . . . . . . . . . . . . . . . . . . . . . .

A-6

Creating Block Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-7

Creating Custom Simulink Blocks . . . . . . . . . . . . . . . . . . .

A-8

Working with Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-9

Data Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

A-10

Code Generation for Variable-Size Data . . . . . . . . . . . . .

A-11

Code Generation for Structures . . . . . . . . . . . . . . . . . . . . .

A-12

Code Generation for Enumerated Data . . . . . . . . . . . . . .

A-13

Code Generation for Function Handles . . . . . . . . . . . . . .

A-14

Using Variable-Length Argument Lists . . . . . . . . . . . . . .

A-15

Optimizing Generated Code . . . . . . . . . . . . . . . . . . . . . . . .

A-16

Index

lxxix

lxxx

Contents

Introduction to Simulink
• Chapter 1, “Simulink Basics”
• Chapter 2, “Simulation Stepping”
• Chapter 3, “How Simulink Works”

1
Simulink Basics
The following sections explain how to perform basic tasks when using the
Simulink® product.
• “Start the Simulink Software” on page 1-2
• “Open a Model” on page 1-4
• “Load a Model” on page 1-7
• “Save a Model” on page 1-8
• “Simulink Editor” on page 1-17
• “Zoom and Pan Block Diagrams” on page 1-23
• “Update a Block Diagram” on page 1-25
• “Copy Models to Third-Party Applications” on page 1-27
• “Print a Block Diagram” on page 1-28
• “Generate a Model Report” on page 1-36
• “End a Simulink Session” on page 1-40
• “Keyboard and Mouse Shortcuts for Simulink” on page 1-41
• “Simulink Demos Are Now Called Examples” on page 1-44

1

Simulink® Basics

Start the Simulink Software
Open the MATLAB Software
To start the Simulink software, first start the MATLAB® technical computing
environment. For details about starting MATLAB, see “Starting and Exiting
the MATLAB Program”.

Open the Library Browser
To start Simulink Library Browser from MATLAB, use one of these
approaches:
• On the MATLAB toolbar, click the Simulink button (

).

• At the MATLAB prompt, enter the simulink command.
The Library Browser opens. It displays a tree-structured view of the Simulink
block libraries installed on your system. The Simulink library window
displays icons representing the pre-installed block libraries.

1-2

Start the Simulink® Software

Note On computers running the Windows® operating system, you can display
the Simulink library window by right-clicking the Simulink node in the
Library Browser window.
To create models, copy blocks from the Library Browser into a model window
in the Simulink Editor.

Open the Simulink Editor
Use one of the following approaches to open the Simulink Editor:
• Open an existing model. For example, at the MATLAB prompt, enter the
name of a model. For details, see “Open an Existing Model” on page 1-4.
• In the Library Browser, select File > Open. Choose a model or enter
the file name of the model.
• At the MATLAB prompt, use the open_system command. For example,
to open a model named vdp:
open_system('vdp')

Note To have the Simulink Editor display properly, use 32-bit color mode.
Typically, remote desktop connections (for example, a VNC connection) use a
default color mode of 16-bits or less.

1-3

1

Simulink® Basics

Open a Model
In this section...
“What Happens When You Open a Model” on page 1-4
“Open an Existing Model” on page 1-4
“Models with Different Character Encodings” on page 1-5
“Avoid Initial Model Open Delay” on page 1-5

What Happens When You Open a Model
Opening a model brings the model into memory and displays the model
graphically in the Simulink Editor.
You can also bring a model into memory without displaying it, as described in
“Load a Model” on page 1-7.

Open an Existing Model
To open an existing model, use one of these approaches:
• (Windows operating systems only) On the Library Browser toolbar, click
the Open button.
• In the Library Browser or the Simulink Editor, select File > Open.
Choose a model or enter the file name of the model.
• At the MATLAB command prompt, enter the name of the model, without
the file extension (e.g., .slx) . The model must be in the current folder
or on the path.
Note If you have an earlier version of the Simulink software, and you want
to open a model that was created in a later version, first use the later version
to save the model in a format compatible with the earlier version. Then open
the model in the earlier version. For details, see “Export a Model to a Previous
Simulink Version” on page 1-14.

1-4

Open a Model

Models with Different Character Encodings
If you open a model created in a MATLAB software session configured to
support one character set encoding (for example, Shift_JIS), in a session
configured to support another character encoding (for example, US_ASCII),
Simulink displays a warning for SLX files. For MDL files, you might see a
warning or an error message, depending on whether it can encode the model,
using the current character encoding. The warning or error message specifies
the encoding of the current session and the encoding used to create the model.
To display the model’s text correctly:
1 Close all models open in the current session.
2 Use the slCharacterEncoding command to change the character encoding

of the current MATLAB software session to that of the model as specified
in the warning message.
3 Reopen the model.

You can now edit and save the model.
Simulink can check if models contain characters unsupported in the current
locale. For more details, see “Check file for foreign characters” and “Saving
Models with Different Character Encodings” on page 1-13.

Avoid Initial Model Open Delay
The first model that you open in a MATLAB session takes longer to open than
do subsequent models. This is because MATLAB does not load the Simulink
product into memory until the first time that you open a Simulink model. This
just-in-time loading of the Simulink product reduces the MATLAB startup
time and avoids unnecessary consumption of system memory.
To avoid the initial model opening delay, you can have MATLAB load the
Simulink software when the MATLAB product starts up. You can issue the
command to load Simulink at MATLAB startup from one of two places:
• The -r command line option
• The MATLAB startup.m file

1-5

1

Simulink® Basics

Use one of these commands:
• load_simulink — loads the Simulink product
• simulink — loads the Simulink product and opens the Simulink Library
Browser
For example, to load the Simulink product when the MATLAB software starts
up on a computer running the Microsoft® Windows operating system, create a
desktop shortcut with the following target:
matlabroot\bin\win32\matlab.exe -r load_simulink

Similarly, the following command loads the Simulink software when the
MATLAB software starts up on Macintosh and Linux® computers:
matlab -r load_simulink

1-6

Load a Model

Load a Model
Loading a model brings it into memory but does not display it graphically.
Tip To both bring a model into memory and display it graphically, open the
model as described in “Open a Model” on page 1-4.
After you load a model (as distinct from opening it), you can work with the
model programmatically as if it were visible. However, you cannot use the
Simulink Editor to edit the model unless you open the model.
You cannot load a model using the Simulink Editor or Library Browser.
To load a model programmatically, at the MATLAB command prompt, enter
the load_system command. Specify the model to be loaded. For example,
to load the vdp model:
load_system('vdp')

1-7

1

Simulink® Basics

Save a Model
In this section...
“How to Tell If a Model Needs Saving” on page 1-8
“Save a Model for the First Time” on page 1-9
“Model Names” on page 1-9
“Save a Previously Saved Model” on page 1-9
“What Happens When You Save a Model?” on page 1-9
“Saving Models in the SLX File Format” on page 1-10
“Saving Models with Different Character Encodings” on page 1-13
“Export a Model to a Previous Simulink Version” on page 1-14
“Save from One Earlier Simulink Version to Another” on page 1-15

How to Tell If a Model Needs Saving
To tell whether a model needs saving, look at the title bar in the Simulink
Editor. If the model needs saving, an asterisk appears next to the model
name in the title bar.

To determine programmatically whether a model needs saving, use the model
parameter Dirty. For example:
if strcmp(get_param(gcs, 'Dirty'), 'on')
save_system;
end

1-8

Save a Model

Save a Model for the First Time
To save a model for the first time, in the Simulink Editor, select File > Save.
Provide a location and name for the model file.

Model Names
Model file names must start with a letter and can contain letters, numbers,
and underscores. The file name must not be the same as that of a MATLAB
software command.
The total number of characters must not be greater than a certain maximum,
usually 63 characters. To find out whether the maximum for your system is
greater than 63 characters, use the MATLAB namelengthmax command.

Save a Previously Saved Model
If you are saving a model whose model file was previously saved:
• To replace the file contents, in the Simulink Editor, select File > Save.
• To save the model with a new name or location, in the Simulink Editor,
select File > Save As.
Note See also “Upgrade Models to SLX” on page 1-10.

What Happens When You Save a Model?
Simulink saves the model by generating a specially formatted file called the
model file that contains the block diagram and block properties. The Simulink
software follows this process while saving a model:
1 If the model file already exists, Simulink renames the model file as a

temporary file.
2 All block PreSaveFcn callback routines execute first, then the block

diagram PreSaveFcn callback routine executes.
3 Simulink writes the model file to a new file using the same name and, by

default, an extension of .slx.

1-9

1

Simulink® Basics

4 All block PostSaveFcn callback routines execute, then the block diagram

PostSaveFcn callback routine executes.
5 Simulink deletes the temporary file.

If an error occurs during this process, Simulink:
• Renames the temporary file to the name of the original model file
• Writes the current version of the model to a file with an .err extension
• Issues an error message
If an error occurs in Step 2 of the save process, then Step 3 is omitted and
Steps 4 and 5 are performed.

Saving Models in the SLX File Format
Save New Models as SLX
You save new models and libraries in the SLX format by default, with file
extension .slx. SLX is a compressed package that conforms to the Open
Packaging Conventions (OPC) interoperability standard. SLX stores model
information using Unicode UTF-8 in XML and other international formats.
Saving Simulink models in the SLX format:
• Typically reduces file size compared to MDL. The file size reduction
between MDL and SLX varies depending on the model.
• Solves some problems in previous releases with loading and saving MDL
files containing Korean and Chinese characters.
You can specify your file format for saving new models and libraries with the
Simulink preference “File format for new models and libraries”.

Upgrade Models to SLX
If you upgrade an MDL file to SLX file format, the file contains the same
information as the MDL file, and you always have a backup file. All
functionality and APIs that currently exist for working with models, such as
the get_param and set_param commands, are also available when using

1-10

Save a Model

the SLX file format. If you upgrade an MDL file to SLX file format without
changing the model name or location, then Simulink creates a backup file by
renaming (if writable) and Simulink does not remove the MDL file.
If you save an existing MDL file using File > Save, Simulink respects the
file’s current format and saves your model in MDL format.
To save an existing MDL file in the SLX file format,
1 Select File > Save As.
2 Leave the default Save as type as SLX, and click Save.

Simulink saves your model in SLX format, and creates a backup file
by renaming the MDL (if writable) to mymodel.mdl.releasename, e.g.,
mymodel.mdl.R2010b.
Alternatively, use save_system:
save_system mymodel mymodel.slx

This command creates mymodel.slx, and if the existing file mymodel.mdl is
writable it is renamed mymodel.mdl.releasename.
SLX files take precedence over MDL files, so if both exist with the same name
and you do not specify a file extension, you load the SLX file.
Simulink Projects can help you migrate files to SLX. For an example, see
“Upgrade Model Files to SLX and Preserve Revision History” on page 13-15.
Caution If you use third-party source control tools, be sure to register
the model file extension .slx as a binary file format. If you do not, these
third-party tools might corrupt SLX files when you submit them.

1-11

1

Simulink® Basics

Operations
with Possible
Compatibility
Considerations when
using SLX

What Happens

Action

Hard-coded references
to file names with
extension .mdl.

Scripts cannot find or
process models saved
with new file extension
.slx.

Third-party source
control tools that
assume a text format
by default.

Binary format of
SLX files can cause
third-party tools to
corrupt the files when
you submit them.

Make your code work
with both the .mdl and
.slxextension.
Use functions like
which and what instead
of strings with .mdl.
Register .slx as a
binary file format with
third-party source
control tools. Also
recommended for .mdl
files. See “Register
Model Files with Source
Control Tools” on page
13-70.

Changing character
encodings.

Some cases are
improved, e.g., SLX
solves some problems
in previous releases
with loading and saving
MDL files containing
Korean and Chinese
characters. However,
sharing models between
different locales
remains problematic.

See “SLX Files and
Character Encodings”
on page 1-14.

The format of content within MDL and SLX files is subject to change.
To operate on model data, use documented APIs (such as get_param,
find_systemand Simulink.MDLInfo.

1-12

Save a Model

Saving Models with Different Character Encodings
• “Differences in Character Encodings” on page 1-13
• “SLX Files and Character Encodings” on page 1-14

Differences in Character Encodings
When you save a model, the current character encoding is used to encode the
text stored in the model file. This can lead to model corruption if you save a
model whose original encoding differs from current encoding.
If you change character encoding, it is possible to introduce characters
that cannot be represented in the current encoding. If this is the case, the
model is saved as model.err, where model is the model name, leaving the
original model file unchanged. Simulink also displays an error message that
specifies the line and column number of the first character which cannot
be represented.
To recover from this error, either:
• Save the model in SLX format (see “Saving Models in the SLX File Format”
on page 1-10).
• Use the following procedure to locate and remove characters one by one.
1 Use a text editor to find the character in the .err file at the position

specified by the save error message.
2 Find and delete the corresponding character in the open model and

resave the model.
3 Repeat this process until you are able to save the model without error.

It’s possible that your model’s original encoding can represent all the text
changes that you’ve made in the current session, albeit incorrectly. For
example, suppose you open a model whose original encoding is A in a session
whose current encoding is B. Further suppose that you edit the model to
include a character that has different encodings in A and B and then save the
model. If in addition the encoding for x in B is the same as the encoding
for y in A, and if you insert x in the model while B is in effect, save the
model, and then reopen the model with A in effect the Simulink software will
display x as y. To alert you to the possibility of such corruptions, the software

1-13

1

Simulink® Basics

displays a warning message whenever you save a model in which the current
and original encoding differ but the original encoding can encode, possibly
incorrectly, all of the characters to be saved in the model file.

SLX Files and Character Encodings
Saving Simulink models in the SLX format typically reduces file size and
solves some problems in previous releases with loading and saving MDL files
containing Korean and Chinese characters.
Considerations for choosing a model file format:
• Use SLX if you are loading and saving models with Korean or Chinese
characters
• Use SLX if you would benefit from a compressed model file
• Whether you use SLX or MDL, Simulink can detect and warn if models
contain characters unsupported in the current locale. For SLX, you can use
the Model Advisor to help you, see “Check file for foreign characters”.

Export a Model to a Previous Simulink Version
You can export (save) a model created with the latest version of the Simulink
software in a format used by an earlier version, such as Simulink 7.0
(R2007b). For example, you might want to perform such an export to make a
model available to colleagues who only have access to a previous version of
the Simulink product.
To export a model in an earlier format:
1 In the Simulink Editor, select File > Save. This saves a copy in the latest

version of Simulink. This step avoids compatibility problems.
2 Simulink Editor, select File > Export > Export Model To Previous

Version.
The Export To Previous Version dialog box appears.
3 In the dialog box, from the Save as type list, select the previous version to

which to export the model.

1-14

Save a Model

4 Click the Save button.

When you export a model to a previous version’s format, the model is saved
in the earlier format, regardless of whether the model contains blocks and
features that were introduced after that version. If the model does contain
blocks or use features that postdate the earlier version, the model might not
give correct results when you run it in the earlier version of Simulink software.
In addition, Simulink converts blocks that postdate an earlier version into
yellow empty masked Subsystem blocks. For example, if you export a model
to Release R2007b, and the model contains Polynomial blocks, Simulink
converts the Polynomial blocks into yellow empty masked Subsystem blocks.
Simulink also removes any unsupported functionality from the model.

Save from One Earlier Simulink Version to Another
You can open a model created in an earlier version of Simulink and export
that model to a different earlier version. To prevent compatibility problems,
use the following procedure if you need to save a model from one earlier
version to another earlier version.
1 Use the current version of Simulink to open the model created with the

earlier version.
2 Before you make any changes, save the model in the current version by

selecting File > Save.
After saving the model in the current version, you can change and resave
it as needed.
3 Save the model in the earlier version of Simulink by selecting File >

Export > Export Model To Previous Version.
4 Start the earlier Simulink version and use it to open the model that you

exported to that earlier version.
5 Save the model in the earlier version by selecting File > Save.

You can now use the model in the earlier version of Simulink exactly as you
could if it had been created in that version.

1-15

1

Simulink® Basics

See also the Simulink preferences that can help you work with models from
earlier versions:
• “Do not load models created with a newer version of Simulink”
• “Save backup when overwriting a file created in an older version of
Simulink”

1-16

Simulink® Editor

Simulink Editor
In this section...
“Editor Layout” on page 1-17
“Undoing Commands” on page 1-21
“Window Management” on page 1-21

Editor Layout
Opening a Simulink model or library displays the model or library in the
Simulink Editor. For more information, see “Open the Simulink Editor” on
page 1-3.

1-17

1

Simulink® Basics

The Simulink Editor has the following major sections:
• Title bar

In the top left corner, the title bar displays the name of the model or
subsystem that is open in the model window.
• Menu bar and toolbar

At the top of the Simulink Editor, you can access commands to work with
models. Several buttons in the toolbar provide quick access to commonly
used Simulink Editor menu options. Other buttons in the toolbar open
other Simulink tools, such as the Model Explorer (for details, see “Open
Simulink Tools from the Toolbar” on page 1-20).
• Palette

The icons in the vertical bar on the right side of the Simulink Editor
perform very common tasks, such as adding an annotation.
• Explorer bar

1-18

Simulink® Editor

The breadcrumb shows the systems that you have open in the editor. Select
a system in the breadcrumb to open that system in the model window. If
you click in the Explorer bar whitespace, you can edit the hierarchy. Also,
the down arrow at the right side of the Explorer bar provides a history.

• Model Browser

Click the double arrows
in the bottom left corner of the Simulink Editor
to open or close a tree-structured view of the model in the editor.
• Canvas — The canvas is area where you edit the block diagram. You can
use the mouse and keyboard to create and connect blocks, select and move
blocks, edit block labels, display block dialog boxes, and so on.
To display context menus specific to a particular model object in the canvas,
such as a block, right-click the object.
• Status information — Near the top of the editor, you can see (and reset)
the simulation time and the simulation mode. The bottom status line
shows the status of Simulink processing, the zoom factor, and the solver.

1-19

1

Simulink® Basics

Open Simulink Tools from the Toolbar
The Simulink Editor toolbar provides several buttons for quick access to
other Simulink tools.
For buttons that have associated menu options, clicking the button invokes
the first menu option.
Tools

Buttons and Associated Menus

Library Browser
Model Explorer
Simulation Stepper

Next Step
Previous Step

Simulation Data Inspector

Advisor Tools

1-20

Simulink® Editor

Undoing Commands
You can cancel the effects of up to 101 consecutive operations. To undo
commands, select Edit > Undo. Repeat until you get to the command that
you want to undo. You can undo operations such as:
• Adding, deleting, or moving a block
• Adding, deleting, or moving a line
• Adding, deleting, or moving a model annotation
• Editing a block name
• Creating a subsystem (see “Undoing Subsystem Creation” on page 4-39
for more information)
To reverse the effects of an Undo command, select Edit > Redo.

Window Management
One Simulink Editor Per Model
When you open a model, that model appears in its own Simulink Editor
window. For example, if you have one model already open, and then you open
a second model, the second model appears in a second Simulink Editor.
To open the same model in two separate Simulink Editor windows, at the
MATLAB command prompt, enter the open_system command, using the
window argument. For example, if you already have the vdp model open, then
to open another instance of the vdp model in a separate Simulink Editor,
enter:
open_system ('vdp', 'window')

Open a Subsystem
The Simulink Editor displays only one active window at a time. By default,
if you open a Subsystem block, the opened subsystem replaces (in terms of
being displayed in the model window) the model from which you opened the
subsystem.

1-21

1

Simulink® Basics

You can use tabs in the Simulink Editor to make it easier to navigate between
model windows for the top model and subsystems. To open a subsystem in a
separate tab:
1 Right-click the Subsystem block.
2 From the context-menu, select Open In New Tab. In the example below,

there are separate tabs for the ex_sscreate2 model and for the Subsystem.

Navigate between the top model and subsystems by clicking the appropriate
tab. Or, choose an option following options from the View > Navigate menu,
such as Back, Back to Parent, or Previous Tab.
For more information about opening subsystems, see “Navigate Model
Hierarchy” on page 4-39.

Open a Referenced Model
If you open a Model block, the referenced model opens in a separate Simulink
Editor.

Bring the MATLAB Desktop Forward
Simulink Editor windows open on top of the MATLAB desktop. To bring the
MATLAB desktop back to the top of your screen, in the Simulink Editor,
select View > MATLAB Desktop.

1-22

Zoom and Pan Block Diagrams

Zoom and Pan Block Diagrams
You can enlarge or shrink the view of the block diagram in the current
Simulink Editor window.
Goal of Zoom or Pan

What You Do

Enlarge the model
diagram incrementally

Select View > Zoom In or press Ctrl++.

Enlarge the model
diagram dynamically

Roll the mouse scroll wheel forward.

Zoom by a factor of two,
displaying the selected
model object

1 In the palette, drag the zoom button (

) to
the object that you want to include in the
enlarged view.

2 Press the left mouse button.

Zoom until the whole
model diagram just fits in
the current window

Select View > Fit to View or press
Spacebar.

Zoom and pan
1 Roll the mouse scroll wheel forward.
2 Release the scroll wheel.
3 Hold the scroll wheel down and pan to the

desired positioning by moving the mouse.
4 Release the scroll wheel.

To disable the zoom and pan behavior for
the scroll wheel, clear the File > Simulink
Preferences > Editor Defaults > Scroll
wheel controls zooming preference.
Pan with the mouse

Hold down p or q and drag mouse.

Shrink the model diagram
incrementally

Select View > Zoom Out.

1-23

1

Simulink® Basics

Goal of Zoom or Pan

What You Do

Shrink the model diagram
dynamically

Roll the mouse scroll wheel backward.

Restore the model diagram
to 100%

Select View > Normal View (100%) or press
Alt+1.

Go back in pan/zoom
history

b

Go forward in pan/zoom
history

t

To disable the zoom and pan behavior for the scroll wheel, clear the File >
Simulink Preferences > Editor Defaults > Scroll wheel controls
zooming preference. If you hold the CRTL key and use the scroll wheel, the
scroll wheel behavior is the opposite of how the preference is set.

1-24

Update a Block Diagram

Update a Block Diagram
Updating the Diagram
You can leave many attributes of a block diagram, such as signal data types
and sample times, unspecified. The Simulink software then infers the values
of block diagram attributes, based on the block connectivity and attributes
that you specify. The process that Simulink uses is known as updating the
diagram.
Simulink attempts to infer the most appropriate values for attributes that
you do not specify. If Simulink cannot infer an attribute, it halts the update
and displays an error dialog box.

Simulation Updates the Diagram
Simulink updates the block diagram at the start of a simulation. The updated
diagram provides the simulation with the results of the latest changes that
you have made to a model.

Update Diagram at Edit Time
As you create a model, at any point you can have Simulink update the
diagram. Updating the diagram periodically can help you to identify and fix
potential simulation issues as you develop the model. This approach can
make it easier to identify the sources of problems by focusing on a set of recent
changes. Also, the update diagram processing takes less time than performing
a simulation, so you can identify issues more efficiently.
To update the diagram at edit time, use one of these approaches:
• In the Simulink Editor, select Simulation > Update Diagram.
• Press Ctrl-D.
For example:
1 Create the following model.

1-25

1

Simulink® Basics

2 In the Simulink Editor, select Display > Signals & Ports > Port Data

Types.
The data types of the output ports of the Constant and Gain blocks appear.
The data type of both ports is double, the default value.

3 In the Constant block parameters dialog box, set Output data type to

single.

The output port data type displays on the block diagram do not reflect
this change.
4 In the Simulink Editor, select Simulation > Update Diagram.

The updated block diagram reflects the change that you made previously.

In this example, Simulink infers a data type for the output of the Gain
block. This is because you did not specify a data type for the block. The
inferred data type inferred is single, because single precision is all that
is necessary to simulate the model accurately, given that the precision of
the block input is single.

1-26

Copy Models to Third-Party Applications

Copy Models to Third-Party Applications
On a computer running the Microsoft Windows operating system, you can:
1 Copy a Simulink product model to the Windows operating system clipboard.
2 Paste the model from the clipboard to a third-party application, such as

word processing software.
You can copy a model in either bitmap or metafile format. You can then
paste the clipboard model to an application that accepts figures in bitmap or
metafile format. For a description of how to set up the figure settings and
save a figure to the clipboard on a Windows platform, see “Exporting to the
Windows or Macintosh Clipboard”.

1-27

1

Simulink® Basics

Print a Block Diagram
In this section...
“Print Interactively or Programmatically” on page 1-28
“Systems to Print” on page 1-28
“Title Block Print Frame” on page 1-30
“Paper Size and Orientation” on page 1-31
“Diagram Positioning and Sizing” on page 1-31
“Tiled Printing” on page 1-32
“Print Sample Time Legend” on page 1-35

Print Interactively or Programmatically
You can print a block diagram:
• Interactively in the Simulink Editor, by selecting File > Print.
• Programmatically, by using the MATLAB print command.
To control some additional aspects of printing a block diagram, use the
param_set command with model parameters.

Systems to Print
From the Simulink Editor
To specify what systems in a block diagram that you want to print:
1 In the Simulink Editor, select File > Print > Print.

The Print Model dialog box appears.
2 In the Options section, select one of the following:

• Current system — The current system only

1-28

Print a Block Diagram

• Current system and above — The current system and all systems
above it in the model hierarchy
• Current system and below — The current system and all systems
below it in the model hierarchy, with the option of looking into the
contents of masked and library blocks
• All systems — All systems in the model, with the option of looking into
the contents of masked and library blocks
To print the contents of masked subsystems that are at or below the level of
the current block, select the Look under mask dialog check box. When
you print all systems, the top-level system is the current block, so Simulink
looks under all masked blocks.
To print the contents of library blocks that are systems, in the Print Model
dialog box, select the Expand unique library links check box. Only one copy
is printed, regardless of how many copies of the block that the model contains.
The print log lists the blocks and systems printed. To print the print log,
select the Include Print Log check box.

With the Print Command
The format of the print command is
print -ssys -device -tileall -pagesp filename
sys is the name of the system to be printed. Precede the system name
with the -s switch identifier. The name of the system is the only required
argument. The system must be open or must have been open during the
current session. If the system name contains spaces or takes more than one
line, you need to specify the name as a string.

The print command prints only the system that you specify. The command
does not have options to specify the scope of the systems to be printed (for
example, current system and below). To specify the scope of the systems to
be printed, use the Simulink Editor.

1-29

1

Simulink® Basics

This example shows how to print the currently selected subsystem
(Controller).
open_system('f14');
open_system('f14/Controller');
print(['-s', gcs])

This example shows how to print the contents of a subsystem named
Controller in the current system.
open_system('f14');
print -sController

This example shows how to print the contents of a subsystem named Aircraft
Dynamics Model.
open_system('sldemo_clutch');
print (['-sAircraft Dynamics Model'])

To print a system whose name appears on multiple lines, assign the newline
character to a variable and use that variable in the print command. This
example shows how to print a subsystem whose name, Aircraft Dynamics
Model, appears on three lines.
open_system('f14');
cr = sprintf('\n');
print (['-sAircraft' cr 'Dynamics' cr 'Model'])

The device specifies the device type. For a list of device types, see the
documentation for the print function.
The filename is a PostScript® file to which you save the output. If filename
exists, it is replaced. If filename does not include an extension, an
appropriate one is appended.

Title Block Print Frame
A title block print frame is a border that contains information relevant to the
block diagram, such as the name of the block diagram. After you create a
print frame, you can print a block diagram with a print frame:

1-30

Print a Block Diagram

1 In the Simulink Editor, select File > Print > Print.

The Print Model dialog box appears.
2 Select the Frame check box.
3 In the adjacent edit box, enter the path to the title block frame.

To create a customized title block frame, use the MATLAB frame editor. For
information about using the frame editor to create title block frames, see
“Custom Print Frames”.

Paper Size and Orientation
On Windows platforms, you can use the Simulink Editor to specify the type
and orientation of the paper for printing a model.
1 Select File > Print > Page Setup.

The Print Setup dialog box appears.
2 In the Paper and Orientations section, set the fields for paper size and

orientation.
On all platforms, you can set the paper orientation alone, using the MATLAB
orient command.

On all platforms, you can also set the paper type and orientation by using the
set_param command with the model’s PaperType andPaperOrientation
properties, respectively (see “Model Parameters”).

Diagram Positioning and Sizing
To position and size the model diagram on the printed page, use the
set_param command with a model’s PaperPositionMode and PaperPosition
parameters.
The value of the PaperPosition parameter is a vector of form [left bottom
width height]. The first two elements specify the bottom-left corner of a
rectangular area on the page, measured from the page’s bottom-left corner.
The last two elements specify the width and height of the rectangle.

1-31

1

Simulink® Basics

If you set the PaperPositionMode parameter to manual, Simulink positions
(and scales, if necessary) the model diagram to fit inside the specified print
rectangle. If PaperPositionMode is auto, Simulink centers the model
diagram on the printed page, scaling the diagram, if necessary, to fit the page.
For example, these commands print the block diagram of the vdp model in the
lower-left corner of a U.S. letter-size page in landscape orientation.
open_system('vdp');
set_param('vdp', 'PaperType', 'usletter');
set_param('vdp', 'PaperOrientation', 'landscape');
set_param('vdp', 'PaperPositionMode', 'manual');
set_param('vdp', 'PaperPosition', [0.5 0.5 4 4]);
print -svdp

Tiled Printing
By default, each block diagram is scaled during the printing process so that
it fits on a single page. That is, the size of a small diagram is increased or
the size of a large diagram is decreased to confine its printed image to one
page. In the case of a large diagram, scaling can make the printed image
difficult to read.
By contrast, tiled printing enables you to print even the largest block
diagrams without sacrificing clarity and detail. Tiled printing allows you to
distribute a block diagram over multiple pages. You can control the number
of pages over which Simulink prints the block diagram, and hence, the total
size of the printed diagram.
Also, you can set different tiled-print settings for each of the systems in
your model. Consequently, you can customize the appearance of all printed
images to best suit your needs. The following sections describe how to use
tiled printing.

Enable Tiled Printing
To enable tiled printing for a model or subsystem, use one of these approaches:
• In the Simulink Editor, select File > Print > Enable Tiled Printing.
• At the MATLAB command prompt:

1-32

Print a Block Diagram

1 Use the set_param command to set the PaperPositionMode parameter

to tiled (see ).
2 Use the print command with the -tileall argument.

For example, to open the f14 model and enable tiled printing for the
Controller subsystem, enter:
open_system('f14');
set_param('f14/Controller', 'PaperPositionMode', 'tiled');
print('-sf14/Controller', '-tileall')

Display Page Boundaries
Displaying the page boundaries in the Simulink Editor can help you to
visualize the model size and layout with respect to the page. To make the
page boundaries visible, select File > Print > Show Page Boundaries.
Simulink renders the page boundaries on the Simulink Editor canvas. If tiled
printing is enabled, Simulink represents page boundaries with a checkerboard
pattern. Each checkerboard square indicates the extent of a separate page.

If tiled printing is disabled, only a single page appears on the canvas.
To display the page boundaries programmatically, use the set_param
command, with the system’s ShowPageBoundaries parameter set to on (see
“Model Parameters”). For example:

1-33

1

Simulink® Basics

open_system('vdp');
set_param('vdp', 'ShowPageBoundaries', 'on')

Scaling and Margins
To scale the block diagram so that more or less of it appears on a single tiled
page, use the set_param command with the TiledPageScale parameter. By
default, its value is 1. Values greater than 1 proportionally scale the diagram
such that it occupies a smaller percentage of the tiled page, while values
between 0 and 1 proportionally scale the diagram such that it occupies a larger
percentage of the tiled page. For example, a TiledPageScale of 0.5 makes the
printed diagram appear twice its size on a tiled page, while a TiledPageScale
of 2 makes the printed diagram appear half its size on a tiled page.
To specify the margin sizes associated with tiled pages, use the set_param
command with the TiledPaperMargins parameter. The value of
TiledPaperMargins is a vector of form [left top right bottom]. Each
element specifies the size of the margin at a particular edge of the page.
The value of the PaperUnits parameter determines the margin’s units of
measurement. Each margin to 0.5 inches by default. By decreasing the
margin sizes, you can increase the printable area of the tiled pages.

Range of Tiled Pages
By default, Simulink prints all of a system’s tiled pages.
On a Microsoft Windows platform, to specify a range of tiled page numbers to
print, you can use the Simulink Editor.
1 In the Simulink Editor, select File > Print > Print.

The Print Model dialog box appears.
2 In the Options section, select Current system and Enable tiled printing

for all systems.
3 In the Print range section in the middle of the dialog box, select Pages and

enter a page range.

1-34

Print a Block Diagram

To specify a range of tiled page numbers programmatically, use the print
command with the -tileall argument and the -pages argument. Append to
-pages a two-element vector that specified the range.
Note Simulink uses a row-major scheme to number tiled pages. For example,
the first page of the first row is 1, the second page of the first row is 2, and
so on.
For example, to print the second, third, and fourth pages:
open_system('vdp');
print('-svdp', '-tileall', '-pages[2 4]')

Print Sample Time Legend
You can print a legend that contains sample time information for your entire
system, including any subsystems. The legend appears on a separate page
from the model. To print a sample time legend:
• In the Simulink Editor, select File > Print > Print.
The Print Model dialog box appears.
• In the Options section select, select Print Sample Time Legend.
For more information about the contents and the settings of the legend, see
“View Sample Time Information” on page 5-9.

1-35

1

Simulink® Basics

Generate a Model Report
A model report is an HTML document that describes the structure and
content of a model. The report includes block diagrams of the model and its
subsystems and the settings of its block parameters.
Tip If you have the SimulinkReport 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”.
To generate a model report for the current model:
1 In the Simulink Editor, select File > Print > Print Details.

The Print Details dialog box appears.
2 Select the desired report options. For details, see “Model Report Options”

on page 1-37.
3 Select Print.

The Simulink software generates the HTML report and displays the report in
your default HTML browser.

1-36

Generate a Model Report

While generating the report, Simulink displays status messages on a
messages pane that replaces the options pane on the Print Details dialog box.

Select the detail level of the messages from the list at the top of the messages
pane. When the report generation process begins, the Print button changes
to a Stop button. To terminate the report generation, press Stop. When the
report generation process finishes, the Stop button changes to an Options
button. Clicking this button redisplays the report generation options, allowing
you to generate another report without having to reopen the Print Details
dialog box.

Model Report Options
Use the Print Details dialog box allows you to specify the following report
options.

Directory
The folder where the HTML report is stored. The options include your
system’s temporary folder (the default), your system’s current folder, or
another folder whose path you specify in the adjacent edit field.

1-37

1

Simulink® Basics

Increment filename to prevent overwriting old files
Creates a unique report file name each time you generate a report for the
same model in the current session. This preserves each report.

Current object
Include only the currently selected object in the report.

Current and above
Include the current object and all levels of the model above the current object
in the report.

Current and below
Include the current object and all levels below the current object in the report.

Entire model
Include the entire model in the report.

Look under mask dialog
Include the contents of masked subsystems in the report.

Expand unique library links
Include the contents of library blocks that are subsystems. The report
includes a library subsystem only once even if it occurs in more than one
place in the model.

Printing Limitations
Printing Properties (Windows)
On Windows platforms, the File > Print > Print dialog box includes:
• Printing options, such as the printer to use, the print range, the number of
copies, and which systems to print.

1-38

Generate a Model Report

• A Properties button, which displays additional printing properties, such
as paper orientation and resizing options. In R2012b, Simulink ignores the
settings for these additional printing properties. Simulink only uses the
settings in the main Print dialog box.

Printer Name (Mac)
On Mac platforms, the printer name that you specify in the File > Print >
Print dialog box must:
• Use only alphanumeric characters (letters and numbers), and not special
characters such as an underscore or ampersand (&)
• Include no blank spaces

1-39

1

Simulink® Basics

End a Simulink Session
To terminate a Simulink software session, close all Simulink windows.
To terminate a MATLAB software session, choose one of these commands
from the File menu:
• On a computer running the Microsoft Windows operating system: Exit
MATLAB
• On a UNIX® system, system: Quit MATLAB

1-40

Keyboard and Mouse Shortcuts for Simulink®

Keyboard and Mouse Shortcuts for Simulink
In this section...
“Model Viewing Shortcuts” on page 1-41
“Block Editing Shortcuts” on page 1-41
“Line Editing Shortcuts” on page 1-43
“Signal Label Editing Shortcuts” on page 1-43
“Annotation Editing Shortcuts” on page 1-43

Model Viewing Shortcuts
The following table lists keyboard shortcuts for viewing models.
Task

Shortcut

Zoom in

Ctrl++

Zoom out

Ctrl+-

Zoom to normal (100%)

Alt+1

Pan

Hold the mouse scroll wheel down and drag
the mouse

Fit diagram to screen

Spacebar

Pan with mouse

Hold down p or q and drag mouse

Go back in pan/zoom history

b

Go forward in pan/zoom
history

t

Delete selection

Delete or Backspace

Move selection

Make selection and use arrow keys

Block Editing Shortcuts
The following table lists mouse and keyboard actions that apply to blocks.

1-41

1

1-42

Simulink® Basics

Task

Shortcut

Select one block

Left mouse button (LMB)

Select multiple blocks

Shift + LMB

Copy block from another
window

Drag block

Move block

Drag block

Rotate block clockwise

Ctrl+R or Ctrl+Y

Rotate block
counterclockwise

Ctrl+Shift+R

Flip block

Ctrl+I

Duplicate block

Ctrl+C, then Ctrl+V

Connect blocks

Select output port, hover over input port, and
press Ctrl + LMB

Disconnect block

Shift + drag block

Create subsystem from
selected blocks

Ctrl+G

Open selected subsystem

Enter

Go to parent of selected
subsystem

Esc

Look under a block mask

Ctrl + U

Keyboard and Mouse Shortcuts for Simulink®

Line Editing Shortcuts
The following table lists mouse and keyboard actions that apply to lines.
Task

Shortcut

Select one line

Left mouse button (LMB)

Select multiple lines

Shift + LMB

Draw branch line

Ctrl + drag line; or RMB and drag line

Route lines around blocks

Shift + draw line segments

Move line segment

Drag segment

Move vertex

Drag vertex

Signal Label Editing Shortcuts
The next table lists mouse and keyboard actions that apply to signal labels.
Action

Shortcut

Create signal label

Double-click line, then enter label

Copy signal label

Ctrl + drag label

Move signal label

LMB + drag label

Edit signal label

Click in label, then edit

Annotation Editing Shortcuts
The next table lists mouse and keyboard actions that apply to annotations.
Action

Shortuct

Create annotation

Double-click in diagram, then enter text

Copy annotation

Ctrl+C then Ctrl+V

Move annotation

Drag annotation

Edit annotation

Click in text, then edit

1-43

1

Simulink® Basics

Simulink Demos Are Now Called Examples
Starting in R2012b, Simulink models and videos that were previously called
demos are now called examples. There are two ways to access these examples
from the Help browser:
• At the top of the product landing page, click Examples.

• On any documentation page, click the Table of Contents button
then select Examples.

You can filter documentation search results to display only examples.

1-44

, and

Simulink® Demos Are Now Called Examples

For more information about changes to the Help browser, see the R2012b
MATLAB Release Notes.

1-45

1

1-46

Simulink® Basics

2
Simulation Stepping
• “Simulation Stepping” on page 2-2
• “Step Through a Simulation” on page 2-12

2

Simulation Stepping

Simulation Stepping
In this section...
“About Simulation Stepping” on page 2-2
“Simulation Stepper Graphical Cues” on page 2-5
“Current Limitations” on page 2-9

About Simulation Stepping
The Simulation Stepper steps through the major time steps of a simulation
without changing the course of a simulation. The Simulation Stepper is
available from the Simulink Editor toolbar:

With Simulation Stepper, you can:
• Start and stop simulation of Simulink models
• Step forward and backward through a simulation
• Change from stepping backward to running with the Play button
• Change from running to paused (Pause button) or step backward (if
backward stepping is enabled)
• Add conditional breakpoints
• Add breakpoints at simulation time
You can use the stepping capabilities to perform actions such as analyze
plotted data at a particular moment in simulation time.
The stepping backward capability requires capturing simulation snapshots.
A simulation snapshot at a particular simulation time captures all the
information required to continue a simulation from that point. A simulation
snapshot contains simulation state (SimState) and possibly information
related to logged data and visualization blocks.

2-2

Simulation Stepping

The Simulink software can store simulation state only when it is stepping
forward through a simulation. When stepping backward, the software uses
the simulation snapshot, stored as SimState, to restore the previous state
of the simulation.
Stepping backward does not mean that the model is simulating backward.
Stepping backward involves loading a previously captured snapshot of the
model. When stepping forward again, the model is simulated from that point
and new snapshots are captured.

Simulation Stepper Versus Simulink Debugger
The Simulation Stepper and the Simulink Debugger both enable you to start,
stop, and step through a model simulation. Both allow you to use breakpoints
as part of a debugging session. However, Simulation Stepper and Simulink
Debugger are very different in their intended use. Simulation Stepper lets
you see all the data in between major steps. Simulink Debugger lets you
enter a major step.
Use the following table as a guideline:
Action

Simulation Stepper

Simulink Debugger

Look at state of system
after executing a major
time step.

X

X

Observe dynamics of
the entire model from
step to step.

X

Step simulation
backward.

X

Pause across major
steps.

X

Control a Stateflow®
debugging session.

X

Step through
simulation by major
steps.

X

2-3

2

Simulation Stepping

Action

Simulation Stepper

Simulink Debugger

Monitor single block
dynamics (for example,
output, update, and so
forth) during a single
major time step.

X

Look at state of system
while executing a major
time step.

X

Observe solver
dynamics during a
single major step.

X

Show various stages of
Simulink simulation.

X

Pause within a major
step.

X

Step through
a simulation
block-by-block.

X

Command-line
interface.

X

To better understand the difference between Simulation Stepper and
Simulink Debugger, you need a good understand of the simulation process.
(For more information, see “How S-Functions Work”.)
In particular, use Simulink Debugger for advanced debugging scenarios
that involve custom blocks (such as S-functions). In this case, the Simulink
Debugger can help you analyze the issues with a particular block method.
Simulink Debugger also gives you finer control on breakpoints. It also gives
you finer control to step from one method to another block method within a
time step. For more information on the debugger, see “Introduction to the
Debugger” on page 21-2.

2-4

Simulation Stepping

Simulation Stepper Graphical Cues
Simulation Stepper Toolbar Icons
Icon

Action
Displays the Simulation Stepping Options dialog box,
which affect Simulation Stepper performance. You can
configure stepping options such as pausing after a specific
simulation time and enabling stepping backward. This
button is available until you enable previous stepping
in the dialog box and start the simulation. To access
this dialog box again, select Simulation > Simulation
Stepping Options.
In conjunction with enabling the step back capability,
you must also simulate the model or step it forward to
save snapshots for the step backward capability.
Tip Snapshots for stepping backward are available only
within the duration of a simulation. The Simulation
Stepper does not save the steps for step backward across
simulations.
Steps the simulation to a previously captured simulation
snapshot. Stepping to the final step ends the simulation.
Starts/pauses/continues simulation.
,
Steps the simulation forward.
Stops the simulation.

2-5

2

Simulation Stepping

Simulation Stepping Options Dialog Box
Click the Simulation Stepping Options icon (
Stepping Options dialog box.

) to display the Simulation

Use this dialog box to specify how you want to step through a simulation.
When you enable stepping backward and start the simulation, the icon
changes to

, so that you can step backward.

If you enter an invalid value, the dialog box reverts all settings to the values
that were last applied.

Note When the icon changes to
, you cannot access this dialog box from
the toolbar. To access this dialog box again, select Simulation > Simulation
Stepping Options.

2-6

Simulation Stepping

When the simulation is running and there are no saved back steps (but
stepping back is enabled), the icon changes to

(disabled state).

The Simulation Stepping Options dialog box contains the following
parameters. For any setting, you can change the value while the simulation
is running or paused.
Parameter

Operation

Enable stepping back

Select check box to enable backward
stepping.

Maximum number of saved back
steps

Enter maximum number of
snapshots that the software can
capture. A snapshot at a particular
simulation time captures all the
information required to continue
a simulation from that point. For
more information, see “Simulation
Snapshots” on page 2-14.

Interval between stored back
steps

Enter the number of major time
steps to take between capturing
simulation snapshots. For more
information, see “Simulation
Snapshots” on page 2-14.

Move back/forward by

Enter the number of major time
steps for a single call to step forward
or backward. For more information,
see “Simulation Snapshots” on page
2-14.

Pause simulation when time
reaches

Select check box to pause simulation
when time reaches the specified
time(s). This value can be a scalar
value, or a vector of times. Specifying
a vector of pause times is equivalent
to specifying multiple separate pause
times for a single simulation. You
can specify pause times as variables
in the model or MATLAB workspace.

2-7

2

Simulation Stepping

Parameter

Operation

Note The stepper does not alter
the course of the simulation. As a
consequence, specifying a value for
a pause time does not necessarily
pause the simulation at exactly that
time. Instead, the simulation pauses
at whatever simulation time is
closest to the requested pause time,
without going below it.

Simulation Stepper Pause Status
The status bar at the bottom of the Simulink Editor displays the simulation
time of the last completed simulation step. While a simulation is running,
the editor updates the time display to indicate where the simulation is. This
display is an approximation because the status bar is not updated at every
simulation time step. When you pause a simulation, the status bar display
time catches up to the actual time of the last completed step.

When you use Simulation Stepper to step through a simulation, the time on
the status bar updates at every major time step of the simulation. The value
that is displayed (the time of the last completed step) might not always be the
same as the time of the solver. This event occurs because of the difference
in the way that different solvers propagate the simulation time in a single
iteration of the simulation loop. Simulation Stepper pauses at a single
position within the simulation loop. However, some solvers perform their time
advance before the stepper pauses and others perform their time advance after
the stepper pauses, which then becomes part of the next step. As result, for
some solvers, the solver time is always one major step ahead of the time of the
last model output. When this condition occurs, and the simulation is paused,
the status bar time displays an asterisk next to it. The asterisk indicates that

2-8

Simulation Stepping

the solver in this simulation has already advanced past the displayed time
(which is the time of the last completed simulation step). Continuous and
variable step discrete solvers exhibit this behavior. Other solvers do not cause
the asterisk to be displayed because the times are synchronized.

Current Limitations
• There is no command-line interface for the Simulation Stepper.
• Simulation stepping (forward and backward) is available for only Normal
and Accelerator modes.
• The step back capability relies on SimState (“Save and Restore Simulation
State as SimState” on page 14-32) technology for saving and restoring the
state of a simulation. As a result, the step back capability is available only
for models that support SimState.
• Some blocks do not support backwards stepping for reasons other than
SimState support. Overall, the presence of any of the following blocks in a
model prevents the model from being enabled for backward stepping:

-

S-functions that have P-work vectors but do not declare their SimState
compliance level, or declare it to be unknown or disallowed (see
“S-Function Compliance with the SimState”).

-

SimMechanics™ First Generation blocks
Model blocks configured for Accelerator mode.
SimEvents® blocks

• MATLAB Function blocks generally support stepping backward. However,
use of certain constructs in the MATLAB code of this block might prevent
this block from supporting backward stepping. The following scenarios
prevent the MATLAB Function from being fully supported or stepping
backward:

-

Persistent variables of opaque data type. Attempts to step back under
this condition result in an error message based on the specific variable
type.

-

Extrinsic functions calls that might contain state (such as properties of
objects or persistent data of functions). No warnings or error messages
are displayed, but the result will likely be incorrect.

2-9

2

Simulation Stepping

-

Calls to custom C code (through MEX function calls) that might not
contain static variables. No warnings or error messages are displayed,
but the result will likely be incorrect.

• Some visualization blocks do not support stepping backward. Because
these blocks are not critical to the state of the simulation, there are no
errors or warnings issued when back stepping is performed on a model
that contains these blocks:

-

XY Graph
Floating Scope
Signal Viewer
Auto Correlator
Cross Correlator
Spectrum Analyzer
Averaging Spectrum Analyzer
Power Spectral Density
Averaging Power Spectral Density
Floating Bar Plot
3Dof Animation
MATLAB Animation
VR Sink

Any blocks that implement custom visualization in their output method
(for example, an S-function that outputs to a MATLAB figure) are not
fully compliant with backward stepping because the block method
Output is not executed during backward stepping. While the state of
such blocks remain consistent with the simulation time (if the blocks
comply with SimState) the visualization component will be inconsistent
until the next step forward of the simulation.

Because these block do not affect the numerical result of a simulation, the
back stepping is not disabled for these blocks. Note that the values these
blocks output are inaccurate until the simulation is stepped forward again.

2-10

Simulation Stepping

• Port values displays do not always update when stepping backward. Upon
stepping backward, if the port value is unavailable, the unavailable label
is displayed.
• Simulation Stepper steps through the major time steps of a simulation
without changing the course of a simulation. Choosing a refine factor
greater than unity produces loggable outputs at times in between of the
major time steps of the solver. These times are not major time steps, and
stepping to a model state at those times is not possible.
• You cannot add conditional breakpoints on inputs to, outputs from, or
signals inside variant subsystems.
If the simulation is run with the Enable stepping back check box selected,
the Simulink software checks the capability of the model to step back. As a
result, it might display a warning at the MATLAB command prompt. In
some cases, the step backward capability might not be supported for that
simulation. The step back capability is then disabled for the duration of that
simulation (until the model is terminated, at which point the setting resets to
the originally requested value).

2-11

2

Simulation Stepping

Step Through a Simulation
In this section...
“Configure Simulation Stepping” on page 2-12
“Forward and Backward Stepping” on page 2-12
“Conditional Breakpoints” on page 2-18

Configure Simulation Stepping
To control aspects of the simulation stepping operations, such as to enable
stepping backward or limiting how many simulation snapshots to capture,
use the Simulation Stepping Options dialog box. You can access this dialog
box in one of the following ways:

• In the Simulation toolbar, click the

button, the Next icon.

• If the
button is no longer available, or if you prefer to use the menu
bar, select Simulation > Simulation Stepping Options.
For a description of the options, see “Simulation Stepping Options Dialog
Box” on page 2-6.

Forward and Backward Stepping
This topic describes how to step forward and backward through a simulation.
1 In the MATLAB Command Window, type

vdp

The model and its associated scope are displayed.
2 In the Simulation toolbar, click

. The

Simulation Stepping Options dialog box is displayed.

2-12

Step Through a Simulation

3 Click the Enable previous stepping check box, then click OK.

4 In the Simulation toolbar, click

.

The simulation simulates one step. At the same time, the software stores
the simulation snapshot for that step.
5 Repeatedly click the Next button to continue stepping forward and storing

simulation data. For example, 25 clicks plots data that looks like:

If you clear the Enable previous stepping check box, the software clears
the stored snapshot cache.
Note You must step forward before you can step backward to create the
simulation state that the step backward operation requires.

2-13

2

Simulation Stepping

6 In the Simulation toolbar, click

one or more times to step backward
to the previously stepped simulation snapshot.
The scope updates to show that data has been removed from the scope.

Simulation Snapshots
In the Simulation Stepping Options dialog box, you can specify options for
snapshot capturing:
• The maximum number of snapshots to capture while simulating forward.
The greater the number of steps, the more memory the simulation will
occupy. This number can impact simulation speed.
• The number of steps to skip between snapshots. This capability enables
you to create snapshots of simulation state at periodic intervals, such

2-14

Step Through a Simulation

as every three steps. This interval is independent of the number of
steps taken in either the forward or backward direction. Because taking
simulation snapshots affects simulation speed, saving snapshots at larger
intervals can improve simulation speed (compared to setting this interval
to a smaller number).
The following figure illustrates how the stepper can move along the steps
of a simulation. In this case, the stepper first pauses the simulation after
two major steps, then again after two consecutive single major steps, and
the again after two major steps. The number of simulation steps between
stepper pauses is the Move back/forward by setting in the stepper
options dialog box. You can change this setting during simulation as shown
in the following figure.

The following figure illustrates snapshot captures where the interval
between stored snapshots is three.

In the following figure, the number of steps to skip between snapshots is
three at first, but after the fourth step, the number of steps changes to one.
This example illustrates the flexibility of the stepper, which allows you to
change the stepping options while stepping forward. In this example, at the
fourth step, the Simulation Stepping Options dialog box was used to change
the snapshot steps from three to one. This capability is most useful when
you want to capture more snapshots around a simulation time of interest.

2-15

2

Simulation Stepping

The following figure illustrates how the snapshots settings of the stepper
can change the action for stepping backward. For example, suppose
that the interval between snapshots is set to 3 (simulation steps), and
starting at a certain simulation time (corresponding to state 6 in the
following figure), the stepper Move back/forward by setting is set to 1.
To accomplish this task, the stepper first restores the simulation state to
the last saved snapshot (state 3), and then simulates for two major times
steps to arrive at the desired state (5). This capability is helpful for memory
usage and simulation performance.

Stepping to the final step ends the simulation. This means that stepping
backward after reaching the end of simulation is not possible unless you
restart the simulation.

Tune Parameters
While using the stepper, if the simulation is in a paused state, you can change
tunable parameters, including some solver settings.
Although you can change tunable parameters when a simulation is paused (as
part of stepping or by using the Pause button), changes to the solver step size

2-16

Step Through a Simulation

take effect when the solver advances the simulation time. For some solvers,
this occurs after the next simulation step is taken.
The Simulation Stepper takes into account the size of a movement (Move
back/forward by) and the frequency of saving backward steps (Interval
between stored back steps). If you specify a frequency that is larger than
the step size, the stepper first steps back to the last saved step, then simulates
forward until the total step count difference reaches the size of the step. Note
that new tunable parameters are applied when simulating forward. For
this reason, in a scenario like this, if you change tunable parameters before
stepping back, the resulting simulation output might not match the previous
simulation output at that step.
For example, assume a snapshot save frequency of 3 and a step size of 1 ( see
the previous figure). The stepper first steps back to the last saved step, up
to three steps, then simulates forward until the total step count difference
reaches one. If you change tunable parameters before stepping back, the
resulting simulation output might not match the previous simulation output
at that step.

Referenced Models
When using the stepper and Model block, the referenced model uses the
stepping options of the top model for the duration of a simulation. In addition,
the stepper dialog box of the referenced model serves as a direct link to the
settings of the top model. As a result, changing the stepper settings through
the referenced model during simulation also changes the stepper settings
of the top model. When the simulation ends, the stepper settings of the
referenced model revert to the original values.
This table illustrates this behavior for the Move back/forward by parameter
(number of steps):

2-17

2

Simulation Stepping

Simulation Off

Simulation On

Changed
Referenced Model
Setting

Simulation Off

Top Model

Number of steps =
Original
OrgTopModel
top model
number
of steps
(OrgTopModel)

New number
of steps
(NewRefModel)
copied from
referenced model

Keeps value
NewRefModel

Referenced
Model

Number of steps =
Original
OrgTopModel
referenced
model
number
of steps
(OrgRefModel)

New number
of steps =
NewRefModel

Reverts to original
referenced model
number of steps
OrgRefModel

Simulation Stepper and Stateflow Debugger
When you debug a Stateflow chart (for example, when the simulation stops at
a Stateflow breakpoint), Simulation Stepper changes to contain additional
buttons to control the Stateflow debugging session. When the Stateflow
debugging session ends, the default Simulation Stepper interface is reinstated.
For more information about controlling the Stateflow debugger through the
Simulink Editor toolbar, see “Control Chart Execution in the Debugger”.

Conditional Breakpoints
The Simulation Stepper allows you to set conditional breakpoints for scalar
signals. A conditional breakpoint is a breakpoint that is triggered based on a
certain expression evaluated on a signal. When the breakpoint is triggered,
the corresponding simulation pauses.
Note When simulation arrives at a conditional breakpoint, simulation does
not stop immediately when the block is executed. Instead, simulation stops
only after the current simulation step completes.
To set a conditional breakpoint for a signal:

2-18

Step Through a Simulation

1 Right-click that signal and select Add Conditional Breakpoint.

Alternatively, select the signal then, from the menu bar, select
Simulation > Debug > Add Conditional Breakpoint.
Note You cannot add conditional breakpoints on inputs to, outputs from,
or signals inside variant subsystems.
This action displays the Add Conditional Breakpoint dialog box.

2 From the drop-down list, select the condition for this signal:

2-19

2

Simulation Stepping

Condition Pause simulation if the signal value is...
>

Greater than the specified value.

>=

Greater than or equal to the specified value.

=

Equal to the specified value.

~=

Not equal to the specified value.

<=

Less than or equal to the specified value.

<

Less than the specified value.

3 Enter the signal value at which you want simulation to pause. The affected

signal line is updated with a conditional breakpoint icon like the following,
.
You can add multiple conditional breakpoints to a signal line.
4 To view a summary of the conditional breakpoints and edit them, left-click

the conditional breakpoint icon. (Alternatively, from the menu bar,
select Simulation > Debug > Conditional Breakpoints List.) A
Conditional Breakpoints List dialog box like the following is displayed. If
the conditional breakpoints list is empty, a message pops up to warn you
that there are no conditional breakpoints.

In this dialog box, you can:
• Change the condition for the signal value.

2-20

Step Through a Simulation

• Change the value of the signal.
• Disable and enable the conditional breakpoint.
• Delete the condition.
Condition values:
• Must be numeric. They cannot be expressions.
• Cannot be NaN.
5 Click OK when done and simulate the model.

2-21

2

2-22

Simulation Stepping

3
How Simulink Works
• “How Simulink Works” on page 3-2
• “Modeling Dynamic Systems” on page 3-3
• “Simulating Dynamic Systems” on page 3-18

3

How Simulink® Works

How Simulink Works
Simulink is a software package that enables you to model, simulate, and
analyze systems whose outputs change over time. Such systems are often
referred to as dynamic systems. The Simulink software can be used to explore
the behavior of a wide range of real-world dynamic systems, including
electrical circuits, shock absorbers, braking systems, and many other
electrical, mechanical, and thermodynamic systems. This section explains
how Simulink works.
Simulating a dynamic system is a two-step process. First, a user creates a
block diagram, using the Simulink model editor, that graphically depicts
time-dependent mathematical relationships among the system’s inputs,
states, and outputs. The user then commands the Simulink software to
simulate the system represented by the model from a specified start time to
a specified stop time.
For more information on this process, see:
• “Modeling Dynamic Systems” on page 3-3
• “Simulating Dynamic Systems” on page 3-18

3-2

Modeling Dynamic Systems

Modeling Dynamic Systems
In this section...
“Block Diagram Semantics” on page 3-3
“Creating Models” on page 3-4
“Time” on page 3-5
“States” on page 3-5
“Block Parameters” on page 3-9
“Tunable Parameters” on page 3-9
“Block Sample Times” on page 3-9
“Custom Blocks” on page 3-10
“Systems and Subsystems” on page 3-11
“Signals” on page 3-16
“Block Methods” on page 3-16
“Model Methods” on page 3-17

Block Diagram Semantics
A classic block diagram model of a dynamic system graphically consists
of blocks and lines (signals). The history of these block diagram models
is derived from engineering areas such as Feedback Control Theory and
Signal Processing. A block within a block diagram defines a dynamic system
in itself. The relationships between each elementary dynamic system in a
block diagram are illustrated by the use of signals connecting the blocks.
Collectively the blocks and lines in a block diagram describe an overall
dynamic system.
The Simulink product extends these classic block diagram models by
introducing the notion of two classes of blocks, nonvirtual blocks and virtual
blocks. Nonvirtual blocks represent elementary systems. Virtual blocks exist
for graphical and organizational convenience only: they have no effect on
the system of equations described by the block diagram model. You can use
virtual blocks to improve the readability of your models.

3-3

3

How Simulink® Works

In general, blocks and lines can be used to describe many “models of
computations.” One example would be a flow chart. A flow chart consists of
blocks and lines, but one cannot describe general dynamic systems using
flow chart semantics.
The term “time-based block diagram” is used to distinguish block diagrams
that describe dynamic systems from that of other forms of block diagrams,
and the term block diagram (or model) is used to refer to a time-based block
diagram unless the context requires explicit distinction.
To summarize the meaning of time-based block diagrams:
• Simulink block diagrams define time-based relationships between signals
and state variables. The solution of a block diagram is obtained by
evaluating these relationships over time, where time starts at a user
specified “start time” and ends at a user specified “stop time.” Each
evaluation of these relationships is referred to as a time step.
• Signals represent quantities that change over time and are defined for all
points in time between the block diagram’s start and stop time.
• The relationships between signals and state variables are defined by a set
of equations represented by blocks. Each block consists of a set of equations
(block methods). These equations define a relationship between the input
signals, output signals and the state variables. Inherent in the definition
of a equation is the notion of parameters, which are the coefficients found
within the equation.

Creating Models
The Simulink product provides a graphical editor that allows you to create
and connect instances of block types (see “Connect Blocks” on page 4-12)
selected from libraries of block types (see “Block Libraries”) via a library
browser. Libraries of blocks are provided representing elementary systems
that can be used as building blocks. The blocks supplied with Simulink are
called built-in blocks. Users can also create their own block types and use
the Simulink editor to create instances of them in a diagram. User-defined
blocks are called custom blocks.

3-4

Modeling Dynamic Systems

Time
Time is an inherent component of block diagrams in that the results of a block
diagram simulation change with time. Put another way, a block diagram
represents the instantaneous behavior of a dynamic system. Determining
a system’s behavior over time thus entails repeatedly solving the model at
intervals, called time steps, from the start of the time span to the end of the
time span. The process of solving a model at successive time steps is referred
to as simulating the system that the model represents.

States
Typically the current values of some system, and hence model, outputs are
functions of the previous values of temporal variables. Such variables are
called states. Computing a model’s outputs from a block diagram hence
entails saving the value of states at the current time step for use in computing
the outputs at a subsequent time step. This task is performed during
simulation for models that define states.
Two types of states can occur in a Simulink model: discrete and continuous
states. A continuous state changes continuously. Examples of continuous
states are the position and speed of a car. A discrete state is an approximation
of a continuous state where the state is updated (recomputed) using finite
(periodic or aperiodic) intervals. An example of a discrete state would be the
position of a car shown on a digital odometer where it is updated every second
as opposed to continuously. In the limit, as the discrete state time interval
approaches zero, a discrete state becomes equivalent to a continuous state.
Blocks implicitly define a model’s states. In particular, a block that needs
some or all of its previous outputs to compute its current outputs implicitly
defines a set of states that need to be saved between time steps. Such a block
is said to have states.
The following is a graphical representation of a block that has states:

3-5

3

How Simulink® Works

Blocks that define continuous states include the following standard Simulink
blocks:
• Integrator
• State-Space
• Transfer Fcn
• Variable Transport Delay
• Zero-Pole
The total number of a model’s states is the sum of all the states defined
by all its blocks. Determining the number of states in a diagram requires
parsing the diagram to determine the types of blocks that it contains and then
aggregating the number of states defined by each instance of a block type
that defines states. This task is performed during the Compilation phase
of a simulation.

Working with States
The following facilities are provided for determining, initializing, and logging
a model’s states during simulation:
• The model command displays information about the states defined by a
model, including the total number of states defined by the model, the block
that defines each state, and the initial value of each state.
• The Simulink debugger displays the value of a state at each time step
during a simulation, and the Simulink debugger’s states command
displays information about the model’s current states (see “Debugging”).
• The Data Import/Export pane of a model’s Configuration Parameters
dialog box (see “Import and Export States” on page 45-113) allows you to
specify initial values for a model’s states, and to record the values of the
states at each time step during simulation as an array or structure variable
in the MATLAB workspace.
• The Block Parameters dialog box (and the ContinuousStateAttributes
parameter) allows you to give names to states for those blocks (such as the
Integrator) that employ continuous states. This can simplify analyzing
data logged for states, especially when a block has multiple states.

3-6

Modeling Dynamic Systems

The Two Cylinder Model with Load Constraints model illustrates the
logging of continuous states.

Continuous States
Computing a continuous state entails knowing its rate of change, or
derivative. Since the rate of change of a continuous state typically itself
changes continuously (i.e., is itself a state), computing the value of a
continuous state at the current time step entails integration of its derivative
from the start of a simulation. Thus modeling a continuous state entails
representing the operation of integration and the process of computing
the state’s derivative at each point in time. Simulink block diagrams use
Integrator blocks to indicate integration and a chain of blocks connected to
an integrator block’s input to represent the method for computing the state’s
derivative. The chain of blocks connected to the integrator block’s input is the
graphical counterpart to an ordinary differential equation (ODE).
In general, excluding simple dynamic systems, analytical methods do not
exist for integrating the states of real-world dynamic systems represented
by ordinary differential equations. Integrating the states requires the use
of numerical methods called ODE solvers. These various methods trade
computational accuracy for computational workload. The Simulink product
comes with computerized implementations of the most common ODE
integration methods and allows a user to determine which it uses to integrate
states represented by Integrator blocks when simulating a system.
Computing the value of a continuous state at the current time step entails
integrating its values from the start of the simulation. The accuracy of
numerical integration in turn depends on the size of the intervals between
time steps. In general, the smaller the time step, the more accurate the
simulation. Some ODE solvers, called variable time step solvers, can
automatically vary the size of the time step, based on the rate of change
of the state, to achieve a specified level of accuracy over the course of a
simulation. The user can specify the size of the time step in the case of
fixed-step solvers, or the solver can automatically determine the step size in
the case of variable-step solvers. To minimize the computation workload, the
variable-step solver chooses the largest step size consistent with achieving an
overall level of precision specified by the user for the most rapidly changing
model state. This ensures that all model states are computed to the accuracy
specified by the user.

3-7

3

How Simulink® Works

Discrete States
Computing a discrete state requires knowing the relationship between its
value at the current time step and its value at the previous time step. This is
referred to this relationship as the state’s update function. A discrete state
depends not only on its value at the previous time step but also on the values
of a model’s inputs. Modeling a discrete state thus entails modeling the state’s
dependency on the systems’ inputs at the previous time step. Simulink block
diagrams use specific types of blocks, called discrete blocks, to specify update
functions and chains of blocks connected to the inputs of discrete blocks to
model the dependency of a system’s discrete states on its inputs.
As with continuous states, discrete states set a constraint on the simulation
time step size. Specifically, the step size must ensure that all the sample
times of the model’s states are hit. This task is assigned to a component of the
Simulink system called a discrete solver. Two discrete solvers are provided: a
fixed-step discrete solver and a variable-step discrete solver. The fixed-step
discrete solver determines a fixed step size that hits all the sample times
of all the model’s discrete states, regardless of whether the states actually
change value at the sample time hits. By contrast, the variable-step discrete
solver varies the step size to ensure that sample time hits occur only at times
when the states change value.

Modeling Hybrid Systems
A hybrid system is a system that has both discrete and continuous states.
Strictly speaking, any model that has both continuous and discrete sample
times is treated as a hybrid model, presuming that the model has both
continuous and discrete states. Solving such a model entails choosing a
step size that satisfies both the precision constraint on the continuous state
integration and the sample time hit constraint on the discrete states. The
Simulink software meets this requirement by passing the next sample time
hit, as determined by the discrete solver, as an additional constraint on
the continuous solver. The continuous solver must choose a step size that
advances the simulation up to but not beyond the time of the next sample
time hit. The continuous solver can take a time step short of the next sample
time hit to meet its accuracy constraint but it cannot take a step beyond the
next sample time hit even if its accuracy constraint allows it to.
You can simulate hybrid systems using any one of the integration methods,
but certain methods are more effective than others. For most hybrid systems,

3-8

Modeling Dynamic Systems

ode23 and ode45 are superior to the other solvers in terms of efficiency.
Because of discontinuities associated with the sample and hold of the discrete
blocks, do not use the ode15s and ode113 solvers for hybrid systems.

Block Parameters
Key properties of many standard blocks are parameterized. For example,
the Constant value of the Simulink Constant block is a parameter. Each
parameterized block has a block dialog that lets you set the values of the
parameters. You can use MATLAB expressions to specify parameter values.
Simulink evaluates the expressions before running a simulation. You can
change the values of parameters during a simulation. This allows you to
determine interactively the most suitable value for a parameter.
A parameterized block effectively represents a family of similar blocks. For
example, when creating a model, you can set the Constant value parameter of
each instance of the Constant block separately so that each instance behaves
differently. Because it allows each standard block to represent a family of
blocks, block parameterization greatly increases the modeling power of the
standard Simulink libraries. See “Block Parameters” on page 3-9 and “Block
Libraries” for more information.

Tunable Parameters
Many block parameters are tunable. A tunable parameter is a parameter
whose value can be changed without recompiling the model (see “Model
Compilation” on page 3-18 for more information on compiling a model). For
example, the gain parameter of the Gain block is tunable. You can alter the
block’s gain while a simulation is running. If a parameter is not tunable and
the simulation is running, the dialog box control that sets the parameter
is disabled.
When you change the value of a tunable parameter, the change takes effect
at the start of the next time step. See “Block Parameters” on page 3-9 and
“Tunable Parameters” on page 24-13 for more information.

Block Sample Times
Every Simulink block has a sample time which defines when the block will
execute . Most blocks allow you to specify the sample time via a SampleTime

3-9

3

How Simulink® Works

parameter. Common choices include discrete, continuous, and inherited
sample times.
Common Sample
Time Types

Sample Time

Examples

Discrete

[Ts, To]

Unit Delay, Digital
Filter

Continuous

[0, 0]

Integrator, Derivative

Inherited

[–1, 0]

Gain, Sum

For discrete blocks, the sample time is a vector [Ts, To] where Ts is the time
interval or period between consecutive sample times and To is an initial offset
to the sample time. In contrast, the sample times for nondiscrete blocks are
represented by ordered pairs that use zero, a negative integer, or infinity to
represent a specific type of sample time (see “View Sample Time Information”
on page 5-9). For example, continuous blocks have a nominal sample time of
[0, 0] and are used to model systems in which the states change continuously
(e.g., a car accelerating). Whereas you indicate the sample time type of an
inherited block symbolically as [–1, 0] and Simulink then determines the
actual value based upon the context of the inherited block within the model.
Note that not all blocks accept all types of sample times. For example, a
discrete block cannot accept a continuous sample time.
For a visual aid, Simulink allows the optional color-coding and annotation of
any block diagram to indicate the type and speed of the block sample times.
You can capture all of the colors and the annotations within a legend (see
“View Sample Time Information” on page 5-9).
For a more detailed discussion of sample times, see “Sample Time”

Custom Blocks
You can create libraries of custom blocks that you can then use in your models.
You can create a custom block either graphically or programmatically. To
create a custom block graphically, you draw a block diagram representing
the block’s behavior, wrap this diagram in an instance of the Simulink
Subsystem block, and provide the block with a parameter dialog, using the

3-10

Modeling Dynamic Systems

Simulink block mask facility. To create a block programmatically, you create
a MATLAB file or a MEX-file that contains the block’s system functions (see
“S-Function Basics”). The resulting file is called an S-function. You then
associate the S-function with instances of the Simulink S-Function block in
your model. You can add a parameter dialog to your S-Function block by
wrapping it in a Subsystem block and adding the parameter dialog to the
Subsystem block. See “Block Creation” for more information.

Systems and Subsystems
A Simulink block diagram can consist of layers. Each layer is defined by a
subsystem. A subsystem is part of the overall block diagram and ideally has
no impact on the meaning of the block diagram. Subsystems are provided
primarily to help with the organizational aspects of a block diagram.
Subsystems do not define a separate block diagram.
The Simulink software differentiates between two different types of
subsystems: virtual and nonvirtual. The primary difference is that nonvirtual
subsystems provide the ability to control when the contents of the subsystem
are evaluated.

Virtual Subsystems
Virtual subsystems provide graphical hierarchy in models. Virtual
subsystems do not impact execution. During model execution, the Simulink
engine flattens all virtual subsystems, i.e., Simulink expands the subsystem
in place before execution. This expansion is very similar to the way macros
work in a programming language such as C or C++. Roughly speaking, there
will be one system for the top-level block diagram which is referred to as
the root system, and several lower-level systems derived from nonvirtual
subsystems and other elements in the block diagram. You will see these
systems in the Simulink Debugger. The act of creating these internal systems
is often referred to as flattening the model hierarchy.

Nonvirtual Subsystems
Nonvirtual subsystems, which are drawn with a bold border, provide
execution and graphical hierarchy in models. Nonvirtual subsystems are
executed as a single unit (atomic execution) by the Simulink engine. You
can create conditionally executed subsystems that are executed only when

3-11

3

How Simulink® Works

a precondition—such as a trigger, an enable, a function-call, or an action—
occurs (see “Conditional Subsystems”). Simulink always computes all inputs
used during the execution of a nonvirtual subsystem before executing the
subsystem. Simulink defines the following nonvirtual subsystems.
Atomic subsystems. The primary characteristic of an atomic subsystem is
that blocks in an atomic subsystem execute as a single unit. This provides
the advantage of grouping functional aspects of models at the execution
level. Any Simulink block can be placed in an atomic subsystem, including
blocks with different execution rates. You can create an atomic subsystem by
selecting the Treat as atomic unit option on a virtual subsystem (see the
Atomic Subsystem block for more information).
Enabled subsystems. An enabled subsystem behaves similarly to an
atomic subsystem, except that it executes only when the signal driving the
subsystem enable port is greater than zero. To create an enabled subsystem,
place an Enable Port block within a Subsystem block. You can configure an
enabled subsystem to hold or reset the states of blocks within the enabled
subsystem prior to a subsystem enabling action. Simply select the States
when enabling parameter of the Enable Port block. Similarly, you can
configure each output port of an enabled subsystem to hold or reset its output
prior to the subsystem disabling action. Select the Output when disabled
parameter in the Outport block.
Triggered subsystems. You create a triggered subsystem by placing a
trigger port block within a subsystem. The resulting subsystem executes
when a rising or falling edge with respect to zero is seen on the signal driving
the subsystem trigger port. The direction of the triggering edge is defined by
the Trigger type parameter on the trigger port block. Simulink limits the
type of blocks placed in a triggered subsystem to blocks that do not have
explicit sample times (i.e., blocks within the subsystem must have a sample
time of -1) because the contents of a triggered subsystem execute in an
aperiodic fashion. A Stateflow chart can also have a trigger port which is
defined by using the Stateflow editor. Simulink does not distinguish between
a triggered subsystem and a triggered chart.

3-12

Modeling Dynamic Systems

Function-call subsystems. A function-call subsystem is a subsystem that
another block can invoke directly during a simulation. It is analogous to a
function in a procedural programming language. Invoking a function-call
subsystem is equivalent to invoking the output and update methods of the
blocks that the subsystem contains in sorted order. The block that invokes
a function-call subsystem is called the function-call initiator. Stateflow,
Function-Call Generator, and S-function blocks can all serve as function-call
initiators. To create a function-call subsystem, drag a Function-Call
Subsystem block from the Ports & Subsystems library into your model and
connect a function-call initiator to the function-call port displayed on top of the
subsystem. You can also create a function-call subsystem from scratch by first
creating a Subsystem block in your model and then creating a Trigger block in
the subsystem and setting the Trigger block Trigger type to function-call.
You can configure a function-call subsystem to be triggered (the default) or
periodic by setting its Sample time type to be triggered or periodic,
respectively. A function-call initiator can invoke a triggered function-call
subsystem zero, once, or multiple times per time step. The sample times of all
the blocks in a triggered function-call subsystem must be set to inherited (-1).
A function-call initiator can invoke a periodic function-call subsystem only
once per time step and must invoke the subsystem periodically. If the
initiator invokes a periodic function-call subsystem aperiodically, Simulink
halts the simulation and displays an error message. The blocks in a periodic
function-call subsystem can specify a noninherited sample time or inherited
(-1) sample time. All blocks that specify a noninherited sample time must
specify the same sample time, that is, if one block specifies .1 as its sample
time, all other blocks must specify a sample time of .1 or -1. If a function-call
initiator invokes a periodic function-call subsystem at a rate that differs from
the sample time specified by the blocks in the subsystem, Simulink halts the
simulation and displays an error message.

3-13

3

How Simulink® Works

Enabled and triggered subsystems. You can create an enabled and
triggered subsystem by placing a Trigger Port block and an Enable Port block
within a Subsystem block. The resulting subsystem is essentially a triggered
subsystem that executes when the subsystem is enabled and a rising or
falling edge with respect to zero is seen on the signal driving the subsystem
trigger port. The direction of the triggering edge is defined by the Trigger
type parameter on the trigger port block. Because the contents of a triggered
subsystem execute in an aperiodic fashion, Simulink limits the types of blocks
placed in an enabled and triggered subsystem to blocks that do not have
explicit sample times. In other words, blocks within the subsystem must
have a sample time of -1).
Action subsystems. Action subsystems can be thought of as an intersection
of the properties of enabled subsystems and function-call subsystems. Action
subsystems are restricted to a single sample time (e.g., a continuous, discrete,
or inherited sample time). Action subsystems must be executed by an action
subsystem initiator. This is either an If block or a Switch Case block. All
action subsystems connected to a given action subsystem initiator must have
the same sample time. An action subsystem is created by placing an Action
Port block within a Subsystem block. The subsystem icon will automatically
adapt to the type of block (i.e., If or Switch Case block) that is executing the
action subsystem.
Action subsystems can be executed at most once by the action subsystem
initiator. Action subsystems give you control over when the states reset via
the States when execution is resumed parameter on the Action Port
block. Action subsystems also give you control over whether or not to hold
the outport values via the Output when disabled parameter on the outport
block. This is analogous to enabled subsystems.
Action subsystems behave very similarly to function-call subsystems because
they must be executed by an initiator block. Function-call subsystems can be
executed more than once at any given time step whereas action subsystems can
be executed at most once. This restriction means that a larger set of blocks
(e.g., periodic blocks) can be placed in action subsystems as compared to
function-call subsystems. This restriction also means that you can control
how the states and outputs behave.

3-14

Modeling Dynamic Systems

While iterator subsystems. A while iterator subsystem will run multiple
iterations on each model time step. The number of iterations is controlled by
the While Iterator block condition. A while iterator subsystem is created by
placing a While Iterator block within a subsystem block.
A while iterator subsystem is very similar to a function-call subsystem in that
it can run for any number of iterations at a given time step. The while iterator
subsystem differs from a function-call subsystem in that there is no separate
initiator (e.g., a Stateflow Chart). In addition, a while iterator subsystem
has access to the current iteration number optionally produced by the While
Iterator block. A while iterator subsystem also gives you control over whether
or not to reset states when starting via the States when starting parameter
on the While Iterator block.
For iterator subsystems. A for iterator subsystem will run a fixed number
of iterations at each model time step. The number of iterations can be an
external input to the for iterator subsystem or specified internally on the For
Iterator block. A for iterator subsystem is created by placing a For Iterator
block within a subsystem block.
A for iterator subsystem has access to the current iteration number that is
optionally produced by the For Iterator block. A for iterator subsystem also
gives you control over whether or not to reset states when starting via the
States when starting parameter on the For Iterator block. A for iterator
subsystem is very similar to a while iterator subsystem with the restriction
that the number of iterations during any given time step is fixed.
For each subsystems. The for each subsystem allows you to repeat an
algorithm for individual elements (or subarrays) of an input signal. Here,
the algorithm is represented by the set of blocks in the subsystem and is
applied to a single element (or subarray) of the signal. You can configure the
decomposition of the subsystem inputs into elements (or subarrays) using the
For Each block, which resides in the subsystem. The For Each block also
allows you to configure the concatenation of individual results into output
signals. An advantage of this subsystem is that it maintains separate sets of
states for each element or subarray that it processes. In addition, for certain
models, the for each subsystem improves the code reuse of the code generated
by Simulink Coder™.

3-15

3

How Simulink® Works

Signals
The term signal refers to a time varying quantity that has values at all
points in time. You can specify a wide range of signal attributes, including
signal name, data type (e.g., 8-bit, 16-bit, or 32-bit integer), numeric type
(real or complex), and dimensionality (one-dimensional, two-dimensional, or
multidimensional array). Many blocks can accept or output signals of any
data or numeric type and dimensionality. Others impose restrictions on the
attributes of the signals they can handle.
On the block diagram, signals are represented with lines that have an
arrowhead. The source of the signal corresponds to the block that writes to the
signal during evaluation of its block methods (equations). The destinations of
the signal are blocks that read the signal during the evaluation of the block’s
methods (equations).
A good way to understand the definition of a signal is to consider a classroom.
The teacher is the one responsible for writing on the white board and the
students read what is written on the white board when they choose to. This
is also true of Simulink signals: a reader of the signal (a block method) can
choose to read the signal as frequently or infrequently as so desired.
For more information about signals, see “Signals”.

Block Methods
Blocks represent multiple equations. These equations are represented as
block methods. These block methods are evaluated (executed) during the
execution of a block diagram. The evaluation of these block methods is
performed within a simulation loop, where each cycle through the simulation
loop represents the evaluation of the block diagram at a given point in time.

Method Types
Names are assigned to the types of functions performed by block methods.
Common method types include:
• Outputs
Computes the outputs of a block given its inputs at the current time step
and its states at the previous time step.

3-16

Modeling Dynamic Systems

• Update
Computes the value of the block’s discrete states at the current time step,
given its inputs at the current time step and its discrete states at the
previous time step.
• Derivatives
Computes the derivatives of the block’s continuous states at the current
time step, given the block’s inputs and the values of the states at the
previous time step.

Method Naming Convention
Block methods perform the same types of operations in different ways for
different types of blocks. The Simulink user interface and documentation uses
dot notation to indicate the specific function performed by a block method:
BlockType.MethodType

For example, the method that computes the outputs of a Gain block is referred
to as
Gain.Outputs

The Simulink debugger takes the naming convention one step further and
uses the instance name of a block to specify both the method type and the
block instance on which the method is being invoked during simulation, e.g.,
g1.Outputs

Model Methods
In addition to block methods, a set of methods is provided that compute the
model’s properties and its outputs. The Simulink software similarly invokes
these methods during simulation to determine a model’s properties and its
outputs. The model methods generally perform their tasks by invoking block
methods of the same type. For example, the model Outputs method invokes
the Outputs methods of the blocks that it contains in the order specified by
the model to compute its outputs. The model Derivatives method similarly
invokes the Derivatives methods of the blocks that it contains to determine
the derivatives of its states.

3-17

3

How Simulink® Works

Simulating Dynamic Systems
In this section...
“Model Compilation” on page 3-18
“Link Phase” on page 3-19
“Simulation Loop Phase” on page 3-19
“Solvers” on page 3-21
“Zero-Crossing Detection” on page 3-23
“Algebraic Loops” on page 3-39

Model Compilation
The first phase of simulation occurs when the system’s model is open and
you simulate the model. In the Simulink Editor, select Simulation > Run.
Running the simulation causes the Simulink engine to invoke the model
compiler. The model compiler converts the model to an executable form, a
process called compilation. In particular, the compiler:
• Evaluates the model’s block parameter expressions to determine their
values.
• Determines signal attributes, e.g., name, data type, numeric type, and
dimensionality, not explicitly specified by the model and checks that each
block can accept the signals connected to its inputs.
• A process called attribute propagation is used to determine unspecified
attributes. This process entails propagating the attributes of a source
signal to the inputs of the blocks that it drives.
• Performs block reduction optimizations.
• Flattens the model hierarchy by replacing virtual subsystems with the
blocks that they contain (see “Solvers” on page 3-21).
• Determines the block sorted order (see “Control and Displaying the Sorted
Order” on page 23-35 for more information).

3-18

Simulating Dynamic Systems

• Determines the sample times of all blocks in the model whose sample times
you did not explicitly specify (see “How Propagation Affects Inherited
Sample Times” on page 5-29).

Link Phase
In this phase, the Simulink engine allocates memory needed for working
areas (signals, states, and run-time parameters) for execution of the block
diagram. It also allocates and initializes memory for data structures that
store run-time information for each block. For built-in blocks, the principal
run-time data structure for a block is called the SimBlock. It stores pointers
to a block’s input and output buffers and state and work vectors.

Method Execution Lists
In the Link phase, the Simulink engine also creates method execution lists.
These lists list the most efficient order in which to invoke a model’s block
methods to compute its outputs. The block sorted order lists generated during
the model compilation phase is used to construct the method execution lists.

Block Priorities
You can assign update priorities to blocks (see “Assign Block Priorities” on
page 23-47). The output methods of higher priority blocks are executed before
those of lower priority blocks. The priorities are honored only if they are
consistent with its block sorting rules.

Simulation Loop Phase
Once the Link Phase completes, the simulation enters the simulation loop
phase. In this phase, the Simulink engine successively computes the states
and outputs of the system at intervals from the simulation start time to the
finish time, using information provided by the model. The successive time
points at which the states and outputs are computed are called time steps.
The length of time between steps is called the step size. The step size depends
on the type of solver (see “Solvers” on page 3-21) used to compute the system’s
continuous states, the system’s fundamental sample time (see “Sample Times
in Systems” on page 5-22), and whether the system’s continuous states have
discontinuities (see “Zero-Crossing Detection” on page 3-23).

3-19

3

How Simulink® Works

The Simulation Loop phase has two subphases: the Loop Initialization phase
and the Loop Iteration phase. The initialization phase occurs once, at the
start of the loop. The iteration phase is repeated once per time step from the
simulation start time to the simulation stop time.
At the start of the simulation, the model specifies the initial states and
outputs of the system to be simulated. At each step, new values for the
system’s inputs, states, and outputs are computed, and the model is updated
to reflect the computed values. At the end of the simulation, the model reflects
the final values of the system’s inputs, states, and outputs. The Simulink
software provides data display and logging blocks. You can display and/or log
intermediate results by including these blocks in your model.

Loop Iteration
At each time step, the Simulink engine:
1 Computes the model’s outputs.

The Simulink engine initiates this step by invoking the Simulink model
Outputs method. The model Outputs method in turn invokes the model
system Outputs method, which invokes the Outputs methods of the blocks
that the model contains in the order specified by the Outputs method
execution lists generated in the Link phase of the simulation (see “Solvers”
on page 3-21).
The system Outputs method passes the following arguments to each
block Outputs method: a pointer to the block’s data structure and to its
SimBlock structure. The SimBlock data structures point to information
that the Outputs method needs to compute the block’s outputs, including
the location of its input buffers and its output buffers.
2 Computes the model’s states.

The Simulink engine computes a model’s states by invoking a solver. Which
solver it invokes depends on whether the model has no states, only discrete
states, only continuous states, or both continuous and discrete states.
If the model has only discrete states, the Simulink engine invokes the
discrete solver selected by the user. The solver computes the size of the
time step needed to hit the model’s sample times. It then invokes the

3-20

Simulating Dynamic Systems

Update method of the model. The model Update method invokes the
Update method of its system, which invokes the Update methods of each of
the blocks that the system contains in the order specified by the Update
method lists generated in the Link phase.
If the model has only continuous states, the Simulink engine invokes the
continuous solver specified by the model. Depending on the solver, the
solver either in turn calls the Derivatives method of the model once or
enters a subcycle of minor time steps where the solver repeatedly calls
the model’s Outputs methods and Derivatives methods to compute the
model’s outputs and derivatives at successive intervals within the major
time step. This is done to increase the accuracy of the state computation.
The model Outputs method and Derivatives methods in turn invoke their
corresponding system methods, which invoke the block Outputs and
Derivatives in the order specified by the Outputs and Derivatives methods
execution lists generated in the Link phase.
3 Optionally checks for discontinuities in the continuous states of blocks.

A technique called zero-crossing detection is used to detect discontinuities
in continuous states. See “Zero-Crossing Detection” on page 3-23 for more
information.
4 Computes the time for the next time step.

Steps 1 through 4 are repeated until the simulation stop time is reached.

Solvers
A dynamic system is simulated by computing its states at successive time
steps over a specified time span, using information provided by the model.
The process of computing the successive states of a system from its model is
known as solving the model. No single method of solving a model suffices for
all systems. Accordingly, a set of programs, known as solvers, are provided
that each embody a particular approach to solving a model. The Configuration
Parameters dialog box allows you to choose the solver most suitable for your
model (see “Choosing a Solver Type” on page 14-10).

3-21

3

How Simulink® Works

Fixed-Step Solvers Versus Variable-Step Solvers
The solvers provided in the Simulink software fall into two basic categories:
fixed-step and variable-step.
Fixed-step solvers solve the model at regular time intervals from the beginning
to the end of the simulation. The size of the interval is known as the step size.
You can specify the step size or let the solver choose the step size. Generally,
decreasing the step size increases the accuracy of the results while increasing
the time required to simulate the system.
Variable-step solvers vary the step size during the simulation, reducing the
step size to increase accuracy when a model’s states are changing rapidly
and increasing the step size to avoid taking unnecessary steps when the
model’s states are changing slowly. Computing the step size adds to the
computational overhead at each step but can reduce the total number of steps,
and hence simulation time, required to maintain a specified level of accuracy
for models with rapidly changing or piecewise continuous states.

Continuous Versus Discrete Solvers
The Simulink product provides both continuous and discrete solvers.
Continuous solvers use numerical integration to compute a model’s continuous
states at the current time step based on the states at previous time steps and
the state derivatives. Continuous solvers rely on the individual blocks to
compute the values of the model’s discrete states at each time step.
Mathematicians have developed a wide variety of numerical integration
techniques for solving the ordinary differential equations (ODEs) that
represent the continuous states of dynamic systems. An extensive set of
fixed-step and variable-step continuous solvers are provided, each of which
implements a specific ODE solution method (see “Choosing a Solver Type”
on page 14-10).
Discrete solvers exist primarily to solve purely discrete models. They compute
the next simulation time step for a model and nothing else. In performing
these computations, they rely on each block in the model to update its
individual discrete states. They do not compute continuous states.

3-22

Simulating Dynamic Systems

Note You must use a continuous solver to solve a model that contains both
continuous and discrete states. You cannot use a discrete solver because
discrete solvers cannot handle continuous states. If, on the other hand, you
select a continuous solver for a model with no states or discrete states only,
Simulink software uses a discrete solver.
Two discrete solvers are provided: A fixed-step discrete solver and a
variable-step discrete solver. The fixed-step solver by default chooses a step
size and hence simulation rate fast enough to track state changes in the fastest
block in your model. The variable-step solver adjusts the simulation step size
to keep pace with the actual rate of discrete state changes in your model. This
can avoid unnecessary steps and hence shorten simulation time for multirate
models (see “Sample Times in Systems” on page 5-22 for more information).

Minor Time Steps
Some continuous solvers subdivide the simulation time span into major and
minor time steps, where a minor time step represents a subdivision of the
major time step. The solver produces a result at each major time step. It
uses results at the minor time steps to improve the accuracy of the result at
the major time step.

Shape Preservation
Usually the integration step size is only related to the current step size and
the current integration error. However, for signals whose derivative changes
rapidly, you can obtain a more accurate integration results by including the
derivative input information at each time step. To do so, enable the Model
Configuration Parameters > Solver > Shape Preservation option.

Zero-Crossing Detection
A variable-step solver dynamically adjusts the time step size, causing it to
increase when a variable is changing slowly and to decrease when the variable
changes rapidly. This behavior causes the solver to take many small steps in
the vicinity of a discontinuity because the variable is rapidly changing in this
region. This improves accuracy but can lead to excessive simulation times.

3-23

3

How Simulink® Works

The Simulink software uses a technique known as zero-crossing detection to
accurately locate a discontinuity without resorting to excessively small time
steps. Usually this technique improves simulation run time, but it can cause
some simulations to halt before the intended completion time.
Two algorithms are provided in the Simulink software: Nonadaptive and
Adaptive. For information about these techniques, see “Zero-Crossing
Algorithms” on page 3-33.

Demonstrating Effects of Excessive Zero-Crossing Detection
The Simulink software comes with three models that illustrate zero-crossing
behavior: sldemo_bounce_two_integrators, sldemo_doublebounce, and
sldemo_bounce.
• The sldemo_bounce_two_integrators model demonstrates how excessive
zero crossings can cause a simulation to halt before the intended completion
time unless you use the adaptive algorithm.
• The sldemo_bounce model uses a better model design than
sldemo_bounce_two_integrators.
• The sldemo_doublebounce model demonstrates how the adaptive
algorithm successfully solves a complex system with two distinct
zero-crossing requirements.

3-24

Simulating Dynamic Systems

The Bounce Model with Two Integrators.

1 At the MATLAB command prompt, type sldemo_bounce_two_integrators

to load the example.
2 Once the block diagram appears, set the Model Configuration

Parameters > Solver > Algorithm parameter to Nonadaptive.
3 Also in the Solver pane, set the Stop time parameter to 20 s.
4 Run the model. In the Simulink Editor, select Simulation > Run.
5 After the simulation completes, click the Scope block window to see the

results.
You may need to click on Autoscale to view the results in their entirety.

3-25

3

How Simulink® Works

6 Use the scope zoom controls to closely examine the last portion of the

simulation. You can see that the velocity is hovering just above zero at the
last time point.

3-26

Simulating Dynamic Systems

7 Change the simulation Stop time edit box in the Simulink Editor toolbar

to 25 seconds, and run the simulation again.
8 This time the simulation halts with an error shortly after it passes the

simulated 20 second time point.
Excessive chattering as the ball repeatedly approaches zero velocity has
caused the simulation to exceed the default limit of 1000 for the number of
consecutive zero crossings allowed. Although you can increase this limit by
adjusting the Model Configuration Parameters > Solver > Number
of consecutive zero crossings parameter. In this case, making that
change does not allow the simulation to simulate for 25 seconds.
9 Also in the Solver pane, from the Algorithm pull down menu, select the

Adaptive algorithm.
10 Run the simulation again.
11 This time the simulation runs to completion because the adaptive algorithm

prevented an excessive number of zero crossings from occurring.

3-27

3

How Simulink® Works

Bounce Model with a Second-Order Integrator.

3-28

Simulating Dynamic Systems

The Double-Bounce Model.

1 At the MATLAB command prompt, type sldemo_doublebounce to load the

example. The model and an animation window open. In the animation
window, two balls are resting on two platforms.
2 In the animation window, click the Nonadaptive button to run the

example using the nonadaptive algorithm. This is the default setting used
by the Simulink software for all models.
3 The ball on the right is given a larger initial velocity and has Consequently,

the two balls hit the ground and recoil at different times.
4 The simulation halts after 14 seconds because the ball on the left exceeded

the number of zero crossings limit. The ball on the right is left hanging in
mid air.
5 An error message dialog opens. Click OK to close it.
6 Click on the Adaptive button to run the simulation with the adaptive

algorithm.

3-29

3

How Simulink® Works

7 Notice that this time the simulation runs to completion, even after the

ground shifts out from underneath the ball on the left at 20 seconds.

How the Simulator Can Miss Zero-Crossing Events
The bounce and double-bounce models show that high-frequency fluctuations
about a discontinuity (’chattering’) can cause a simulation to prematurely halt.
It is also possible for the solver to entirely miss zero crossings if the solver
error tolerances are too large. This is possible because the zero-crossing
detection technique checks to see if the value of a signal has changed sign
after a major time step. A sign change indicates that a zero crossing has
occurred, and the zero-crossing algorithm will then hunt for the precise
crossing time. However, if a zero crossing occurs within a time step, but the
values at the beginning and end of the step do not indicate a sign change, the
solver steps over the crossing without detecting it.
The following figure shows a signal that crosses zero. In the first instance,
the integrator steps over the event because the sign has not changed between
time steps. In the second, the solver detects change in sign and so detects
the zero-crossing event.

Preventing Excessive Zero Crossings
Use the following table to prevent excessive zero-crossing errors in your model.

3-30

Simulating Dynamic Systems

Make this
change...

How to make this
change...

Rationale for making
this change...

Increase the
number of
allowed zero
crossings

Increase the value of the
Number of consecutive
zero crossings. option
on the Solver pane in the
Configuration Parameters
dialog box.

This may give your model
enough time to resolve the
zero crossing.

Relax the
Signal
threshold

Select Adaptive from the
Algorithm pull down and
increase the value of the
Signal threshold option
on the Solver pane in the
Configuration Parameters
dialog box.

The solver requires less
time to precisely locate
the zero crossing. This
can reduce simulation
time and eliminate an
excessive number of
consecutive zero-crossing
errors. However, relaxing
the Signal threshold may
reduce accuracy.

Use the
Adaptive
Algorithm

Select Adaptive from the
Algorithm pull down on
the Solver pane in the
Configuration Parameters
dialog box.

This algorithm
dynamically adjusts the
zero-crossing threshold,
which improves accuracy
and reduces the number of
consecutive zero crossings
detected. With this
algorithm you have the
option of specifying both
the Time tolerance and
the Signal threshold.

3-31

3

How Simulink® Works

Make this
change...
Disable
zero-crossing
detection for a
specific block

How to make this
change...
1 Clear the Enable

zero-crossing
detection check box
on the block’s parameter
dialog box.
2 Select Use local

settings from
the Zero-crossing
control pull down
on the Solver pane
of the Configuration
Parameters dialog box.

Disable
zero-crossing
detection for the
entire model

If using the
ode15s solver,
consider
adjusting the
order of the
numerical
differentiation
formulas
Reduce the
maximum step
size

3-32

Rationale for making
this change...
Locally disabling
zero-crossing detection
prevents a specific
block from stopping the
simulation because of
excessive consecutive zero
crossings. All other blocks
continue to benefit from the
increased accuracy that
zero-crossing detection
provides.

Select Disable all
from the Zero-crossing
control pull down on
the Solver pane of the
Configuration Parameters
dialog box.

This prevents zero
crossings from being
detected anywhere in your
model. A consequence is
that your model no longer
benefits from the increased
accuracy that zero-crossing
detection provides.

Select a value from the

For more information, see
“Maximum order”.

Maximum order pull down

on the Solver pane of the
Configuration Parameters
dialog box.

Enter a value for the
Max step size option on

the Solver pane of the
Configuration Parameters
dialog box.

This can insure the solver
takes steps small enough
to resolve the zero crossing.
However, reducing the
step size can increase
simulation time, and

Simulating Dynamic Systems

Make this
change...

How to make this
change...

Rationale for making
this change...
is seldom necessary
when using the Adaptive
algorithm.

Zero-Crossing Algorithms
The Simulink software includes two zero-crossing detection algorithms:
Nonadaptive and Adaptive.
To choose the algorithm, either use the Algorithm option in the Solver pane
of the Configuration Parameter dialog box, or use the ZeroCrossAlgorithm
command. The command can either be set to 'Nonadaptive' or 'Adaptive'.
The Nonadaptive algorithm is provided for backwards compatibility with
older versions of Simulink and is the default. It brackets the zero-crossing
event and uses increasingly smaller time steps to pinpoint when the zero
crossing has occurred. Although adequate for many types of simulations, the
Nonadaptive algorithm can result in very long simulation times when a high
degree of ’chattering’ (high frequency oscillation around the zero-crossing
point) is present.
The Adaptive algorithm dynamically turns the bracketing on and off, and
is a good choice when:
• The system contains a large amount of chattering.
• You wish to specify a guard band (tolerance) around which the zero crossing
is detected.
The Adaptive algorithm turns off zero-crossing bracketing (stops iterating) if
either of the following are satisfied:
• The zero crossing error is exceeded. This is determined by the value
specified in the Signal threshold option in the Solver pane of the
Configuration Parameters dialog box. This can also be set with the
ZCThreshold command. The default is Auto, but you can enter any real
number greater than zero for the tolerance.

3-33

3

How Simulink® Works

• The system has exceeded the number of consecutive zero crossings specified
in the Number of consecutive zero crossings option in the Solver pane
of the Configuration Parameters dialog box. Alternatively, this can be set
with the MaxConsecutiveZCs command.

Understanding Signal Threshold
The Adaptive algorithm automatically sets a tolerance for zero-crossing
detection. Alternatively, you can set the tolerance by entering a real number
greater than or equal to zero in the Configuration Parameters Solver pane,
Signal threshold pull down. This option only becomes active when the
zero-crossing algorithm is set to Adaptive.
This graphic shows how the Signal threshold sets a window region around
the zero-crossing point. Signals falling within this window are considered
as being at zero.

Signal
Threshold
Tn-1

Tn

The zero-crossing event is bracketed by time steps Tn-1 and Tn. The solver
iteratively reduces the time steps until the state variable lies within the band
defined by the signal threshold, or until the number of consecutive zero
crossings equals or exceeds the value in the Configuration Parameters Solver
pane, Number of consecutive zero crossings pull down.
It is evident from the figure that increasing the signal threshold increases the
distance between the time steps which will be executed. This often results in
faster simulation times, but might reduce accuracy.

3-34

Simulating Dynamic Systems

How Blocks Work with Zero-Crossing Detection
A block can register a set of zero-crossing variables, each of which is a function
of a state variable that can have a discontinuity. The zero-crossing function
passes through zero from a positive or negative value when the corresponding
discontinuity occurs. The registered zero-crossing variables are updated at
the end of each simulation step, and any variable that has changed sign is
identified as having had a zero-crossing event.
If any zero crossings are detected, the Simulink software interpolates between
the previous and current values of each variable that changed sign to estimate
the times of the zero crossings (that is, the discontinuities).
Blocks That Register Zero Crossings. The following table lists blocks that
register zero crossings and explains how the blocks use the zero crossings:
Block

Description of Zero Crossing

Abs

One: to detect when the input signal crosses zero in
either the rising or falling direction.

Backlash

Two: one to detect when the upper threshold is engaged,
and one to detect when the lower threshold is engaged.

Compare To
Constant

One: to detect when the signal equals a constant.

Compare To Zero

One: to detect when the signal equals zero.

Dead Zone

Two: one to detect when the dead zone is entered (the
input signal minus the lower limit), and one to detect
when the dead zone is exited (the input signal minus
the upper limit).

Enable

One: If an Enable port is inside of a Subsystem block,
it provides the capability to detect zero crossings.
See the Enable Subsystem block for details “Enabled
Subsystems” on page 7-4.

From File

One: to detect when the input signal has a discontinuity
in either the rising or falling direction

From Workspace

One: to detect when the input signal has a discontinuity
in either the rising or falling direction

3-35

3

How Simulink® Works

Block

Description of Zero Crossing

If

One: to detect when the If condition is met.

Integrator

If the reset port is present, to detect when a reset
occurs.
If the output is limited, there are three zero crossings:
one to detect when the upper saturation limit is
reached, one to detect when the lower saturation limit
is reached, and one to detect when saturation is left.

3-36

MinMax

One: for each element of the output vector, to detect
when an input signal is the new minimum or maximum.

Relational
Operator

One: to detect when the specified relation is true.

Relay

One: if the relay is off, to detect the switch-on point. If
the relay is on, to detect the switch-off point.

Saturation

Two: one to detect when the upper limit is reached or
left, and one to detect when the lower limit is reached
or left.

Second-Order
Integrator

Five: two to detect when the state x upper or lower
limit is reached; two to detect when the state dx/dt
upper or lower limit is reached; and one to detect when
a state leaves saturation.

Sign

One: to detect when the input crosses through zero.

Signal Builder

One: to detect when the input signal has a discontinuity
in either the rising or falling direction

Step

One: to detect the step time.

Switch

One: to detect when the switch condition occurs.

Switch Case

One: to detect when the case condition is met.

Simulating Dynamic Systems

Block

Description of Zero Crossing

Trigger

One: If a Triggered port is inside of a Subsystem block,
it provides the capability to detect zero crossings. See
the Triggered Subsystem block for details: “Triggered
Subsystems” on page 7-20.

Enabled and
Triggered
Subsystem

Two: one for the enable port and one for the trigger
port. See the Triggered and Enabled Subsystem block
for details: “Triggered and Enabled Subsystems” on
page 7-24

Note Zero-crossing detection is also available for a Stateflow chart that uses
continuous-time mode. See “Configuring a Stateflow Chart to Update in
Continuous Time” in the Stateflow documentation for more information.
Implementation Example: Saturation Block. An example of a Simulink
block that registers zero crossings is the Saturation block. Zero-crossing
detection identifies these state events in the Saturation block:
• The input signal reaches the upper limit.
• The input signal leaves the upper limit.
• The input signal reaches the lower limit.
• The input signal leaves the lower limit.
Simulink blocks that define their own state events are considered to have
intrinsic zero crossings. Use the Hit Crossing block to receive explicit
notification of a zero-crossing event. See “Blocks That Register Zero
Crossings” on page 3-35 for a list of blocks that incorporate zero crossings.
The detection of a state event depends on the construction of an internal
zero-crossing signal. This signal is not accessible by the block diagram. For
the Saturation block, the signal that is used to detect zero crossings for the
upper limit is zcSignal = UpperLimit - u, where u is the input signal.
Zero-crossing signals have a direction attribute, which can have these values:

3-37

3

How Simulink® Works

• rising — A zero crossing occurs when a signal rises to or through zero, or
when a signal leaves zero and becomes positive.
• falling — A zero crossing occurs when a signal falls to or through zero, or
when a signal leaves zero and becomes negative.
• either — A zero crossing occurs if either a rising or falling condition occurs.
For the Saturation block’s upper limit, the direction of the zero crossing is
either. This enables the entering and leaving saturation events to be detected
using the same zero-crossing signal.

3-38

Simulating Dynamic Systems

Algebraic Loops
• “What Is an Algebraic Loop?” on page 3-39
• “Problems Caused by Algebraic Loops” on page 3-43
• “Identifying Algebraic Loops in Your Model” on page 3-43
• “What If I Have an Algebraic Loop in My Model?” on page 3-47
• “Simulink Algebraic Loop Solver” on page 3-49
• “Removing Algebraic Loops” on page 3-51
• “Additional Techniques to Help the Algebraic Loop Solver” on page 3-53
• “Changing Block Priorities Does Not Remove Algebraic Loops” on page 3-54
• “Artificial Algebraic Loops” on page 3-54

What Is an Algebraic Loop?
• “Algebraic Loops in Simulink” on page 3-39
• “Mathematical Definition of an Algebraic Loop” on page 3-41
• “Meaning of Algebraic Loops in Physical Systems” on page 3-42
Algebraic Loops in Simulink. An algebraic loop in a Simulink model occurs
when a signal loop exists with only direct feedthrough blocks within the loop.
Direct feedthrough means that the block output depends on the value of an
input port; the value of the input directly controls the value of the output.
Non-direct-feedthrough blocks maintain a State variable. Two examples are
the Integrator or Unit Delay block.
Some Simulink blocks have input ports with direct feedthrough. The software
cannot compute the output of these blocks without knowing the values of the
signals entering the blocks at these input ports at the current time step.
Some examples of blocks with direct feedthrough inputs are:
• Math Function block
• Gain block

3-39

3

How Simulink® Works

• Product block
• State-Space block, when the D matrix coefficient is nonzero
• Sum block
• Transfer Fcn block, when the numerator and denominator are of the same
order
• Zero-Pole block, when the block has as many zeros as poles
Tip To determine if a block has direct feedthrough:
1 Double-click the block.

The block parameter dialog box opens.
2 Click the Help button in the block parameter dialog box.

The block reference page opens.
3 Scroll to the Characteristics section of the block reference page, which

lists whether or not that block has direct feedthrough.

An example of an algebraic loop is the following simple loop. Note that this is
not a recommended modeling pattern.

Mathematically, this loop implies that the output of the Sum block is an
algebraic variable xa that is constrained to equal the first input u minus xa
(for example, xa = u – xa). The solution of this simple loop is xa = u/2.

3-40

Simulating Dynamic Systems

Mathematical Definition of an Algebraic Loop. Simulink contains a
suite of numerical solvers for simulating ordinary differential equations
(ODEs), which are systems of equations that you can write as:

x = f ( x, t),
x is the state vector and t is the independent time variable.
Some systems of equations contain additional constraints that involve the
independent variable and the state vector, but not the derivative of the state
vector. Such systems are differential algebraic equations (DAEs), not ODEs.
The term algebraic refers to equations that do not involve any derivatives.
You can express DAEs that arise in engineering in a semi-explicit form:

x = f (x, x a , t)
0 = g (x, x a , t),
• f and g can be vector functions.
• The first equation is the differential equation.
• The second equation is the algebraic equation.
• The vector of differential variables is x.
• The vector of algebraic variables is xa.
In Simulink models, algebraic loops are algebraic constraints. Models with
algebraic loops define a system of differential algebraic equations. Simulink
does not solve DAEs directly. Simulink solves the algebraic equations (the
algebraic loop) numerically for xa at each step of the ODE solver.
The following Simulink model is equivalent to this system of equations in
semi-explicit form:

x = f ( x, xa , t) = xa
0 = g( x, xa , t) = − x + u − 2 xa .

3-41

3

How Simulink® Works

At each step of the ODE solver, the algebraic loop solver must solve the
algebraic constraint for xa before calculating the derivative x .
Meaning of Algebraic Loops in Physical Systems. Algebraic constraints
can occur when modeling physical systems, often due to conservation
laws, such as conservation of mass and energy. You can also use algebraic
constraints to impose design constraints on system responses in a dynamic
system.
Choosing a particular coordinate system for a model can also result in an
algebraic constraint. In most cases, you can eliminate algebraic loops,
as described in “Removing Algebraic Loops” on page 3-51, to produce an
ordinary differential equation (ODE). However, this technique may be too
time consuming if you have a large, complex model.

3-42

Simulating Dynamic Systems

MathWorks® offers the Simscape™ software that extends Simulink by
providing tools to model systems that span mechanical, electrical, hydraulic,
and other physical domains as physical networks.
Simscape software automatically constructs the differential algebraic
equations (DAEs) that characterize the behavior of a Simulink model. These
equations are integrated with the rest of the model, and the Simscape
software solves the DAEs directly. The variables for the components in the
different physical domains are solved simultaneously, thereby avoiding
problems with algebraic loops.

Problems Caused by Algebraic Loops
If your model contains an algebraic loop:
• You cannot generate code for the model.
• The Simulink algebraic loop solver might not be able to solve the algebraic
loop.
• While Simulink is trying to solve the algebraic loop, the simulation might
execute slowly.
For most models, the algebraic loop solver is computationally expensive for
the first time step. Simulink solves subsequent time steps rapidly because
a good starting point for xa is available from the previous time step.

Identifying Algebraic Loops in Your Model
• “Algebraic Loop Diagnostic” on page 3-43
• “Highlighting Algebraic Loops Using the Algebraic Loop Diagnostic” on
page 3-44
• “Highlighting Algebraic Loops Using the ashow Debugger Command” on
page 3-45
Algebraic Loop Diagnostic. Simulink detects algebraic loops during
simulation initialization, for example, when you update your diagram. You
can set the Algebraic loop diagnostic to report an error or warning if the
software detects any algebraic loops in your model.

3-43

3

How Simulink® Works

In the Configuration Parameters dialog box, on the main Diagnostics pane,
set the Algebraic loop parameter as follows.
Setting

Simulation Response

none

Simulink tries to solve the algebraic loop;
reports an error only if the algebraic loop
cannot be solved.

warning

Algebraic loops result in warnings. Simulink
tries to solve the algebraic loop; reports an error
only if the algebraic loop cannot be solved.

error

Algebraic loops stop the initialization.

If you want Simulink to try to solve the loop, select none or warning. If you
want to review the loop before Simulink tries to solve the loop, select error.
Highlighting Algebraic Loops Using the Algebraic Loop Diagnostic. To
highlight algebraic loops in the Simulink Editor when updating or simulating
a model:
1 Open the sldemo_hydcyl model:

sldemo_hydcyl
2 Open the Configuration Parameters dialog box by selecting

Simulation > Model Configuration Parameters.
3 On the Diagnostics pane, set the Algebraic loop parameter to error.

If the Simulink software finds an algebraic loop in the model, it should stop
the simulation and report an error.
4 Click OK to save the setting.
5 Click the Start simulation button.

When Simulink detects an algebraic loop during initialization, the
simulation stops. The Diagnostics Viewer displays an error message and
lists all the blocks in the model that are part of that algebraic loop.

3-44

Simulating Dynamic Systems

In the Simulink Editor, the software highlights the blocks and signals that
constitute the loop in red.

6 To restore the diagram to its original colors, close the Diagnostics Viewer.
7 Close the sldemo_hydcyl model without saving the changes.

In the next section, the ashow debugger command shows that this model
actually has two algebraic loops.
Highlighting Algebraic Loops Using the ashow Debugger Command.
The Simulink debugger allows you to step through a model simulation. To use
the ashow command to highlight algebraic loops:
1 Open the sldemo_hydcyl model.

By default, the Algebraic loop parameter for this model is set to none.

3-45

3

How Simulink® Works

2 Start the Simulink debugger. In the Simulink Editor, select Simulation >

Debug > Debug Model.
3 Click the Start/Continue button to start the debugger.
4 In the MATLAB Command Window, type:

ashow

The software lists the two algebraic loops in the sldemo_hydcyl model and
the number of blocks in each algebraic loop.
Found 2 Algebraic loop(s):
System number#Algebraic loop id, number of blocks in loop
- 0#1, 9 blocks in loop
- 0#2, 4 blocks in loop
5 To list the blocks in the first algebraic loop, in the MATLAB Command

Window, enter the following command:
ashow 0#1

The software opens the Control Valve Flow subsystem in the
Valve/Cylinder/Piston/Spring Assembly subsystem, highlights that
algebraic loop in the model, and lists the nine blocks in the algebraic loop:
- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/IC
- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/signed sqrt
- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/Product
- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/laminar flow pressure drop
- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Sum7
- sldemo_hydcyl/Pump/IC

- sldemo_hydcyl/Valve//Cylinder//Piston//Spring Assembly/Control Valve Flow/Sum1 (algebraic v
- sldemo_hydcyl/Pump/Sum1
- sldemo_hydcyl/Pump/leakage (algebraic variable)

6 In the Simulink debugger, click Close.
7 At the MATLAB command prompt, press Enter to restore the default

MATLAB command prompt.

3-46

Simulating Dynamic Systems

What If I Have an Algebraic Loop in My Model?
If Simulink reports an algebraic loop in your model, the algebraic loop solver
might be able to solve the loop. If Simulink cannot solve the loop, there are
several techniques to eliminate the loop.
The following workflow helps you evaluate what techniques to try to eliminate
an algebraic loop. Some of those techniques are described in the following
sections.

3-47

3

How Simulink® Works

Simulink detects
an algebraic loop

Done

Yes

Is the
solution
correct
and
efficient?

If you are generating code
for your model, you must
eliminate the
algebraic loop.

Can
Simulink
solve the
algebraic
loop?

Yes

No

No

* Use IC block
* Convert atomic subsystem
to virtual
* Enable Minimize algebraic
loop occurrences
* Restructure model

Modify
Modify model
model or
(may have side effects)
adjust model
settings?
Adjust
model
settings

No

* Change algorithm
(TrustRegion / LineSearch)
* Change solver parameters

Done

Yes

Loop
solved?

No

Is
there a
DAE?

No

Yes
Algebraic constraint exists. Convert
DAE to ODE by restructuring
underlying equations

Loop Yes
solved?

Done

No
Algebraic constraint does not exist.
* Add delays
* Add real dynamics (e.g., sensor)
* Convert to Simscape model (if
physical system)
* Eliminate nonzero matrix

Done

3-48

Loop
solved?

Yes

Done

Simulating Dynamic Systems

Simulink Algebraic Loop Solver
• “How the Algebraic Loop Solver Works” on page 3-49
• “Trust-Region and Line-Search Algorithms in the Algebraic Loop Solver”
on page 3-50
• “Limitations of the Algebraic Loop Solver” on page 3-50
How the Algebraic Loop Solver Works. When a model contains an
algebraic loop, the Simulink software uses a nonlinear solver at each time
step to solve the algebraic loop. The solver performs iterations to determine
the solution to the algebraic constraint (if possible). As a result, models with
algebraic loops can run more slowly than models without algebraic loops.
The algebraic loop solver requires:
• One block where the loop solver can break the loop and attempt to solve
the loop
• Real double signals
• The underlying algebraic constraint must be a smooth function
For example, suppose your model has a Sum block with two inputs—one
additive, the other subtractive. If you feed the output of the Sum block to one
of the inputs, you create an algebraic loop where all of the blocks include
direct feedthrough.

The Sum block cannot compute the output without knowing the input.
Simulink detects the algebraic loop, and the algebraic loop solver solves the
loop using an iterative loop. In the Sum block example, the software computes
the correct result as follows:
xa(t) = u(t) / 2.

3-49

3

How Simulink® Works

The algebraic loop solver uses a gradient-based search method, which requires
continuous first derivatives of the algebraic constraint that correspond to
the algebraic loop. As a result, if the algebraic loop contains discontinuities,
the algebraic loop solver might fail.
Trust-Region and Line-Search Algorithms in the Algebraic Loop
Solver. The Simulink algebraic loop solver uses one of two algorithms to
solve algebraic loops: trust region and line search. By default, the algebraic
loop solver uses the trust-region algorithm.
If the algebraic loop solver cannot solve the algebraic loop with the trust-region
algorithm, try simulating the model using the line-search algorithm.
To switch to the line-search algorithm, at the MATLAB command line, enter:
set_param(model_name, 'AlgebraicLoopSolver', 'LineSearch');

To switch back to the trust-region algorithm, at the MATLAB command line,
enter:
set_param(model_name, 'AlgebraicLoopSolver', 'TrustRegion');

For more information, see:
• “Trust-Region Methods for Nonlinear Minimization” in the Optimization
Toolbox™ documentation.
• “Line Search” in the Optimization Toolbox documentation.
Limitations of the Algebraic Loop Solver. Algebraic loop solving is an
iterative process. The Simulink algebraic loop solver is successful only if the
algebraic loop converges to a definite answer. When the loop fails to converge,
or converges too slowly, the simulation exits with an error.
The algebraic loop solver cannot solve algebraic loops that contain any of
the following:
• Blocks with discrete-valued outputs
• Blocks with nondouble or complex outputs
• Discontinuities

3-50

Simulating Dynamic Systems

• Stateflow charts

Removing Algebraic Loops
Introducing a Delay.
Algebraic loops can occur in large models when atomic subsystems create
feedback loops.
In the following generic model, there are two algebraic loops that involve
subsystems.
• BlackBox_A —> BlackBox_B —> BlackBox_C —> BlackBox_A
• BlackBox_B —> BlackBox_C —> BlackBox_B

When you update this model, Simulink detects the loop BlackBox_A —>
BlackBox_B —> BlackBox_C —> BlackBox_A.
Since you do not know the contents of these subsystems, you must break the
loops by adding a Unit Delay block outside the subsystems. There are three
ways to use the Unit Delay to break these loops:
• Add a unit delay between BlackBox_A and BlackBox_C
• Add a unit delay between BlackBox_B and BlackBox_C
• Add unit delays to both algebraic loops

3-51

3

How Simulink® Works

Add a unit delay between BlackBox_A and BlackBox_C
If you add a unit delay on the feedback signal between the subsystems
BlackBox_A and BlackBox_C, you introduce the minimum number of unit
delays (1) to the system. By introducing the delay before BlackBox_A,
BlackBox_B and BlackBox_C use data from the current time step.

Add a unit delay between BlackBox_B and BlackBox_C
If you add a unit delay between the subsystems BlackBox_B and BlackBox_C,
you break the algebraic loop between BlackBox_B and BlackBox_C. In
addition, you break the loop between BlackBox_A and BlackBox_C, because
that signal completes the algebraic loop. By inserting the Unit Delay block
before BlackBox_C, BlackBox_C now works with data from the previous time
step only.

3-52

Simulating Dynamic Systems

Add unit delays to both algebraic loops
In the following example, you insert Unit Delay blocks to break both algebraic
loops. In this model, BlackBox_A and BlackBox_B use data from the previous
time step. BlackBox_C uses data from the current time step.

Additional Techniques to Help the Algebraic Loop Solver
If the Simulink software cannot solve the algebraic loop, the software reports
an error. If the Simulink algebraic loop solver cannot solve the algebraic loop,
use one of the following techniques to solve the loop manually:

3-53

3

How Simulink® Works

• Restructure the underlying DAEs using techniques such as differentiation
or change of coordinates. These techniques put the DAEs in a form that is
easier for the algebraic loop solver to solve.
• Convert the DAEs to ODEs, which eliminates any algebraic loops.
• “Create Initial Guesses Using the IC and Algebraic Constraint Blocks”
on page 3-54
Create Initial Guesses Using the IC and Algebraic Constraint Blocks.
Your model might contain loops for which the loop solver cannot converge
without a good, initial guess for the algebraic states. You can specify an initial
guess for the algebraic state variables, but use this technique only when you
think the loop is legitimate.
There are two ways to specify an initial guess:
• Place an IC block in the algebraic loop.
• Specify an initial guess for a signal in an algebraic loop using an Algebraic
Constraint block.

Changing Block Priorities Does Not Remove Algebraic Loops
During the updating phase of simulation, Simulink determines the order in
which to execute the block methods during simulation. This block invocation
ordering is the sorted order.
If you assign priorities to nonvirtual blocks to indicate to Simulink their
execution order relative to other blocks, the algebraic loop solver does not
honor these priorities when attempting to solve any algebraic loops.

Artificial Algebraic Loops
• “What Is an Artificial Algebraic Loop?” on page 3-55
• “Eliminating Artificial Algebraic Loops Caused by Atomic Subsystems”
on page 3-57
• “Bundled Signals That Create Artificial Algebraic Loops” on page 3-57
• “Model and Block Parameters for Diagnosing and Eliminating Artificial
Algebraic Loops” on page 3-62

3-54

Simulating Dynamic Systems

• “Block Reduction and Artificial Algebraic Loops” on page 3-63
• “How Simulink Eliminates Artificial Algebraic Loops” on page 3-68
• “When Simulink Cannot Eliminate Artificial Algebraic Loops” on page 3-75
• “Managing Large Models with Artificial Algebraic Loops” on page 3-77
What Is an Artificial Algebraic Loop?. An artificial algebraic loop occurs
when an atomic subsystem or Model block causes Simulink to detect an
algebraic loop, even though the contents of the subsystem do not contain an
algebraic constraint. When you create an atomic subsystem, all Inport blocks
are direct feedthrough, resulting in an algebraic loop.
The following model does not contain an algebraic loop. The model simulates
without error.

3-55

3

How Simulink® Works

Suppose you enclose the Controller and Plant blocks in a subsystem and, in
the Subsystem Parameters dialog box, select Treat as atomic unit to make
the subsystem atomic.

When simulating this model, Simulink detects an algebraic loop because the
subsystem is direct feedthrough, even though the path within the atomic
subsystem is not direct feedthrough.
In the Configuration Parameters dialog box, on the main Diagnostics pane,
if you set the Algebraic loop parameter to error, Simulink stops the
simulation with an algebraic loop error.

3-56

Simulating Dynamic Systems

Eliminating Artificial Algebraic Loops Caused by Atomic Subsystems.
One way to eliminate an artificial algebraic loop caused by an atomic
subsystem is to convert the atomic subsystem to a virtual subsystem. Doing
so has no effect on the behavior of the model.
When the subsystem is atomic and you simulate the model, Simulink invokes
the algebraic loop solver. The algebraic loop solver terminates after one
iteration. The algebraic loop is automatically solved because there is no
algebraic constant. After you make the subsystem virtual, during simulation,
Simulink does not invoke the algebraic loop solver.
To convert an atomic subsystem to a virtual subsystem:
1 Open the model that contains the atomic subsystem.
2 Right-click the atomic subsystem and select Subsystem Parameters.
3 Clear the Treat as atomic unit parameter.
4 Click OK to save the changes and close the dialog box.
5 Save the model.

If you replace the atomic subsystem with a virtual subsystem and the
simulation still fails with an algebraic loop error, you probably have one of the
following elsewhere in your model:
• An algebraic constraint
• An artificial algebraic loop not caused by this atomic subsystem
Examine your model, try to identify the location of the algebraic loop, and use
some of the techniques described in this section to solve the loop.
Bundled Signals That Create Artificial Algebraic Loops. Some models
bundle signals together. This bundling might cause Simulink to detect
an algebraic loop, even when an algebraic constraint does not exist. If you
redirect one or more signals, you might remove the artificial algebraic loop.
The following linearized model simulates the dynamics of a two-tank system
fed by a single pump. In this model:

3-57

3

How Simulink® Works

• Output q1 is the rate of the fluid flow into the tank from the pump.
• Output h2 is the height of the fluid in the second tank.
• The State-Space block defines the dynamic response of the tank system to
the pump operation:

• The output from the State-Space block is a vector that contains q1 and h2.

3-58

Simulating Dynamic Systems

If you simulate this model with the Algebraic loop parameter set to warn
or error, Simulink identifies the algebraic loop.

3-59

3

How Simulink® Works

To eliminate this algebraic loop:
1 Change the C and D matrices as follows:

3-60

Simulating Dynamic Systems

2 Pass q1 directly to the Scope instead of through the State-Space block.

Now, the input (q1) does not pass directly to the output (the D matrix
is 0), so the State-Space block no longer has direct feedthrough. The
feedback signal has only one element now, so the Selector block is no longer
necessary, as you can see in the following model.

3-61

3

How Simulink® Works

Model and Block Parameters for Diagnosing and Eliminating
Artificial Algebraic Loops. There are two parameters to consider when you
think that your model has an artificial algebraic loop:
• Minimize algebraic loop occurrences parameter — Specify that
Simulink try to eliminate any artificial algebraic loops for:

-

Atomic subsystems — In the Subsystem Parameters dialog box, select
Minimize algebraic loop occurrences.

-

Model blocks — For the referenced model, in the Configuration
Parameters dialog box, on the Model Referencing pane, select
Minimize algebraic loop occurrences

• Minimize algebraic loop parameter — If the Minimize algebraic loop
occurrences parameter has no effect, specifies what diagnostic action
Simulink takes.

3-62

Simulating Dynamic Systems

The Minimize algebraic loop parameter is in the Configuration
Parameters dialog box, on the main Diagnostics pane. The diagnostic
actions for this parameter are:
Setting

Simulation Response

none

Simulink takes no action.

warning

Simulink displays a warning that the
Minimize algebraic loop occurrences
parameter has no effect.

error

Simulink terminates the simulation and
displays an error that the Minimize
algebraic loop occurrences parameter has
no effect.

Block Reduction and Artificial Algebraic Loops. When you enable the
Block reduction optimization in the Configuration Parameters dialog box,
Simulink collapses certain groups of blocks into a single, more efficient block,
or removes them entirely. Enabling block reduction results in faster execution
during model simulation and in generated code.
Enabling block reduction may also help Simulink solve artificial algebraic
loops.
Consider the following example model.

3-63

3

3-64

How Simulink® Works

Simulating Dynamic Systems

Initially, block reduction is turned off. When you simulate this model, the
Atomic Unit subsystem and Gain and Compare to Constant blocks are part
of an algebraic loop that Simulink cannot solve.

3-65

3

How Simulink® Works

If you enable block reduction and sorted order, and resimulate the model,
Simulink does not display the sorted order for blocks that have been reduced.
You can now quickly see which blocks have been reduced.

3-66

Simulating Dynamic Systems

The Compare to Constant and Gain blocks have been eliminated from the
model, so they no longer generate an algebraic loop error. The Atomic Unit
subsystem generates a warning:
Warning: If the inport 'ex_aloop_block_reduction_errwarn/
Atomic Unit/In1' of subsystem 'ex_aloop_block_reduction_errwarn/
Atomic Unit' involves direct feedback, then an algebraic loop
exists, which Simulink cannot remove. Consider clearing the
'Minimize algebraic loop occurrences' parameter to avoid this
warning.

3-67

3

How Simulink® Works

Tip Use Bus Selector blocks to pass only the required signals into atomic
subsystems.
How Simulink Eliminates Artificial Algebraic Loops. When you enable
Minimize algebraic loop occurrences, Simulink tries to eliminate
artificial algebraic loops. This section describes this process, using this model,
which from contains an atomic subsystem that causes an artificial algebraic
loop.

The contents of the atomic subsystem are not direct feedthrough, but
Simulink identifies the atomic subsystem as direct feedthrough.

3-68

Simulating Dynamic Systems

If the Algebraic loop diagnostic is set to error, simulating the model results
in an error because the model contains an artificial algebraic loop involving
its atomic subsystem.
To see how Simulink tries to eliminate this algebraic loop, follow these steps:
1 Create the model from the preceding graphics, with the atomic subsystem

that causes the artificial algebraic loop.
2 Select Simulation > Model Configuration Parameters.
3 In the Configuration Parameters dialog box, on the main Diagnostics

pane, set the Algebraic loop parameter to warning or none.

3-69

3

How Simulink® Works

4 On the Data Import/Export pane, make sure the Signal logging

parameter is disabled. If signal logging is enabled, Simulink cannot
eliminate artificial algebraic loops.
5 Click OK.
6 To display the sorted order for this model and the atomic subsystem, select

Format > Block Displays > Sorted Order.
Reviewing the sorted order might help you understand how to eliminate
the artificial algebraic loop.
All the blocks in the subsystem execute at the same level: 1. (0 is the lowest
level, indicating the first blocks to execute.)

3-70

Simulating Dynamic Systems

Note For more information about sorted order, see “Control and
Displaying the Sorted Order” on page 23-35.
7 In the top-level model, right-click the subsystem and select Subsystem

Parameters.
8 Select Minimize algebraic loop occurrences.

This parameter indicates to Simulink to try to eliminate the algebraic loop
that contains the atomic subsystem when it simulates the model.
9 Click OK.
10 Click Simulation > Update Diagram to recalculate the sorted order.

Now there are two levels of sorted order inside the subsystem: 1 and 2.

3-71

3

How Simulink® Works

To eliminate the artificial algebraic loop, Simulink tries to make the input of
the subsystem or referenced model non-direct feedthrough.
When you simulate a model, all the blocks first execute their mdlOutputs
method, and then their mdlDerivatives and mdlUpdate methods.
In the original version of this model, the execution of the mdlOutputs method
starts with the Plant block because the Plant block is non-direct feedthrough.
The execution finishes with the Controller block.

3-72

Simulating Dynamic Systems

Note For more information about these methods, see “Block Methods” on
page 3-16.
If you enable the Minimize algebraic loop occurrences parameter for the
atomic subsystem, Simulink divides the subsystem into two atomic units.

3-73

3

How Simulink® Works

Atomic unit 1

Atomic unit 2

The following conditions are true:
• Atomic unit 2 is not direct feedthrough.
• Atomic unit 1 has only a mdlOutputs method.
The output of Atomic unit 1 is needed only by the mdlDerivatives or
mdlUpdate methods of Atomic unit 2. Simulink can execute what normally
would have been executed during the mdlOutput method of Atomic unit 1 in
the mdlDerivatives methods of Atomic unit 2.
The new execution order for the model is:
• mdlOutputs method of model

-

mdlOutputs method of Atomic unit 2
mdlOutputs methods of other blocks

• mdlDerivatives method of model

-

mdlOutputs method of Atomic unit 1
mdlDerivatives method of Atomic unit 2
mdlDerivatives method of other blocks

For the Minimize algebraic loop occurrences technique to be successful,
the subsystem or referenced model must have a non-direct-feedthrough block
connected directly to an Inport. Simulink can then set the DirectFeedthrough

3-74

Simulating Dynamic Systems

property of the block Inport to false to indicate that the input port does
not have direct feedthrough.
When Simulink Cannot Eliminate Artificial Algebraic Loops. Setting
the Minimize algebraic loop occurrences parameter does not always
work. Simulink cannot change the DirectFeedthrough property of an Inport
for an atomic subsystem if the Inport is connected to an Outport only through
direct-feedthrough blocks.
Consider the following model. The subsystem Plant+Controller causes an
algebraic loop, but it has an extra Gain block and an extra output.

3-75

3

How Simulink® Works

Simulink cannot move the mdlOutputs method of the Controller block to the
mdlDerivative method of an Atomic unit 1 because the output of the atomic
subsystem depends on the output of the Controller block. You cannot make
the subsystem non-direct-feedthrough.
You can modify this model to eliminate the artificial algebraic loop by
redefining the atomic subsystem by adding additional Inport and Gain
blocks, as you can see in the following model. Doing so makes In1
non-direct-feedthrough and In2 direct feedthrough, breaking the algebraic
loop.

3-76

Simulating Dynamic Systems

Managing Large Models with Artificial Algebraic Loops. For
large models with algebraic loops, MathWorks recommends the following
techniques:
• Avoid creating loops that contain discontinuities or nondouble data types.
The Simulink algebraic loop solver is gradient-based and must solve
algebraic constraints to high precision.
• Develop a scheme for clearly identifying atomic subsystems as direct
feedthrough or not direct feedthrough. Use a visual scheme such as coloring
the blocks or defining a block-naming convention.
• If you plan to generate code for your model, enable the Minimize
algebraic loop occurrences parameter for all atomic subsystems. When

3-77

3

How Simulink® Works

possible, make sure that the input ports for the atomic subsystems are
connected directly to non-direct-feedthrough blocks.
• Avoid combining non-direct-feedthrough and direct-feedthrough paths
using the Bus Creator or Mux blocks. Simulink might not be able to
eliminate any resulting artificial algebraic loops. Instead, consider
clustering the non-direct-feedthrough and direct-feedthrough objects in
separate subsystems.
Use Bus Selector blocks to pass only the required signals into atomic
subsystems.

3-78

Modeling Dynamic Systems
• Chapter 4, “Creating a Model”
• Chapter 5, “Working with Sample Times”
• Chapter 6, “Referencing a Model”
• Chapter 7, “Creating Conditional Subsystems”
• Chapter 8, “Modeling Variant Systems”
• Chapter 9, “Exploring, Searching, and Browsing Models”
• Chapter 10, “Managing Model Configurations”
• Chapter 11, “Configuring Models for Targets with Multicore
Processors”
• Chapter 12, “Modeling Best Practices”
• Chapter 13, “Managing Projects”

4
Creating a Model
• “Create an Empty Model” on page 4-2
• “Populate a Model” on page 4-4
• “Select Modeling Objects” on page 4-6
• “Specify Block Diagram Colors” on page 4-8
• “Connect Blocks” on page 4-12
• “Align, Distribute, and Resize Groups of Blocks” on page 4-22
• “Annotate Diagrams” on page 4-23
• “Create a Subsystem” on page 4-36
• “Control Flow Logic” on page 4-44
• “Callback Functions” on page 4-54
• “Model Workspaces” on page 4-67
• “Symbol Resolution” on page 4-76
• “Consult the Model Advisor” on page 4-81
• “Manage Model Versions” on page 4-107
• “Model Discretizer” on page 4-122

4

Creating a Model

Create an Empty Model
To create an empty model:
1 Open the Library Browser, by typing simulink at the MATLAB command

line.
2 In the Library Browser, select File > New > Model or click the New

model button (

).

The Simulink software creates an empty model in memory and displays the
empty model in a Simulink Editor window.

Create a Model Template
When you create a model, Simulink uses defaults for many configuration
parameters. For example, by default new models have a white canvas, the
ode45 solver, and a visible toolbar. If these or other defaults do not meet your
needs, use the Simulink model construction functions listed in “Modeling
Basics” to write a function that creates a model with the defaults that you
prefer. For example, the following function creates a model that has a green
canvas and uses the ode3 solver:
function new_model(modelname)
% NEW_MODEL Create a new, empty Simulink model
%
NEW_MODEL('MODELNAME') creates a new model with
%
the name 'MODELNAME'. Without the 'MODELNAME'
%
argument, the new model is named 'my_untitled'.
if nargin == 0
modelname = 'my_untitled';
end
% create and open the model
open_system(new_system(modelname));
% set default screen color
set_param(modelname, 'ScreenColor', 'green');
% set default solver

4-2

Create an Empty Model

set_param(modelname, 'Solver', 'ode3');
% save the model
save_system(modelname);

4-3

4

Creating a Model

Populate a Model
In this section...
“Copy Blocks to Your Model” on page 4-4
“Browse Block Libraries” on page 4-4
“Search Block Libraries” on page 4-5
“Copy Blocks to Models” on page 4-5

Copy Blocks to Your Model
Use the Simulink Library Browser as the source for populating your model.
In the Library Browser, browse and search blocks from built-in and user
libraries. Copy blocks from the Library Browser to your model in the
Simulink Editor.
To open the Library Browser, at the MATLAB command line, enter:
simulink

For details, see “Open the Simulink Library Browser”.
For information about creating your own libraries and adding them to the
Library Browser, see “Block Libraries”.

Browse Block Libraries
The Libraries pane on the left displays a tree-structured folder of the block
libraries on your system. Initially, the Simulink library is selected and its
top level is open. You can scroll the pane and expand and collapse libraries
and sublibraries to browse the libraries on your system and the blocks that
the libraries contain.
The contents of the library that you select in the Libraries pane appear in
the Library tab to the right of the pane. The contents can be sublibraries,
blocks, or a mixture of the two. An icon and a name identifies each member of
the selected library.
To open a sublibrary, use one of the following approaches:

4-4

Populate a Model

• Select the library in the Libraries pane.
• Double-click the library in the Library tab.
To get help for a block:
1 Right-click the block.
2 From the context menu, select Help.

The help text and the context menu are the same as what appear when you
right-click an instance of that block in a model.

Search Block Libraries
To search for library blocks whose names contain a specified character string:
1 In the Library Browser, in Search text field, enter the search character

string.
2 Press Return or click Search.

The browser searches all libraries for blocks whose names match the specified
string. The browser displays the results in the Found pane. The pane shows
the blocks from each library separately.
By default, the search finds any substring and is not case-sensitive. To change
these defaults or to enable use of MATLAB regular expressions in the Search
field, click the Library Browser Options button and select the appropriate
commands. Work with blocks that you find by searching just as you do with
blocks that you find by selecting a library.

Copy Blocks to Models
To copy a block from the Library Browser into a model, drag and drop the
library block into the model window at the location where you want to create
the copy. Simulink copies the block to the model at the point that you select.
The resulting block retains a link to its source library. Updates to the source
library automatically propagate to all of its linked copies. See “Libraries”
for information about library links.

4-5

4

Creating a Model

Select Modeling Objects
In this section...
“Select an Object” on page 4-6
“Select Multiple Objects” on page 4-6

Select an Object
To select a modeling object (for example, a block or line), click it. When you
place the cursor on a block, small black square handles appear at the corners
of the block. Placing the cursor on a line highlights part of the line in blue.
Clicking a block or line highlights the whole object in blue. For example, the
figure below shows a selected Sine Wave block.
Selecting an object by clicking it deselects any other selected objects.

Select Multiple Objects
To select more than one object, use one of these approaches:
• Select objects one at a time.
• Use a bounding box to select objects located near each other.
• Select the entire model.

Select Multiple Objects One at a Time
To select more than one object by selecting each object individually, hold down
the Shift key and click each object that you want to select.
To deselect a selected object, click the object again while holding down the
Shift key.

Select Multiple Objects Using a Bounding Box
To select more than one object in the same area of the window, draw a
bounding box around the objects. This type of selection is also known as
“marquee selection” and “drag selection.”

4-6

Select Modeling Objects

1 Define the starting corner of a bounding box. Position the cursor (pointer)

at one corner of the box, then press and hold the left mouse button.
2 Drag the cursor to the opposite corner of the box. A blue rectangle encloses

the selected blocks and lines.
3 Release the mouse button. Simulink selects all blocks and lines that are

at least partially enclosed by the bounding box. For example, in the figure
below, the bounding box enclosed at least part of the Sine Wave and the
line from the Sine Wave block.

Select All Objects
To select all objects in the active window, select Edit > Select All.
Note To create a subsystem, you cannot select all blocks and signals . For
more information, see “Create a Subsystem” on page 4-36.

4-7

4

Creating a Model

Specify Block Diagram Colors
In this section...
“Set Block Diagram Colors Interactively” on page 4-8
“Platform Differences for Custom Colors” on page 4-9
“Choose a Custom Color” on page 4-9
“Define a Custom Color” on page 4-10
“Specify Colors Programmatically” on page 4-11

Set Block Diagram Colors Interactively
You can specify the foreground and background colors of any block or
annotation in a diagram, as well as the background color of the diagram.
Type of Color

How to Set

Block diagram background

Select Diagram > Format >
Canvas Color.

Block or annotation background
1 Select the blocks and annotations.
2 Select Diagram > Format >

Background Color
Block or annotation foreground
1 Select the blocks and annotations.
2 Select Diagram > Format >

Foreground Color
In all cases, you see a menu of color choices. Choose the desired color from the
menu. If you select a color other than Custom, the background or foreground
color of the diagram or diagram element changes to the selected color.

4-8

Specify Block Diagram Colors

Platform Differences for Custom Colors
On Mac platforms, choosing Custom invokes the Mac color picker interface.
Use the color picker to choose and define custom colors.
On Windows and Linux platforms, use the Simulink interface, as described in:
• “Choose a Custom Color” on page 4-9
• “Define a Custom Color” on page 4-10

Choose a Custom Color
If you choose Custom, and there are no custom colors already defined,
Simulink displays the Choose Custom Color dialog box.

If you choose Custom, and there are custom colors already defined, Simulink
displays the Select Color dialog box.

4-9

4

Creating a Model

The Select Color dialog box displays a palette of basic colors and a palette of
already defined custom colors. To choose a color from either palette, click
the color and then click OK.

Define a Custom Color
To define the first custom color, in the Choose Custom Color dialog box, click
the Define Custom Colors button.
The dialog box expands to display the Select Color dialog box. To define a
custom color:
1 Specify the color using one of these approaches:

• Enter the red, green, and blue components of the color as values between
0 (darkest) and 255 (brightest).
• Enter hue, saturation, and luminescence components of the color as
values in the range 0 to 255.
• Move the hue-saturation cursor to select the hue and saturation of the
desired color and the luminescence cursor to select the luminescence
of the desired color.

4-10

Specify Block Diagram Colors

2 Adjust the values until the color in the box to the right of the custom colors

palette is the custom color that you want.
3 Click the Add to Custom Colors button.

To replace an existing custom color, select the custom color in the custom
color palette before defining the new custom color.

Specify Colors Programmatically
You can use the set_param command at the MATLAB command line or
in a MATLAB program to set parameters that determine the background
color of a diagram and the background color and foreground color of diagram
elements. The following table summarizes the parameters that control block
diagram colors.
Parameter

Determines

Block diagram
background

ScreenColor

Block and annotation
background

BackgroundColor

Block and annotation
foreground

ForegroundColor

Set the color parameter to either a named color or an RGB value.
• Named color: 'black', 'white', 'red', 'green', 'blue', 'cyan',
'magenta', 'yellow', 'gray', 'lightBlue', 'orange', 'darkGreen'
• RBG value: '[r,g,b]'
where r, g, and b are the red, green, and blue components of the color
normalized to the range 0.0 to 1.0.
For example, the following command sets the background color of the
currently selected system or subsystem to a light green color:
set_param(gcs, 'ScreenColor', '[0.3, 0.9, 0.5]')

4-11

4

Creating a Model

Connect Blocks
In this section...
“Automatically Connect Blocks” on page 4-12
“Manually Connect Blocks” on page 4-15
“Disconnect Blocks” on page 4-21

Automatically Connect Blocks
You can have the Simulink software connect blocks automatically. This
eliminates the need to draw the connecting lines yourself. When connecting
blocks, Simulink routes the lines around intervening blocks to avoid cluttering
the diagram.

Autoconnect Two Blocks
When connecting two blocks with multiple ports, Simulink draws as many
connections as possible between the two blocks.
To autoconnect two blocks:
1 Select the source block. In this example, the Sine Wave block is the source

block.

4-12

Connect Blocks

2 Hold down Ctrl and left-click the destination block. In this example, the

Integrator block is the destination block.
The source block is connected to the destination block, and the lines are
routed around intervening blocks if necessary.

4-13

4

Creating a Model

Connect Groups of Blocks
To connect a group of source blocks to a destination block:
1 Select the source blocks.

2 Hold down Ctrl and left-click the destination block.

To connect a source block to a group of destination blocks:
1 Select the destination blocks.

4-14

Connect Blocks

2 Hold down Ctrl and left-click the source block.

Manually Connect Blocks
You can draw lines manually between blocks or between lines and blocks.
You might want to do this if you need to control the path of the line or to
create a branch line.

Draw a Line Between Blocks
You can create lines either from output to input ports, or from input to output
ports. For example, to connect the output port of a Constant block to the
input port of Gain block:
1 Position the cursor over the output port of the Constant block. You do not

need to position the cursor precisely on the port.

4-15

4

Creating a Model

The cursor shape changes to crosshairs.

2 Hold down the left mouse button.
3 Drag the cursor to the input port of the Gain block. Position the cursor on

or near the port or in the block. If you position the cursor in the block, the
line connects to the closest input port.
4 Release the mouse button. A connecting line with an arrow showing the

direction of the signal flow replaces the port symbol.
The arrow appears at the appropriate input port, and the signal is the same.

Draw a Branch Line
A branch line is a line that starts from an existing line and carries its signal to
the input port of a block. Both the existing line and the branch line represent
the same signal. Use branch lines to connect a signal to more than one block.

4-16

Connect Blocks

This example shows how to connect the Product block output to both the
Scope block and the To Workspace block.

To add a branch line:
1 Position the cursor on the line where you want the branch line to start.
2 While holding down the Ctrl key, press and hold down the left or right

mouse button.
3 Drag the cursor to the input port of the target block, then release the

mouse button and the Ctrl key.

Draw Line Segments
Manually draw line segments when you want to draw:
• Line segments differently than autoconnect feature draws the lines
• A line, before you copy the block to which the line connects
To draw a line segment:
1 Draw a line from the block port to an unoccupied area of the canvas.

Release the mouse button where you want the line segment to end.
The cursor turns into a circle, and blue arrow guides appear.

4-17

4

Creating a Model

2 For each additional line segment, position the cursor over the blue arrow

guide that points in the direction in which you want to draw a line segment.
The cursor turns into an empty arrowhead.

Tip To reroute the whole line instead of extending it, select the end of
the line itself when the circle cursor is displayed and drag the line end to
a new location.
3 Drag the cursor to draw the second line segment and release the mouse

button to finish drawing the line.

Move a Line Segment
To move a line segment:
1 Position the cursor on the segment that you want to move.
2 Press and hold down the left mouse button.
3 Drag the cursor to the desired location and release the mouse button.

4-18

Connect Blocks

Draw a Diagonal Line
You cannot draw a single diagonal line between two ports. You can draw very
short line segments connecting to each port, with a longer diagonal segment
in the middle. For example, suppose you position two blocks as shown below:

To approximate a diagonal line:
1 Draw a short line segment from the output port of the Constant block.
2 At the end of the first line segment, draw a second line segment.

3 Draw a third line segment to connect to the Scope block.

4-19

4

Creating a Model

4 Position the cursor at the bend of the second and third line segments. The

cursor turns into a circle.

5 Hold the Shift key down and drag the cursor to make the second line

segment a diagonal.

Move a Line Vertex
To move a vertex of a line:
1 Position the cursor on the vertex, then press and hold down the left mouse

button.

4-20

Connect Blocks

The cursor changes to a circle.

2 Drag the vertex to the desired location.

3 Release the mouse button.

Insert a Block in a Line
You can insert a block in a line, if the block has only one input and one output.
1 Drag the block over the line in which you want to insert the block.
2 Release the mouse button. Simulink inserts the block for you at the point

where you drop the block.

Disconnect Blocks
To disconnect a block from its connecting lines, hold down the Shift key,
then drag the block to a new location.

4-21

4

Creating a Model

Align, Distribute, and Resize Groups of Blocks
To align, distribute, or resize a group of blocks:
1 Select the blocks that you want to align, as described in “Select Multiple

Objects” on page 4-6.
Simulink highlights one of the selected blocks. Simulink uses the
highlighted block as the reference for aligning the other selected blocks.
For example, in the following model, the Constant block is the alignment
reference block.

One of the selected blocks displays empty selection handles. The model
editor uses this block as the reference for aligning the other selected blocks.
If you want another block to serve as the alignment reference, click that
block.
2 From the Diagram > Arrange menu, select an alignment, distribution, or

sizing option. For example, select Align Top to align the top edges of the
selected blocks with the top edge of the reference block.

4-22

Annotate Diagrams

Annotate Diagrams
In this section...
“Add and Edit Annotations” on page 4-23
“Summary of Annotations Properties Dialog Box” on page 4-28
“Annotation Callback Functions” on page 4-29
“Associate Click Functions with Annotations” on page 4-30
“Annotations API” on page 4-32
“TeX Formatting Commands in Annotations” on page 4-32
“Create Annotations Programmatically” on page 4-34

Add and Edit Annotations
Annotations provide textual information to document a model. You can add
an annotation to any unoccupied area of your block diagram.

Add an Annotation
To add an annotation:
1 Double-click an unoccupied area of the block diagram. A small rectangle

appears and the cursor changes to an insertion point.

4-23

4

Creating a Model

2 Type the annotation contents. Each line is centered in the rectangle that

surrounds the annotation.
Alternatively, from the Simulink Editor palette (to the left of the model),
select the Annotation button ( ) and either drag the cursor into the model
window or click in the model window.

Move an Annotation
To move an annotation, drag it to a new location.

Annotations Properties Dialog Box
As an alternative to directly editing an annotation, you can use the Annotation
properties dialog box to specify the contents and format of the currently
selected annotation and to associate a click function with the annotation. The
Annotations properties dialog box consolidates the options for specifying the
content and appearance of an annotation.
To display the Annotation properties dialog box for an annotation:
1 Select an annotation.
2 Select Diagram > Properties.

The Annotation properties dialog box opens.

4-24

Annotate Diagrams

Edit an Annotation
To edit an annotation directly, select the annotation.

4-25

4

Creating a Model

• To insert characters, click between two characters to position the insertion
point, then insert text.
• To replace characters, drag the mouse to select a range of text to replace,
then enter the new text.
To edit annotation text using the Annotations properties dialog box, edit
the Text field.

Change Annotation Font
To change the annotation font:
1 Select the annotation.
2 Select Diagram > Format > Font Style.
3 Select a font and size from the dialog box.

To change the annotation font using the Annotations properties dialog box,
press the Font button.

Use TeX commands
To use TeX (LaTeX) commands in an annotation:
1 Select the annotation.
2 Select Diagram > Format > Enable TeX Commands.
3 Enter TeX commands.

As an alternative, to enable the use of TeX commands using the Annotations
properties dialog box, select Enable TeX commands.
For details, see “TeX Formatting Commands in Annotations” on page 4-32.

Text Alignment
To change the text alignment (left, center, or right) in an annotation:
1 Select the annotation.

4-26

Annotate Diagrams

2 Select Diagram > Format > Text Alignment.
3 Select an alignment option, such as Center.

As an alternative, to change the annotation text alignment using the
Annotations properties dialog box, use the Alignment field.

Background Color or Text Color
To change the background color or text color of an annotation:
1 Select the annotation.
2 Set the annotation background color by selecting Diagram > Format >

Background.
3 Set the annotation text color by selecting Diagram > Format >

Foreground.
As an alternative, to change the background color or text color using the
Annotations properties dialog box:
• To specify the color of the annotation box, use the Background color field.
• To specify the annotation text color of the annotation box, use the
Foreground color field.

Border or Drop Shadow
To specify a border for the annotation:
1 Select the annotation.
2 Select the annotation background color by selecting Diagram > Format >

Annotation Border.
To specify a drop shadow for the annotation (to give it a 3-D appearance), in
the Annotations properties dialog box, select Drop shadow.

Delete an Annotation
To delete an annotation, do one of the following:

4-27

4

Creating a Model

• Draw a selection box that includes part of the annotation and press Delete.
• Select all of the text in the annotation, press Delete, and move the cursor.

Summary of Annotations Properties Dialog Box
The dialog box includes the following controls.

Text
Displays the current text of the annotation. Edit this field to change the
annotation text.

Enable TeX commands
Enables the use of TeX formatting commands in this annotation. For details,
see “TeX Formatting Commands in Annotations” on page 4-32.

Font
Displays a font chooser dialog box. Use the font chooser to change the font
used to render the annotation’s text.

Foreground color
Specifies the color of the annotation text.

Background color
Specifies the color of the background of the bounding box of the annotation.

Alignment
Specifies the alignment of the annotation text relative to its bounding box.

ClickFcn
Specifies MATLAB code to be executed when a user single-clicks this
annotation. Simulink stores the code entered in this field with the model. For
details, see “Associate Click Functions with Annotations” on page 4-30.

4-28

Annotate Diagrams

Use display text as click callback
Treats the Text field as the annotation click function. The specified text must
be a valid MATLAB expression comprising symbols that are defined in the
MATLAB workspace when the user clicks this annotation. For details, see
“Associate Click Functions with Annotations” on page 4-30. Selecting this
option disables the ClickFcn edit field.

Annotation Callback Functions
You can make an annotation interactive by adding a callback. For example,
you can use an annotation click callback function to set up a link from
annotation text.
You can associate the following callback functions with annotations.

Click Function
A click function is a MATLAB function that Simulink invokes when a user
single-clicks an annotation. You can associate a click function with any model
annotation (for details, see “Associate Click Functions with Annotations”
on page 4-30).
You can use click functions to add hyperlinks and custom command “buttons”
to a model. For example, you can use a click function to allow a user to display
the values of workspace variables referenced by the model or to open related
models simply by clicking on annotations displayed on the block diagram.
Simulink uses the color blue to display the text of annotations associated
with click functions.

Load Function
This function is invoked when it loads the model containing the associated
annotation. To associate a load function with an annotation, set the LoadFcn
property of the annotation to the desired function (see “Annotations API”
on page 4-32).

4-29

4

Creating a Model

Delete function
This function is invoked before deleting the associated annotation. To
associate a delete function with an annotation, set the DeleteFcn property of
the annotation to the desired function (see “Annotations API” on page 4-32).

Associate Click Functions with Annotations
Use one of two ways to associate a click function with an annotation with
either the Annotation Properties dialog box (see “Summary of Annotations
Properties Dialog Box” on page 4-28) or a separately defined function.
• Specify the annotation itself as the click function.
Enter a valid MATLAB expression in the Text field and check the Use
display text as click callback.

4-30

Annotate Diagrams

• Specify a separately defined click function.
Enter the MATLAB code that defines the click function in the ClickFcn
edit field.

Note You can also use MATLAB code to associate a click function with an
annotation. See “Annotations API” on page 4-32 for more information.

Select and Edit Annotations Associated with Click Functions
If you associate an annotation with a click function, then you cannot select
the annotation by clicking on it. Instead, use a boundary box to select the
annotation.
To move the annotation, use the up, down, right, or left arrow keys.

4-31

4

Creating a Model

Similarly, you cannot edit the annotation text by clicking on the text. To edit
the annotation:
1 Drag select the annotation.
2 Right-click the selected annotation.
3 In the context menu, select Properties.
4 In the Properties dialog box, in the Text field, edit the text.

Annotations API
To use MATLAB code to get and set the properties of annotations, use:
• Simulink.Annotation class
Set the properties of annotations, by using MATLAB code. For example,
annotation load functions (see “Load Function” on page 4-29).
• getCallbackAnnotation function
Get the Simulink.Annotation object for the annotation associated with
the currently executing annotation callback function. Use this function to
determine which annotation was clicked to invoke the current callback.
This function is also useful if you write a callback function in a separate
MATLAB file contains multiple callback calls.

TeX Formatting Commands in Annotations
You can use TeX formatting commands to include mathematical and other
symbols and Greek letters in block diagram annotations.

4-32

Annotate Diagrams

To use TeX commands in an annotation:
1 Select the annotation.
2 Select Diagram > Format > Enable TeX Commands.
3 Enter or edit the text of the annotation, using TeX commands where needed

to achieve the desired appearance.

4-33

4

Creating a Model

See “Mathematical Symbols, Greek Letters, and TeX Characters” in
the MATLAB documentation for information about the supported TeX
formatting commands.
4 Deselect the annotation by clicking outside it or press the Esc key.

The text reflects the TeX formatting.

Create Annotations Programmatically
To create annotations at the command line or in a MATLAB program, use the
add_block command.
add_block('built-in/Note','path/text','Position', ...
[center_x, 0, 0, center_y]);

where path is the path of the diagram to be annotated, text is the text of
the annotation, and [center_x, 0, 0, center_y] is the position of the center
of the annotation in pixels relative to the upper left corner of the diagram.
For example:
new_system('test')

4-34

Annotate Diagrams

open_system('test')
add_block('built-in/Gain', 'test/Gain', 'Position', ...
[260, 125, 290, 155])
add_block('built-in/Note','test/programmatically created', ...
'Position', [550 0 0 180])

The code creates the following model, which includes an annotation.

To delete an annotation, use the find_system command to get the annotation
handle. Then use the delete function to delete the annotation. For example:
delete(find_system(gcs, 'FindAll', 'on', 'type', 'annotation'));

4-35

4

Creating a Model

Create a Subsystem
In this section...
“Subsystem Advantages” on page 4-36
“Two Ways to Create a Subsystem” on page 4-36
“Create a Subsystem by Adding the Subsystem Block” on page 4-37
“Create a Subsystem by Grouping Existing Blocks” on page 4-37
“Subsystem Execution” on page 4-39
“Navigate Model Hierarchy” on page 4-39
“Label Subsystem Ports” on page 4-42
“Control Access to Subsystems” on page 4-42
“Interconvert Subsystems and Block Diagrams” on page 4-43
“Empty Subsystems and Block Diagrams” on page 4-43

Subsystem Advantages
A subsystem is a set of blocks that you replace with a single block called a
Subsystem block. As your model increases in size and complexity, you can
simplify it by grouping blocks into subsystems. Using subsystems has these
advantages:
• Helps reduce the number of blocks displayed in your model window.
• Keeps functionally related blocks together.
• Establishes a hierarchical block diagram, where a Subsystem block is on
one layer and the blocks that make up the subsystem are on another.
For additional information about how subsystems compare to other Simulink
componentization techniques, see “Componentization Guidelines” on page
12-17.

Two Ways to Create a Subsystem
You can create a subsystem in two ways:

4-36

Create a Subsystem

• Add a Subsystem block to your model, then open that block and add the
blocks that it contains to the subsystem window.
• Add the blocks that make up the subsystem, then group those blocks into a
subsystem.

Create a Subsystem by Adding the Subsystem Block
To create a subsystem before adding the blocks that it contains, add a
Subsystem block to the model, then add the blocks that make up the
subsystem.
1 Copy the Subsystem block from the Ports & Subsystems library into your

model.
2 Open the Subsystem block by double-clicking it.
3 In the empty Subsystem window, create the subsystem. Use Inport blocks

to represent input from outside the subsystem and Outport blocks to
represent external output.
For example, this subsystem includes a Sum block and Inport and Outport
blocks to represent input to and output from the subsystem.

Create a Subsystem by Grouping Existing Blocks
If your model already contains the blocks that you want to convert to a
subsystem, create the subsystem by grouping those blocks.
1 Select individual blocks that you want to include in a subsystem. To select

multiple blocks that are in one area of the model, click the left mouse
button and drag the cursor to create a bounding box that encloses the
blocks and the connecting lines that you want to include in the subsystem.
For more information, see “Select Multiple Objects Using a Bounding Box”
on page 4-6.

4-37

4

Creating a Model

For example, this figure shows a model that represents a counter. The
bounding box selects the Sum and Unit Delay blocks.

When you release the mouse button, the two blocks and all the connecting
lines are selected.
2 Select Diagram > Subsystems & Model Reference > Create

Subsystem from Selection. A Subsystem block replaces the selected
blocks.
3 Resize the Subsystem block so the port labels are readable.

If you open the Subsystem block, the underlying system opens. For example:

Notice that Simulink adds Inport and Outport blocks to represent input from
and output to blocks outside the subsystem.

4-38

Create a Subsystem

As with all blocks, you can change the name of the Subsystem block. To
customize the appearance and dialog box of the block, you can mask the
subsystem (see “Masking”).

Undoing Subsystem Creation
Right after you create subsystem by grouping blocks (see “Create a Subsystem
by Grouping Existing Blocks” on page 4-37), you can undo that operation. To
undo subsystem creation, select Edit > Undo Subsystem Creation.

Subsystem Execution
You can configure a subsystem to execute either conditionally or
unconditionally.
• An unconditionally executed subsystem always executes.
• A conditionally executed subsystem may or may not execute, depending on
the value of an input signal. For details, see “Conditional Subsystems”.

Navigate Model Hierarchy
Subsystems allow you to create a hierarchical model comprising many layers.
You can navigate this hierarchy using the “Model Browser” on page 9-80 or
with Simulink Editor model navigation commands.
To open a subsystem using the Simulink Editor context menu for the
Subsystem block:
1 In the Simulink Editor, right-click the Subsystem block.

4-39

4

Creating a Model

2 From the context menu, select one of these options:

• Open — Open the subsystem, in the same window and tab as used for
the top model.

• Open In New Tab — Open the subsystem, creating an additional tab
for the subsystem.

• Open In New Window— Open the subsystem, opening a new Simulink
Editor window.

4-40

Create a Subsystem

For any operation to open a subsystem, you can use a keyboard shortcut to
have the subsystem open in a new tab or window:
Where to Open the Subsystem

Keyboard Shortcut

In a new tab

Hold the CTRL key while opening
the subsystem.

In a new window

Hold the SHIFT key while
opening the subsystem.

To display the parent of a subsystem:
1 Open the tab that contains the subsystem.
2 Select View > Navigate > Up to Parent.

4-41

4

Creating a Model

Label Subsystem Ports
By default, Simulink labels ports on a Subsystem block. The labels are the
names of the Inport and Outport blocks that connect the subsystem to blocks
outside of the subsystem.
You can specify how Simulink labels the ports of a subsystem.
1 Select the Subsystem block.
2 Select one of the labeling options from Diagram > Format > Port

Labels menu (for example, From Port Block Name).

Control Access to Subsystems
You can control user access to subsystems. For example, you can prevent a
user from viewing or modifying the contents of a library subsystem while still
allowing the user to employ the subsystem in a model.
Note This method does not necessarily prevent a user from changing the
access restrictions. To hide proprietary information that is in a subsystem,
consider using protected model referencing models (see “Protected Model”
on page 6-67).
To restrict access to a library subsystem, open the subsystem parameter
dialog box and set Read/Write permissions to one of these values:
• ReadOnly: A user can view the contents of the library subsystem but
cannot modify the reference subsystem without disabling its library link or
changing its Read/Write permissions to ReadWrite.
• NoReadOrWrite: A user cannot view the contents of the library subsystem,
modify the reference subsystem, or change reference subsystem
permissions.
Both options allow a user to employ the library subsystem in models by
creating links (see “Libraries”). For more information about subsystem access
options, see the Subsystem block documentation.

4-42

Create a Subsystem

Note You do not receive a response if you attempt to view the contents
of a subsystem whose Read/Write permissions parameter is set to
NoReadOrWrite. For example, when double-clicking such a subsystem,
Simulink does not open the subsystem and does not display any messages.

Interconvert Subsystems and Block Diagrams
To interconvert subsystems and block diagrams, use one of these functions:
Simulink.SubSystem.copyContentsToBlockDiagram

Copies the contents of a subsystem to an empty block diagram.
Simulink.BlockDiagram.copyContentsToSubSystem

Copies the contents of a block diagram to an empty subsystem.

Empty Subsystems and Block Diagrams
To empty subsystems and block diagrams, use one of these functions:
Simulink.SubSystem.deleteContents

Deletes the contents of a subsystem.
Simulink.BlockDiagram.deleteContents

Deletes the contents of a block diagram.

4-43

4

Creating a Model

Control Flow Logic
In this section...
“Equivalent C Language Statements” on page 4-44
“Conditional Control Flow Logic” on page 4-44
“While and For Loops” on page 4-47

Equivalent C Language Statements
You can use block diagrams to model control flow logic equivalent to the
following C programming language statements:
• for
• if-else
• switch
• while

Conditional Control Flow Logic
You can use the following blocks to perform conditional control flow logic.
C Statement

Equivalent Blocks

if-else

If, If Action Subsystem

switch

Switch Case, Switch Case Action Subsystem

If-Else Control Flow
The following diagram represents if-else control flow.

4-44

Control Flow Logic

Construct an if-else control flow diagram as follows:
1 Provide data inputs to the If block for constructing if-else conditions.

In the If block parameters dialog box, set inputs to the If block. Internally,
the inputs are designated as u1, u2,..., un and are used to construct
output conditions.
2 In the If block parameters dialog box, set output port if-else conditions

for the If block.
In the If block parameters dialog box, set Output ports. Use the input
values u1, u2, ..., un to express conditions for the if, elseif, and else
condition fields in the dialog box. Of these, only the if field is required.
You can enter multiple elseif conditions and select a check box to enable
the else condition.
3 Connect each condition output port to an Action subsystem.

Connect each if, elseif, and else condition output port on the If block to a
subsystem to be executed if the port’s case is true.
Create these subsystems by placing an Action Port block in a subsystem.
This creates an atomic Action subsystem with a port named Action, which
you then connect to a condition on the If block.

4-45

4

Creating a Model

Once connected, the subsystem takes on the identity of the condition it is
connected to and behaves like an enabled subsystem.
For more detailed information, see the If and Action Port blocks.
Note All blocks in an Action subsystem driven by an If or Switch Case block
must run at the same rate as the driving block.

Switch Control Flow
The following diagram represents switch control flow.

Construct a switch control flow statement as follows:
1 Provide a data input to the argument input of the Switch Case block.

The input to the Switch Case block is the argument to the switch control
flow statement. This value determines the appropriate case to execute.
Noninteger inputs to this port are truncated.
2 Add cases to the Switch Case block based on the numeric value of the

argument input.
Using the parameters dialog box of the Switch Case block, add cases to the
Switch Case block. Cases can be single or multivalued. You can also add an

4-46

Control Flow Logic

optional default case, which is true if no other cases are true. Once added,
these cases appear as output ports on the Switch Case block.
3 Connect each Switch Case block case output port to an Action subsystem.

Each case output of the Switch Case block is connected to a subsystem to be
executed if the port’s case is true. You create these subsystems by placing
an Action Port block in a subsystem. This creates an atomic subsystem
with a port named Action, which you then connect to a condition on the
Switch Case block. Once connected, the subsystem takes on the identity of
the condition and behaves like an enabled subsystem. Place all the block
programming executed for that case in this subsystem.
For more detailed information, see documentation for the Switch Case and
Action Port blocks.
Note After the subsystem for a particular case executes, an implied break
executes, which exits the switch control flow statement altogether. Simulink
switch control flow statement implementations do not exhibit the “fall
through” behavior of C switch statements.

While and For Loops
Use the following blocks to perform while and for loops.
C Statement

Equivalent Blocks

do-while

While Iterator Subsystem

for

For Iterator Subsystem

while

While Iterator Subsystem

While Loops
The following diagram illustrates a while loop.

4-47

4

Creating a Model

In this example, Simulink repeatedly executes the contents of the While
subsystem at each time step until a condition specified by the While Iterator
block is satisfied. In particular, for each iteration of the loop specified by the
While Iterator block, Simulink invokes the update and output methods of all
the blocks in the While subsystem in the same order that the methods would
be invoked if they were in a noniterated atomic subsystem.
Note Simulation time does not advance during execution of a While
subsystem’s iterations. Nevertheless, blocks in a While subsystem treat each
iteration as a time step. As a result, in a While subsystem, the output of
a block with states (that is, a block whose output depends on its previous
input), reflects the value of its input at the previous iteration of the while
loop. The output does not reflect that block’s input at the previous simulation
time step. For example, a Unit Delay block in a While subsystem outputs the
value of its input at the previous iteration of the while loop, not the value at
the previous simulation time step.
Construct a while loop as follows:
1 Place a While Iterator block in a subsystem.

The host subsystem label changes to while {...}, to indicate that it is
modeling a while loop. These subsystems behave like triggered subsystems.

4-48

Control Flow Logic

This subsystem is host to the block programming that you want to iterate
with the While Iterator block.
2 Provide a data input for the initial condition data input port of the While

Iterator block.
The While Iterator block requires an initial condition data input (labeled
IC) for its first iteration. This must originate outside the While subsystem.
If this value is nonzero, the first iteration takes place.
3 Provide data input for the conditions port of the While Iterator block.

Conditions for the remaining iterations are passed to the data input port
labeled cond. Input for this port must originate inside the While subsystem.
4 (Optional) Set the While Iterator block to output its iterator value through

its properties dialog.
The iterator value is 1 for the first iteration and is incremented by 1 for
each succeeding iteration.
5 (Optional) Change the iteration of the While Iterator block to do-while

through its properties dialog.
This changes the label of the host subsystem to do {...} while. With
a do-while iteration, the While Iteration block no longer has an initial
condition (IC) port, because all blocks in the subsystem are executed once
before the condition port (labeled cond) is checked.
6 Create a block diagram in the subsystem that defines the subsystem’s

outputs.
Note The diagram must not contain blocks with continuous states (for
example, blocks from the Continuous block library). The sample times of
all the blocks must be either inherited (-1) or constant (inf).
For more information, see the While Iterator block.

4-49

4

Creating a Model

Modeling For Loops
The following diagram represents a for loop:

In this example, Simulink executes the contents of the For subsystem
multiples times at each time step. The input to the For Iterator block specifies
the number of iterations . For each iteration of the for loop, Simulink invokes
the update and output methods of all the blocks in the For subsystem in the
same order that it invokes the methods if they are in a noniterated atomic
subsystem.
Note Simulation time does not advance during execution of a For subsystem’s
iterations. Nevertheless, blocks in a For subsystem treat each iteration as a
time step. As a result, in a For subsystem, the output of a block with states
(that is, a block whose output depends on its previous input) reflects the value
of its input at the previous iteration of the for loop. The output does not reflect
that block’s input at the previous simulation time step. For example, a Unit
Delay block in a For subsystem outputs the value of its input at the previous
iteration of the for loop, not the value at the previous simulation time step.
Construct a for loop as follows:
1 Drag a For Iterator Subsystem block from the Library Browser or Library

window into your model.

4-50

Control Flow Logic

2 (Optional) Set the For Iterator block to take external or internal input for

the number of iterations it executes.
Through the properties dialog of the For Iterator block you can set it to take
input for the number of iterations through the port labeled N. This input
must come from outside the For Iterator Subsystem.
You can also set the number of iterations directly in the properties dialog.
3 (Optional) Set the For Iterator block to output its iterator value for use in

the block programming of the For Iterator Subsystem.
The iterator value is 1 for the first iteration and is incremented by 1 for
each succeeding iteration.
4 Create a block diagram in the subsystem that defines the subsystem’s

outputs.
Note The diagram must not contain blocks with continuous states (for
example, blocks from the Continuous block library). The sample times of
all the blocks must be either inherited (-1) or constant (inf).
The For Iterator block works well with the Assignment block to reassign
values in a vector or matrix. The following example shows the use of a For
Iterator block. Note the matrix dimensions in the data being passed.

4-51

4

Creating a Model

The above example outputs the sine value of an input 2-by-5 matrix (2 rows,
5 columns) using a For subsystem containing an Assignment block. The
process is as follows.
1 A 2-by-5 matrix is input to the Selector block and the Assignment block.
2 The Selector block strips off a 2-by-1 matrix from the input matrix at the

column value indicated by the current iteration value of the For Iterator
block.
3 The sine of the 2-by-1 matrix is taken.
4 The sine value 2-by-1 matrix is passed to an Assignment block.
5 The Assignment block, which takes the original 2-by-5 matrix as one of

its inputs, assigns the 2-by-1 matrix back into the original matrix at the
column location indicated by the iteration value.
The rows specified for reassignment in the property dialog for the
Assignment block in the above example are [1,2]. Because there are only
two rows in the original matrix, you could also have specified -1 for the
rows, (that is, all rows).

4-52

Control Flow Logic

Note The Trigonometric Function block is already capable of taking the
sine of a matrix. The above example uses the Trigonometric Function
block only as an example of changing each element of a matrix with the
collaboration of an Assignment block and a For Iterator block.

4-53

4

Creating a Model

Callback Functions
In this section...
“What You Can Do with Callback Functions” on page 4-54
“Callback Tracing” on page 4-55
“Create Model Callback Functions” on page 4-55
“Create Block Callback Functions” on page 4-58
“Port Callback Parameters” on page 4-63
“Callback Function Tasks” on page 4-64

What You Can Do with Callback Functions
Callback functions are a powerful way to customize your Simulink model. A
callback is a function that executes when you perform various actions on
your model, such as clicking on a block or starting a simulation. You can use
callbacks to execute a MATLAB script or other MATLAB commands. You can
use block, port, or model parameters to specify callback functions.
Common tasks that you can achieve by using callback functions include:
• Loading variables into the MATLAB workspace automatically when you
open your Simulink model
• Executing a MATLAB script by double-clicking on a block
• Executing a series of commands before starting a simulation
• Executing commands when a block diagram is closed
For examples of these tasks, see “Callback Function Tasks” on page 4-64.

4-54

Callback Functions

For related tasks, see
• “Model Workspaces” on page 4-67 for loading and modifying variables
required by your model
• “Analyze Model Dependencies” on page 13-104 for analyzing model and
block callbacks, and identifying and packaging files required by your model

Callback Tracing
Use callback tracing to determine the callbacks that Simulink invokes and in
what order the it invokes them when you open or simulate a model.
To enable callback tracing, do one of the following:
• In the Preferences dialog box, select the Callback tracing.
• Execute set_param(0, 'CallbackTracing', 'on').
This option causes the callbacks to appear in the MATLAB Command
Window as they are invoked. This option applies to all Simulink models,
not just models that are open when you the preference is enabled.

Create Model Callback Functions
You can create model callback functions interactively or programmatically.
To create model callbacks interactively, use the Callbacks pane of the model’s
Model Properties dialog box (see “Specifying Callbacks” on page 4-111).
To create a callback programmatically, use the set_param command to assign
a MATLAB expression that implements the function to the model parameter
corresponding to the callback (see “Model Callback Functions” on page 4-56).
For example, this command evaluates the variable testvar when the user
double-clicks the Test block in mymodel:
set_param('mymodel/Test', 'OpenFcn', testvar)

You can examine the clutch system model, sldemo_clutch, for routines
associated with many model callbacks. This model defines the following
callbacks:

4-55

4

Creating a Model

• PreLoadFcn
• PostLoadFcn
• StartFcn
• StopFcn
• CloseFcn

Model Callback Functions
Model Callback
Function

When Executed

CloseFcn

Before the block diagram is closed. Any
ModelCloseFcn and DeleteFcn callbacks set on
blocks in the model are called prior to the model’s
CloseFcn. The DestroyFcn callback of any blocks in
the model is called after the model’s CloseFcn.

ContinueFcn

Before the simulation continues.

InitFcn

At start of model simulation.

PauseFcn

After the simulation pauses.

PostLoadFcn

After the model is loaded. Defining a callback
routine for this parameter might be useful for
generating an interface that requires that the model
has already been loaded.
Note If you make structural changes with
PostLoadFcn, the function does not set the model
Dirty flag to indicate unsaved changes. You can
close the model without being prompted to save.

4-56

Callback Functions

Model Callback
Function

When Executed

PostSaveFcn

After the model is saved.
Note If you make structural changes with
PostSaveFcn, the function does not set the model
Dirty flag to indicate unsaved changes. You can
close the model without being prompted to save.

PreLoadFcn

Before the model is loaded. Defining a callback
routine for this parameter might be useful for
loading variables used by the model.
Note In a PreLoadFcn callback routine, the
get_param command does not return the model’s
parameter values because the model is not yet
loaded.
In a PreLoadFcn routine, get_param returns:
• The default value for a standard model parameter
such as solver
• An error message for a model parameter added
with add_param
In a PostLoadFcn callback routine, however,
get_param returns the model’s parameter values
because the model is loaded.

PreSaveFcn

Before the model is saved.

StartFcn

Before the simulation starts.

StopFcn

After the simulation stops. Output is written to
workspace variables and files before the StopFcn is
executed.

4-57

4

Creating a Model

Note Beware of adverse interactions between callback functions of models
referenced by other models. (See “Model Reference”.) For example, suppose:
• Model A references model B.
• Model A’s OpenFcn creates variables in the MATLAB workspace.
• Model B’s CloseFcn clears the MATLAB workspace.
• Simulating model A requires rebuilding model B.
Rebuilding B entails opening and closing model B and hence invoking model
B’s CloseFcn, which clears the MATLAB workspace, including the variables
created by A’s OpenFcn.

Create Block Callback Functions
You can create block callback functions interactively or programmatically.
To create block callbacks interactively:
1 Right-click a block.
2 In the context menu, select Properties.
3 In the Block Properties dialog box, select the Callback tab.
4 Create the callback function. For details, see “Block Callbacks” on page

23-19.
To create a callback programmatically, use the set_param command to assign
a MATLAB expression that implements the function to the block parameter
corresponding to the callback. For details, see “Block Callback Parameters”
on page 4-59.

4-58

Callback Functions

Note A callback for a masked subsystem cannot directly reference the
parameters of the masked subsystem (see “Masking”). Simulink evaluates
block callbacks in the MATLAB base workspace, whereas the mask
parameters reside in the masked subsystem’s private workspace. A block
callback, however, can use get_param to obtain the value of a mask
parameter. For example:
get_param(gcb, 'gain')

where gain is the name of a mask parameter of the current block.

Block Callback Parameters
This table lists the parameters for which you can define block callback
routines, and indicates when those callback routines execute. Routines that
execute before or after actions take place occur immediately before or after
the action.
Parameter

When Executed

ClipboardFcn

When the block is copied or cut to the system
clipboard.

CloseFcn

When the block is closed using the close_system
command. The CloseFcn is not called when you
interactively close the block, when you interactively
close the subsystem or model containing the block,
or when you close the subsystem or model containing
the block using close_system.

ContinueFcn

Before the simulation continues.

CopyFcn

After a block is copied. The callback is recursive for
Subsystem blocks (that is, if you copy a Subsystem
block that contains a block for which the CopyFcn
parameter is defined, the routine is also executed).
The routine is also executed if an add_block
command is used to copy the block.

4-59

4

4-60

Creating a Model

Parameter

When Executed

DeleteChildFcn

After a block or line is deleted in a subsystem. If
the block has a DeleteFcn or DestroyFcn, those
functions are executed prior to the DeleteChildFcn.
Only Subsystem blocks have a DeleteChildFcn
callback.

DeleteFcn

After a block is graphically deleted, e.g., when you
graphically delete the block, invoke delete_block
on the block, or close the model containing the
block. When the DeleteFcn is called, the block
handle is still valid and can be accessed using
get_param. The DeleteFcn callback is recursive for
Subsystem blocks. If the block is graphically deleted
by invoking delete_block or by closing the model,
after deletion the block is destroyed from memory
and the block’s DestroyFcn is called.

DestroyFcn

When the block has been destroyed from memory
(for example, when you invoke delete_block on
either the block or a subsystem containing the block
or close the model containing the block). If the block
was not previously graphically deleted, the block’s
DeleteFcn is called prior to the DestroyFcn. When
the DestroyFcn is called, the block handle is no
longer valid.

ErrorFcn

When an error has occurred in a subsystem. Only
Subsystem blocks have an ErrorFcn callback. For
more information, see “Subsystem Error Function
Callback” on page 4-62.

InitFcn

Before the block diagram is compiled and before
block parameters are evaluated.

LoadFcn

After the block diagram is loaded. This callback is
recursive for Subsystem blocks.

ModelCloseFcn

Before the block diagram is closed. When the model
is closed, the block’s ModelCloseFcn is called prior
to its DeleteFcn. This callback is recursive for
Subsystem blocks.

Callback Functions

Parameter

When Executed

MoveFcn

When the block is moved or resized.

NameChangeFcn

After a block’s name or path changes. When a
Subsystem block’s path changes, the Subsystem
block recursively calls this function for all blocks
that it contains after calling its own NameChangeFcn
routine.

OpenFcn

When the block is opened. Generally, use this
parameter with Subsystem blocks. The routine is
executed when you double-click the block or when an
open_system command is called with the block as
an argument. The OpenFcn parameter overrides the
normal behavior associated with opening a block,
which is to display the block’s dialog box or to open
the subsystem.

ParentCloseFcn

Before closing a subsystem containing the block or
when the block is made part of a new subsystem
using the new_system command or in the Simulink
Editor, select Diagram > Subsystem & Model
ReferenceCreate Subsystem from Selection .
The ParentCloseFcn of blocks at the root model
level is not called when the model is closed.

PauseFcn

After the simulation pauses.

PostSaveFcn

After the block diagram is saved. This callback is
recursive for Subsystem blocks.

PreCopyFcn

Before a block is copied. The callback is recursive for
Subsystem blocks (that is, if you copy a Subsystem
block that contains a block for which the PreCopyFcn
parameter is defined, that routine is also executed).
The block’s CopyFcn is called after all PreCopyFcn
callbacks are executed, unless the PreCopyFcn
invokes the error command either explicitly or via a
command used in any PreCopyFcn. The PreCopyFcn
is also executed if an add_block command is used to
copy the block.

4-61

4

Creating a Model

Parameter

When Executed

PreDeleteFcn

Before a block is graphically deleted (for example,
when the user graphically deletes the block
or invokes delete_block on the block). The
PreDeleteFcn is not called when the model
containing the block is closed. The block’s
DeleteFcn is called after the PreDeleteFcn, unless
the PreDeleteFcn invokes the error command
either explicitly or via a command used in the
PreDeleteFcn.

PreSaveFcn

Before the block diagram is saved. This callback is
recursive for Subsystem blocks.

StartFcn

After the block diagram is compiled and before the
simulation starts. In the case of an S-Function
block, StartFcn executes immediately before the
first execution of the block’s mdlProcessParameters
function. For more information, see “S-Function
Callback Methods”.

StopFcn

At any termination of the simulation. In the case
of an S-Function block, StopFcn executes after the
block’s mdlTerminate function executes. For more
information, see “S-Function Callback Methods”.

UndoDeleteFcn

When a block deletion is undone.

Note Do not call the run command from within model or block callbacks.
Doing so can result in unexpected behavior (such as errors or incorrect
results) if a Simulink model is loaded, compiled, or simulated from inside
a MATLAB function.

Subsystem Error Function Callback
The callback error function should have the following form:
newException = errorHandler(subsys, errorType, originalException)

where

4-62

Callback Functions

• errorHandler is the name of the callback function
• subsys is a handle to the subsystem in which the error occurred
• errorType is a Simulink string indicating the type of error that occurred
• originalException is an MSLException (see “Error Handling in Simulink
Using MSLException” on page 15-15)
• newException is an MSLException specifying the error message to be
displayed to the user
If you provide the original exception, then you do not need to specify the
subsystem and the error type.
The following command sets the ErrorFcn of the subsystem subsys to call
the errorHandler callback function
set_param(subsys,'ErrorFcn','errorHandler')

In such calls to set_param, do not include the input arguments of the callback
function. Simulink displays the error message errorMsg returned by the
callback function.

Subsystem Error Function Callback: Compatibility
Considerations
In terms of backward compatibility, the following command works but is
not recommended:
errorMsg = errorHandler(subsys, errorType)

where errorMsg is a string containing the error message.

Port Callback Parameters
Block input and output ports have a single callback function parameter,
ConnectionCallback. This parameter allows you to set callbacks on ports
that are triggered every time the connectivity of these ports changes.
Examples of connectivity changes include adding a connection from the port
to a block, deleting a block connected to the port, and deleting, disconnecting,
or connecting branches or lines to the port.

4-63

4

Creating a Model

Use get_param to get the port handle of a port and set_param to set the
callback on the port. The callback function must have one input argument
that represents the port handle, but the input argument is not included in
the call to set_param. For example, suppose the currently selected block has
a single input port. The following code fragment sets foo as the connection
callback on the input port.
phs = get_param(gcb, 'PortHandles');
set_param(phs.Inport, 'ConnectionCallback', 'foo');

where, foo is defined as:
function foo(portHandle)

Callback Function Tasks
The following sections describe simple examples for commonly used callback
routines.
• “Load Variables Automatically When Opening a Model” on page 4-64
• “Execute a MATLAB Script by Double-Clicking a Block” on page 4-65
• “Execute Commands Before Starting Simulation” on page 4-66

Load Variables Automatically When Opening a Model
You can use the PreloadFcn callback to automatically preload variables into
the MATLAB workspace when you open your model.
Parameters in different parts of the Simulink model might require some
variables. For example, if you have a model that contains a Gain block and
the gain is specified as K, Simulink looks for the variable K to be defined. You
can automatically define K every time the model is opened.
You can define variables, such as K, in a MATLAB script. You can use the
PreLoadFcn callback to execute the MATLAB script.
To create model callbacks interactively, in the Simulink Editor, select File >
Model Properties > Model Properties and use the Callbacks tab to edit
callbacks (see “Specifying Callbacks” on page 4-111).

4-64

Callback Functions

To create a callback programmatically, at the MATLAB command prompt,
enter the following :
set_param('mymodelname','PreloadFcn', 'expression')

where expression is a valid MATLAB command or a MATLAB script that
exists in your MATLAB search path.
For example, if your model is called modelname.slx and your variables are
defined in a MATLAB script called loadvar.m, you would type the following:
set_param('modelname','PreloadFcn', 'loadvar')

Now save the model. Every time you subsequently open this model, the
loadvar function will execute. You can see the variables from the loadvar.m
declared in the MATLAB workspace.

Execute a MATLAB Script by Double-Clicking a Block
You can use the OpenFcn callback to automatically execute MATLAB scripts
when the you double-click a block. MATLAB scripts can perform many
different tasks, such as defining variables for a block, making a call to
MATLAB that brings up a plot of simulated data, or generating a GUI.
The OpenFcn overrides the normal behavior which occurs when opening a
block (its parameter dialog box is displayed or a subsystem is opened).
To create block callbacks interactively, open the block’s Block Properties
dialog box and use the Callbacks tab to edit callbacks (see “Block Callbacks”
on page 23-19).
To create the OpenFcn callback programmatically, click the block to which you
want to add this property, then enter the following at the MATLAB command
prompt:
set_param(gcb,'OpenFcn','expression')

where expression is a valid MATLAB command or a MATLAB script that
exists in your MATLAB search path.

4-65

4

Creating a Model

The following example shows how to set up the callback to execute a
MATLAB script called myfunction.m when double clicking a subsystem
called mysubsystem.
set_param('mymodelname/mysubsystem','OpenFcn','myfunction')

Execute Commands Before Starting Simulation
You can use the StartFcn callback to automatically execute commands before
the simulation starts.
For example, you can make all of the Scope blocks that exist in a model come
to the forefront before running the simulation. Create a simple MATLAB
script named openscopes.m and save it on your MATLAB search path, as
shown in the following code.
% openscopes.m
% Brings scopes to forefront at beginning of simulation.
blocks = find_system(bdroot,'BlockType','Scope');
% Finds all of the scope blocks on the top level of your
% model to find scopes in subsystems, give the subsystem
% names. Type help find_system for more on this command.
for i = 1:length(blocks)
set_param(blocks{i},'Open','on')
end
% Loops through all of the scope blocks and brings them
% to the forefront

After you create this MATLAB script, set the StartFcn for the model to call
the script. For example,
set_param('mymodelname','StartFcn','openscopes')

Now every time you run the model, all of the Scope blocks automatically open
in the forefront.

4-66

Model Workspaces

Model Workspaces
In this section...
“Model Workspace Differences from MATLAB Workspace” on page 4-67
“Troubleshooting Memory Issues” on page 4-68
“Simulink.ModelWorkspace Data Object Class” on page 4-68
“Change Model Workspace Data” on page 4-69
“Specify Data Sources” on page 4-72

Model Workspace Differences from MATLAB
Workspace
Each model is provided with its own workspace for storing variable values.
The model workspace is similar to the base MATLAB workspace except that:
• Variables in a model workspace are visible only in the scope of the model.
If both the MATLAB workspace and a model workspace define a variable
of the same name, and the variable does not appear in any intervening
masked subsystem or model workspaces, the Simulink software uses
the value of the variable in the model workspace. A model’s workspace
effectively provides it with its own name space, allowing you to create
variables for the model without risk of conflict with other models.
• When the model is loaded, the workspace is initialized from a data source.
The data source can be a Model file, a MAT-file, a MATLAB file, or
MATLAB code stored in the model file. For more information, see “Data
source” on page 4-72.
• You can interactively reload and save MAT-file, MATLAB file, and
MATLAB code data sources.
• Only Simulink.Parameter and Simulink.Signal objects for which the
storage class is set to Auto can reside in a model workspace. You must
create all other Simulink data objects in the base MATLAB workspace
to ensure the objects are unique within the global Simulink context and
accessible to all models.

4-67

4

Creating a Model

Note Subclasses of Simulink.Parameter and Simulink.Signal classes,
including mpt.Parameter and mpt.Signal objects (Embedded Coder®
license required), can reside in a model workspace only if their storage
class is set to Auto.
• In general, parameter variables in a model workspace are not tunable.
However, you can tune model workspace variables declared as model
arguments for referenced models. For more information, see “Using Model
Arguments” on page 6-53.
Note When resolving references to variables used in a referenced model, the
variables of the referenced model are resolved as if the parent model did
not exist. For example, suppose a referenced model references a variable
that is defined in both the parent model’s workspace and in the MATLAB
workspace but not in the referenced model’s workspace. In this case, the
MATLAB workspace is used.

Troubleshooting Memory Issues
When you use a workspace variable as a block parameter, Simulink creates a
copy of the variable during the compilation phase of the simulation and stores
the variable in memory. This can cause your system to run out of memory
during simulation, or in the process of generating code. Your system might
run out of memory if you have:
• Large models with many parameters
• Models with parameters that have a large number of elements
This issue does not affect the amount of memory that is used to represent
parameters in generated code.

Simulink.ModelWorkspace Data Object Class
An instance of the Simulink.ModelWorkspace class describes a model
workspace. Simulink creates an instance of this class for each model that

4-68

Model Workspaces

you open during a Simulink session. The methods associated with this class
can be used to accomplish a variety of tasks related to the model workspace,
including:
• Listing the variables in the model workspace
• Assigning values to variables
• Evaluating expressions
• Clearing the model workspace
• Reloading the model workspace from the data source
• Saving the model workspace to a specified MAT-file or MATLAB file
• Saving the workspace to the MAT-file or MATLAB file that the workspace
designates as its data source

Change Model Workspace Data
The procedure for modifying a workspace depends on the data source of the
model workspace.

Change Workspace Data Whose Source Is the Model File
If the data sources of a model workspace is data stored in the model, you can
use Model Explorer or MATLAB commands to change the model’s workspace
(see “Use MATLAB Commands to Change Workspace Data” on page 4-71).
For example, to create a variable in a model workspace:
1 Open the Model Explorer by selecting View > Model Explorer.
2 In the Model Explorer Model Hierarchy pane, select the model workspace.
3 Select Add > MATLAB Variable.

You can similarly use the Add menu or toolbar to add a
Simulink.Parameter object to a model workspace.
To change the value of a model workspace variable:
1 Open the Model Explorer by selecting View > Model Explorer.

4-69

4

Creating a Model

2 In the Model Explorer Model Hierarchy pane, select the model workspace.
3 In the Contents pane, select the variable.
4 In the Contents pane or in Dialog pane, edit the value displayed.

To delete a model workspace variable:
1 Open the Model Explorer by selecting View > Model Explorer.
2 In the Model Explorer Model Hierarchy pane, select the model workspace.
3 In Contents pane, select the variable.
4 Select Edit > Delete.

Change Workspace Data Whose Source Is a MAT-File or
MATLAB File
You can use Model Explorer or MATLAB commands to modify workspace
data whose source is a MAT-file or MATLAB file.
To make the changes permanent, in the Model Workspace dialog box, use the
Save To Source button to save the changes to the MAT-file or MATLAB file.
1 Open the Model Explorer by selecting View > Model Explorer.
2 In the Model Explorer Model Hierarchy pane, right-click the workspace.
3 Select the Properties menu item.
4 In the Model Workspace dialog box, use the Save To Source button to

save the changes to the MAT-file or MATLAB file.
To discard changes to the workspace, in the Model Workspace dialog box, use
the Reinitialize From Source button.

Changing Workspace Data Whose Source Is MATLAB Code
The safest way to change data whose source is MATLAB code is to edit and
reload the source. Edit the MATLAB code and then in the Model Workspace

4-70

Model Workspaces

dialog box, use Reinitialize From Source button to clear the workspace
and re-execute the code.
To save and reload alternative versions of the workspace that result from
editing the MATLAB code source or the workspace variables themselves, see
“Exporting Workspace Variables” on page 9-60 and “Importing Workspace
Variables” on page 9-62.

Use MATLAB Commands to Change Workspace Data
To use MATLAB commands to change data in a model workspace, first get
the workspace for the currently selected model:
hws = get_param(bdroot, 'modelworkspace');

This command returns a handle to a Simulink.ModelWorkspace object
whose properties specify the source of the data used to initialize the model
workspace. Edit the properties to change the data source.
Use the workspace methods to:
• List, set, and clear variables
• Evaluate expressions in the workspace
• Save and reload the workspace
For example, the following MATLAB code creates variables specifying model
parameters in the model workspace, saves the parameters, modifies one of
them, and then reloads the workspace to restore it to its previous state.
hws = get_param(bdroot, 'modelworkspace');
hws.DataSource = 'MAT-File';
hws.FileName = 'params';
hws.assignin('pitch', -10);
hws.assignin('roll', 30);
hws.assignin('yaw', -2);
hws.saveToSource;
hws.assignin('roll', 35);
hws.reload;

4-71

4

Creating a Model

Specify Data Sources
To specify a data source for a model workspace, in the Model Explorer, use the
Model Workspace dialog box. To display the dialog box for a model workspace:
1 Open the Model Explorer by selecting View > Model Explorer.
2 In the Model Hierarchy pane, right-click the model workspace.

3 Select the Properties menu item, which opens the Model Workspace

dialog box.
To use MATLAB commands to change data in a model workspace, see “Use
MATLAB Commands to Change Workspace Data” on page 4-71.

Data source
The Data source field in the Model Workspace dialog box includes the
following data source options for a workspace:
• Model File
Specifies that the data source is the model itself.
• MAT-File

4-72

Model Workspaces

Specifies that the data source is a MAT file. Selecting this option causes
additional controls to appear (see “MAT-File and MATLAB File Source
Controls” on page 4-73).
• MATLAB File
Specifies that the data source is a MATLAB file. Selecting this option
causes additional controls to appear (see “MAT-File and MATLAB File
Source Controls” on page 4-73).
• MATLAB Code
Specifies that the data source is MATLAB code stored in the model file.
Selecting this option causes additional controls to appear (see “MATLAB
Code Source Controls” on page 4-74).

MAT-File and MATLAB File Source Controls
Selecting MAT-File or MATLAB File as the Data source for a workspace
causes the Model Workspace dialog box to display additional controls.

File name. Specifies the file name or path name of the MAT-file or MATLAB
file that is the data source for the selected workspace. If you specify a file
name, the name must reside on the MATLAB path.

4-73

4

Creating a Model

Reinitialize From Source. Clears the workspace and reloads the data from
the MAT-file or MATLAB file specified by the File name field.
Save To Source. Saves the workspace in the MAT-file or MATLAB file
specified by the File name field.

MATLAB Code Source Controls
Selecting MATLAB Code as the Data source for a workspace causes the Model
Workspace dialog box to display additional controls.

4-74

Model Workspaces

MATLAB Code. Specifies MATLAB code that initializes the selected
workspace. To change the initialization code, edit this field, then select the
Reinitialize from source button on the dialog box to clear the workspace
and execute the modified code.
Reinitialize from Source. Clears the workspace and executes the contents
of the MATLAB Code field.

Model Arguments (For Referencing This Model)
Specifies arguments that can be passed to instances of a model that another
model references. For more information, see “Using Model Arguments” on
page 6-53.

4-75

4

Creating a Model

Symbol Resolution
In this section...
“Symbols” on page 4-76
“Symbol Resolution Process” on page 4-76
“Numeric Values with Symbols” on page 4-78
“Other Values with Symbols” on page 4-78
“Limit Signal Resolution” on page 4-79
“Explicit and Implicit Symbol Resolution” on page 4-80

Symbols
When you create a Simulink model, you can use symbols to provide values
and definitions for many types of entities in the model. Model entities that
you can define with symbols include block parameters, configuration set
parameters, data types, signals, signal properties, and bus architecture.
A symbol that provides a value or definition must be a legal MATLAB
identifier. Such an identifier starts with an alphabetic character, followed by
alphanumeric or underscore characters up to the length given by the function
namelengthmax. You can use the function isvarname to determine whether a
symbol is a legal MATLAB identifier.
A symbol provides a value or definition in a Simulink model by corresponding
to some item that:
• Exists in an accessible workspace
• Has a name that matches the symbol
• Provides the required information

Symbol Resolution Process
The process of finding an item that corresponds to a symbol is called symbol
resolution or resolving the symbol. The matching item can provide the needed
information directly, or it can itself be a symbol. A symbol must resolve to
some other item that provides the information.

4-76

Symbol Resolution

When the Simulink software compiles a model, it tries to resolve every symbol
in the model, except symbols in MATLAB code that runs in a callback or as
part of mask initialization. Depending on the particular case, the item to
which a symbol resolves can be a variable, object, or function.
Simulink attempts to resolve a symbol by searching through the accessible
workspaces in hierarchical order for a MATLAB variable or Simulink object
whose name is the same as the symbol.
The search path is identical for every symbol. The search begins with the
block that uses the symbol, or is the source of a signal that is named by the
symbol, and proceeds upward. Except when simulation occurs via the sim
command, the search order is:
1 Any mask workspaces, in order from the block upwards (see “How Mask

Parameters Work” on page 26-4)
2 The model workspace of the model that contains the block (see “Model

Workspaces” on page 4-67)
3 The MATLAB base workspace (see “What Is the MATLAB Workspace?”)

If Simulink finds a matching item in the course of this search, the search
terminates successfully at that point, and the symbol resolves to the matching
item. The result is the same as if the value of that item had appeared literally
instead of the symbol that resolved to the item. An object defined at a lower
level shadows any object defined at a higher level.
If no matching item exists on the search path, Simulink attempts to evaluate
the symbol as a function. If the function is defined and returns an appropriate
value, the symbol resolves to whatever the function returned. Otherwise, the
symbol remains unresolved, and an error occurs. Evaluation as a function
occurs as the final step whenever a hierarchical search terminates without
having found a matching workspace variable.
If the model that contains the symbol is a referenced model, and the search
reaches the model workspace but does not succeed there, the search jumps
directly to the base workspace without trying to resolve the symbol in
the workspace of any parent model. Thus a given symbol resolves to the
same item, irrespective of whether the model that contains the symbol is

4-77

4

Creating a Model

a referenced model. For information about model referencing, see “Model
Reference”.

Numeric Values with Symbols
You can specify any block parameter that requires a numeric value by
providing a literal value, a symbol, or an expression, which can contain
symbols and literal values. Each symbol is resolved separately, as if none of
the others existed. Different symbols in an expression can thus resolve to
items on different workspaces, and to different types of item.
When a single symbol appears and resolves successfully, its value provides the
value of the parameter. When an expression appears, and all symbols resolve
successfully, the value of the expression provides the value of the parameter.
If any symbol cannot be resolved, or resolves to a value of inappropriate type,
an error occurs.
For example, suppose that the Gain parameter of a Gain block is given as
cos(a*(b+2)). The symbol cos will resolve to the MATLAB cosine function,
and a and b must resolve to numeric values, which can be obtained from the
same or different types of items in the same or different workspaces. If the
symbols resolve to numeric values, the value returned by the cosine function
becomes the value of the Gain parameter.

Other Values with Symbols
Most symbols and expressions that use them provide numeric values, but the
same techniques that provide numeric values can provide any type of value
that is appropriate for its context.
Another common use of symbols is to name objects that provide definitions
of some kind. For example, a signal name can resolve to a signal object
(Simulink.Signal) that defines the properties of the signal, and a Bus
Creator block Data type parameter can name a bus object (Simulink.Bus)
that defines the properties of the bus. You can use symbols for many
purposes, including:
• Define data types
• Specify input data sources

4-78

Symbol Resolution

• Specify logged data destinations
For hierarchical symbol resolution, all of these different uses of symbols,
whether singly or in expressions, are the same. Each symbol is resolved, if
possible, independently of any others, and the result becomes available where
the symbol appeared. The only difference between one symbol and another is
the specific item to which the symbol resolves and the use made of that item.
The only requirement is that every symbol must resolve to something that
can legally appear at the location of the symbol.

Limit Signal Resolution
Hierarchical symbol resolution traverses the complete search path by default.
You can truncate the search path by using the Permit Hierarchical
Resolution option of any subsystem. This option controls what happens if
the search reaches that subsystem without resolving to a workspace variable.
The Permit Hierarchical Resolution values are:
• All
Continue searching up the workspace hierarchy trying to resolve the
symbol. This is the default value.
• None
Do not continue searching up the hierarchy.
• ExplicitOnly
Continue searching up the hierarchy only if the symbol specifies a block
parameter value, data store memory (where no block exists), or a signal or
state that explicitly requires resolution. Do not continue searching for an
implicit resolution. See “Explicit and Implicit Symbol Resolution” on page
4-80 for more information.
If the search does not find a match in the workspace, and terminates
because the value is ExplicitOnly or None, Simulink evaluates the symbol
as a function. The search succeeds or fails depending on the result of the
evaluation, as previously described.

4-79

4

Creating a Model

Explicit and Implicit Symbol Resolution
Models and some types of model entities have associated parameters that can
affect symbol resolution. For example, suppose that a model includes a signal
named Amplitude, and that a Simulink.Signal object named Amplitude
exists in an accessible workspace. If the Amplitude signal’s Signal name
must resolve to Simulink signal object option is checked, the signal will
resolve to the object. See “Signal Properties Controls” for more information.
If the option is not checked, the signal may or may not resolve to the object,
depending on the value of Configuration Parameters > Data Validity >
Signal resolution. This parameter can suppress resolution to the object
even though the object exists, or it can specify that resolution occurs on the
basis of the name match alone. For more information, see “Diagnostics Pane:
Data Validity” > “Signal resolution”.
Resolution that occurs because an option such as Signal name must resolve
to Simulink signal object requires it is called explicit symbol resolution.
Resolution that occurs on the basis of name match alone, without an explicit
specification, is called implicit symbol resolution.
Tip Implicit symbol resolution can be useful for fast prototyping. However,
when you are done prototypying, consider using explicit symbol resolution,
because implicit resolution slows performance, complicates model validation,
and can have nondeterministic effects.

4-80

Consult the Model Advisor

Consult the Model Advisor
In this section...
“About the Model Advisor” on page 4-81
“Start the Model Advisor” on page 4-82
“Overview of the Model Advisor Window” on page 4-85
“Overview of the Model Advisor Dashboard” on page 4-87
“Run Model Advisor Checks” on page 4-88
“Run Checks Using Model Advisor Dashboard” on page 4-91
“Highlight Model Advisor Analysis Results” on page 4-93
“Fix a Warning or Failure” on page 4-95
“Revert Changes Using Restore Points” on page 4-99
“View and Save Model Advisor Reports” on page 4-101
“Run the Model Advisor Programmatically” on page 4-104
“Check Support for Libraries” on page 4-104
“Model Advisor Limitations” on page 4-105
“Consult the Upgrade Advisor” on page 4-105

About the Model Advisor
The Model Advisor checks a model or subsystem for conditions and
configuration settings that can result in inaccurate or inefficient simulation
of the system that the model represents. If you have a Simulink Coder
or Simulink Verification and Validation™ license, the Model Advisor can
also check for model settings that result in generation of inefficient code
or code unsuitable for safety-critical applications. (For more information
about using the Model Advisor in code generation applications, see “Advice
About Optimizing Models for Code Generation” in the Simulink Coder
documentation.)
The Model Advisor produces a report that lists the suboptimal conditions or
settings that it finds, suggesting better model configuration settings where
appropriate. In some cases, the Model Advisor provides mechanisms for

4-81

4

Creating a Model

automatically fixing warnings and failures or fixing them in batches. For
more information on individual checks, see “Simulink Checks”.
Software is inherently complex and may not be completely free of
errors. Model Advisor checks might contain bugs. MathWorks reports
known bugs brought to its attention on its Bug Report system at
http://www.mathworks.com/support/bugreports/. The bug reports are an
integral part of the documentation for each release. Examine periodically all
bug reports for a release as such reports may identify inconsistencies between
the actual behavior of a release you are using and the behavior described
in this documentation.
While applying Model Advisor checks to your model will increase the
likelihood that your model does not violate certain modeling standards
or guidelines, their application cannot guarantee that the system being
developed will be safe or error-free. It is ultimately your responsibility to
verify, using multiple methods, that the system being developed provides its
intended functionality and does not include any unintended functionality.

Start the Model Advisor
There are two Model Advisor GUIs to run checks that verify the syntax of
your model: the Model Advisor window and the Model Advisor dashboard.
If you want
to ...

Use the ...

Consistently
run the same
set of checks on
your model.

Model Advisor
dashboard. The
Model Advisor
dashboard does
not reload
checks for an
analysis, saving
analysis time.

Select checks
to run on your
model.

4-82

Model Advisor
window.

Set Options ...

1 From the Model Editor,

select Analysis > Model
Advisor > Options.
2 In the Model Advisor Options

window, for the Default GUI, select
Model Advisor Dashboard.
1 From the Model Editor,

select Analysis > Model
Advisor > Options.

Consult the Model Advisor

If you want
to ...

Use the ...

Set Options ...

2 In the Model Advisor Options

window, for the Default GUI, select
Model Advisor.

Before starting the Model Advisor, ensure that the current folder is writable.
If the folder is not writable, when you start the Model Advisor, you see an
error message.
The Model Advisor uses the Simulink project (slprj) folder to store reports
and other information. If this folder does not exist in the current folder, the
Model Advisor creates it.
To start the Model Advisor, use any of the following methods:
To open the
Model Advisor
window or
Model Advisor
dashboard ...

For a...

Do this action:

From the Model
Editor

Model or
subsystem

1 Select Analysis > Model

Advisor > Model Advisor or
Model Advisor Dashboard.
Alternately, on the Model Editor
toolbar

drop-down list, select

Model Advisor or Model Advisor
Dashboard.

4-83

4

Creating a Model

To open the
Model Advisor
window or
Model Advisor
dashboard ...

For a...

Do this action:

Note Clicking
opens
the Model Advisor GUI set
in the Analysis > Model
Advisor > Options interface.
2 In the System Selector window,

select the model or subsystem that
you want.
3 Click OK.

4-84

From the Model
Explorer

Model

In the Contents pane, select Advice
for model. model is the name of the
model that you want to check. (For
more information, see “Model Explorer
Overview” on page 9-2.)

From the context
menu

Subsystem

Right-click the subsystem that you
want to check and select Model
Advisor.

Programmatically Model or
subsystem

At the MATLAB prompt, enter
modeladvisor(model). model is
a handle or name of the model or
subsystem that you want to check.
(For more information, see the
modeladvisor function reference
page.)

Consult the Model Advisor

Overview of the Model Advisor Window
When you start the Model Advisor, the Model Advisor window displays two
panes. The left pane lists the folders in the Model Advisor. Expanding the
folders displays the available checks. The right pane provides instructions on
how to view, enable, and disable checks. It also provides a legend describing
the displayed symbols.

You can:
• Select By Task to display checks related to specific tasks, such as updating
the model to be compatible with the current Simulink version.
• Select some or all of the checks using the check boxes or context menus for
the checks, and then run one or all selected checks.
• Reset the status of the checks to not run by right-clicking Model Advisor
in the right pane and selecting Reset from the context menu.
• Specify input parameters for some checks to run (for an example, see
“Check for proper Merge block usage” in the Product > Simulink folder).

4-85

4

Creating a Model

To find checks and folders, enter text in the Find: field and click the Find
Next button (
). The Model Advisor searches in check names, folder
names, and analysis descriptions for the text.
To customize the Model Advisor checks shown in the left pane, on the toolbar,
you can select:
• View > Show By Product Folder
• View > Show By Task Folder

To run the selected checks, on the toolbar of the Model Advisor window, click
Run selected checks ( ).
After running checks, the Model Advisor displays the results in the right
pane. Additionally, the Model Advisor generates an HTML report of the check
results. You can view this report in a separate browser window by clicking
either Open Report ( ) or the Report link at the folder level.
To view the analysis results for individual checks, you can specify that the
Model Advisor use color highlighting on the model diagram. To enable Model
Advisor highlighting, do one of the following in the Model Advisor window, on
the toolbar:
• Select Highlighting > Model Advisor Highlighting.
• Click the Enable Model Advisor highlighting toggle button (

).

When you use highlighting on the model diagram, you can specify that the
Model Advisor highlight model blocks that are excluded from individual
Model Advisor checks. On the toolbar of the Model Advisor window, select
Highlighting > Highlight exclusions. If you have a Simulink Verification
and Validation license, you can create or modify exclusions to the Model
Advisor checks.
To switch to the Model Advisor dashboard, click the Switch to Model
Advisor Dashboard toggle button ( ).

4-86

Consult the Model Advisor

Note When you open the Model Advisor for a model that you have previously
checked, the Model Advisor initially displays the check results generated
the last time that you checked the model. If you recheck the model, the new
results replace the previous results in the Model Advisor window.

Overview of the Model Advisor Dashboard
Using the Model Advisor dashboard, you can efficiently check that your
model complies with modeling guidelines. When you use the Model Advisor
dashboard, the Model Advisor does not reload checks for an analysis, saving
analysis time.

To run checks, on the Model Advisor dashboard toolbar, click Run model
advisor ( ).
After running checks, the Model Advisor generates an HTML report of the
check results. You can view this report in a separate browser window by
clicking the Open Report ( ).
To view highlighted results, click the Highlighting results toggle button
( ).
To switch to the Model Advisor window, click the Switch to Model Advisor
toggle button ( ).
Tip Use the Model Advisor window to select and view checks. To open the
Model Advisor window, click the Switch to Model Advisor toggle button
( ).

4-87

4

Creating a Model

Run Model Advisor Checks
To perform checks on your model and view the results:
1 Open your model. For example, open the Model Advisor example model:

sldemo_mdladv.
2 Start the Model Advisor.
a From the Model Editor, select Analysis > Model Advisor > Model

Advisor.
Alternately, from the Model Editor toolbar
Model Advisor.

drop-down list, select

b In the System Selector window, select the model or system that you want

to review. For example, sldemo_mdladv, and click OK.
The Model Advisor window opens and displays checks for the
sldemo_mdladv model.
3 In the left pane, expand the By Product folder to display the subfolders.

Then expand the Simulink folder to display the available checks.
4 In the left pane, select the By Product folder. The right pane changes to

a By Product view.

4-88

Consult the Model Advisor

5 After you run the checks, select the Show report after run check box to

see an HTML report of check results.
Tip Use the Model Advisor window for interactive fixing of warnings and
failures. Model Advisor reports are best for viewing a summary of checks.
6 Run the selected checks by clicking the Run Selected Checks button.

Alternately, select Run selected checks ( ). After the Model Advisor
runs the checks, an HTML report displays the check results in a browser
window.

4-89

4

Creating a Model

7 Return to the Model Advisor window, which shows the check results.
8 Select an individual check to open a detailed view of the results in the right

pane. For example, selecting Identify unconnected lines, input ports,
and output ports changes the right pane to the following view. Use this
view to examine and exercise a check individually.

9 In the Model Advisor window, click the Enable Model Advisor

highlighting toggle button (
icon.
an

4-90

). Checks with highlighted results have

Consult the Model Advisor

• The model window opens. The blocks causing the Identify
unconnected lines, input ports, and output ports check warning
are highlighted in yellow.

• The Model Advisor Highlighting information window opens with a link
to the Model Advisor window. In the Model Advisor window, you can
find more information about the check results and how to correct the
warning condition.

10 After reviewing these check results in the Model Advisor window, you

can choose to fix warnings or failures as described in “Fix a Warning or
Failure” on page 4-95.

Run Checks Using Model Advisor Dashboard
To run checks on your model using the Model Advisor dashboard:
1 Open your model. For example, open the Model Advisor model,

sldemo_mdladv.
2 Start the Model Advisor dashboard.
a From the Model Editor, select Analysis > Model Advisor > Model

Advisor Dashboard .

4-91

4

Creating a Model

Alternately, from the Model Editor toolbar
Model Advisor Dashboard.

drop-down list, select

b In the System Selector window, select the model or system that you want

to review. For example, sldemo_mdladv and click OK.
The Model Advisor dashboard opens.
3 Optionally, select or view checks to run on your model by clicking the

Switch to Model Advisor toggle button (
opens.

). The Model Advisor window

a For example, in the Model Advisor window, open the By Product folder

and select checks:
Identify unconnected lines, input ports, and output ports
Check root model Inport block specifications
b Switch back to the Model Advisor dashboard by clicking the Switch to

Model Advisor Dashboard toggle button (

).

4 On the Model Advisor dashboard, click Run model advisor (

) to run

the checks.
5 Click the Highlighting results toggle button (

) to view highlighted

results.
• The model window opens. The blocks causing the Identify
unconnected lines, input ports, and output ports check warning
are highlighted in yellow.

• The Model Advisor Highlighting information window opens with a link
to the Model Advisor window. In the Model Advisor window, you can

4-92

Consult the Model Advisor

find more information about the check results and how to correct the
warning condition.

6 After reviewing the check results, you can choose to fix warnings or failures

as described in “Fix a Warning or Failure” on page 4-95. For example,
fix the Identify unconnected lines, input ports, and output ports
check warning:
a

Connect model blocks Gain2 and Out4.

On the Model Advisor dashboard, click Run model advisor ( ) to
rerun the checks. The Model Advisor does not reload all the available
checks, saving analysis time.
The Identify unconnected lines, input ports, and output ports check
passes.
b

Highlight Model Advisor Analysis Results
You can use color highlighting on the model diagram to indicate the analysis
results for individual Model Advisor checks. Blocks that pass a check, fail a
check, or cause a check warning are highlighted in color in the model window.
Model Advisor highlighting is available for the following:
• Simulink blocks
• Stateflow charts
After you run a Model Advisor analysis, checks with highlighted results are
icon in the Model Advisor window.
indicated with an
To use Model Advisor highlighting:
1 Run Model Advisor checks on your model.

4-93

4

Creating a Model

2 Enable Model Advisor highlighting by doing one of the following:

• On the toolbar of the Model Advisor window, select
Highlighting > Model Advisor Highlighting.
• On the toolbar of the Model Advisor window, click the Enable
highlighting button ( ).
• On the toolbar of the Model Advisor Dashboard, click the Highlighting
results button ( ).
3 Optionally, to view model blocks that are excluded from the Model Advisor

checks, select Highlighting > Highlight exclusions on the Model
Advisor window toolbar. If you have a Simulink Verification and Validation
license, you can create or modify exclusions to the Model Advisor checks .
4 In the left pane of the Model Advisor window, select a check with

highlighted results. Checks with highlighted results are indicated with the
icon. Highlighting is not available for all checks.
Both the model window and a Model Advisor Highlighting information
window open. The Model Advisor Highlighting information window
provides a link to the Model Advisor window, where you can review the
check results.
Highlight Colors in the model window

4-94

Yellow with
orange border

Blocks that cause the check failure or warning.

White with
orange border

Subsystem with blocks that cause the check
warning or failure.

White with
gray border

Blocks or subsystems without highlighting.

Consult the Model Advisor

Highlight Colors in the model window
Gray with
black border

Blocks that are excluded from the check.

White with
black border

Subsystems that are excluded from the check.

5 After reviewing the check results in both the model window and the Model

Advisor window, you can choose to fix warnings or failures as described in
“Fix a Warning or Failure” on page 4-95.
6 To view highlighted results for another check, in the left pane of the Model

Advisor window, select a check with an

icon.

Tip If a check warns or fails and the model window highlights all blocks in
gray, closely examine the results in the Model Advisor window. A Model
Advisor check might fail or warn due to your parameter or diagnostic settings.

Fix a Warning or Failure
Checks fail when a model or submodel has a suboptimal condition. A warning
result is informational. You can choose to fix the reported issue, or move on to
the next task. For more information on why a specific check does not pass, see
the check documentation. You can use Model Advisor highlighting to identify
model objects that cause a check warning or failure.
Caution When you fix a warning or failure, rerun all checks to update the
results of all checks. If you do not rerun all checks, the Model Advisor might
report an invalid check result.
To fix warnings and failures:

4-95

4

Creating a Model

• Follow the instructions in the Analysis Result box to manually fix any
warning or failure. See “Manually Fix Warnings or Failures” on page 4-96.
• Use the Action box, when available, to automatically fix all failures. See
“Automatically Fix Warnings or Failures” on page 4-97.
• Use the Model Advisor Results Explorer, when available, to batch-fix
failures. See “Batch-Fix Warnings or Failures” on page 4-98.

Manually Fix Warnings or Failures
All checks have an Analysis Result box that describes the recommended
actions to manually fix warnings or failures.
To manually fix warnings or failures within a task:
1 Optionally, save a model and data restore point so you can undo the

changes that you make. For more information, see “Revert Changes Using
Restore Points” on page 4-99.
2 In the Analysis Result box, review the recommended actions. Use the

information to make changes to your model.

3 Rerun the check to verify that it passes.

4-96

Consult the Model Advisor

Caution When you fix a warning or failure, rerun all checks to update
the results of all checks. If you do not rerun all checks, the Model Advisor
might report an invalid check result.

Automatically Fix Warnings or Failures
Some checks have an Action box where you can automatically fix failures.
The action box applies all of the recommended actions listed in the Analysis
Result box.
Caution Before automatically fixing failures, review the Analysis Result
box to ensure that you want to apply all of the recommended actions. If you
do not want to apply all of the recommended actions, do not use this method
to fix warnings or failures.
To automatically fix all warnings or failures within a check:
1 Optionally, save a model and data restore point so you can undo the

changes that you made by clicking the Modify All button. For more
information, see “Revert Changes Using Restore Points” on page 4-99.
2 In the Action box, click Modify All.

The Action Result box displays a table of changes.
3 Rerun the check to verify that it passes.

Caution When you fix a warning or failure, rerun all checks to update
the results of all checks. If you do not rerun all checks, the Model Advisor
might report an invalid check result.

4-97

4

Creating a Model

Batch-Fix Warnings or Failures
Some checks in the Model Advisor have an Explore Result button that starts
the Model Advisor Result Explorer. The Model Advisor Result Explorer allows
you to quickly locate, view, and change elements of a model.
The Model Advisor Result Explorer helps you to modify only the items that
the Model Advisor is checking.
If a check does not pass and you want to explore the results and make batch
changes:
1 Optionally, save a model and data restore point so you can undo any

changes that you make. For more information, see “Revert Changes Using
Restore Points” on page 4-99.
2 In the Analysis box, click Explore Result.

The Model Advisor Result Explorer window opens.
3 Use the Model Advisor Result Explorer to modify block parameters.
4 In the Model Advisor window, rerun the check to verify that it passes.

Caution When you fix a warning or failure, rerun all checks to update
the results of all checks. If you do not rerun all checks, the Model Advisor
might report an invalid check result.

4-98

Consult the Model Advisor

In the following example, run Check root model Inport block
specifications for the sldemo_mdladv model. The result is a warning.
Clicking the Explore Result button opens the Model Advisor Result Explorer
window.

Revert Changes Using Restore Points
The Model Advisor provides a model and data restore point capability for
reverting changes that you made in response to advice from the Model
Advisor. A restore point is a snapshot in time of the model, base workspace,
and Model Advisor. The Model Advisor maintains restore points for the model
or subsystem of interest through multiple sessions of MATLAB.
Caution A restore point saves only the current working model, base
workspace variables, and Model Advisor tree. It does not save other items,
such as libraries and referenced submodels.

4-99

4

Creating a Model

Save a Restore Point
You can save a restore point and give it a name and optional description, or
allow the Model Advisor to automatically name the restore point for you.
To save a restore point:
1 Go to File > Save Restore Point As.

The Save Model and Data Restore Point dialog box opens.

2 In the Name field, enter a name for the restore point.
3 In the Description field, you can optionally add a description to help you

identify the restore point.
4 Click Save.

The Model Advisor saves a restore point of the current model, base
workspace, and Model Advisor status.
To quickly save a restore point, go to File > Save Restore Point. The Model
Advisor saves a restore point with the name autosaven. n is the sequential
number of the restore point. If you use this method, you cannot change the
name of, or add a description to, the restore point.

Load a Restore Point
To load a restore point:

4-100

Consult the Model Advisor

1 Optionally, save a model and data restore point so you can undo any

changes that you make.
2 Go to File > Load Restore Point.

The Load Model and Data Restore Point dialog box opens.

3 Select the restore point that you want.
4 Click Load.

The Model Advisor issues a warning that the restoration will remove all
changes that you made after saving the restore point.
5 Click Load to load the restore point that you selected.

The Model Advisor reverts the model, base workspace, and Model Advisor
status.

View and Save Model Advisor Reports
When the Model Advisor runs checks, it generates an HTML report of check
results. Each folder in the Model Advisor contains a report for all of the
checks in that folder and the subfolders within that folder.

View Model Advisor Reports
You can access any report by selecting a folder and clicking the link in the
Report box.

4-101

4

Creating a Model

Tip While you can fix warnings and failures through Model Advisor reports,
use the Model Advisor window for interactive fixing of warnings and failures.
Model Advisor reports are best for viewing a summary of checks.
As you run checks, the Model Advisor updates the reports with the latest
information for each check in the folder. When you run the checks at different
times, a message appears in the report. Time stamps indicate when checks
have been run. The time of the current run appears at the top right of
the report. Checks that occurred during previous runs have a time stamp
following the check name.

To show only what you are interested in viewing, you can manipulate the
report.
• To view only the checks with the status that you are interested in, next to
the Run Summary status, select the appropriate check boxes. For example,
you can remove the checks that have not run by clearing the check box
next to the Not Run status.
• Minimize folder results in the report by clicking the minus sign next to the
folder name. When you minimize a folder, the report is updated to display
a run summary for that folder:

4-102

Consult the Model Advisor

Some checks have input parameters specified in the right pane of the Model
Advisor. For example, Check for proper Merge block usage has an input
parameter for Maximum analysis time (seconds). When you run checks
with input parameters, the Model Advisor displays the values of the input
parameters in the HTML report.

For more information, see the EmitInputParametersToReport property of
the Simulink.ModelAdvisor class.

4-103

4

Creating a Model

Save Model Advisor Reports
You can archive a Model Advisor report by saving it to a new location.
1 In the Model Advisor window, navigate to the folder that contains the

report that you want to save.
2 Select the folder that you want. The right pane of the Model Advisor

window displays information about that folder, including a Report box.
3 In the Report box, click Save As. A save as dialog box opens.
4 In the save as dialog box, navigate to the location where you want to save

the report, and click Save. The Model Advisor saves the report to the new
location.
Note If you rerun the Model Advisor, the report is updated in the working
folder, not in the save location.
You can find the full path to the report in the title bar of the
report window. Typically, the report is in the working folder:
slprj/modeladvisor/model_name.

Run the Model Advisor Programmatically
If you have a license for Simulink Verification and Validation, you can create
MATLAB scripts and functions that run the Model Advisor programmatically.
For example, you can create a function to check whether your model passes a
specified set of the Model Advisor checks every time that you open the model,
start a simulation, or, if you have Simulink Coder, generate code from the
model. For more information, see the ModelAdvisor.run function in the
Simulink Verification and Validation documentation.

Check Support for Libraries
There are Model Advisor checks available to verify the syntax of library
models. When you use the Model Advisor to check a library model, the Model
Advisor window indicates (~) checks that do not check libraries. To determine
if you can run the check on library models, you can also refer to the check

4-104

Consult the Model Advisor

documentation, “Capabilities and Limitations”. You cannot use checks that
require model compilation. If you have a license for Simulink Verification
and Validation, you can use an API to create custom checks which support
library models.

Model Advisor Limitations
When you use the Model Advisor to check systems, the following limitations
apply:
• If you rename a system, you must restart the Model Advisor to check that
system.
• In systems that contain a variant subsystem, the Model Advisor checks
only the active subsystem.
• Checks do not search in model blocks or subsystem blocks with the
block parameter Read/Write set to NoReadorWrite. However, on a
check-by-check basis, Model Advisor checks do search in library blocks and
masked subsystems.
For limitations that apply to specific checks, see the Limitations section
within the documentation of each check.

Consult the Upgrade Advisor
Use the Upgrade Advisor to help you upgrade and improve models with the
current release. The Upgrade Advisor can identify cases where you can
benefit by changing your model to use new features and settings in Simulink.
The Advisor provides advice for transitioning to new technologies, and
upgrading a model hierarchy.
The Upgrade Advisor can also help identify cases when a model will not work
because changes and improvements in Simulink require changes to a model.
The Upgrade Advisor offers options to perform recommended actions
automatically or instructions for manual fixes.
You can open the Upgrade Advisor in the following ways:

4-105

4

Creating a Model

1 From the Model Editor, select Analysis > Model Advisor > Upgrade

Advisor
2 From the MATLAB command line, use the upgradeadvisor function:

upgradeadvisor modelname
3 Alternatively, you can open the Upgrade Advisor from the Model Advisor.
a Under By Task checks, expand the folder Upgrading to the Current

Simulink Version and select the check Open the Upgrade Advisor.
b In the right pane under Recommended Action, click the link Open the

Upgrade Advisor . This action closes the Model Advisor and opens the
Upgrade Advisor.
In the Upgrade Advisor, you create reports and run checks in the same way
as when using the Model Advisor.
• Select the top Upgrade Advisor node in the left pane to run all selected
checks and create a report.
• Select each individual check to open a detailed view of the results in the
right pane. View the analysis results for recommended actions to manually
fix warnings or failures. In some cases, the Upgrade Advisor provides
mechanisms for automatically fixing warnings and failures.
Caution When you fix a warning or failure, rerun all checks to update the
results of all checks. If you do not rerun all checks, the Upgrade Advisor
might report an invalid check result.
For more information on individual checks, see
• “Model Upgrades” for upgrade checks only
• “Simulink Checks” for all upgrade and advisor checks
.

4-106

Manage Model Versions

Manage Model Versions
In this section...
“How Simulink Helps You Manage Model Versions” on page 4-107
“Model File Change Notification” on page 4-108
“Specify the Current User” on page 4-110
“Manage Model Properties” on page 4-110
“Log Comments History” on page 4-117
“Version Information Properties” on page 4-119

How Simulink Helps You Manage Model Versions
The Simulink software has these features to help you to manage multiple
versions of a model:
• Use Simulink Projects to manage your project files, connect to source
control, review modified files and compare revisions. See “Simulink
Projects”.
• Model File Change Notification helps you manage work with source control
operations and multiple users. See “Model File Change Notification” on
page 4-108.
• As you edit a model, the Simulink software generates version information
about the model, including a version number, who created and last updated
the model, and an optional comments history log. The Simulink software
automatically saves these version properties with the model.

-

Use the Model Properties dialog box to view and edit some of the version
information stored in the model and specify history logging.

-

The Model Info block lets you display version information as an
annotation block in a model diagram.

-

You can access Simulink version parameters from the MATLAB
command line or a MATLAB script.

• See Simulink.MDLInfo to extract information from a model file without
loading the block diagram into memory. You can use MDLInfo to query

4-107

4

Creating a Model

model version and Simulink version, find the names of referenced models
without loading the model into memory, and attach arbitrary metadata to
your model file.

Model File Change Notification
You can use the Simulink Preferences window to specify whether to notify if
the model has changed on disk when updating, simulating, editing, or saving
the model. This can occur, for example, with source control operations and
multiple users.
Note To programmatically check whether the model has changed on disk
since it was loaded, use the function slIsFileChangedOnDisk.
To access the Simulink Preferences window, use one of these approaches:
• In the Simulink Model Browser, select File > Simulink Preferences.
• From the MATLAB Toolstrip, in the Home tab, in the Environment
section, select Preferences. Click the Launch Simulink Preferences
button .

The Model File Change Notification options are in the right pane. You can
use the three independent options as follows:

4-108

Manage Model Versions

• If you select the Updating or simulating the model check box, you can
choose what form of notification you want from the Action list:

-

Warning — in the MATLAB command window.

-

Reload model (if unmodified) — if the model is modified, you see the
prompt dialog. If unmodified, the model is reloaded.

-

Show prompt dialog — in the dialog, you can choose to close and reload,
or ignore the changes.

Error — in the MATLAB command window if simulating from the

command line, or if simulating from a menu item, in the Simulation
Diagnostics window.

• If you select the First editing the model check box, and the file has
changed on disk, and the block diagram is unmodified in Simulink:

-

Any command-line operation that causes the block diagram to be
modified (e.g., a call to set_param) will result in a warning:
Warning: Block diagram 'mymodel' is being edited but file has
changed on disk since it was loaded. You should close and
reload the block diagram.

-

Any graphical operation that modifies the block diagram (e.g., adding a
block) causes a warning dialog to appear.

• If you select the Saving the model check box, and the file has changed
on disk:

-

The save_system function displays an error, unless the
OverwriteIfChangedOnDisk option is used.

-

Saving the model by using the menu (File > Save) or a keyboard
shortcut causes a dialog to be shown. In the dialog, you can choose to
overwrite, save with a new name, or cancel the operation.

For more options to help you work with source control and multiple users, see
“Simulink Projects”.

4-109

4

Creating a Model

Specify the Current User
When you create or update a model, your name is logged in the model for
version control purposes. The Simulink software assumes that your name
is specified by at least one of the following environment variables: USER,
USERNAME, LOGIN, or LOGNAME. If your system does not define any of these
variables, the Simulink software does not update the user name in the model.
UNIX systems define the USER environment variable and set its value to the
name you use to log on to your system. Thus, if you are using a UNIX system,
you do not have to do anything to enable the Simulink software to identify
you as the current user.
Windows systems, on the other hand, might define some or none of the
“user name” environment variables that the Simulink software expects,
depending on the version of Windows installed on your system and whether it
is connected to a network. Use the MATLAB command getenv to determine
which of the environment variables is defined. For example, enter
getenv('user')

at the MATLAB command line to determine whether the USER environment
variable exists on your Windows system. If not, you must set it yourself.
On Windows, set the USER environment variable (if it is not already defined).

Manage Model Properties
You can use the Model Properties dialog box to view and edit model
information (including some version parameters), callback functions, history,
and the model description. To open the dialog box,
• In a model, select File > Model Properties.
• In a library, select File > Library Properties.
Library Properties includes an additional tab, Forwarding Table,
for specifying the mapping from old library blocks to new library
blocks. For information on using the Fowarding Table, see “Make
Backward-Compatible Changes to Libraries” on page 28-22.

4-110

Manage Model Versions

Model Properties and Library Properties both include the tabs Main Model
Information, Callbacks, History and Description. The controls in the shared
tabs are described next on this page.

The dialog box includes the following panes.

Viewing Model Information
The Main pane summarizes information about the current version of this
model, such as whether the model is modified, the Model Version, and Last
Saved date. You can edit some of this information in the History tab, see
“Viewing and Editing Model Information and History” on page 4-112.

Specifying Callbacks
Use the Callbacks pane to specify functions to be invoked at specific points
in the simulation of the model.

4-111

4

Creating a Model

In the left pane, select the callback. In the right pane, enter the name of the
function you want to be invoked for the selected callback. See “Create Model
Callback Functions” on page 4-55 for information on the callback functions
listed on this pane.

Viewing and Editing Model Information and History
Use the History pane to view and edit model information, and to enable,
view, and edit this model’s change history in the lower Model history field.
To use the history controls see “Log Comments History” on page 4-117.

4-112

Manage Model Versions

Viewing Model Information. When the Read Only check box is selected,
you can view but not edit the following grayed out fields.
• Created by
Name of the person who created this model. The Simulink software sets
this property to the value of the USER environment variable when you
create the model.
• Created on
Date and time this model was created.
• Last saved by
Name of the person who last saved this model. The Simulink software sets
the value of this parameter to the value of the USER environment variable
when you save a model.

4-113

4

Creating a Model

• Last saved on
Date that this model was last saved. The Simulink software sets the value
of this parameter to the system date and time whenever you save a model.
• Model version
Version number for this model.
Editing Model Information. Clear the Read Only check box to edit model
information. When the check box is deselected, the dialog box shows the
format strings or values for the following fields. You can edit all but the
Created on field, as described.

4-114

Manage Model Versions

• Created by
Name of the person who created this model. The Simulink software sets
this property to the value of the USER environment variable when you
create the model. Edit this field to change the value.
• Created on

4-115

4

Creating a Model

Date and time this model was created. Do not edit this field.
• Last saved by
Enter a format string describing the format used to display the Last saved
by value in the History pane and the ModifiedBy entry in the history log
and Model Info blocks. The value of this field can be any string. The string
can include the tag %. Simulink replaces occurrences of this tag with
the current value of the USER environment variable.
• Last saved on
Enter a format string describing the format used to display the Last saved
on date in the History pane and the ModifiedOn entry in the history log
and the in Model Info blocks. The value of this field can be any string.
The string can contain the tag %. The Simulink software replaces
occurrences of this tag with the current date and time.
• Model version
Enter a format string describing the format used to display the model
version number in the Model Properties pane and in Model Info blocks.
The value of this parameter can be any text string. The text string can
include occurrences of the tag % where # is an integer.
Simulink replaces the tag with an integer when displaying the model’s
version number. For example, it displays the tag
1.%

as
1.2

Simulink increments # by 1 when saving the model. For example, when
you save the model,
1.%

becomes
1.%

and the model version number is reported as 1.3.

4-116

Manage Model Versions

Viewing and Editing the Model Description
Use the Description pane to enter a description of the model. You can view
the model description by typing help followed by the model name at the
MATLAB prompt. The contents of the Model description field appear in
the Command Window.

Log Comments History
You can create and store a record of changes to a model in the model itself.
The Simulink software compiles the history automatically from comments
that you or other users enter when they save changes to a model. For more
flexibility adding labels and comments to models and submissions, see instead
“Simulink Projects”.

4-117

4

Creating a Model

Logging Changes
To start a change history,
1 Select File > Model Properties.
2 In the Model Properties dialog box, select the History tab.
3 Select When saving model from the Prompt to update model history

list.
This causes Simulink to prompt you to enter a comment when saving the
model.
The next time you save the model, the Log Change dialog box prompts you
to enter a comment.

For example you could describe changes that you have made to the model
since the last time you saved it. To add an item to the model’s change history,

4-118

Manage Model Versions

enter the item in the Modified Comments edit field and click Save. The
information is stored in the model’s change history log.
If you do not want to enter an item for this session, clear the Include
"Modified Comments" in "Modified History" option.
To discontinue change logging, either:
• In the Log Change dialog box, clear the check box Show this dialog box
next time when save.
• In the Model Properties dialog box History pane, select Never from the
Prompt to update model history list.

Viewing and Editing the Model History Log
In the Model Properties dialog box you can view and edit the model history on
the History tab.
The model history text field displays the history for the model in a scrollable
text field. To change the model history, edit the contents of this field.

Version Information Properties
Some version information is stored as model parameters in a model. You can
access this information from the MATLAB command line or from a MATLAB
script, using the Simulink get_param command.
The following table describes the model parameters used by Simulink to store
version information.
Property

Description

Created

Date created.

Creator

Name of the person who created this
model.

4-119

4

Creating a Model

Property

Description

Description

User-entered description of this model.
Enter or edit a description on the
Description tab of the Model Properties
dialog box. You can view the model
description by typing
help 'mymodelname'

at the MATLAB command line.

4-120

LastModifiedBy

Name of the user who last saved the model.

LastModifiedDate

Date when the model was last saved.

ModifiedBy

Current value of the user name of the
person who last modified this model.
When you save, this information is saved
with the file as LastModifiedBy.

ModifiedByFormat

Format of the ModifiedBy parameter.
Value can be any string. The string can
include the tag %. The Simulink
software replaces the tag with the current
value of the USER environment variable.

ModifiedDateFormat

Format of the ModifiedDate parameter.
Value can be any string. The string
can include the tag %. Simulink
replaces the tag with the current date and
time when saving the model.

ModifiedComment

Comment entered by user who last
updated this model.

ModifiedHistory

History of changes to this model.

Manage Model Versions

Property

Description

ModelVersion

Version number.

ModelVersionFormat

Format of model version number. Can be
any string. The string can contain the
tag % where # is an
integer. Simulink replaces the tag with #
when displaying the version number. It
increments # when saving the model.

LibraryVersion is a block parameter for a linked block. LibraryVersion is
the ModelVersion of the library at the time the link was created.

For source control version information, see instead “Simulink Projects”.

4-121

4

Creating a Model

Model Discretizer
In this section...
“What Is the Model Discretizer?” on page 4-122
“Requirements” on page 4-122
“Discretize a Model from the Model Discretizer GUI” on page 4-122
“View the Discretized Model” on page 4-132
“Discretize Blocks from the Simulink Model” on page 4-135
“Discretize a Model from the MATLAB Command Window” on page 4-146

What Is the Model Discretizer?
Model Discretizer selectively replaces continuous Simulink blocks with
discrete equivalents. Discretization is a critical step in digital controller
design and for hardware in-the-loop simulations.
You can use the Model Discretizer to:
• Identify a model’s continuous blocks
• Change a block’s parameters from continuous to discrete
• Apply discretization settings to all continuous blocks in the model or
selected blocks
• Create configurable subsystems that contain multiple discretization
candidates along with the original continuous block(s)
• Switch among the different discretization candidates and evaluate the
resulting model simulations

Requirements
To use Model Discretizer, you must have a Control System Toolbox™ license,
Version 5.2 or later.

Discretize a Model from the Model Discretizer GUI
To discretize a model:

4-122

Model Discretizer

• Start the Model Discretizer
• Specify the Transform Method
• Specify the Sample Time
• Specify the Discretization Method
• Discretize the Blocks

4-123

4

Creating a Model

The f14 model shows the steps in discretizing a model.

4-124

Model Discretizer

Start Model Discretizer
To open the tool, in the Simulink Editor, select Analysis > Control
Design > Model Discretizer.
The Simulink Model Discretizer opens.

Alternatively, you can open Model Discretizer from the MATLAB Command
Window using the slmdldiscui function.
The following command opens the Simulink Model Discretizer window
with the f14 model:
slmdldiscui('f14')

To open a new model or library from Model Discretizer, select File > Load
model.

4-125

4

Creating a Model

Specify the Transform Method
The transform method specifies the type of algorithms used in the
discretization. For more information on the different transform methods, see
the Control System Toolbox documentation.
The Transform method drop-down list contains the following options:
• zero-order hold
Zero-order hold on the inputs.
• first-order hold
Linear interpolation of inputs.
• tustin
Bilinear (Tustin) approximation.
• tustin with prewarping
Tustin approximation with frequency prewarping.
• matched pole-zero
Matched pole-zero method (for SISO systems only).

Specify the Sample Time
Enter the sample time in the Sample time field.
You can specify an offset time by entering a two-element vector for discrete
blocks or configurable subsystems. The first element is the sample time and
the second element is the offset time. For example, an entry of [1.0 0.1]
would specify a 1.0 second sample time with a 0.1 second offset. If no offset is
specified, the default is zero.
You can enter workspace variables when discretizing blocks in the s-domain.
See “Discrete blocks (Enter parameters in s-domain)” on page 4-127.

Specify the Discretization Method
Specify the discretization method in the Replace current selection with
field. The options are

4-126

Model Discretizer

• “Discrete blocks (Enter parameters in s-domain)” on page 4-127
Creates a discrete block whose parameters are retained from the
corresponding continuous block.
• “Discrete blocks (Enter parameters in z-domain)” on page 4-128
Creates a discrete block whose parameters are “hard-coded“ values placed
directly into the block’s dialog.
• “Configurable subsystem (Enter parameters in s-domain)” on page 4-129
Create multiple discretization candidates using s-domain values for the
current selection. A configurable subsystem can consist of one or more
blocks.
• “Configurable subsystem (Enter parameters in z-domain)” on page 4-130
Create multiple discretization candidates in z-domain for the current
selection. A configurable subsystem can consist of one or more blocks.
Discrete blocks (Enter parameters in s-domain). Creates a discrete block
whose parameters are retained from the corresponding continuous block.
The sample time and the discretization parameters are also on the block’s
parameter dialog box.
The block is implemented as a masked discrete block that uses c2d to
transform the continuous parameters to discrete parameters in the mask
initialization code.
These blocks have the unique capability of reverting to continuous behavior if
the sample time is changed to zero. Entering the sample time as a workspace
variable ('Ts', for example) allows for easy changeover from continuous to
discrete and back again. See “Specify the Sample Time” on page 4-126.
Note Parameters are not tunable when Inline parameters is selected in
the model’s Configuration Parameters dialog box.

4-127

4

Creating a Model

The following figure shows a continuous Transfer Function block next to a
Transfer Function block that has been discretized in the s-domain. The Block
Parameters dialog box for each block appears below the block.

Discrete blocks (Enter parameters in z-domain). Creates a discrete block
whose parameters are “hard-coded” values placed directly into the block’s
dialog box. Model Discretizer uses the c2d function to obtain the discretized
parameters, if needed.
For more help on the c2d function, type the following in the Command
Window:
help c2d

4-128

Model Discretizer

The following figure shows a continuous Transfer Function block next to a
Transfer Function block that has been discretized in the z-domain. The Block
Parameters dialog box for each block appears below the block.

Note If you want to recover exactly the original continuous parameter values
after the Model Discretization session, you should enter parameters in the
s-domain.
Configurable subsystem (Enter parameters in s-domain). Create
multiple discretization candidates using s-domain values for the current
selection. A configurable subsystem can consist of one or more blocks.
The Location for block in configurable subsystem field becomes active
when this option is selected. This option allows you to either create a new
configurable subsystem or overwrite an existing one.
Note The current folder must be writable in order to save the library or
libraries for the configurable subsystem option.

4-129

4

Creating a Model

Configurable subsystem (Enter parameters in z-domain). Create
multiple discretization candidates in z-domain for the current selection. A
configurable subsystem can consist of one or more blocks.
The Location for block in configurable subsystem field becomes active
when this option is selected. This option allows you to either create a new
configurable subsystem or overwrite an existing one.
Note The current folder must be writable in order to save the library or
libraries for the configurable subsystem option.
Configurable subsystems are stored in a library containing the discretization
candidates and the original continuous block. The library will be named
_disc_lib and it will be stored in the current . For example
a library containing a configurable subsystem created from the f14 model
will be named f14_disc_lib.
If multiple libraries are created from the same model, then the filenames
will increment accordingly. For example, the second configurable subsystem
library created from the f14 model will be named f14_disc_lib2.
You can open a configurable subsystem library by right-clicking on the
subsystem in the model and selecting Link options > Go to library block
from the pop-up menu.

Discretize the Blocks
To discretize blocks that are linked to a library, you must either discretize the
blocks in the library itself or disable the library links in the model window.
You can open the library from Model Discretizer by selecting Load model
from the File menu.
You can disable the library links by right-clicking on the block and selecting
Link options -> Disable link from the pop-up menu.
There are two methods for discretizing blocks.

4-130

Model Discretizer

Select Blocks and Discretize.
1 Select a block or blocks in the Model Discretizer tree view pane.

To choose multiple blocks, press and hold the Ctrl button on the keyboard
while selecting the blocks.
Note You must select blocks from the Model Discretizer tree view. Clicking
blocks in the editor does not select them for discretization.
2 Select Discretize current block from the Discretize menu if a single

block is selected or select Discretize selected blocks from the Discretize
menu if multiple blocks are selected.
You can also discretize the current block by clicking the Discretize button,
shown below.

Store the Discretization Settings and Apply Them to Selected Blocks
in the Model.
1 Enter the discretization settings for the current block.
2 Click Store Settings.

This adds the current block with its discretization settings to the group
of preset blocks.
3 Repeat steps 1 and 2, as necessary.
4 Select Discretize preset blocks from the Discretize menu.

4-131

4

Creating a Model

Deleting a Discretization Candidate from a Configurable
Subsystem
You can delete a discretization candidate from a configurable subsystem by
selecting it in the Location for block in configurable subsystem field and
clicking the Delete button, shown below.

Undoing a Discretization
To undo a discretization, click the Undo discretization button, shown below.

Alternatively, you can select Undo discretization from the Discretize
menu.
This operation undoes discretizations in the current selection and its children.
For example, performing the undo operation on a subsystem will remove
discretization from all blocks in all levels of the subsystem’s hierarchy.

View the Discretized Model
Model Discretizer displays the model in a hierarchical tree view.

Viewing Discretized Blocks
The block’s icon in the tree view becomes highlighted with a “z” when the
block has been discretized.

4-132

Model Discretizer

The following figure shows that the Aircraft Dynamics Model subsystem has
been discretized into a configurable subsystem with three discretization
candidates.

The other blocks in this f14 model have not been discretized.

4-133

4

Creating a Model

The following figure shows the Aircraft Dynamics Model subsystem of the f14
example model after discretization into a configurable subsystem containing
the original continuous model and three discretization candidates.

4-134

Model Discretizer

The following figure shows the library containing the Aircraft Dynamics
Model configurable subsystem with the original continuous model and three
discretization candidates.

Refreshing Model Discretizer View of the Model
To refresh Model Discretizer’s tree view of the model when the model has been
changed, click the Refresh button, shown below.

Alternatively, you can select Refresh from the View menu.

Discretize Blocks from the Simulink Model
You can replace continuous blocks in a Simulink software model with the
equivalent blocks discretized in the s-domain using the Discretizing library.
The procedure below shows how to replace a continuous Transfer Fcn block in
the Aircraft Dynamics Model subsystem of the f14 model with a discretized
Transfer Fcn block from the Discretizing Library. The block is discretized

4-135

4

Creating a Model

in the s-domain with a zero-order hold transform method and a two second
sample time.
1 Open the f14 model.
2 Open the Aircraft Dynamics Model subsystem in the f14 model.

3 Open the Discretizing library window.

Enter discretizing at the MATLAB command prompt.

4-136

Model Discretizer

The Library: discretizing window opens.

This library contains s-domain discretized blocks.
4 Add the Discretized Transfer Fcn (with initial states) block to the

f14/Aircraft Dynamics Model window.

4-137

4

Creating a Model

a Click the Discretized Transfer Fcn block in the Library: discretizing

window.
b Drag it into the f14/Aircraft Dynamics Model window.

5 Open the parameter dialog box for the Transfer Fcn.1 block.

4-138

Model Discretizer

Double-click the Transfer Fcn.1 block in the f14/Aircraft Dynamics
Model window.
The Block Parameters: Transfer Fcn.1 dialog box opens.

6 Open the parameter dialog box for the Discretized Transfer Fcn block.

Double-click the Discretized Transfer Fcn block in the f14/Aircraft
Dynamics Model window.

4-139

4

Creating a Model

The Block Parameters: Discretized Transfer Fcn dialog box opens.

4-140

Model Discretizer

Copy the parameter information from the Transfer Fcn.1 block’s dialog box
to the Discretized Transfer Fcn block’s dialog box.

7 Enter 2 in the Sample time field.
8 Select zoh from the Method drop-down list.

4-141

4

Creating a Model

The parameter dialog box for the Discretized Transfer Fcn now looks like
this.

9 Click OK.

4-142

Model Discretizer

The f14/Aircraft Dynamics Model window now looks like this.

10 Delete the original Transfer Fcn.1 block.
a Click the Transfer Fcn.1 block.
b Press the Delete key.

4-143

4

Creating a Model

The f14/Aircraft Dynamics Model window now looks like this.

11 Add the Discretized Transfer Fcn block to the model.
a Click the Discretized Transfer Fcn block.
b Drag the Discretized Transfer Fcn block into position to complete the

model.

4-144

Model Discretizer

The f14/Aircraft Dynamics Model window now looks like this.

4-145

4

Creating a Model

Discretize a Model from the MATLAB Command
Window
Use the sldiscmdl function to discretize Simulink software models from the
MATLAB Command Window. You can specify the transform method, the
sample time, and the discretization method with the sldiscmdl function.
For example, the following command discretizes the f14 model in the s-domain
with a 1-second sample time using a zero-order hold transform method:
sldiscmdl('f14',1.0,'zoh')

4-146

5
Working with Sample Times
• “What Is Sample Time?” on page 5-2
• “Specify Sample Time” on page 5-3
• “View Sample Time Information” on page 5-9
• “Print Sample Time Information” on page 5-13
• “Types of Sample Time” on page 5-14
• “Block Compiled Sample Time ” on page 5-20
• “Sample Times in Subsystems” on page 5-21
• “Sample Times in Systems” on page 5-22
• “Resolve Rate Transitions” on page 5-28
• “How Propagation Affects Inherited Sample Times” on page 5-29
• “Monitor Backpropagation in Sample Times” on page 5-31

5

Working with Sample Times

What Is Sample Time?
The sample time of a block is a parameter that indicates when, during
simulation, the block produces outputs and if appropriate, updates its internal
state. The internal state includes but is not limited to continuous and discrete
states that are logged.
Note Do not confuse the Simulink usage of the term sample time with the
engineering sense of the term. In engineering, sample time refers to the rate
at which a discrete system samples its inputs. Simulink allows you to model
single-rate and multirate discrete systems and hybrid continuous-discrete
systems through the appropriate setting of block sample times that control
the rate of block execution (calculations).
For many engineering applications, you need to control the rate of block
execution. In general, Simulink provides this capability by allowing you
to specify an explicit SampleTime parameter in the block dialog or at the
command line. Blocks that do not have a SampleTime parameter have an
implicit sample time. You cannot specify implicit sample times. Simulink
determines them based upon the context of the block in the system. The
Integrator block is an example of a block that has an implicit sample time.
Simulink automatically sets its sample time to 0.
Sample times can be port-based or block-based. For block-based sample times,
all of the inputs and outputs of the block run at the same rate. For port-based
sample times, the input and output ports can run at different rates.
Sample times can also be discrete, continuous, fixed in minor step, inherited,
constant, variable, triggered, or asynchronous. The following sections discuss
these sample time types, as well as sample time propagation and rate
transitions between block-based or port-based sample times. You can use
this information to control your block execution rates, debug your model,
and verify your model.

5-2

Specify Sample Time

Specify Sample Time
In this section...
“Designate Sample Times” on page 5-3
“Specify Block-Based Sample Times Interactively” on page 5-6
“Specify Port-Based Sample Times Interactively” on page 5-6
“Specify Block-Based Sample Times Programmatically” on page 5-7
“Specify Port-Based Sample Times Programmatically” on page 5-8
“Access Sample Time Information Programmatically” on page 5-8
“Specify Sample Times for a Custom Block” on page 5-8
“Determining Sample Time Units” on page 5-8
“Change the Sample Time After Simulation Start Time” on page 5-8

Designate Sample Times
Simulink allows you to specify a block sample time directly as a numerical
value or symbolically by defining a sample time vector. In the case of a
discrete sample time, the vector is [Ts, To] where Ts is the sampling period
and To is the initial time offset. For example, consider a discrete model that
produces its outputs every two seconds. If your base time unit is seconds, you
can directly set the discrete sample time by specifying the numerical value of
2 as the SampleTime parameter. Because the offset value is zero, you do not
need to specify it; however, you can enter [2,0] in the Sample time field.
For nondiscrete blocks, the components of the vector are symbolic values
that represent one of the types in “Types of Sample Time” on page 5-14. The
following table summarizes these types and the corresponding sample time
values. The table also defines the explicit nature of each sample time type
and designates the associated color and annotation. Because an inherited
sample time is explicit, you can specify it as [-1, 0] or as -1. Whereas, a
triggered sample time is implicit; only Simulink can assign the sample time
of [-1, -1]. (For more information about colors and annotations, see “View
Sample Time Information” on page 5-9.)

5-3

5

Working with Sample Times

Designations of Sample Time Information
Sample Time
Type

Sample
Time

Color

Annotation

Explicit

Discrete

[Ts, To]

In descending
order of
speed: red,
green, blue,
light blue,
dark green,
orange

D1, D2, D3, D4,
D5, D6, D7,...
Di

Yes

Continuous

[0, 0]

black

Cont

Yes

Fixed in minor
step

[0, 1]

gray

FiM

Yes

Inherited

[–1, 0]

N/A

N/A

Yes

Constant

[Inf, 0]

magenta

Inf

Yes

Variable

[–2,Tvo]

brown

V1, V2,... Vi

No

Hybrid

N/A

yellow

N/A

No

Triggered

[–1, –1]

cyan

T

No

Asynchronous

[–1, –n]

purple

A1, A2,... Ai

No

The color that is assigned to each block depends on its sample time relative
to other sample times in the model. This means that the same sample time
may be assigned different colors in a parent model and in models that it
references. (See “Model Reference”.)
For example, suppose that a model defines three sample times: 1, 2, and 3.
Further, suppose that it references a model that defines two sample times: 2
and 3. In this case, blocks operating at the 2 sample rate appear as green in
the parent model and as red in the referenced model.
It is important to note that Mux and Demux blocks are simply grouping
operators; signals passing through them retain their timing information. For
this reason, the lines emanating from a Demux block can have different colors
if they are driven by sources having different sample times. In this case, the

5-4

Specify Sample Time

Mux and Demux blocks are color coded as hybrids (yellow) to indicate that
they handle signals with multiple rates.
Similarly, Subsystem blocks that contain blocks with differing sample times
are also colored as hybrids, because there is no single rate associated with
them. If all the blocks within a subsystem run at a single rate, the Subsystem
block is colored according to that rate.
You can use the explicit sample time values in this table to specify sample
times interactively or programmatically for either block-based or port-based
sample times.
The following model, ex_specify_sample_time, serves as a reference for
this section.

ex_specify_sample_time

In this example, set the sample time of the input sine wave signal to 0.1. The
goal is to achieve an output sample time of 0.2. The Rate Transition block
serves as a zero-order hold. The resulting block diagram after setting the
sample times and simulating the model is shown in the following figure. (The
colors and annotations indicate that this is a discrete model.)

Sample Time 0.1

Sample Time 0.2

ex_specify_sample_time after Setting Sample Times

5-5

5

Working with Sample Times

Specify Block-Based Sample Times Interactively
To set the sample time of a block interactively:
1 In the Simulink model window, double-click the block. The block parameter

dialog box opens.
2 Enter the sample time in the Sample time field.
3 Click OK.

Following is a figure of a parameters dialog box for the Sine Wave block after
entering 0.1 in the Sample time field.

Enter the sample time
value in this field

Specify Port-Based Sample Times Interactively
The Rate Transition block has port-based sample times. You can set the
output port sample time interactively by completing the following steps:

5-6

Specify Sample Time

1 Double-click the Rate Transition block. The parameters dialog box opens.
2 Leave the drop-down menu choice of the Output port sample time

options as Specify.
3 Replace the -1 in the Output port sample time field with 0.2.

Enter sample time
in Output port
sample time field

4 Click OK.

For more information about the sample time options in the Rate Transition
parameters dialog box, see the Rate Transition reference page.

Specify Block-Based Sample Times Programmatically
To set a block sample time programmatically, set its SampleTime parameter
to the desired sample time using the set_param command. For example, to
set the sample time of the Gain block in the “Specify_Sample_Time” model to
inherited (-1), enter the following command:
set_param('Specify_Sample_Time/Gain','SampleTime','[-1, 0]')

As with interactive specification, you can enter just the first vector component
if the second component is zero.
set_param('Specify_Sample_Time/Gain','SampleTime','-1')

5-7

5

Working with Sample Times

Specify Port-Based Sample Times Programmatically
To set the output port sample time of the Rate Transition block to 0.2, use
the set_param command with the parameter OutPortSampleTime:
set_param('Specify_Sample_Time/Rate Transition',...
'OutPortSampleTime', '0.2')

Access Sample Time Information Programmatically
To access all sample times associated with a model, use the API
Simulink.BlockDiagram.getSampleTimes.
To access the sample time of a single block, use the API
Simulink.Block.getSampleTimes.

Specify Sample Times for a Custom Block
You can design custom blocks so that the input and output ports operate at
different sample time rates. For information on specifying block-based and
port-based sample times for S-functions, see “Sample Times” .

Determining Sample Time Units
Since the execution of a Simulink model is not dependent on a specific set of
units, you must determine the appropriate base time unit for your application
and set the sample time values accordingly. For example, if your base time
unit is second, then you would represent a sample time of 0.5 second by
setting the sample time to 0.5.

Change the Sample Time After Simulation Start Time
To change a sample time after simulation begins, you must stop the
simulation, reset the SampleTime parameter, and then restart execution.

5-8

View Sample Time Information

View Sample Time Information
In this section...
“View Sample Time Display” on page 5-9
“Sample Time Legend” on page 5-10

View Sample Time Display
Simulink models can display color coding and annotations that represent
specific sample times. As shown in the table Designations of Sample Time
Information on page 5-4, each sample time type has one or more colors
associated with it. You can display the blocks and signal lines in color, the
annotations in black, or both the colors and the annotations. To choose one
of these options:
1 In the Simulink model window, select Display > Sample Time.
2 Select Colors, Annotations, or All.

Selecting All results in the display of both the colors and the annotations.
Regardless of your choice, Simulink performs an Update Diagram
automatically. To turn off the colors and annotations:
1 Select Display > Sample Time.
2 Select Off.

Simulink performs another Update Diagram automatically.

5-9

5

Working with Sample Times

Your Sample Time Display choices directly control the information that the
Sample Time Legend displays.
Note The discrete sample times in the table Designations of Sample Time
Information on page 5-4 represent a special case. Five colors indicate the
fastest through the fifth fastest discrete rate. A sixth color, orange, represents
all rates that are slower than the fifth discrete rate. You can distinguish
between these slower rates by looking at the annotations on their respective
signal lines.

Sample Time Legend
You can view the Sample Time Legend for an individual model or for multiple
models. Additionally, you can prevent the legend from automatically opening
when you select options on the Sample Time menu.

Viewing the Legend
To assist you with interpreting your block diagram, a Sample Time Legend
is available that contains the sample time color, annotation, description, and
value for each sample time in the model. You can use one of three methods
to view the legend, but upon first opening the model, you must first perform
an Update Diagram.

5-10

View Sample Time Information

1 In the Simulink model window, select Simulation > Update Diagram.
2 Select Display > Sample Time > Sample Time Legend or press Ctrl +J.

In addition, whenever you select Colors, Annotations, or All from the
Sample Time menu, Simulink updates the model diagram and opens
the legend by default. The legend contents reflect your Sample Time
Display choices. By default or if you have selected Off, the legend contains
a description of the sample time and the sample time value. If you turn
colors on, the legend displays the appropriate color beside each description.
Similarly, if you turn annotations on, the annotations appear in the legend.
The legend does not provide a discrete rate for all types of sample times. For
asynchronous and variable sample times, the legend displays a link to the
block that controls the sample time in place of the sample time value. Clicking
one of these links highlights the corresponding block in the block diagram. The
rate listed under hybrid and asynchronous hybrid models is “Not Applicable”
because these blocks do not have a single representative sample time.
Note The Sample Time Legend displays all of the sample times in the model,
including those that are not associated with any block. For example, if the
fixed step size is 0.1 and all of the blocks have a sample time of 0.2, then both
rates (i.e., 0.1 and 0.2) appear in the legend.
For subsequent viewings of the legend, repeat the Update Diagram to access
the latest known information.

Turning the Legend Off
If you do not want to view the legend upon selecting Sample Time Display:
1 In the Simulink model window, select File > Simulink Preferences.
2 Scroll to the bottom of the main Preferences pane.
3 Clear Open the sample time legend whenever the sample time

display is changed.

5-11

5

Working with Sample Times

Viewing Multiple Legends
If you have more than one model open and you view the Sample Time
Legend for each one, a single legend window appears with multiple
tabs. Each tab contains the name of the model and the respective legend
information. The following figure shows the tabbed legends for the f14 and
vdp models.

5-12

Print Sample Time Information

Print Sample Time Information
You can print the sample time information in the Sample Time Legend by
using either of these methods:
• In the Sample Time Legend window, click Print.
• Print the legend from the Print Model dialog box:
1 In the model window, select File > Print.
2 Under Options, select the check box beside Print Sample Time

Legend.
3 Click OK.

5-13

5

Working with Sample Times

Types of Sample Time
In this section...
“Discrete Sample Time” on page 5-14
“Continuous Sample Time” on page 5-15
“Fixed in Minor Step” on page 5-15
“Inherited Sample Time” on page 5-15
“Constant Sample Time” on page 5-16
“Variable Sample Time” on page 5-17
“Triggered Sample Time” on page 5-18
“Asynchronous Sample Time” on page 5-18

Discrete Sample Time
Given a block with a discrete sample time, Simulink executes the block output
or update method at times

tn = nTs + To
where the sample time period Ts is always greater than zero and less than
the simulation time, Tsim . The number of periods ( n ) is an integer that
must satisfy:

0≤n≤

Tsim
Ts

As simulation progresses, Simulink computes block outputs only once at each
of these fixed time intervals of tn . These simulation times, at which Simulink
executes the output method of a block for a given sample time, are referred
to as sample time hits. Discrete sample times are the only type for which
sample time hits are known a priori.
If you need to delay the initial sample hit time, you can define an offset, To .
The Unit Delay block is an example of a block with a discrete sample time.

5-14

Types of Sample Time

Continuous Sample Time
Unlike the discrete sample time, continuous sample hit times are divided into
major time steps and minor time steps, where the minor steps represent
subdivisions of the major steps (see “Minor Time Steps” on page 3-23). The
ODE solver you choose integrates all continuous states from the simulation
start time to a given major or minor time step. The solver determines the
times of the minor steps and uses the results at the minor time steps to
improve the accuracy of the results at the major time steps. However, you
see the block output only at the major time steps.
To specify that a block, such as the Derivative block, is continuous, enter [0,
0] or 0 in the Sample time field of the block dialog.

Fixed in Minor Step
If the sample time of a block is set to [0, 1], the block becomes fixed in minor
step. For this setting, Simulink does not execute the block at the minor time
steps; updates occur only at the major time steps. This process eliminates
unnecessary computations of blocks whose output cannot change between
major steps.
While you can explicitly set a block to be fixed in minor step, more typically
Simulink sets this condition as either an inherited sample time or as an
alteration to a user specification of 0 (continuous). This setting is equivalent
to, and therefore converted to, the fastest discrete rate when you use a
fixed-step solver.

Inherited Sample Time
If a block sample time is set to [–1, 0] or –1, the sample time is inherited and
Simulink determines the best sample time for the block based on the block
context within the model. Simulink performs this task during the compilation
stage; the original inherited setting never appears in a compiled model.
Therefore, you never see inherited ([–1, 0]) in the Sample Time Legend. (See
“View Sample Time Information” on page 5-9.)
Examples of inherited blocks include the Gain and Add blocks.
All inherited blocks are subject to the process of sample time propagation, as
discussed in “How Propagation Affects Inherited Sample Times” on page 5-29

5-15

5

Working with Sample Times

Constant Sample Time
Specifying a constant (Inf) sample time is a request for an optimization for
which the block executes only once during model initialization. Simulink
honors such requests if all of the following conditions hold:
• The Inline parameters check box is selected on the Configuration
Parameters dialog box Optimization > Signal and Parameters pane
(see the “Optimization Pane: Signals and Parameters”).
• The block has no continuous or discrete states.
• The block allows for a constant sample time.
• The block does not drive an output port of a conditionally executed
subsystem (see “Enabled Subsystems” on page 7-4).
• The block has no tunable parameters.
One exception is an empty subsystem. A subsystem that has no blocks—not
even an input or output block—always has a constant sample time regardless
of the status of the conditions listed above.
This optimization process speeds up the simulation by eliminating the need to
recompute the block output at each step. Instead, during each model update,
Simulink first establishes the constant sample time of the block and then
computes the initial values of its output ports. Simulink then uses these
values, without performing any additional computations, whenever it needs
the outputs of the block.
Note The Simulink block library includes several blocks, such as the
MATLAB S-Function block, the Level-2 MATLAB S-Function block, and the
Model block, whose ports can produce outputs at different sample rates. It is
possible for some of the ports of such blocks to have a constant sample time.
These ports produce outputs only once—at the beginning of a simulation. Any
other ports produce output at their respective sample times.
If Simulink cannot honor the request to use the optimization, then Simulink
treats the block as if it had specified an inherited sample time (–1 ).

5-16

Types of Sample Time

One specific case for which Simulink rejects the request is when parameters
are tunable. By definition, you can change the parameter values of a block
having tunable parameters; therefore, the block outputs are variable rather
than constant. For such cases, Simulink performs sample time propagation
(see “How Propagation Affects Inherited Sample Times” on page 5-29) to
determine the block sample time.
An example of a Constant block with tunable parameters is shown below
(ex_inline_parameters_off. Since the Inline parameters option is
disabled, the Constant value parameter is tunable and the sample time
cannot be constant, even if it is set to Inf. To ensure accurate simulation
results, Simulink treats the sample time of the Constant block as inherited
and uses sample time propagation to calculate the sample time. The
Discrete-Time Integrator block is the first block, downstream of the Constant
block, which does not inherit its sample time. The Constant block, therefore,
inherits the sample time of 1 from the Integrator block via backpropagation.

Inline Parameters Off

Ts = Inf

Ts = −1

Ts = 1

Ts = −1

Variable Sample Time
Blocks that use a variable sample time have an implicit SampleTime
parameter that the block specifies; the block tells Simulink when to run it.
The compiled sample time is [–2, Tvo] where Tvo is a unique variable offset.
The Pulse Generator block is an example of a block that has a variable sample
time. Since Simulink supports variable sample times for variable-step solvers

5-17

5

Working with Sample Times

only, the Pulse Generator block specifies a discrete sample time if you use a
fixed-step solver.
To learn how to write your own block that uses a variable sample time, see “C
MEX S-Function Examples”.

Triggered Sample Time
If a block is inside of a triggered-type (e.g., function-call, enabled and
triggered, or iterator) subsystem, the block may have either a triggered or a
constant sample time. You cannot specify the triggered sample time type
explicitly. However, to achieve a triggered type during compilation, you must
set the block sample time to inherited (–1). Simulink then determines the
specific times at which the block computes its output during simulation. One
exception is if the subsystem is an asynchronous function call, as discussed in
the following section.

Asynchronous Sample Time
An asynchronous sample time is similar to a triggered sample time. In both
cases, it is necessary to specify an inherited sample time because the Simulink
engine does not regularly execute the block. Instead, a run-time condition
determines when the block executes. For the case of an asynchronous sample
time, an S-function makes an asynchronous function call.
The differences between these sample time types are:
• Only a function-call subsystem can have an asynchronous sample time.
(See “Function-Call Subsystems” on page 7-30.)
• The source of the function-call signal is an S-function having the option
SS_OPTION_ASYNCHRONOUS.
• The asynchronous sample time can also occur when a virtual block is
connected to an asynchronous S-function or an asynchronous function-call
subsystem.
• The asynchronous sample time is important to certain code-generation
applications. (See “Handle Asynchronous Events”.)
• The sample time is [ −1, − n] .

5-18

Types of Sample Time

For an explanation of how to use blocks to model and generate code for
asynchronous event handling, see “Rate Transitions and Asynchronous
Blocks”.

5-19

5

Working with Sample Times

Block Compiled Sample Time
During the compilation phase of a simulation, Simulink determines the
sample time of a block from its SampleTime parameter (if it has an explicit
sample time), its block type (if it has an implicit sample time), or by its context
within the model. This compiled sample time determines the sample rate of
a block during simulation. You can determine the compiled sample time of
any block in a model by first updating the model and then getting the block
CompiledSampleTime parameter, using the get_param command.

5-20

Sample Times in Subsystems

Sample Times in Subsystems
Subsystems fall into two categories: triggered and nontriggered. For
triggered subsystems, in general, the subsystem gets its sample time from the
triggering signal. One exception occurs when you use a Trigger block to create
a triggered subsystem. If you set the block Trigger type to function-call
and the Sample time type to periodic, the SampleTime parameter becomes
active. In this case, you specify the sample time of the Trigger block, which in
turn, establishes the sample time of the subsystem.
The four nontriggered subsystems are virtual, enabled, atomic, and action.
Simulink calculates the sample times of virtual and enabled subsystems
based on the respective sample times of their contents. The atomic subsystem
is a special case in that the subsystem block has a SampleTime parameter.
Moreover, for a sample time other than the default value of –1, the blocks
inside the atomic subsystem can have only a value of Inf, –1, or the identical
(discrete) value of the subsystem SampleTime parameter. If the atomic
subsystem is left as inherited, Simulink calculates the block sample time
in the same manner as the virtual and enabled subsystems. However, the
main purpose of the subsystem SampleTime parameter is to allow for the
simultaneous specification of a large number of blocks, within an atomic
subsystem, that are all set to inherited. Finally, the sample time of the action
subsystem is set by the If block or the Switch Case block.

5-21

5

Working with Sample Times

Sample Times in Systems
In this section...
“Purely Discrete Systems” on page 5-22
“Hybrid Systems” on page 5-25

Purely Discrete Systems
A purely discrete system is composed solely of discrete blocks and can be
modeled using either a fixed-step or a variable-step solver. Simulating
a discrete system requires that the simulator take a simulation step at
every sample time hit. For a multirate discrete system—a system whose
blocks Simulink samples at different rates—the steps must occur at integer
multiples of each of the system sample times. Otherwise, the simulator
might miss key transitions in the states of the system. The step size that the
Simulink software chooses depends on the type of solver you use to simulate
the multirate system and on the fundamental sample time.
The fundamental sample time of a multirate discrete system is the largest
double that is an integer divisor of the actual sample times of the system. For
example, suppose that a system has sample times of 0.25 and 0.50 seconds.
The fundamental sample time in this case is 0.25 seconds. Suppose, instead,
the sample times are 0.50 and 0.75 seconds. The fundamental sample time
is again 0.25 seconds.
The importance of the fundamental sample time directly relates to whether
you direct the Simulink software to use a fixed-step or a variable-step discrete
solver to solve your multirate discrete system. A fixed-step solver sets the
simulation step size equal to the fundamental sample time of the discrete
system. In contrast, a variable-step solver varies the step size to equal the
distance between actual sample time hits.
The following diagram illustrates the difference between a fixed-step and a
variable-step solver.

5-22

Sample Times in Systems

In the diagram, the arrows indicate simulation steps and circles represent
sample time hits. As the diagram illustrates, a variable-step solver requires
fewer simulation steps to simulate a system, if the fundamental sample time
is less than any of the actual sample times of the system being simulated.
On the other hand, a fixed-step solver requires less memory to implement
and is faster if one of the system sample times is fundamental. This can be
an advantage in applications that entail generating code from a Simulink
model (using Simulink Coder). In either case, the discrete solver provided
by Simulink is optimized for discrete systems; however, you can simulate a
purely discrete system with any one of the solvers and obtain equivalent
results.
Consider the following example of a simple multirate system. For this
example, the DTF1 Discrete Transfer Fcn block’s Sample time is set to
[1 0.1], which gives it an offset of 0.1. The Sample time of the DTF2
Discrete Transfer Fcn block is set to 0.7, with no offset. The solver is set to a
variable-step discrete solver.

5-23

5

Working with Sample Times

Running the simulation and plotting the outputs using the stairs function
simOut = sim('ex_dtf','StopTime', '3');
t = simOut.find('tout')
y = simOut.find('yout')
stairs(t,y, '-*')

produces the following plot.

(For information on the sim command. see “Run Simulation Using the sim
Command” on page 15-3. )
As the figure demonstrates, because the DTF1 block has a 0.1 offset, the
DTF1 block has no output until t = 0.1. Similarly, the initial conditions of
the transfer functions are zero; therefore, the output of DTF1, y(1), is zero
before this time.

5-24

Sample Times in Systems

Hybrid Systems
Hybrid systems contain both discrete and continuous blocks and thus have
both discrete and continuous states. However, Simulink solvers treat any
system that has both continuous and discrete sample times as a hybrid
system. For information on modeling hybrid systems, see “Modeling Hybrid
Systems” on page 3-8.
In block diagrams, the term hybrid applies to both hybrid systems (mixed
continuous-discrete systems) and systems with multiple sample times
(multirate systems). Such systems turn yellow in color when you perform
an Update Diagram with Sample Time Display Colors turned ’on’. As an
example, consider the following model that contains an atomic subsystem,
“Discrete Cruise Controller”, and a virtual subsystem, “Car Dynamics”. (See
ex_execution_order.)

Car Model

With the Sample Time option set to All, an Update Diagram turns the
virtual subsystem yellow, indicating that it is a hybrid subsystem. In this
case, the subsystem is a true hybrid system since it has both continuous
and discrete sample times. As shown below, the discrete input signal, D1,
combines with the continuous velocity signal, v, to produce a continuous input
to the integrator.

Car Model after an Update Diagram

5-25

5

Working with Sample Times

Car Dynamics Subsystem after an Update Diagram

Now consider a multirate subsystem that contains three Sine Wave source
blocks, each of which has a unique sample time — 0.2, 0.3, and 0.4,
respectively.

Multirate Subsystem after an Update Diagram

5-26

Sample Times in Systems

An Update Diagram turns the subsystem yellow because the subsystem
contains more than one sample time. As shown in the block diagram, the
Sine Wave blocks have discrete sample times D1, D2, and D3 and the output
signal is fixed in minor step.
In assessing a system for multiple sample times, Simulink does not consider
either constant [inf, 0] or asynchronous [–1, –n] sample times. Thus a
subsystem consisting of one block with a constant sample time and one block
with a discrete sample time will not be designated as hybrid.
The hybrid annotation and coloring are very useful for evaluating whether
or not the subsystems in your model have inherited the correct or expected
sample times.

5-27

5

Working with Sample Times

Resolve Rate Transitions
In general, a rate transition exists between two blocks if their sample times
differ, that is, if either of their sample-time vector components are different.
The exceptions are:
• A constant sample time ([Inf, 0]) never has a rate transition with any
other rate.
• A continuous sample time (black) and the fastest discrete rate (red) never
has a rate transition if you use a fixed-step solver.
• A variable sample time and fixed in minor step do not have a rate transition.
You can resolve rate transitions by inserting rate transition blocks and by
using two diagnostic tools. For the single-tasking execution mode, the Single
task rate transition diagnostic allows you to set the level of Simulink rate
transition messages. The Multitask rate transition diagnostic serves the
same function for multitasking execution mode. These execution modes
directly relate to the type of solver in use: Variable-step solvers are always
single-tasking; fixed-step solvers may be explicitly set as single-tasking or
multitasking.
For a detailed discussion on rate transitions, see “Single-Tasking and
Multitasking Execution Modes” and “Handle Rate Transitions”.

5-28

How Propagation Affects Inherited Sample Times

How Propagation Affects Inherited Sample Times
During a model update, for example at the beginning of a simulation, Simulink
uses a process called sample time propagation to determine the sample times
of blocks that inherit their sample times. The figure below illustrates a
Discrete Filter block with a sample time period Ts driving a Gain block.

Because the output of the Gain block is the input multiplied by a constant,
its output changes at the same rate as the filter. In other words, the Gain
block has an effective sample rate equal to the sample rate of the filter. The
establishment of such effective rates is the fundamental mechanism behind
sample time propagation in Simulink.

Process for Sample Time Propagation
Simulink uses the following basic process to assign sample times to blocks
that inherit their sample times:
1 Propagate known sample time information forward.
2 Propagate known sample time information backward.
3 Apply a set of heuristics to determine additional sample times.
4 Repeat until all sample times are known.

Simulink Rules for Assigning Sample Times
A block having a block-based sample time inherits a sample time based on
the sample times of the blocks connected to its inputs, and in accordance
with the following rules:

5-29

5

5-30

Working with Sample Times

If...

then

all of the inputs have the same
sample time and the block can accept
that sample time

Simulink assigns the sample time to
the block

the inputs have different discrete
sample times and all of the input
sample times are integer multiples
of the fastest input sample time

Simulink assigns the sample time of
the fastest input to the block . (This
assignment assumes that the block
can accept the fastest sample time.)

the inputs have different discrete
sample times, some of the input
sample times are not integer
multiples of the fastest sample time,
and the model uses a variable-step
solver

Simulink assigns a
fixed-in-minor-step sample time to
the block.

the inputs have different discrete
sample times, some of the input
sample times are not integer
multiples of the fastest sample
time, the model uses a fixed-step
solver, and Simulink can compute
the greatest common integer divisor
(GCD) of the sample times coming
into the block,

Simulink assigns the GCD sample
time to the block. Otherwise,
Simulink assigns the fixed step size
of the model to the block.

the sample times of some of the
inputs are unknown, or if the block
cannot accept the sample time

Simulink determines a sample
time for the block based on a set of
heuristics.

Monitor Backpropagation in Sample Times

Monitor Backpropagation in Sample Times
When you update or simulate a model that specifies the sample time of a
source block as inherited (–1), the sample time of the source block may be
backpropagated; Simulink may set the sample time of the source block to be
identical to the sample time specified by or inherited by the block connected
to the source block. For example, in the model below, the Simulink software
recognizes that the Sine Wave block is driving a Discrete-Time Integrator
block whose sample time is 1; so it assigns the Sine Wave block a sample
time of 1.

You can verify this sample time setting by selecting Sample Time > Colors
from the Simulink Display menu and noting that both blocks are red.
Because the Discrete-Time Integrator block looks at its input only during its
sample hit times, this change does not affect the results of the simulation, but
does improve the simulation performance.
Now replacing the Discrete-Time Integrator block with a continuous
Integrator block, as shown in the model below, causes the Sine Wave and
Gain blocks to change to continuous blocks. You can test this change by
selecting Simulation > Update Diagram to update the colors; both blocks
now appear black.

5-31

5

Working with Sample Times

Note Backpropagation makes the sample times of model sources dependent
on block connectivity. If you change the connectivity of a model whose sources
inherit sample times, you can inadvertently change the source sample times.
For this reason, when you update or simulate a model, by default, Simulink
displays warnings at the command line if the model contains sources that
inherit their sample times.

5-32

6
Referencing a Model
• “Overview of Model Referencing” on page 6-2
• “Create a Model Reference” on page 6-8
• “Convert a Subsystem to a Referenced Model” on page 6-12
• “Referenced Model Simulation Modes” on page 6-21
• “View a Model Reference Hierarchy” on page 6-35
• “Model Reference Simulation Targets” on page 6-37
• “Simulink Model Referencing Requirements” on page 6-45
• “Parameterize Model References” on page 6-52
• “Conditional Referenced Models” on page 6-59
• “Protected Model” on page 6-67
• “Use Protected Model in Simulation” on page 6-68
• “Inherit Sample Times” on page 6-70
• “Refresh Model Blocks” on page 6-74
• “S-Functions with Model Referencing” on page 6-75
• “Buses in Referenced Models” on page 6-78
• “Signal Logging in Referenced Models” on page 6-79
• “Model Referencing Limitations” on page 6-80

6

Referencing a Model

Overview of Model Referencing
In this section...
“About Model Referencing” on page 6-2
“Referenced Model Advantages” on page 6-5
“Masking Model Blocks” on page 6-6
“Models That Use Model Referencing” on page 6-7
“Model Referencing Resources” on page 6-7

About Model Referencing
You can include one model in another by using Model blocks. Each instance
of a Model block represents a reference to another model, called a referenced
model or submodel. For simulation and code generation, the referenced
model effectively replaces the Model block that references it. The model that
contains a referenced model is its parent model. A collection of parent and
referenced models constitute a model reference hierarchy. A parent model and
all models subordinate to it comprise a branch of the reference hierarchy.
The interface of a referenced model consists of its input and output ports (and
control ports, in the case of a conditional referenced model) and its parameter
arguments. A Model block displays inputs and outputs corresponding to the
root-level inputs and outputs of the model it references. These ports enable
you to incorporate the referenced model into the block diagram of the parent
model.
For example, the sldemo_mdref_basic model includes Model
blocks that reference three instances of the same referenced model,
sldemo_mdlref_counter.

6-2

Overview of Model Referencing

Use the ports on a Model block to connect the submodel to other elements of
the parent model. Connecting a signal to a Model block port has the same
effect as connecting the signal to the corresponding port in the submodel.
For example, the Model block CounterA has three inputs: two Constant
blocks and a Pulse Generator block with a sample time of .1. The Model block
CounterB also has three inputs: the same two Constant blocks, and a Pulse
Generator block with a sample time of .5. Each Model block has an output to
a separate Scope block.
The referenced model includes Inport and Outport blocks (and possibly
Trigger or Enable blocks) to connect to the parent model. The
sldemo_mdlref_counter model has three Inport blocks (upper, input, and
lower) and one Outport block (output).

6-3

6

Referencing a Model

A referenced model can itself contain Model blocks and thus reference
lower-level models, to any depth. The top model is the topmost model in a
hierarchy of referenced models. Where only one level of model reference exists,
the parent model and top model are the same. To prevent cyclic inheritance, a
Model block cannot refer directly or indirectly to a model that is superior to it
in the model reference hierarchy. This figure shows cyclic inheritance.

6-4

Overview of Model Referencing

Top model

A

Model A
Referenced
models

B

Model B

A parent model can contain multiple Model blocks that reference the same
submodel as long as the submodel does not define global data. The submodel
can also appear in other parent models at any level. You can parameterize a
referenced model to provide tunability for all instances of the model. Also,
you can parameterize a referenced model to let different Model blocks specify
different values for variables that define the behavior of the submodel. See
“Parameterize Model References” on page 6-52 for details.
By default, the Simulink software executes a top model interpretively, just
as it would if the model did not include submodels. Simulink can execute a
referenced model interpretively, as if it were an atomic subsystem, or by
compiling the submodel to code and executing the code. See “Referenced
Model Simulation Modes” on page 6-21 for details.
You can use a referenced model as a standalone model, if it does not depend
on data that is available only from a higher-level model. An appropriately
configured model can function as both a standalone model and a referenced
model, without changing the model or any entities derived from it.

Referenced Model Advantages
Like subsystems, referenced models allow you to organize large models
hierarchically; Model blocks can represent major subsystems. Like libraries,
referenced models allow you to use the same capability repeatedly without
having to redefine it. However, referenced models provide several advantages
that are unavailable with subsystems and/or library blocks:
• Modular development

6-5

6

Referencing a Model

You can develop a referenced model independently from the models that
use it.
• Model Protection
You can obscure the contents of a referenced model, allowing you to
distribute it without revealing the intellectual property that it embodies.
• Inclusion by reference
You can reference a model multiple times without having to make
redundant copies, and multiple models can reference the same model.
• Incremental loading
Simulink loads a referenced model at the point it needs to use the model,
which speeds up model loading.
• Accelerated simulation
Simulink can convert a referenced model to code and simulate the model by
running the code, which is faster than interactive simulation.
• Incremental code generation
Accelerated simulation requires code generation only if the model has
changed since the code was previously generated.
• Independent configuration sets
The configuration set used by a referenced model can differ from the
configuration set of its parent or other referenced models.
For additional information about how model referencing compares to other
Simulink componentization techniques, see “Componentization Guidelines”
on page 12-17. For a video summarizing advantages of model referencing, see
Modular Design Using Model Referencing

Masking Model Blocks
You can use the masking facility to create custom dialog boxes and icons for
Model blocks. Masked dialog boxes can make it easier to specify additional
parameters for Model blocks. For information about block masks, see
“Masking”.

6-6

Overview of Model Referencing

Models That Use Model Referencing
Simulink includes several models that illustrate model referencing.
The Introduction to Managing Data with Model Reference example
introduces the basic concepts and workflow related to managing data with
model referencing. To explore these topics in more detail, select the Detailed
Workflow for Managing Data with Model Reference example.
In addition, the sldemo_absbrake model represents a wheel speed calculation
as a Model block within the context of an anti-lock braking system (ABS).

Model Referencing Resources
The following are the most commonly needed resources for working with
model referencing:
• The Model block, which represents a model that another model
references. See the Model block parameters in “Ports & Subsystems
Library Block Parameters” for information about accessing a Model block
programmatically.
• The Configuration Parameters > Diagnostics > Model Referencing
pane, which controls the diagnosis of problems encountered in model
referencing. See “Diagnostics Pane: Model Referencing” for details.
• The Configuration Parameters > Model Referencing pane, which
provides options that control model referencing and list files on which
referenced models depend. See “Model Referencing Pane” for details.

6-7

6

Referencing a Model

Create a Model Reference
A model becomes a submodel when a Model block in some other model
references it. Any model can function as a submodel, and such use does not
preclude using it as a separate model also.
For a video introducing how to create model references, see Getting Started
with Model Referencing.
To create a reference to a model (submodel) in another model (parent model):
1 If the folder containing the submodel you want to reference is not on the

MATLAB path, add the folder to the MATLAB path.
2 In the submodel:

• Enable Configuration Parameters > Optimization > Inline
parameters. You must enable Inline parameters for all models in a
model reference hierarchy except the top model in the hierarchy. See
“Inline Parameter Requirements” on page 6-49 for details.
• Set Configuration Parameters > Model Referencing > Total
number of instances allowed per top model to:
– One, if the hierarchy uses the model at most once
– Multiple, to use the model more than once per top model. To reduce
overhead, specify Multiple only when necessary.
– Zero, which precludes referencing the model
3 Create an instance of the Model block in the parent model by dragging a

Model block instance from the Ports & Subsystems library to the parent
model. The new block is initially unresolved (specifies no submodel) and
has the following appearance:

6-8

Create a Model Reference

4 Open the new Model block’s parameter dialog box by double-clicking the

Model block. See “Navigating a Model Block” for more about accessing
Model block parameters.

6-9

6

6-10

Referencing a Model

Create a Model Reference

5 Enter the name of the submodel in the Model name field. This name must

contain fewer than 60 characters. (See “Name Length Requirement” on
page 6-45.)
• For information about Model Arguments and Model argument
values, see “Using Model Arguments” on page 6-53.
• For information about the Simulation mode, see “Referenced Model
Simulation Modes” on page 6-21.
6 Click OK or Apply.

If the referenced model contains any root-level inputs or outputs, Simulink
displays corresponding input and output ports on the Model block instance
that you have created. Use these ports to connect the referenced model to
other ports in the parent model.
A signal that connects to a Model block is functionally the same signal outside
and inside the block. Therefore that signal is subject to the restriction
that a given signal can have at most one associated signal object. See
Simulink.Signal for more information. For information about connecting a
bus signal to a referenced model, see “Bus Usage Requirements” on page 6-50.

6-11

6

Referencing a Model

Convert a Subsystem to a Referenced Model
Conversion Process
The process for converting a subsystem to a referenced model involves these
tasks:
1 “Select Subsystems to Convert” on page 6-12.
2 “Prepare the Model for Conversion” on page 6-13.
3 “Run a Conversion Tool” on page 6-16.
4 “Connect the Model Block and Perform Other Post-Conversion Tasks” on

page 6-18.

Select Subsystems to Convert
Model referencing offers several benefits for modeling large, complex systems
and for team-based development, as summarized in “Referenced Model
Advantages” on page 6-5.
Subsystems or libraries are better suited for some modeling goals than
model referencing. Many large models involve using a combination of
subsystems and referenced models. For information to help you to decide
which subsystems to convert to referenced models, see “Componentization
Guidelines” on page 12-17.
The types of subsystems that you can convert to a referenced model are:
• Atomic Subsystem
• “Triggered Subsystems” on page 7-20
• “Enabled Subsystems” on page 7-4
• “Triggered and Enabled Subsystems” on page 7-24
• “Function-Call Subsystems” on page 7-30

6-12

Convert a Subsystem to a Referenced Model

Note If you want to create a referenced model that accepts an
asynchronous function call, see “Asynchronous Support Limitations”.
If you convert a masked subsystem, you might need to perform some
additional tasks to maintain the same general behavior that the masked
subsystem provided. For details, see “Convert a Masked Subsystem” on page
6-19.

Prepare the Model for Conversion
Simulink provides a tool that you can use to convert a subsystem to a
referenced model.
When the conversion tool identifies a change that you need to make to a model
or subsystem to support the conversion, the conversion processing stops.
The conversion tool reports conversion issues one at a time. To perform the
conversion efficiently, before using the conversion tool, consider modifying
your model as described in the following steps.
When you run the conversion tool, it will flag any additional model
modifications that you may need to make.
1 Save a backup copy of the model.

You can use the backup copy of the model to help you to configure the model
after performing the conversion. For example, if you convert a masked
subsystem and want to have a masked Model block, you might want to copy
information from the masked subsystem into the masked Model block.
Also, you can revert to the original version of the model if you decide not to
convert the subsystem after you have started to modify the model, or if the
conversion processing is unsuccessful.
2 Use the Configuration Parameters dialog box to set the following model

configuration parameters.
a Select Optimization > Inline parameters.

6-13

6

Referencing a Model

b Set Diagnostics > Data Validity > Signal resolution to Explicit

only.
c Set Diagnostics > Connectivity > Mux blocks used to create bus

signals to Error. For information about proper mux usage, see “Avoid
Mux/Bus Mixtures” on page 48-95.
As an alternative for steps b and c, consider using the associated Model
Advisor checks.
3 Configure subsystem interfaces to the model.

Subsystem
Interface

What to Look For

Model Modification

Goto or From
blocks

Crossing of subsystem
boundaries.

Add input or output ports to the
subsystem. Reconfigure the model as
necessary to reflect the added ports.

Data stores

Data Store Memory blocks
accessed by Data Store Read or
Data Store Write blocks from
outside of the subsystem.

Replace the Data Store Memory block
with a global data store. Define a global
data store with a Simulink.Signal
object. For details, see “Data Stores
with Signal Objects” on page 46-12.

Tunable
parameters

Global tunable parameters
listed in the dialog box that
opens when you select the
Configuration Parameters >
Optimization > Signals and
Parameters > Configure
button.

Use tunablevars2parameterobjects
to create a Simulink.Parameter object
for each tunable parameter.
The Simulink.Parameter objects must
have a non-Auto storage class.
For more information, see “Parameterize
Model References” on page 6-52 and
“Tunable Parameters” on page 3-9.

4 Configure the subsystem and its contents.

6-14

Convert a Subsystem to a Referenced Model

Subsystem
What to Look For
Configuration

Model Modification

Inactive
subsystem
variants

Make active the subsystem
variant that you want to
convert. The conversion tool
does not convert inactive
subsystem variants.

Variant Subsystem
blocks.

To have the new Model
block behave similar to the
subsystem variant, convert
each variant subsystem
separately.
For details, see “Set Up
Variant Subsystems” on page
8-15.
Function calls

Function-call signals
that cross virtual
subsystem boundaries.

Move the Function-Call
Generator block inside of the
subsystem that you want to
convert.

Function-call outputs.

Change the function-call
outputs to data triggers.

Wide function-call ports.

Eliminate wide signals for
function-call subsystems.

Sample times

Sample time of an
Inport block that does
not match the sample
time of the block driving
the Inport.

Insert Rate Transition blocks
where appropriate.

Inport blocks

Merged Inport blocks.

Configure the model to avoid
merged Inport blocks. See the
Merge block documentation.

Constant
blocks

Constant blocks that
input to subsystems.

Consider moving the Constant
blocks into the subsystem.

6-15

6

Referencing a Model

Subsystem
What to Look For
Configuration

Model Modification

Buses

Bus signals that enter
and exit a subsystem.

Match signal names and bus
element names for blocks
inside of the subsystem.

Duplicate signal names
in buses.

Make signal names of the bus
elements unique.

Signal names that are
not valid MATLAB
identifiers. A valid
identifier is a character
string of letters, digits,
and underscores, such
that the first character
is a letter, and the
length of the string
is less than or equal
to the value returned
by the namelengthmax
function.

Change any invalid signal
names to be valid MATLAB
identifiers.

Run a Conversion Tool
Run a conversion tool, using one of these approaches:
• From the context menu of the subsystem, select Subsystem & Model
Reference > Convert to > Referenced Model.
• Use the Simulink.SubSystem.convertToModelReference command.
This function provides more capabilities than the Referenced Model
menu option. For example, with the function, you can replace a subsystem
with an equivalent Model block in a single operation.
Simulink saves the contents of the subsystem as a new model, then creates
and opens an untitled model that contains a Model block whose referenced
model is the new model.

6-16

Convert a Subsystem to a Referenced Model

Model Name
Simulink automatically provides a model name that is based on the block
name and is unique in the MATLAB path. This name always contains fewer
than 60 characters.

Error Handling
During the conversion, if an error occurs, the outcome depends on the kind
of error.
• For some errors, a message box appears that gives you the choice of
cancelling or continuing.
Before you continue, note any changes that you want to make after the
conversion. If you cancel, then the conversion tool exits.
• If continuing is impossible, Simulink cancels the conversion without
offering a choice to continue. If the new Model block has not been created,
then the model is not affected by the conversion tool processing.

What Gets Copied by the Conversion?
The conversion tool copies the following elements from the original model to
the newly created referenced model:
• Configuration sets – If the referencing model uses a configuration set
that is not a referenced configuration set, then the conversion tool copies
that entire configuration set to the referenced model.
If the referencing model uses a referenced configuration set, then both the
referencing and referenced models use the same referenced configuration
set.
• Variables – All of the model workspace variables of the original model are
copied into the model workspace of the referenced model.
• Requirements links – Requirements links created with the Simulink
Verification and Validation software (for example, requirements links to
blocks and signals) are copied. Any requirements links on the subsystem
that you convert are transferred to the new Model block.

6-17

6

Referencing a Model

Connect the Model Block and Perform Other
Post-Conversion Tasks
After you successfully complete the conversion:
1 Connect the referenced model.
a Delete the subsystem block from the source model.
b Copy the new Model block to the location of the deleted subsystem block.

Simulink automatically reconnects all signals. The source model is a
parent model that contains the referenced model.
2 For root Inport blocks in the new referenced model, check the Interpolate

data parameter to make sure it is appropriate. For details, see the Inport
block documentation.
3 (Optional) Delete unused duplicate variables.

The conversion tool copies into the model workspace of the referenced
model (for example, ModelB) all of the model workspace variables of the
referencing model (ModelA). This step results in duplicate variables in the
two model workspaces. To improve the reliability of your model in case the
model changes in the future, consider removing unused variables or moving
variables that are used by both ModelA and ModelB:
• For a model workspace variable used only by the referencing model
(ModelA), delete the variable from the model workspace of the referenced
model (ModelB).
• For a model workspace variable used only by the referenced model
(ModelB), delete the variable from the model workspace of the referencing
model (ModelA).
• For model workspace variables used by both the referencing and
referenced model, consider moving that variable to the base workspace.
4 (Optional) To achieve similar results in the new referenced model as you

did by using the Variant Subsystem block, convert each of the variant
subsystems to referenced models, and then use a Model Variants block. For
more information, see “Set Up Model Variants” on page 8-5.

6-18

Convert a Subsystem to a Referenced Model

If you convert a masked subsystem, you may need to perform some additional
tasks to maintain the same general behavior that the masked subsystem
provided. For details, see “Convert a Masked Subsystem” on page 6-19.

Convert a Masked Subsystem
Perform the tasks described in:
• “Select Subsystems to Convert” on page 6-12.
• “Prepare the Model for Conversion” on page 6-13.
• “Run a Conversion Tool” on page 6-16.
• “Connect the Model Block and Perform Other Post-Conversion Tasks” on
page 6-18.
If the subsystem that you converted contains a mask, then you might want
to mask the Model block in your new referenced model (see “Masking”).
Configure the referenced model to support the functionality that was in the
masked subsystem.
Note The referenced model does not support the functionality that you can
achieve with mask initialization code to create masked parameters.

Masked
Subsystem
Functionality
Masked
parameters

Referenced Model Configuration

1 In the model workspace of the referenced model,

create a variable for each masked parameter.
2 In the Model Explorer, select the Model Workspace

node. In the Dialog pane, in the Model arguments
parameter, enter the variables that you want to be
model arguments.

6-19

6

Referencing a Model

Masked
Subsystem
Functionality

Referenced Model Configuration

3 In the new Model block, for the Model arguments

parameter, specify the values for the model
arguments.
Masked callbacks,
icons, ports, and
documentation

In the backup copy of the masked subsystem, open
the Mask Editor and select the content to copy into to
masked Model block.
In the Mask Editor for the new Model block, copy the
appropriate content from the masked subsystem that
you converted.

6-20

Referenced Model Simulation Modes

Referenced Model Simulation Modes
In this section...
“Simulation Modes for Referenced Models” on page 6-21
“Specify the Simulation Mode” on page 6-23
“Mixing Simulation Modes” on page 6-23
“Using Normal Mode for Multiple Instances of Referenced Models” on page
6-25
“Accelerating a Freestanding or Top Model” on page 6-33

Simulation Modes for Referenced Models
Simulink executes the top model in a model reference hierarchy just as
it would if no referenced models existed. All Simulink simulation modes
are available to the top model. Simulink can execute a referenced model
in any of four modes: Normal, Accelerator, Software-in-the-loop (SIL), or
Processor-in-the-loop (PIL).

Normal Mode
Simulink executes a Normal mode submodel interpretively. Normal mode,
compared to other simulation modes:
• Requires no delay for code generation or compilation
• Works with more Simulink and Stateflow tools, supporting tools such as:

-

Scopes, port value display, and other output viewing tools
•

-

Scopes work with Accelerator mode referenced models, but require
using the Signal & Scope Manager and adding test points to signals.
Adding or removing a test point necessitates rebuilding the SIM
target for a model, which can be time-consuming.

Model coverage analysis
Stateflow debugging and animation

• Provides more accurate linearization analysis
• Supports more S-functions than Accelerator mode does

6-21

6

Referencing a Model

Normal mode executes slower than Accelerator mode does.
Simulation results for a given model are nearly the same in either Normal
or Accelerator mode. Trivial differences can occur due to differences in the
optimizations and libraries that you use.
You can use Normal mode with multiple instances of a referenced model.
For details, see “Using Normal Mode for Multiple Instances of Referenced
Models” on page 6-25.

Accelerator Mode
Simulink executes an Accelerator mode submodel by creating a MEX-file (or
simulation target) for the submodel, then running the MEX-file. See “Model
Reference Simulation Targets” on page 6-37 for more information. Accelerator
mode:
• Takes time for code generation and code compilation
• Does not fully support some Simulink tools, such as Model Coverage and
the Simulink Debugger.
• Executes faster than Normal mode
Simulation results for a given model are nearly identical in either Normal
or Accelerator mode. Trivial differences can occur due to differences in the
optimizations and libraries that you use.

Software-in-the-Loop (SIL) Mode
Simulink executes a SIL-mode referenced model by generating production
code using the model reference target for the submodel. This code is compiled
for, and executed on, the host platform.
With SIL mode, you can:
• Verify generated source code without modifying the original model
• Reuse test harnesses for the original model with the generated source code
SIL mode provides a convenient alternative to PIL simulation when the
target hardware is not available.

6-22

Referenced Model Simulation Modes

This option requires Embedded Coder software.
For more information, see “Numerical Equivalence Testing” in the Embedded
Coder documentation.

Processor-in-the-Loop (PIL) Mode
Simulink executes a PIL-mode referenced model by generating production
code using the model reference target for the submodel. This code is
cross-compiled for, and executed on, a target processor or an equivalent
instruction set simulator.
With PIL mode, you can:
• Verify deployment object code on target processors without modifying the
original model
• Reuse test harnesses for the original model with the generated source code
This option requires Embedded Coder software.
For more information, see “Numerical Equivalence Testing” in the Embedded
Coder documentation.

Specify the Simulation Mode
The Model block for each instance of a referenced model controls its simulation
mode. To set or change the simulation mode for a submodel:
1 Access the block parameter dialog box for the Model block. (See “Navigating

a Model Block”.)
2 Set the Simulation mode parameter.
3 Click OK or Apply.

Mixing Simulation Modes
The following table summarizes the relationship between the simulation
mode of the parent model and its submodels.

6-23

6

Referencing a Model

Parent Model
Simulation Mode

Submodel Simulation Modes

Normal

• Submodels can use Normal, Accelerator, SIL,
or PIL mode.
• A submodel can execute in Normal mode only
if every model that is superior to it in the
hierarchy also executes in Normal mode. A
Normal mode path then extends from the top
model through the model reference hierarchy
down to the Normal mode submodel.

Accelerator

• All subordinate models must also execute in
Accelerator mode.
• When a Normal mode model is subordinate to
an Accelerator mode model, Simulink posts
a warning and temporarily overrides the
Normal mode specification.
• When a SIL-mode or PIL-mode model is
subordinate to an Accelerator mode model, an
error occurs.

SIL

• All subordinate models also execute in SIL
mode regardless of the simulation mode
specified by their Model blocks.
• The SIL mode Model block uses the model
reference targets of the blocks beneath.
• Only one Model block, starting at the top
of a model reference hierarchy, can execute
at a time in SIL mode. See “Simulation
Mode Override Behavior in Model Reference
Hierarchy”.

PIL

• All subordinate models also execute in PIL
mode regardless of the simulation mode
specified by their Model blocks.
• The PIL mode Model block uses the model
reference targets of the blocks beneath.

6-24

Referenced Model Simulation Modes

Parent Model
Simulation Mode

Submodel Simulation Modes

• Only one Model block, starting at the top
of a model reference hierarchy, can execute
at a time in PIL mode. See “Simulation
Mode Override Behavior in Model Reference
Hierarchy”.
For more information about SIL and PIL modes, see in the Embedded Coder
documentation:
• “Code Interfaces for SIL and PIL”
• “SIL and PIL Simulation Support and Limitations”

Using Normal Mode for Multiple Instances of
Referenced Models
You can simulate a model that has multiple references in Normal mode.

Normal Mode Visibility
All instances of a Normal mode referenced model are part of the simulation.
However, Simulink displays only one instance in a model window; that
instance is determined by the Normal Mode Visibility setting. Normal mode
visibility includes the display of Scope blocks and data port values.
If you do not set Normal Mode Visibility, Simulink picks one instance of each
Normal mode model to display.
After a simulation, if you try to open a referenced model from a Model block
that has Normal Mode Visibility set to off, Simulink displays a warning.
For a description of how to set up your model to control which instance of
a referenced model in Normal mode has visibility and to ensure proper
simulation of the model, see “Specify the Instance That Has Normal Mode
Visibility” on page 6-28.

6-25

6

Referencing a Model

Note If you change the Normal Mode Visibility setting for a referenced
model, you must simulate the top model in the model reference hierarchy to
make use of the new setting.

Examples of a Model with Multiple Referenced Instances in
Normal Mode
sldemo_mdlref_basic. The sldemo_mdlref_basic model has three
Model blocks (CounterA, CounterB, and CounterC) that each reference the
sldemo_mdlref_counter model.
If you update the diagram, the sldemo_mdlref_basic displays different icons
for each of the three Model blocks that reference sldemo_mdlref_counter.

6-26

Model Block

Icon
Corners

Simulation Mode and Normal
Mode Visibility Setting

CounterA

White

Normal mode, with Normal Mode
Visibility enabled

CounterB

Gray
corners

Normal mode, with Normal Mode
Visibility disabled

CounterC

Black
corner

Accelerator mode (Normal Mode
Visibility is not applicable)

Referenced Model Simulation Modes

If you do the following steps, then the ScopeA block appears as shown below:
1 Simulate sldemo_mdlref_basic.
2 Open the sldemo_mdlref_counter model.
3 Open the ScopeA block.

That ScopeA block reflects the results of simulating the CounterA Model
block, which has Normal Mode Visibility enabled.
If you try to open mdlref_counter model from the CounterB Model block (for
example, by double-clicking the Model block), ScopeA in mdlref_counter still
shows the results of the CounterA Model block, because that is the Model
block with Normal Mode Visibility set to on.
sldemo_mdlref_depgraph. The sldemo_mdlref_depgraph model shows
the use of the Model Dependency Viewer for a model that has multiple Normal
mode instances of a referenced model. The model shows what you need to do
to set up a model with multiple referenced instances in Normal mode.

6-27

6

Referencing a Model

Set Up a Model with Multiple Instances of a Referenced Model
in Normal Mode
This section describes how to set up a model to support the use of multiple
instances of Normal mode referenced models.
1 Set the Configuration Parameters > Model Referencing > Total

number of instances allowed per top model parameter to Multiple.
If you cannot use the Multiple setting for your model, because of the
requirements described in the “Total number of instances allowed per top
model” parameter documentation, then you can have only one instance of
that referenced model be in Normal mode.
2 For each instance of the referenced model that you want to be in Normal

mode, in the block parameters dialog box for the Model block, set the
Simulation Mode parameter to Normal. Ensure that all the ancestors in
the hierarchy for that Model block are in Normal mode.
The corners of icons for Model blocks that are in Normal mode can be white
(empty), or gray after you update the diagram or simulate the model.
3 (If necessary) Modify S-functions used by the model so that they work with

multiple instances of referenced models in Normal mode. For details, see
“Supporting the Use of Multiple Instances of Referenced Models That Are
in Normal Mode”.
By default, Simulink assigns Normal mode visibility to one of the instances.
After you have performed the steps in this section, you can specify a
non-default instance to have Normal mode visibility. For details, see “Specify
the Instance That Has Normal Mode Visibility” on page 6-28.

Specify the Instance That Has Normal Mode Visibility
This section describes how to specify Normal Mode Visibility for an instance
other than the one that an instance that Simulink selects automatically.
You need to:
1 (Optionally) “Determine Which Instance Has Normal Mode Visibility” on

page 6-29.

6-28

Referenced Model Simulation Modes

2 “Set Normal Mode Visibility” on page 6-30.
3 Simulate the top model to apply the new Normal Mode Visibility settings.

Determine Which Instance Has Normal Mode Visibility. If you do not
already know which instance currently has Normal mode visibility, you can
determine that by using one of these approaches:
• If you update the diagram and have made no other changes to the model,
then you can navigate through the model hierarchy to examine the Model
blocks that reference the model that you are interested in. The Model block
that has white corners has Normal Mode Visibility enabled.
• When you are editing a model or during compilation, use the
ModelReferenceNormalModeVisibilityBlockPath parameter.
If you use this parameter while editing a model, you must update the
diagram before you use this parameter.
The result is a Simulink.BlockPath object that is the block path for the
Model block that references the model that has Normal Mode Visibility
enabled. For example:
get_param('sldemo_mdlref_basic',...
'ModelReferenceNormalModeVisibilityBlockPath')
ans =
Simulink.BlockPath
Package: Simulink
Block Path:
'sldemo_mdlref_basic/CounterA'

• For a top model that is being simulated or that is in a compiled state, you
can use the CompiledModelBlockInstancesBlockPath parameter. For
example:
a = get_param('sldemo_mdlref_depgraph',...
'CompiledModelBlockInstancesBlockPath')
a =

6-29

6

Referencing a Model

sldemo_mdlref_F2C: [1x1 Simulink.BlockPath]
sldemo_mdlref_heater: [1x1 Simulink.BlockPath]
sldemo_mdlref_outdoor_temp: [1x1 Simulink.BlockPath]

Set Normal Mode Visibility. To enable Normal Mode Visibility for a
different instance of the referenced model than the instance that currently
has Normal Mode Visibility, use one of these approaches:
• Navigate to the top model and select the Diagram > Subsystem & Model
Reference > Model Block Normal Mode Visibility menu item.
The Model Block Normal Mode Visibility dialog box appears. That dialog
box includes instructions in the right pane. For additional details about
the dialog box, see “Model Block Normal Mode Visibility Dialog Box” on
page 6-31.
• From the MATLAB command line, set the
ModelReferenceNormalModeVisibility parameter.
For input, you can specify:

-

An array of Simulink.BlockPath objects. For example:
bp1 = Simulink.BlockPath({'mVisibility_top/Model', ...
'mVisibility_mid_A/Model'});
bp2 = Simulink.BlockPath({'mVisibility_top/Model1', ...
'mVisibility_mid_B/Model1'});
bps = [bp1, bp2];
set_param(topMdl, 'ModelBlockNormalModeVisibility', bps);

-

A cell array of cell arrays of strings, with the strings being paths to
individual blocks and models. The following example has the same
effect as the preceding example (which shows how to specify an array
of Simulink.BlockPath objects):
p1 = {'mVisibility_top/Model', 'mVisibility_mid_A/Model'};
p2 = {'mVisibility_top/Model1', 'mVisibility_mid_B/Model1'};
set_param(topMdl, 'ModelBlockNormalModeVisibility', {p1, p2});

-

6-30

An empty array, to specify the use of the Simulink default selection of
the instance that has Normal mode visibility. For example:

Referenced Model Simulation Modes

set_param(topMdl, 'ModelBlockNormalModeVisibility', []);

Using an empty array is equivalent to clearing all the check boxes in the
Model Block Normal Mode Visibility dialog box.
Note You cannot change Normal Mode Visibility during a simulation.

Model Block Normal Mode Visibility Dialog Box
If you have a model that has multiple instances of a referenced model in
Normal mode, you can use the Block Model Normal Mode Visibility dialog box
to set Normal Mode Visibility for a specific instance. For a description of
Normal mode visibility, see “Normal Mode Visibility” on page 6-25.
Alternatively, you can set the ModelReferenceNormalModeVisibility
parameter. For information about how to specify an instance of a referenced
model that is in Normal mode that is different than the instance automatically
selected by Simulink, see “Specify the Instance That Has Normal Mode
Visibility” on page 6-28.
Open the Model Block Normal Mode Visibility Dialog Box. To open
the Model Block Normal Mode Visibility dialog box, navigate to the top model
and select Diagram > Subsystem & Model Reference > Model Block
Normal Mode Visibility.
The dialog box for the sldemo_mdlref_basic model, with the hierarchy pane
expanded, looks like this:

6-31

6

Referencing a Model

The model hierarchy pane shows a partial model hierarchy for the model from
which you opened the dialog box. The hierarchy stops at the first Model block
that is not in Normal mode. The model hierarchy pane does not display Model
blocks that reference protected models.
Select a Model for Normal Mode Visibility.
The dialog box shows the complete model block hierarchy for the top model.
The Normal mode instances of referenced models have check boxes. Select
the check box for the instance of each model that you want to have Normal
mode visibility.

6-32

Referenced Model Simulation Modes

When you select a model, Simulink:
• Selects all ancestors of that model
• Deselects all other instances of that model
When a model is deselected, Simulink deselects all children of that model.
Opening a Model from the Model Block Normal Mode Visibility
Dialog Box. You can open a model from the Model Block Normal Mode
Visibility dialog box by right-clicking the model in the model hierarchy pane
and clicking Open.
Refreshing the Model Reference Hierarchy. To ensure the model
hierarchy pane of the Model Block Normal Mode Visibility dialog box reflects
the current model hierarchy, click Refresh.

Accelerating a Freestanding or Top Model
You can use Simulink Accelerator mode or Rapid Accelerator mode to
achieve faster execution of any Simulink model, including a top model in
a model reference hierarchy. For details about Accelerator mode, see the
“Acceleration” documentation. For information about Rapid Accelerator
mode, see “Rapid Simulations”.

6-33

6

Referencing a Model

When you execute a top model in Simulink Accelerator mode or Rapid
Accelerator mode, all submodels execute in Accelerator mode. For any
submodel that specifies Normal mode, Simulink displays an warning message.
Be careful not confuse Accelerator mode execution of a referenced model with:
• Accelerator mode execution of a freestanding or top model, as described
in “Acceleration”
• Rapid Accelerator mode execution of a freestanding or top model, as
described in “Rapid Simulations”
While the different types of acceleration share many capabilities and
techniques, they have different implementations, requirements, and
limitations.

6-34

View a Model Reference Hierarchy

View a Model Reference Hierarchy
Simulink provides tools and functions that you can use to examine a model
reference hierarchy:
• Model Dependency Viewer — Shows the structure the hierarchy lets
you open constituent models. The Referenced Model Instances view
displays Model blocks differently to indicate Normal, Accelerator, and PIL
modes. See “Model Dependency Viewer” on page 9-83 for more information.
• view_mdlrefs function — Invokes the Model Dependency Viewer to
display a graph of model reference dependencies.
• find_mdlrefs function — Finds all models directly or indirectly
referenced by a given model.

Display Version Numbers
To display the version numbers of the models referenced by a model,
for the parent model, choose Display > Blocks > Block Version for
Referenced Models. Simulink displays the version numbers in the icons of
the corresponding Model block instances.

The version number displayed on a Model block icon refers to the version
of the model used to either:
• Create the block
• Refresh the block most recently changed

6-35

6

Referencing a Model

See “Manage Model Versions” on page 4-107 and “Refresh Model Blocks”
on page 6-74 for more information.

6-36

Model Reference Simulation Targets

Model Reference Simulation Targets
In this section...
“Simulation Targets” on page 6-37
“Build Simulation Targets” on page 6-38
“Simulation Target Output File Control” on page 6-39
“Parallel Building for Large Model Reference Hierarchies” on page 6-42

Simulation Targets
A simulation target, or SIM target, is a MEX-file that implements a referenced
model that executes in Accelerator mode. Simulink invokes the simulation
target as needed during simulation to compute the behavior and outputs
of the referenced model. Simulink uses the same simulation target for all
Accelerator mode instances of a given referenced model anywhere in a
reference hierarchy.
If you have a Simulink Coder license, be careful not to confuse the simulation
target of a submodel with any of these other types of target:
• Hardware target — A platform for which Simulink Coder generates code
• System target — A file that tells Simulink Coder how to generate code
for particular purpose
• Rapid Simulation target (RSim) — A system target file supplied with
Simulink Coder
• Model reference target — A library module that contains Simulink Coder
code for a referenced model
Simulink creates a simulation target only for a submodel that has one or
more Accelerator mode instances in a reference hierarchy. A submodel that
executes only in Normal mode always executes interpretively and does not
use a simulation target. When one or more instance of a submodel executes in
Normal mode, and one or more instance executes in Accelerator mode:
• Simulink creates a simulation target for the Accelerator mode instances.

6-37

6

Referencing a Model

• The Normal mode instances do not use that simulation target.
Because Accelerator mode requires code generation, it imposes some
requirements and limitations that do not apply to Normal mode. Aside
from these constraints, you can generally ignore simulation targets and
their details when you execute a referenced model in Accelerator mode. See
“Limitations on Accelerator Mode Referenced Models” on page 6-84 for details.

Build Simulation Targets
Simulink by default generates the needed target from the referenced model:
• If a simulation target does not exist at the beginning of a simulation
• When you perform an update diagram for a parent model
If the simulation target already exists, then by default Simulink checks
whether the submodel has structural changes since the target was last
generated. If so, Simulink regenerates the target to reflect changes in the
model. For details about how Simulink detects whether to rebuild a model
reference target, see the “Rebuild” parameter documentation.
You can change this default behavior to modify the rebuild criteria or specify
that Simulink always or never rebuilds targets. See “Rebuild” for details.
To generate simulation targets interactively for Accelerator mode referenced
models, do one of these steps:
• Update the diagram on a model that directly or indirectly references the
model that is in Accelerator mode
• Execute the slbuild command with appropriate arguments at the
MATLAB command line
While generating a simulation target, Simulink displays status messages at
the MATLAB command line to enable you to monitor the target generation
process. Target generation entails generating and compiling code and linking
the compiled target code with compiled code from standard code libraries
to create an executable file.

6-38

Model Reference Simulation Targets

Reduce Change Checking Time
You can reduce the time that Simulink spends checking whether any or all
simulation targets require rebuilding by setting configuration parameter
values as follows:
• In all referenced models throughout the hierarchy, set Configuration
Parameters > Diagnostics > Data Validity > Signal resolution to
Explicit only. (See “Signal resolution”.)
• To minimize change detection time, consider setting Configuration
Parameters > Model Referencing > Rebuild options to If any
changes in known dependencies detected on the top model. See
“Rebuild”.
These parameter values exist in the configuration set of a referenced model,
not in the individual Model block, so setting either value for any instance of a
referenced model sets it for all instances of that model.

Simulation Target Output File Control
Simulink creates simulation targets in the slprj subfolder of the working
folder. If slprj does not exist, Simulink creates it.
Note Simulink Coder code generation also uses the slprj folder.
Subdirectories in slprj provide separate places for simulation code, Simulink
Coder code, and other files. For details, see “Control the Location for
Generated Files”.
By default, the files generated by Simulink diagram updates and model builds
are placed in a build folder, the root of which is the current working folder
(pwd). However, in some situations, you might want the generated files to go
to a root folder outside the current working folder. For example:
• You need to keep generated files separate from the models and other source
materials used to generate them.
• You want to reuse or share previously-built simulation targets without
having to set the current working folder back to a previous working folder.

6-39

6

Referencing a Model

You might also want to separate generated simulation artifacts from
generated production code.
To allow you to control the output locations for the files generated by diagram
updates and model builds, the software allows you to separately specify the
simulation cache folder build folder. The simulation cache folder is the root
folder in which to place artifacts used for simulation.
To specify the simulation cache folder, use one of these approaches:
• Use the CacheFolder MATLAB session parameter.
• Open the Simulink Preferences dialog box (File > Simulink Preferences)
and specify a location on your file system for the Simulation cache
folder, which, if specified, provides the initial defaults for the MATLAB
session parameters.

Control Output Location for Model Build Artifacts Used for
Simulation
The Simulink preference Simulation cache folder provides control over
the output location for files generated by Simulink diagram updates. The
preference appears in the Simulink Preferences Window, Main Pane, in the
File generation control group. To specify the root folder location for files
generated by Simulink diagram updates, set the preference value by entering
or browsing to a folder path, for example:

The folder path that you specify provides the initial default for the MATLAB
session parameter CacheFolder. When you initiate a Simulink diagram
update, any files generated are placed in a build folder at the root location
specified by CacheFolder (if any), rather than in the current working folder
(pwd).
For example, using a 32-bit Windows host platform, if you set the Simulation
cache folder to 'C:\Work\mymodelsimcache' and then simulate the model
rtwdemo_capi, files are generated into the specified folder as follows:

6-40

Model Reference Simulation Targets

As an alternative to using the Simulink preferences GUI to set Simulation
cache folder, you also can get and set the preference value from the
command line using get_param and set_param. For example,
>> get_param(0, 'CacheFolder')
ans =
''
>> set_param(0, 'CacheFolder', fullfile('C:','Work','mymodelsimcache'))
>> get_param(0, 'CacheFolder')
ans =
C:\Work\mymodelsimcache

Also, you can choose to override the Simulation cache folder preference
value for the current MATLAB session.

Override Build Folder Settings for the Current MATLAB Session
The Simulink preferences Simulation cache folder and Code generation
folder provide the initial defaults for the MATLAB session parameters
CacheFolder and CodeGenFolder, which determine where files generated
by Simulink diagram updates and model builds are placed. However,
you can override these build folder settings during the current MATLAB
session, using the Simulink.fileGenControl function. This function
allows you to directly manipulate the MATLAB session parameters, for

6-41

6

Referencing a Model

example, overriding or restoring the initial default values. The values
you set using Simulink.fileGenControl expire at the end of the current
MATLAB session. For more information and detailed examples, see the
Simulink.fileGenControl function reference page.

Parallel Building for Large Model Reference
Hierarchies
In a parallel computing environment, you can increase the speed of diagram
updates for models containing large model reference hierarchies by building
referenced models that are configured in Accelerator mode in parallel
whenever conditions allow. For example, if you have Parallel Computing
Toolbox™ software, updating of each referenced model can be distributed
across the cores of a multicore host computer. If you additionally have
MATLAB Distributed Computing Server™ (MDCS) software, updating of
each referenced model can be distributed across remote workers in your
MATLAB Distributed Computing Server configuration.
To take advantage of parallel building for a model reference hierarchy:
1 Set up a pool of local and/or remote MATLAB workers in your parallel

computing environment.
a Make sure that Parallel Computing Toolbox software is licensed and

installed.
b To use remote workers, make sure that MATLAB Distributed Computing

Server software is licensed and installed.
c Issue appropriate MATLAB commands to set up the worker pool, for

example, matlabpool 4.
2 In the Configuration Parameters dialog box, go to the Model Referencing

pane and select the Enable parallel model reference builds option.
This selection enables the parameter MATLAB worker initialization
for builds.

6-42

Model Reference Simulation Targets

For MATLAB worker initialization for builds, select one of the
following values:
• None if the software should perform no special worker initialization.
Specify this value if the child models in the model reference hierarchy do
not rely on anything in the base workspace beyond what they explicitly
set up (for example, with a model load function).
• Copy base workspace if the software should attempt to copy the base
workspace to each worker. Specify this value if you use a setup script to
prepare the base workspace for all models to use.
• Load top model if the software should load the top model on each
worker. Specify this value if the top model in the model reference
hierarchy handles all of the base workspace setup (for example, with a
model load function).
3 Optionally, inspect the model reference hierarchy to determine, based on

model dependencies, which models will be built in parallel. For example,
you can use the Model Dependency Viewer from the Simulink Tools menu.
4 Update your model. Messages in the MATLAB command window record

when each parallel or serial build starts and finishes.
The performance gain realized by using parallel builds for updating referenced
models depends on several factors, including how many models can be built
in parallel for a given model referencing hierarchy, the size of the referenced
models, and parallel computing resources such as number of local and/or
remote workers available and the hardware attributes of the local and remote
machines (amount of RAM, number of cores, and so on).
The following notes apply to using parallel builds for updating model
reference hierarchies:
• For local pools, the host machine should have an appropriate amount of
RAM available for supporting the number of local workers (MATLAB
sessions) that you plan to use. For example, setting matlabpool to 4 results
in five MATLAB sessions on your machine, each using approximately 120
MB of memory at startup.
• Remote MDCS workers participating in a parallel build must use a common
platform and compiler.

6-43

6

Referencing a Model

• A consistent MATLAB environment must be set up in each MATLAB
worker session as in the MATLAB client session — for example, all
shared base workspace variables, MATLAB path settings, and so forth.
One approach is to use the PreLoadFcn callback of the top model. If you
configure your model to load the top model with each MATLAB worker
session, its preload function can be used for any MATLAB worker session
setup.

6-44

Simulink® Model Referencing Requirements

Simulink Model Referencing Requirements
In this section...
“About Model Referencing Requirements” on page 6-45
“Name Length Requirement” on page 6-45
“Configuration Parameter Requirements” on page 6-45
“Model Structure Requirements” on page 6-50

About Model Referencing Requirements
A model reference hierarchy must satisfy various Simulink requirements, as
described in this section. Some limitations also apply, as described in “Model
Referencing Limitations” on page 6-80.

Name Length Requirement
The name of a referenced model must contain fewer than 60 characters,
exclusive of the .slx or .mdl suffix. An error occurs if the name of a
referenced model is too long.

Configuration Parameter Requirements
A referenced model uses a configuration set in the same way that any other
model does, as described in “Manage a Configuration Set” on page 10-12. By
default, every model in a hierarchy has its own configuration set. Each model
uses its configuration set the same way that it would if the model executed
independently.
Because each model can have its own configuration set, configuration
parameter values can be different in different models. Furthermore, some
parameter values are intrinsically incompatible with model referencing. The
Simulink response to an inconsistent or unusable configuration parameter
depends on the parameter:
• Where an inconsistency has no significance, or a trivial resolution exists
that carries no risk, Simulink ignores or resolves the inconsistency without
posting a warning.

6-45

6

Referencing a Model

• Where a nontrivial and possibly acceptable solution exists, Simulink
resolves the conflict silently, resolves it with a warning, or generates an
error. See “Model configuration mismatch” for details.
• Where no acceptable resolution is possible, Simulink generates an error.
Change some or all parameter values to eliminate the problem.
Manually eliminating all configuration parameter incompatibilities can be
tedious when:
• A model reference hierarchy contains many submodels that have
incompatible parameter values
• A changed parameter value must propagate to many submodels
You can control or eliminate such overhead by using configuration references
to assign an externally stored configuration set to multiple models. See
“Manage a Configuration Reference” on page 10-18 for details.
Note Configuration parameters on the Code Generation pane of the
Configuration Parameters dialog box do not affect simulation in either
Normal or Accelerated mode. Code Generation parameters affect only code
generation by Simulink Coder itself. Accelerated mode simulation requires
code generation to create a simulation target. Simulink uses default values
for all Code Generation parameters when generating the target, and
restores the original parameter values after code generation is complete.
The tables in the following sections list Configuration parameter options
that can cause problems if set:
• In certain ways, as indicated in the table
• Differently in a referenced model than in a parent model
Where possible, Simulink resolves violations of these requirements
automatically, but most cases require changes to the parameters in some
or all models.

6-46

Simulink® Model Referencing Requirements

Configuration Requirements for All Referenced Model
Simulation
Dialog Box Pane

Option

Requirement

Solver

Start time

The start time of the
top model and all
referenced models must
be the same, but need
not be zero.

Stop time

Simulink uses Stop
time of the top
model for simulation,
overriding any differing
Stop time in a
submodel.

Type
Solver

The Type and Solver
of the top model
apply throughout the
hierarchy. See “Solver
Requirements” on page
6-48.

Data Import/Export

Initial state

Can be on for the top
model, but must be off
for a referenced model.

Optimization

Inline parameters

Can be on or off
for a top model, but
must be on for a
referenced model.
See “Inline Parameter
Requirements” on page
6-49.

Application lifespan
(days)

Must be the same for
top and referenced
models.

6-47

6

Referencing a Model

Dialog Box Pane

Option

Requirement

Model Referencing

Total number of
instances allowed
per top model

Must not be Zero in
a referenced model.
Specifying One rather
than Multiple is
preferable or required
in some cases. See
“Model Instance
Requirements” on page
6-49.

Hardware
Implementation

Embedded hardware
options

All values must be
the same for top and
referenced models.

Solver Requirements. Model referencing works with both fixed-step and
variable-step solvers. All models in a model reference hierarchy use the same
solver, which is always the solver specified by the top model. An error occurs
if the solver type specified by the top model is incompatible with the solver
type specified by any submodel.
Top Model Solver
Type

Submodel Solver
Type

Compatibility

Fixed Step

Fixed Step

Allowed

Variable Step

Variable Step

Allowed

Variable Step

Fixed-step

Allowed unless the
submodel is multi-rate
and specifies both
a discrete sample
time and a continuous
sample time

Fixed Step

Variable Step

Error

If an incompatibility exists between the top model solver and any submodel
solver, one or both models must change to use compatible solvers. For
information about solvers, see “Solvers” on page 3-21 and “Choose a Solver”
on page 14-9.

6-48

Simulink® Model Referencing Requirements

Inline Parameter Requirements. Simulink requires enabling
Configuration Parameters > Optimization > Inline parameters (see
“Inline parameters”) for all referenced models in a reference hierarchy. The
top model can enable or disable inline parameters. If a referenced model
disables inlined parameters, and you try to simulate the parent model:
• For a Normal mode submodel, Simulink generates an error and cancels the
build. All models and compiled files remain unchanged after the failed
build.
• For an Accelerator mode submodel, Simulink temporarily enables inline
parameters, posts no warning, and builds the model. Inline parameters
remain disabled after the build completes.
Simulink ignores tunable parameter specifications in the Model Parameter
Configuration dialog box for both the top model and referenced models. Do not
use this dialog box to override the inline parameters optimization for selected
parameters to permit them to be tuned. Instead, see “Parameterize Model
References” on page 6-52 for alternate techniques.
Model Instance Requirements. A referenced model must specify that it
is available to be referenced, and whether it can be referenced at most once
or can have multiple instances. The Configuration Parameters > Model
Referencing > Total number of instances allowed per top model
parameter provides this specification. See “Total number of instances allowed
per top model” for more information. The possible values for this parameter
are:
• Zero — A model cannot reference this model. An error occurs if a reference
to the model occurs in another model.
• One — A model reference hierarchy can reference the model at most once.
An error occurs if more than one instance of the model exists. This value is
sometimes preferable or required.
• Multiple — A model hierarchy can reference the model more than once, if
it contains no constructs that preclude multiple reference. An error occurs
if the model cannot be multiply referenced, even if only one reference exists.
Setting Total number of instances allowed per top model to Multiple
for a model that is referenced only once can reduce execution efficiency

6-49

6

Referencing a Model

slightly. However, this setting does not affect data values that result from
simulation or from executing code Simulink Coder generates. Specifying
Multiple when only one model instance exists avoids having to change or
rebuild the model when reusing the model:
• In the same hierarchy
• Multiple times in a different hierarchy
Some model properties and constructs require setting Total number of
instances allowed per top model to One. For details, see “General
Reusability Limitations” on page 6-81 and “Accelerator Mode Reusability
Limitations” on page 6-85.

Model Structure Requirements
The following requirements relate to the structure of a model reference
hierarchy.

Signal Propagation Requirements
The signal name must explicitly appear on any signal line connected to an
Outport block of a referenced model. A signal connected to an unlabeled line
of an Outport block of a referenced model cannot propagate out of the Model
block to the parent model.

Bus Usage Requirements
A bus that propagates between a parent model and a referenced model must be
nonvirtual. Use the same bus object to specify the properties of the bus in both
the parent and the referenced model. Define the bus object in the MATLAB
workspace. See “About Composite Signals” on page 48-2 for more information.

Sample Time Requirements
The first nonvirtual block connected to a root-level Inport or Outport block
of a referenced model must have the same sample time as the port to which
it connects. Use Rate Transition blocks to match input and output sample
times, as illustrated in the following diagram.

6-50

Simulink® Model Referencing Requirements

6-51

6

Referencing a Model

Parameterize Model References
In this section...
“Introduction” on page 6-52
“Global Nontunable Parameters” on page 6-53
“Global Tunable Parameters” on page 6-53
“Using Model Arguments” on page 6-53

Introduction
A parameterized referenced model obtains values that affect the behavior of
the referenced model from some source outside the model. Changing the
values changes the behavior of the model, without recompiling the model.
Due to the constraints described in “Inline Parameter Requirements” on
page 6-49, you cannot use the Model Parameter Configuration dialog box to
parameterize referenced models. Simulink provides three other techniques
that you can use to parameterize referenced models:
• Global nontunable parameters
• Global tunable parameters
• Model arguments
Global parameters work the same way with referenced models that they do
with any other model construct. Each global parameter has the same value
in every instance of a referenced model that uses it. Model arguments allow
you to provide different values to each instance of a referenced model. Each
instance can then behave differently from the others. The effect is analogous
to calling a function more than once with different arguments in each call.
You can use a structure parameter to group variables for parameterizing
model references. For details, see “Structure Parameters” on page 24-16.

6-52

Parameterize Model References

Global Nontunable Parameters
A global nontunable parameter is a MATLAB variable or a
Simulink.Parameter object whose storage class is auto. The parameter must
exist in the MATLAB workspace.
Using a global nontunable parameter in a referenced model sets the
parameter value before the simulation begins. This allows you to control the
behavior of the referenced model. All instances of the model use the same
value. You cannot change the value during simulation, but you can change
it between one simulation and the next. The change requires rebuilding the
model in which the change occurs, but not any models that it references. See
“Specify Parameter Values” on page 24-6 for details.

Global Tunable Parameters
A global tunable parameter is a Simulink.Parameter object whose storage
class is other than auto. The parameter exists in the MATLAB workspace.
Using a global tunable parameter in a referenced model allows you to control
the behavior of the referenced model by setting the parameter value. All
instances of the model use the same value. You can change the value during
simulation or between one simulation and the next. The change does not
require rebuilding the model in which the change occurs, or any models that
it references. See “Tunable Parameters” on page 24-13 for details.
To reference a model that uses tunable parameters defined with the “Model
Parameter Configuration Dialog Box”, change the model to implement
tunability another way. To facilitate this task, Simulink provides a
command that converts tunable parameters specified in the Model
Parameter Configuration dialog box to global tunable parameters. See
tunablevars2parameterobjects for details.

Using Model Arguments
Model arguments let you parameterize references to the same model so that
each instance of the model behaves differently. Without model arguments, a
variable in a referenced model has the same value in every instance of the
model. Declaring a variable to be a model argument allows each instance of
the model to use a different value for that variable.

6-53

6

Referencing a Model

To create model arguments for a referenced model:
1 Create MATLAB variables in the model workspace.
2 Add the variables to a list of model arguments associated with the model.
3 Specify values for those variables separately in each Model block that

references the model
The values specified in the Model block replace the values of the MATLAB
variables for that instance of the model.
A referenced model that uses model arguments can also appear as a top model
or a standalone model. No Model block then exists to provide model argument
values. The model uses the values of the MATLAB variables themselves, as
defined in the model workspace. Thus, you can use the same model without
change as a top model, a standalone model, and a parameterized referenced
model.
The sldemo_mdlref_datamngt model demonstrates techniques for using
model arguments. The model passes model argument values to referenced
models through masked Model blocks. Such masking can be convenient, but
is independent of the definition and use of model arguments themselves. See
“Masking” for information about masking.
The rest of this section describes techniques for declaring and using model
arguments to parameterize a referenced model independently of any Model
block masking. The steps are:
• Create MATLAB variables in the model workspace.
• Register the variables to be model arguments.
• Assign values to those arguments in Model blocks.

Creating the MATLAB Variables
To create MATLAB variables for use as model arguments:
1 Open the model for which you want to define model arguments.
2 Open the Model Explorer.

6-54

Parameterize Model References

3 In the Model Explorer Model Hierarchy pane, select the workspace

of the model:

4 From Model Explorer’s Add menu, select MATLAB Variable.

A new MATLAB variable appears in the Contents pane with a default
name and value.
5 In the Contents pane:
a Change the default name of the new MATLAB variable to a name that

you want to declare as a model argument.
b If you also use the model as a top or standalone model, specify the value

for that variable for use in that context. This value must be numeric.
c If the variable type does not match the dimensions and complexity of

the model argument, specify a value that has the correct type. This
type must be numeric.
6 Repeat adding and naming MATLAB variables until you have defined all

the variables that you need.

Register the Model Arguments
To register MATLAB variables as model arguments:
1 Again, in the Model Explorer Model Hierarchy pane, select the workspace

of the model.

6-55

6

Referencing a Model

The Dialog pane displays the Model Workspace dialog.
2 In the Model Workspace dialog, enter the names of the MATLAB variables

that you want to declare as model arguments. Use a comma-separated
list in the Model arguments field.
For example, suppose you added two MATLAB variables named
init_value and incr, and you declared them to be model arguments. The
Contents and Dialog panes of the Model Explorer could look like this:

3 Click Apply to confirm the entered names.

Assign Model Argument Values
If a model declares model arguments, assign values to those arguments in
each Model block that references the model. Failing to assign a value to a
model argument causes an error: the value of the model argument does not
default to the value of the corresponding MATLAB variable. That value is
available only to a standalone or top model. To assign values to the arguments
of a referenced model:
1 Open the block parameters dialog box of the Model block by right-clicking

the block and choosing Block Parameters (ModelReference) from the
context menu.

6-56

Parameterize Model References

The second field, Model arguments, specifies the same MATLAB
variables, in the same order, that you previously typed into the Model

6-57

6

Referencing a Model

arguments field of the Model Workspace dialog. This field is not editable.
It provides a reminder of which model arguments need values assigned,
and in what order.
2 In the Model argument values field, enter a comma-delimited list of

values for the model arguments that appear in the Model arguments
field. Simulink assigns the values to arguments in positional order, so they
must appear in the same order as the corresponding arguments.
You can enter the values as literal values, variable names, MATLAB
expressions, and Simulink parameter objects. Any symbols used resolve to
values as described in “Symbol Resolution Process” on page 4-76. All values
must be numeric (including objects with numeric values).
Note Simulink generates an error if you use a model argument in an
expression that is nontunable because of “Tunable Expression Limitations”.
The value for each argument must have the same dimensions and
complexity as the MATLAB variable that defines the model argument in
the model workspace. The data types need not match. If necessary, the
Simulink software casts a model argument value to the data type of the
corresponding variable.
3 Click OK or Apply to confirm the values for the Model block.

When the model executes in the context of that Model block, the Model
arguments have the values specified in the Model argument values field
of the Model block.

6-58

Conditional Referenced Models

Conditional Referenced Models
In this section...
“Kinds of Conditional Referenced Models” on page 6-59
“Working with Conditional Referenced Models” on page 6-60
“Create Conditional Models” on page 6-61
“Reference Conditional Models” on page 6-63
“Simulate Conditional Models” on page 6-64
“Generate Code for Conditional Models” on page 6-64
“Requirements for Conditional Models” on page 6-65

Kinds of Conditional Referenced Models
You can set up referenced models so that they execute conditionally, similar
to conditional subsystems. For information about conditional subsystems, see
“About Conditional Subsystems” on page 7-2.
You can use the following kinds of conditionally executed referenced models:
• Enabled
• Triggered
• Enabled and triggered
• Function-call

Enabled Models
Use an Enable block to insert an enable port in a model. Add an enable port
to a model if you want a referenced model to execute at each simulation step
for which the control signal has a positive value.
To see an example of an enabled subsystem, see enablesub. A corresponding
enabled referenced model would use the same blocks as are in the enabled
subsystem.

6-59

6

Referencing a Model

Triggered Models
Use a Trigger block to insert a trigger port in a model. Add a trigger port to a
model if you want to use an external signal to trigger the execution of that
model. You can add a trigger port to a root-level model or to a subsystem.
This section focuses on models that contain a trigger port with an edge-based
trigger type (rising, falling, or either).
To view a model that illustrates how you can use trigger ports in referenced
models, see the Introduction to Managing Data with Model Reference
example. In that example, see the “Top Model: Scheduling Calls to the
Referenced Model” section.

Triggered and Enabled Models
A triggered and enabled model executes once at the time step for which a
trigger event occurs, if the enable control signal has a positive value at that
step.

Function-Call Models
Simulink allows certain blocks to control execution of a referenced model
during a time step, using a function-call signal. Examples of such blocks are a
Function-Call Generator or an appropriately configured custom S-function.
See “Function-Call Subsystems” on page 7-30 for more information. A
referenced model that you can invoke in this way is a function-call model.
For an example of a function-call model, see the sldemo_mdlref_fcncall
model.

Working with Conditional Referenced Models
Use a similar approach for each kind of conditionally executed referenced
model for these tasks:
• “Create Conditional Models” on page 6-61
• “Reference Conditional Models” on page 6-63
• “Simulate Conditional Models” on page 6-64
• “Generate Code for Conditional Models” on page 6-64

6-60

Conditional Referenced Models

Each kind of conditionally executed model has some model creating
requirements. For details, see “Requirements for Conditional Models” on
page 6-65.

Create Conditional Models
To create a conditional model:
1 At the root level of the referenced model, insert one of the following blocks:

Kind of Model

Blocks to Insert

Enabled

Enable

Triggered

Trigger

Triggered and Enabled

Trigger and Enable

Function-Call

Trigger

For an enabled model, go to Step 3.
2 For the Trigger block, set the Trigger type parameter, based on the kind

of model:
Kind of Model

Trigger Type Parameter Setting

Triggered

One of the following:

Triggered and enabled

• rising
• falling
• either

Function-Call

function-call

3 Create and connect other blocks to implement the model.

Enabled model example:

6-61

6

Referencing a Model

Triggered model example:

Function-call model example:

6-62

Conditional Referenced Models

4 Ensure that the model satisfies the requirements for a conditional model.

See the appropriate section:
• “Enabled Model Requirements” on page 6-65
• “Triggered Model Requirements” on page 6-65
• “Function-Call Model Requirements” on page 6-65

Reference Conditional Models
To create a reference to a conditional model:
1 Add a Model block to the model that you want to reference the triggered

model. See “Create a Model Reference” on page 6-8 for details.
The top of the Model block displays an icon that corresponds to the kind of
port used in the referenced model. For example, for a triggered model, the
top of the Model block displays the following icon.

For enabled, triggered, and triggered and enabled models, go to Step 3.
2 For a function-call model, connect a Stateflow chart, Function-Call

Generator block, or other function-call-generating block to the function-call
port of the Model block. The signal connected to the port must be scalar.

6-63

6

Referencing a Model

3 Create and connect other blocks to implement the parent model.
4 Ensure that the referencing model satisfies the conditions for model

referencing. See “Simulink Model Referencing Requirements” on page 6-45
and “Model Referencing Limitations” on page 6-80 for details.

Simulate Conditional Models
Use Normal, Accelerator, or Rapid Accelerator mode to simulate a conditional
model.
You can run a standalone simulation of a referenced model. A standalone
simulation is useful for unit testing, because it provides consistent data
across simulations, in terms of data type, dimension, and sample time. In
the Trigger or Enable block, in the Signal Attributes pane of the Block
Parameters dialog box, specify values to lock down the signal data type,
dimension, and sample time.
To run a standalone simulation of a conditional model, specify the inputs
using the Configuration Parameters > Data Import/Export > Input
parameter. The following conditions apply when you use the “Input”
parameter for trigger and enable port inputs:
• Use the last data input for the trigger or enable input. For a triggered and
enabled model, use the last data input for the trigger input.
• If you do not provide any input values, the simulation uses zero as the
default values.
For details about how to specify the input, see “Techniques for Importing
Signal Data” on page 45-61.
You can log data to determine which signal caused the model to run. For the
Trigger or Enable block, in the Main pane of the Block Parameters dialog box,
select Show output port.

Generate Code for Conditional Models
You can build model reference Simulink Coder and SIM targets for referenced
models that contain a trigger or enable port. You cannot generate standalone
Simulink Coder or PIL code. For information about code generation for

6-64

Conditional Referenced Models

referenced models, see “Reusable Code and Referenced Models” and “Generate
Code for Referenced Models”.

Requirements for Conditional Models
Conditional models must meet the requirements for:
• Conditional subsystems (see “Conditional Subsystems”)
• Referenced models (see “Simulink Model Referencing Requirements” on
page 6-45)
In addition, conditional models must meet the requirements described below.

Enabled Model Requirements
• Multi-rate enabled models cannot use multi-tasking solvers. You must
use single-tasking.
• For models with enable ports at the root, if the model uses a fixed-step
solver, the fixed-step size of the model must not exceed the rate for any
block in the model.
• The signal attributes of the enable port in the referenced model must be
consistent with the input that the Model block provides to that enable port.

Triggered Model Requirements
The signal attributes of the trigger port in the referenced model must be
consistent with the input that the Model block provides to that trigger port.

Function-Call Model Requirements
• A function-call model cannot have an outport driven only by Ground
blocks, including hidden Ground blocks inserted by Simulink. To meet
this requirement, do the following:
1 Insert a Signal Conversion block into the signal connected to the outport.
2 Enable the Exclude this block from ’Block reduction’ optimization

option of the inserted block.

6-65

6

Referencing a Model

• The referencing model must trigger the function-call model at the rate
specified by the Configuration Parameters > Solver 'Fixed-step
size' option if the function-call model meets both these conditions:

-

It specifies a fixed-step solver
It contains one or more blocks that use absolute or elapsed time

Otherwise, the referencing model can trigger the function-call model at
any rate.
• A function-call model must not have direct internal connections between its
root-level input and output ports. Simulink does not honor the None and
Warning settings for the Invalid root Inport/Outport block connection
diagnostic for a referenced function-call model. It reports all invalid root
port connections as errors.
• If the Sample time type is periodic, the sample-time period must not
contain an offset.
• The signal connected to a function-call port of a Model block must be scalar.

6-66

Protected Model

Protected Model
A protected model provides the ability to deliver a model without revealing
the intellectual property of the model. A protected model is a referenced
model that hides all block and line information. It does not use encryption
technology. Creating a protected model requires a Simulink Coder license.
However, you can simulate a protected model with only a Simulink license. A
third party that receives a protected model must match the platform and the
version of Simulink for which the protected model was generated.
You cannot view the contents of a protected model, therefore you cannot log
signals in a protected model. Protected models do not appear in the model
hierarchy in the Model Explorer.
Simulating a protected model requires that the protected model:
• Be available somewhere on the MATLAB path.
• Be referenced by a Model block in a model that executes in Normal or
Accelerator mode. To run in Accelerator mode, the protected model must
include code generation capabilities.
• Receives from the Model block the values needed by any defined model
arguments.
• Connects via the Model block to input and output signals that match the
input and output signals of the protected model.
To locate protected models in your model:
• The MATLAB Folder Browser shows a small image of a lock on the node
for the protected model file.
• A Model block that references a protected model shows a small image of a
shield in the lower left corner of the Model block.
For more information, see “Use Protected Model in Simulation” on page
6-68. For more information about creating protected referenced models, see
“Protect a Referenced Model”.

6-67

6

Referencing a Model

Use Protected Model in Simulation
When you receive a protected model it might be included in a protected model
package. The package could include additional files, such as a harness model
and a MAT-file. A protected model file has an .slxp extension. A typical
workflow for using a protected model in a simulation is:
1 If necessary, unpack the files according to any accompanying directions.
2 If there is a MAT-file containing workspace definitions, load that MAT-file.
3 If there is a harness model, copy the Model block referencing the protected

model into your model.
4 If a protected model report was generated when the protected model was

created, double-click the Model block to open it. In the Summary of the
report, check that your Simulink version and platform match the software
and platform used to create the protected model.
5 Connect signals to the Model block that match its input and output port

requirements.
6 Provide any needed model argument values. See “Assign Model Argument

Values” on page 6-56.
There are also other ways to include the protected model into your model:
• Use your own Model block rather than the Model block in the harness
model.
Note When you change a Model block to reference a protected model,
the Simulation mode of the block becomes Accelerator. You cannot
change the mode.
• Start with the harness model, add more constructs to it, and use it in
your model.
• Use the protected model as a variant in a Model Variant block, as described
in “Set Up Model Variants” on page 8-5.

6-68

Use Protected Model in Simulation

• Apply a mask to the Model block that references the protected model. See
“Masking”.
• Configure a callback function, such as LoadFcn, to load the MAT-file
automatically. See “Callback Functions” on page 4-54.
Now you can simulate the model that includes the protected model. Because
the protected model is set to Accelerator mode, the simulation produces the
same outputs that it did when used in Accelerator mode in the source model.

6-69

6

Referencing a Model

Inherit Sample Times
In this section...
“How Sample-Time Inheritance Works for Model Blocks” on page 6-70
“Conditions for Inheriting Sample Times” on page 6-70
“Determining Sample Time of a Referenced Model” on page 6-71
“Blocks That Depend on Absolute Time” on page 6-71
“Blocks Whose Outputs Depend on Inherited Sample Time” on page 6-73

How Sample-Time Inheritance Works for Model
Blocks
The sample times of a Model block are the sample times of the model that
it references. If the referenced model must run at specific rates, the model
specifies the required rates. Otherwise, the referenced model inherits its
sample time from the parent model.
Placing a Model block in a triggered, function call, or iterator subsystem relies
on the ability to inherit sample times. Additionally, allowing a Model block
to inherit sample time maximizes its reuse potential. For example, a model
might fix the data types and dimensions of all its input and output signals.
You could reuse the model with different sample times (for example, discrete
at 0.1 or discrete at 0.2, triggered, and so on).

Conditions for Inheriting Sample Times
A referenced model inherits its sample time if the model:
• Does not have any continuous states
• Specifies a fixed-step solver and the Fixed-step size is auto
• Contains no blocks that specify sample times (other than inherited or
constant)
• Does not contain any S-functions that use their specific sample time
internally

6-70

Inherit Sample Times

• Has only one sample time (not counting constant and triggered sample
time) after sample time propagation
• Does not contain any blocks, including Stateflow charts, that use absolute
time, as listed in “Blocks That Depend on Absolute Time” on page 6-71
• Does not contain any blocks whose outputs depend on inherited sample
time, as listed in “Blocks Whose Outputs Depend on Inherited Sample
Time” on page 6-73.
You can use a referenced model that inherits its sample time anywhere in
a parent model. By contrast, you cannot use a referenced model that has
intrinsic sample times in a triggered, function call, or iterator subsystem. To
avoid rate transition errors, ensure that blocks connected to a referenced
model with intrinsic samples times operate at the same rates as the
referenced model.

Determining Sample Time of a Referenced Model
To determine whether a referenced model can inherit its sample time, set the
Periodic sample time constraint on the Solver configuration parameters
dialog pane to Ensure sample time independent. If the model is unable
to inherit sample times, this setting causes Simulink to display an error
message when building the model. See “Periodic sample time constraint”
for more about this option.
To determine the intrinsic sample time of a referenced model, or the fastest
intrinsic sample time for multirate referenced models:
1 Update the model that references the model
2 Select a Model block within the parent model
3 Enter the following at the MATLAB command line:
get_param(gcb, 'CompiledSampleTime')

Blocks That Depend on Absolute Time
The following Simulink blocks depend on absolute time, and therefore
preclude a referenced model from inheriting sample time:

6-71

6

Referencing a Model

• Backlash (only when the model uses a variable-step solver and the block
uses a continuous sample time)
• Chirp Signal
• Clock
• Derivative
• Digital Clock
• Discrete-Time Integrator (only when used in triggered subsystems)
• From File
• From Workspace
• Pulse Generator
• Ramp
• Rate Limiter
• Repeating Sequence
• Signal Generator
• Sine Wave (only when the Sine type parameter is Time-based)
• Stateflow (only when the chart uses the reserved word t to reference time)
• Step
• To File
• To Workspace (only when logging to Timeseries or Structure With Time
format)
• Transport Delay
• Variable Time Delay
• Variable Transport Delay
Some blocks other than Simulink blocks depend on absolute time. See the
documentation for the blocksets that you use.

6-72

Inherit Sample Times

Blocks Whose Outputs Depend on Inherited Sample
Time
Using a block whose output depends on an inherited sample time in a
referenced model can cause simulation to produce unexpected or erroneous
results. For this reason, when building a submodel that does not need to
run at a specified rate, Simulink checks whether the model contains any
blocks whose outputs are functions of the inherited simulation time. This
includes checking S-Function blocks. If Simulink finds any such blocks,
it specifies a default sample time. Simulink displays an error if you have
set the Configuration Parameters > Solver > Periodic sample time
constraint to Ensure sample time independent. See “Periodic sample time
constraint” for more about this option.
The outputs of the following built-in blocks depend on inherited sample time.
The outputs of these blocks preclude a referenced model from inheriting its
sample time from the parent model:
• Discrete-Time Integrator
• From Workspace (if it has input data that contains time)
• Probe (if probing sample time)
• Rate Limiter
• Sine Wave
Simulink assumes that the output of an S-function does not depend on
inherited sample time unless the S-function explicitly declares the contrary.
See “Sample Times” for information on how to create S-functions that declare
whether their output depends on their inherited sample time.
To avoid simulation errors with referenced models that inherit their sample
time, do not include S-functions in the referenced models that fail to declare
whether their output depends on their inherited sample time. By default,
Simulink warns you if your model contains such blocks when you update or
simulate the model. See “Unspecified inheritability of sample time” for details.

6-73

6

Referencing a Model

Refresh Model Blocks
Refreshing a Model block updates its internal representation to reflect
changes in the interface of the model that it references.
Examples of when to refresh a Model block include:
• Refresh a Model block that references model that has gained or lost a port.
• Refresh all the Model blocks that reference a model whose interface has
changed.
You do not need to refresh a Model block if the changes to the interface of the
referenced model do not affect how the referenced model interfaces to its
parent.
To update a specific Model block, from the context menu of the Model block,
select Diagram > Subsystem & Model Reference > Refresh Selected
Model Block.
To refresh all Model blocks in a model (as well as linked blocks in a library or
model), in the Simulink Editor select Diagram > Refresh Blocks. You can
also refresh a model by starting a simulation or generating code.
You can use Simulink diagnostics to detect changes in the interfaces of
referenced models that could require refreshing the Model blocks that
reference them. The diagnostics include:
• Model block version mismatch
• Port and parameter mismatch

6-74

S-Functions with Model Referencing

S-Functions with Model Referencing
In this section...
“S-Function Support for Model Referencing” on page 6-75
“Sample Times” on page 6-75
“S-Functions with Accelerator Mode Referenced Models” on page 6-76
“Using C S-Functions in Normal Mode Referenced Models” on page 6-77
“Protected Models” on page 6-77
“Simulink® Coder™ Considerations” on page 6-77

S-Function Support for Model Referencing
Each kind of S-function provides its own level of support for model referencing.
Type of S-Function

Support for Model Referencing

Level-1 MATLAB
S-function

Not supported

Level-2 MATLAB
S-function

• Supports Normal and Accelerator mode

Handwritten C MEX
S-function

• Supports Normal and Accelerator mode

S-Function Builder

Supports Normal and Accelerator mode

Legacy Code Tool

Supports Normal and Accelerator mode

• Accelerator mode requires a TLC file
• May be inlined with TLC file

Sample Times
Simulink software assumes that the output of an S-function does not depend
on an inherited sample time unless the S-function explicitly declares a
dependence on an inherited sample time.
You can control inheriting sample time by using
ssSetModelReferenceSampleTimeInheritanceRule in different ways,

6-75

6

Referencing a Model

depending on whether an S-function permits or precludes inheritance. For
details, see “Inherited Sample Time for Referenced Models”.

S-Functions with Accelerator Mode Referenced
Models
For a referenced model that executes in Accelerator mode, set the
Configuration Parameters > Model Referencing > Total number of
instances allowed per top model to One if the model contains an S-function
that is either:
• Inlined, but has not set the SS_OPTION_WORKS_WITH_CODE_REUSE flag
• Not inlined

Inlined S-Functions with Accelerator Mode Referenced Models
For Accelerator mode referenced models, if the referenced model
contains an S-function that should be inlined using a Target Language
Compiler file, the S-function must use the ssSetOptions macro to set the
SS_OPTION_USE_TLC_WITH_ACCELERATOR option in its mdlInitializeSizes
method. The simulation target does not inline the S-function unless the
S-function sets this option.
A referenced model cannot use noninlined S-functions in the following cases:
• The model uses a variable-step solver.
• Simulink Coder generated the S-function.
• The S-function supports use of fixed-point numbers as inputs, outputs,
or parameters.
• The model is referenced more than once in the model reference hierarchy.
To work around this limitation, use Normal mode.
• The S-function uses string parameters.

6-76

S-Functions with Model Referencing

Using C S-Functions in Normal Mode Referenced
Models
Under certain conditions, when a C S-function appears in a referenced model
that executes in Normal mode, successful execution is impossible. For details,
see “S-Functions in Normal Mode Referenced Models”.
Use the ssSetModelReferenceNormalModeSupport SimStruct function to
specify whether an S-function can be used in a Normal mode referenced model.
You may need to modify S-functions that are used by a model so that the
S-functions work with multiple instances of referenced models in Normal
mode. The S-functions must indicate explicitly that they support multiple
exec instances. For details, see “Supporting the Use of Multiple Instances
of Referenced Models That Are in Normal Mode”.

Protected Models
A protected model cannot use non-inlined S-functions directly or indirectly.

Simulink Coder Considerations
A referenced model in Accelerator mode cannot use S-functions generated by
the Simulink Coder software.
Noninlined S-functions in referenced models are supported when generating
Simulink Coder code.
The Simulink Coder S-function target does not support model referencing.
For general information about using Simulink Coder and model referencing,
see “Model Reference”.

6-77

6

Referencing a Model

Buses in Referenced Models
To have bus data cross model reference boundaries, use a nonvirtual bus. Use
a bus object (Simulink.Bus) to define the bus.
For an example of a model referencing model that uses buses, see
sldemo_mdref_bus. For more information, see “Bus Data Crossing Model

Reference Boundaries” on page 48-93.

6-78

Signal Logging in Referenced Models

Signal Logging in Referenced Models
In a referenced model, you can log any signal configured for signal logging.
Use the Signal Logging Selector to select a subset or all of the signals
configured for signal logging for a model reference hierarchy. For details, see
“Models with Model Referencing: Overriding Signal Logging Settings” on
page 45-45.

6-79

6

Referencing a Model

Model Referencing Limitations
In this section...
“Introduction” on page 6-80
“Limitations on All Model Referencing” on page 6-80
“Limitations on Normal Mode Referenced Models” on page 6-83
“Limitations on Accelerator Mode Referenced Models” on page 6-84
“Limitations on PIL Mode Referenced Models” on page 6-87

Introduction
The following limitations apply to model referencing. In addition, a model
reference hierarchy must satisfy all the requirements listed in “Simulink
Model Referencing Requirements” on page 6-45.

Limitations on All Model Referencing
Index Base Limitations
In two cases, Simulink does not propagate 0-based or 1-based indexing
information to referenced-model root-level ports connected to blocks that:
• Accept indexes (such as the Assignment block)
• Produce indexes (such as the For Iterator block)
An example of a block that accepts indexes is the Assignment block. An
example of a block that produces indexes is the For Iterator block.
The two cases result in a lack of propagation that can cause Simulink to fail
to detect incompatible index connections. These two cases are:
• If a root-level input port of the referenced model connects to index inputs
in the model that have different 0-based or 1-based indexing settings,
Simulink does not set the 0-based or 1-based indexing property of the
root-level Inport block.

6-80

Model Referencing Limitations

• If a root-level output port of the referenced model connects to index outputs
in the model that have different 0-based or 1-based indexing settings,
Simulink does not set the 0-based or 1-based indexing property of the
root-level Outport block.

General Reusability Limitations
If a referenced model has any of the following characteristics, the model
must specify Configuration Parameters > Model Referencing > Total
number of instances allowed per top model as One. No other instances
of the model can exist in the hierarchy. An error occurs if you do not set the
parameter correctly, or if more than one instance of the model exists in the
hierarchy. The model characteristics that require that the Total number of
instances allowed per top model setting be One are:
• The model contains any To File blocks
• The model references another model which is set to single instance
• The model contains a state or signal with non-auto storage class
• The model uses any of the following Stateflow constructs:

-

Stateflow graphical functions
Machine-parented data

Block Mask Limitations
• Mask callbacks cannot add Model blocks. Also, mask callbacks cannot
change the Model block name or simulation mode. These invalid callbacks
generate an error.
• If a mask specifies the name of the model that a Model block references, the
mask must provide the name of the referenced model directly. You cannot
use a workspace variable to provide the name.
• The mask workspace of a Model block is not available to the model that the
Mask block references. Any variable that the referenced model uses must
resolve to either of these workspaces:

-

A workspace that the referenced model defines
The MATLAB base workspace

6-81

6

Referencing a Model

For information about creating and using block masks, see “Masking”.

Simulink Tool Limitations
Working with the Simulink Debugger in a parent model, you can set
breakpoints at Model block boundaries. Setting those breakpoints allows
you to look at the input and output values of the Model block. However, you
cannot set a breakpoint inside the model that the Model block references. See
“Debugging” for more information.

Stateflow Limitations
You cannot reference a model multiple times in the same model reference
hierarchy if that model that contains a Stateflow chart that:
• Contains exported graphical functions
• Is part of a Stateflow model that contains machine-parented data

Subsystem Limitations
• You cannot place a Model block in an iterator subsystem, if the Model block
references a model that contains Assignment blocks that are not in an
iterator subsystem.
• In a configurable subsystem with a Model block, during model update, do
not change the subsystem that the configurable subsystem selects.

Other Limitations
• Referenced models can only use asynchronous rates if the model meets
both of these conditions:

-

An external source drives the asynchronous rate through a root-level
Inport block.

-

The root-level Inport block outputs a function-call signal. See
Asynchronous Task Specification.

• A referenced model can input or output only those user-defined data types
that are fixed-point or that Simulink.DataType or Simulink.Bus objects
define.

6-82

Model Referencing Limitations

• To initialize the states of a model that references other models with states,
specify the initial states in structure or structure with time format. For
more information, see “Import and Export State Information for Referenced
Models” on page 45-120.
• A referenced model cannot directly access the signals in a multi-rate
bus. To overcoming this limitation, see Connecting Multi-Rate Buses to
Referenced Models.
• A continuous sample time cannot be propagated to a Model block that is
sample-time independent.
• Goto and From blocks cannot cross model reference boundaries.
• You cannot print a referenced model from a top model.
• To use a masked subsystem in a referenced model that uses model
arguments, do not create in the mask workspace a variable that derives
its value from a mask parameter. Instead, use blocks under the masked
subsystem to perform the calculations for the mask workspace variable.

Limitations on Normal Mode Referenced Models
Normal Mode Visibility for Multiple Instances of a Referenced
Model
You can simulate a model that has multiple instances of a referenced model
that are in Normal mode. All of the instances of the referenced model are
part of the simulation. However, Simulink displays only one of the instances
in a model window. The Normal Mode Visibility setting determines which
instance Simulink displays. Normal Mode Visibility includes the display of
Scope blocks and data port values.
To set up your model to control which instance of a referenced model in
Normal mode has visibility and to ensure proper simulation of the model, see
“Set Up a Model with Multiple Instances of a Referenced Model in Normal
Mode” on page 6-28.

Simulink Profiler
In Normal mode, enabling the Simulink Profiler on a parent model does not
enable profiling for referenced models. You must enable profiling separately
for each referenced model. See “Capture Performance Data” on page 22-31.

6-83

6

Referencing a Model

Limitation with Sim Viewing Devices in Rapid Accelerator Mode
When set to Normal mode, a Model block with a sim viewing device is not
updated during Rapid Accelerator simulation.

Limitations on Accelerator Mode Referenced Models
Subsystem Limitations
If you generate code for an atomic subsystem as a reusable function, when you
use Accelerator mode, the inputs or outputs that connect the subsystem to a
referenced model can affect code reuse. See “Reusable Code and Referenced
Models” for details.

Simulink Tool Limitations
Simulink tools that require access to the internal data or the configuration
of a model have no effect on referenced models executing in Accelerator
mode. Specifications made and actions taken by such tools are ignored
and effectively do not exist. Examples of tools that require access to model
internal data or configuration include:
• Model Coverage
• Simulink Report Generator
• Simulink Debugger
• Simulink Profiler

Runtime Checks
Some blocks include runtime checks that are disabled when you include the
block in a referenced model in Accelerator mode. Examples of these blocks
include Assignment, Selector, and MATLAB Function blocks)

Data Logging Limitations
The following logging methods have no effect when specified in referenced
models executing in Accelerator mode:
• To Workspace blocks (for formats other than Timeseries)

6-84

Model Referencing Limitations

• Scope blocks
• All types of runtime display, such as Port Values Display
During simulation, the result is the same as if the constructs did not exist.

Accelerator Mode Reusability Limitations
You must set Configuration Parameters > Model Referencing > Total
number of instances allowed per top model to One for a referenced model
that executes in Accelerator mode and has any of the following characteristics:
• A subsystem that is marked as function
• An S-function that is:

-

Inlined but has not set the option SS_OPTION_WORKS_WITH_CODE_REUSE
Not inlined

• A function-call subsystem that:

-

Has been forced by Simulink to be a function
Is called by a wide signal

An error occurs in either of these cases:
• You do not set the parameter correctly.
• Another instances of the model exists in the hierarchy, in either Normal
mode or Accelerator mode

Customization Limitations
• For restrictions that apply to grouped custom storage classes in referenced
models in Accelerator mode, see “Custom Storage Class Limitations”.
• Simulation target code generation for referenced models in Accelerator
mode does not support data type replacement.

6-85

6

Referencing a Model

S-Function Limitations
• If a referenced model in Accelerator mode contains an S-function that should
be inlined using a Target Language Compiler file, the S-function must use
the ssSetOptions macro to set the SS_OPTION_USE_TLC_WITH_ACCELERATOR
option in its mdlInitializeSizes method. The simulation target does not
inline the S-function unless the S-function sets this option.
• You cannot use the Simulink Coder S-function target in a referenced model
in Accelerator mode.
• A referenced model in Accelerator mode cannot use noninlined S-functions
in the following cases:

-

The model uses a variable-step solver.

-

The S-function uses string parameters.

Simulink Coder generated the S-function.
The S-function supports use of fixed-point numbers as inputs, outputs,
or parameters.
The model is referenced more than once in the model reference hierarchy.
To work around this limitation:
1 Make copies of the referenced model.
2 Assign different names to the copies.
3 Reference a different copy at each location that needs the model.

MATLAB Function Block Limitation
A MATLAB Function block in a referenced model that executes in Accelerator
mode cannot call MATLAB functions.

Stateflow Limitation
A Stateflow chart in a referenced model that executes in Accelerator mode
cannot call MATLAB functions.

Target Limitations
• The Simulink Coder grt_malloc targets do not support model referencing.

6-86

Model Referencing Limitations

• The Simulink Coder S-function target does not support model referencing.

Other Limitations
• When you create a model, you cannot use that model as an Accelerator
mode referenced model until you have saved the model to disk. You can
work around this limitation by setting the model to Normal mode. See
“Specify the Simulation Mode” on page 6-23.
• When the sim command executes a referenced model in Accelerator mode,
the source workspace is always the MATLAB base workspace.
• Accelerator mode does not support the External mode option. If you
enable the External mode option, Accelerator mode ignores it.

Limitations on PIL Mode Referenced Models
• Only one branch (top model and all subordinates) in a model reference
hierarchy can execute in PIL mode.
• If you create a model, you cannot use that model as a PIL mode referenced
model until you have saved the model to disk. To work around this
limitation, set the model to Normal mode. See “Specify the Simulation
Mode” on page 6-23.
For more information about using PIL mode with model referencing, see
“Model Reference” in the Embedded Coder documentation.

6-87

6

6-88

Referencing a Model

7
Creating Conditional
Subsystems
• “About Conditional Subsystems” on page 7-2
• “Enabled Subsystems” on page 7-4
• “Triggered Subsystems” on page 7-20
• “Triggered and Enabled Subsystems” on page 7-24
• “Function-Call Subsystems” on page 7-30
• “Conditional Execution Behavior” on page 7-32

7

Creating Conditional Subsystems

About Conditional Subsystems
A subsystem is a set of blocks that have been replaced by a single block called
a Subsystem block. This chapter describes a special kind of subsystem for
which execution can be externally controlled. For information that applies to
all subsystems, see “Create a Subsystem” on page 4-36.
A conditional subsystem, also known as a conditionally executed subsystem, is
a subsystem whose execution depends on the value of an input signal. The
signal that controls whether a subsystem executes is called the control signal.
The signal enters a subsystem block at the control input.
Conditional subsystems can be very useful when you are building complex
models that contain components whose execution depends on other
components. Simulink supports the following types of conditional subsystems:
• An enabled subsystem executes while the control signal is positive. It starts
execution at the time step where the control signal crosses zero (from
the negative to the positive direction) and continues execution as long as
the control signal remains positive. For a more detailed discussion, see
“Enabled Subsystems” on page 7-4.
• A triggered subsystem executes once each time a trigger event occurs. A
trigger event can occur on the rising or falling edge of a trigger signal,
which can be continuous or discrete. For more information about triggered
subsystems, see “Triggered Subsystems” on page 7-20.
• A triggered and enabled subsystem executes once at the time step for which
a trigger event occurs if the enable control signal has a positive value at
that step. See “Triggered and Enabled Subsystems” on page 7-24 for more
information.
• A control flow subsystem executes one or more times at the current time
step when enabled by a control flow block. A control flow block implements
control logic similar to that expressed by control flow statements of
programming languages (e.g., if-then, while, do, and for). See “Control
Flow Logic” on page 4-44 for more information.

7-2

About Conditional Subsystems

Note The Simulink software imposes restrictions on connecting blocks
with a constant sample time to the output port of a conditional subsystem.
See “Using Blocks with Constant Sample Times in Enabled Subsystems”
on page 7-15 for more information.
For examples of conditional subsystems, see:
• Simulink Subsystem Semantics
• Triggered Subsystems
• Enabled Subsystems
• Advanced Enabled Subsystems

7-3

7

Creating Conditional Subsystems

Enabled Subsystems
In this section...
“What Are Enabled Subsystems?” on page 7-4
“Creating an Enabled Subsystem” on page 7-5
“Blocks that an Enabled Subsystem Can Contain” on page 7-11
“Using Blocks with Constant Sample Times in Enabled Subsystems” on
page 7-15

What Are Enabled Subsystems?
Enabled subsystems are subsystems that execute at each simulation step for
which the control signal has a positive value.
An enabled subsystem has a single control input, which can be a scalar or
a vector.
• If the input is a scalar, the subsystem executes if the input value is greater
than zero.
• If the input is a vector, the subsystem executes if any one of the vector
elements is greater than zero.
For example, if the control input signal is a sine wave, the subsystem is
alternately enabled and disabled. This behavior is shown in the following
figure, where an up arrow signifies enable and a down arrow disable.

7-4

Enabled Subsystems

The Simulink software uses the zero-crossing slope method to determine
whether an enable event is to occur. If the signal crosses zero and its slope is
positive, then the subsystem becomes enabled. If the slope is negative at the
zero crossing, then the subsystem becomes disabled. Note that a subsystem
is only enabled or disabled at major time steps. Therefore, if zero-crossing
detection is turned off and the signal crosses zero during a minor time step,
then the subsystem will not become enabled (or disabled) until the next
major time step.

Creating an Enabled Subsystem
You create an enabled subsystem by copying an Enable block from the Ports &
Subsystems library into a Subsystem block. An enable symbol and an enable
control input port is added to the Subsystem block.

Setting Initial Conditions for an Enabled Subsystem
You can set the initial output of an enabled subsystem using the subsystems
Outport blocks. The initial output value can be either explicitly specified, or
inherited from its input signal.
Specifying Initial Conditions. To specify the initial output value of the
subsystem:
1 Double-click each Outport block in the subsystem to open its block

parameters dialog box.
2 In the Source of initial output value drop-down list, select Dialog.
3 Specify a valid value for the Initial output parameter. Valid values

include the empty matrix. But Inf and Nan are not valid values.

7-5

7

Creating Conditional Subsystems

If you select Dialog, you can also specify what happens to the output when the
subsystem is disabled. For more information, see the next section: “Setting
Output Values While the Subsystem Is Disabled” on page 7-7.
Inheriting Initial Conditions. The Outport block can inherit an initial
output value for the subsystem from the following sources:
• Output port of another conditionally executed subsystem
• Merge block (with Initial output specified)
• Function-Call Model Reference block
• Constant block (simplified initialization mode only)
• IC block (simplified initialization mode only)
The procedure you use to inherit the initial conditions of the subsystem
differs depending on whether you are using classic initialization mode or
simplified initialization mode.
To inherit initial conditions in classic initialization mode:
1 Double-click each Outport block in the subsystem to open its block

parameters dialog box.
2 In the Source of initial output value drop-down list, select Dialog .
3 Set the Initial output parameter to [] (empty matrix).
4 Click OK.

Note For all other driving blocks, specify an explicit initial output value.
To inherit initial conditions in simplified initialization mode:
1 Double-click each Outport block in the subsystem to open its block

parameters dialog box.
2 In the Source of initial output value drop-down list, select Input

signal.

7-6

Enabled Subsystems

3 Click OK.

The Initial output and Output when disabled parameters are disabled,
and both values are inherited from the input signal.
For more information on classic and simplified initialization mode, see
“Underspecified initialization detection”.

Setting Output Values While the Subsystem Is Disabled
Although an enabled subsystem does not execute while it is disabled, the
output signal is still available to other blocks. While an enabled subsystem
is disabled, you can choose to hold the subsystem outputs at their previous
values or reset them to their initial conditions.
Open the block parameters dialog box for each Outport block and for the
Output when disabled parameter, select one of the choices.
• Choose held to maintain the most recent value.
• Choose reset to revert to the initial condition. Set the Initial output to
the initial value of the output.

7-7

7

Creating Conditional Subsystems

Set the Outport output while
the subsystem is disabled
Initial condition and
value when reset

Note If you are connecting the output of a conditionally executed subsystem
to a Merge block, set Output when disabled to held to ensure consistent
simulation results.
If you are using simplified initialization mode, you must select held when
connecting a conditionally executed subsystem to a Merge block. For more
information, see “Underspecified initialization detection”.

7-8

Enabled Subsystems

Setting States When the Subsystem Becomes Enabled
When an enabled subsystem executes, you can choose whether to hold
the subsystem states at their previous values or reset them to their initial
conditions.
To do this, open the Enable block parameters dialog box and select one of the
choices for the States when enabling parameter:
• Choose held to cause the states to maintain their most recent values.
• Choose reset to cause the states to revert to their initial conditions.

7-9

7

Creating Conditional Subsystems

Note If you are using simplified initialization mode, the subsystem elapsed
time is always reset during the first execution after becoming enabled,
whether or not the subsystem is configured to reset on enable.
For more information on simplified initialization mode, see “Underspecified
initialization detection”.

Outputting the Enable Control Signal
An option on the Enable block dialog box lets you output the enable control
signal. To output the control signal, select the Show output port check box.

7-10

Enabled Subsystems

This feature allows you to pass the control signal down into the enabled
subsystem, which can be useful where logic within the enabled subsystem is
dependent on the value or values contained in the control signal.

Blocks that an Enabled Subsystem Can Contain
An enabled subsystem can contain any block, whether continuous or discrete.
Discrete blocks in an enabled subsystem execute only when the subsystem
executes, and only when their sample times are synchronized with the

7-11

7

Creating Conditional Subsystems

simulation sample time. Enabled subsystems and the model use a common
clock.
Note Enabled subsystems can contain Goto blocks. However, only state ports
can connect to Goto blocks in an enabled subsystem. In the sldemo_clutch
model, see the Locked subsystem for an example of how to use Goto blocks in
an enabled subsystem.
For example, this system contains four discrete blocks and a control signal.
The discrete blocks are:
• Block A, which has a sample time of 0.25 second
• Block B, which has a sample time of 0.5 second
• Block C, within the enabled subsystem, which has a sample time of 0.125
second
• Block D, also within the enabled subsystem, which has a sample time of
0.25 second
The enable control signal is generated by a Pulse Generator block, labeled
Signal E, which changes from 0 to 1 at 0.375 second and returns to 0 at 0.875
second.

7-12

Enabled Subsystems

7-13

7

Creating Conditional Subsystems

The chart below indicates when the discrete blocks execute.

Blocks A and B execute independently of the enable control signal because
they are not part of the enabled subsystem. When the enable control signal

7-14

Enabled Subsystems

becomes positive, blocks C and D execute at their assigned sample rates until
the enable control signal becomes zero again. Note that block C does not
execute at 0.875 second when the enable control signal changes to zero.

Using Blocks with Constant Sample Times in Enabled
Subsystems
Certain restrictions apply when you connect blocks with constant sample
times (see “Constant Sample Time” on page 5-16) to the output port of a
conditional subsystem.
• An error appears when you connect a Model or S-Function block with
constant sample time to the output port of a conditional subsystem.
• The sample time of any built-in block with a constant sample time is
converted to a different sample time, such as the fastest discrete rate in
the conditional subsystem.
To avoid the error or conversion, either manually change the sample time of
the block to a non-constant sample time or use a Signal Conversion block.
The example below shows how to use the Signal Conversion block to avoid
these errors.
Consider the following model ex_enabled_subsys_2.mdl.

7-15

7

Creating Conditional Subsystems

The two Constant blocks in this model have constant sample times. When
you simulate the model, the Simulink software converts the sample time of
the Constant block inside the enabled subsystem to the rate of the Pulse
Generator. If you simulate the model with sample time colors displayed

7-16

Enabled Subsystems

(see “View Sample Time Information” on page 5-9), the Pulse Generator
and Enabled Subsystem blocks are colored red. However, the Constant
and Outport blocks outside of the enabled subsystem are colored magenta,
indicating that these blocks still have a constant sample time.
Suppose the model above is referenced from a Model block inside an enabled
subsystem, as shown below. (See “Model Reference”.)

7-17

7

Creating Conditional Subsystems

An error appears when you try to simulate the top model, indicating that the
second output of the Model block may not be wired directly to the enabled
subsystem output port because it has a constant sample time. (See “Model
Reference”.)
To avoid this error, insert a Signal Conversion block between the second
output of the Model block and the Outport block of the enabled subsystem.

7-18

Enabled Subsystems

This model simulates with no errors. With sample time colors displayed,
the Model and Enabled Subsystem blocks are colored yellow, indicating that
these are hybrid systems. In this case, the systems are hybrid because they
contain multiple sample times.

7-19

7

Creating Conditional Subsystems

Triggered Subsystems
In this section...
“What Are Triggered Subsystems?” on page 7-20
“Using Model Referencing Instead of a Triggered Subsystem” on page 7-22
“Creating a Triggered Subsystem” on page 7-22
“Blocks That a Triggered Subsystem Can Contain” on page 7-23

What Are Triggered Subsystems?
Triggered subsystems are subsystems that execute each time a trigger event
occurs.
A triggered subsystem has a single control input, called the trigger input, that
determines whether the subsystem executes. You can choose from three types
of trigger events to force a triggered subsystem to begin execution:
For example, in the following timing diagram for a discrete system, a rising
trigger (R) does not occur at time step 3 because the signal remains at zero for
only one time step prior to the rise.

A simple example of a triggered subsystem is illustrated.

7-20

Triggered Subsystems

In this example, the subsystem is triggered on the rising edge of the square
wave trigger control signal.

7-21

7

Creating Conditional Subsystems

Using Model Referencing Instead of a Triggered
Subsystem
You can use triggered ports in referenced models. Add a trigger port to a
referenced model to create a simpler, cleaner model than when you include
either:
• A triggered subsystem in a referenced model
• A Model block in a triggered subsystem
For information about using trigger ports in referenced models, see
“Conditional Referenced Models” on page 6-59.
To convert a subsystem to use model referencing, see “Convert a Subsystem to
a Referenced Model” on page 6-12.

Creating a Triggered Subsystem
You create a triggered subsystem by copying the Trigger block from the Ports
& Subsystems library into a subsystem. The Simulink software adds a trigger
symbol and a trigger control input port to the Subsystem block.

To select the trigger type, open the Trigger block dialog box and select one of
the choices for the Trigger type parameter.
Different symbols appear on the Trigger and Subsystem blocks to indicate
rising and falling triggers (or either). This figure shows the trigger symbols
on Subsystem blocks.

7-22

Triggered Subsystems

Outputs and States Between Trigger Events
Unlike enabled subsystems, triggered subsystems always hold their outputs
at the last value between triggering events. Also, triggered subsystems
cannot reset their states when triggered; the states of any discrete block is
held between trigger events.

Outputting the Trigger Control Signal
An option on the Trigger block dialog box lets you output the trigger control
signal. To output the control signal, select the Show output port check box.
In the Output data type field, specify the data type of the output signal as
auto, int8, or double. The auto option causes the data type of the output
signal to be the data type (either int8 or double) of the port to which the

signal connects.

Blocks That a Triggered Subsystem Can Contain
All blocks in a triggered subsystem must have either inherited (-1) or
constant (inf) sample time. This is to indicate that the blocks in the triggered
subsystem run only when the triggered subsystem itself runs, for example,
when it is triggered. This requirement means that a triggered subsystem
cannot contain continuous blocks, such as the Integrator block.

7-23

7

Creating Conditional Subsystems

Triggered and Enabled Subsystems
In this section...
“What Are Triggered and Enabled Subsystems?” on page 7-24
“Creating a Triggered and Enabled Subsystem” on page 7-25
“A Sample Triggered and Enabled Subsystem” on page 7-26
“Creating Alternately Executing Subsystems” on page 7-27

What Are Triggered and Enabled Subsystems?
A third kind of conditional subsystem combines two types of conditional
execution. The behavior of this type of subsystem, called a triggered and
enabled subsystem, is a combination of the enabled subsystem and the
triggered subsystem, as shown by this flow diagram.

A triggered and enabled subsystem contains both an enable input port and
a trigger input port. When the trigger event occurs, the enable input port is
checked to evaluate the enable control signal. If its value is greater than zero,
the subsystem is executed. If both inputs are vectors, the subsystem executes
if at least one element of each vector is nonzero.

7-24

Triggered and Enabled Subsystems

The subsystem executes once at the time step at which the trigger event
occurs.

Creating a Triggered and Enabled Subsystem
You create a triggered and enabled subsystem by dragging both the Enable
and Trigger blocks from the Ports & Subsystems library into an existing
subsystem. The Simulink software adds enable and trigger symbols and
enable and trigger control inputs to the Subsystem block.

You can set output values when a triggered and enabled subsystem is disabled
as you would for an enabled subsystem. For more information, see “Setting
Output Values While the Subsystem Is Disabled” on page 7-7. Also, you can
specify what the values of the states are when the subsystem is reenabled.
See “Setting States When the Subsystem Becomes Enabled” on page 7-9.
Set the parameters for the Enable and Trigger blocks separately. The
procedures are the same as those described for the individual blocks.

7-25

7

Creating Conditional Subsystems

A Sample Triggered and Enabled Subsystem
A simple example of a triggered and enabled subsystem is illustrated in the
following model.

7-26

Triggered and Enabled Subsystems

Creating Alternately Executing Subsystems
You can use conditional subsystems in combination with Merge blocks to
create sets of subsystems that execute alternately, depending on the current
state of the model.

7-27

7

Creating Conditional Subsystems

The following figure shows a model that uses two enabled blocks and a Merge
block to model a full-wave rectifier – a device that converts AC current to
pulsating DC current.

7-28

Triggered and Enabled Subsystems

The block labeled pos is enabled when the AC waveform is positive; it passes
the waveform unchanged to its output. The block labeled neg is enabled when
the waveform is negative; it inverts the waveform. The Merge block passes
the output of the currently enabled block to the Mux block, which passes the
output, along with the original waveform, to the Scope block.
The Scope creates the following display.

7-29

7

Creating Conditional Subsystems

Function-Call Subsystems
A function-call subsystem is a subsystem that another block can invoke
directly during a simulation. It is analogous to a function in a procedural
programming language. Invoking a function-call subsystem is equivalent to
invoking the output methods (See “Block Methods” on page 3-16) of the blocks
that the subsystem contains in sorted order (See “How Simulink Determines
the Sorted Order” on page 23-45). The block that invokes a function-call
subsystem is called the function-call initiator. Stateflow, Function-Call
Generator, and S-function blocks can all serve as function-call initiators.
To create a function-call subsystem, drag a Function-Call Subsystem
block from the Ports & Subsystems library into your model and connect
a function-call initiator to the function-call port displayed on top of the
subsystem. You can also create a function-call subsystem from scratch. First
create a Subsystem block in your model and then create a Trigger block in
the subsystem. Next, on the Trigger block parameters pane, set the Trigger
type to function-call.
You can configure a function-call subsystem to be triggered (the default) or
periodic by setting the Sample time type of its Trigger port to be triggered
or periodic, respectively. A function-call initiator can invoke a triggered
function-call subsystem zero, once, or multiple times per time step. The
sample times of all the blocks in a triggered function-call subsystem must be
set to inherited (-1).
A function-call initiator can invoke a periodic function-call subsystem
only once per time step and must invoke the subsystem periodically. If
the initiator invokes a periodic function-call subsystem aperiodically, the
simulation is halted and an error message is displayed. The blocks in a
periodic function-call subsystem can specify a noninherited sample time or
inherited (-1) sample time. All blocks that specify a noninherited sample time
must specify the same sample time. For example, if one block specifies 0.1 as
the sample time, all other blocks must specify a sample time of 0.1 or -1. If
a function-call initiator invokes a periodic function-call subsystem at a rate
that differs from the sample time specified by the blocks in the subsystem, the
simulation halts and an error message appears.

7-30

Function-Call Subsystems

Note During range checking, the design minimum and maximum are
back-propagated to the actual source port of the function-call subsystem, even
when the function-call subsystem is not enabled.
To prevent this back propagation, add a Signal Conversion block and a
Signal Specification block after the source port, set the Output of the Signal
Conversion block to Signal copy, and specify the design minimum and
maximum on the Signal Specification block instead of specifying them on
the source port.
For more information about function-call subsystems, see “Function-Call
Subsystems” in “Writing S-Functions” in the online documentation.

7-31

7

Creating Conditional Subsystems

Conditional Execution Behavior
In this section...
“What Is Conditional Execution Behavior?” on page 7-32
“Propagating Execution Contexts” on page 7-34
“Behavior of Switch Blocks” on page 7-35
“Displaying Execution Contexts” on page 7-36
“Disabling Conditional Execution Behavior” on page 7-37
“Displaying Execution Context Bars” on page 7-37

What Is Conditional Execution Behavior?
To speed the simulation of a model, by default the Simulink software avoids
unnecessary execution of blocks connected to Switch, Multiport Switch, and
of conditionally executed blocks. This behavior is conditional execution (CE)
behavior. You can disable this behavior for all Switch and Multiport Switch
blocks in a model, or for specific conditional subsystems. See “Disabling
Conditional Execution Behavior” on page 7-37.
The following model illustrates conditional execution behavior.

7-32

Conditional Execution Behavior

The Scope block shows the simulation result:

This model:
• Has the Display > Signals & Ports > Execution Context Indicator
menu option enabled.
• The Pulse Generator block has the following parameter settings:

-

Pulse type — Sample based
Period — 100
Pulse width — 50
Phase delay — 50
Sample Time — 0.01

7-33

7

Creating Conditional Subsystems

• The Gain block’s sorted order (1:2) is second (2) in the enabled subsystem’s
execution context (1).
• The Enabled Subsystem block has the Propagate execution context
across subsystem boundary parameter enabled.
• In the enabled subsystem, the Out1 block has the following parameter
settings:

-

Initial output — []
Output when disabled — held

The outputs of the Constant block and Gain blocks are computed only while
the enabled subsystem is enabled (for example, at time steps 0.5 to 1.0 and 1.5
to 2.0). This behavior is necessary because the output of the Constant block
is required and the input of the Gain block changes only while the enabled
subsystem is enabled. When CE behavior is off, the outputs of the Constant
and Gain blocks are computed at every time step, regardless of whether the
outputs are needed or change.
In this example, the enabled subsystem is regarded as defining an execution
context for the Constant and Gain blocks. Although the blocks reside
graphically in the root system of the model, the Simulink software invokes
the block methods during simulation as if the blocks reside in the enabled
subsystem. This is indicated in the sorted order labels displayed on the
diagram for the Constant and Gain blocks. The notations list the subsystem’s
(id = 1) as the execution context for the blocks even though the blocks exist
graphically at the root level (id = 0) of the model. The Gain block’s sorted
order (1:2) is second (2) in the enabled subsystem’s execution context (1).

Propagating Execution Contexts
In general, the Simulink software defines an execution context as a set of
blocks to be executed as a unit. At model compilation time, the Simulink
software associates an execution context with the model’s root system and
with each of its nonvirtual subsystems. Initially, the execution context of
the root system and each nonvirtual subsystem is simply the blocks that
it contains.
When compiling, each block in the model is examined to determine whether it
meets the following conditions:

7-34

Conditional Execution Behavior

• The block output is required only by a conditional subsystem or the block
input changes only as a result of the execution of a conditionally executed
subsystem.
• The execution context of the subsystem can propagate across the subsystem
boundaries.
• The output of the block is not a test point (see “Test Points” on page 47-58).
• The block is allowed to inherit its conditional execution context.
The Simulink software does not allow some built-in blocks, such as the
Delay block, ever to inherit their execution context. Also, S-Function
blocks can inherit their execution context only if they specify the
SS_OPTION_CAN_BE_CALLED_CONDITIONALLY option.
• The block is not a multirate block.
• The block sample time is set to inherited (-1).
If a block meets these conditions and execution context propagation is
enabled for the associated conditional subsystem (see “Disabling Conditional
Execution Behavior” on page 7-37), the Simulink software moves the block
into the execution context of the subsystem. This ensures that the block
methods execute during the simulation loop only when the corresponding
conditional subsystem executes.
Note Execution contexts are not propagated to blocks having a constant
sample time.

Behavior of Switch Blocks
This behavior treats the input branches of a Switch or Multiport Switch block
as invisible, conditional subsystems, each of which has its own execution
context. This CE is enabled only when the control input of the switch selects
the corresponding data input. As a result, switch branches execute only when
selected by switch control inputs.

7-35

7

Creating Conditional Subsystems

Displaying Execution Contexts
To determine the execution context to which a block belongs, in the Simulink
Editor, select Display > Blocks > Sorted Execution Order. The sorted
order index for each block in the model is displayed in the upper-right corner
of the block. The index has the format s:b, where s specifies the subsystem to
whose execution context the block belongs and b is an index that indicates the
block sorted order in the execution context of the subsystem. For example,
0:0 indicates that the block is the first block in the execution context of the
root subsystem.
If a bus is connected to a block input, the block sorted order is displayed as
s:B. For example, 0:B indicates that the block belongs to the execution context
of the root system and has a bus connected to its input.
The sorted order index of conditional subsystems is expanded to include
the system ID of the subsystem itself in curly brackets as illustrated in the
following figure.

In this example, the sorted order index of the enabled subsystem is 0:1{1}.
The 0 indicates that the enabled subsystem resides in the root system of the
model. The first 1 indicates that the enabled subsystem is the second block on
the sorted list of the root system (zero-based indexing). The 1 in curly brackets
indicates that the system index of the enabled subsystem itself is 1. Thus any
block whose system index is 1 belongs to the execution context of the enabled
subsystem and hence executes when it does. For example, the fact that the
Constant block has an index of 1:0 indicates that it is the first block on the
sorted list of the enabled subsystem, even though it resides in the root system.

7-36

Conditional Execution Behavior

Disabling Conditional Execution Behavior
To disable conditional execution behavior for all Switch and Multiport Switch
blocks in a model, turn off the Conditional input branch execution
optimization on the Optimization pane of the Configuration Parameters
dialog box (see “Optimization Pane: General”). To disable conditional
execution behavior for a specific conditional subsystem, clear the Propagate
execution context across subsystem boundary check box on the
subsystem parameter dialog box.
Even if this option is enabled, the execution context of the subsystem cannot
propagate across its boundaries under either of the following circumstances:
• The subsystem is a triggered subsystem with a latched input port.
• The subsystem has one or more output ports that specify an initial
condition other than []. In this case, a block connected to the subsystem
output cannot inherit the execution context of the subsystem.

Displaying Execution Context Bars
Simulink can optionally display bars next to the ports of subsystems across
which execution contexts cannot propagate. To display the bars, select
Display > Signals & Ports > Execution Context Indicator.
For example, it displays bars on subsystems from which no block can inherit
its execution context. In the following figure, the context bars appear next to
the In1 and Out1 ports of the Enabled Subsystem block.

7-37

7

7-38

Creating Conditional Subsystems

8
Modeling Variant Systems
• “Working with Variant Systems” on page 8-2
• “Set Up Model Variants” on page 8-5
• “Set Up Variant Subsystems” on page 8-15
• “Set Up Variant Control” on page 8-25
• “Select the Active Variant” on page 8-29
• “About Variant Objects” on page 8-32
• “Code Generation of Variants” on page 8-36
• “Variant System Reference” on page 8-37

8

Modeling Variant Systems

Working with Variant Systems
In this section...
“Overview of Variant Systems” on page 8-2
“Workflow for Implementing Variant Systems” on page 8-3

Overview of Variant Systems
Many applications require the ability to customize a model to fit different
specifications, without replacing or duplicating the model. For example, a
design engineer has a model that simulates an automobile. Various models of
an automobile can have many similarities, yet differ in specific ways, such
as fuel usage, engine size, or emission standards.
With blocks for variant systems, Simulink provides techniques to customize a
model for different applications through design and simulation:
• The Model Variants block references two or more models, where the
referenced model used during simulation is the active variant.
• The Variant Subsystem block consists of a set of subsystems, where the
subsystem used during simulation is the active variant.
Each variant, active or inactive, has an object. Simulink evaluates the variant
objects to determine the active variant.
You can parameterize the variant object by making it dependent on the
values of variables and objects in the MATLAB base workspace. For a quick
overview, see “Model Variants Block Overview” on page 8-5 and “Variant
Subsystem Block Overview” on page 8-15.
You can programmatically switch the active variant by modifying the values
of variant control variables in the base workspace. Alternatively, you can
manually override the variant selection on the block parameter dialog box.
Both variant models and variant subsystems use variants in a similar
workflow. For more information, see “Workflow for Implementing Variant
Systems” on page 8-3.

8-2

Working with Variant Systems

For alternative techniques to customize a model for different specifications,
see:
Technique

Reference

Change data values in the base
workspace.

“Tunable Parameters” on page 3-9

Select alternate subsystems from a
library.

Configurable Subsystem block

Use a mask to change a subsystem.

“Create Dynamic Masked
Subsystems” on page 26-61

Change the arguments to a
parameterized referenced model.

“Parameterize Model References” on
page 6-52

Workflow for Implementing Variant Systems
You can implement a variant system in your model by using the Model
Variants block or the Variant Subsystem block. Both blocks use a similar
workflow.
1 Create the subsystems or referenced models that you want to use as

variants.
2 Set up your model to use the variants. Add the Model Variants block or the

Variant Subsystem block, depending on your application. Use the blocks to:
a Specify variant models or subsystems.
b Create a variant object to associate with each variant.
c Define a condition for each variant. When the condition is true,

Simulink uses this active variant for simulation.
For more information, see “Set Up Model Variants” on page 8-5 and “Set
Up Variant Subsystems” on page 8-15.
3 Create the control variables for evaluating variant conditions and selecting

the active variant. See “Set Up Variant Control” on page 8-25 and “Select
the Active Variant” on page 8-29.

8-3

8

Modeling Variant Systems

4 Simulate using the active variant.
5 Modify the variant specification to select another variant and simulate

again.
6 Generate code for the active variant or all variants, depending on your

application. See “Code Generation of Variants” on page 8-36.
7 Save the control variables and objects for your variants from the base

workspace as described in “Exporting Workspace Variables” on page 9-60.

8-4

Set Up Model Variants

Set Up Model Variants
In this section...
“Model Variants Block Overview” on page 8-5
“Example of a Model Variants Block” on page 8-7
“Configuring the Model Variants Block” on page 8-9
“Disabling and Enabling Model Variants” on page 8-12
“Parameterizing Model Variants” on page 8-12
“Requirements, Limitations, and Tips for Model Variants” on page 8-13
“Model Variants Example” on page 8-14

Model Variants Block Overview
Model variants provide multiple implementations of a referenced model, with
only one implementation active during simulation. You can programmatically
swap the active implementation with another, without modifying the model.
For example, you could use variants to switch between data types, such as
double and int8, by specifying different data types in your referenced models.

8-5

8

Modeling Variant Systems

A Model Variants block can reference multiple models, using variants as
follows:
• Each variant has a variant object that you associate with it.
• Each variant has a condition that you specify. When compiling the model,
Simulink tests each variant to determine which condition is true. The
variant with the true condition becomes the active variant.
• Only one variant can be the active variant for a Model Variants block.
• The active variant is the referenced model used for simulation.
You specify the model variant associations in the Model Reference Parameter
dialog box, in the Variant choices table.

8-6

Set Up Model Variants

The Model Variants block parameters specification must include at least:
• The name of a variant object, in the Variant object column of the Variant
choices table
• The name of a referenced model, in the Model name column of the
Variant choices table
• A simulation mode, in the Simulation mode field of the Model
parameters section
• Values in the Model argument values field of the Model parameters
section, if a referenced model has arguments
Instructions for specifying model variants are in “Configuring the Model
Variants Block” on page 8-9.

Example of a Model Variants Block
To view the example model, either click AutoMRVar, or execute:
addpath([docroot '/toolbox/simulink/ug/examples/variants/mdlref/']);
open('AutoMRVar');

8-7

8

Modeling Variant Systems

• The icon
appears in the lower-left corner to indicate that the block
uses variants.
• The name of the variant that was active the last time you saved the model
appears at the top of the block.
• When you change the active variant and press Ctrl+K, the variant block
refreshes and its name changes.
• When you open the example model, a callback function loads a MAT-file
that populates the base workspace with the variables and objects that the
model uses. The base workspace contains the variant control variables
and variant objects.

8-8

Set Up Model Variants

The example implements the following application:
• An automobile that can use either a diesel or a gasoline engine
• Each engine must meet either the European or American (USA) emission
standard
AutoMRVar implements the automobile application using the Model Variants
block, named Engine. The Engine block specifies four variant referenced
models. Each referenced model represents one permutation of engine fuel and
emission standards.

Variant Object

Variant Condition

Model Name

GU

FUEL==1 && EMIS==1

GasolUSA

GE

FUEL==1 && EMIS==2

GasolEuro

DU

FUEL==2 && EMIS==1

DieselUSA

DE

FUEL==2 && EMIS==2

DieselEuro

To see how to specify these variants, in the Simulink Editor, right-click the
Engine block, and select Block Parameters (ModelReference) or select
Diagram > Block Parameters (ModelReference). View the Variant
choices table in the dialog box.

For instructions, see “Configuring the Model Variants Block” on page 8-9.

Configuring the Model Variants Block
To add and configure a Model Variants block to specify your variants, do
the following:

8-9

8

Modeling Variant Systems

1 From the Simulink Library Browser, add a Model Variants block to your

model:
Simulink > Ports and Subsystems→Model Variants block.
2 To configure your variants, open the Model Variants block dialog box.

In the Simulink Editor, right-click the Model Variants block, and select
Block Parameters (ModelReference) or select Diagram > Block
Parameters (ModelReference).
The Model Variants block parameters dialog box opens.

3 Specify the variant name in the Variant object column of the Variant

choices table. Double-click the default Variant1 name, then type the
name of the variant object. For an existing variant object, Simulink
retrieves the variant condition for the object when you press Enter or
click away from the Variant object.
4 To specify the Condition that determines which variant is active, click the

. For the selected variant
Create/Edit selected variant button
choice, you create a variant object in the base workspace if necessary, or
edit an existing variant. The Simulink.Variant parameter dialog box opens.
a Specify the Condition for the variant object. For example, FUEL==1

&& EMIS==1. Do not surround the condition with parentheses or single

quotes.

8-10

Set Up Model Variants

When the variant object condition evaluates to true at compile time, the
referenced model associated with the variant becomes the active variant.
b Click Apply to check the expression, then click OK.
5 Choose a referenced model to associate with the variant object.
a In the Variant choices table, click to select a variant.
b Enter the model name into either the Model name table cell, or the

Model name field for the chosen variant, in the Model parameters
for chosen variant in table pane to the right of the table. To specify
a protected model, use the extension .slxp. See “Protected Model” on
page 6-67.
Alternatively, to find a model, click the Browse button next to the
Model name field. Select the model, and click Open. The model name
appears in the Model name column and edit box.
c (Optional) For the selected model, you can also click Open Model

to check which model you are specifying, specify model arguments
(see “Parameterizing Model Variants” on page 8-12), or specify the
Simulation mode. All simulation modes work with model variants. See
“Referenced Model Simulation Modes” on page 6-21.
d Click Apply to associate the referenced model with its variant object.

6 To add another variant, click the Add a new variant button

.

A new Variant choices table row appears below the other variant choices.
7 Repeat the previous steps until you have specified all your referenced

models and their associated variant objects. For information on the other
buttons, see the Model Variants block page.
8 Click OK to close the Model Variants dialog box.

Note Your variant conditions might require you to define control variables
in the base workspace before they can be evaluated. See “Creating Control
Variables” on page 8-25 and “Saving Variant Components” on page 8-26.

8-11

8

Modeling Variant Systems

For next steps, see “Select the Active Variant” on page 8-29. The model
diagram displays the new active variant on the block when you refresh the
block by pressing Ctrl+K.

Disabling and Enabling Model Variants
You can disable model variants without losing your variant settings. After
you enable variants, they remain enabled until you explicitly disable them.
You can close and reopen the Model Variants block without affecting the
variant specification.
To disable variants from your Model block or Model Variants block:
1 Right-click the block and select Block Parameters (ModelReference) to

open the block parameters dialog box.
2 Select the Disable Variants button. Disabling variants:

• Hides the Block parameter dialog box for variants
• Leaves the active variant as the model name and the execution
environment when the variants were disabled
• Ignores subsequent changes to variant control variables, variant
conditions, and other models, other than the current model.
If you decide to reenable variants, select the Enable Variants button.
• The Model block or Model Variants block remembers your previous variant
specifications as they were before.
• The Model block or Model Variants block selects an active variant according
to the current base workspace variables and conditions.
You can also override variants and specify the active variant. See “Overriding
Variant Conditions” on page 8-30.

Parameterizing Model Variants
You can parameterize any or all variants of the Model Variants block. You
can parameterize some variants but choose not to parameterize others. You
can also parameterize different variants differently from one another.

8-12

Set Up Model Variants

To parameterize a variant (referenced model) of a Model Variants block,
specify the necessary values in the Model parameters for chosen variant
in table section using the Model argument values field. You can use
the same values as for any referenced model. For more information, see
“Parameterize Model References” on page 6-52.

Requirements, Limitations, and Tips for Model
Variants
A Model Variants block and its referenced models must satisfy the
requirements in “Simulink Model Referencing Requirements” on page 6-45
and “Model Referencing Limitations” on page 6-80. You can nest Model
Variants blocks to any level.
Note Requirements and limitations that apply to code generation are in
“Limitations on Generating Code for Variants”.
Tips for working with model variants:
• A Model Variants block can log only those signals that the referenced model
specifies as logged. If a model is a variant model, or contains a variant
model, then you can either log all logged signals or log no logged signals.
The Signal Logging Selector configuration for the model must be in one
of these states:

-

The Logging Mode is set to Log all signals as specified in
model.

-

The Logging Mode is set to Override signals and the check box for
the model block is either checked (
cannot be filled (

) or empty (

). The check box

).

For more information about logging referenced models, see “Models with
Model Referencing: Overriding Signal Logging Settings” on page 45-45.
To enable logging programmatically, use the DefaultDataLogging
parameter.

8-13

8

Modeling Variant Systems

• You can enable or suppress warning messages about mismatches between
a Model Variants block and its referenced model by setting diagnostics on
the “Diagnostics Pane: Model Referencing”.
• During model compilation, Simulink evaluates variant objects before
calling the model InitFcn callback. Therefore, do not modify the condition
of the variant object in the InitFcn callback.

Model Variants Example
To see a example that shows how to define a variant model in
Simulink , click sldemo_mdlref_variants. In the Help Browser
select: Simulink > Examples > Modeling Features > Model
Reference > Model Reference Variants.

8-14

Set Up Variant Subsystems

Set Up Variant Subsystems
In this section...
“Variant Subsystem Block Overview” on page 8-15
“Example of a Variant Subsystem Block” on page 8-17
“Configuring the Variant Subsystem Block” on page 8-20
“Disabling and Enabling Subsystem Variants” on page 8-23
“Variant Subsystem Block Requirements” on page 8-23
“Variant Subsystem Example” on page 8-24

Variant Subsystem Block Overview
A variant subsystem provides multiple implementations of a subsystem, with
only one implementation active during simulation. You can programmatically
swap the active implementation with another, without modifying the model.

8-15

8

Modeling Variant Systems

A Variant Subsystem block consists of multiple subsystems as follows:
• Each subsystem has a variant object that you associate with it.
• The subsystem whose variant object condition is true becomes the active
variant.
• A Variant Subsystem block can have only one active variant.
• The active variant is the subsystem used for simulation.
The specifications of the Variant Subsystem block parameters dialog box
must include:
• The name of a variant object, in the Variant object column of the Variant
choices table.
• The variant object must have a conditional expression that evaluates to
true or false.

8-16

Set Up Variant Subsystems

Instructions for specifying a variant subsystem are in “Configuring the
Variant Subsystem Block” on page 8-20.

Example of a Variant Subsystem Block
To view the example model, either click AutoSSVar, or execute:
addpath([docroot '/toolbox/simulink/ug/examples/variants/mdlref/']);
open('AutoSSVar');

• An icon
variants.

appears in the lower-left corner to indicate that the block uses

• The name of the variant that was active the last time you saved the model
appears at the top of the block.
• When you change the active variant and refresh the diagram by pressing
Ctrl+K, the variant block name changes.
• When you open the example model, a callback function loads a MAT-file
that populates the base workspace with the variables and objects that the
model uses. The base workspace contains the variant control variables
and variant objects.

8-17

8

Modeling Variant Systems

The example model illustrates the same application as the “Example of a
Model Variants Block” on page 8-7, but using variant subsystems instead of
variant referenced models. Both examples show the use of variants for the
following cases:
• An automobile that can use either a diesel or a gasoline engine
• Each engine must meet either the European or American (USA) emission
standard
The example model, AutoSSVar, implements the application using a Variant
Subsystem block, named Engine. The Engine block consists of a set of four
subsystems. Each subsystem represents one permutation of engine fuel and
emission standards.
Double-click the Variant Model block, Engine, to view the child subsystems.

8-18

Set Up Variant Subsystems

The subsystem diagram for a Variant Subsystem block has no connections.
The only blocks allowed in the Variant Subsystem block diagram are Inport,
Outport, and Subsystem blocks. If you are generating code for a Variant
Subsystem block, see “Restrictions on Variant Subsystem Code Generation”.
To view how to specify these variants, in the Simulink Editor, right-click
the Engine block, and select Block Parameters (Subsystem) or select
Diagram > Block Parameters (Subsystem).
View the Variant choices (list of child subsystems) table in the dialog
box, as shown in the following figure.

8-19

8

Modeling Variant Systems

For instructions, see “Configuring the Variant Subsystem Block” on page 8-20.

Configuring the Variant Subsystem Block
To add and configure a Variant Subsystem block to specify your variants,
do the following:
1 From the Simulink Library Browser, add a Variant Subsystem block to

your model:
Simulink > Ports and Subsystems > Variant Subsystem block
2 To configure your variants, open the Variant Subsystem block dialog box.

In the Simulink Editor, right-click the Variant Subsystem block, Engine,
and select Block Parameters (Subsystem) or select Diagram > Block
Parameters (Subsystem).
The Variant Subsystem block parameters dialog box opens.

3 Add a new subsystem choice in the Variant Subsystem block. In the

Variant choices table, click the Create and add a new subsystem
choice button
. A new variant choice appears in the table and a new
Subsystem block appears in the Variant Subsystem block diagram window.

8-20

Set Up Variant Subsystems

4 Rename the subsystem in the Variant Subsystem block diagram window,

and open and configure the subsystem as desired. You can drag and drop
existing subsystems into the new variant subsystem.

Note
• The Inport, Outport, and Connection Port blocks in the Variant
Subsystem block must be identical to the corresponding inports and
outports of its child subsystems.
• Inside the Variant Subsystem block diagram, you cannot create any
lines connecting blocks.
5 Return to the Variant Subsystem parameter dialog box. In the Variant

object column of the Variant choices table, specify the variant name in
the row of the subsystem you just configured. Double-click the default
name, then type the name of the variant object. For an existing variant
object, Simulink retrieves the variant condition for the object when you
press Enter or click away from the Variant object. In the Variant
choices table, double-click the Variant object field in the row of the
subsystem you just configured. Specify the name for the Variant object.
6 To specify the Condition that determines which variant is active, click the

Create/Edit selected variant button
. For the selected variant
choice, you create a variant object in the base workspace if necessary, or
edit an existing variant. The Simulink.Variant parameter dialog box opens.

8-21

8

Modeling Variant Systems

a Specify the Condition for the variant object. For example, FUEL==2

&& EMIS==2.

When the variant object condition evaluates to true at compile time, the
subsystem associated with the variant becomes the active variant.
b Click Apply to check the expression, then click OK.

The Variant choices table is updated with the condition for the
new variant object. Simulink also created the variant object as a
Simulink.Variant object in the base workspace. If you use a variant
control variable in the Condition expression, you must create the variant
control variables in the base workspace.
7 To add another variant, click the Create and add a new subsystem

choice button
8 Repeat the previous steps until you have specified all your variant

subsystems and their associated variant objects.
For more information on the block controls, see the Variant Subsystem
block page.
9 Click OK to close the Variant Subsystem dialog box.

8-22

Set Up Variant Subsystems

Note Your variant conditions might require you to define control variables
in the base workspace before they can be evaluated. See “Creating Control
Variables” on page 8-25 and “Saving Variant Components” on page 8-26.
For next steps, see “Select the Active Variant” on page 8-29. The model
diagram does not display the new active variant on the block until you refresh
the diagram by pressing Ctrl+K.

Disabling and Enabling Subsystem Variants
You can disable individual subsystem choices. To ignore a subsystem for
simulation and code generation, you can comment out the variant object in
the Variant Choices table as follows:
1 In the Variant choices table, double-click the name of the variant object.
2 Add a ’%’ to the beginning of the variant object name.
3 Click Apply and OK.

To enable the subsystem variant again, remove the %’ from the variant object
name.
You can also override variants and specify the active variant. See “Overriding
Variant Conditions” on page 8-30.

Variant Subsystem Block Requirements
A Variant Subsystem block must meet the following requirements:
• The Inport, Outport, and Connection Port blocks in the Variant Subsystem
block must be identical to the corresponding inports and outports of its
child subsystems.
• Inside the Variant Subsystem block diagram, you cannot create any lines
connecting blocks.

8-23

8

Modeling Variant Systems

You can nest Variant Subsystem blocks to any level. The hierarchy resulting
from nesting must satisfy all applicable requirements and limitations when
you compile the model or generate code for it.
Note Requirements and limitations that apply to code generation are in
“Limitations on Generating Code for Variants”.

Variant Subsystem Example
To see an example that shows how to define a variant subsystem,
click sldemo_variant_subsystems. In the Help Browser, select:
Simulink > Examples > Modeling Features > Subsystems > Variant
Subsystems.

8-24

Set Up Variant Control

Set Up Variant Control
In this section...
“Creating Control Variables” on page 8-25
“Saving Variant Components” on page 8-26
“Example Variant Control Variables” on page 8-26
“Using Enumerated Types for Variant Control Variable Values” on page
8-27

Creating Control Variables
You must create variant control variables to control which variant is active.
You create variant control variables in the same way for variant subsystems
or variant models.
To specify the condition of a variant object, you can use MATLAB variables,
or Simulink.Parameter objects that reside in the base workspace. The
conditions of the variant objects determine which variant is the active
variant. At the MATLAB command line or in the Model Explorer, create
variant control variables to match your specified conditions. Before compiling
or simulating, you set the variant control variables to values that specify the
environment in which you want to simulate.
Note To control variants using meaningful readable names, you can use
a Simulink.Parameter object of enumerated type to define the variant
condition. See “Using Enumerated Types for Variant Control Variable
Values” on page 8-27.
At the MATLAB Command Window or in the Model Explorer, create variant
control variables:
• In the MATLAB Command Window
For example,
EMIS = 1

8-25

8

Modeling Variant Systems

FUEL = 2

• In the Model Explorer
1 Select the Base Workspace.
2 Select Add > MATLAB Variable.
3 Name the variable and specify its value.

Each technique creates the variant control variables in the base workspace.
Note A variant control variable for code generation must be a Simulink
parameter that meets the requirements described in “Generate Preprocessor
Conditionals for Variant Systems”.

Saving Variant Components
Variant control variables and variant objects exist in the base workspace.
If you want to reload variant control variables or variant objects with your
model, you must save them to a MAT-file.

Example Variant Control Variables
The example AutoMRVar uses the control variables EMIS and FUEL. Depending
on the values of EMIS and FUEL, you can see which variant is active.
Variant Control
Variables

Variant Object

Active Variant
(Model Block or
Subsystem Block)

FUEL=1 and EMIS=1

GU

GasolUSA

FUEL=1 and EMIS=2

GE

GasolEuro

FUEL=2 and EMIS=1

DU

DieselUSA

FUEL=2 and EMIS=2

DE

DieselEuro

To try an example changing control variables:
1 Open AutoMRVar.

8-26

Set Up Variant Control

2 Specify FUEL=2 and EMIS=2 in the base workspace. When you choose these

values for the variant control variables, the variant condition associated
with the variant object DE is true. Therefore, the active variant is
DieselEuro, and the model AutoMRVar uses DieselEuro as its referenced
model during simulation.
3 Press Ctrl+K to updated the active variant.

Note To control variants using meaningful readable names, you can use
a Simulink.Parameter object of enumerated type to define the variant
condition. See “Using Enumerated Types for Variant Control Variable
Values” on page 8-27.
For an example explaining control variables for variant subsystems, including
the use of enumerated types, see the example sldemo_variant_subsystems.

Using Enumerated Types for Variant Control Variable
Values
You can use enumerated types to give meaningful names to the integers that
you use as values of variant control variables. For more information about
defining and using enumerated types, see “About Simulink Enumerations”
on page 44-2. For example, suppose you defined the following enumerated
class, whose elements represent vehicle properties:
classdef(Enumeration) VarParams < Simulink.IntEnumType
enumeration
gasoline(1)
diesel(2)
USA(1)
European(2)
end
end

With the class VarParams defined, you can use meaningful names to specify
variant control variables and variant conditions. For example, you can
substitute names for the integers for variant control variables EMIS and FUEL.

8-27

8

Modeling Variant Systems

EMIS = VarParams.USA
FUEL = VarParams.diesel

Using the techniques described in “About Variant Objects” on page 8-32,
the variant objects are:
GU=Simulink.Variant('FUEL==VarParams.gasoline && EMIS==VarParams.USA')
GE=Simulink.Variant('FUEL==VarParams.gasoline && EMIS==VarParams.European')
DU=Simulink.Variant('FUEL==VarParams.diesel && EMIS==VarParams.USA')
DE=Simulink.Variant('FUEL==VarParams.diesel && EMIS==VarParams.European')

Specifying meaningful names rather than integers as the values of variant
control variables facilitates creating complex variant specifications. It also
clarifies the generated code, which contains the names of the values rather
than integers.
For an example explaining the use of enumerated types with variants, see the
example sldemo_variant_subsystems.

8-28

Select the Active Variant

Select the Active Variant
In this section...
“What Is an Active Variant?” on page 8-29
“Selecting the Active Variant for Simulation” on page 8-29
“Checking and Opening the Active Variant” on page 8-30
“Overriding Variant Conditions” on page 8-30

What Is an Active Variant?
The active variant is the variant Simulink uses when simulating your model.
An active variant can be either:
• A referenced model of a Model Variants block, or
• A subsystem of a Variant Subsystem block.
You control variants by setting conditions. Simulink determines the active
variant by which variant object condition evaluates to true at compile time.

Selecting the Active Variant for Simulation
You select the active variant in the same way for variant models or variant
subsystems.
You can switch the active variant by:
• Programmatically modifying the values of variant control variables or
parameters in the base workspace
• Using the Variant menu to choose a variant. Right-click the block or select
Diagram > Variant > Override using > variant choice.
• Manually overriding the variant selection on the block parameter dialog box
The condition of the variant objects determine which variant is active. You
define the condition using variant control variables or parameters defined
in the base workspace, so you can modify the values of the variant control

8-29

8

Modeling Variant Systems

variables to select the active variant. See “Creating Control Variables” on
page 8-25.
You can also override the variant conditions and manually select one active
variant. For instructions, see “Overriding Variant Conditions” on page 8-30.

Checking and Opening the Active Variant
When you open a model, variant blocks display the name of the variant that
was active the last time the model was saved.
When the active variant changes (for example, when you change the control
variables for variant conditions), you can update the variant block name by
pressing Ctrl+K to refresh.
You can use the Variant menu to open the active variant. Right-click the
block or select Diagram > Variant > Open > (active variant)
To find the name of the active variant for the currently selected block, enter
at the command line:
get_param(gcb, 'ActiveVariant')

Overriding Variant Conditions
You can specify one variant as the active variant. You can either:
• Use the Variant menu to choose a variant. Right-click the block or select
Diagram > Variant > Override using > variant choice.
• Manually override the variant selection on the block parameter dialog box.
In both the Model Variants and Variant Subsystem block parameters dialog
boxes, use the “Override variant conditions and use following variant”
parameter, at the bottom left.

8-30

Select the Active Variant

1 Select the parameter Override variant conditions and use following

variant. The “Variant” parameter becomes enabled.
2 Click the Variant drop-down list and select a variant object from the list.

In the Model Variants block, the list shows each variant and the associated
model name.

In the Variant Subsystem block, the list shows only variant object names.
Check the variant choices table for the name of the subsystem associated
with each variant.
3 After you make the change, click Apply or OK. The variant object that you

specified becomes the active variant, overriding all other specifications that
determine which variant is active. The variant remains active until you
either select a different variant from the drop-down list, or clear Override
variant conditions and use following variant.

8-31

8

Modeling Variant Systems

About Variant Objects
In this section...
“What Is a Variant Object?” on page 8-32
“Creating Variant Objects” on page 8-32
“Reusing Variant Objects” on page 8-33
“Variant Condition” on page 8-34

What Is a Variant Object?
A variant object is an instance of the Simulink.Variant class in the base
workspace. You can use the controls in the variant blocks to create variant
objects. Alternatively, you can create variant objects in the Model Explorer or
at the command line.
The variant object can have any unique legal name. The value of the variant
object specifies a variant condition.
Each variant object corresponds to a different simulation environment. When
compiling the model, Simulink tests the variant condition specified by each
variant object. The variant object whose variant condition is true designates
the active variant. The active variant determines which variant is used
during simulation. You must organize the variant objects for a model variant
or a variant subsystem so that, when the model compiles, only one variant
condition is true based on the current base workspace values.
Note You cannot use the same variant object more than once in the same
variant block, because a conflict occurs when that variant condition is true.
The same type of conflict occurs in a variant block where two different variant
objects both evaluate to true. For more information, see “Reusing Variant
Objects” on page 8-33.

Creating Variant Objects
There are three techniques for defining variant objects for your applications.
Choose the technique that complements your workflow.

8-32

About Variant Objects

• Using the Create variant option
Click the Create/Edit selected variant button in either the Model
Variants block or the Variant Subsystem block dialog boxes. Specify the
condition in the dialog box and click Apply. The blocks create variant
objects for you in the base workspace, as described in “Configuring the
Model Variants Block” on page 8-9 and “Configuring the Variant Subsystem
Block” on page 8-20.
• In the Model Explorer
1 Select the Base Workspace.
2 Select Add > Simulink Variant.

The Model Explorer creates a new variant object named Variant in
the base workspace.
3 Specify the name and condition for the variant object in the same way

as from the variant blocks.
• In the MATLAB Command Window
Enter code like the following to define your variant object name and
condition:
variantObjectName=Simulink.Variant(conditionExpression)

For example:
DU=Simulink.Variant('FUEL==2 && EMIS==1')

Reusing Variant Objects
For simplicity, the example models, AutoMRVar and AutoSSVar, show only one
variant block. A variant block refers to a Model Variants block or a Variant
Subsystem block. Your applications may use multiple variant blocks.
Some applications have multiple variant blocks that might reuse some of
the same variant objects associated with their variants (referenced models
or subsystems). For example, a model or subsystem of an automobile might
include many capabilities that change depending on the applicable fuel and
emission standards. To meet those different requirements using variants,
you can use the same variant object in multiple variant blocks. To do this,
associate the variant object with the same, or a different, variant in each

8-33

8

Modeling Variant Systems

of the variant blocks. The variant blocks change their selected variants in
synchrony as variant control variable values change. The separate uses of the
variant object do not affect one another.
Other applications might associate multiple variant objects to one variant in a
Model Variants block. To do this, you can assign each of the variant objects
to a different parameterization or execution mode of the referenced model
variant. The separate uses of the referenced model do not affect one another.
Reusing variant objects, subsystems, and referenced models allows you to
globally reconfigure a model hierarchy to suit different environments by doing
nothing more than changing variant control variable values. No matter how
many simulation environments you define, selecting an environment requires
only setting variable or parameter values appropriately in the base workspace.

Variant Condition
A variant condition is the value of the variant object. Specify a Boolean
expression that references at least one base workspace variable or parameter.
The expression can include:
• MATLAB variables defined in the base workspace
• Simulink.Parameter objects defined in the base workspace
• Scalar variables
• Enumerated values
• Operators ==, !=, &&, ||, ~
• Parentheses for grouping
For instructions on specifying variant conditions, see “Configuring the Model
Variants Block” on page 8-9 and “Configuring the Variant Subsystem Block”
on page 8-20.
For instructions on variant control variables, see “Set Up Variant Control”
on page 8-25.

8-34

About Variant Objects

Note You can define the variant condition using a Simulink.Parameter
object of enumerated type. Doing so provides meaningful names and improves
the readability of the conditions. See “Using Enumerated Types for Variant
Control Variable Values” on page 8-27.

8-35

8

Modeling Variant Systems

Code Generation of Variants
Generating code from variants depends on your MathWorks code generation
software.
• Simulink Coder generates code only for the variant that is active in your
system.
• Embedded Coder generates code for all variants, unless you override
variant conditions and specify a variant for code generation.

-

By default, Embedded Coder generates code for all variants. The
generated code for each variant is surrounded by C preprocessor
conditionals, #if, #elif, and #endif. At C compile time, the
preprocessor conditionals select the active variant and determine which
code to execute.

-

You can specify a single variant for code generation by using the
Override variant conditions and use following variant option in
the Model Variants block or Variant Subsystem block.

For instructions, see “Generate Preprocessor Conditionals for Variant
Systems”.

8-36

Variant System Reference

Variant System Reference
In this section...
“Custom Storage Classes” on page 8-37
“Blocks” on page 8-37

Custom Storage Classes
Reference information for Simulink classes used in implementing variants:
• Simulink.Parameter for variant control variables
• Simulink.Variant for variant objects

Blocks
Reference information for blocks used in implementing variants:
• Model Variants block
• Variant Subsystem block

8-37

8

8-38

Modeling Variant Systems

9
Exploring, Searching, and
Browsing Models
• “Model Explorer Overview” on page 9-2
• “Model Explorer: Model Hierarchy Pane” on page 9-9
• “Model Explorer: Contents Pane” on page 9-19
• “Control Model Explorer Contents Using Views” on page 9-26
• “Organize Data Display in Model Explorer” on page 9-36
• “Filter Objects in the Model Explorer” on page 9-46
• “Workspace Variables in Model Explorer” on page 9-52
• “Search Using Model Explorer” on page 9-63
• “Model Explorer: Property Dialog Pane” on page 9-70
• “Finder” on page 9-73
• “Model Browser” on page 9-80
• “Model Dependency Viewer” on page 9-83
• “View Linked Requirements in Models and Blocks” on page 9-96

9

Exploring, Searching, and Browsing Models

Model Explorer Overview
In this section...
“What You Can Do Using the Model Explorer” on page 9-2
“Opening the Model Explorer” on page 9-2
“Model Explorer Components” on page 9-3
“The Main Toolbar” on page 9-4
“Adding Objects” on page 9-5
“Customizing the Model Explorer Interface” on page 9-5
“Basic Steps for Using the Model Explorer” on page 9-6
“Focusing on Specific Elements of a Model or Chart” on page 9-7

What You Can Do Using the Model Explorer
Use the Model Explorer to quickly view, modify, and add elements of Simulink
models, Stateflow charts, and workspace variables. The Model Explorer
provides several ways for you to focus on specific elements (for example,
blocks, signals, and properties) without your having to navigate through the
model diagram or chart.

Opening the Model Explorer
To open the Model Explorer, use one of these approaches:
• From the Simulink Editor View menu, select Model Explorer or select
the Model Explorer icon

from the toolbar.

• In an open model in the Simulink Editor, right-click a block and from the
context menu, select Explore.
• In an open Stateflow chart, right-click in the drawing area and from the
context menu, select Explore.
• At the MATLAB command line, enter daexplr.

9-2

Model Explorer Overview

Model Explorer Components
By default, the Model Explorer opens with three panes (Model Hierarchy,
Contents, and Dialog), a main toolbar, and a search bar.

Search bar

Model Hierarchy pane

Main toolbar

Contents pane

Dialog pane

9-3

9

Exploring, Searching, and Browsing Models

Component

Purpose

Documentation

Main toolbar

Execute Model Explorer
commands

“The Main Toolbar” on
page 9-4

Search bar

Perform a search within
the context of the selected
node in Model Hierarchy
pane.

“Search Using Model
Explorer” on page 9-63

Model
Hierarchy pane

Navigate and explore
model, chart, and
workspace nodes

“Model Explorer: Model
Hierarchy Pane” on page
9-9

Contents pane

Display and modify model
or chart objects

“Model Explorer: Contents
Pane” on page 9-19

Dialog pane

View and change the
details of object properties

“Model Explorer: Property
Dialog Pane” on page 9-70

The Main Toolbar
The main toolbar at the top of the Model Explorer provides buttons you click
to perform Model Explorer operations. Most of the toolbar buttons perform
actions that you can also perform using Model Explorer menu items.
The toolbar buttons in the following table perform actions that you cannot
perform using Model Explorer menus:
Button

Usage
Bring the MATLAB window to the front.
Display the Simulink Library Browser.

If you have Simulink Verification and Validation installed, you can use
additional toolbar buttons relating to requirements links.

9-4

Model Explorer Overview

Adding Objects
You can use the Model Explorer to add many kinds of objects to a model, chart,
or workspace. The types of objects that you can add depend on what node you
select in the Model Hierarchy pane. Use toolbar buttons or the Add menu
to add objects. The Add menu lists the kinds of objects you can add.

Customizing the Model Explorer Interface
You can customize the Model Explorer interface in several ways. This section
describes how to show or hide the main toolbar and how to control the font
size.
Other ways you can customize the Model Explorer interface include:

9-5

9

Exploring, Searching, and Browsing Models

• “Marking Nonexistent Properties” on page 9-45
• “Showing and Hiding the Search Bar” on page 9-64
• “Showing and Hiding the Dialog Pane” on page 9-70

Showing and Hiding the Main Toolbar
To show or hide the main toolbar, in the Model Explorer select View >
Toolbars > Main Toolbar.

Controlling the Font Size
You can change the font size in the Model Explorer panes:
• To increase the font size, press the Ctrl + Plus Sign (+).
Alternatively, from the Model Explorer View menu, select Increase Font
Size.
• To decrease the font size, press the Ctrl + Minus Sign (-).
Alternatively, from the Model Explorer View menu, select Decrease
Font Size.
Note The changes remain in effect for the Model Explorer and in the
Simulink dialog boxes across Simulink sessions.

Basic Steps for Using the Model Explorer
Use the Model Explorer to perform a wide range of activities relating to
viewing and changing model and chart elements. You can perform activities
in any order, using panes in the order you choose. Your actions in one pane
often affect other panes.
For example, if you want to edit properties of objects in a model, you might
use a general workflow such as:
1 Open a model.
2 Open the Model Explorer.

9-6

Model Explorer Overview

3 Select the model in the Model Hierarchy pane, specifying whether the

Model Explorer displays only the current system or the whole system
hierarchy of the current system
4 Control what model information the Contents pane displays, and how it

displays that information, by using a combination of:
• The View > Column View option to control which property columns to
display
• The View > Row Filter option to control which types of objects to
display
• Techniques to directly manipulate column headings
5 Identify model elements with specific values, using the search bar.
6 Edit the values for model elements, in either the Contents pane or the

Dialog pane. To edit workspace variables, you can use the Variable Editor.

Focusing on Specific Elements of a Model or Chart
As you explore a model or chart, you might want to narrow the contents that
you see in the Model Explorer to particular elements of a model or chart.
You can use several different techniques. The following table summarizes
techniques for controlling what content the Model Explorer displays and how
the contents appear.
Technique

When to Use

Documentation

Show partial or whole
model hierarchy
contents

To control how much of
a hierarchical model to
display

“Displaying Partial or
Whole Model Hierarchy
Contents” on page 9-12

Use the Row Filter
option

To focus on, or hide, a
specific kind of a model
object, such as signals

“Using the Row Filter
Option” on page 9-46

9-7

9

Exploring, Searching, and Browsing Models

Technique

When to Use

Documentation

Search

To find objects that
might not be currently
displayed

“Search Using Model
Explorer” on page 9-63

Filter contents

To focus on specific
objects in the Contents
pane, based on a search
string

“Filtering Contents” on
page 9-48

Once you have the general set of data that you are interested in, you can use
the following techniques to organize the display of contents.

9-8

Technique

When to Use

Documentation

Sort

To quickly organize
data for a property
in ascending or
descending order

“Sorting Column
Contents” on page
9-36

Group by property
column

To logically group data
based on values for a
property

“How to Group by a
Property Column” on
page 9-39

Use column views

To display a named
subset of property
columns to apply to
different kinds of
nodes in the Model
Hierarchy pane

“Control Model
Explorer Contents
Using Views” on page
9-26

Add, delete, or
rearrange property
table columns

To customize property
columns

“Organize Data Display
in Model Explorer” on
page 9-36

Model Explorer: Model Hierarchy Pane

Model Explorer: Model Hierarchy Pane
In this section...
“What You Can Do with the Model Hierarchy Pane” on page 9-9
“Simulink Root” on page 9-10
“Base Workspace” on page 9-10
“Configuration Preferences” on page 9-11
“Model Nodes” on page 9-11
“Displaying Partial or Whole Model Hierarchy Contents” on page 9-12
“Displaying Linked Library Subsystems” on page 9-13
“Displaying Masked Subsystems” on page 9-14
“Linked Library and Masked Subsystems” on page 9-14
“Displaying Node Contents” on page 9-14
“Navigating to the Block Diagram” on page 9-15
“Working with Configuration Sets” on page 9-15
“Expanding Model References” on page 9-15
“Cutting, Copying, and Pasting Objects” on page 9-17

What You Can Do with the Model Hierarchy Pane
The Model Hierarchy pane displays a tree-structured view of the Simulink
model and Stateflow chart hierarchy. Use the Model Hierarchy pane to
navigate to the part of the model and chart hierarchy that you want to explore.

9-9

9

Exploring, Searching, and Browsing Models

Simulink Root
The first node in the hierarchy represents the Simulink root. Expand the
root node to display nodes representing the MATLAB workspace, Simulink
models, and Stateflow charts that are in the current session.

Base Workspace
This node represents the MATLAB workspace. The MATLAB workspace is
the base workspace for Simulink models and Stateflow charts. Variables
defined in this workspace are visible to all open models and charts.
For information about exporting and importing workspace variables, see
“Exporting Workspace Variables” on page 9-60 and “Importing Workspace
Variables” on page 9-62.

9-10

Model Explorer: Model Hierarchy Pane

Configuration Preferences
To display a Configuration Preferences node in the expanded Simulink
Root node, enable the View > Show Configuration Preferences option.
Selecting this node displays the preferred configuration for new models
(see “Manage a Configuration Set” on page 10-12). You can change the
preferred configuration by editing the displayed settings and using the Model
Configuration Preferences dialog box to save the settings (see “Model
Configuration Preferences” on page 10-28).

Model Nodes
Expanding a model or chart node in the Model Hierarchy pane displays
nodes representing the following elements, as applicable for the models and
charts you have open.
Node

Description

Model workspace

For information about how to use the Model Explorer
to work with model workspace variables, see the
following sections:
• “Finding Variables That Are Used by a Model or
Block” on page 9-52
• “Finding Blocks That Use a Specific Variable” on
page 9-55
• “Editing Workspace Variables” on page 9-58
• “Exporting Workspace Variables” on page 9-60
• “Importing Workspace Variables” on page 9-62
• “Model Workspaces” on page 4-67

Configuration sets

For information about adding, deleting, saving,
and moving configuration sets, see “Manage a
Configuration Set” on page 10-12.

Top-level
subsystems

Expand a node representing a subsystem to display
underlying subsystems, if any.

9-11

9

Exploring, Searching, and Browsing Models

Node

Description

Model blocks

Expand model blocks to show contents of referenced
models (see “Expanding Model References” on page
9-15).

Stateflow charts

• Expand a node representing a Stateflow chart to
display the top-level states of the chart.
• Expand a node representing a state to display its
substates.

Displaying Partial or Whole Model Hierarchy
Contents
By default, the Model Explorer displays objects for the system that you select
in the Model Hierarchy pane. It does not display data for child systems.
You can override that default, so that the Model Explorer displays objects
for the whole hierarchy of the currently selected system. To toggle between
displaying only the current system and displaying the whole system hierarchy
of the current system, use one of these techniques:
• Select View > Show Current System and Below.
• Click the Show Current System and Below button (
the Contents pane.

) at the top of

When you select the Show Current System and Below option:
• The Model Hierarchy pane highlights in pale blue the current system
and its child systems.

9-12

Model Explorer: Model Hierarchy Pane

• After the path in the Contents of field, the text (and below) appears.
• The appearance of the Show Current System and Below button at the
top of the Contents pane and in the View menu changes.
• The status bar indicates the scope of the displayed objects when you hover
over the Show Current System and Below button.
Loading very large models for the current system and below can be slow. To
stop the loading process at any time, either click the Show Current System
and Below button or click another node in the tree hierarchy.
If you show the current system and below, you might want to change the view
to better reflect the displayed system contents. For details about views, see
“Control Model Explorer Contents Using Views” on page 9-26.
The setting for the Show Current System and Below option is persistent
across Simulink sessions.

Displaying Linked Library Subsystems
By default, the Model Explorer does not display the contents of linked library
subsystems in the Model Hierarchy pane. To display the contents of linked
library subsystems, use one of these approaches:
• At the top of the Model Hierarchy pane, click the Show/Hide Library
Links button ( ).
• From the View menu, select Show Library Links.
Library-linked subsystems are visible in the Contents pane, regardless of
how you configure the Model Hierarchy pane.
Note Search does not find elements in linked library or masked subsystems
that are not displayed in the Model Hierarchy pane.

9-13

9

Exploring, Searching, and Browsing Models

Displaying Masked Subsystems
By default, the Model Explorer does not display the contents of masked
subsystems in the Model Hierarchy pane. To display the contents of masked
subsystems, use one of these approaches:
• At the top of the Model Hierarchy pane, click the Show/Hide Masked
Subsystems button ( ) .
• From the View menu, select Show Masked Subsystems.
Masked subsystems are visible in the Contents pane, regardless of how you
configure the Model Hierarchy pane.

Linked Library and Masked Subsystems
For subsystems that are both library-linked and masked, how you set the
linked library subsystems and masked subsystems options affects which
subsystems appear in the Model Hierarchy pane, as described in the
following table.
Settings

Subsystems Displayed in the
Model Hierarchy Pane

Show Library Links

Only library-linked, unmasked
subsystems

Hide Masked Subsystems
Hide Library Links
Show Masked Subsystems
Show Library Links
Show Masked Subsystems

Only masked subsystems that are
not library-linked subsystems
All library-linked or masked
subsystems

Displaying Node Contents
Select the object in the Model Hierarchy pane whose contents you want to
display in the Contents pane.

9-14

Model Explorer: Model Hierarchy Pane

Navigating to the Block Diagram
To open a graphical object (for example, a model, subsystem, or chart) in an
editor window, right-click the object in the Model Hierarchy pane. From the
context menu, select Open.

Working with Configuration Sets
See “Manage a Configuration Set” on page 10-12 for information about using
the Model Hierarchy pane to perform tasks such as adding, deleting, saving,
and moving configuration sets.

Expanding Model References
To browse a model that includes Model blocks, you can expand the
Model Hierarchy pane nodes of the Model blocks. For example, the
sldemo_mdlref_depgraph model includes Model blocks that reference other
models. If you open the sldemo_mdlref_depgraph model and expand that
model node in the Model Hierarchy pane, you see that the model contains
several Model blocks, including heat2cost.

To browse a model referenced by a Model block:
1 Right-click the referenced model node in the Model Hierarchy pane.

9-15

9

Exploring, Searching, and Browsing Models

2 From the context menu, choose Open Model.

• The referenced model opens.
• The Model Hierarchy pane indicates that you can expand the Model
block node.
• The Model Hierarchy pane displays a separate expandable node for
the referenced model (read-only).
• The Contents pane displays objects corresponding to the Model block
node (read-only).
For example, if you right-click the heat2cost Model block node and select the
Open Model option, the Contents pane displays the objects corresponding
to the heat2cost Model block. You can expand the heat2cost node.

You can browse the contents of the referenced model, but you cannot edit the
model objects that are underneath the Model block.

9-16

Model Explorer: Model Hierarchy Pane

Editing the Referenced Model
To edit the referenced model, expand the referenced model node in the Model
Hierarchy pane. For example, expand the sldemo_mdlref_heat2cost node:

You can now edit the properties of object in the referenced model.
For information about referenced models, see “Model Reference”.

Cutting, Copying, and Pasting Objects
To cut, copy, and paste workspace objects from one workspace into another
workspace:
1 In the Contents pane, right-click on the workspace object you want to

cut or copy.
2 From the context menu, select Cut or Copy.

9-17

9

Exploring, Searching, and Browsing Models

• You can also cut a workspace object by selecting in the Contents pane
Edit > Cut or by clicking the Cut button ( ).
• You can also copy a workspace object by selecting Edit > Copy or by
clicking the Copy button ( ).
3 If you want to paste the workspace object that you cut or copied, in the

Model Hierarchy pane, right-click the workspace into which you want to
paste the object, and select Paste.
• You can also paste the object by selecting Edit > Paste or by clicking
the Paste button ( ).
You can also perform cut, copy, and paste operations by selecting an object
and performing drag and drop operations.

9-18

Model Explorer: Contents Pane

Model Explorer: Contents Pane
In this section...
“Contents Pane Tabs” on page 9-19
“Data Displayed in the Contents Pane” on page 9-22
“Link to the Currently Selected Node” on page 9-22
“Horizontal Scrolling in the Object Property Table” on page 9-23
“Working with the Contents Pane” on page 9-24
“Editing Object Properties” on page 9-25

Contents Pane Tabs
The Contents pane displays one of two tables containing information about
models and charts, depending on the tab that you select:
• The Contents tab displays an object property table for the node that you
select in the Model Hierarchy pane.
• The Search Results tab displays the search results table (see “Search
Using Model Explorer” on page 9-63).
Optionally, you can also open a column view details section in the Contents
pane. The following graphic shows the Contents pane with the column view
details section opened.

9-19

9

Exploring, Searching, and Browsing Models

Contents tab

Search Results tab

To open the column view details section, click Show Details, at the top of
the Contents pane.

9-20

Model Explorer: Contents Pane

Column
View
Details
section

Object
Property
Table
section

The Column view details section provides an interface for customizing
the column view (hidden by default).
The Object property table section displays a table of model and chart object
data (open by default).

9-21

9

Exploring, Searching, and Browsing Models

Data Displayed in the Contents Pane
In the object property table section of the Contents tab and in the Search
Results tab:
• Table columns correspond to object properties (for example, Name and
BlockType).
• Table rows correspond to objects (for example, blocks, and states).
The objects and properties displayed in the Contents pane depend on:
• The column view that you select in the Contents pane
• The node that you select in the Model Hierarchy pane
• The kind of object (for example, subsystem, chart, or configuration set) that
you select in the Model Hierarchy pane
• The View > Row Filter options that you select
For more information about controlling which objects and properties to
display in the Contents pane, see:
• “Control Model Explorer Contents Using Views” on page 9-26
• “Organize Data Display in Model Explorer” on page 9-36
• “Filter Objects in the Model Explorer” on page 9-46

Link to the Currently Selected Node
The Contents of link at the top left side of the Contents pane links to the
currently selected node in the Model Hierarchy pane. The model data
displayed in the Contents pane reflects the setting of the Current System
and Below option. In the following example, Contents of links to the vdp
model, which is the currently selected node.

9-22

Model Explorer: Contents Pane

Horizontal Scrolling in the Object Property Table
The object property table displays the first two columns (the object icon and
the Name property) persistently. These columns remain visible, regardless of
how far you scroll to the right.
For example, the following image shows the initial display of the object
property table for the vdp model. The ParamDataTypeStr column is too far
to the right to be displayed.

The next image shows the results of scrolling to the right. The icon and Name
columns remain visible, but now you can see the ParamDataTypeStr column.

9-23

9

Exploring, Searching, and Browsing Models

Working with the Contents Pane
The following table summarizes the key tasks to control what is displayed
in the Contents.

9-24

Task

Documentation

Control which kinds of objects to
display.

“Using the Row Filter Option” on
page 9-46

Search within the selected set of
objects.

“Search Using Model Explorer” on
page 9-63

Specify a set of properties to display
based on the kind of node.

“Control Model Explorer Contents
Using Views” on page 9-26

Group data based on unique values
in a property column.

“Grouping by a Property” on page
9-37

Manage views (for example, save
and export a view).

“Managing Views” on page 9-30

Add, remove, or rearrange columns.

“Organize Data Display in Model
Explorer” on page 9-36

Edit object property values.

“Editing Object Properties” on page
9-25

Model Explorer: Contents Pane

Editing Object Properties
To open a properties dialog box for an object in the Model Hierarchy
pane, right-click the object, and from the context menu, select Properties.
Alternatively, click an object and from the Edit menu, select Properties.
You can change modifiable properties in the Contents pane (for example, a
block name) by editing the displayed value. To edit a value, first select the
row that contains the value, and then click the value. An edit control replaces
the value (for example, an edit field for text values or a list for a range of
values). For workspace variables that are arrays or structures, you can use
the Variable Editor. Use the edit control to change the value of the selected
property.
To assign the same property value to multiple objects in the Contents
pane, select the objects and then change one of the selected objects to have
the new property value. An edit control replaces the value with ,
indicating that you are doing batch editing. The Model Explorer assigns the
new property value to the other selected objects, as well.
You can also change property values using the Dialog pane. See “Model
Explorer: Property Dialog Pane” on page 9-70.

9-25

9

Exploring, Searching, and Browsing Models

Control Model Explorer Contents Using Views
In this section...
“Using Views” on page 9-26
“Customizing Views” on page 9-29
“Managing Views” on page 9-30

Using Views
What Is a Column View?
A view in the Model Explorer is a named set of properties.
The Model Explorer uses views to specify sets of property columns to display
in the Contents pane.
For each kind of node in the Model Hierarchy pane, certain properties are
most relevant for the objects displayed in the Contents pane. For example,
for a Simulink model node, such as a model or subsystem, some properties
that are useful to display include:
• BlockType (block type)
• OutDataTypeStr (output data type)
• OutMin (minimum value for the block output)
Generally, a column view does not contain the total set of properties for
all the objects in a node. Specifying a subset of properties to display can
streamline the task of exploring and editing model and chart object properties
and increase the density of the data displayed in the Contents pane.

What You Can Capture in a View
You can use a view to capture the following characteristics of the model
information to show in the Model Explorer:
• Properties that you want to display in the Contents pane (see “Customizing
Views” on page 9-29)

9-26

Control Model Explorer Contents Using Views

• Layout of the Contents pane (for example, grouping by property, the order
of property columns, and sorting), as described in “Organize Data Display
in Model Explorer” on page 9-36.

Use Standard Views or Customized Views
You can use views in the following ways:
• Use the standard views shipped with the Model Explorer
• Customize the standard views
• Create your own views

Automatically Applied Views
The first time you open the Model Explorer, the software automatically applies
one of the standard views to the node you select in the Model Hierarchy
pane. The Model Explorer applies a view based on the kind of node you select.
The Model Explorer assigns one of four categories of nodes in the Model
Hierarchy pane. The Model Explorer initially associates a default view with
each node category. The four node categories are:
Node Category

Kinds of Hierarchy
Nodes Included

Initial Associated
View

Simulink

Models, subsystems,
and root level models

Block Data Types

Workspace

Base and model
workspace objects

Data Objects

Stateflow

Stateflow charts and
states

Stateflow

Other

Objects that do not fit
into one of the first
three categories; for
example, configuration
sets

Default

9-27

9

Exploring, Searching, and Browsing Models

The Column View field at the top of the Contents pane displays the view
that the Model Explorer is currently using.
If you select a view. In the Contents pane, from the Column View
list, you can select a different view. If you select a different view, then the
Model Explorer associates that view with the category of the current node.
For example, suppose the selected node in the Model Hierarchy pane is a
Simulink model, and the current view is Data Objects. If you change the
view to Signals, then when you select another Simulink model node, the
Model Explorer uses the Signals view. See “Selecting a View Manually”
on page 9-28.

Selecting a View Manually
By default, the Model Explorer automatically applies a view, based on the
category of node that you select and the last view used for that node. You can
manually select a view from the Column View list that better meets your
current task.
You can shift from the default mode of having the Model Explorer
automatically apply views to a mode in which you must manually select a
view to change views.
To enable the manual view selection mode:
1 Select View > Column View > Manage Views.

The View Manager dialog box opens.
2 In the View Manager dialog box, click the Options button and clear

Change View Automatically.
In the manual view selection mode, if you switch to a different kind of node in
the Model Hierarchy pane that has a different view associated with it, the
Contents pane displays a yellow informational bar suggesting a view to use.

9-28

Control Model Explorer Contents Using Views

Tip interface. The tip interface appears immediately above the object
property table.
The tip does not appear if you use automatic view selection.
To hide the currently displayed tip, from the menu button on the right-hand
side of the tip bar, select Hide This Tip.
The tip interface displays a link for changing the current view to a suggested
view. To choose the suggested view displayed in the tip bar, click the link.
Initially, the suggested view is the default view associated with a node. If you
associate a different view with a node category, then the tip suggests the most
recently selected view when you select similar nodes.
To change from manual specification of views to automatic specification,
from the tip interface, select the down arrow and then the Change View
Automatically menu item.

Customizing Views
If a standard view does not meet your needs, you can either modify the view
or create a new view.
You can customize the object property table represented by the current view
in several ways, as described in these sections:
• “Adding Property Columns” on page 9-42
• “Hiding or Removing Property Columns” on page 9-43
• “Changing the Order of Property Columns” on page 9-41

9-29

9

Exploring, Searching, and Browsing Models

How the Model Explorer Saves Your Customizations
As you modify the object property table, you change the current view
definition.
The Model Explorer saves the following changes to the object property table
as part of the column view definition:
• Grouping by property
• Sorting in a column
• Changing the order of property columns
• Adding a property column
• Hiding and removing property columns
When you change from one view to another view, the Model Explorer saves
any customizations that you have made to the previous view.
For example, suppose you use the Block Data Types view and you remove
the LockScale property column. If you then switch to use the Data Objects
view, and later use the Block Data Types view again, the Block Data Types
view no longer includes the LockScale column that you deleted.
At the end of a Simulink session, the Model Explorer saves the view
customizations that you made during that session. When you reopen the
Model Explorer, Simulink uses the customized view, reflecting any changes
that you made to the view in the previous session.

Managing Views
If a standard view does not meet your needs, you can either modify the view
or create a new view. See “Customizing Views” on page 9-29.
You can manage views (for example, create a new view or export a view)
using the View Manager dialog box.

Opening the View Manager Dialog Box
To open the View Manager dialog box, select the Manage Views option
from either:

9-30

Control Model Explorer Contents Using Views

• The View > Column View menu
• The options listed when you click the Options button in the column view
details section
The View Manager dialog box displays a list of defined views and provides
tools for you to manage views.

You can manage views in several ways, including:
• “Creating a New View” on page 9-32
• “Deleting Views” on page 9-33
• “Reordering Views” on page 9-33
• “Exporting Views” on page 9-33
• “Importing Views” on page 9-34
• “Resetting Views to Factory Settings” on page 9-34

9-31

9

Exploring, Searching, and Browsing Models

Creating a New View
To create a new view that has a new name, you can use one of these
approaches:
• Copy an existing view, rename it, and customize the view.
• Create a completely new view.
After you create a new view, you can customize the view as described in
“Customizing Views” on page 9-29.
Copying and renaming an existing view. You can build a new view
by copying an existing view, renaming it, and optionally customizing the
renamed view. In the View Manager dialog box:
1 Select the view that you want to use as the starting point for your new view.
2 Click the Copy button.

A new row appears at the bottom of the View Manager table of views. The
new row contains the name of the view you copied, followed by a number in
parentheses. For example, if you copy the Stateflow view, the initial name
of the copied view is Stateflow (1).
Creating a completely new view. To create a completely view, in the View
Manager dialog box, click the New button. A new view row appears at the
bottom of the View Manager dialog box list of views.
Naming and describing a new view. Once you create a view, you can
name the view and provide a description of the view:
1 Double-click New View in the left column of the table of views and replace

the text with a name for the view.
2 Double-click Description in the table and replace the text with a

description of the view.
3 Click OK.

9-32

Control Model Explorer Contents Using Views

Deleting Views
To delete a view from the Column View list of views:
1 In the View Manager dialog box, select one or more views that you want to

remove from the list.
2 Click the Delete button or the Delete key.
3 Click OK.

Deleting a view using the View Manager dialog box permanently deletes that
view from the Model Explorer interface.
If you think you or someone else might want to use a view again, consider
exporting the view before you delete it (see “Exporting Views” on page 9-33).

Reordering Views
To change the position of a view in the Column View list, in the View
Manager dialog box:
1 Select one or more views that you wish to move up or down one row in

the table of views.
2 Click the up or down arrow buttons to the right of the table of views.

Repeat this step until the view appears where you want it to be in the table.
3 Click OK.

Exporting Views
To export views that you or others can then import, in the View Manager
dialog box:
1 In the View Manager dialog box, select one or more views that you want to

export.
2 Click the Export button.

An Export Views dialog box opens, with check marks next to the views
that you selected.

9-33

9

Exploring, Searching, and Browsing Models

3 Click OK.

An Export to File Name dialog box opens.
4 Navigate to the folder to which you want to export the view.

By default, the Model Explorer exports views to the MATLAB current
folder.
5 Specify the file name for the exported view.

The file format is .mat.
6 Click OK.

Importing Views
To import view files from another location for use by the Model Explorer:
1 In the View Manager dialog box, click the Import button.

The Select .mat File to Import dialog box opens.
2 Navigate to the folder from which you want to import the view.
3 Select the MAT-file containing the view that you want to import and then

click Open.
A confirmation dialog box opens. Click OK to import the view.
The imported view appears at the bottom of the Column View list of views.
The Model Explorer automatically renames the view if a name conflict occurs.

Resetting Views to Factory Settings
You can reset (restore) the original definition of a specific standard view (that
is, a view shipped with the Model Explorer) if that view is the current view.
To do so, click the Options button in the column view details section and
select Reset This View to Factory Settings.

9-34

Control Model Explorer Contents Using Views

To reset the factory settings for all standard views in one step, in the View
Manager dialog box, click the Options button and select Reset All Views
to Factory Settings.
Note When you reset all views, the Model Explorer removes all the custom
views you have created. Before you reset views to factory settings, export any
views that you will want to use in the future.

9-35

9

Exploring, Searching, and Browsing Models

Organize Data Display in Model Explorer
In this section...
“Layout Options” on page 9-36
“Sorting Column Contents” on page 9-36
“Grouping by a Property” on page 9-37
“Changing the Order of Property Columns” on page 9-41
“Adding Property Columns” on page 9-42
“Hiding or Removing Property Columns” on page 9-43
“Marking Nonexistent Properties” on page 9-45

Layout Options
You can control how the object property table and Search Results pane
organize the layout of property information by:
• Sorting column contents
• Grouping by a property
• Changing the order of property columns
• Adding a property column
• Hiding and removing property columns

Sorting Column Contents
To sort the column contents in ascending order, click the heading of the
property column. A triangle pointing up appears in the column heading.
To change the order from ascending to descending, or from descending to
ascending, click the heading of the column again.
For example, if properties are in ascending order, based on the Name property
(the default), click the heading of the Name column to display objects by name,
in descending order.

9-36

Organize Data Display in Model Explorer

By default, the Contents pane displays its contents in ascending order,
based on the name of the object. Objects that have no values in any property
columns appear at the end of the object property table.
Note When you group by property, the Model Explorer applies sorting of
column contents within each group.

Grouping by a Property
Organizing Contents by Property Values
When you explore a model, you might want to focus on all objects with the
same property value. One approach is to group data by a property column.
For example, suppose that you want to see all of the blocks in the f14 model.
You could perform the following search.

The search results obscure the whole path name for lower-level nodes:

9-37

9

Exploring, Searching, and Browsing Models

By grouping on the Path property column, you see the whole path for
lower-level nodes.

9-38

Organize Data Display in Model Explorer

You can also collapse groups to focus on specific portions of a model.

How to Group by a Property Column
To group by a property:
1 In the object property table, right-click the column heading of the property

by which you want to group contents.
You can group by object icons, such as a block icon ( ), which represents a
type of object. Right-click the empty column heading in the first column.
2 From the context menu, select the Group By This Column menu item.

9-39

9

Exploring, Searching, and Browsing Models

Sorting with Grouped Data
When you group by property, the Model Explorer applies sorting of column
contents within each group.

Expanding and Collapsing Grouped Data
By default, Model Explorer displays groups in expanded form. That is, all the
objects in each group are visible. You can collapse and expand groups.
• To collapse the contents of a group, click the minus sign icon for that group.
• To expand a group, click the plus sign.
• To collapse or expand all the groups, right-click anywhere in the object
property table and select either the Collapse All Groups menu item
(Shift+C) or Expand All Groups menu item (Shift+E).

Hiding the Group Column
By default, the property column that you use for grouping appears in the
property table. That property also appears in the top row for each group.
To hide the group column in the property table, use one of the following
approaches:
• From the View menu, clear the Show Group Column check box.
• Right-click a column heading in the property table and clear the Show
Group Column check box.

Persistence of Grouped Data Settings
If you group by a property, that grouping is saved as part of the view
definition.
When you select a different node in the Model Hierarchy pane, the contents
for the new node are grouped by that same property. However, all groups are
expanded, even if you had collapsed all groups before switching nodes.

9-40

Organize Data Display in Model Explorer

Grouping Search Results
You can use grouping to organize the Search Results pane. The grouping
that you apply to the Search Results pane also applies to the object property
table, if that property is in the table. If the search results include a property
that is not in the object property table, and you group on that property, then
the Model Explorer removes the grouping setting that was in effect in the
object property table.

Changing the Order of Property Columns
Object Icon and Name Columns Are Always First
The first two columns of every object property table are the object icon column
(the column with a blank column heading) and the Name property column. You
cannot hide, remove, or change the location of the first two columns.

How to Change the Order of Property Columns
To change the order of property columns in the object property table, use one
of these approaches:
• In the object property table, select a column heading and drag it to a new
location in the table.
This approach avoids opening the column view details section and makes it
easier to move a column a short distance to the right or left.
• In the column view details section, select one or more property columns
and move them up or down in the list, using the arrow buttons to the
right of the list.
This approach allows you to move several property columns in one step, but
it moves the selected columns right or left by only one column at a time.
To move a property column by using the view details interface:
1 In the Display column names in this order list on the right side of

the column view details section, select one or more property columns
that you want to move.

9-41

9

Exploring, Searching, and Browsing Models

2 Click the Move column left in view button (

right in view button (

) or the Move column

).

Adding Property Columns
To add property columns to a view:
1 If you do not have the column view details section of the Contents pane

already open, then at the top of the Contents pane, select Show Details.

9-42

Organize Data Display in Model Explorer

2 In the list of properties on left side of the column view details section, select

one or more properties that you want to add.
• The list displays property names in alphabetical order. You can use the
Find Properties search box in the column view details section to search
for properties that contain the text string that you enter. You can specify
the scope of the search with the From list to the right of the search box.
3 In the list of column names on the right side, select the property column

that you want to be to the left of the property columns you insert.
4 Click the Display property as column in view button (

)

Adding a Path Property Column
The Model Explorer provides a shortcut for adding a Path property column to
a view. To add a Path property column:
1 Right-click the column heading in the object property table to the right of

which you want to insert a Path column.
2 From the context menu, select Insert Path.

Hiding or Removing Property Columns
You can choose between two approaches to hide (remove) a property column
from the object property table. Hiding and removing a column both have the
same result. You can:
• Hide a column using the context menu for a column heading. This approach
avoids needing to open the column view details section.
• Remove a column using the column view details interface. This approach
allows you to delete several properties in one step.

Hiding a Column Using the Column Heading Context Menu
1 Right-click the column heading of the column that you want to remove.
2 From the context menu, select Hide.

9-43

9

Exploring, Searching, and Browsing Models

Removing a Column Using the Column View Details Interface
1 If you do not have the column view details section of the Contents pane

already open, then at the top of the Contents pane, select Show Details.

2 In the column view details section of the Contents pane, in the Display

column names in this order list, select one or more properties that you
want to remove.
3 Click the Remove column from view button (

) or the Delete key.

Inserting Recently Hidden or Removed Columns
The Model Explorer maintains a list of columns you hide or remove for each
view during a Simulink session.
To add a recently hidden or removed column back into a view:
1 Right-click the column heading of the column to the right of which you

want to insert a recently hidden column.
2 From the context menu, select Insert Recently Hidden Columns.
3 Select the column that you want to insert.

See “Hiding or Removing Property Columns” on page 9-43.

9-44

Organize Data Display in Model Explorer

Marking Nonexistent Properties
Usually, some of the properties that the Contents pane displays do not apply
to all the displayed objects (in other words, some objects do not have values
set). By default, the Model Explorer displays a dash (–) to mark properties
that do not have a value.
If you want the Model Explorer to display a blank (instead of the default dash)
in property cells that have no values, clear the View > Show Nonexistent
Properties as “–” option. The Contents pane looks similar to the following
graphic:

9-45

9

Exploring, Searching, and Browsing Models

Filter Objects in the Model Explorer
In this section...
“Controlling the Set of Objects to Display” on page 9-46
“Using the Row Filter Option” on page 9-46
“Filtering Contents” on page 9-48

Controlling the Set of Objects to Display
Two techniques that you can use to control the set of objects that the
Contents pane displays are:
• Using the Row Filter option
• Filtering contents
For a summary of other techniques, see “Focusing on Specific Elements of a
Model or Chart” on page 9-7.

Using the Row Filter Option
You can filter the kinds of objects that the Contents pane displays:
1 Open the Row Filter options menu. In the Model Explorer, at the top-right

corner of the Contents pane, click the Row Filter button.

9-46

Filter Objects in the Model Explorer

An alternative way to open the Row Filter menu is to select View > Row
Filter.
By default, the Contents pane displays these kinds of objects for the
selected node:
• Blocks
• Signals and connections
• Stateflow states, functions, and boxes
• Stateflow events
• Stateflow data
2 Clear the kinds of objects that you do not want to display in the Contents

pane, or enable any cleared options to display more kinds of objects. For
example, clear All Signals/Connections to prevent the display of signal
and connection objects in the Contents pane.

Object Count
The top-right portion of the Contents pane includes an object counter,
indicating how many objects the Contents pane is displaying.

9-47

9

Exploring, Searching, and Browsing Models

When you use the Row Filter option to filter objects, the object count
indicator reflects that the Contents pane displays a subset of all the model
and chart objects.
To view an explanation of the current object count, click the object count link
(for example, 12 of 25 objects). That link displays a pop-up information
box:

Filtering Contents
To refine the display of objects that are currently displayed in the Contents
pane, you can use the Filter Contents text box at the top of the Contents
pane to specify search strings for filtering a subset of objects.

9-48

Filter Objects in the Model Explorer

Using the Filter Contents text box can help you to find specific objects
within the set of objects, based on a particular object name, property value, or
property that is of interest to you. For example, if you enter the text string
fuel in the Filter Contents edit box, the Model Explorer displays results
similar to those shown above. The results highlight the text string that you
specified.

Specifying Filter Text Strings
As you enter text in the Filter Contents text box, the Model Explorer
performs a dynamic search, displaying results that reflect the text as you
enter it.
The text strings you enter must be in the format consistent with the guidelines
described in the following sections.
Case Sensitivity. By default, the Model Explorer ignores case as it performs
the filtering.
To specify that you want the Model Explorer to respect case sensitivity for
a text string that you enter, put that text string in quotation marks. For
example, if you want to restrict the filtering to display only objects that
include the text Fuel (with a capital F), enter "Fuel" (with quotation marks).

9-49

9

Exploring, Searching, and Browsing Models

Specifying Property Values. To restrict the filtering to apply to values for
a specific property, specify the property name followed by a colon (:) and
then the value. For example, to filter the contents to display only objects
whose OutDataTypeStr property has a value that includes Inherit, enter
OutDataTypeStr: Inherit (alternatively, you could put the whole string in
quotation marks to enforce case sensitivity):

Wildcards and MATLAB Expressions Not Supported. The Model
Explorer does not recognize wildcard characters, such as an asterisk (*), as
having any special meaning. For example, if you enter fuel* in the Filter
Contents text box, you get no results, even if several objects contain the
text string fuel.
Also, if you specify a MATLAB expression, in the Filter Contents text box,
the Model Explorer interprets that string as literal text, not as a MATLAB
expression.

Clearing the Filtered Contents
To redisplay the object property table as it appeared before you filtered the
contents, click the X in the Filter Contents text box.

9-50

Filter Objects in the Model Explorer

Filtering Removes Grouping
If you have set up grouping on a column, then when you filtering contents,
the Model Explorer does not retain that grouping.

9-51

9

Exploring, Searching, and Browsing Models

Workspace Variables in Model Explorer
In this section...
“Finding Variables That Are Used by a Model or Block” on page 9-52
“Finding Blocks That Use a Specific Variable” on page 9-55
“Finding Unused Workspace Variables” on page 9-56
“Editing Workspace Variables” on page 9-58
“Exporting Workspace Variables” on page 9-60
“Importing Workspace Variables” on page 9-62

Finding Variables That Are Used by a Model or Block
In the Model Explorer, you can get a list of variables that a model or block
uses. The following approach is one way to get that list of variables:
1 In the Contents pane, right-click the block for which you want to find

the variables that it uses.
2 Select the Find Referenced Variables menu item.

9-52

Workspace Variables in Model Explorer

Model Explorer returns results similar to these:

9-53

9

Exploring, Searching, and Browsing Models

For performance, Model Explorer uses cached information from the last
compiled version of the model. If you want to recompile the model, either do
so manually or, in the Model Explorer, set the Update diagram field to
yes and repeat the search.
You can also use the following approaches to find variables that a model or
block uses:
• In the Model Explorer, in the Model Hierarchy pane, right-click a block
or model node and select the Find Referenced Variables menu item.
• In the Model Explorer, in the search bar, use the for Referenced
Variables search type option.
• In the Model Editor, right-click a block, subsystem, or in the canvas and
select the Find Referenced Variables menu item. Clicking the canvas
returns results for the whole model.
The Simulink.findVars function provides additional options for returning
information about workspace variables that is not available from the Model
Explorer or Model Editor.

9-54

Workspace Variables in Model Explorer

For information about limitations when finding referenced variables, see the
Simulink.findVars documentation.

Using the Set of Returned Variables
For a variable in the set of returned variables, you can find the blocks that use
that variable (for details, see “Finding Blocks That Use a Specific Variable” on
page 9-55). Also, you can export variables from the returned set of variables.
For details, see “Exporting Workspace Variables” on page 9-60.

Finding Blocks That Use a Specific Variable
You can use the Model Explorer to get a list of blocks that use a specific
workspace variable. One way to get that list of blocks is to right-click a
variable in the Contents pane and select the Find Where Used menu item.
For example:
1 Open the f14 model.
2 Open the Model Explorer.
3 In the Model Hierarchy pane, select the Base Workspace node.
4 In the Contents pane, right-click the Mq variable and select the Find

Where Used menu item.
5 In the Hierarchy dialog box that appears, select f14. The Model Explorer

displays output similar to this:

9-55

9

Exploring, Searching, and Browsing Models

The property columns whose values include Mq represent the block
parameters that use the Mq variable. If those property columns are not
already in the view, then the Model Explorer adds them to the end of the
search results display.
You can also find blocks that use a specific variable, by using one of these
approaches:
• In the search bar, select the for Variable Usage search type option.
• In the Search Results pane, right-click a variable and select the Find
Where Used menu item.
If you do not find the variable that you are looking for because that variable is
not in the currently selected system, try selecting View > Show Current
System and Below and repeat the search.

Finding Unused Workspace Variables
You can use the Model Explorer to get a list of variables that are defined in
a workspace but not used by a model or block. One way to get that list of
variables is to right-click a workspace name in the Model Hierarchy pane
and select the Find Unused Variables menu item. For example:
1 Open the f14 model.
2 Open the Model Explorer.
3 In the search toolbar, set the Update diagram field to yes.
4 In the Model Hierarchy pane, right-click the Base Workspace node and

select the Find Unused Variables menu item.

9-56

Workspace Variables in Model Explorer

5 The Model Explorer displays output similar to this:

9-57

9

Exploring, Searching, and Browsing Models

The Simulink.findVars function provides additional options for returning
information about unused workspace variables that is not available from
the Model Explorer or Model Editor.

Editing Workspace Variables
In the Model Explorer Contents pane, you can use the Variable Editor to edit
variables from the MATLAB workspace or model workspace. The Variable
Editor is available for editing large arrays and structures.
To open the Variable Editor for a variable that is an array or structure:
1 Click the Value cell for the variable.
2 Select the Variable Editor icon.

The Variable Editor opens:

9-58

Workspace Variables in Model Explorer

Right-click in an edit box to open a context menu with several editing options:

You can resize and move the Variable Editor. The Contents pane reflects the
edits that you make in the Variable Editor.
When you finish editing, the Variable Editor closes when you click the Close
button in the upper right corner of the editor or when you click outside of
the editor.

9-59

9

Exploring, Searching, and Browsing Models

Exporting Workspace Variables
You can export (save) a set of variables listed in the Model Explorer, exporting
either individual variables or all the variables in the base or model workspace.
One possible workflow is to export the set of variables returned with the
Find Referenced Variables option or the Simulink.findVars function.
For details, see “Finding Variables That Are Used by a Model or Block” on
page 9-52.
Note All the variables that you export must be from the same workspace.
To export all the variables in a workspace in the Model Explorer to a MATLAB
code file or MAT-file:
1 Select the variables that you want to export.
a To select all the variables in a workspace, right-click the workspace

node (for example, Base Workspace) and select the Export menu item.
For example:

9-60

Workspace Variables in Model Explorer

b To select individual variables, in the Contents pane, select the variables

that you want to export. Right-click one of the highlighted variables and
select the Export Selected menu item.
If the Contents pane has data grouped by a property, selecting the top line
in a group does not select all the variables in that group. For details about
grouped data, see“Grouping by a Property” on page 9-37.
2 Specify whether to save the variables in a MATLAB code file or a MAT-file.

The MATLAB code file format is easier to read, is editable, and supports
version control. The MAT-file format is binary, which has performance
advantages.
If you specify a MATLAB code file format, the Model Explorer may create
an associated MAT-file, reflecting the name of the MATLAB code file, but
with an extension of .mat instead of .m.
3 Specify a name and location for the file.

9-61

9

Exploring, Searching, and Browsing Models

4 If the file already exists, Model Explorer displays a dialog box asking you to

choose one of these options:
• Overwrite entire file
– Replaces all variables in the target file with the selected variables,
which are stored in alphabetical order.
• Update variables that exist in file and append new variables
to file
– Updates existing variables in place and appends new variables.
• Only update variables that exist in file
– Updates existing variables, but does not add any new variables, which
eliminates potentially extraneous variables.

Importing Workspace Variables
You can import (load) a set of variables from a file into the base workspace or
into a model workspace using the Model Explorer. When you import variables
into a workspace, the Model Explorer overwrites existing variables and adds
any new variables.
To import variables into a workspace:
1 In the Model Hierarchy pane, right-click the workspace into which you

want to import variables.
2 Select the Import menu item.
3 In the Import from File dialog box, select a MATLAB code file or MAT-file

for the variables that you want to import.
Note If you import a MATLAB code file, then Simulink also imports the
associated MAT-file.

9-62

Search Using Model Explorer

Search Using Model Explorer
In this section...
“Searching in the Model Explorer” on page 9-63
“The Search Bar” on page 9-64
“Showing and Hiding the Search Bar” on page 9-64
“Search Bar Controls” on page 9-64
“Search Options” on page 9-66
“Search Button” on page 9-68
“Refining a Search” on page 9-69

Searching in the Model Explorer
Use the Model Explorer search bar to search for specific objects from the node
you select in the Model Hierarchy pane.
The Model Explorer displays search results in the Search Results tab of
the Contents pane.
The search results appear in a table that is similar to the object property table
in the Contents tab. The search results table uses the current column view
(the object property table) definition as a starting point, and adds relevant
properties that are not already included in the current view. Any additional
property columns added to the Search Results pane do not affect the view
definition.
If you modify the property columns in the search results table that also
appear in the property table view, the changes you make affect both tables.
For example, if you hide OutMax column in the search results table, and the
OutMax column was also in the object property view table, then the OutMax
column is hidden in both tables. However, if in the search results table you
reorder where the Complexity column appears, if the view does not include
the Complexity property, then that change to the search results table does
not affect the view.
You can edit property values in the search results table.

9-63

9

Exploring, Searching, and Browsing Models

The Search Bar
The search bar appears at the top of the Model Explorer window.

Search
bar

Showing and Hiding the Search Bar
By default, the search bar is visible. To show or hide the search bar, select or
clear the View > Toolbars > Search Bar option.

Search Bar Controls
The search bar includes the following controls:
Select
search
type

Specify
search
criteria

Select
search
options

Start
search

Search Type
Use the Search Type control to specify the type of objects or properties to
include in the search.

9-64

Search Using Model Explorer

Search Type Option

Description

by Name

Searches a model or chart for all
objects that have the specified string
in the name of the object. See
“Search Strings” on page 9-68.

by Property Name

Searches for objects that have a
specified property. Specify the
target property name from a list of
properties that objects in the search
domain can have.

by Property Value

Searches for objects with a property
value that matches the value you
specify. Specify the name of the
property, the value to be matched,
and the type of match (for example,
equals, less than, or greater than).
See “Search Strings” on page 9-68.

by Block Type

Searches for blocks of a specified
block type. Select the target block
type from the list of types contained
in the currently selected model.

by Stateflow Type

Searches for Stateflow objects of a
specified type.

for Variable Usage

Searches for blocks that use
variables defined in a workspace.
Select the base workspace or a
model workspace (model name) and,
optionally, the name of a variable.
See “Search Strings” on page 9-68.

for Referenced Variables

Searches for variables that a model
or block uses. Specify the name of
the model or block in the by System
field. The model or block must be in
the Model Hierarchy pane.

9-65

9

Exploring, Searching, and Browsing Models

Search Type Option

Description

for Unused Variables

Searches for variables that are
defined in a workspace but not used
by any model or block. Select the
name of the workspace from the
drop-down list for the in Workspace
field.

for Library Links

Searches for library links in the
current model.

by Class

Searches for Simulink objects of a
specified class.

for Fixed Point Capable

Searches a model for all blocks that
support fixed-point computations.

for Model References

Searches a model for references to
other models.

by Dialog Prompt

Searches a model for all objects
whose dialogs contain the prompt
you specify. See “Search Strings” on
page 9-68.

by String

Searches a model for all objects in
which the string you specify occurs.
See “Search Strings” on page 9-68.

Search Options
Use the Search Options control to specify the scope and how to apply search
strings.

9-66

Search Option

Description

Match Whole String

Do not allow partial string matches
(for example, do not allow sub to
match substring).

Match Case

Considers case when matching
strings (for example, Gain does not
match gain).

Search Using Model Explorer

Search Option

Description

Regular Expression

Considers a string to be matched as
a regular expression.

Evaluate Property Values
During Search

Applies only for searches by property
value. If enabled, the option causes
the Model Explorer to evaluate the
value of each property as a MATLAB
expression and compare the result
to the search value. If this option
is disabled (the default), the Model
Explorer compares the unevaluated
property value to the search value.

Refine Search

Initiates a secondary search that
provides additional search criteria to
refine the initial search results. The
second search operation searches for
objects that meet both the original
and the new search criteria (see
“Refining a Search” on page 9-69).

By default, the Model Explorer searches for objects in the system that you
select in the Model Hierarchy pane. It does not search in child systems. You
can override that default, so that the Model Explorer searches for objects
in the whole hierarchy of the currently selected system. To toggle between
searching only in the current system and searching in the whole system
hierarchy of the current system, use one of these techniques:
• Select View > Show Current System and Below.
• Click the Show Current System and Below button at the top of the
Contents pane.

9-67

9

Exploring, Searching, and Browsing Models

Search Strings
By default, search strings are case-insensitive and are treated as regular
expressions.
By default, the search allows partial string matches. You cannot use wildcard
characters in search strings. For example, if you enter *1 as a name search
string, you get no search results unless there is an item whose name starts
with the two characters *1. If there is an out1 item, the search results do
not include that item.

Search Button
Click the Search button to start the search specified by the current settings
of the search bar on the object selected in the Model Hierarchy pane. The
Model Explorer displays the results of the search in the Search Results pane.
The top of the Search Results pane displays a summary of the results,
including the scope of the search and the search criteria that you specified.

9-68

Search Using Model Explorer

You can edit the results displayed in the Search Results pane. For example,
to change all objects found by a search to have the same property value,
select the objects in the Search Results pane and change the property value
of one of the objects.

Refining a Search
To refine the previous search, in the search bar, click the Select Search
Options button ( ) and select Refine Search. A Refine button replaces
the Search button on the search bar. Use the search bar to define new search
criteria and then click the Refine button. The Model Explorer searches for
objects that match both the previous search criteria and the new criteria.

9-69

9

Exploring, Searching, and Browsing Models

Model Explorer: Property Dialog Pane
In this section...
“What You Can Do with the Dialog Pane” on page 9-70
“Showing and Hiding the Dialog Pane” on page 9-70
“Editing Properties in the Dialog Pane” on page 9-70

What You Can Do with the Dialog Pane
You can use the Dialog pane to view and change properties of objects that
you select in the Model Hierarchy pane or in the Contents pane.

Showing and Hiding the Dialog Pane
By default, the Dialog pane appears in the Model Explorer, to the right of
the Contents pane. To show or hide the Dialog pane, use one of these
approaches:
• From the View menu, select Show Dialog Pane.
• From the main toolbar, click the Dialog View button (

).

Editing Properties in the Dialog Pane
To edit property values using the Dialog pane:
1 In the Contents pane, select an object (such as a block or signal). The

Dialog pane displays the properties of the object you selected.

9-70

Model Explorer: Property Dialog Pane

2 Change a property (for example, the port number of an Outport block)

in the Dialog pane.
3 Click Apply to accept the change, or click Revert to return to the original

value.
By default, clicking outside a dialog box with unapplied changes causes the
Apply Changes dialog box to appear:

Click Apply to accept the changes or Ignore to revert to the original settings.
To prevent display of the Apply Changes dialog box:
1 In the dialog box, click the In the future Apply or Ignore (whichever I

select) without asking check box.

9-71

9

Exploring, Searching, and Browsing Models

2 If you want Simulink to apply changes without warning you, press Apply.

If you want Simulink to ignore changes without warning you, press Ignore.
To restore display of the Apply Changes dialog box, from the Tools menu,
select Prompt if dialog has unapplied changes.

9-72

Finder

Finder
In this section...
“Find Model Objects” on page 9-73
“Filter Options” on page 9-75
“Search Criteria” on page 9-76

Find Model Objects
Use the Finder to locate blocks, signals, states, or other objects in a model.
1 Open the Finder. In the Simulink Editor, either select Edit > Find, or

press Ctrl+F.

2 In the Filter options area, specify the kinds of objects to look for, and

where to search for them. See “Filter Options” on page 9-75.
3 In the Search criteria area, specify the criteria that objects must meet to

satisfy your search request. See “Search Criteria” on page 9-76.
4 If you have more than one system or subsystem open, click the Start in

system list. From this list, select the system or subsystem where you want
the search to begin.
5 Click Find.

9-73

9

Exploring, Searching, and Browsing Models

The Finder searches the selected system for objects that meet the criteria that
you have specified. Any objects that satisfy the criteria appear in the results
panel at the bottom of the dialog box.

Display a Found Object
To display a found object, double-click its entry in the search results list.
Simulink opens the system or subsystem that contains the object (if necessary)
and highlights and selects the object.
To sort the results list based on the values in a column, click the button at the
top of that column. For example, to sort the results by object type, click the
Type button. To sort the list in ascending order, click the button once. To sort
the list in descending order, click the button twice.
To display the parameters or properties of an object, right-click the object in
the list. From the context menu, select Parameter or Properties.
If you close a model that has objects in the Finder search results list, then
double-clicking a found object from that model does not open the model. To

9-74

Finder

open an object that was in the Finder search results list, simply rerun the
search by clicking the Find button.

Filter Options
To specify the kinds of objects to look for, and where to search for them, use
the Filter options panel.

Object Type List
The object type list lists the types of objects that the Finder can find. To
exclude a type of object from the Finder search, clear the check box for the
object.

Specifying Kinds of Systems To Search
You can configure the Finder to search inside masked systems, linked library
systems, and referenced models. The search starts with the system that you
specify in the Start in system field.

9-75

9

Exploring, Searching, and Browsing Models

Object Type Option

Where the Finder Searches

Look inside masked systems

Inside masked subsystems

Look inside linked systems

Inside subsystems linked to libraries

Look inside referenced models

Inside referenced models, down
through a model reference hierarchy
Note The Finder loads unopened
referenced models. You can stop the
search by using the pop-up cancel
dialog box.

If you select more than one option, then the Finder searches in systems that
fit any of the specified options. For example, if you select the Look inside
linked systems and Look inside referenced models options, then the
Finder:
• Searches in linked library systems and referenced models that are not
in a masked system
• Does not search inside:

-

Masked systems, including those that are in linked library systems or
referenced models

-

Linked library systems or model referenced models, if the system or
model is in a masked system

Search Criteria
To specify the criteria that objects must meet to satisfy your search request,
use the Search criteria panel.

Basic
To search for an object whose name matches a specified text string, use the
Basic panel. Enter search text in the Find what edit box. To reuse previous
search text, select the appropriate search text from the dropdown list.

9-76

Finder

To include dialog parameters in the search, select Search block dialog
parameters.

Advanced
To specify a set of as many as seven properties that an object must have to
satisfy your search request, use the Advanced panel.

9-77

9

Exploring, Searching, and Browsing Models

To specify a property, enter its name in one of the cells in the Property
column or select the property from the property list of a cell. To display the
property list, select the down arrow button next to the cell. Next enter the
value of the property in the Value column. When you enter a property name,
the Finder checks the check box next to the property name in the Select
column. This indicates that the property is to be included in the search. To
exclude the property, clear the check box.

Match case
Select this option if you want the Finder to consider case when matching
search text against the value of an object property.

Other match options
Next to the Match case option is a dropdown list that specifies other match
options.
• Matches search string
Specifies a match if the property value and the search text are identical
except possibly for case.
• Contains search string
Specifies a match if a property value includes the search text.
• Regular expression
Specifies that the search text should be treated as a regular expression
when matched against property values. The following characters have
special meanings when they appear in a regular expression.

9-78

Character

Meaning

^

Matches start of string.

$

Matches end of string.

.

Matches any character.

\

Escape character. Causes the next character to have its
ordinary meaning. For example, the regular expression
\.. matches .a and .2 and any other two-character
string that begins with a period.

Finder

Character

Meaning

*

Matches zero or more instances of the preceding
character. For example, ba* matches b, ba, baa, and so
on.

+

Matches one or more instances of the preceding
character. For example, ba+ matches ba, baa, etc.

[]

Indicates a set of characters that can match the current
character. A hyphen can be used to indicate a range
of characters. For example, [a-zA-Z0-9_]+ matches
foo_bar1 but not foo$bar. A ^ indicates a match
when the current character is not one of the following
characters. For example, [^0-9] matches any character
that is not a digit.

\w

Matches a word character (same as [a-z_A-Z0-9]).

\W

Matches a nonword character (same as [^a-z_A-Z0-9]).

\d

Matches a digit (same as [0-9]).

\D

Matches a nondigit (same as [^0-9]).

\s

Matches white space (same as [ \t\r\n\f]).

\S

Matches nonwhite space (same as [^ \t\r\n\f]).

\

Matches WORD where WORD is any string of word
characters surrounded by white space.

9-79

9

Exploring, Searching, and Browsing Models

Model Browser
In this section...
“About the Model Browser” on page 9-80
“Navigating with the Mouse” on page 9-82
“Navigating with the Keyboard” on page 9-82
“Showing Library Links” on page 9-82
“Showing Masked Subsystems” on page 9-82

About the Model Browser
The Model Browser enables you to
• Navigate a model hierarchically
• Open systems in a model
• Determine the blocks contained in a model
Note The browser is available only on Microsoft Windows platforms.
To display the Model Browser, in the Simulink Editor, select View > Model
Browser > Show Model Browser.

9-80

Model Browser

The model window splits into two panes. The left pane displays the browser, a
tree-structured view of the block diagram displayed in the right pane.
Note The Browser initially visible preference causes Simulink to open
models by default in the Model Browser. To set this preference, in the
Simulink Editor, select File > Simulink Preferences.
The top entry in the tree view corresponds to your model. A button next to the
model name allows you to expand or contract the tree view. The expanded
view shows the model’s subsystems. A button next to a subsystem indicates
that the subsystem itself contains subsystems. You can use the button to
list the subsystem’s children. To view the block diagram of the model or
any subsystem displayed in the tree view, select the subsystem. You can

9-81

9

Exploring, Searching, and Browsing Models

use either the mouse or the keyboard to navigate quickly to any subsystem
in the tree view.

Navigating with the Mouse
Click any subsystem visible in the tree view to select it. Click the + button
next to any subsystem to list the subsystems that it contains. Click the button
again to contract the entry.

Navigating with the Keyboard
Use the up/down arrows to move the current selection up or down the tree
view. Use the left/right arrow or +/- keys on your numeric keypad to expand
an entry that contains subsystems.

Showing Library Links
The Model Browser can include or omit library links from the tree view of a
model. Use the Preferences dialog box to specify whether to display library
links by default. To toggle display of library links, select Show Library
Links from the Model Browser Options submenu of the View menu.

Showing Masked Subsystems
The Model Browser can include or omit masked subsystems from the tree
view. If the tree view includes masked subsystems, selecting a masked
subsystem in the tree view displays its block diagram in the diagram
view. Use the Preferences dialog box to specify whether to display masked
subsystems by default. To toggle display of masked subsystems, select Show
Masked Subsystems from the Model Browser Options submenu of the
View menu.

9-82

Model Dependency Viewer

Model Dependency Viewer
In this section...
“About Model Dependency Views” on page 9-83
“Opening the Model Dependency Viewer” on page 9-88
“Manipulating a Dependency View” on page 9-89
“Browsing Dependencies” on page 9-95
“Saving a Dependency View” on page 9-95
“Printing a Dependency View” on page 9-95

About Model Dependency Views
The Model Dependency Viewer displays a dependency view of a model. The
dependency view is a graph of all the models and libraries referenced directly
or indirectly by the model. You can use the dependency view to quickly
find and open referenced libraries and models. To identify and package all
required files, see instead “Analyze Model Dependencies” on page 13-104.
The Model Dependency Viewer allows you to choose between the following
types of dependency views of a model reference hierarchy.
• “File Dependency View” on page 9-83
• “Referenced Model Instances View” on page 9-85
• “Processor-in-the-Loop Mode Indicator” on page 9-87
• “Warning Icon” on page 9-88

File Dependency View
A file dependency view shows the model and library files referenced by a
top model. A referenced model or library file appears only once in the view
even if it is referenced more than once in the model hierarchy displayed in
the view. A file dependency view consists of a set of blocks connected by
arrows. Blue blocks represent model files; brown boxes, libraries. Arrows
represent dependencies. For example, the arrows in the following view

9-83

9

Exploring, Searching, and Browsing Models

indicate that the aero_guidance model references two libraries: aerospace
and simulink_need_slupdate.

An arrow that points to the library from which it emerges indicates that the
library references itself, i.e., blocks in the library reference other blocks
in that same library. For example, the preceding view indicates that the
aerospace library references itself.
A file dependency view optionally includes a legend that identifies the model
in the view and the date and time the view was created.

9-84

Model Dependency Viewer

Legend

Referenced Model Instances View
A referenced model instances view shows every reference to a model in a
model reference hierarchy (see “Model Reference”) rooted at the top model
targeted by the view. If a model hierarchy references the same model more
than once, the referenced model appears multiple times in the instance view,
once for each reference. For example, the following view indicates that the
model reference hierarchy rooted at sldemo_mdlref_depgraph contains two
references to the model sldemo_mdlref_F2C.

9-85

9

Exploring, Searching, and Browsing Models

In an instance view, boxes represent a top model and model references.
Boxes representing accelerated-mode instances (see “Referenced Model
Simulation Modes” on page 6-21) have filled triangles in their corners; boxes
representing normal-mode instances, have unfilled triangles in their corners.
For example, the following diagram indicates that one of the references to
sldemo_mdlref_F2C operates in normal mode; the other, in accelerated mode.

9-86

Model Dependency Viewer

Boxes representing protected referenced models models have a lock icon, and
the model name has the .slxp extension. Protected referenced model boxes
have no expand(+)/collapse(–) button.

Processor-in-the-Loop Mode Indicator
An instance view appends PIL to the names of models that run in
Processor-in-the-Loop mode (see “Specify the Simulation Mode” on page 6-23).
For example, the following dependency instance view indicates that the model
named rtwdemo_pil_component runs in processor-in-the-loop mode.

9-87

9

Exploring, Searching, and Browsing Models

Warning Icon
An instance view displays warning icons on instance boxes to indicate that a
reference is configured to run in Normal mode actually runs in Accelerated
mode because it is directly or indirectly referenced by another model reference
that runs in Accelerated mode.
The warning icon is a yellow triangle

.

Opening the Model Dependency Viewer
The Model Dependency Viewer displays a graph of all the models and libraries
referenced directly or indirectly by the model. You can use the dependency
viewer to quickly find and open referenced libraries and models.
To display a dependency view for a model:
1 Open the model.
2 Select Analysis > Model Dependencies > Model Dependency

Viewer, then select the type of view you want to see:
• Models & Libraries
• Models Only
• Referenced Model Instances

9-88

Model Dependency Viewer

The Model Dependency Viewer appears, displaying a dependency view
of the model.

Manipulating a Dependency View
The Model Dependency Viewer allows you to manipulate dependency views in
various ways. See the following topics for more information:
• “Changing Dependency View Type” on page 9-90
• “Excluding Block Libraries from a File Dependency View” on page 9-90

9-89

9

Exploring, Searching, and Browsing Models

• “Including Simulink Blocksets in a File Dependency View” on page 9-90
• “Changing View Orientation” on page 9-91
• “Expanding or Collapsing Views” on page 9-91
• “Zooming a Dependency View” on page 9-92
• “Moving a Dependency View” on page 9-92
• “Rearranging a Dependency View” on page 9-93
• “Displaying and Hiding a Dependency View’s Legend” on page 9-93
• “Displaying Full Paths of Referenced Model Instances” on page 9-93
• “Refreshing a Dependency View” on page 9-94

Changing Dependency View Type
You can change the type of dependency view displayed in the viewer.
To change the type of dependency view, in the Model Dependency Viewer:
• Select View > Dependency Type > Model File Dependencies (see
“File Dependency View” on page 9-83 )
or
• Select View > Dependency Type > Referenced Model Instances (see
“Referenced Model Instances View” on page 9-85 ).

Excluding Block Libraries from a File Dependency View
By default a file dependency view includes libraries on which a model depends.
To exclude block libraries:
• Deselect View > Include Libraries.

Including Simulink Blocksets in a File Dependency View
By default, a file dependency view omits MathWorks block libraries when
View > Include Libraries is selected.
To include libraries supplied by MathWorks:

9-90

Model Dependency Viewer

• Select View > Show MathWorks Dependencies.

Changing View Orientation
By default the orientation of the dependency graph displayed in the viewer is
vertical.
To change the orientation to horizontal:
• Select View > Orientation > Horizontal.

Expanding or Collapsing Views
You can expand or collapse each model or library in the dependency view to
display or hide the dependencies for that model or library.
To expand or collapse views:
• Click the expand(+)/collapse(-) button on the box representing the model or
library to expand or collapse that view.

9-91

9

Exploring, Searching, and Browsing Models

Expand/Collapse
Button

Zooming a Dependency View
You can enlarge or reduce the size of the dependency graph displayed in the
viewer.
To zoom a dependency view in or out, do either of the following:
• Press and hold down the spacebar key and then press the + or - key on
the keyboard.
• Move the scroll wheel on your mouse forward or backward.
To fit the view to the viewer window:
• Press and release the spacebar key.

Moving a Dependency View
You can move a dependency view to another location in the viewer window.
To move the dependency view:
1 Move the cursor over the view.
2 Press your keyboard’s space bar and your mouse’s left button

simultaneously.
3 Move the cursor to drag the view to another location.

9-92

Model Dependency Viewer

Rearranging a Dependency View
You can rearrange a dependency view by moving the blocks representing
models and libraries. This can make a complex view easier to read.
To move a block to another location:
1 Select the block you want to move by clicking it.
2 Drag and drop the block in the new location.

Displaying and Hiding a Dependency View’s Legend
The dependency view can display a legend that identifies the model in the
view and the date and time the view was created.
To display or hide a dependency view’s legend:
• Select View > Show Legend from the viewer’s menu bar.

Displaying Full Paths of Referenced Model Instances
In an instance view (see “Referenced Model Instances View” on page 9-85) ,
you can display the full path of a model reference in a tooltip or in the box
representing the reference.
To display the full path in a tooltip:
• Move the cursor over the box representing the reference in the view.
A tooltip appears, displaying the path displays the full path of the Model
block corresponding to the instance.

9-93

9

Exploring, Searching, and Browsing Models

To display full paths in the boxes representing the instances:
• Select View > Show Full Path.
Each box in the instance view now displays the path of the Model block
corresponding to the instance. The name of the referenced model appears
in parentheses as illustrated in the following figure.

Refreshing a Dependency View
After changing a model displayed in a dependency view or any of its
dependencies, you must update the view to reflect any dependency changes.
To update the view:
• Select View > Refresh from the dependency viewer’s menu bar.

9-94

Model Dependency Viewer

Browsing Dependencies
You can use a dependency view to browse a model’s dependencies:
• To open a model or library displayed in the view, double-click its block.
• To display the Model block corresponding to an instance in an instance
view, right-click the instance and select Highlight Block from the menu
that appears.
• To open all models displayed in the view, select File > Open All Models
from the viewer’s menu bar.
• To save all models displayed in the view, select File > Save All Models.
• To close all models displayed in the view, select File > Close All Models.

Saving a Dependency View
You can save a dependency view for later viewing.
To save the current view:
• Select File > Save As from the viewer’s menu bar, then enter a name
for the view.
To reopen the view:
• Select File > Open from any viewer’s menu bar, then select the view you
want to open.

Printing a Dependency View
To print a dependency view:
• Select File > Print from the dependency viewer’s menu bar.

9-95

9

Exploring, Searching, and Browsing Models

View Linked Requirements in Models and Blocks
In this section...
“Overview of Requirements Features in Simulink” on page 9-96
“Highlighting Requirements in a Model” on page 9-97
“Viewing Information About a Requirements Link” on page 9-99
“Navigating to Requirements from a Model” on page 9-100
“Filtering Requirements in a Model” on page 9-101

Overview of Requirements Features in Simulink
If your Simulink model has links to requirements in external documents,
you can review these links. To identify which model objects satisfy certain
design requirements, use the following requirements features available in
Simulink software:
• Highlighting objects in your model that have links to external requirements
• Viewing information about a requirements link
• Navigating from a model object to its associated requirement
• Filtering requirements highlighting based on specified keywords
Having a Simulink Verification and Validation license enables you to perform
the following additional tasks, using the Requirements Management Interface
(RMI):
• Adding new requirements
• Changing existing requirements
• Deleting existing requirements
• Applying user tags to requirements
• Creating reports about requirements links in your model
• Checking the validity of the links between the model objects and the
requirements documents

9-96

View Linked Requirements in Models and Blocks

Highlighting Requirements in a Model
You can highlight a model to identify which objects in the model have links
to requirements in external documents. Both the Simulink Editor and the
Model Explorer provide this capability.
• “Highlighting a Model Using the Simulink Editor” on page 9-97
• “Highlighting a Model Using the Model Explorer” on page 9-98
Note If your model contains a Model block whose referenced model
contains requirements, those requirements are not highlighted. If you have
Simulink Verification and Validation, you can view this information only in
requirements reports. To generate requirements information for referenced
models and then see highlighted snapshots of those requirements, follow the
steps in “Report for Requirements in Model Blocks”.

Highlighting a Model Using the Simulink Editor
If you are working in the Simulink Editor and want to see which model
objects in the slvnvdemo_fuelsys_officereq model have requirements,
follow these steps:
1 Open the example model:

slvnvdemo_fuelsys_officereq
2 Select Analysis > Requirements > Highlight Model.

Two types of highlighting indicate model objects with requirements:
• Yellow highlighting indicates objects that have requirements links for
the object itself.

• Orange outline indicates objects, such as subsystems, whose child objects
have requirements links.

9-97

9

Exploring, Searching, and Browsing Models

Objects that do not have requirements are colored gray.

3 To remove the highlighting from the model, select Analysis >

Requirements > Unhighlight Model. Alternatively, you can right-click
anywhere in the model, and select Remove Highlighting.
While a model is highlighted, you can still manage the model and its contents.

Highlighting a Model Using the Model Explorer
If you are working in Model Explorer and want to see which model objects
have requirements, follow these steps:
1 Open the example model:

9-98

View Linked Requirements in Models and Blocks

slvnvdemo_fuelsys_officereq
2 Select View > Model Explorer.
3 To highlight all model objects with requirements, click the Highlight

items with requirements on model icon (

).

The Model Editor window opens, and all objects in the model with
requirements are highlighted.
Note If you are running a 64-bit version of MATLAB, when you navigate to
a requirement in a PDF file, the file opens at the top of the page, not at the
bookmark location.

Viewing Information About a Requirements Link
Using Simulink, you can view detailed information about a requirements
link, such as identifying the location and type of document that contains
the requirement.
Note You can only modify the requirements information if you have a
Simulink Verification and Validation license.
For example, to view information about the requirements link from the MAP
Sensor block in the slvnvdemo_fuelsys_officereq example model, follow
these steps:
1 Open the example model:

slvnvdemo_fuelsys_officereq
2 Right-click the MAP sensor block, and select Requirements > Edit/Add

Links.
The Requirements dialog box opens and displays the following information
about the requirements link:

9-99

9

Exploring, Searching, and Browsing Models

• The description of the link (which is the actual text of the requirement).
• The Microsoft Excel® workbook named

slvnvdemo_FuelSys_TestScenarios.xlsx, which contains the linked

requirement.
• The requirements text, which appears in the named cell
Simulink_requirement_item_2 in the workbook.
• The user tag test, which is associated with this requirement.

Navigating to Requirements from a Model
Navigating from the Model Object
You can navigate directly from a model object to that object’s associated
requirement. When you take these steps, the external requirements document
opens in the application, with the requirements text highlighted.
1 Open the example model:

slvnvdemo_fuelsys_officereq
2 Open the fuel rate controller subsystem.
3 To open the linked requirement, right-click the Airflow calculation

subsystem and select Requirements > 1. “Mass airflow estimation”.
The Microsoft Word document
slvnvdemo_FuelSys_DesignDescription.docx, opens with the section 2.1

Mass airflow estimation selected.
Note If you are running a 64-bit version of MATLAB, when you navigate to
a requirement in a PDF file, the file opens at the top of the page, not at the
bookmark location.

Navigating from a System Requirements Block
Sometimes you want to see all the requirements links at a given level of the
model hierarchy. In such cases, you can insert a System Requirements block

9-100

View Linked Requirements in Models and Blocks

to collect all requirements links in the model or subsystem. The System
Requirements block does not list requirements links for any blocks for that
model or subsystem.
For example, you can insert the System Requirements block at the top level of
the slvnvdemo_fuelsys_officereq model, and navigate to the requirements
using the links inside the block.
1 Open the example model:

slvnvdemo_fuelsys_officereq
2 Select Analysis > Requirements > Highlight Model.
3 In the slvnvdemo_fuelsys_officereq model, open the fuel rate controller

subsystem.
The Airflow calculation subsystem has a requirements link.
4 Open the Airflow calculation subsystem.
5 Select View > Library Browser
6 On the Libraries pane, click the Simulink Verification and Validation

library.
This library contains only one block—the System Requirements block.
7 Drag a System Requirements block into the Airflow calculation subsystem.

The RMI software collects and displays any requirements links for that
subsystem.
8 Double-click 1. “Mass airflow subsystem”.

The Microsoft Word document,
slvnvdemo_FuelSys_DesignDescription.docx, opens, with the section

2.1 Mass airflow estimation selected.

Filtering Requirements in a Model
• “Filtering Requirements Highlighting by User Tag” on page 9-102

9-101

9

Exploring, Searching, and Browsing Models

• “Filtering Options for Highlighting Requirements” on page 9-103

Filtering Requirements Highlighting by User Tag
Some requirements links in your model can have one or more associated user
tags. User tags are keywords that you create to categorize a requirement,
for example, design or test.
For example, in the slvnvdemo_fuelsys_officereq model, the requirements
link from the MAP sensor block has the user tag test.
To highlight only all the blocks that have a requirement with the user tag
test:
1 Open the example model:

slvnvdemo_fuelsys_officereq
2 In the Simulink Editor, select Analysis > Requirements > Settings.

The Requirements Settings dialog box opens. If you do not have a Simulink
Verification and Validation license, the Filters tab is the only option
available.
By default, your model has no requirements filtering enabled.
3 Select Filter links by user tags when highlighting and reporting

requirements.
4 In the Include links with any of these tags text box, delete design,

and enter test.
5 Press Enter.
6 Highlight the slvnvdemo_fuelsys_officereq model for requirements.

Select Analysis > Requirements > Highlight Model.
In the top-level model, only the MAP sensor block and the Test inputs
block are highlighted.

9-102

View Linked Requirements in Models and Blocks

7 To disable the filtering by user tag, select Analysis > Requirements >

Settings, and clear Filter links by user tags when highlighting and
reporting requirements.
The model highlighting updates immediately.

Filtering Options for Highlighting Requirements
On the Filters tab, you select options that designate which objects with
requirements are highlighted. The following table describes these settings,
which apply to all requirements in your model for the duration of your
MATLAB session.
Option

Description

Filter links by user tags when
highlighting and reporting
requirements

Enables filtering for highlighting
and reporting, based on specified
user tags.

Include links with any of these
tags

Highlights all objects whose
requirements match at least one
of the specified user tags. The tag
names must match exactly. Separate
multiple user tags with commas or
spaces.

Exclude links with any of these
tags

Excludes from the highlighting all
objects whose requirements match
at least one of the specified user
tags. The tag names must match
exactly. Separate multiple user tags
with commas or spaces.

9-103

9

Exploring, Searching, and Browsing Models

9-104

Option

Description

Apply same filters in context
menus

Disables navigation links in
context menus for all objects whose
requirements do not match at least
one of the specified user tags.

Under Link type filters, Disable
DOORS surrogate item links in
context menus

Disables links to IBM® Rational®
DOORS® surrogate items from the
context menus when you right-click
a model object. This option does not
depend on current user tag filters.

10
Managing Model
Configurations
• “About Model Configurations” on page 10-2
• “Multiple Configuration Sets in a Model” on page 10-3
• “Share a Configuration for Multiple Models” on page 10-4
• “Share a Configuration Across Referenced Models” on page 10-6
• “Manage a Configuration Set” on page 10-12
• “Manage a Configuration Reference” on page 10-18
• “About Configuration Sets” on page 10-26
• “About Configuration References” on page 10-29
• “Model Configuration Command Line Interface” on page 10-33

10

Managing Model Configurations

About Model Configurations
A model configuration is a named set of values for the parameters of a model.
It is referred to as a configuration set. Every new model is created with
a default configuration set, called Configuration, that initially specifies
default values for the model parameters. You can change the default values
for new models by setting the Model Configuration Preferences. For more
information, see “Model Configuration Preferences” on page 10-28.
You can subsequently create and modify additional configuration sets and
associate them with the model. The configuration sets associated with a
model can specify different values for any or all configuration parameters.
For more information, see “About Configuration Sets” on page 10-26. For
examples on how to use configuration sets, see:
• “Multiple Configuration Sets in a Model” on page 10-3
• “Manage a Configuration Set” on page 10-12
By default, a configuration set resides within a single model so that only
that model can use it. Alternatively, you can store a configuration set
independently, so that other models can use it. A configuration set that
exists outside any model is a freestanding configuration set. Each model that
uses a freestanding configuration set defines a configuration reference that
points to the freestanding configuration set. A freestanding configuration
set allows you to single-source a configuration set for several models. For
more information, see “About Configuration References” on page 10-29. For
examples on how to use configuration references, see:
• “Share a Configuration for Multiple Models” on page 10-4
• “Share a Configuration Across Referenced Models” on page 10-6
• “Manage a Configuration Reference” on page 10-18

10-2

Multiple Configuration Sets in a Model

Multiple Configuration Sets in a Model
A model can include many different configuration sets. This capability is
useful if you want to compare the difference in simulation output after
changing the values of several parameters. Attaching additional configuration
sets allows you to quickly switch the active configuration.
1 To create additional configuration sets in your model, in the Model

Explorer, select your model node in the Model Hierarchy pane and do one
of the following:
• Right-click the model node and select Configuration > Add
Configuration.
• Right-click an existing configuration set. In the context menu, select
Copy.
2 To import a previously saved configuration set, right-click the model node

and select Configuration > Import. In the Import Configuration From
File dialog box, select a configuration file.
3 To modify the newly added configuration set, in the Model Hierarchy pane,

select the configuration node. In the Contents pane, select a component,
and then modify any parameters which are displayed in the right pane.
4 To make the new configuration set the active configuration, in the

configuration set context menu, select Activate. In the Model Hierarchy
pane, the new configuration set name is now displayed as (Active).
5 To simulate your model using a different configuration set, switch the

active configuration by repeating step 4.

10-3

10

Managing Model Configurations

Share a Configuration for Multiple Models
To share a configuration set between models, the configuration set must
be a configuration set object in the base workspace and you must create a
configuration reference in your model to reference the configuration set object.
You can create configuration references in other models that also point to the
same configuration set object.
For example, first convert an existing configuration set in your model to a
configuration reference:
1 Open the Model Explorer.
2 In the Model Hierarchy pane, right-click the active configuration set to

share.
3 In the configuration set context menu, select Convert to Configuration

Reference, which opens a dialog box. Alternatively, you can right-click the
model node and select Configuration > Convert Active Configuration
to Reference.
4 In the Convert Active Configuration to Reference dialog box, use the default

configuration set object name, configSetObj, or type a name.
5 Click OK, which creates a configuration reference in the model and a

configuration set object in the base workspace. The configuration reference
points to the configuration set object, which has the same values as the
original active configuration set. The configuration reference name in the
Model Hierarchy is now marked as (Active).
6 To change the name of the configuration reference, select it in the Model

Hierarchy, and in the right pane, change the Name field.
To share the preceding configuration set, which is stored as configSetObj in
the base workspace, create a configuration reference in another model:
1 In the Model Hierarchy pane, right-click the model node.
2 In the context menu, select Configuration > Add Configuration

Reference.

10-4

Share a Configuration for Multiple Models

3 The Create Configuration Reference dialog box opens. Specify the name of

the configuration set object, configSetObj, in the base workspace.
4 To make the new configuration reference the active configuration, in the

Model Hierarchy, right-click the configuration reference. In the context
menu, select Activate.
Both models now contain a configuration reference that points to the same
configuration set object in the base workspace. Before saving and closing
your models, follow the instructions to “Save a Referenced Configuration Set”
on page 10-23. If you do not save the referenced configuration set from the
base workspace, when you reopen your model, the configuration reference is
unresolved. To set up your model to automatically load the configuration set
object, see “Callback Functions” on page 4-54.

10-5

10

Managing Model Configurations

Share a Configuration Across Referenced Models
If you have a model reference hierarchy, you might want the top model
and the referenced models to share the same configuration set. You can
use a configuration reference in each of the models to reference the same
configuration set object in the base workspace.

In the diagram, each model shown in the Model Dependency Viewer specifies
the configuration reference, my_configuration, as its active configuration
set. my_configuration points to the freestanding configuration set,
Configuration. Therefore, the parameter values in Configuration apply
to all four models. Any parameter change in Configuration applies to all
four models.

10-6

Share a Configuration Across Referenced Models

Convert Configuration Set to Configuration Reference

In the top model, you must convert the active configuration set to a
configuration reference:
1 Open the sldemo_mdlref_depgraph model and the Model Explorer.
2 In the Model Hierarchy pane, expand the top model,

sldemo_mdlref_depgraph. In the list, right-click Configuration
(Active). In the context menu, select Convert to Configuration

Reference.
3 In the Configuration set name field, specify a name for the configuration

set object, or use the default name, configSetObj. This configuration set
object is stored in the base workspace.
4 Optionally, you can save the configuration set to a MAT-file. Select Save

configuration set to file. This enables the File name parameter.
5 In the File name field, specify a name for the MAT-file.

10-7

10

Managing Model Configurations

6 Click OK.

The original configuration set is now stored as a configuration set object,
configSetObj, in the base workspace. The configuration set is also stored
in a MAT-file, configuration_set.mat. The active configuration for the top

model is now a configuration reference. This configuration reference points to
the configuration set object in the base workspace.
Propagate a Configuration Reference

Now that the top model contains an active configuration reference, you can
propagate this configuration reference to all of the child models. Propagation
creates a copy of the top model configuration reference in each referenced
model. For each referenced model, the configuration reference is now the
active configuration. The configuration references point to the configuration
set object, configSetObj, in the base workspace.
1 In the Model Explorer, in the Model Hierarchy pane, expand the

sldemo_mdlref_depgraph node.

10-8

Share a Configuration Across Referenced Models

2 Right-click the active configuration reference, Reference (Active). In the

context menu, select Propagate to Referenced Models.
3 In the Configuration Reference Propagation dialog box, select the check box

for each referenced model. In this example, they are already selected.
4 Verify that your current folder is a writable folder. The propagation

mechanism saves the original configuration parameters for each referenced
model so that you can undo the propagation. Click Propagate.
5 In the Propagation Confirmation dialog box, click OK.

10-9

10

Managing Model Configurations

6 In the Configuration Reference Propagation dialog box, the Propagation

Report is updated and the Status for each referenced model is marked as
Converted.

Undo a Configuration Reference Propagation

After propagating a configuration reference from a top model to the referenced
models, you can undo the propagation for all referenced models by clicking
Restore All. If you want to undo the propagation for individual referenced
models, in the Undo/Redo column, click the Undo button. The Propagation
Report is updated and the Status for the referenced model is set to Restored.

10-10

Share a Configuration Across Referenced Models

10-11

10

Managing Model Configurations

Manage a Configuration Set
In this section...
“Create a Configuration Set in a Model” on page 10-12
“Create a Configuration Set in the Base Workspace” on page 10-12
“Open a Configuration Set in the Configuration Parameters Dialog Box” on
page 10-13
“Activate a Configuration Set” on page 10-13
“Set Values in a Configuration Set” on page 10-14
“Copy, Delete, and Move a Configuration Set” on page 10-14
“Save a Configuration Set” on page 10-15
“Load a Saved Configuration Set” on page 10-16
“Copy Configuration Set Components” on page 10-16

Create a Configuration Set in a Model
1 Open the Model Explorer.
2 In the Model Hierarchy pane, select the model name.
3 You can create a new configuration set in any of the following ways:

• From the Add menu, select Configuration.
• On the toolbar, click the Add Configuration button

.

• In the Model Hierarchy pane, right-click an existing configuration set
and copy and paste the configuration set.

Create a Configuration Set in the Base Workspace
1 Open the Model Explorer.
2 In the Model Hierarchy pane, select Base Workspace.
3 You can create a new configuration set object in the following ways:

• From the Add menu, select Configuration

10-12

Manage a Configuration Set

• In the toolbar, click the Add Configuration button
4 The configuration set object appears in the Contents pane, with the default

name, ConfigSet.

Open a Configuration Set in the Configuration
Parameters Dialog Box
In the Model Explorer, to open the Configuration Parameters dialog box for
a configuration set, right-click the configuration set’s node to display the
context menu, then select Open. You can open the Configuration Parameters
dialog box for any configuration set, whether or not it is active.
The title bar of the dialog box indicates whether the configuration set is active
or inactive.

Note Every configuration set has its own Configuration Parameters dialog
box. As you change the state of a configuration set, the title bar of the dialog
box changes to reflect the state.

Activate a Configuration Set
Only one configuration set associated with a model is active at any given
time. The active set determines the current values of the model parameters.
You can change the active or inactive set at any time (except when executing
the model). In this way, you can quickly reconfigure a model for different

10-13

10

Managing Model Configurations

purposes, for example, testing and production, or apply standard configuration
settings to new models.
To activate a configuration set, right-click the configuration set node to
display the context menu, then select Activate.

Set Values in a Configuration Set
To set the value of a parameter in a configuration set, in the Model Explorer:
1 In the Model Hierarchy, select the configuration set node.
2 In the Contents pane, select the component from where the parameter

resides.
3 In the Dialog pane, edit the parameter value.

Copy, Delete, and Move a Configuration Set
You can use edit commands on the Model Explorer Edit or context menus or
object drag-and-drop operations to delete, copy, and move configuration sets
among models displayed in the Model Hierarchy pane.
For example, to copy a configuration set from one model to another:
1 In the Model Hierarchy pane, right-click the configuration set node that

you want to copy.
2 Select Copy in the configuration set context menu.
3 Right-click the model node in which you want to create the copy.
4 Select Paste from the model context menu.

To copy the configuration set using object drag-and-drop, hold down the right
mouse button and drag the configuration set node to the node of the model in
which you want to create the copy.
To move a configuration set from one model to another using drag-and-drop,
hold the left mouse button down and drag the configuration set node to the
node of the destination model.

10-14

Manage a Configuration Set

Note You cannot move or delete an active configuration set from a model.

Save a Configuration Set
You can save the settings of configuration sets as MATLAB functions or
scripts. Using the MATLAB function or script, you can share and archive
model configuration sets. You can also compare the settings in different
configuration sets by comparing the MATLAB functions or scripts of the
configuration sets.
To save an active or inactive configuration set from the Model Explorer:
1 Open the model.
2 Open the Model Explorer.
3 Save the configuration set:
a In the Model Hierarchy pane:

• Right-click the model node and select Configuration > Export
Active Configuration Set.
• Right-click a configuration set and select Export.
• Select the model. In the Contents pane, right-click a configuration
set and select Export.
b In the Export Configuration Set to File dialog box, specify the name of

the file and the file type. If you specify a .m extension, the file contains
a function that creates a configuration set object. If you specify a .mat
extension, the file contains a configuration set object.
Note Do not specify the name of the file to be the same as a model name.
If the file and model have the same name, the software cannot determine
which file contains the configuration set object when loading the file.
c Click Save. The Simulink software saves the configuration set.

10-15

10

Managing Model Configurations

Load a Saved Configuration Set
You can load configuration sets that you previously saved as MATLAB
functions or scripts.
To load a configuration set from the Model Explorer:
1 Open the model.
2 Open the Model Explorer.
3 In the Model Hierarchy pane, right-click the model and select

Configuration > Import.
4 In the Import Configuration Set From File dialog box, select the .m file that

contains the function to create the configuration set object, or the .mat file
that contains the configuration set object.
5 Click Open. The Simulink software loads the configuration set.

Note If you load a configuration set object that contains an invalid custom
target, the software sets the “System target file” parameter to ert.tlc.
6 Optionally, activate the configuration set. For more information, see

“Activate a Configuration Set” on page 10-13.

Copy Configuration Set Components
To copy a configuration set component from one configuration set to another:
1 Select the component in the Model Explorer Contents pane.
2 From either the Model Explorer Edit menu or the component context

menu, select Copy.
3 Select the configuration set into which you want to copy the component.
4 From either the Model Explorer Edit menu or the component context

menu, select Paste.

10-16

Manage a Configuration Set

Note The copy replaces the component of the same name in the destination
configuration set. For example, if you copy the Solver component of
configuration set A and paste it into configuration set B, the copy replaces
the existing Solver component in B.

10-17

10

Managing Model Configurations

Manage a Configuration Reference
In this section...
“Create and Attach a Configuration Reference” on page 10-18
“Resolve a Configuration Reference” on page 10-19
“Activate a Configuration Reference” on page 10-21
“Manage Configuration Reference Across Referenced Models” on page 10-22
“Change Parameter Values in a Referenced Configuration Set” on page
10-23
“Save a Referenced Configuration Set” on page 10-23
“Load a Saved Referenced Configuration Set” on page 10-24
“Why is the Build Button Not Available for a Configuration Reference?” on
page 10-25

Create and Attach a Configuration Reference
To use a configuration reference, it must point to freestanding configuration
set. Create a freestanding configuration set before creating a configuration
reference, see “Create a Configuration Set in the Base Workspace” on page
10-12.
To create a configuration reference:
1 In the Model Explorer, in the Model Hierarchy pane, select the model.
2 Click the Add Reference tool

or select Add > Configuration
Reference. The Create Configuration Reference dialog box opens.

3 Specify the Configuration set name of the configuration set object in

the base workspace to be referenced.
4 Click OK. If you chose to create a configuration reference without first

creating a configuration set object, a dialog box opens asking if you would
like to continue. If you choose:

10-18

Manage a Configuration Reference

• Yes, an unresolved configuration reference is created. For more
information, see “Unresolved Configuration References” on page 10-30.
Follow the instructions in“Resolve a Configuration Reference” on page
10-19.
• No, then the configuration reference is not created. Follow the
instructions in“Create a Configuration Set in the Base Workspace” on
page 10-12, and then return to step 1 above.
5 A new configuration reference appears in the Model Hierarchy under the

selected model. The default name of the new reference is Reference.

Resolve a Configuration Reference
An unresolved configuration reference is a configuration reference that is not
pointing to a valid configuration set object.
To resolve a configuration reference:
1 In the Model Hierarchy pane, select the unresolved configuration reference

or right-click the configuration reference, and select Open from the context
menu.
The Configuration Reference dialog box opens in the Dialog pane or a
separate window.

10-19

10

Managing Model Configurations

2 Specify the Referenced configuration set to be a configuration set

object already in the base workspace. If one does not exist, see “Create a
Configuration Set in the Base Workspace” on page 10-12.
Tip Do not specify the name of a configuration reference. If you nest a
configuration reference, an error occurs.
3 Click OK or Apply.

If you specified a Referenced configuration that exists in the base
workspace, the Is Resolved field in the dialog box changes to yes.

10-20

Manage a Configuration Reference

Activate a Configuration Reference
After you create a configuration reference and attach it to a model, you can
activate it so that it is the active configuration.
• In the GUI, from the context menu of the configuration reference, select
Activate.
• From the API, execute setActiveConfigSet, specifying the configuration
reference as the second argument.
When a configuration reference is active, the Is Active field of the
Configuration Reference dialog box changes to yes. Also, the Model Explorer
shows the name of the reference with the suffix (Active).

10-21

10

Managing Model Configurations

The freestanding configuration set of the active reference now provides the
configuration parameters for the model.

Manage Configuration Reference Across Referenced
Models
In a model hierarchy, you can share a configuration reference across
referenced models. Using the Configuration Reference Propagation dialog box,
you can propagate a configuration reference of a top model to an individual
referenced model or to all referenced models in the model hierarchy. The
dialog box provides:
• A list of referenced models in the top model.
• The ability to select only specific referenced models for propagation.
• After propagation, the status for the converted configuration for each
referenced model.
• A view of the changed parameters after the propagation.
• The ability to undo the configuration reference and restore the previous
configuration settings for a referenced model.
To open the dialog box, in the Model Explorer, in the model hierarchy pane,
right-click the configuration reference node of a model. In the context menu,

10-22

Manage a Configuration Reference

select Propagate to Referenced Models. For an example, see “Share a
Configuration Across Referenced Models” on page 10-6.

Change Parameter Values in a Referenced
Configuration Set
To obtain a referenced configuration set:
1 In the Model Hierarchy pane, select the configuration reference, or

right-click the configuration reference, and select Open from the context
menu.
The Configuration Reference dialog box appears in the Dialog pane or in
a separate window.

2 To the right of the Referenced configuration field, click Open. The

Configuration Parameters dialog box opens. You can now change and apply
parameter values as you would for any configuration set.

Save a Referenced Configuration Set
If your model uses a configuration reference to specify the model configuration,
before closing your model, you need to save the referenced configuration set to
a MAT-file or MATLAB script.

10-23

10

Managing Model Configurations

1 In the Model Explorer, in the Model Hierarchy, select Base Workspace.
2 In the Contents pane, right-click the name of the referenced configuration

set object.
3 From the context menu, select Export Selected.
4 Specify the filename for saving the configuration set as either a MAT-file

or a MATLAB script.
Tip When you reopen the model you must load the saved configuration set,
otherwise, the configuration reference is unresolved. To set up your model
to automatically load the configuration set object, see “Callback Functions”
on page 4-54.

Load a Saved Referenced Configuration Set
If your model uses a configuration reference to specify the model configuration,
you need to load the referenced configuration set from a MAT-file or MATLAB
script to the base workspace.
1 In the Model Explorer, in the Model Hierarchy, right-click Base

Workspace.
2 From the context menu, select Import.
3 Specify the filename for the saved configuration set and select OK. The

configuration set object appears in the base workspace.
Tip When you reopen the model you must load the saved configuration set,
otherwise, the configuration reference is unresolved. To set up your model
to automatically load the configuration set object, see “Callback Functions”
on page 4-54.

10-24

Manage a Configuration Reference

Why is the Build Button Not Available for a
Configuration Reference?
The Code Generation pane of the Configuration Parameters dialog box
contains a Build button. Its availability depends on whether the configuration
set displayed by the dialog box resides in a model or is a freestanding
configuration set.
• When the pane displays a configuration set stored in a model, the Build
button is available. Click it to generate and compile code for the model.
• When the pane displays a freestanding configuration set, the Build button
is unavailable. The configuration set does not know which (if any) models
link to it.
To provide the same capabilities whether a configuration set resides in a
model or is freestanding, the Configuration Reference dialog box contains a
Build button. This button has the same capability as its equivalent in the
Configuration Parameters dialog box. It operates on the model that contains
the configuration reference.

10-25

10

Managing Model Configurations

About Configuration Sets
In this section...
“What Is a Configuration Set?” on page 10-26
“What Is a Freestanding Configuration Set?” on page 10-27
“Model Configuration Preferences” on page 10-28

What Is a Configuration Set?
A configuration set comprises groups of related parameters called components.
Every configuration set includes the following components:
• Solver
• Data Import/Export
• Optimization
• Diagnostics
• Hardware Implementation
• Model Referencing
• Simulation Target
Some MathWorks products that work with Simulink, such as Simulink Coder,
define additional components. If such a product is installed on your system,
the configuration set also contains the components that the product defines.
When you select any model configuration, the Model Configuration dialog
appears in the Model Explorer Dialog pane. In this location, you can edit the
name and description of your configuration.

10-26

About Configuration Sets

What Is a Freestanding Configuration Set?
A freestanding configuration set is a configuration set object,
Simulink.ConfigSet, stored in the base workspace. To use a freestanding
configuration set as the configuration for a model, you must create a
configuration reference in the model that references it. You can create a
freestanding configuration set in the base workspace in these ways:
• Create a new configuration set object.
• Copy a configuration set that resides within a model to the base workspace.
• Load a configuration set from a MAT-file.

10-27

10

Managing Model Configurations

You can store any number of configuration sets in the base workspace by
assigning each set to a different MATLAB variable.
Note Although you can store a configuration set in a model and point to it
with a base workspace variable, such a configuration set is not freestanding.
Using it in a configuration reference causes an error.

Model Configuration Preferences
Model Configuration Preferences are the preferred configuration for new
models. You can change the preferred configuration by editing the settings in
the Model Explorer.
1 Select View > Show Configuration Preferences to display the

Configuration Preferences node in the expanded Simulink Root node.
2 Under the Simulink Root node, select Configuration Preferences . The

Model Configuration Preferences dialog box opens in the Dialog pane.
3 In the Contents pane, select components and change any parameter

values.

10-28

About Configuration References

About Configuration References
In this section...
“What Is a Configuration Reference?” on page 10-29
“Why Use Configuration References?” on page 10-29
“Unresolved Configuration References” on page 10-30
“Configuration Reference Limitations” on page 10-31
“Configuration References for Models with Older Simulation Target
Settings” on page 10-31

What Is a Configuration Reference?
A configuration reference in a model is a reference to a configuration set
object in the base workspace. A model that has a configuration reference that
points to a freestanding configuration set uses that configuration set when
configuration reference is active. The model then has the same configuration
parameters as if the referenced configuration set resides directly in the model.
You can attach any number of configuration references to a model. Each
reference must have a unique name. For more information, see “Why Use
Configuration References?” on page 10-29. For an example on how to use
configuration references, see “Share a Configuration for Multiple Models” on
page 10-4 or “Create and Attach a Configuration Reference” on page 10-18.
Tip Save or export the configuration set object. Otherwise, when you reopen
your model the configuration reference is unresolved. To set up your model
to automatically load the configuration set object, see “Callback Functions”
on page 4-54.

Why Use Configuration References?
You can use configuration references and freestanding configuration sets to:
• Assign the same configuration set to any number of models

10-29

10

Managing Model Configurations

Each model that uses a given configuration set contains a configuration
reference that points to a MATLAB variable. The value of that variable is a
freestanding configuration set. All the models share that configuration set.
Changing the value of any parameter in the set changes it for every model
that uses the set. Use this feature to reconfigure many submodels quickly
and ensure consistent configuration of parent models and referenced
models.
• Replace the configuration sets of any number of models without
changing the model files
When multiple models use configuration references to access a freestanding
configuration set, assigning a different set to the MATLAB variable assigns
that set to all models. Use this feature to maintain a library of configuration
sets and assign them to any number of models in a single operation.
• Use different configuration sets for a referenced model used in
different contexts without changing the model file
A submodel that uses different configuration sets in different contexts
contains a configuration reference that specifies the submodel configuration
set as a variable. When you call an instance of the submodel, Simulink
software assigns that variable a freestanding configuration set for the
current context.

Unresolved Configuration References
When a configuration reference does not reference a valid configuration set,
the Is Resolved field of the Configuration Reference dialog box has the value
no. If you activate an unresolved configuration reference, no warning or error
occurs. However, an unresolved configuration reference that is active provides
no configuration parameter values to the model. Therefore:
• Fields that display values known only by accessing a configuration
parameter, like Stop Time in the model window, are blank.
• Trying to build the model, simulate it, generate code for it, or otherwise
require it to access configuration parameter values, causes an error.
For more information, see “Resolve a Configuration Reference” on page 10-19.

10-30

About Configuration References

Configuration Reference Limitations
• You cannot nest configuration references. Only one level of indirection is
available, so a configuration reference cannot link to another configuration
reference. Each reference must specify a freestanding configuration set.
• If you replace the base workspace variable and configuration set that
configuration references use, execute refresh for each reference that
uses the replaced variable and set. See “Use refresh When Replacing a
Referenced Configuration Set” on page 10-41.
• If you activate a configuration reference when using a custom target, the
ActivateCallback function does not trigger to notify the corresponding
freestanding configuration set. Likewise, if a freestanding configuration
set switches from one target to another, the ActivateCallback function
does not trigger to notify the new target. This behavior occurs, even if an
active configuration reference points to that target. For more information
about ActivateCallback functions, see “rtwgensettings Structure” in the
Simulink Coder documentation.

Configuration References for Models with Older
Simulation Target Settings
Suppose that you have a nonlibrary model that contains one of these blocks:
• MATLAB Function
• Stateflow chart
• Truth Table
• Attribute Function
In R2008a and earlier, this type of nonlibrary model does not store simulation
target (or sfun) settings in the configuration parameters. Instead, the model
stores the settings outside any configuration set.
When you load this older type of model, the simulation target settings migrate
to parameters in the active configuration set.
• If the active configuration set resides internally with the model, the
migration happens automatically.

10-31

10

Managing Model Configurations

• If the model uses an active configuration reference to point to a
configuration set in the base workspace, the migration process is different.
The following sections describe the two types of migration for nonlibrary
models that use an active configuration reference.

Default Migration Process That Disables the Configuration
Reference
Because multiple models can share a configuration set in the base workspace,
loading a nonlibrary model cannot automatically change any parameter
values in that configuration set. By default, these actions occur during loading
of a model to ensure that simulation results are the same, no matter which
version of the software that you use:
• A copy of the configuration set in the base workspace attaches to the model.
• The simulation target settings migrate to the corresponding parameters in
this new configuration set.
• The new configuration set becomes active.
• The old configuration reference becomes inactive.
A warning message appears in the MATLAB Command Window to describe
those actions. Although this process ensures consistent simulation results
for the model, it disables the configuration reference that links to the
configuration set in the base workspace.

10-32

Model Configuration Command Line Interface

Model Configuration Command Line Interface
In this section...
“Overview” on page 10-33
“Load and Activate a Configuration Set at the Command Line” on page
10-34
“Save a Configuration Set at the Command Line” on page 10-35
“Create a Freestanding Configuration Set at the Command Line” on page
10-36
“Create and Attach a Configuration Reference at the Command Line” on
page 10-37
“Attach a Configuration Reference to Multiple Models at the Command
Line” on page 10-38
“Get Values from a Referenced Configuration Set” on page 10-39
“Change Values in a Referenced Configuration Set” on page 10-39
“Obtain a Configuration Reference Handle” on page 10-40
“Use refresh When Replacing a Referenced Configuration Set” on page
10-41

Overview
An application programming interface (API) lets you create and manipulate
configuration sets at the command line or in a script. The API includes the
Simulink.ConfigSet and Simulink.ConfigSetRef classes and the following
functions:
• attachConfigSet
• attachConfigSetCopy
• detachConfigSet
• getConfigSet
• getConfigSets
• setActiveConfigSet

10-33

10

Managing Model Configurations

• getActiveConfigSet
• openDialog
• closeDialog
• Simulink.BlockDiagram.saveActiveConfigSet
• Simulink.BlockDiagram.loadActiveConfigSet
These functions, along with the methods and properties of
Simulink.ConfigSet class, allow you to create a script to:
• Create and modify configuration sets.
• Attach configuration sets to a model.
• Set the active configuration set for a model.
• Open and close configuration sets.
• Detach configuration sets from a model.
• Save configuration sets.
• Load configuration sets.
For examples using the preceding functions and the Simulink.ConfigSet
class, see the function and class reference pages.

Load and Activate a Configuration Set at the
Command Line
To load a configuration set from a MATLAB function or script:
1 Use the getActiveConfigSet or getConfigSet function to get a handle to

the configuration set that you want to update.
2 Call the MATLAB function or execute the MATLAB script to load the saved

configuration set.
3 Optionally, use the attachConfigSet function to attach the configuration

set to the model. To avoid configuration set naming conflicts, set
allowRename to true.

10-34

Model Configuration Command Line Interface

4 Optionally, use the setActiveConfigSet function to activate the

configuration set.
Alternatively, to load a configuration set at the command line and make it
the active configuration set:
1 Open the model.
2 Use the Simulink.BlockDiagram.loadActiveConfigSet function to load

the configuration set and make it active.
Note If you load a configuration set with the same name as the:
• Active configuration set, the software overwrites the active configuration
set.
• Inactive configuration set that is associated with the model, the software
detaches the inactive configuration from the model.

Save a Configuration Set at the Command Line
To save an active or inactive configuration set as a MATLAB function or script:
1 Use the getActiveConfigSet or getConfigSet function to get a handle to

the configuration set.
2 Use the saveAs method of the Simulink.Configset class to save the

configuration set as a function or script.
Alternatively, to save the active configuration set:
1 Open the model.
2 Use the Simulink.BlockDiagram.saveActiveConfigSet function to save

the active configuration set.

10-35

10

Managing Model Configurations

Create a Freestanding Configuration Set at the
Command Line
Copy a Configuration Set Stored in a Model
Create a freestanding configuration set to be referenced by a configuration
reference in several models. You must copy any configuration set obtained
from an existing model, otherwise, cset refers to the existing configuration
set stored in the model, rather than a new freestanding configuration set in
the base workspace. For example, use one of the following:
•
cset = copy (getActiveConfigSet(model))

•
cset = copy (getConfigSet(model, ConfigSetName))

model is any open model, and ConfigSetName is the name of any configuration

set attached to the model.

Read a Configuration Set from a MAT-File
To use a freestanding configuration set across multiple MATLAB sessions,
you can save it to a MAT-file. To create the MAT-file, you first copy the
configuration set to a base workspace variable, then save the variable to the
MAT-file:
save (workfolder/ConfigSetName.mat, cset)
workfolder is a working folder, ConfigSetName.mat is the MAT-file name,
and cset is a base workspace variable whose value is the configuration set
to save. When you later reopen your model, you can reload the configuration
set into the variable:
load (workfolder/ConfigSetName.mat)

To execute code that reads configuration sets from MAT-files, use one of these
techniques:
• The preload function of a top model

10-36

Model Configuration Command Line Interface

• The MATLAB startup script
• Interactive entry of load statements

Create and Attach a Configuration Reference at the
Command Line
To create and populate a configuration reference, Simulink.ConfigSetRef,
using the API:
1 Create the reference:
cref = Simulink.ConfigSetRef

2 Change the default name if desired:
cref.Name = 'ConfigSetRefName'

3 Specify the referenced configuration set:
cref.WSVarName = 'cset'

Tip Do not specify the name of a configuration reference. If you nest a
configuration reference, an error occurs.
4 Attach the reference to a model:

attachConfigSet(model, cref, true)

The third argument is optional and authorizes renaming to avoid a name
conflict.
Using a configuration reference with an invalid configuration set, WSVarName,
generates an error and is called an unresolved configuration reference. The
GUI equivalent of WSVarName is Referenced configuration. You can later
use the API or GUI to provide the name of a freestanding configuration
set. For more information, see “Unresolved Configuration References” on
page 10-30.

10-37

10

Managing Model Configurations

Attach a Configuration Reference to Multiple Models
at the Command Line
After you create a configuration reference and attach it to a model, you can
attach copies of the reference to any other models. Each model has its own
copy of any configuration reference attached to it, just as each model has its
own copy of any attached configuration set.
If you use the GUI, attaching an existing configuration reference to another
model automatically attaches a distinct copy to the model. If necessary
to prevent name conflict, the GUI adds or increments a digit at the end
of the name of the copied reference. If you use the API, be sure to copy the
configuration reference explicitly before attaching it, with statements like:
cref = copy (getConfigSet(model, ConfigSetRefName))
attachConfigSet (model, cref, true)

If you omit the copy operation, cref becomes a handle to the original
configuration reference, rather than a copy of the reference. Any attempt to
use cref causes an error. If you omit the argument true to attachConfigSet,
the operation fails if a name conflict exists.
The following example shows code for obtaining a freestanding configuration
set and attaching references to it from two models. After the code executes,
one of the models contains an internal configuration set and a configuration
reference that points to a freestanding copy of that set. If the internal copy
is an extra copy, you can remove it with detachConfigSet, as shown in the
last line of the example.
open_system('model1')
% Get handle to local cset
cset = getConfigSet('model1', 'Configuration')
% Create freestanding copy; original remains in model
cset1 = copy(cset)
% In the original model, create a configuration
% reference to the cset copy
cref1 = Simulink.ConfigSetRef
cref1.WSVarName = 'cset1'

10-38

Model Configuration Command Line Interface

% Attach the configuration reference to the model
attachConfigSet('model1', cref1, true)
% In a second model, create a configuration
% reference to the same cset
open_system('model2')
% Rename if name conflict occurs
attachConfigSetCopy('model2', cref1, true)
% Delete original cset from first model
detachConfigSet('model1', 'Configuration')

Get Values from a Referenced Configuration Set
You can use get_param on a configuration reference to obtain parameter
values from the linked configuration set, as if the reference object were
the configuration set itself. Simulink software retrieves the referenced
configuration set and performs the indicated get_param on it.
For example, if configuration reference cref links to configuration set cset,
the following operations give identical results:
get_param (cset, 'StopTime')
get_param (cref, 'StopTime')

Change Values in a Referenced Configuration Set
By operating on only a configuration reference, you cannot change the
referenced configuration set parameter values. If you execute:
set_param (cset, 'StopTime', '300')
set_param (cref, 'StopTime', '300')

% ILLEGAL

the first operation succeeds, but the second causes an error. Instead, you
must obtain the configuration set itself and change it directly, using the
GUI or the API.
To obtain a referenced configuration set using the API:
1 Follow the instructions in “Obtain a Configuration Reference Handle” on

page 10-40.

10-39

10

Managing Model Configurations

2 Obtain the configuration set cset from the configuration reference cref:
cset = cref.getRefConfigSet

You can now use set_param on cset to change parameter values. For
example:
set_param (cset, 'StopTime', '300')

Tip If you want to change parameter values through the GUI, execute:
cset.openDialog

The Configuration Parameters dialog box opens on the specified
configuration set.

Obtain a Configuration Reference Handle
Most functions and methods that operate on a configuration reference take a
handle to the reference. When you create a configuration reference:
cref = Simulink.ConfigSetRef

the variable cref contains a handle to the reference. If you do not already
have a handle, you can obtain one by executing:
cref = getConfigSet(model, 'ConfigSetRefName')

ConfigSetRefName is the name of the configuration reference as it appears in
the Model Explorer, for example, Reference. You specify this name by setting
the Name field in the Configuration Reference dialog box or executing:
cref.Name = 'ConfigSetRefName'

The technique for obtaining a configuration reference handle is the same
technique you use to obtain a configuration set handle. Wherever the same
operation applies to both configuration sets and configuration references,
applicable functions and methods overload to perform correctly with either
class.

10-40

Model Configuration Command Line Interface

Use refresh When Replacing a Referenced
Configuration Set
You can replace the base workspace variable and configuration set that a
configuration reference uses. However, the pointer from the configuration
reference to the configuration set becomes invalid. To avoid this situation,
execute:
cref.refresh

cref is the configuration reference. If you do not execute “refresh”, the
configuration reference continues to use the previous instance of the base
workspace variable and its configuration set. This example illustrates the
problem.
% Create a new configuration set
cset1 = Simulink.ConfigSet;
% Set a non-default stop time
set_param (cset1, 'StopTime', '500')
% Create a new configuration reference
cref1 = Simulink.ConfigSetRef;
% Resolve the configuration reference to the configuration set
cref1.WsVarName = 'cset1';
% Attach the configuration reference to an untitled model
attachConfigSet('untitled', cref1, true)
% Set the active configuration set to the reference
setActiveConfigSet('untitled','Reference')
% Replace config set in the base workspace
cset1 = Simulink.ConfigSet;
% Call to refresh is commented out!
% cref1.refresh;
% Set a different stop time
set_param (cset1, 'StopTime', '75')

10-41

10

Managing Model Configurations

If you simulate the model, the simulation stops at 500, not 75. Calling
cref1.refresh as shown prevents the problem.

10-42

11
Configuring Models for
Targets with Multicore
Processors
• “Introduction to Concurrent Execution” on page 11-2
• “Design Considerations” on page 11-5
• “Modeling Process for Concurrent Execution” on page 11-11
• “Configure Your Model” on page 11-12
• “Baseline Analysis Using Configuration Defaults” on page 11-17
• “Customize Concurrent Execution Settings” on page 11-19
• “Interpret Simulation Results” on page 11-26
• “Build and Download to a Multicore Target” on page 11-32
• “Concurrent Execution Example Model” on page 11-45
• “Command-Line Interface” on page 11-55

11

Configuring Models for Targets with Multicore Processors

Introduction to Concurrent Execution
In this section...
“About Configuring Models for Concurrent Execution” on page 11-2
“Supported Targets” on page 11-3
“Helpful Terms” on page 11-3
“Software Requirements” on page 11-4

About Configuring Models for Concurrent Execution
Configuring your model for concurrent execution in the Simulink environment
enables you to capture and simulate the effects of deploying your design to a
multicore system. A model that is configured for concurrent execution gives
you control over how a design should execute on a multicore target. It allows
the design to be mapped into concurrently executing tasks. Subsequently,
the Simulink environment enables the simulation of the mapped design by
identifying data transfer points and by simulating the mapped design in
conjunction with data transfer latencies. You can deploy the design to a
multicore system using Simulink Coder, Embedded Coder, and xPC Target™
software.
You can use simulation results to identify whether a mapping scheme is
suitable with respect to the functional characteristics of the design. You can
also explore alternate partitioning schemes using a mapping interface. In
addition, you can use profiling results on the deployed design to validate if the
mapping scheme is efficiently using the multicore system.
• Create a new model configuration or extend existing configurations for
concurrent execution.
• Use the Model block to define potential opportunities for concurrency in
your design.
• Set up and configure concurrent on-target tasks using a task editing
interface.
• Use either the GUI or command-line interface to iteratively map design
partitions (based on Model blocks) to tasks and find optimal concurrent
execution scenarios.

11-2

Introduction to Concurrent Execution

• Generate code that uses threading APIs on Windows, Linux, or xPC Target
platforms for on-target execution.

Supported Targets
You can build and download concurrent execution models for the following
targets using system target files:
• Linux, Windows, and Mac OS using ert.tlc and grt.tlc.
• xPC Target using xpctarget.tlc and xpctargetert.tlc.
• Linux and Windows using idelink_ert.tlc and idelink_grt.tlc.
• Embedded Linux and VxWorks® using idelink_ert.tlc and
idelink_grt.tlc.
Note Deploying to embedded Linux and VxWorks targets requires the
Embedded Coder product.
You cannot build and download a model, configured for concurrent execution,
for field-programmable gate arrays (FPGAs) and programmable logic
controllers (PLCs). For FPGA optimization and hardware utilization
techniques, see the “Streaming, Resource Sharing, and Delay Balancing”
chapter of the HDL Coder™ User’s Guide.

Helpful Terms
Task — Object that corresponds to a thread of execution on a target. From
within the Simulink environment, you can specify tasks, configure their
properties, and map Model blocks to them.
Task configuration — Configuration properties that apply to the set of tasks
set up for your multicore system.
Trigger — Abstraction of operating system timers, signals, interrupts, and
system events.

11-3

11

Configuring Models for Targets with Multicore Processors

Aperiodic trigger — Event trigger that has no inherent periodicity, such
as an interrupt. When multiple triggers coexist, the software assumes that
they are asynchronous to each other.
Periodic triggers — Periodic event trigger such as an operating system
trigger.

Software Requirements
• To build and download your model, you must have Simulink Coder software
installed.
• To build and download your model to an xPC Target system, you must
have xPC Target software installed. You must also have a multicore target
system supported by the xPC Target product.

11-4

Design Considerations

Design Considerations
In this section...
“Modeling for Concurrency” on page 11-5
“Simulation Limitations” on page 11-9

Modeling for Concurrency
A model configured for concurrent execution is defined as a model designed
to execute concurrently on a real-time multicore target. In this situation,
different pieces of the model ultimately execute in concurrent threads on the
target environment. Modeling for concurrent execution allows the designer to
factor in the effect of the concurrent execution semantics within the model, to
simulate and to provide initial conditions for data transfer points.
Note The simulation itself does not require a multicore host. The current
simulation engine uses only one thread to simulate.
Modeling for concurrency is an iterative process. It ultimately deploys a
model on a multicore target environment while making the best use of the
computational power provided by the multiple cores. To support the iterative
workflow, Simulink provides a mapping interface that allows you to map the
potential concurrency in the design to the actual concurrency available on the
target. A model configured for concurrent execution consists of three parts:
• A model that has identified blocks for concurrent execution
• A description of the available concurrency in terms of the number of tasks
and their periodicities
• A mapping that places the identified blocks in the model into actual tasks
for concurrent execution
These parts constitute a mapped model. To manage mapped models, Simulink
software provides:
• Explicit control over task configuration and how blocks are mapped to tasks

11-5

11

Configuring Models for Targets with Multicore Processors

• Control over how data is communicated between tasks

11-6

Design Considerations

• Simulation of a mapped model that allows you to validate a desired
functionality against the data transfer requirements of a particular
mapping
To validate if a particular mapping is an acceptable design, first validate that
the mapped model produces the desired simulation traces. Simulation results
vary from mapping to mapping because each mapping imposes communication
(data transfer) requirements that might cause the Simulink software to treat
certain signal lines as delays for data transfer. Ultimately, however, you
must evaluate the mapping on the target, and profile the behavior to measure
whether the mapping meets the computational requirements and makes
good use of the available computational power of the target platform. This
evaluation and profiling are beyond the scope of the software.

Identifying Opportunities for Concurrent Execution
To use the software mapping interface, a model must first specify
opportunities for concurrency by identifying blocks for concurrent execution.

11-7

11

Configuring Models for Targets with Multicore Processors

Use Model blocks (referenced models) to identify potential opportunities for
concurrent execution. A Model block defines a unit of functionality that the
software can map for execution in one or more target tasks. More precisely,
you can map a multirate Model block that contains N rates to exactly N tasks,
the periodicity of which agree with the respective rates. You can map several
Model blocks to the same task. Map a Model block that contains continuous
blocks to a task, the period of which agrees with the fundamental sample time
of the model. You can specify the fundamental sample time of the model in
the Fixed-step size (fundamental sample time) of the Solver pane in the
Configuration Parameters dialog box.
Because Model blocks must be used to express opportunities for concurrency,
a design must consist entirely of Model blocks. You can also use virtual
connectivity blocks to organize the block diagram, including:
• Goto and From blocks
• Ground and Terminator blocks
• Inport and Outport blocks
• Virtual subsystem blocks that contain permitted blocks
A model configured for concurrent execution reports an error diagnostic if any
other blocks are detected. Place all other blocks in one or more referenced
models.
Also consider signal lines when designing for concurrent execution. Depending
on the mapping, any signal line can potentially be identified as a data transfer
point. In particular, if the source port of a signal originates in a block from
one task and the destination port is to a block in another task, the Simulink
software identifies that signal as a data transfer point.

Algebraic Loops
An algebraic constraint or algebraic loop might impose tight coupling
between tasks and can lead to severe computational penalties. Therefore, a
model configured for concurrent execution cannot contain algebraic loops or
algebraic constraints that originate from physical modeling in a referenced
model. This condition makes an algebraic loop fully contained in a task.

11-8

Design Considerations

However, the use of Model blocks might lead to artificial algebraic loops.
This condition might occur if Simulink cannot identify if a break point is
encapsulated within a referenced model. In such situations, use one of the
following methods to remove artificial algebraic loops:
• In the referenced model Configuration Execution dialog box, select Model
Referencing > Minimize algebraic loop occurrences.
• Insert a Memory or Unit Delay block as the first block at the relevant input
port of the referenced model.
Additionally, if the model is configured for the Embedded Coder target
(ert.tlc), in the Configuration Parameters dialog box, clear the Code
Generation > Interface > Single output/update function check box.
This last operation prevents optimizations that can lead to artificial algebraic
loops.

Simulation Limitations
When modeling for concurrent execution, configure the model to use the
fixed-step solver.
Do not use the following modes of simulation for models in the concurrent
execution environment:
• External mode
• Logging to MAT-files
• Processor-in-the-loop (PIL) simulation mode
• Software-in-the-loop (SIL) simulation mode
• If you are simulating your model using Rapid Accelerator mode, the
top-level model cannot contain a root level Inport block that outputs
function calls.
In the Configuration Parameters dialog box, set the Diagnostics > Sample
Time > Multitask conditionally executed subsystem and
Diagnostics > Data Validity > Multitask data store parameters to error.
In addition, for all Rate Transition blocks within the Model blocks:

11-9

11

Configuring Models for Targets with Multicore Processors

• Select the Ensure data integrity during data transfer check box.
• Clear the Ensure deterministic data transfer (maximum delay) check
box.

11-10

Modeling Process for Concurrent Execution

Modeling Process for Concurrent Execution
You can model for concurrent execution using the following general workflow.
These steps assume that you have a model that meets the modeling guidelines
in “Design Considerations” on page 11-5.
1 Configure your model for concurrent execution.
2 Perform baseline analysis of your model for concurrent execution.
3 Explicitly set configuration values in the concurrent execution

configuration.
4 Simulate the model and evaluate the results
5 As necessary, refine the results.
6 Build and download the model to the multicore target and evaluate the

results.
7 As necessary, refine the results.

11-11

11

Configuring Models for Targets with Multicore Processors

Configure Your Model
You can use configuration references or configuration sets to configure a
model for concurrent execution.
If Your Model Has...

Create...

A single-level model, or if it
has multiple descendants, such
as reference models, and the
descendants do not share the same
configuration settings.

A configuration set for a single
model. For more information, see
“Creating a Concurrent Execution
Configuration Set” on page 11-12.

A top-level model and multiple
descendants, such as referenced
models, all of which share the same
configuration settings.

A configuration reference object that
can be shared between all models in
the hierarchy. For more information,
see “Creating and Propagating a
Configuration Reference” on page
11-13.

Creating a Concurrent Execution Configuration Set
You can create a concurrent execution configuration set from an existing
configuration set, or create a new configuration set:
1 In the Simulink model editor, select View > Model Explorer.

The Model Explorer window is displayed.
2 In the Model Explorer window:

11-12

Configure Your Model

To...

Do...

Preserve existing configuration
settings for your model, convert
an existing configuration set to a
concurrent execution configuration
set.

Expand the node for the model.
Under the model, right-click
Configuration, then select Show
Concurrent Execution options.

Create new configuration settings,
add a new concurrent execution
configuration set.

Expand the node for the model.
Right-click the model node and
select Configuration > Add
Configuration for Concurrent
Execution.
Activate the configuration set
by right-clicking it and selecting
Activate.

3 In the third column of the Model Explorer window, the Solver pane is

updated to display an Allow tasks to execute concurrently on target
check box. Click the Configure Tasks button.
If you want to create a configuration reference, see “Creating and Propagating
a Configuration Reference” on page 11-13. Otherwise, to begin configuring the
model for concurrent execution, see “Baseline Analysis Using Configuration
Defaults” on page 11-17.

Creating and Propagating a Configuration Reference
This topic assumes that you have an existing concurrent execution
configuration. If you have not yet created one, see “Creating a Concurrent
Execution Configuration Set” on page 11-12.
For more information on configuration references, see “About Configuration
References” on page 10-29. This topic describes one way to create and
propagate a configuration reference.
1 In the Simulink model editor, select View > Model Explorer.

The Model Explorer window is displayed.

11-13

11

Configuring Models for Targets with Multicore Processors

2 In the Model Explorer window, expand the node for the model and do one

of the following:
To...

Do...

Preserve existing configuration
settings for your model, convert
an existing configuration set to a
concurrent execution configuration
set.

Right-click and select
Configuration > Show
Concurrent Execution options.

Create new configuration settings,
add a new concurrent execution
configuration set.

Right-click and select
Configuration > Add
Configuration for Concurrent
Execution.

3 Activate the configuration set by right-clicking it and selecting Activate.
4 In the Model Hierarchy column, right-click Configuration > Convert to

Configuration Reference.
A Convert Active Configuration to Reference dialog box is displayed.

5 Click OK to accept the default name for the configuration reference.

11-14

Configure Your Model

The configuration is converted to a configuration reference.
6 To share the configuration reference with the other referenced models in

the model hierarchy, activate the configuration reference, then right-click
it and select Configuration > Propagate to Referenced Models.
A Propagate to Referenced Models dialog box is displayed.

7 Click Propagate to propagate the configuration reference.

A propagation confirmation dialog box is displayed.
8 Click OK to continue.

The hierarchy of each referenced model is updated with the configuration
reference.
9 Click OK.
10 In the Model Explorer, in the left column, select the Reference (Active)

node.

11-15

11

Configuring Models for Targets with Multicore Processors

The right column changes to display the Configuration Parameters
reference pane.
11 In the Configuration Parameters reference pane, click the Open button

of the Referenced configuration parameter.
The Configuration Parameters dialog box is displayed.
12 Navigate to the Solver node.
13 Click the Allow tasks to execute concurrently on target check box

and click Configure Tasks button.
The Open Task Editor dialog window is displayed.

Consider saving the configuration reference to MAT-file if you want to use
it in future MATLAB sessions. To save the configuration reference named
configSetObj, enter the following command in the MATLAB Command
Window:
save configsetobj.mat configSetObj

To load the saved configuration reference into another MATLAB session,
enter the following command in the MATLAB Command Window:
load configsetobj.mat

To begin configuring the model for concurrent execution, see “Baseline
Analysis Using Configuration Defaults” on page 11-17.

11-16

Baseline Analysis Using Configuration Defaults

Baseline Analysis Using Configuration Defaults
Perform an automatic baseline analysis of the model. This step allows you to
identify initial bottlenecks in the model execution.
1 In the Concurrent Execution dialog box, select the Tasks and Mapping node.

The Map blocks to tasks pane is displayed.
2 Click the Get Default Configuration button.
3 Select Yes in the resulting dialog box.

This button updates the diagram.
Upon a successful update, the software:
• Creates one periodic task for each periodic sample time in the model.
• Creates one aperiodic trigger for each function-call input in the model.
• Configures the block-to-task mapping so that each block maps to a task
based on sample time analysis.
If the software reports a diagnostic during the update phase, the analysis
might not complete. In this case, address the modeling issues reported in the
diagnostics before continuing.
The following is the automatic baseline analysis for the
sldemo_concurrent_execution model.

11-17

11

Configuring Models for Targets with Multicore Processors

When the analysis is complete, decide on your next step.

11-18

To...

Go to...

Explicitly configure how data is
transferred to override the settings
detected by automatic analysis.

“Customize Concurrent Execution
Settings” on page 11-19

Simulate the model.

“Interpret Simulation Results” on
page 11-26

Customize Concurrent Execution Settings

Customize Concurrent Execution Settings
After you set configuration defaults using automatic analysis, you might want
to fine-tune simulation results by performing operations such as explicitly
creating a different number of tasks or setting data transfer parameters.
Note If you do not want to customize concurrent execution settings, in
the Concurrent Execution pane clear the Enable explicit model
partitioning for concurrent behavior check box. Clearing this check box
allows the model to use rate-based tasks and ignores task-to-block mappings.

Configuring Data Transfer Communications
Use the Data Transfer Options pane to define communications between
tasks.
Data Transfer Options
Data Transfer Type

Simulation

Deployment

Ensure data integrity
only.

Data transfer is
simulated using a
one-step delay.

Simulink Coder ensures
data integrity during
data transfer. Data is
transferred as soon as
possible.

Ensure deterministic
transfer (maximum
delay).

Data transfer is
simulated using a
one-step delay.

Ensure deterministic
transfer (minimum
delay).

Data transfer occurs
within the same step.

Simulink Coder
ensures data transfer
is identical with
simulation.

• For continuous signals, the Simulink software uses extrapolation methods
to compensate for numerical errors that were introduced due to delays
and discontinuities in data transfer.
• For signals that are configured for Ensure Data Integrity Only and
Ensure deterministic transfer (maximum delay) data transfers, you

11-19

11

Configuring Models for Targets with Multicore Processors

might need to provide an initial condition to avoid numerical errors. You
can specify this initial condition in the Data Transfer tab of the Signal
Properties dialog box. To access this dialog box, right-click the signal
line and select Properties from the context menu. A dialog box like the
following is displayed.

1 From the Data Transfer Options on page 11-19 table, determine how you

want your tasks to communicate.
2 In the Concurrent Execution dialog box, select Data Transfer defaults

and apply the settings from step 1.

11-20

Customize Concurrent Execution Settings

3 Apply your changes.

Configuring Periodic Tasks
If you want to explore the effects of increasing the concurrency on your model
execution, you can create additional periodic tasks in your model.
1 In the Concurrent Execution dialog box, right-click on the Periodic node

and select Add task.
A task node appears in the Configuration Execution hierarchy.
2 Select the task node and enter a name and period for the task, then click

Apply.
The task node is renamed to the name you enter.
3 Optionally, specify a color for the task. The color illustrates the

block-to-task mapping. If you do not assign a color, Simulink chooses a

11-21

11

Configuring Models for Targets with Multicore Processors

default color. If you enable sample time colors for your model, the software
honors the setting.
4 Click Apply as necessary.

When the periodic tasks are complete, configure the aperiodic (interrupt)
tasks as necessary. If you do not need aperiodic tasks, continue to “Mapping
Blocks to Tasks” on page 11-24.

Configuring Aperiodic Triggers and Tasks
1 To create an aperiodic trigger, in the Concurrent Execution dialog box,

right-click the Concurrent Execution node and click the Add aperiodic
trigger icon.
A node named InterruptN appears in the configuration tree hierarchy.
2 Select Interrupt.

This node represents an aperiodic trigger for your system.
3 Specify the name of the trigger and configure the aperiodic trigger source.

Depending on your deployment target, choose either Posix Signal
(Linux/VxWorks 6.x) or Event (Windows). For POSIX® signals, specify
the signal number to use for delivering the aperiodic event. For Windows
events, specify the name of the event.

11-22

Customize Concurrent Execution Settings

4 Click Apply.

The software services aperiodic triggers as soon as the system can respond to
the trigger. If you want to process the trigger response using a task:
1 Right-click the Interrupt node and select Add task.

A new task node appears under the Interrupt node.
2 Specify the name of the new task node.
3 Optionally, specify a color for the task. The color illustrates the

block-to-task mapping. If you do not assign a color, Simulink chooses
a default color.
4 Click Apply.

11-23

11

Configuring Models for Targets with Multicore Processors

You can delete tasks (both periodic and aperiodic) as well as triggers by
right-clicking them in the pane and selecting Delete.
When the aperiodic tasks are complete, continue to “Mapping Blocks to
Tasks” on page 11-24.

Mapping Blocks to Tasks
After you simulate and evaluate a model that has automatic analysis defaults,
you are likely to want to redo the block-to-task mappings. If you have
specified new tasks and triggers explicitly, you must map the blocks to the
newly created tasks and triggers.
1 In the Concurrent Execution dialog box, click the Tasks and Mapping node.

The Map blocks to tasks pane appears.
2 If you changed the model by adding or removing blocks, consider using

automatic analysis by clicking the Get Default Configuration button.
If you added a new Model block, a select task entry appears under the
block.
3 If you want to add a new task to a block, in the Name column, right-click a

task under the block and select add new entry.
4 To assign a task for the entry, left-click the box in the Name column and

select a task from the list. For example:

11-24

Customize Concurrent Execution Settings

The block-to-task mapping icon appears on the top-left corner of the Model
block. If a Model block is assigned to multiple tasks, multiple task icons
are displayed in the top-left corner. For example:

5 Click Apply.

When the mapping is complete, simulate the model again (see “Interpret
Simulation Results” on page 11-26).

11-25

11

Configuring Models for Targets with Multicore Processors

Interpret Simulation Results
In this section...
“Introduction” on page 11-26
“Default Configuration” on page 11-27
“Sample Configured Model with Multiple Target Tasks” on page 11-28
“How Simulink Determines Data Transfer Requirements” on page 11-31

Introduction
A model configured for concurrent execution is a model that is designed
to execute concurrently on a real-time multicore target. Simulink enables
you to simulate such models and observe the effects of task-to-task data
transfer. You can also observe how this transfer can impact the numerical
characteristics of the model.
Note The simulation itself does not require a multicore target. The number
of tasks that you use to simulate the design is determined by other factors
and does not impose any requirements on the number of tasks modeled by
the design. Factors that influence the concurrency of the simulation include
the use of the Basic Linear Algebra Subprograms (BLAS) library, Rapid
Accelerator mode, and the MATLAB parfor command.
Consider the model sldemo_concurrent_execution. To understand
simulation results, compare the signal x in two scenarios:
• Default configuration — The target has exactly one periodic task and all
blocks are mapped to execute within this task. In this configuration, the
target does not allow for any concurrent execution.
• Sample configuration — The target has three periodic tasks and all blocks
are mapped to execute concurrently in these tasks.

11-26

Interpret Simulation Results

Default Configuration
In the following example, the model is configured as described in “Baseline
Analysis Using Configuration Defaults” on page 11-17. Because this model
contains only one sample time (continuous sample time), the automatic
analysis configures the target with one task and maps all blocks to run in that
task. The period of the task is selected as 0.1, which agrees with the fixed-step
size of the model. Because the design has only one task, no task-to-task
data transfer is needed. Therefore, simulation of the model should produce
the same numeric results as if the model is not configured for concurrent
execution.

11-27

11

Configuring Models for Targets with Multicore Processors

Note Configuring a model with automatic analysis always configures a model
to minimize task-to-task communication requirements. In particular, only
those communications that require rate transitions are included in the design.
Configure the model to inspect data using the Simulation Data Inspector by
clicking the Record & Inspect Simulation Output button in the toolbar.
(Alternatively, in the Configuration Parameters dialog box, select the Data
Input and Output > Record and inspect simulation output button).
After you enable the Simulation Data Inspector, click Simulate > Run to
simulate the model using the single task configuration. After simulation,
launch the Simulation Data Inspector as directed in the editor. Observe that
the tool has recorded the simulation results for the signal labeled x.

Sample Configured Model with Multiple Target Tasks
In the Concurrent Execution dialog box, create two additional tasks and map
the ControllerA block to the first additional task and the ControllerB block to
the second additional task.
1 Open the Concurrent Execution dialog box.
2 Click the Add Task button twice.
3 Select the first added task and label it ControllerA.
4 Select the second added task and label it ControllerB.
5 In the Map blocks to tasks pane, check that the ControllerA block is

assigned to execute within the ControllerA task and the ControllerB block
is assigned to execute within the ControllerB task.

11-28

Interpret Simulation Results

6 Simulate the model again.
7 After simulation completes, compare the results for the default and custom

configurations using the Simulation Data Inspector.

11-29

11

Configuring Models for Targets with Multicore Processors

To understand the source of the phase margin, observe that:
• For the first run of the model, signal x, identified by the black line, shows a
default task configuration.
• In the second run of the model, signal x, identified by the red line, shows a
custom task configuration and the effects of communication latencies from
lines crossing task boundaries. This is different from the first run, which
has only one periodic task and therefore, no communication latencies.
• The default setting for data transfer is to ensure determinism, so the data
transfer is deterministic (see Data Transfer Options on page 11-19).
Because the data transfer is deterministic, the simulated model takes into
account a unit delay to capture the effects of data transfer. This delay causes
a small phase margin in the mapped design. The delay agrees with the step
size of the model, which is 0.1. This delay is the least possible delay that the
software can impose on the signal.

11-30

Interpret Simulation Results

How Simulink Determines Data Transfer
Requirements
The software determines data transfer based on how the blocks are mapped to
tasks. When a model is simulated, either from an update diagram or upon
code generation, Simulink software examines the block-to-task mapping
and determines which signals must be configured for task-to-task data
transfer. The software considers only the signals where the source of the
signal originates from one task and the destination of the signal resides in a
different task. You can specify global options that control data transfer (see
Data Transfer Options on page 11-19). You can also override these options for
each signal from the Data Transfer pane of the Signal Properties dialog box.
Therefore, the block-to-task mapping dictates which blocks execute in which
tasks. Consequently, this mapping also dictates which signals you configure
for task-to-task data transfer.

11-31

11

Configuring Models for Targets with Multicore Processors

Build and Download to a Multicore Target
In this section...
“Generating Code” on page 11-32
“Configuring Embedded Coder for Native Threads Example” on page 11-42
“Build and Download” on page 11-43
“Profile and Evaluate” on page 11-44

Generating Code
To generate code, in the Simulink editor window, select Tools > Code
Generation > Build Model. This code can run concurrently on a multicore
target with Simulink Coder or Embedded Coder software. The coder generates
all target-dependent code for thread creation, thread synchronization,
interrupt service routines, and signal handlers and data transfer. The source
files of the mapped model (for example, model.c and model.h) do not contain
target-dependent code for setting up the execution of threads. However,
target-dependent code might exist for data transfer types, which generate
target-specific data protection or semaphore application programming
interface (API) calls.
For each periodic task, Simulink Coder combines the output and update
methods of the blocks mapped to that task and binds these methods to a
target-specific thread. Additionally, for each periodic task that contains
continuous states, a separate solver instance is generated in the source file of
the mapped model. This mapped model can concurrently run the continuous
parts of the model. (The generated solver instances share the solver type
specified in the Solver of the Configuration Parameters dialog box of the
mapped model.)
For each aperiodic task or aperiodic trigger, Simulink Coder combines the
output and update methods of the blocks mapped to that task and binds these
to a target-specific Interrupt Service Routine (ISR) or to a target-specific
event handler.
Following is an example of generated code in the source file of a mapped
model. This code shows the functions generated for the mapped model:

11-32

Build and Download to a Multicore Target

• Two solver instances
• Three periodic tasks with two of them having continuous states
• Two aperiodic tasks
• Two aperiodic triggers
/*
* This function updates continuous states using the ODE3 fixed-step
* solver algorithm
*/
static void Periodic_Task1_rt_ertODEUpdateContinuousStates(RTWSolverInfo
{

*si )

}

/*
* This function updates continuous states using the ODE3 fixed-step
* solver algorithm
*/
static void Periodic_Task2_rt_ertODEUpdateContinuousStates(RTWSolverInfo
{

*si )

}

/* OutputUpdate for Task: Periodic_Task1 */
void Periodic_Task1_step(void)

/* Sample time: [0.1s, 0.0s] */

{
Periodic_Task1_rt_ertODEUpdateContinuousStates(&task_M[0]->solverInfo);

}

/* OutputUpdate for Task: Periodic_Task2 */
void Periodic_Task2_step(void)

/* Sample time: [0.2s, 0.0s] */

{
Periodic_Task2_rt_ertODEUpdateContinuousStates(&task_M[1]->solverInfo);

}

/* OutputUpdate for Task: Periodic_Task3 */
void Periodic_Task3_step(void)
{

/* Sample time: [0.1s, 0.0s] */

}

11-33

11

Configuring Models for Targets with Multicore Processors

/* OutputUpdate for Task: Periodic_Task4 */
void Periodic_Task4_step(void)
{

/* Sample time: [0.2s, 0.0s] */

}

/* OutputUpdate for Task:Interrupt1_asyncTask1 */
void Interrupt1_asyncTask1(void)
{

}

/* OutputUpdate for Task:Interrupt2_asyncTask2 */
void Interrupt2_asyncTask2(void)
{

}

/* OutputUpdate for Task:Interrupt3 */
void Interrupt3(void)
{

}

/* OutputUpdate for Task:Interrupt4 */
void Interrupt4(void)
{

}

In addition, for continuous signals, the coder produces code for the
extrapolation method that you select. There are four types of extrapolation
methods: zero-order hold, linear, quadratic, and none. None is an ideal case
when the two communicating tasks synchronize in minor steps.
The following code snippets contain the generated task functions in the source
file of the mapped model. The sldemo_concurrent_execution model has
been modified so that:
• ControllerA/u1 uses Ensure data Integrity only option in the Signal
Properties dialog box.
• Plant is remapped to a new task that executes concurrently with
Compensator. The data transfer from Plant to Compensator is Ensure
deterministic transfer (minimum delay).
The coder makes sure that the data transfer between concurrently executing
tasks behave as described Data Transfer Options on page 11-19.

11-34

Build and Download to a Multicore Target

Generate Code to Share Data in a Concurrent Environment
For Ensure data integrity only, the generated code allows data to be
shared in a concurrent environment. This is achieved with a double-buffer
algorithm (for same rate data transfer) and a triple buffer algorithm (for
rate-transition data transfer) and target-specific protection code for the buffer
flag management. The following example shows code generated using the
sldemo_concurrent_execution model:
1 Open the Signal Properties dialog box for ControllerA/u1 and select Data

Integrity Only as the data transfer handling option from the Data

Transfer pane.
2 To generate code, select Code > C/C++ Code > Build Model.

The coder generates code like the following. This code is for ControllerA/u1
on the Linux platform.
/* Output for Task: Periodic_ControllerA */
void Periodic_ControllerA_output(void) /* Sample time: [0.1s, 0.0s] */
{

/* TaskTransBlk: '/TaskTransAtController AOut1' */
sldemo_concurrent_execution_DWork.
TaskTransAtControllerAOut1_buf_3[sldemo_concurrent_execution_DWork.fw_buf_3]
= sldemo_concurrent_execution_B.ControllerA;
rtw_pthread_mutex_lock(sldemo_concurrent_execution_DWork.mw_buf_3);
sldemo_concurrent_execution_DWork.fw_buf_3 = 1 sldemo_concurrent_execution_DWork.fw_buf_3;
rtw_pthread_mutex_unlock(sldemo_concurrent_execution_DWork.mw_buf_3);
}
/* Output for Task: Periodic_Plant */
void Periodic_Plant_output(void)

/* Sample time: [0.0s, 0.0s] */

{

if (rtmIsMajorTimeStep(task_M[2])) {
/* TaskTransBlk: '/TaskTransAtPlantIn1' */
rtw_pthread_mutex_lock(sldemo_concurrent_execution_DWork.mw_buf_3);
wrBufIdx = 1 - sldemo_concurrent_execution_DWork.fw_buf_3;
rtw_pthread_mutex_unlock(sldemo_concurrent_execution_DWork.mw_buf_3);
sldemo_concurrent_execution_B.TaskTransAtPlantIn1 =

11-35

11

Configuring Models for Targets with Multicore Processors

sldemo_concurrent_execution_DWork.TaskTransAtControllerAOut1_buf_3[wrBufIdx];

}

}
void MdlInitialize(void)
{

sldemo_concurrent_execution_DWork.fw_buf_3 = 0;
rtw_pthread_mutex_init(&sldemo_concurrent_execution_DWork.mw_buf_3);

}

Generate Code for Maximum Capacity During Data Transfer
For Ensure deterministic transfer (maximum delay), the generated
code for the task transition is ANSI® C code with writing and reading to
and from double buffers. In the Signal Properties dialog box, you provide a
value for the Initial Condition value that initializes the buffer used for the
first read operation.
The software generates code like the following. This example is for
ControllerB/u1 on the Linux platform.
/* Output for Task: Periodic_ControllerB */
void Periodic_ControllerB_output(void) /* Sample time: [0.1s, 0.0s] */
{

sldemo_concurrent_execution_DWork.
TaskTransAtControllerBOut1_buf_4[sldemo_concurrent_execution_DWork.fw_buf_4]
= sldemo_concurrent_execution_B.ControllerB;
sldemo_concurrent_execution_DWork.fw_buf_4 = 1 sldemo_concurrent_execution_DWork.fw_buf_4;
}
/* Output for Task: Periodic_Plant */
void Periodic_Plant_output(void)
{

if (rtmIsMajorTimeStep(task_M[2])) {

11-36

/* Sample time: [0.0s, 0.0s] */

Build and Download to a Multicore Target

/* TaskTransBlk: '/TaskTransAtPlantIn2' */
sldemo_concurrent_execution_B.TaskTransAtPlantIn2 =
sldemo_concurrent_execution_DWork.
TaskTransAtControllerBOut1_buf_4[sldemo_concurrent_execution_DWork.fr_buf_4];
sldemo_concurrent_execution_DWork.fr_buf_4 = 1 sldemo_concurrent_execution_DWork.fr_buf_4;
}

}

void MdlInitialize(void)
{

/* InitializeConditions for TaskTransBlk: '/TaskTransAtController BOut1' */
sldemo_concurrent_execution_DWork.fw_buf_4 = 0;

}

Generated Code for Maximum Data Integrity During Data
Transfer
For Ensure deterministic transfer (minimum delay), the generated code
for the data transfer makes sure that the task reading the data is waiting
for the task writing the data to complete its computation of the data. This
behavior produces target-specific code for data synchronization (for example,
semaphores).
The software generates code like the following. This example code is for
Plant/x on the Linux platform.
/*
* This function updates continuous states using the ODE3 fixed-step
* solver algorithm
*/

11-37

11

Configuring Models for Targets with Multicore Processors

static void Periodic_Compensator_rt_ertODEUpdateContinuousStates(RTWSolverInfo
*si )
{
/* TaskTransBlk: '/TaskTransAtCompensatorIn1' */
if (sldemo_concurrent_execution_DWork.br_buf_5) {
sldemo_concurrent_execution_DWork.br_buf_5 = FALSE;
} else {
rtw_pthread_sem_wait(sldemo_concurrent_execution_DWork.sw_buf_5);
sldemo_concurrent_execution_B.TaskTransAtCompensatorIn1 =
sldemo_concurrent_execution_DWork.TaskTransAtPlantOut1_buf_5;
rtw_pthread_sem_post(sldemo_concurrent_execution_DWork.sr_buf_5);
if (rtmIsMajorTimeStep(task_M[0])) {
sldemo_concurrent_execution_DWork.br_buf_5 = TRUE;
}
}
/* End of TaskTransBlk: '/TaskTransAtCompensatorIn1' */
}
/* Output for Task: Periodic_Plant */
void Periodic_Plant_output(void)

/* Sample time: [0.0s, 0.0s] */

{
if (rtmIsMajorTimeStep(task_M[3])) {
/* TaskTransBlk: '/TaskTransAtPlantOut1' */
rtw_pthread_sem_wait(sldemo_concurrent_execution_DWork.sr_buf_5);
sldemo_concurrent_execution_DWork.TaskTransAtPlantOut1_buf_5 =
sldemo_concurrent_execution_B.x;
rtw_pthread_sem_post(sldemo_concurrent_execution_DWork.sw_buf_5);
}
void MdlInitialize(void)
{
/* InitializeConditions for TaskTransBlk: '/TaskTransAtPlantOut1' */
sldemo_concurrent_execution_DWork.fw_buf_5 = 0;
rtw_pthread_sem_create(&sldemo_concurrent_execution_DWork.sw_buf_5, 0);
}

11-38

Build and Download to a Multicore Target

Threading APIs
For Embedded Coder targets and generic real-time targets, the generated
code from a mapped model creates a thread for each task and automatically
leverages the threading APIs supported by the operating system running
on the host machine.
• If the host machine is a Windows platform, the generated code will create
and run Windows threads.
• If the host machine is Linux or Mac OS platform, the generated code will
create and run POSIX pthreads.
Aspect of
Concurrent
Execution

Linux
Implementation

Windows
Implementation

Mac OS
Implementation

Periodic triggering
event

POSIX timer

Windows timer

Not applicable

Aperiodic triggering
event

POSIX real-time
signal

Windows event

POSIX non-real-time
signal

Aperiodic trigger

For blocks mapped
to an aperiodic task:
thread waiting for a
signal

Thread waiting for an
event

For blocks mapped
to an aperiodic task:
thread waiting for a
signal
For blocks mapped to
an aperiodic trigger:
signal action

For blocks mapped to
an aperiodic trigger:
signal action
Threads

POSIX

Windows

POSIX

11-39

11

Configuring Models for Targets with Multicore Processors

Aspect of
Concurrent
Execution

Linux
Implementation

Windows
Implementation

Mac OS
Implementation

Threads priority

Assigned based on
sample time: fastest
task has highest
priority

Priority class
inherited from the
parent process.

Assigned based on
sample time: fastest
task has highest
priority

Yes

Yes

Example of overrun
detection

Assigned based on
sample time: fastest
task has highest
priority for the first
three fastest tasks.
The rest of the tasks
share the lowest
priority.

No

The data transfer between concurrently executing tasks behave as described
in Data Transfer Options on page 11-19. The coders use the following APIs on
supported targets for this behavior:
Data Protection and Synchronization APIs that Embedded Coder and Generic Real-Time
Targets Use
API

Linux Implementation

Windows
Implementation

Mac OS
Implementation

Data protection
API

• pthread_mutex_init

• CreateMutex

• pthread_mutex_init

• pthread_mutex_-

• CloseHandle

• pthread_mutex_-

destroy

• pthread_mutex_lock

• WaitForSingleObject
• ReleaseMutex

unlock

unlock

11-40

• pthread_mutex_lock
• pthread_mutex_-

• pthread_mutex_Synchronization • sem_init
API
• sem_destroy

destroy

• CreateSemaphore

• sem_open

• CloseHandle

• sem_unlink

Build and Download to a Multicore Target

Data Protection and Synchronization APIs that Embedded Coder and Generic Real-Time
Targets Use (Continued)
API

Linux Implementation

Windows
Implementation

Mac OS
Implementation

• sem_wait

• WaitForSingle-

• sem_wait

• sem_post

Object

• sem_post

• ReleaseSemaphore
The main() code is always dynamically generated. The general structure of
the generated main file is depicted in the following pseudocode:
main()
{
Model_initialize();
For_each_periodic_task
{
Create_synchronization_event(periodic_task);
Create_thread(periodic_task);
}
For_each_aperiodic_task
{
Create_external_event(aperiodic_task);
Create_thread(aperiodic_task);
}
Create_timer();
Create_thread(Periodic_task_scheduler);
For_each_aperiodic_trigger
{
Hookup_isr_to_aperiodic_event();
}
Wait_for_stopping();
Cleanup();
Model_terminate();
return 0;

11-41

11

Configuring Models for Targets with Multicore Processors

}
Periodic_task_scheduler()
{
Wait_for_event_from_timer(clock);
For_each_periodic_task
{
If periodic_task has a sample time hit
Set the event to run the task
}
}
Periodic_Task()
{
Wait_for_event(Periodic_task_scheduler);
Run the appropriate periodic_task();
}
Aperiodic_Task()
{
Wait_for_aperiodic_event();
Run the appropriate aperiodic_task();
}
Isr()
{
Run the appropriate aperiodic_trigger ();
}

Configuring Embedded Coder for Native Threads
Example
To generate code for an Embedded Coder target, in the Configuration
Execution dialog box:
• Select the Code Generation > Templates > Generate an example
main program check box.
• From the Code Generation > Templates > Target Operating System
list, select NativeThreadsExample.

11-42

Build and Download to a Multicore Target

Build and Download
You can build and download concurrent execution models for the following
targets using system target files:
• Linux, Windows, and Mac OS using ert.tlc and grt.tlc.
• xPC Target using xpctarget.tlc and xpctargetert.tlc.
• Linux and Windows using idelink_ert.tlc and idelink_grt.tlc.
• Embedded Linux and VxWorks using idelink_ert.tlc and
idelink_grt.tlc.
Note Deploying to embedded Linux and VxWorks targets requires the
Embedded Coder product.
You cannot generate code for C++ (Encapsulated) language option.

11-43

11

Configuring Models for Targets with Multicore Processors

Profile and Evaluate
Profile the execution of your code on the multicore system using a
profiling tool like that provided in the xPC Target software. Profiling
lets you identify the areas in your model that are execution bottlenecks.
You can analyze the execution time of each task and find the task that
takes most of the execution time. For example, if you are using the xPC
Target profiling tool, you can compare the average execution times of the
tasks. If a task is computation-intensive, or does not satisfy real-time
requirements and overruns, you can break it into multiple tasks that are less
computation-intensive and that can run concurrently.
Based on this analysis, you can then explicitly change the mapping of Model
blocks to efficiently use the concurrency available on your multicore system
(see “Mapping Blocks to Tasks” on page 11-24).

11-44

Concurrent Execution Example Model

Concurrent Execution Example Model
For an interactive example of a model that has been configured to work in a
concurrent execution environment:
1 In the MATLAB Command Window, click the question mark.

The Documentation Center window opens.
2 Navigate to Simulink > Examples > Modeling Features > Modeling

Concurrency > Modeling Concurrent Execution on Multi-Core
Targets.

Modeling Concurrent Execution on Multi-Core Targets
This model shows how you can use Simulink and Simulink Coder™ to
realize concurrent execution of a model on a multicore target. Additionally,
the example also illustrates how simulation captures effects of on-target
concurrent execution, such as the transfer of data between tasks.
Example Requirements

If you want to generate code for this model, ensure that Simulink Coder™
is installed. Note, when you simulate the example, Simulink and Simulink
Coder™ might generate code in a Simulink project folder created in the
current working folder. If you do not want to (or cannot) generate files in this
folder, change the current working folder to a suitable folder.
topmdl = 'sldemo_concurrent_execution';
open_system(topmdl);
curDir = pwd;
cd(tempdir);

11-45

11

Configuring Models for Targets with Multicore Processors

Overview of the Model

To take advantage of the concurrent execution feature, use Model blocks to
partition your model into portions that can potentially execute concurrently.
Open the model and examine its partitioning into four Model blocks: Plant,
Compensator, ControllerA, and ControllerB. This example also shows how
you can specify and simulate the effects of asynchronous external inputs to
your system via the root input port Interrupt of ControllerB.
Starting with a Default Configuration

This model has been configured for concurrent execution on a target. For
more information, see the documentation.

11-46

Concurrent Execution Example Model

Use the Concurrent Execution dialog to configure your model for concurrent
execution on the target. Open the Concurrent Execution dialog.
Each element of the Concurrent Execution dialog tree-view allows
configuration of the following model aspects:
• Data Transfer - Allows default configuration of the data transfer options
between tasks (you can override these by configuring each signal through
the signal properties dialog)
• Tasks and Mapping - Allows explicit mapping of blocks to tasks
• Periodic - Allows specification and configuration of periodic tasks
• Interrupt - Allows specification and configuration of aperiodic tasks
As a first step, set up the model to behave in non-concurrent fashion to identify
bottlenecks in execution. You can use the Get Default Configuration
button in the Tasks and Mapping pane to do this. Alternatively, click on
the following link. You can now simulate the default configuration of the
model with all Model blocks mapped to a single periodic task Task_TID01 and
a single aperiodic trigger AperiodicEventHandler1. Observe the outputs
of ControllerB in the scope.

11-47

11

Configuring Models for Targets with Multicore Processors

Exploring Concurrent Execution

This example is a fairly simple model illustrating the basic elements of
concurrent execution. In a real-world application model, you might see
bottlenecks due to all blocks mapped to a single periodic task as with the
default configuration for this example.
Assume that you have significant computation in all four Model blocks which
needs to be mapped to separate tasks on a multicore target platform. To
experiment with a different mapping for the Model blocks, change the task
configuration to create new tasks, and map the blocks to the newly created
tasks. Do this automatically using the following link or by following the
instructions below.
To change the task mapping, first create tasks. Both periodic and aperiodic
tasks (not used in this model) are supported. Refer to the documentation for
more information about configuring aperiodic tasks.

11-48

Concurrent Execution Example Model

1 Click the Add Task button on the toolbar to create a new task. You can

configure Name, Period (i.e., sample time) and Color of the newly created
task. Rename the task to Plant. Change the period attribute of the task to
be 0.1. Click the Apply button to save your changes. Similarly, create two
more tasks named ControllerA and ControllerB, both with period 0.1.
2 Click the Add aperiodic trigger button on the toolbar to create a new

aperiodic trigger. You can configure an aperiodic trigger to generate
an aperiodic event, e.g., to simulate the effects of an interrupt on the
system. You can also configure the behavior of aperiodic triggers during
simulation and code generation. To configure the simulation behavior,
open the Configuration Parameters dialog box for the top-level model,
select the Data Import/Export pane, and select the Input check box. This
parameter specifies the time points at which the external aperiodic trigger
is generated. This example is pre-configured to generate the aperiodic
trigger at time points 4 and 7.
3 Click Tasks and Mapping node. Change the mapping of

Block:Compensator by clicking the task Periodic:Task_TID01 in
the Name column and changing it to Periodic:Plant from the task
drop-down list. Similarly, change the mapping of Block:ControllerA to
Periodic:ControllerA, Block:ControllerB to Periodic:ControllerB,
Block:Plant to Periodic:Plant, and Block:Interrupt to
AperiodicEventHandler1.
Now, simulate the model and examine the effects of your mapping. The
Simulink editor shows the inter task communication via the new
icons on
the signals between the Model blocks. The
icon on the signal indicates
that inter task communication introduces a unit delay in the communication
between each pair of tasks.

11-49

11

Configuring Models for Targets with Multicore Processors

% Enable the external inputs to the system.
set_param(topmdl, 'LoadExternalInput', 'on');
%Get Active Configuration Set
csTop = getActiveConfigSet(topmdl);
% Get the task configuration.
tc = csTop.concurrentExecutionComponents;
% Get the block handles for mapping.
plantBlkH
= get_param([topmdl
compensatorBlkH = get_param([topmdl
controlABlkH
= get_param([topmdl
controlBBlkH
= get_param([topmdl
interruptBlkH
= get_param([topmdl
% Delete any previously created tasks
periodicTrigger = tc.Triggers(1);

11-50

'/Plant'], 'Handle');
'/Compensator'], 'Handle');
'/Controller A'], 'Handle');
'/Controller B'], 'Handle');
'/Interrupt'], 'Handle');

Concurrent Execution Example Model

periodicTasks
= periodicTrigger.Tasks;
tnames
= {periodicTasks.Name};
for i = 1:length(periodicTasks)
periodicTrigger.deleteTask(tnames{i});
end
% Delete Aperiodic Trigger
aperiodicTrigger = tc.Triggers(2);
tc.deleteTrigger(aperiodicTrigger);
% Create and configure new tasks.
plant
= periodicTrigger.addTask('Plant');
controlA
= periodicTrigger.addTask('ControllerA');
controlB
= periodicTrigger.addTask('ControllerB');
interruptSource = tc.addAperiodicTrigger('Interrupt');
plant.Period
= '0.1';
controlA.Period = '0.1';
controlB.Period = '0.1';
% Perform mapping of blocks to tasks.
tc.map(plantBlkH, plant);
tc.map(compensatorBlkH, plant);
tc.map(controlABlkH, controlA);
tc.map(controlBBlkH, controlB);
tc.map(interruptBlkH, interruptSource);
% Launch Concurrent Execution dialog
Simulink.SoftwareTarget.concurrentExecution(topmdl, ...
'OpenDialog', ...
'Configuration');
sim(topmdl);
Viewing Simulation Results

You can use the Simulation Data Inspector to view the simulation results.
Note that the output of Block:ControllerB (u2) becomes zero around points
4 and 7 because of the occurrence of the aperiodic event (switch). After the
event, the output continues to settle down to zero. To further observe the

11-51

11

Configuring Models for Targets with Multicore Processors

effect of the aperiodic trigger on the system, alter the time points at which the
aperiodic event trigger is generated.

Configuring Inter Task Communication

You can change the modes of the inter task communication between the
Model blocks in the model to better suit design criteria. Do this by clicking
the following link or by following these instructions:
Click on Data Transfer node of the Concurrent Execution dialog. In the Data
Transfer Options pane, change Defaults > Periodic signals to Ensure
data integrity only by selecting it. Click Apply to save the changes.
Now, simulate the model. The lock icon on the signals between the Model
blocks indicates that data transfer between concurrent tasks is performed in

11-52

Concurrent Execution Example Model

data-integrity-only mode. For fine-grained control on the data transfer modes
between tasks at the level of individual signals, see the documentation.
Generating Code
1 To generate code for the model, save the model after performing the

preceding steps. You can change to a temporary folder so that the original
example model remains unchanged.
2 Depending on the host platform that you use for running this example, you

might need to change the code generation properties of the aperiodic trigger.
You can configure aperiodic triggers to generate code using POSIX signals
or Windows events. To generate code using POSIX signals to represent
the aperiodic triggers, select the AperiodicEventHandler1 node in the
Concurrent Execution dialog. For the ’Aperiodic trigger source’ parameter,
choose ’POSIX Signal (Linux/VxWorks 6.x)’. For the ’Signal number’
parameter, enter a valid signal number, [2, SIGRTMAX-SIGRTMIN-1], to
represent the POSIX signal to represent this aperiodic trigger. To generate
aperiodic triggers using Windows Events, for the ’Aperiodic trigger source’
parameter, choose ’Event (Windows)’. Enter a name to represent this
aperiodic trigger.
3 Generate code from the model.
4 In the code generation report, click grt_main.c to view the threads created

for tasks. Because you created three tasks in the task configuration, you
will see three threads created in the main() function. Depending on the
platform that you are using to view this example, you will see that either
Windows or POSIX threads are used for tasks. You will also see that either
Windows events or POSIX signal handlers are generated corresponding to
the aperiodic trigger.
5 Open sldemo_concurrent_execution.c to view the output/update

functions that are mapped to tasks. For example, Periodic_Plant_output
corresponds to the task Plant, Periodic_ControllerA_output
corresponds to the task ControllerA, etc. Observe that a
function AperiodicEventHandler1 is generated for the aperiodic
trigger. This function is associated with a signal handler
sigHandler_AperiodicEventHandler1 generated in grt_main.c. If you
chose Windows events, you will observe a similar function generated for
the aperiodic trigger.

11-53

11

Configuring Models for Targets with Multicore Processors

Closing the Models

close_system(topmdl, 0);
close_system([topmdl,'_plant'], 0);
close_system([topmdl,'_compensator'], 0);
close_system([topmdl,'_controller_A'], 0);
close_system([topmdl,'_controller_B'], 0);
cd(curDir);
Conclusion

This example illustrates a simple workflow using Simulink and Simulink
Coder™ to examine the effects of concurrent execution on a multicore
target. You can iteratively apply this workflow to optimize performance of a
real-world application on a multicore xPC Target™ environment, along with
the on-target profiling capability of xPC Target™.

11-54

Command-Line Interface

Command-Line Interface
The previous topics describe how to configure models for concurrent
execution using the Simulink Configuration Execution dialog box.
You can also perform the configuration using a command-line
interface. The following classes, their methods and properties, and the
Simulink.SoftwareTarget.concurrentExecution function comprise this
interface:
To...

Use...

Create a configuration
set for concurrent
execution

Simulink.SoftwareTarget.concurrentExecution

Specify aperiodic
trigger

Simulink.SoftwareTarget.AperiodicTrigger

Specify periodic trigger

Simulink.SoftwareTarget.PeriodicTrigger

Specify aperiodic
trigger for POSIX
targets

Simulink.SoftwareTarget.PosixSignalHandler

Specify task that
models unit of
concurrent execution

Simulink.SoftwareTarget.Task

Configure model for
concurrent execution

Simulink.SoftwareTarget.TaskConfiguration

Specify base class for
PeriodicTrigger and
AperiodicTrigger

Simulink.SoftwareTarget.WindowsEventHandler

Describe aperiodic
trigger for Windows
target

Simulink.SoftwareTarget.Trigger

Configure concurrent
execution data
transfers

Simulink.GlobalDataTransfer

11-55

11

11-56

Configuring Models for Targets with Multicore Processors

12
Modeling Best Practices
• “General Considerations when Building Simulink Models” on page 12-2
• “Model a Continuous System” on page 12-8
• “Best-Form Mathematical Models” on page 12-11
• “Model a Simple Equation” on page 12-15
• “Componentization Guidelines” on page 12-17
• “Modeling Complex Logic” on page 12-36
• “Modeling Physical Systems” on page 12-37
• “Modeling Signal Processing Systems” on page 12-38

12

Modeling Best Practices

General Considerations when Building Simulink Models
In this section...
“Avoiding Invalid Loops” on page 12-2
“Shadowed Files” on page 12-4
“Model Building Tips” on page 12-6

Avoiding Invalid Loops
You can connect the output of a block directly or indirectly (i.e., via other
blocks) to its input, thereby, creating a loop. Loops can be very useful. For
example, you can use loops to solve differential equations diagrammatically
(see “Model a Continuous System” on page 12-8) or model feedback control
systems. However, it is also possible to create loops that cannot be simulated.
Common types of invalid loops include:
• Loops that create invalid function-call connections or an attempt to
modify the input/output arguments of a function call (see “Function-Call
Subsystems” on page 7-30 for a description of function-call subsystems)
• Self-triggering subsystems and loops containing non-latched triggered
subsystems (see “Triggered Subsystems” on page 7-20 in the Using
Simulink documentation for a description of triggered subsystems and
Inport in the Simulink reference documentation for a description of
latched input)
• Loops containing action subsystems
The Subsystem Examples block library in the Ports & Subsystems library
contains models that illustrates examples of valid and invalid loops involving
triggered and function-call subsystems. Examples of invalid loops include
the following models:
• simulink/Ports&Subsystems/sl_subsys_semantics/Triggered
subsystem/sl_subsys_trigerr1 (sl_subsys_trigerr1)
• simulink/Ports&Subsystems/sl_subsys_semantics/Triggered
subsystem/sl_subsys_trigerr2 (sl_subsys_trigerr2)

12-2

General Considerations when Building Simulink® Models

• simulink/Ports&Subsystems/sl_subsys_semantics/Function-call
systems/sl_subsys_fcncallerr3 (sl_subsys_fcncallerr3)
You might find it useful to study these examples to avoid creating invalid
loops in your own models.

Detecting Invalid Loops
To detect whether your model contains invalid loops, select Update Diagram
from the model’s Simulation menu. If the model contains invalid loops, the
invalid loops are highlighted. This is illustrated in the following model ,

and displays an error message in the Simulation Diagnostics Viewer.

12-3

12

Modeling Best Practices

Shadowed Files
If there are two Model files with the same name (e.g. mylibrary.slx) on
the MATLAB path, the one higher on the path is loaded, and the one lower
on the path is said to be "shadowed".
The rules Simulink software uses to find Model files are similar to those used
by MATLAB software. See "How the Search Path Determines Which Function
to Use" in the MATLAB documentation. However, there is an important
difference between how Simulink block diagrams and MATLAB functions are
handled: a loaded block diagram takes precedence over any unloaded ones,
regardless of its position on the MATLAB path. This is done for performance
reasons, as part of the Simulink software’s incremental loading methodology.
The precedence of a loaded block diagram over any others can have important
implications, particularly since a block diagram can be loaded without the
corresponding Simulink window being visible.

12-4

General Considerations when Building Simulink® Models

Making Sure the Correct Block Diagram Is Loaded
When using libraries and referenced models, a block diagram may be loaded
without showing its window. If the MATLAB path or the current MATLAB
folder changes while block diagrams are in memory, these block diagrams
may interfere with the use of other files of the same name. For example,
after a change of folder, a loaded but invisible library may be used instead
of the one the user expects.
To see an example:
1 Enter sldemo_hydcyl4 to open the Simulink model sldemo_hydcyl4.
2 Use the find_system command to see which block diagrams are in memory:

find_system('type','block_diagram')
ans =
'hydlib'
'sldemo_hydcyl4'

Note that a Simulink library, hydlib, has been loaded, but is currently
invisible.
3 Now close sldemo_hydcyl4. Run the find_system command again, and

you will see that the library is still loaded.
If you change to another folder which contains a different library called
hydlib, and try to run a model in that folder, the library in that folder would

not be loaded because the block diagram of the same name in memory takes
precedence. This can lead to problems including:
• Simulation errors
• "Bad Link" icons on blocks which are library links
• Wrong results
To prevent these conditions, it is necessary to close the library explicitly as
follows:

12-5

12

Modeling Best Practices

close_system('hydlib')

Then, when the Simulink software next needs to use a block in a library called
hydlib it will use the file called hydlib.slx which is highest on the MATLAB
path at the time. Alternatively, to make the library visible, enter:
open_system('hydlib')

Detecting and Fixing Problems
When updating a block diagram, the Simulink software checks the position
of its file on the MATLAB path and will issue a warning if it detects that
another file of the same name exists and is higher on the MATLAB path.
The warning reads:
The file containing block diagram 'mylibrary' is shadowed
by a file of the same name higher on the MATLAB path.

This may indicate that the wrong file called mylibrary.slx is being used. To
see which file called mylibrary.slx is loaded into memory, enter:
which mylibrary
C:\work\Model1\mylibrary.slx

To see all the files called mylibrary which are on the MATLAB path,
including MATLAB scripts, enter:
which -all mylibrary
C:\work\Model1\mylibrary.slx
C:\work\Model2\mylibrary.slx

% Shadowed

To close the block diagram called mylibrary and let the Simulink software
load the file which is highest on the MATLAB path, enter:
close_system('mylibrary')

Model Building Tips
Here are some model-building hints you might find useful:

12-6

General Considerations when Building Simulink® Models

• Memory issues
In general, more memory will increase performance.
• Using hierarchy
More complex models often benefit from adding the hierarchy of subsystems
to the model. Grouping blocks simplifies the top level of the model and can
make it easier to read and understand the model. For more information,
see “Create a Subsystem” on page 4-36. The Model Browser provides useful
information about complex models (see “Model Browser” on page 9-80).
• Cleaning up models
Well organized and documented models are easier to read and understand.
Signal labels and model annotations can help describe what is happening
in a model. For more information, see “Signal Names and Labels” on page
47-19 and “Annotate Diagrams” on page 4-23.
• Modeling strategies
If several of your models tend to use the same blocks, you might find it
easier to save these blocks in a model. Then, when you build new models,
just open this model and copy the commonly used blocks from it. You can
create a block library by placing a collection of blocks into a system and
saving the system. You can then access the system by typing its name in
the MATLAB Command Window.
Generally, when building a model, design it first on paper, then build it
using the computer. Then, when you start putting the blocks together
into a model, add the blocks to the model window before adding the lines
that connect them. This way, you can reduce how often you need to open
block libraries.

12-7

12

Modeling Best Practices

Model a Continuous System
To model the differential equation
x´= –2x(t)+u(t),
where u(t) is a square wave with an amplitude of 1 and a frequency of 1
rad/sec, use an integrator block and a gain block. The Integrator block
integrates its input x´ to produce x. Other blocks needed in this model include
a Gain block and a Sum block. To generate a square wave, use a Signal
Generator block and select the Square Wave form but change the default
units to radians/sec. Again, view the output using a Scope block. Gather the
blocks and define the gain.
In this model, to reverse the direction of the Gain block, select the block, then
use the Diagram > Rotate & Flip > Flip Block command. To create the
branch line from the output of the Integrator block to the Gain block, hold
down the Ctrl key while drawing the line. For more information, see “Draw a
Branch Line” on page 4-16.
Now you can connect all the blocks.

An important concept in this model is the loop that includes the Sum block,
the Integrator block, and the Gain block. In this equation, x is the output of
the Integrator block. It is also the input to the blocks that compute x´, on
which it is based. This relationship is implemented using a loop.

12-8

Model a Continuous System

The Scope displays x at each time step. For a simulation lasting 10 seconds,
the output looks like this:

The equation you modeled in this example can also be expressed as a transfer
function. The model uses the Transfer Fcn block, which accepts u as input
and outputs x. So, the block implements x/u. If you substitute sx for x´ in
the above equation, you get
sx = –2x + u.
Solving for x gives
x = u/(s + 2)
or,
x/u = 1/(s + 2).
The Transfer Fcn block uses parameters to specify the numerator and
denominator coefficients. In this case, the numerator is 1 and the denominator

12-9

12

Modeling Best Practices

is s+2. Specify both terms as vectors of coefficients of successively decreasing
powers of s.
In this case the numerator is [1] (or just 1) and the denominator is [1 2].

The results of this simulation are identical to those of the previous model.

12-10

Best-Form Mathematical Models

Best-Form Mathematical Models
In this section...
“Series RLC Example” on page 12-11
“Solving Series RLC Using Resistor Voltage” on page 12-12
“Solving Series RLC Using Inductor Voltage” on page 12-13

Series RLC Example
You can often formulate the mathematical system you are modeling in several
ways. Choosing the best-form mathematical model allows the simulation to
execute faster and more accurately. For example, consider a simple series
RLC circuit.

R

L

C

VAC
According to Kirchoff’s voltage law, the voltage drop across this circuit is
equal to the sum of the voltage drop across each element of the circuit.

VAC = VR + VL + VC
Using Ohm’s law to solve for the voltage across each element of the circuit,
the equation for this circuit can be written as

VAC = Ri + L

di 1 t
i(t) dt
+
dt C ∫−∞

You can model this system in Simulink by solving for either the resistor
voltage or inductor voltage. Which you choose to solve for affects the structure
of the model and its performance.

12-11

12

Modeling Best Practices

Solving Series RLC Using Resistor Voltage
Solving the RLC circuit for the resistor voltage yields

VR = Ri
Ri = VAC − L

di 1 t
i(t) dt
−
dt C ∫−∞

Circuit Model
The following diagram shows this equation modeled in Simulink where R is
70, C is 0.00003, and L is 0.04. The resistor voltage is the sum of the voltage
source, the capacitor voltage, and the inductor voltage. You need the current
in the circuit to calculate the capacitor and inductor voltages. To calculate
the current, multiply the resistor voltage by a gain of 1/R. Calculate the
capacitor voltage by integrating the current and multiplying by a gain of 1/C.
Calculate the inductor voltage by taking the derivative of the current and
multiplying by a gain of L.

This formulation contains a Derivative block associated with the inductor.
Whenever possible, you should avoid mathematical formulations that
require Derivative blocks as they introduce discontinuities into your system.
Numerical integration is used to solve the model dynamics though time.

12-12

Best-Form Mathematical Models

These integration solvers take small steps through time to satisfy an accuracy
constraint on the solution. If the discontinuity introduced by the Derivative
block is too large, it is not possible for the solver to step across it.
In addition, in this model the Derivative, Sum, and two Gain blocks create
an algebraic loop. Algebraic loops slow down the model’s execution and can
produce less accurate simulation results. See “Algebraic Loops” on page 3-39
for more information.

Solving Series RLC Using Inductor Voltage
To avoid using a Derivative block, formulate the equation to solve for the
inductor voltage.

VL = L
L

di
dt

1 t
di
= VAC − Ri − ∫ i(t) dt
dt
C −∞

Circuit Model
The following diagram shows this equation modeled in Simulink. The
inductor voltage is the sum of the voltage source, the resistor voltage, and the
capacitor voltage. You need the current in the circuit to calculate the resistor
and capacitor voltages. To calculate the current, integrate the inductor
voltage and divide by L. Calculate the capacitor voltage by integrating the
current and dividing by C. Calculate the resistor voltage by multiplying the
current by a gain of R.

12-13

12

Modeling Best Practices

This model contains only integrator blocks and no algebraic loops. As a result,
the model simulates faster and more accurately.

12-14

Model a Simple Equation

Model a Simple Equation
To model the equation that converts Celsius temperature to Fahrenheit
TF = 9/5(TC) + 32

First, consider the blocks needed to build the model:
• A Ramp block to input the temperature signal, from the Sources library
• A Constant block to define a constant of 32, also from the Sources library
• A Gain block to multiply the input signal by 9/5, from the Math Operations
library
• A Sum block to add the two quantities, also from the Math Operations
library
• A Scope block to display the output, from the Sinks library
Next, gather the blocks into your model window.

Assign parameter values to the Gain and Constant blocks by opening
(double-clicking) each block and entering the appropriate value. Then, click
the OK button to apply the value and close the dialog box.

12-15

12

Modeling Best Practices

Now, connect the blocks.

The Ramp block inputs Celsius temperature. Open that block and change the
Initial output parameter to 0. The Gain block multiplies that temperature
by the constant 9/5. The Sum block adds the value 32 to the result and
outputs the Fahrenheit temperature.
Open the Scope block to view the output. Now, choose Run from the
Simulation menu to run the simulation. The simulation runs for 10 seconds.

12-16

Componentization Guidelines

Componentization Guidelines
Componentization
A component is a piece of your design, a unit level item, or a subassembly,
that you can work on without needing the higher level parts of the model.
Componentization involves organizing your model into components.
Componentization provides many benefits for organizations that develop large
Simulink models that consist of many functional pieces. The benefits include:
• Meeting development process requirements, such as:

-

Component reuse
Team-based development
Intellectual property protection
Unit testing

• Improving performance for:

-

Model loading
Simulation speed
Memory usage

Componentization Techniques
Key componentization techniques that you can use with Simulink include:
• Subsystems
• Libraries
• Model referencing
These componentization techniques support a wide range of modeling
requirements for models that vary in size and complexity. Most large models
use a combination of componentization techniques. For example, you can
include subsystems in referenced models, and include referenced models in
subsystems. As another example, a large model might use model reference

12-17

12

Modeling Best Practices

Accelerator blocks at the top level component partitions and blend model
reference Accelerator and atomic subsystem libraries at lower levels.
Simulink provides tools to convert from subsystems to model referencing.
Because of the differences between subsystems and model referencing,
switching from subsystems to model referencing can involve several steps
(see Converting a Subsystem to a Referenced Model). Consider scalability
and support for anticipated future modeling requirements, such as how a
model is likely to grow in size and complexity and possible code generation
requirements. Designing a scalable architecture can avoid later conversion
costs.

General Componentization Guidelines
This table provides high-level guidelines about the kinds of modeling goals
and models for which subsystems, libraries, and model referencing are each
particularly well suited.
Componentization
Technique

Modeling Goals for Which the Technique Is
Well Suited

Subsystems

• Add hierarchy to organize and visually
simplify a model.
• Maximize design reuse with inherited
attributes for context-dependent behavior.

Libraries

• Provide a frequently used, and infrequently
changed, modeling utility.
• Reuse components repeatedly in a model or in
multiple models.

Model referencing

• Develop a referenced model independently
from the models that use it.
• Obscure the contents of a referenced model,
allowing you to distribute it without revealing
the intellectual property that it embodies.
• Reference a model multiple times without
having to make redundant copies.

12-18

Componentization Guidelines

Componentization
Technique

Modeling Goals for Which the Technique Is
Well Suited
• Facilitate changes by multiple people, with
defined interfaces for top-level components.
• Improve the overall performance by using
incremental model loading, update diagram,
simulation, and code generation for large
models (for example, a model with 10,000
blocks).
• Perform unit testing.
• Simplify debugging for large models.
• Generate code that reflects the model
structure.

For a more detailed comparison of these modeling techniques, see “Summary
of Componentization Techniques” on page 12-19.

Summary of Componentization Techniques
This section compares subsystems, libraries, and model referencing. The table
includes recommendations and notes about a range of modeling requirements
and features.
To see more information about a specific requirement or feature, click a link
in a table cell.
Modeling
Requirement
or Feature
Subsystems

Libraries

Model
Referencing

Development Process
Component
reuse

Not supported

Well suited

Well suited

Team-based
development

Not supported

Supported, with
limitations

Well suited

12-19

12

Modeling Best Practices

Modeling
Requirement
or Feature
Subsystems

Libraries

Model
Referencing

Intellectual
property
protection

Not supported

Not supported

Well suited

Unit testing

Supported, with
limitations

Supported, with
limitations

Well suited

Model loading
speed

Supported, with
limitations

Well suited

Well suited

Simulation
speed for
large models

Supported, with
limitations

Supported, with
limitations

Well suited

Memory

Supported, with
limitations

Supported, with
limitations

Well suited

Artificial
algebraic loop
avoidance

Well suited

Well suited

Supported, with
limitations

Signal
property
inheritance

Well suited

Well suited

Supported, with
limitations

State
initialization

Well suited

Well suited

Supported, with
limitations

Tunability

Well suited

Well suited

Supported, with
limitations

Buses

Well suited

Well suited

Supported, with
limitations

S-functions

Well suited

Well suited

Supported, with
limitations

Performance

Features

12-20

Componentization Guidelines

Modeling
Requirement
or Feature
Subsystems

Libraries

Model
Referencing

Model
configuration
settings

Well suited

Well suited

Supported, with
limitations

Tools

Well suited

Well suited

Supported, with
limitations

Code
generation

Supported, with
limitations

Supported, with
limitations

Well suited

For each modeling technique, you can see a summary table that includes
the more detailed information included in the links in the above summary
table of componentization techniques:
• “Subsystems Summary” on page 12-21
• “Libraries Summary” on page 12-25
• “Model Referencing Summary” on page 12-29

Subsystems Summary
This section provides guidelines for using subsystems for each of the modeling
requirements and features highlighted in the “Summary of Componentization
Techniques” on page 12-19.
For additional information about subsystems, see:
• Creating Subsystems
• “Conditional Subsystems”

12-21

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Subsystems

Development Process
Component reuse

Not supported
• Copy a subsystem to reuse it in a model.
• Subsystem copies are independent of each other.
• Save a subsystem by saving the model that
contains the subsystem.
• Configuration management for subsystems is
difficult.

Team-based
development

Not supported
• For subsystems in a model, Simulink provides no
direct interface with source control tools.
• To create or change a subsystem, you need to
open the parent model’s file. This can lead to file
contention when multiple people want to work on
multiple subsystems in a model.

Intellectual
property protection

Not supported

Unit testing

Supported, with limitations

Use model referencing protected models instead.

• For coverage testing, use Signal Builder and source
blocks.
• Each time a subsystem changes, you need to copy
the subsystem to a harness model.
• The test harness may have different Simulink sort
orders, due to virtual boundaries.
• Test harness files require configuration
management overhead.
Performance

12-22

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Subsystems

Model loading
speed

Supported, with limitations

Simulation speed
for large models

Supported, with limitations

Loading a model loads all subsystems at one time.
There is no incremental loading.

• To speed simulation, use Accelerator or Rapid
Accelerator simulation mode.
• Simulation mode applies to the whole model.
Model referencing provides a finer level of control
for simulation modes.
Memory

Supported, with limitations
Memory use for simulation and code generation is
comparable for subsystems and libraries. For models
with over 500 blocks, model reference Accelerator
mode can significantly reduce memory usage for
simulation and code generation.

Artificial algebraic
loop avoidance

Well suited
• Virtual subsystems avoid artificial algebraic loops.
• For nonvirtual subsystems, consider enabling the
Subsystem block parameter Minimize algebraic
loop occurrences.

Features
Signal property
inheritance

Well suited
• Inheriting signal properties from outside of the
subsystem boundary avoids your having to specify
properties for every signal.
• Propagation of signal properties can lead to
Simulink using signal properties that you did not
anticipate.

12-23

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Subsystems

State initialization

Well suited
You can initialize states of subsystems.

Tunability

Well suited
• Tune subsystems using a block parameterization
or masked subsystems.
• Control tunability using Configuration
Parameters > Optimization > Signals and
Parameters > Inline parameters.

Buses

Well suited
Subsystems do not require the use of bus objects for
virtual buses.

S-functions

Well suited
Subsystems support inlined or noninlined S-functions.

Model
configuration
settings

Well suited

Tools

Well suited

A subsystem uses the model configuration settings of
the model that contains the subsystem.
Subsystems provide extensive support for Simulink
tools.

Code generation

Supported, with limitations
• To generate code for a subsystem by itself,
right-click the Subsystem block and select a code
generation option.
• As an optimization, Simulink attempts to recognize
identical subsystems. For detected identical
subsystems, the generated code includes only one
copy of code for the multiple subsystems.

12-24

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Subsystems

• For virtual subsystems, you cannot specify file or
function code partitions for code generation.

Libraries Summary
This section provides guidelines for using libraries for each of the modeling
requirements and features highlighted in the “Summary of Componentization
Techniques” on page 12-19.
For additional information about libraries, see “Libraries”.
Modeling
Requirement or
Feature

Guidelines for Libraries

Development Process
Component reuse

Well suited
• Access a collection of well-defined utility blocks.
• Create a component once and reuse it in models.
• Link to the same library block multiple times
without creating multiple copies.
• Link to the same library block from multiple
models.
• Restrict write access to library components.
• Maintain one truth: propagate changes from a
single library block to all blocks that link to that
library.
• Disable a link to allow independent changes to a
linked block.
• Managing library links adds some overhead.

12-25

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Libraries

• Save library in a file similar to a Simulink model,
but you cannot simulate the file contents.
Team-based
development

Supported, with limitations
• Place library files in source control for version
control and configuration management.
• Maintain one truth: propagate changes from a
single library block to all blocks that link to that
library.
• To reduce file contention, use one subsystem per
library.
• Link to the same library block from multiple
models.
• Restrict write access to library component.
• See General Reusability Limitations.

Intellectual
property protection

Not supported

Unit testing

Supported, with limitations

Use model referencing protected models instead.

• For coverage testing, use Signal Builder and
source blocks.
• Test harness may have different Simulink sort
orders, due to virtual boundaries.
• Test harness files require configuration
management overhead.
Performance

12-26

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Libraries

Model loading speed

Well suited
Simulink incrementally loads a library at the point
needed during editing, updating a diagram, or
simulating a model.

Simulation speed
for large models

Supported, with limitations
• To speed simulation, use Accelerator or Rapid
Accelerator simulation mode.
• Simulation mode applies to the whole model.
Model referencing provides a finer level of control
for simulation modes.

Memory

Supported, with limitations
• Simulink incrementally loads libraries at the point
needed during editing, updating a diagram, or
simulating a model.
• Simulink duplicates library block instances during
block update.
• Memory usage for simulation and code generation
is comparable for subsystems and libraries. For
models with over 500 blocks, model reference
Accelerator mode can significantly reduce memory
usage for simulation and code generation.

Artificial algebraic
loop avoidance

Well suited
• Virtual subsystems avoid artificial algebraic loops.
• For nonvirtual subsystems, consider enabling the
Subsystem block parameter Minimize algebraic
loop occurrences.

Features

12-27

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Libraries

Signal property
inheritance

Well suited
• Inheriting signal properties from outside of the
library block boundary avoids your having to
specify properties for every signal.
• Propagation of signal properties can lead to
Simulink using signal properties that you did not
anticipate.

State initialization

Well suited
You can initialize states of library blocks.

Tunability

Well suited
• Tune library blocks using block parameterization
or masked subsystems.
• Control tunability using Configuration
Parameters > Optimization > Signals and
Parameters > Inline parameters.

Buses

Well suited
Libraries do not require the use of bus objects for
virtual buses.

S-functions

Well suited
Libraries support inlined and noninlined S-functions.

Model configuration
settings

Well suited
• Library models do not have model configuration
settings.
• A referenced library block uses the model
configuration setting of the model that contains
that block.

12-28

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Libraries

Tools

Supported, with limitations
There are some limitations for using some Simulink
tools, such as the Model Advisor, with libraries.

Code generation

Supported, with limitations
• As an optimization, Simulink attempts to recognize
identical subsystems. For detected identical
subsystems, the generated code includes only one
copy of code for the multiple subsystems.
• For virtual subsystems, you cannot specify file or
function code partitions for code generation.

Model Referencing Summary
This section provides guidelines for using model referencing for each of
the modeling requirements and features highlighted in the “Summary of
Componentization Techniques” on page 12-19.
For additional information about model referencing, see:
• “Model Reference”
• Simulink Model Referencing Requirements
• Model Referencing Limitations

12-29

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Development Process Requirements
Component reuse

Well suited
• Create a standalone component once and reuse it
in multiple models.
• Reference the same model multiple times without
creating multiple copies.
• Reference the same model from multiple models.
• Model referencing uses specified boundaries for
preserving component integrity.

Team-based
development

Well suited
• For version control and configuration management,
you can place model reference files in a source
control system.
• Design, create, simulate, and test a referenced
model independently from the model that
references it.
• Link to the same model reference from multiple
models.
• Changes made to a referenced model apply to all
instances of that referenced model.
• Simulink does not limit access for changing a
model reference.
• You save a referenced model in a separate file from
the model that references it. Using separate files
helps to avoid file contention.

12-30

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Intellectual
property protection

Well suited
• Use the protected model feature to obscure
contents of a referenced model in a distributed
model.
• Creating a protected model feature requires a
Simulink Coder license. Using a protected model
does not require a Simulink Coder license.

Unit testing

Well suited
• Test components independently to isolate
behaviors, by simulating them standalone.
• You can eliminate unit retest for unchanged
components.
• Use a data-defined test harness, with MATLAB
test vectors and direct coverage collection.
• For coverage testing, use root inports and outports.

Performance
Model loading speed

Well suited
• Simulink incrementally loads a referenced model
at the point needed during editing, updating a
diagram, or simulating a model.
• If a simulation target build is required, first-time
loading can be slow.

12-31

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Simulation speed
for large models

Well suited
• Simulate a referenced model standalone.
• The Model block has an option for specifying the
simulation mode.
• You can improve rebuild performance by selecting
the appropriate setting for the Configuration
Parameters > Model Referencing > Rebuild
parameter.
• Simulation through code generation can have a
slow start-up time, which might be undesirable
during prototyping.
• See “Limitations on Normal Mode Referenced
Models” on page 6-83, “Limitations on Accelerator
Mode Referenced Models” on page 6-84, and
“Limitations on PIL Mode Referenced Models” on
page 6-87.

Memory

Well suited
• Simulink loads a referenced model at the point
that model is needed for navigation during editing,
updating a diagram, or simulating a model.
• Use model reference Accelerator mode to reduce
memory usage, incrementally loading a compiled
version of a referenced model.

Artificial algebraic
loop avoidance

Features

12-32

Supported, with limitations
Consider enabling Configuration Parameters >
Model Referencing > Minimize algebraic loop
occurrences.

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Signal property
inheritance

Supported, with limitations
• Inherit sample time when the referenced model is
sample-time independent. You cannot propagate
a continuous sample time to a Model block that is
sample-time independent.
• Model block is context-independent, so it cannot
inherit signal properties. Explicitly set input and
output signal properties.
• Use a bus object to define the signal data type of a
bus signal that is passed into a referenced model.
• Goto and From block lines cannot cross model
referencing boundaries.
•
• See Index Base Limitations.

State initialization

Supported, with limitations
• You can initialize states from the top model.
• Use either the structure format or structure with
time format to initialize the states of a top model
and the models that it references.
• To use the SimState (simulation state) feature
with model referencing, simulate all Model blocks
in Normal mode.
• See “Import and Export State Information for
Referenced Models” on page 45-120.

12-33

12

Modeling Best Practices

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Tunability

Supported, with limitations
• To have each instance of a referenced model use
different values, use model arguments in the
Model block.
• To have each instance of a referenced model use
the same values, use Simulink.Parameter objects.
• To have each instance of a referenced model use
the same values, use Simulink.Parameter objects.
By default, all other parameters are inlined.

Buses

Supported, with limitations
You must use bus objects for bus signals that cross
referenced model boundaries (for example, global
data stores, root inports, root outports).

S-functions

Supported, with limitations
Model referencing generally supports inlined or
noninlined S-functions. See “S-Function Limitations”
on page 6-86.

Model configuration
settings

Supported, with limitations
• To apply the same model configuration settings to
all models in a model hierarchy, use a referenced
configuration set.
• Configuration settings for the root model and
referenced models must be consistent. However,
not all configuration settings need to be the same
across the model hierarchy.

12-34

Componentization Guidelines

Modeling
Requirement or
Feature

Guidelines for Model Referencing

Tools

Supported, with limitations
• There are some limitations for using some
Simulink tools, such as the Simulink Debugger,
with model referencing.
• For details, see “Simulink Tool Limitations” on
page 6-82.

Code generation

Well suited
• By default, model referencing generates code
incrementally.
• You can improve rebuild performance by selecting
the appropriate setting for the Configuration
Parameters > Model Referencing > Rebuild
parameter.
• Model referencing requires the use of bus objects.
For information about the impact of bus objects
for code generation, in the Embedded Coder
documentation, see “Buses”.

12-35

12

Modeling Best Practices

Modeling Complex Logic
To model complex logic in a Simulink model, consider using Stateflow
software.
Stateflow extends Simulink with a design environment for developing state
charts and flow graphs. Stateflow provides the language elements required
to describe complex logic in a natural, readable, and understandable form.
It is tightly integrated with MATLAB and Simulink products, providing an
efficient environment for designing embedded systems that contain control,
supervisory, and mode logic.
For more information on Stateflow software, see “Stateflow”.

12-36

Modeling Physical Systems

Modeling Physical Systems
To model physical systems in the Simulink environment, consider using
Simscape software.
Simscape extends Simulink with tools for modeling systems spanning
mechanical, electrical, hydraulic, and other physical domains as physical
networks. It provides fundamental building blocks from these domains to let
you create models of custom components. The MATLAB based Simscape
language enables text-based authoring of physical modeling components,
domains, and libraries.
For more information on Simscape software, see “Simscape”.

12-37

12

Modeling Best Practices

Modeling Signal Processing Systems
To model signal processing systems in the Simulink environment, consider
using DSP System Toolbox™ software.
DSP System Toolbox provides algorithms and tools for the design and
simulation of signal processing systems. These capabilities are provided
as MATLAB functions, MATLAB System objects, and Simulink blocks.
The system toolbox includes design methods for specialized FIR and IIR
filters, FFTs, multirate processing, and DSP techniques for processing
streaming data and creating real-time prototypes. You can design adaptive
and multirate filters, implement filters using computationally efficient
architectures, and simulate floating-point digital filters. Tools for signal I/O
from files and devices, signal generation, spectral analysis, and interactive
visualization enable you to analyze system behavior and performance. For
rapid prototyping and embedded system design, the system toolbox supports
fixed-point arithmetic and C or HDL code generation.
For more information on DSP System Toolbox software, see “DSP System
Toolbox”.

12-38

13
Managing Projects
• “Organize Large Modeling Projects” on page 13-2
• “Try Simulink Project Tools with the Airframe Project” on page 13-4
• “Create a New Simulink Project” on page 13-23
• “Analyze Project Dependencies” on page 13-32
• “Manage Project Files” on page 13-44
• “Automate Project Startup and Run Frequent Tasks” on page 13-52
• “Run Batch Functions on Project Files” on page 13-58
• “Use Source Control with Projects” on page 13-60
• “Retrieve and Check Out Files Under Source Control” on page 13-76
• “Review Changes and Commit Modified Files” on page 13-89
• “Use Templates to Create Standard Project Settings” on page 13-97
• “Archive Projects in Zip Files” on page 13-103
• “Analyze Model Dependencies” on page 13-104

13

Managing Projects

Organize Large Modeling Projects
In this section...
“What Are Simulink Projects?” on page 13-2
“Get Started with Your Project” on page 13-2

What Are Simulink Projects?
You can use Simulink Projects to help you organize your work. Find all your
required files; manage and share files, settings, and user-defined tasks; and
interact with source control.
Projects can promote more efficient team work and individual productivity
by helping you to:
• Find all the files that belong with your project.
• Share projects using built-in integration with the Subversion client, an
external source control tool.
• View and label modified files for peer review workflows.
• Create standard ways to initialize and shut down a project.
• Create, store, and easily access common operations.
See the Web page
http://www.mathworks.com/products/simulink/simulink-projects/ for

the latest information, downloads, and videos.

Get Started with Your Project
To get started with managing your files in a project:
1 Try an example project to see how the tools can help you organize your

work. See “Try Simulink Project Tools with the Airframe Project” on page
13-4.
2 Create a new project. See “Create a New Simulink Project” on page 13-23.

13-2

Organize Large Modeling Projects

3 Use the Dependency Analysis view to analyze your project and check

required files. See “Analyze Project Dependencies” on page 13-32.
4 Explore views of your files. See “Manage Project Files” on page 13-44.
5 Create shortcuts to save and run frequent tasks. See “Automate Project

Startup and Run Frequent Tasks” on page 13-52.
6 Run operations on batches of files. See “Run Batch Functions on Project

Files” on page 13-58.
7 If you use a source control integration, you can use the Modified Files

view to review changes, compare revisions, and commit modified files. If
you want to use source control with your project, see “Use Source Control
with Projects” on page 13-60.

13-3

13

Managing Projects

Try Simulink Project Tools with the Airframe Project
In this section...
“Explore the Airframe Project” on page 13-4
“Set Up the Project Files and Open the Simulink Project Tool” on page 13-5
“View, Search, and Sort Project Files” on page 13-5
“Automate Project Startup and Shutdown Tasks” on page 13-7
“Open and Run Frequently Used Files” on page 13-9
“Review Changes in Modified Files” on page 13-10
“Run Project Integrity Checks” on page 13-12
“Run Dependency Analysis” on page 13-12
“Commit Modified Files” on page 13-15
“Upgrade Model Files to SLX and Preserve Revision History” on page 13-15
“View Source Control and Project Information” on page 13-21

Explore the Airframe Project
Try an example Simulink project to see how the tools can help you organize
your work. Projects can help you to manage:
• Your design (model and library files, .m, .mat, and other files, source code
for S-functions, data)
• A set of actions to use with your project (run setup code, open models,
simulate, build, run shutdown code).
• Working with files under source control (check out, compare revisions,
tag or label, and check in)
The Airframe example shows how to:
1 Set up and browse some example project files, under local revision control.
2 Examine project shortcuts to run setup and shutdown tasks, and access

frequently used files and tasks.

13-4

Try Simulink® Project Tools with the Airframe Project

3 Analyze dependencies in the example project and locate required files that

are not yet in the project.
4 Modify some project files, find and review modified files, compare to an

ancestor version, and commit modified files to source control.
5 Explore views of project files only, modified files, and all files under the

project root folder.
Follow the steps below to explore the example project.

Set Up the Project Files and Open the Simulink
Project Tool
Run this command to create a working copy of the project files and open the
project:
sldemo_slproject_airframe

The project example copies files to your temporary folder so that you can edit
them and put them under local revision control.
The Simulink Project Tool opens and loads the project. The project is
configured to run some startup tasks, including changing the current working
folder to the project root folder.

View, Search, and Sort Project Files
1 Click the Project Files view to manage the files within your project. Only

the files that are in your project are shown.
2 Click the All Files view to see all the files in your sandbox. This view shows

all the files that are under the project root, not just the files that are in the
project. This view is useful for adding files to the project that exist within
your sandbox, but which are not yet part of the project.
3 To find particular files or file types, in any file view, type in the search box

or click the Filter button next to the search box.

13-5

13

Managing Projects

Click the x to clear the search.
4 To view files as a list instead of a tree, click the List view button at the

top right.

5 To sort files and to customize the columns that you want to show, click the

"cog" icon Actions button at the far right of the search box.

13-6

Try Simulink® Project Tools with the Airframe Project

6 You can dock and undock the Simulink Project Tool into the MATLAB

Desktop. If you want to maximize space for viewing your project files,
undock the Simulink Project Tool.

Automate Project Startup and Shutdown Tasks
You can use shortcuts to automatically run startup or shutdown tasks, and to
easily find files within a large project.
1 Click the Shortcuts node to view the startup tasks and other shortcuts.
2 If you see a tree view, click the List view button at the top right of the

Simulink Project Tool to view the shortcuts as a list of files.

13-7

13

Managing Projects

In this example, you can see that:
• Some files are set as Run at Startup shortcuts. Startup shortcut
files automatically run (.m files), load (.mat files), and open (Simulink
models) when you open the project. You can use these shortcuts to set up
the environment for your project. The file set_up_project.m sets the
MATLAB path, and defines where to create the slprj folder. Open the
set_up_project.m file to view how it works. The following lines use the
project API to get the current project:
p = Simulink.ModelManagement.Project.CurrentProject;
projectRoot = p.getRootDirectory;

13-8

Try Simulink® Project Tools with the Airframe Project

• Another file is set as a Run at Shutdown shortcut. This type
of file runs before the current project closes. In this example, the
file clean_up_project.m resets the environment changes made by
set_up_project.m.
To create new startup or shutdown shortcuts, select the Project Files view,
right-click a file, and select Create Shortcut. Go to the Shortcuts view to set
an existing shortcut to Run at Startup or Run at Shutdown.

Open and Run Frequently Used Files
You can use shortcuts to make scripts easier to find in a large project. In this
example, the script that regenerates S-Functions is a shortcut so that a new
user of the project can easily find it. You can also make the top-level model, or
models, within a project easier to find. In this example, the top-level model,
slproject_f14.mdl, is a shortcut.
Use the example shortcuts:
1 Double-click the shortcut slproject_f14.mdl to open the root model

for this project. This model will not run until you compile a required
S-Function.
2 Right-click the shortcut rebuild_s_functions.m and select Run to

generate the S-Function. Open this file to view how it works.
Note This shortcut builds a MEX-file. If you do not have a compiler set
up, then first run the following command:
mex -setup

13-9

13

Managing Projects

3 To create new shortcuts, select the Project Files view, right-click a file,

and select Create Shortcut.

Review Changes in Modified Files
1 Open and make changes to one of the utility MATLAB files. You can

double-click to open files for editing from the Simulink Project, or right-click
and select Open. Make a change in the Editor and save the file.

13-10

Try Simulink® Project Tools with the Airframe Project

2 In the Simulink Project Tool, click the Modified Files node to see the files

that you have modified.
3 To review changes, right-click a file in the Modified Files view and select

Compare to Ancestor.

13-11

13

Managing Projects

The MATLAB Comparison Tool opens a report comparing the modified
version of the file in your sandbox against its ancestor stored in the version
control tool. Comparison type depends on the file you select. If you select a
Simulink model, and you have Simulink Report Generator installed, this
command runs a Simulink XML comparison.

Run Project Integrity Checks
In the Modified Files view, click Check Project to run the project integrity
checks to look for missing files, files that should be added to source control or
retrieved from source control, and other issues. The checks dialog can offer
automatic fixes to problems found. Click the Fix button to view recommended
actions and decide whether to make the changes.
Close the Project Integrity Checks dialog box.
For an example using the project checks to fix issues, see the later steps in
“Upgrade Model Files to SLX and Preserve Revision History” on page 13-15.

Run Dependency Analysis
Run a file dependency analysis on the modified files in your project, to check
that you have all the required files added to the project.
1 In the Modified Files view, click the Dependency Analysis button to

perform analysis on the modified files.
The Simulink Project Tool opens the Dependency Analysis view with your
modified files selected for analysis.

13-12

Try Simulink® Project Tools with the Airframe Project

2 Add all files to the analysis. Click the list of files, and then press Ctrl+A to

select all files. Right-click and select Include.
3 Click the Analyze button.
4 Review reported problem files. Observe that Problem files automatically

appears in the search box for filtering your file views.
5 Observe that the S-Function binary file, timesthree.mexw64, is required

by the project but is not currently part of it. Click the problem file to view
where it is used in the table below, in the Used By column.

13-13

13

Managing Projects

You might want to add binary files to your project or, as in this project,
provide a utility script that regenerates them from the source code that
is part of the project.
6 Right-click the problem file and select Add External File. You remove

the file from the problem files list, and the next time you run dependency
analysis, this file will not be marked as a problem file.
7 Click the Graph node to view the dependency graph of the project

structure. Try some right-click options to customize the graph.

13-14

Try Simulink® Project Tools with the Airframe Project

Commit Modified Files
1 Return to the Modified Files view, and click Check Project again to make

sure your changes are ready to commit. When you are satisfied with the
results of the checks, commit your modified files.
2 To commit your changes to source control, click the Commit Modified

Files button.

The Modified Files list includes a .SimulinkProject folder. The files
stored in the .SimulinkProject folder are internal project definition files
generated by your changes. These definition files allow you to add a label to
a file without checking it out. You should never need to view the definition
files directly unless you need to merge them, but they are shown so that
you know about all the files being committed to the source control system.
See “Project Definition Files” on page 13-91.
3 Enter a comment for your submission, and click Submit.

Upgrade Model Files to SLX and Preserve Revision
History
Simulink Projects help you upgrade model files from MDL format to SLX
format. You can use the Project Integrity checks to automatically add the new
SLX file to your project, remove the MDL file from the project, and preserve
the revision history of your MDL file with the new SLX file. You can then
commit your changes to source control and maintain the continuity of your
model file history.

13-15

13

Managing Projects

The following steps show how the project tools can help you migrate files to
SLX, using the Airframe example project. If you have not done the previous
example steps, you can run this command to open a new copy of the project:
sldemo_slproject_airframe
1 In the Project Files view, right-click the model file AnalogControl.mdl,

and select Open.
2 Select File > Save As.
3 Ensure that Save as type is SLX, and click Save. SLX is the default

unless you change your preferences.
4 Select the All Files view to see the results. Click the tree view

button and expand the models folder. Simulink saves your model in
SLX format, and creates a backup file by renaming the MDL file to
mymodel.mdl.releasename. The project also reports the original name
of the MDL file as missing.

5 To resolve these issues, click Check Project on the Simulink Project tab

to run the project integrity checks. The checks look for MDL files converted
to SLX, and offer automatic fixes if that check fails.
6 Click the Fix button to view recommended actions and decide whether

to make the changes.

13-16

Try Simulink® Project Tools with the Airframe Project

When you click Fix, the Missing Files dialog box offers to remove the
missing MDL file from the project and add the new SLX file to the project.
Click Yes to perform the fix.

Project checks rerun after you click Fix, in case there are remaining issues.

13-17

13

Managing Projects

Close the Project Integrity Checks dialog.
7 Select the Modified Files view. Expand the models folder and check the

Modifications column to see that the newly created SLX file has been added
to the project, and the original MDL file is scheduled for removal.

8 Click Commit Modified Files. Enter a comment for your submission in

the dialog, for example, Convert to SLX, and click Submit.
9 Select the All Files view to see that your backup file

AnalogControl.mdl.r2012b is still present, along with the new

SLX file.

13-18

Try Simulink® Project Tools with the Airframe Project

10 Select the Project Files view to see that only the new SLX file is now

included in the project, and the backup file is not included in the project.

13-19

13

Managing Projects

11 Right-click the model file AnalogControl.slx and select Show Revisions.

The File Revisions dialog box opens, and you can verify that the previous
revision is AnalogControl.mdl. The revision history of your previous
model file is preserved with the new SLX file.

13-20

Try Simulink® Project Tools with the Airframe Project

View Source Control and Project Information
1 Click the Source Control node to see information about the source control

tool being used by the current project. The Airframe example project is
under the control of the Local Version Control tool.

13-21

13

Managing Projects

For source control information on individual files (e.g., modified, checked
out), see the Modifications column in the Files views.
2 Click the root tree node Project: Simulink Project Airframe to see

information about the currently open project, including a description and
the location of the project root folder.

13-22

Create a New Simulink® Project

Create a New Simulink Project
In this section...
“Create a New Project to Manage Existing Files” on page 13-23
“Add Files to the Project” on page 13-26
“Create a New Project from an Archived Project” on page 13-28
“Open Recent Projects” on page 13-29
“Change the Project Name, Root, Description, and Startup Folder” on
page 13-30

Create a New Project to Manage Existing Files
If you already have files that you want to organize into a project, with or
without source control, use the following steps for a new project.
Note If you want to retrieve your project from a source control repository,
see instead “Retrieve a Working Copy of a Project from Source Control” on
page 13-76.
To create a new project to manage your files, either:
• From MATLAB, on the Home tab, in the File section, select
New > Simulink Project > Blank.
• From the Model Editor, select File > New > Simulink Project.
• From the Simulink Project Tool, on the Simulink Project tab, in the File
section, select New.
The Create Simulink Project dialog box appears.

13-23

13

Managing Projects

1 Enter the project name.
2 Select a project folder. The default is your current folder.
3 (Optional) Click Detect to check the project folder for source control

integration options. If your selected folder is under source control that the
project can recognize, the Source control integration field reports the
detected source control. You can change available source control tools here.
Note You can put the project under source control later by using the
Source Control node in the Project tree. See “Use Source Control with
Projects” on page 13-60.

13-24

Create a New Simulink® Project

The next example shows the project has detected SVN in the selected
project folder, and so the project selects Built-In SVN Integration.

4 (Optional) Change the template.

• Leave the default Blank Project template if you want to create a blank
project without any preconfigured structure or utilities. Use the blank
template if you are creating a project in a folder that already contains
files.
• Change the template if you want to create a project with some
preconfigured settings to guide you with setting up your project.
– Try the Project Environment template if you are creating a project
in a new folder and intend to add files later. Click Change next to
Template to open a dialog box and select the Project Environment

13-25

13

Managing Projects

template. You can view information about the template settings in
the description field. The Project Environment template can create
a new project with a preconfigured structure, and utilities to configure
the path and environment with startup and shutdown shortcuts. For
example, the path utilities help set up your search path to ensure
dependency analysis can detect project files. You can modify any of
these files, folders, and settings later.
– Similarly, try the Code Generation Example template to set up a
project with settings for production code generation of a plant and
controller. This template requires Simulink Coder and Embedded
Coder. See “Example Templates” on page 13-101.
–

If you create your own templates, you can select them in the Select a
Template dialog box. See “Use Templates to Create Standard Project
Settings” on page 13-97.

Note A warning tells you when your chosen template will overwrite any
files in the chosen location.
5 (Optional) Change project definition files.

Use multiple project files is better for avoiding merging issues on

shared projects.
Use a single project file is faster but is likely to cause merge issues
when multiple users submit changes in the same project to a source control
tool. See “Project Definition Files” on page 13-91.
6 Click Create to create your new project.

The Simulink Project Tool displays the empty Project Files list for your chosen
project root. Your project does not yet contain any files. You need to select
files to add. For next steps, see “Add Files to the Project” on page 13-26.

Add Files to the Project
The All Files node in the Project tree shows all files in your project folder.
Files under your chosen project root are not included in your project until you

13-26

Create a New Simulink® Project

add them. You might not want to include all files in your project. You can
add files to your project from the All Files view.
In the All Files view, select files or folders, right-click and select Add to
Project or Add to Project (including child files).

13-27

13

Managing Projects

To add and remove project files at the command line, see the
Simulink.ModelManagement.Project.CurrentProject reference page.
To help you set up your project with all required files, see “Choose Files and
Run Dependency Analysis” on page 13-33.
To configure your project to automatically run startup and shutdown tasks,
see “Automate Project Startup and Run Frequent Tasks” on page 13-52.

Create a New Project from an Archived Project
To create a new project from an archived project, either:
• From MATLAB, on the Home tab, in the File section, select
New > Simulink Project > From Archive.
• From the Simulink Project Tool, on the Simulink Project tab, select
New > New Project from Zip Archive

13-28

Create a New Simulink® Project

Open Recent Projects
Note You can have one project open. If you open another project, any
currently open project closes. Having multiple projects open could cause
conflicts.
To open recent projects:
• From MATLAB, on the Home tab, in the File section, select Open and
then select your project under the Recent Simulink Projects list.
From the Current Folder browser, you can open projects by double-clicking
your .prj file.
• From the Simulink Project Tool, on the Simulink Project tab, select a
recent project to open from the Open > Recent list.
Alternatively, to browse for a project from the Simulink Project Tool:

-

For projects created or saved in Release 2012b or later, select
Open > Open Project File. Browse and select your project .prj file,
and click OK to load the project.

-

For projects last saved in Release 2012a or earlier, select
Open > Open Project by Folder. Navigate to the folder containing
the .SimulinkProject folder, and click OK to load the project.
Subsequently, you can use Open Project File.

To open the Simulink Project Tool:
• From the MATLAB command line, enter:
simulinkproject

• From the Library Browser or Simulink Editor, select View > Simulink
Project.

13-29

13

Managing Projects

Tip Create a MATLAB shortcut for opening or giving focus to the Simulink
Project Tool by dragging this command to the toolstrip from the Command
History or Command Window:
simulinkproject

Change the Project Name, Root, Description, and
Startup Folder
Use the Project tree node if you want to edit the project name or add a
description. If you edit the name or description, click Apply to save your
changes.
You can view the project root folder, and click Set as Current Folder to
change the current working folder to your project root. You can change your
project root by moving your entire project on your file system, and reopening
your project in its new location. All project file paths are stored as relative
paths.
The check box option Change current folder to project root on start
up is selected by default. Clear the check box if you do not want to change
to the project root folder on startup.
You can also configure startup shortcut scripts that set the current folder
and perform other setup tasks. If you configure startup shortcuts to set the
current folder, your shortcut setting takes precedence over the check box at
the Project node. To set up shortcuts, see “Automate Project Startup and
Run Frequent Tasks” on page 13-52.

13-30

Create a New Simulink® Project

13-31

13

Managing Projects

Analyze Project Dependencies
In this section...
“What Is Dependency Analysis?” on page 13-32
“Choose Files and Run Dependency Analysis” on page 13-33
“Check Dependencies Results and Resolve Problems” on page 13-35
“Investigate Dependencies Graph” on page 13-38
“Options for Analyzing Model Dependencies” on page 13-43

What Is Dependency Analysis?
You can analyze project structure and discover files required by your project
with the Dependency Analysis view.
• You can use dependency analysis to help you set up your project with all
required files. For example, you can add a top-level model to your project,
analyze the model dependencies, and then add all dependent files to your
project.
• You can run dependency analysis at any point in your workflow when you
want to check that all required files are in the project. For example, you
can check dependencies again before submitting a version of your project
to source control.
• You can use the Graph view of your dependency analysis to analyze the
structure of your project visually. From the graph, you can examine your
project structure and perform file operations such as adding labels and
opening files.
Note You can analyze only files within your project. If your project is new,
you must add initial files to the project before running dependency analysis.
Click the All Files node under Management in the Project tree. Select the files
you want to analyze, right-click, and select Add to Project.

13-32

Analyze Project Dependencies

Choose Files and Run Dependency Analysis
1 In the Project tree, click Dependency Analysis.

Files in your project are shown in the list.
2 To specify which files to analyze, select the check boxes in the Include

column.
If you click the Dependency Analysis button in the Modified Files view, you
open the Dependency Analysis view with your modified files preselected.
To include or exclude all files, press Ctrl+A to select all files, then
right-click and select Include or Exclude.

13-33

13

Managing Projects

3 If desired, use the search box or Filter button to alter the list of files

displayed.
You see a message under the list if your filtering hides some of the files
selected for dependency analysis. To show all files selected for analysis,
click the button to the right of the search box to show only included files.

13-34

Analyze Project Dependencies

4 Click Analyze to discover required files.

The view changes to the Dependencies node to show your results in list
form.

Check Dependencies Results and Resolve Problems
If dependency analysis finds any problems, the Simulink Project Tool displays
the problem files. The search box shows that the list is filtered to show only
Problem files.

13-35

13

Managing Projects

The list reports dependent files that you should review because they are
required by the project but not currently in the project or missing.
1 Click each file in the Problem list to see where they are being used by other

files in the project, under Used By in the lower pane.

Note If you clear the search box, you can return to viewing only problem
files or external files by clicking the toolbar buttons to the right of the
search box.

13-36

Analyze Project Dependencies

2 In the dependencies table, check the Problem Description and Project

Status of dependent files, and if desired right-click to add any required files
that are not in the project. You can select multiple files. For example,
press Ctrl+A to select all files in the dependent files list, right-click, and
select Add to Project.
3 To open the referencing component for editing, right-click a file in the

Used By table and select Open Component. The referencing file opens.
MATLAB files open in the MATLAB Editor, and Simulink models open in
the Model Editor with the block highlighted.

4 If you want to remove files from the Problem list but not add them to

the project, you can right-click to select Add External File. The file
disappears from the Problem list. Next time you run dependency analysis,
this file will not appear in the Problem list. To view all external files, click
the Show only external files button to the right of the search box.
You might not want to add all required files to the project. For example,
you might want to exclude derived S-Function binary files that the source
code in your project can generate. See “Work with Derived Files in Projects”
on page 13-96.
Check the Status message and the Path for dependent files, where $
indicates the project root. Check if required files are outside your project
root—you cannot add such files to your project. This dependency might
not indicate a problem if the file is on your path and is a utility or other
resource that is not part of your project. Use dependency analysis to ensure
that you understand your design’s dependencies.

13-37

13

Managing Projects

5 If you decide the file needs to be part of your project, copy or move it within

the project root, add it the project and the path, and remember to remove
the original from the path.
6 Clear the search box to view all identified dependencies. Click files to view

where they are used. Also try the Graph view to investigate your project
dependencies graphically. See “Investigate Dependencies Graph” on page
13-38.

Investigate Dependencies Graph
To investigate dependencies visually, click Graph in the tree under
Dependency Analysis.
1 To highlight dependencies of selected files, right-click the graph canvas

and select Highlight Dependencies, and then click graph items to view
their highlighted dependencies. You can highlight upstream, downstream,
and circular dependencies.

13-38

Analyze Project Dependencies

2 Right-click the graph canvas to Filter by File Type, and select the file

types you want to display or hide.

13-39

13

Managing Projects

3 Right-click the graph canvas to highlight all graph items by file type and

reference type. The following example shows a project dependency graph
with many file types and reference types highlighted.

13-40

Analyze Project Dependencies

4 Right-click the graph canvas to Highlight by Labels, and select a category

of labels to use for highlighting. For example, you might want to see which
files have the label To Review. The following example shows highlighting
of custom labels to show Engine Type in the project.

13-41

13

Managing Projects

5 Right-click the graph canvas to try different graph layouts and change

zoom. You can also control zoom with a mouse wheel, or use the keyboard.
Press + and – to zoom in or out, press space to fit to view.
6 Right-click files in the graph to perform operations such as Open, Add

Label, or Remove from Project. You can also double-click to open a file.

You can perform file operations on multiple files. To select multiple files,
press Shift and drag the mouse to enclose the files. Hold down Ctrl to
multiselect and add to any existing selection. Press F to fit the view to
the currently selected files.
7 You can select Hide Self-Dependencies if you want a simpler view of

other graph items. For example, a library that contains multiple blocks
that use another block in the same library shows many self-references.

13-42

Analyze Project Dependencies

Self-referencing files do not introduce any new file dependencies, so you
can hide these self-dependencies if you want to simplify the graph. The
layout regenerates whenever you change the graph.
8 To save the graph as a .png image file, right-click and select Save As,

or select Copy to copy the image to your clipboard for pasting into other
documents.

Options for Analyzing Model Dependencies
You can use the Simulink Project Tool to analyze file dependencies for your
entire project. For detailed dependency analysis of a specific model, use the
manifest tools instead to control more options. Use the manifest tools if you
want to:
• Save the list of the model dependencies to a manifest file.
• Create a report to identify where dependencies arise.
• Control the scope of dependency analysis.
• Identify required toolboxes.
See “Analyze Model Dependencies” on page 13-104.

13-43

13

Managing Projects

Manage Project Files
In this section...
“Choose Views of Files to Manage” on page 13-44
“Group and Sort File Views” on page 13-45
“Search and Filter File Views” on page 13-46
“Work with Project Files” on page 13-47
“Back Out Changes” on page 13-49
“Label Files” on page 13-49

Choose Views of Files to Manage
Use the Project Files views to explore project files, interact with source
control, view modified or labeled files, and save tasks or shortcuts.
1 In the Project tree, use the nodes under Files to choose the view with the

files you want to manage:
• All Files — View all files within your project folder (or projectroot).
This list can be different from the list in the Project Files node. For
example, you might want to exclude some files under projectroot from
your project, such as SVN or CVS source control folders.
• Project Files — View only files added to your project. This list can be
different from the list of all files within your project folder.
• Shortcuts — View files you have specified as shortcuts for frequent
tasks, such as opening top-level models, running startup or shutdown
code and other tasks, or simulating models. You can set up shortcuts
to run when you open or close your project, or to run manually. The
Shortcuts node is blank until you create shortcuts from the All Files or
Project Files views. See “Automate Project Startup and Run Frequent
Tasks” on page 13-52.
• Modified Files — View only files with changes. This view is available
only if you are using a source control integration with your project. See
“Review Changes and Commit Modified Files” on page 13-89.

13-44

Manage Project Files

Note To access previous projects, see “Open Recent Projects” on page 13-29.

Group and Sort File Views
To group and sort the views in all Files nodes:
• Use the List view or Tree view buttons at top right to switch between a flat
list of files and a hierarchical tree of files.
In a list view, you can click the Hide Folders button if you want to view
only files.

• Click the Actions cog button at top right (next to the Tree view button) to
select the columns to show and select groupings, for example, to sort by
Review Status labels or any labels you have defined.

13-45

13

Managing Projects

Search and Filter File Views
Use the search box or Filter button to alter the list of files displayed. In all
the file views, and in batch job and dependency analysis nodes, you can use
the search box and filtering tools.
• Type a search term in the search box, for example, part of a file name, or a
file extension. You can use wildcards, such as *.m to find only MATLAB
files, or *.m* to find both MATLAB and model files.

Click the x to clear the search.
• Click the filter button to the right of the search box to build a filter for
the current view.

13-46

Manage Project Files

In the Filter Builder dialog box you can select multiple filter criteria to
apply using names, project status, and labels. Press Ctrl to multiselect
labels.
The dialog reports the resulting filter at the bottom, for example:
Filter = file name contains '.mdl' AND project status
is 'In project' AND has Label 'Engine Type:Diesel'

When you click OK, the search box shows the filter you are applying.

Click the x to clear the filter.

Work with Project Files
In all Files nodes, use the right-click menus to perform actions on the files
that you are viewing. Right-click a file (or selected multiple files) to perform
project options such as:
• Open or run files.
• Add and remove files from the project.
• Add, change and remove labels. See “Label Files” on page 13-49.
• Create entry point shortcuts (for example, code to run at startup or
shutdown, open models, simulate, or generate code). See “Automate Project
Startup and Run Frequent Tasks” on page 13-52.
• If a source control interface is enabled, you can also:

-

Refresh source control status.
Update from source control.
Check for modifications.

13-47

13

Managing Projects

-

Revert.
Compare against revision (select a version to compare)

See “Use Source Control with Projects” on page 13-60.

13-48

Manage Project Files

Back Out Changes
Use the Undo buttons to back out recent changes. Use the Undo or Redo
buttons and their drop-down list buttons to undo or redo recent actions in
the project. You can select multiple actions to undo. Hover over each action
to view details in a tooltip.

Label Files
Use labels to organize your files. The project automatically applies built-in
labels for file categories. You can create your own labels.
• In the Files views, right-click a file (or multiple selected files) to add or
remove labels. Once added to a file, a label persists across revisions of
the file.

13-49

13

Managing Projects

• In the Files views, you can organize lists by labels. Use the Actions button
(cog icon at top right) and select Sort By.
• Use the Labels tree node to create new label categories.

1 To add a new category of labels, right-click in the blank areas of the

Categories list and select Create New.
a In the dialog box, enter a name for the new category.
b If only one label of the category can be attached to a file at a time, then

select the check box Single Valued.

13-50

Manage Project Files

For example, if you want to create a category with labels for Prototype
and Release and want to apply only one of those labels to any specific
file, then select Single Valued to ensure only one label can be attached.
c If desired, change the Type selection to change the data type that can be

stored in the label, e.g., double, logical, integer, string, or none.
d Click Create to create your new category.
2 To add a new label in your new category, right-click in the blank areas of

the Labels list and select Create New.
a In the dialog box, enter a name for the new label.
b Click OK to create the label.
c Repeat to create more labels in your selected category.
3 To delete labels, right-click user-defined categories and labels and select

Remove. You cannot delete built-in labels.

To add labels at the command line, see the
Simulink.ModelManagement.Project.CurrentProject reference page.

13-51

13

Managing Projects

Automate Project Startup and Run Frequent Tasks
In this section...
“Create Shortcuts” on page 13-52
“Use Shortcuts to Find and Run Frequent Tasks” on page 13-53
“Automate Startup Tasks with Shortcuts” on page 13-54
“Automate Shutdown Tasks with Shortcuts” on page 13-57

Create Shortcuts
Use shortcuts for your common project tasks and to make it easy to find and
access important files and operations. For example, find and open top models,
run startup code (e.g., change the path or load data), simulate models, or run
shutdown code. The Shortcuts node is blank until you add shortcuts. You can
create shortcuts from the Files node, in the All Files or Project Files view.
1 To add a shortcut, right-click a file in the All Files or Project Files view

and select Create Shortcut.
2 After you add shortcuts, use the Shortcuts node to use, change, or remove

your shortcuts. You can specify Startup, Shutdown, or basic shortcuts.
• Startup shortcuts run when you open your project.
• Shutdown shortcuts run when you close your project.
• Run basic shortcuts manually by right-clicking.

13-52

Automate Project Startup and Run Frequent Tasks

Use Shortcuts to Find and Run Frequent Tasks
Use shortcuts to make it easy to find and access important files and
operations, for yourself and any other project users. You can use shortcuts
to make top models or scripts easier to find in a large project, so that a new
user of the project can easily find it.
Note Shortcuts are included when you commit your modified files to source
control, so you can share shortcuts with other project users.

13-53

13

Managing Projects

To use your shortcuts:
1 Click the Shortcuts node.

In the Shortcuts view, it can be useful to switch to List view. Click the
List view button at top right.
2 Right-click the shortcut file and select an action, e.g., Open or Run.

Automate Startup Tasks with Shortcuts
You can use startup shortcuts to set up the environment for your project.
To configure your shortcut to run when you open your project:

13-54

Automate Project Startup and Run Frequent Tasks

1 Click the Shortcuts node.
2 Right-click the shortcut file and select Set as Startup Shortcut.

The Action column displays Run at Start Up.
Startup shortcut files are automatically run (.m files), loaded (.mat files), and
opened (Simulink models) when you open the project.
Startup shortcut scripts can have any name. You do not need to use
startup.m.
Note Remember that files named startup.m on the MATLAB path run
when you start MATLAB. If your startup.m file calls the project with the
CurrentProject class, you might see an error because no project is loaded
yet. To avoid the error, rename the file and use it as a project startup shortcut
instead.
You can view an example in the sldemo_slproject_airframe project, where
the file set_up_project.m sets the MATLAB path, and defines where to
create the slprj folder.
You can change back to a basic shortcut by selecting Clear
Startup/Shutdown Action.

13-55

13

Managing Projects

Projects warn if you have more than one startup shortcut, because they run in
alphabetical order, which you might not want. If execution order is important,
consider creating another script that calls all the others, and use that script
as your only startup shortcut.

13-56

Automate Project Startup and Run Frequent Tasks

Note Be aware that shortcuts are included when you commit your modified
files to source control, so any startup shortcuts you create will also run for
any other project users.

Automate Shutdown Tasks with Shortcuts
To configure your shortcut to run when you close your project:
1 Click the Shortcuts node.
2 Right-click the shortcut file and select Set as Shutdown Shortcut.

The Action column displays Run at Shutdown.
You can use shutdown shortcuts to clean up the environment for the
current project when you close it. Shutdown shortcuts should undo the
settings applied in startup shortcuts. You can view an example in the
sldemo_slproject_airframe project.
You can change back to a basic shortcut by selecting Clear
Startup/Shutdown Action.
Note Be aware that shortcuts are included when you commit your modified
files to source control, so any shutdown shortcuts you create will also run
for any other project users.

13-57

13

Managing Projects

Run Batch Functions on Project Files
Select the Batch Job view to create and run functions on selected project files.
To create a batch function to use on your files:
1 Click Create.

The MATLAB Editor opens a new untitled file containing a simple example
batch job. The instructions guide you to create a batch job with the correct
function signature.
2 Edit the function to perform the desired action on each file.
3 Save the function file on your MATLAB path.

To use the batch job from the Simulink Project Tool:
1 In the Batch Job view, select the check boxes of project files you want to

include in the batch job. Only selected files are included in the batch job.
If the batch function can determine if a file it is given is appropriate, you
might want to include all files. The batch function operates only on the
appropriate subset of the included files. For example, the batch job function
saveModelFiles in the airframe project checks that the file is a Simulink
model, and does nothing if it is not. Include all files if you want your batch
function to check all files.
To select multiple files, Shift or Ctrl+click, and then right-click a file and
select Include or Exclude.
2 Click Browse to locate your batch job function file, or enter the name of

your batch function.
3 Click Run Batch Job.

The Simulink Project Tool displays the results in the Batch Job Results
column.

13-58

Run Batch Functions on Project Files

For example batch jobs, see Running Batch Jobs with a Simulink Project. This
example shows how to apply a batch job function to a set of files managed by a
Simulink Project. The example batch job function saveModelFiles identifies
and saves any loaded Simulink model files that contain unsaved changes. This
action can be useful to perform before committing changes to source control.
Open the example airframe project to view example batch job files
saveModelFiles and checkCodeProblems. See “Try Simulink Project Tools
with the Airframe Project” on page 13-4.

13-59

13

Managing Projects

Use Source Control with Projects
In this section...
“About Source Control with Projects” on page 13-60
“Add a Project to Source Control” on page 13-61
“View or Change Project Source Control” on page 13-68
“Register Model Files with Source Control Tools” on page 13-70
“Subversion Integration with Projects” on page 13-70
“Write a Source Control Adapter with the SDK” on page 13-75

About Source Control with Projects
You can use the Simulink Project Tool to work with source control.
Projects automatically recognize supported source control applications when
you create a new project in a folder under source control and click Detect.
Simulink projects contain interfaces to:
• Subversion® (SVN) — See “Subversion Integration with Projects” on page
13-70.
• A local version control tool — Project examples use the light-weight local
version control tool so you can try out source control operations after a
single command. The local version control tool is designed for a single
user for example purposes only. See “Try Simulink Project Tools with the
Airframe Project” on page 13-4.
You can add your project to source control to use the built-in SVN integration
that comes with Simulink projects.
When your project is under source control, you can use these project features:
• “Retrieve and Check Out Files Under Source Control” on page 13-76
• “Review Changes and Commit Modified Files” on page 13-89

13-60

Use Source Control with Projects

Add a Project to Source Control
Check your sandbox folder is on a local hard disk, not a network location.
Caution Using a network folder with SVN is slow and currently has known
bugs, e.g., http://subversion.tigris.org/issues/show_bug.cgi?id=3053. Instead,
use local sandbox folders.
To add source control to a newly created project or an existing one:
1 Select the Source Control node in the project tree.
2 Under Available Source Control Integrations, click Add project to

source control.

13-61

13

Managing Projects

3 On the Add to Source Control dialog box, leave the default Source control

integration selected to use Built-In SVN Integration.
4 Next to Repository path, click Change.

13-62

Use Source Control with Projects

5 On the Specify SVN Repository URL dialog box, either select an existing

repository or create a new one.

13-63

13

Managing Projects

• To specify an existing repository, click the Browse button to the right
of the Repository URL box, paste a URL into the box, or use the
drop-down list to select a recent repository.
• To create a new repository, click the Create button to the right of the
Repository URL box. A file browser opens. Create a new folder where
you want to create the new repository and click Select Folder. Do not
place the new repository inside the existing project folder.
Caution Create new repository is for single users only. See “Create
Subversion Repository” on page 13-74.
The Simulink Project Tool creates a repository in your folder and you
return to the Specify SVN Repository URL dialog box. The URL of your
new repository is specified in the Repository URL box, and the project
automatically selects the trunk folder.
6 Click Validate to check the path to your selected repository. If you have

problems, check the dialog messages for required path styles.

13-64

Use Source Control with Projects

Caution Use file:// URLs only for single user repositories. For more
information, see “Create Subversion Repository” on page 13-74.
When your path is valid, you can browse the repository folders. Select the
trunk folder if needed, and verify the selected URL at the bottom of the
dialog box. If you created a new repository, trunk is automatically selected.

7 Click OK to return to the Add to Source Control dialog box.
8 Click Convert to finish adding the project to source control.

13-65

13

Managing Projects

The project runs integrity checks.

13-66

Use Source Control with Projects

9 Click Open Project to return to your project.
10 If you created a new repository, you need to add your files to it. To commit

files to your new repository:
a Select the Modified Files view. All your project files should be in the

Modified Files list.
b Click Commit Modified Files to commit the first version of your

files to the new repository. A dialog box opens, where you can enter a
comment and click Submit.

13-67

13

Managing Projects

For more information about the default Built-In SVN Integration, see “Select
Subversion Source Control” on page 13-71.

View or Change Project Source Control
• “Viewing Source Control Type and Repository” on page 13-69
• “Adding, Changing, or Removing Source Control” on page 13-69
• “Tagging Files” on page 13-70

13-68

Use Source Control with Projects

Viewing Source Control Type and Repository
The Source Control node in the project tree shows details of the current source
control tool, the adapter interfacing to source control in your current project,
and the repository location.

Adding, Changing, or Removing Source Control
To add source control to a newly created project or an existing one, under
Available Source Control Integrations, select Add project to source
control. See “Add a Project to Source Control” on page 13-61.

13-69

13

Managing Projects

Use the same control to remove a project from source control by selecting No
source control integration and clicking Reload. For example, this action
might be useful when you are preparing a project to create a template from it,
and you want to avoid accidentally committing unwanted changes. You can
later select your previous source control from the list again.

Tagging Files
Use tags to identify specific revisions of all project files. In the Source Control
node, click the Tag button under Project Source Control Actions. Specify the
text for the tag. This action adds your tag to every project file.
Not every source control has the concept of tags. To use tags with SVN, you
need the standard folder structure in your repository and you need to check
out your files from trunk. See “Create Subversion Repository” on page 13-74

Register Model Files with Source Control Tools
If you use third-party source control tools, be sure to register your model file
extensions (.mdl and .slx) as binary formats. If you do not, these third-party
tools might corrupt your model files when you submit them, by changing
end-of-line characters, expanding tokens, keyword substitution, or attempting
to automerge. Corruption can occur whether you use the source control tools
outside of Simulink or if you try submitting files from the Simulink Project
Tool without first registering your file formats.
You should also check that other file extensions are registered as binary to
avoid corruption at check-in for files such as .mat, .xlsx, .jpg, .pdf, .docx,
etc.
For instructions, see “Register Model Files with Subversion” on page 13-73

Subversion Integration with Projects
• “Select Subversion Source Control” on page 13-71
• “Built-In SVN Integration” on page 13-71
• “Command-Line SVN Integration (Compatibility Mode)” on page 13-72
• “Register Model Files with Subversion” on page 13-73

13-70

Use Source Control with Projects

• “Create Subversion Repository” on page 13-74

Select Subversion Source Control
To use SVN in your project, you can use any of the following workflows:
• Create a new project in a folder already under SVN source control and
click Detect. See “Create a New Project to Manage Existing Files” on
page 13-23.
• Add source control to a project. See “Add a Project to Source Control” on
page 13-61.
• Retrieve files from an existing SVN repository and create a new project. See
“Retrieve a Working Copy of a Project from Source Control” on page 13-76.
When you add to source control or retrieve from source control, you can
optionally change the SVN integration in the Source control integration
list.
SVN Version You Want to Use

SVN Integration to Select

SVN version 1.7 or below
(no installation steps required)

“Built-In SVN Integration” on page
13-71

Other SVN version
(requires additional installation
steps)

“Command-Line SVN Integration
(Compatibility Mode)” on page 13-72

Note Also, you can check for updated
downloads on the Simulink Projects Web page:
http://www.mathworks.com/products/simulink/simulink-projects/

Built-In SVN Integration
Select the Built-In SVN Integration for use with SVN sandboxes and
repositories at version 1.7 and below.
You do not need to install SVN to use this integration because Built-In SVN
Integration includes an implementation of SVN. This integration ignores

13-71

13

Managing Projects

any existing SVN installation. If you need support for a later version of
SVN, then select Command-Line SVN Integration (compatibility mode)
instead.
The Built-In SVN Integration supports secure logins and moving @ folders.

Command-Line SVN Integration (Compatibility Mode)
Note Select Command-Line SVN Integration (compatibility mode) only
if you need to use a later version of SVN than 1.7. Otherwise, use Built-In
SVN Integration instead, for more features, improved performance, and no
need to install an additional command-line SVN client.
If you select Command-Line SVN Integration (compatibility mode), you
must also install a command-line SVN client.
Command-line SVN integration communicates with any Subversion (SVN)
client that supports the command-line interface. Install an SVN client that
supports the command-line interface, and then you can use this integration
with the Simulink Project Tool.
TortoiseSVN does not support the command-line interface. However, you can
continue to use TortoiseSVN from Windows Explorer after installing another
SVN client that supports the command-line interface. Ensure that the major
version numbers match, e.g., both clients should be SVN 1.7.
You can find Subversion clients on this Web page:
http://subversion.apache.org/packages.html

.
If you try to rename a file in a project under SVN source control, and the
folder name contains an @ character, you see an error because command-line
SVN treats all characters after the @ symbol to be a peg revision value.

13-72

Use Source Control with Projects

Register Model Files with Subversion
If you do not register your model file extension as binary, Subversion may add
annotations to conflicted Simulink files and attempt automerge. This corrupts
model files so you cannot load the models in Simulink.
To avoid this problem when using Subversion, follow these steps to register
your file extensions:
1 Locate your SVN config file, e.g.:

C:\Users\myusername\AppData\Roaming\Subversion\config,
or C:\Documents and Settings\username\Application
Data\Subversion\config on Windows, or in ~/.subversion on Linux or
Mac OS X.
2 Add the following lines to the end of the config file, and SVN will no longer

add annotations to Simulink files on conflict, and will never attempt an
automerge.
*.mdl = svn:mime-type= application/octet-stream
*.mat = svn:mime-type=application/octet-stream
*.slx = svn:mime-type= application/octet-stream

13-73

13

Managing Projects

Create Subversion Repository
You can create an SVN repository when adding a project to source control.
See “Add a Project to Source Control” on page 13-61.
Caution Creating new repositories is provided for local single-user access
only, for testing and debugging. Do not use for multiple users or you risk
corrupting the repository.
When you use Simulink Projects to create a repository, you create a repository
using the file:// protocol. Subversion documentation strongly recommends
only single users access a repository directly via file:// URLs. See the Web
page:

http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.choosing.recomme

It is not recommended to allow multiple users to access a repository directly
via file:// URLs. You risk corrupting the repository. Use file:// URLs
only for single user repositories.
When you want to share a repository, you need to set up a server. You can use
svnserve or the Apache™ SVN module. See the Web page references:
http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.svnserve
http://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.httpd

On Windows, search the Web for Subversion servers that you can set up in
a few clicks.
To enable tagging within projects when using SVN, create your repository
with the standard tags, trunk, and branch folders, and check out your files
from trunk. This structure is recommended by the Subversion project. See
the Web page:
http://svn.apache.org/repos/asf/subversion/trunk/doc/user/svn-best-practices.html

.
You can create an SVN repository with the standard structure from the
project, and the project automatically selects the trunk folder.

13-74

Use Source Control with Projects

After you create a repository with this structure, you can use the Tag button
in the Project Source Control node to add tags to all your project files. Tag
errors if you do not create a tags folder in your repository.

Write a Source Control Adapter with the SDK
Simulink provides a Software Development Kit (SDK) that you can use to
integrate Simulink Projects with third-party source control tools.
The SDK provides instructions for writing an adapter to a source control tool
that has a published API that can be called from Java™.
You must create a .jar file which implements a collection of Java interfaces
and a Java Manifest file, which defines a set of required properties.
The SDK also provides example source code, Javadoc, and files for validating,
building, and testing your source control adapter. Build and test your own
interfaces using the example as a guide, then you can use your source control
adapter with Simulink Projects.
1 To extract the contents of the SDK, enter:

run(fullfile(matlabroot,'toolbox','simulink','simulink','slproject',...
'adapterSDK','extractSDK'))

Select a folder to place the cm_adapter_SDK folder and files inside, and
click OK.
2 Locate the new folder cm_adapter_SDK, and open the file

cm_adapter_SDK_guide.pdf for instructions.

13-75

13

Managing Projects

Retrieve and Check Out Files Under Source Control
In this section...
“Retrieve a Working Copy of a Project from Source Control” on page 13-76
“Refresh Status of Project Files” on page 13-81
“Update Revisions of Project Files” on page 13-84
“Check Out Files” on page 13-86

Retrieve a Working Copy of a Project from Source
Control
To create or update a new local copy of a project by retrieving files from source
control:
1 From MATLAB, on the Home tab, in the File section, select

New > Simulink Project > From Source Control.
Alternatively, from the Simulink Project Tool, on the Simulink Project
tab, select Source Control.
The Source Control dialog box appears.

13-76

Retrieve and Check Out Files Under Source Control

2 (Optional) Select your source control interface from the Source Control

Adapters drop-down list.
Leave the default Built-In SVN Integration to use the default SVN
integration with your project. For more information on SVN support, see
“Select Subversion Source Control” on page 13-71.
3 Click Change to select the Repository Path that you want to retrieve files

from.
The Specify Repository URL dialog box opens.

13-77

13

Managing Projects

a Click the Generate URL from folder button to the right of the

Repository URL box to browse for your repository location.

Select the folder containing your repository and click OK.
The retriever generates a URL for you in the Repository URL field.
Alternatively, manually enter or paste the Repository URL.
b Click Validate to check the repository path.

If the path is invalid, check the URL against your source control
repository browser.
Caution Use file:// URLs only for single user repositories. For more
information, see “Create Subversion Repository” on page 13-74.
c If necessary, select a deeper folder in the repository tree. The example

shows trunk selected, and the Selected URL displays at the bottom of
the dialog box.

13-78

Retrieve and Check Out Files Under Source Control

The retriever uses the Selected URL when you click OK.

d Click OK to continue and return to the Project Retriever.
4 Click Browse to select the sandbox folder where you want to put the

retrieved files for your new project.
Caution Using a network folder with SVN is slow and currently has
known bugs e.g., http://subversion.tigris.org/issues/show_bug.cgi?id=3053.
Instead, use local sandbox folders.

13-79

13

Managing Projects

5 Click Retrieve.
6 Watch the Built-In SVN Integration pane for messages as the project

retrieves your files from source control.
If you are retrieving files to update an existing project, your project opens.
7 If you are retrieving files to a new sandbox, a dialog appears to report that

the files in the repository have been checked out to your selected sandbox
folder, and to check whether you want to create a project in the folder.
Click Yes to continue creating the project. Click No to leave the files on
disk and return to the retriever.
8 When you click Yes, the new project controls appear.
a Enter a project name.

13-80

Retrieve and Check Out Files Under Source Control

b Click Detect to identify the source control in the project folder.
c Click Create to finish creating the new project in your new sandbox.

The Simulink Project Tool displays the empty Project Files list for your chosen
project root. Your project does not yet contain any files. You need to select
files to add. For next steps, see “Add Files to the Project” on page 13-26.

Refresh Status of Project Files
To check the status of individual files, right-click files in any view to select
Refresh. This action queries the local sandbox state and checks for changes
made with another tool. For SVN, Refresh does not contact the repository.

13-81

13

Managing Projects

To check source control status of all project files, click the Refresh button in
the source control pane at bottom left. The source control pane title depends

13-82

Retrieve and Check Out Files Under Source Control

on your source control, for example, Built-In SVN Integration. The source
control pane reports source control messages, and the buttons in the pane
apply to the whole project.

13-83

13

Managing Projects

Refresh refreshes the view of the source control status for all files under
projectroot. When you click Refresh, this updates the information shown
in the Revision column and the source control status column (e.g., SVN or
Modifications column). Hover over the Modifications row to see the tooltip
showing the source control status of a file, e.g., Modified (Checked Out).
For SVN repositories that require login, you can click Clear login
information to clear your login information.

Update Revisions of Project Files
To get the latest revisions of all project files from the source control repository,
click the Update button in the source control pane. The source control pane
title depends on your source control, for example, Built-In SVN Integration.

13-84

Retrieve and Check Out Files Under Source Control

13-85

13

Managing Projects

To update selected files, right-click and select Update from Built-In SVN
Integration Repository to get fresh local copies of the selected file from
the repository.

Check Out Files
To check out files,
1 In any Files view, click to select a file, or press Shift+click to select

multiple files.
2 Right-click the selected files and select Checkout from Source Control.

The menu wording for Source Control is specific to your selected source
control, e.g., for SVN, Checkout from Built-In SVN Integration
Repository.

13-86

Retrieve and Check Out Files Under Source Control

13-87

13

Managing Projects

Note With SVN, use Checkout from Built-In SVN Integration
Repository to get a lock on a file. This option does not modify the file in
your local sandbox.
To get a fresh local copy of the file from the repository, select Update from
Built-In SVN Integration Repository.
For next steps, see “Review Changes and Commit Modified Files” on page
13-89.

13-88

Review Changes and Commit Modified Files

Review Changes and Commit Modified Files
In this section...
“View Modified Files” on page 13-89
“Review Changes” on page 13-91
“Precommit Actions” on page 13-93
“Commit Modified Files” on page 13-94
“Revert Local Changes and Release Locks” on page 13-94
“Resolve Conflicts” on page 13-95
“Work with Derived Files in Projects” on page 13-96

View Modified Files
The Modified Files node is visible only if you are using source control
integration with your project.
Use the Modified Files node to review, analyze, label, and commit modified
files. Lists of modified files are sometimes called changesets. The Modified
Files node aids the reviewing process.
In the Modified Files view, it can be useful to switch to List view. Use the List
view or Tree view buttons at top right.

As in the other Files nodes, in the Modified Files view you can right-click files
or multiple selected files to:
• Add and remove labels.
• Update from source control.

13-89

13

Managing Projects

• Uncheckout from source control.
• Commit to repository.
• Refresh source control status.
• Compare against selected revision or ancestor.

13-90

Review Changes and Commit Modified Files

Project Definition Files
The files in .SimulinkProject are project definition files generated by your
changes. The project definition files allow you to create shortcuts and add
labels to files without checking them out, and add other metadata such as a
project description. Project definition files also define which files are added to
your project.
Any changes you make to your project (e.g., to shortcuts, labels, categories,
or files in the project) generate changes in the .SimulinkProject folder.
These files store the definition of your project in XML files whose format
is subject to change.
You should never need to view project definition files directly, except when
the source control tool requires a merge. The files are shown so that you
know about all the files being committed to the source control system. See
“Resolve Conflicts” on page 13-95.

Review Changes
To review changes in modified files, right-click selected files to view revision
logs and compare against another revision or ancestor.
• Select Show Revisions to open the File Revisions dialog box and browse
the history of a file. In the table, you can view SVN information about
who previously committed the file, when they committed it, and the log
messages.
• Select Compare to Revision to open a dialog where you can select the
revision you want to compare. You can select multiple files and select a
revision to compare against for each file. When you click Compare, your
comparisons run and the Comparison Tool displays reports.
• Select Compare to Ancestor to run a comparison with the last checked
out version in the sandbox. The Comparison Tool displays a report.

13-91

13

Managing Projects

When reviewing changes, you can merge Simulink models from the
Comparison Tool report (requires Simulink Report Generator).

13-92

Review Changes and Commit Modified Files

Precommit Actions
The Precommit actions pane in the Modified Files view contains tools you
might want to use before committing your changes to source control.

• Click the Check Project button to check the integrity of the project. For
example, is everything under source control in the project? Are all project
files under source control? A dialog box reports results. You can click for
details and follow prompts to fix problems, e.g., if you would like to add
files to your repository.
For an example showing how the checks can help you, see “Upgrade Model
Files to SLX and Preserve Revision History” on page 13-15.
This function is also in the Simulink Project tab (Check Project) so you
can run the checks from any project view.
For more information on some problems the checks can fix, see “Work with
Derived Files in Projects” on page 13-96.
• If you want to check for required files, click the Dependency Analysis
button to open the Dependency Analysis view, with your modified files
selected for analysis. You can optionally change the check box selections
before clicking Analyze. You can use the dependency tools to analyze the
structure of your project. See “Analyze Project Dependencies” on page
13-32.
• If you want to add the label To Review to all files in your changeset, click
the Label for Review button.

13-93

13

Managing Projects

Note The files in .SimulinkProject are project definition files generated
by your changes, and these files are not labeled. See “Project Definition
Files” on page 13-91.

Commit Modified Files
To commit your changes to source control:
1 Click the Commit Modified Files button to check in all files in the

modified files list.

2 A dialog prompts you to enter comments for your submission.
3 Click Submit or Cancel.

Revert Local Changes and Release Locks
If you want to roll back local changes, right-click a file and select Uncheckout
from Built-In SVN Integration Repository to release locks and revert to
the version in the last sandbox update (e.g., the last version you synchronized
or retrieved from the repository).
Select Revert using Built-In SVN Integration Repository to choose a
revision to revert to.

13-94

Review Changes and Commit Modified Files

Resolve Conflicts
If two people both change the same file in different sandboxes, you get a
conflict message when you try to commit your modified files. You can also
get conflicts in your project definition files. For example, if two people both
change the labels attached to a file, you can get a conflict in one of the project
definition files in the .SimulinkProject folder.
To resolve conflict problems:
1 Look for conflicted files in the Modified Files view.
2 It can be useful to switch to List view. Click List view at the top right.
3 Check the source control status column (e.g., the SVN or Modifications

column) for files with a red icon. The tooltip shows Conflicted.

4 Examine the conflict. You might want to select Compare to Ancestor

to run a comparison with the last checked out version in the sandbox, or
Compare to Revision to select revisions for comparison.
In the Comparison Tool, examine the report to see how the files have
changed.
5 Resolve the conflict. In the Comparison Tool report, you can merge changes

between revisions (requires Simulink Report Generator). For example, you
can merge project file labels and shortcuts.
You might want to open files from the project to make changes and resolve
the conflict. If you need to change labels manually, see “Label Files” on
page 13-49, or to change the project description, see the Project node.
6 When you are satisfied that you have resolved the changes and want to

commit the version in your sandbox, right-click the file and select Mark
Conflict Resolved. You can now commit your file.

13-95

13

Managing Projects

Work with Derived Files in Projects
You might not want to include derived and temporary files in your project or
commit them to source control. Use Check Project in the Precommit Actions
pane or the Simulink Project tab to check the integrity of the project. If you
add the slprj folder to a project, the project checks advise you to remove this
from the project and offer to make the fix. The checks recommend a best
practice of not adding derived and temporary files to source control.
You might not want to commit derived files, such as .mex*, the contents of the
slprj folder, sccprj folder, or other code generation folders, because they
can cause problems. For example:
• With a source control that can do file locking, users can encounter conflicts.
If slprj is under source control and a user generates code, this changes
most of the files under slprj and locks those files. Other users then cannot
generate code because they get file permission errors. The slprj folder is
also used for simulation via code generation (e.g., with model reference or
Stateflow), so locking these files can have a big impact on a team. The
same problems arise with binaries, such as .mex*.
• Deleting slprj is quite commonly required. However, deleting slprj
causes problems such as “not a working copy” errors if the folder is under
some source control tools (e.g., SVN).
• If you want to check in the generated code as an artifact of the process,
then it is common to copy some of the files out of the slprj cache folder and
into a separate location that is part of the project. That way the temporary
cache folder can be deleted whenever required. See the packNGo function to
discover the list of generated code files, and use the project API to add to
the project with appropriate metadata.
• The slprj folder can contain a large number of small files. This can have
a performance impact with some source control tools when each of those
files has to be checked to see if it is up-to-date.

13-96

Use Templates to Create Standard Project Settings

Use Templates to Create Standard Project Settings
In this section...
“Use Templates for Standard Project Setup” on page 13-97
“Create a Template from Your Current Project” on page 13-97
“View and Validate Templates” on page 13-99
“Create a New Project Using a Template” on page 13-100
“Import New Templates” on page 13-100
“Example Templates” on page 13-101

Use Templates for Standard Project Setup
You can use templates to create and reuse a standard project structure. You
can use templates to make consistent projects across teams. You could use
templates to create new projects that:
• Use a standard folder structure.
• Set up a company standard environment, for example, with company
libraries on the path.
• Have access to tools such as company Model Advisor checks.
• Use company standard startup and shutdown scripts.
• Share labels and categories.
When your existing project is in a state that others would find useful, or
you want to reuse, then you can create a template from it and use it when
creating new projects.

Create a Template from Your Current Project
You can create a template from an existing project, and then use the template
to create new projects.
To create a template from your current project, on the Simulink Project tab,
in the Template section, select Create.

13-97

13

Managing Projects

To use the template when creating new projects, you must put the template
on the template path. If the folder where you create the new template is
not already on the template path, you can add folders to the path later in
the Template Manager.
When you create a new template, it contains the structure and all the contents
of the current project, so that you can reuse scripts and other files for your
standard project setup. Before creating the template, create and edit a new
copy of the project to contain only the files you want to reuse.
To create a template from an existing project that is under version control:
1 Get a new working copy of the project. See “Retrieve a Working Copy of a

Project from Source Control” on page 13-76.
2 To avoid accidentally committing changes to your project that you have

made only to create the template, you might want to stop using source
control with this sandbox. In the Source Control view, click Select an
available source control integration and select None to remove this
sandbox from source control.
3 Remove the files that you do not want in the template. For example, you

might want to reuse o