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
.
Page Count: 2839
| Download | |
| Open PDF In Browser | View 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 only the utility functions, startup and shutdown
scripts, and labels. In the Project Files view, right-click unwanted files
and select Remove from Project.
4 On the Simulink Project tab, in the Template section, click Create.
5 To verify that your template behaves as you expect, create a new empty
project that uses your new template.
To make changes to an existing template:
1 Create a new empty project using the template you want to modify.
2 Make the desired changes to the project.
3 On the Simulink Project tab, in the Template section, click Create.
Either create a new template, or overwrite the existing template.
13-98
Use Templates to Create Standard Project Settings
View and Validate Templates
Use the Template Manager to view a default template, or locate and validate
template files. On the Simulink Project tab, in the Template section,
click Manager.
Click the templates in the Templates pane to view the Description.
For example, the Project Environment template shows you how to specify
options to:
• Set up and reset the folders on the path when you open or close the project.
13-99
13
Managing Projects
• Define the location of the folder (slprj) for generated code and other
temporary files.
• Run standard scripts at startup and shutdown.
• Include information in a template about names, authors, and description.
See also “Example Templates” on page 13-101.
In the Template Manager you can:
• Validate that a template is usable to create new projects.
• Add folders to the template path to make templates visible in the New
Project dialog Templates list.
• Specify which templates to make visible in the Templates list.
Create a New Project Using a Template
To try using the Project Environment template, select it when creating a
new project.
Use the Templates list to select a template during project creation. Only
templates on the template path appear in the dialog.
Note If you create a project in a folder that already contains files, you are
warned if there are any collisions with the template. The template will
overwrite the existing files if you choose to continue.
Import New Templates
You can use templates to share information and best practices. New templates
can be created by you, your colleagues, or downloaded from MATLAB Central:
http://www.mathworks.com/matlabcentral/
.
You need to import a new template to make it available for use in new projects.
13-100
Use Templates to Create Standard Project Settings
1 On the Simulink Project tab, in the Template section, click Manager.
2 Click Import.
3 Browse to the zip file that contains the new template.
4 Select a location on the template path to save the new template. Click
Import to validate the template and import it. If validation fails, then it
will not be imported.
Example Templates
Project Environment Template
Try the Project Environment template if you are creating a project in a
new folder and intend to add files later. You can view information about
the template settings in the description field of the Template Manager. 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. To try the template,
select the Project Environment template when creating a new project.
The utilities set_up_project.m, clean_up_project.m and project_paths.m
configure the path and settings when you open and close the project. The
startup shortcut changes current folder to the project root. The utilities set
the folder (slprj) where generated code and other temporary files are created
for the current project, and reset that folder to the default location when
the project is closed. Shortcuts provide quick access to frequently required
models and tasks.
Code Generation Example Template
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. To try the template, select
the Code Generation Example template when creating a new project.
The utilities set_up_project.m, clean_up_project.m and project_paths.m
configure the path and settings when you open and close the project, as
13-101
13
Managing Projects
in the Project Environment template. These utilities set the folder (slprj)
where generated code and other temporary files are created for the current
project, and reset that folder to the default location when the project is closed.
The startup shortcut also changes the current folder to the project root.
Other shortcuts define the controller parameters as a tunable structure in
the generated code. Shortcuts provide quick access to frequently required
models and tasks.
The settings of the model feedback_control are changed to be suitable
for production code generation. Settings are changed as the Model Advisor
recommends in the checks for both By Product > Embedded Coder and By
Task > Code Efficiency, including:
• System Target File is set to ert.tlc.
• Code Generation reporting is enabled.
• The following diagnostics are set:
-
Bus Signals Treated As Vectors, Connectivity pane, set to Error.
Model Initialisation, Underspecified initialization detection set
to Simplified
• The following optimizations are enabled:
-
All Data Initialisation Optimizations
-
Inline parameters, Inline Invariant Signals
Saturation maths operations for floating point to integer conversion
(and vice versa)
After you create the project, open the model feedback_harness to examine
the controller and plant models.
Right-click to run the project shortcut generate_controller_code.m to
generate code for the controller and display a code generation report.
13-102
Archive Projects in Zip Files
Archive Projects in Zip Files
To package and share project files, you can export all project files to a zip file.
For example, you can share a zipped project with people who do not have
access to the connected source control tool.
1 On the Simulink Project tab, select Archive. A file browser opens.
2 (Optional) Edit the zip file name and change the destination folder. By
default, the file myprojectname.zip is created in the current working
folder.
3 Click Save.
The archive command exports a complete project.
To create a new project from an archived project, on the Simulink Project
tab, select New > New Project from Zip Archive.
Locate the archive zip file to extract.
13-103
13
Managing Projects
Analyze Model Dependencies
In this section...
“What Are Model Dependencies?” on page 13-104
“Generate Manifests” on page 13-105
“Command-Line Dependency Analysis” on page 13-112
“Edit Manifests” on page 13-114
“Compare Manifests” on page 13-117
“Export Files in a Manifest” on page 13-118
“Scope of Dependency Analysis” on page 13-120
“Best Practices for Dependency Analysis” on page 13-123
“Use the Model Manifest Report” on page 13-124
What Are Model Dependencies?
Each Simulink model requires a set of files to run successfully. These
files can include referenced models, data files, S-functions, and other files
without which the model cannot run. These required files are called model
dependencies.
Dependency Analysis
Requirements
Tools to Choose
Find required files for an entire
project
Use dependency analysis from the
Simulink Project Tool. See “Analyze
Project Dependencies” on page 13-32.
Detailed dependency analysis of a
specific model with control of more
options
Use the manifest tools from your
model. See “Generate Manifests” on
page 13-105. Generate a manifest if
you want to:
• Save the list of the model
dependencies to a manifest file.
• Create a report to identify where
dependencies arise.
13-104
Analyze Model Dependencies
Dependency Analysis
Requirements
Tools to Choose
• Control the scope of dependency
analysis.
• Identify required toolboxes.
After you generate a manifest for a model to determine its dependencies,
you can:
• View the files required by your model in a manifest file.
• Trace dependencies using the report to understand why a particular file
or toolbox is required by a model.
• Package the model with its required files into a zip file to send to another
Simulink user.
• Compare older and newer manifests for the same model.
• Save a specific version of the model and its required files in a revision
control system.
You can also view the libraries and models referenced by your model
in a graphical format using the Model Dependency Viewer. See “Model
Dependency Viewer” on page 9-83.
Generate Manifests
Generating a manifest performs the dependency analysis and saves the list of
model dependencies to a manifest file. You must generate the manifest before
using any of the other Simulink Manifest Tools.
Note The model dependencies identified in a manifest depend upon the
Analysis Scope options you specify. For example, performing an analysis
without selecting Find Library Links might not find all the Simulink
blocksets that your model requires, because they are often included in a model
as library links. See “Manifest Analysis Scope Options” on page 13-109.
13-105
13
Managing Projects
To generate a manifest:
1 Select Analysis > Model Dependencies > Generate Manifest.
The Generate Model Manifest dialog box appears.
13-106
Analyze Model Dependencies
2 Click OK to generate a manifest and report using the default settings.
Alternatively you can first change the following settings:
13-107
13
Managing Projects
• Select the Analysis scope check boxes to specify the type of
dependencies you want to detect (see “Manifest Analysis Scope Options”
on page 13-109).
• Control whether to report file dependency locations by selecting Report
file dependency locations for:
– User files only (default) — only report locations where
dependencies are upon user files. Use this option if you want to
understand the interdependencies of your own code and do not care
about the locations of dependencies on MathWorks products. This
option speeds up report creation and streamlines the report.
– All files — report all locations where dependencies are introduced,
including all dependencies on MathWorks products. This is the
slowest option and the most verbose report. Use this option if you need
to trace all dependencies to understand why a particular file or toolbox
is required by a model. If you need to analyze many references, it can
be helpful to sort the results by clicking the report column headers.
– None — do not report any dependency locations. This is the fastest
option and the most streamlined report. Use this option if you want
to discover and package required files and do not require all the
information about file references.
• If desired, change the Project Root Location. Select one of the
check box options: Folder containing root model file (the default),
Common root folder of required files, or User-defined location —
for this option, enter a path in the edit box, or browse to a location.
• If desired, edit the Manifest file name and location in which to save
the file.
• Use the check box View HTML report on completion to
specify if you want to generate a report when you generate the
manifest. You can edit the Report file name or leave the default,
mymodelname_manifest_report.html. You can set the Report style to
Plain HTML or HTML with Hyperlinks.
When you click OK Simulink generates a manifest file containing a list of the
model dependencies. If you selected View HTML report on completion,
the Model Manifest Report appears after Simulink generates the manifest.
See “Use the Model Manifest Report” on page 13-124 for an example.
13-108
Analyze Model Dependencies
The manifest is an XML file with the extension .smf located (by default) in
the same folder as the model itself.
Manifest Analysis Scope Options
The Simulink Manifest Tools allow you to specify the scope of analysis when
generating the manifest. The dependencies identified by the analysis depend
upon the scope you specify.
The following table describes the Analysis Scope options.
Check Box Option
Description
Find orphaned base
workspace data (performs
a Model Update)
Searches for base workspace variables the
model requires, that are not defined in any
file in this Manifest.
If Model Update fails you see an error
message. Either clear this analysis option
to generate a manifest without a Model
Update, or try a manual Model Update
to find out more about the problem. For
example your model may require variables
that are not present in the workspace (e.g.,
if a block parameter defines a variable that
you forgot to load manually).
Find and analyze model
references
Searches for Model blocks in the model,
and identifies any referenced models as
dependencies.
Find and analyze linked
libraries
Searches for links to library blocks in the
model, and identifies any library links as
dependencies.
Allow models with
unsaved changes to be
analyzed
Select this check box only if you want to
allow analysis of unsaved changes.
Click the >> button on the right to show the following advanced analysis
options.
13-109
13
Managing Projects
13-110
Check Box Option
Description
Find S-functions
Searches for S-Function blocks in the model,
and identifies S-function files (MATLAB
code and C) as dependencies. See the source
code item in “Special Cases” on page 13-122.
Analyze model and block
callbacks (including
Interpreted MATLAB
Function blocks)
Searches for file dependencies introduced
by the code in Interpreted MATLAB
Function blocks, block callbacks, and model
callbacks. For more detail on how callbacks
are analyzed, see “Code Analysis” on page
13-121.
Find files required for
code generation
Searches for file dependencies introduced
by Simulink Coder custom code, and
Embedded Coder templates. If you do not
have a code generation product, this check
is off by default, and produces a warning if
you select it.
This includes analysis of all configuration
sets (not just the Active set) and
STF_make_rtw_hook functions, and locates
system target files and Code Replacement
Library definition files (.m or .mat). See
also “Required Toolboxes” on page 13-126,
and the source code item in “Special Cases”
on page 13-122.
Find data files (e.g. in
“From File” blocks)
Searches for explicitly referenced data files,
such as those in From File blocks, and
identifies those files as dependencies. See
“Special Cases” on page 13-122.
Analyze Stateflow charts
Searches for file dependencies introduced
through the use of syntax such as
ml.mymean(myvariable) in models that
use Stateflow.
Analyze Model Dependencies
Check Box Option
Description
Analyze code in MATLAB
Functions blocks
Searches for MATLAB Function blocks
in the model, and identifies any file
dependencies (outside toolboxes) introduced
in the code. Toolbox dependencies
introduced by a MATLAB Function block
are not detected.
Find requirements
documents
Searches for requirements documents
linked using the Requirements
Management Interface. Note that
requirements links created with Telelogic®
DOORS software are not included in
manifests. For more information, see
“Links Between Models and Requirements”
in the Simulink Verification and Validation
documentation.This option is disabled if
you do not have a Simulink Verification and
Validation license, and Simulink ignores
any requirements links in your model.
Analyze files in “user
toolboxes”
Searches for file dependencies introduced
by files in user-defined toolboxes. See
“Special Cases” on page 13-122.
Analyze MATLAB files
Searches for file dependencies introduced
by MATLAB files called from the model.
For example, if this option is selected and
you have a callback to mycallback.m, then
the referenced file mycallback.m is also
analyzed for further dependencies. See
“Code Analysis” on page 13-121.
Store MATLAB code
analysis warnings in
manifest
Saves any warnings in the manifest.
See also “Scope of Dependency Analysis” on page 13-120 for more information.
13-111
13
Managing Projects
Command-Line Dependency Analysis
• “Check File Dependencies” on page 13-112
• “Check Toolbox Dependencies” on page 13-112
Check File Dependencies
To programmatically check for file dependencies, use the function
dependencies.fileDependencyAnalysis as follows.
[files, missing, depfile, manifestfile] =
dependencies.fileDependencyAnalysis('modelname', 'manifestfile')
This returns the following:
• files — a cell array of strings containing the full-paths of all existing files
referenced by the model modelname.
• missing — a cell array of strings containing the names all files that are
referenced by the model modelname, but cannot be found.
• depfile — returns the full path of the user dependencies (.smd) file, if it
exists, that stores the names of any files you manually added or excluded.
Simulink uses the .smd file to remember your changes the next time you
generate a manifest. See “Edit Manifests” on page 13-114.
• manifestfile — (optional input) specify the name of the manifest file to
create. Note that the suffix .smf is always added to the user-specified name.
If you specify the optional input, manifestfile, then the command
creates a manifest file with the specified name and path manifestfile.
manifestfile can be a full-path or just a file name (in which case the
file is created in the current folder).
If you try this analysis on an example model, it returns an empty list of
required files because the standard MathWorks installation includes all the
files required for the example models.
Check Toolbox Dependencies
To check which toolboxes are required, use the function
dependencies.toolboxDependencyAnalysis as follows:
13-112
Analyze Model Dependencies
[names,dirs] = dependencies.toolboxDependencyAnalysis(files_in)
files_in must be a cell array of strings containing .m or model files on the
MATLAB path. Simulink model names (without file extension) are also
allowed.
This returns the following:
• names — a cell-array of toolbox names required by the files in files_in.
• dirs — a cell-array of the toolbox folders.
Note The method toolboxDependencyAnalysis looks for toolbox
dependencies of the files in files_in but does not analyze any subsequent
dependencies.
If you want to find all detectable toolbox dependencies of your model and
the files it depends on:
1 Call fileDependencyAnalysis on your model.
For example:
[files, missing, depfile, manifestfile] = dependencies.fileDependencyAnalysis('mymodel')
files =
'C:\Work\manifest\foo.m'
'C:\Work\manifest\mymodel'
missing =
[]
depfile =
[]
manifestfile =
[]
2 Call toolboxDependencyAnalysis on the files output of step 1.
For example:
13-113
13
Managing Projects
tbxes = dependencies.toolboxDependencyAnalysis(files)
tbxes =
[1x24 char]
'MATLAB'
'Simulink Coder'
'Simulink'
To view long product names examine the tbxes cell array as follows:
tbxes{:}
ans =
Image Processing Toolbox
ans =
MATLAB
ans =
Simulink Coder
ans =
Simulink
For command line dependency analysis, the analysis uses the default settings
for analysis scope to determine required toolboxes. For example, if you have
code generation products, then the check Find files required for code
generation is on by default and Simulink Coder is always reported as
required. See “Required Toolboxes” on page 13-126 for more examples of
how your installed products and analysis scope settings can affect reported
toolbox requirements.
Edit Manifests
After you generate a manifest, you can view the list of files identified as
dependencies, and manually add or delete files from the list.
To edit the list of required files in a manifest:
1 Select Analysis > Model Dependencies > Edit Manifest Contents.
13-114
Analyze Model Dependencies
Alternatively, if you are viewing a manifest report you can click Edit in
the top Actions box, or you can click View and Edit Manifest in the
Export Manifest dialog box.
The View and Edit Manifest dialog box appears, showing the latest
manifest for the current model.
13-115
13
Managing Projects
Note You can open a different manifest by clicking the Browse for
. If you have not generated a manifest, select
manifest file button
Generate Manifest to open the Generate Model Manifest dialog box (see
“Generate Manifests” on page 13-105).
2 Examine the Files to be exported list on the left side of the dialog box.
This list shows the files identified as dependencies.
3 To add a file to the manifest:
a Click Add Files.
The Add Files to Manifest dialog box opens.
b Select the file you want to add, then click Open.
The selected file is added to the Files to be exported list.
4 To remove a file from the manifest:
a Select the file you want to remove from the Files to be exported list.
b Click the Exclude selected files button
.
The selected file is moved to the Excluded files list.
Note If you add a file to the manifest and then exclude it, that file is
removed from the dialog (it is not added to the Excluded files list).
Only files detected by the Simulink Manifest Tools are included in the
Excluded files list.
5 If desired, change the Project Root Location.
6 Click Save to save your changes to the manifest file.
Simulink saves the manifest (.smf) file, and creates a user dependencies
(.smd) file that stores the names of any files you manually added or
13-116
Analyze Model Dependencies
excluded. Simulink uses the .smd file to remember your changes the
next time you generate a manifest, so you do not need to repeat manual
editing. For example, you might want to exclude source code or include a
copyright document every time you generate a manifest for exporting to
a customer. The user dependencies (.smd) file has the same name and
folder as the model. By default, the user dependencies (.smd) file is also
included in the manifest.
Note If the user dependencies (.smd) file is read-only, a warning is
displayed when you save the manifest.
7 To view the Model Manifest Report for the updated manifest, click Show
Report.
An updated Model Manifest Report appears, listing the required files and
toolboxes, and details of references to other files. See “Use the Model
Manifest Report” on page 13-124 for an example.
8 When you are finished editing the manifest, click OK.
Compare Manifests
You can compare two manifests to see how the list of model dependencies
differs between two models, or between two versions of the same model. You
can also compare a manifest with a folder or a ZIP file.
To compare manifests:
1 From the Current Folder browser, right-click a manifest file and select
Compare Against > Choose.
Alternatively, from your model, select Analysis > Model
Dependencies > Compare Manifests.
The dialog box Select Files or Folders for Comparison appears.
2 In the dialog box Select Files or Folders for Comparison, select files to
compare, and the comparison type.
a Use the drop-down lists or browse to select manifest files to compare.
13-117
13
Managing Projects
b Select the Comparison type. For two manifests you can select:
• Simulink manifest comparison — Select for a manifest file list
comparison reporting new, removed and changed files. The report
contains links to open files and compare files that differ. You can
use a similar file List comparison for comparing a manifest to a
folder or a ZIP file.
• Simulink manifest comparison (printable) — Select for a
printable Model Manifest Differences Report without links. The report
provides details about each manifest file, and lists the differences
between the files.
3 View the report in the Comparison Tool comparing the file names, dates,
and sizes stored in the manifests.
Be aware the details stored in the manifest may differ from the files on
disk. If you click a “compare” link in the report, you see warnings if there
are problems such as size mismatches, or if the tool cannot find those files
on disk.
For more information on the Comparison Tool, see “Comparing Files and
Folders” in the MATLAB Desktop Tools and Development Environment
documentation.
Export Files in a Manifest
You can export copies of the files listed in the manifest to a ZIP file. Exporting
the files allows you to package the model with its required files into a single
ZIP file, so you can easily send it to another user or save it in a revision
control system.
To export your model with its required files:
1 Select Analysis > Model Dependencies > Export Files in Manifest.
Alternatively, if you are viewing a manifest report you can click Export in
the top Actions box.
The Export Files in Manifest dialog box appears, showing the latest
manifest for the current model.
13-118
Analyze Model Dependencies
Note You can export a different manifest by clicking the Browse for
manifest file button
. If you have not generated a manifest, select
Generate Manifest to open the Generate Model Manifest dialog box (see
“Generate Manifests” on page 13-105).
2 If you want to view or edit the manifest before exporting it, click View
and Edit Manifest to view or change the list of required files. See “Edit
Manifests” on page 13-114. When you close the View and Edit Manifest
dialog box, you return to the Export Files in Manifest dialog box.
3 Click Validate to check the manifest. Validation reports information
about possible problems such as missing files, warnings, and orphaned
base workspace data.
13-119
13
Managing Projects
4 Enter the ZIP file name to which you want to export the model.
5 Select Preserve folder hierarchy when exporting if you want to keep
folder structure for your exported model and files. Then, select the root
folder to use for this structure (usually the same as the Project Root
Location on the Generate Manifest dialog box).
Note You must select Preserve folder hierarchy if you are exporting a
model that uses an .m file inside a MATLAB class (to maintain the folder
structure of the class), or if the model refers to files in other folders (to
ensure the exported files maintain the same relative paths).
6 Click OK.
The model and its file dependencies are exported to the specified ZIP file.
Scope of Dependency Analysis
The Simulink Manifest Tools identify required files and list them in an XML
file called a manifest. When Simulink generates a manifest file, it performs
a static analysis on your model, which means that the model does not need
to be capable of performing an “update diagram” operation (see “Update a
Block Diagram” on page 1-25). The only exception to this is when you select
the analysis option Find orphaned base workspace data (performs a
Model Update).
You can specify the type of dependencies you want to detect when you
generate the manifest. See “Manifest Analysis Scope Options” on page 13-109.
For more information on what the tool analyzes, refer to the following sections:
• “Analysis Limitations” on page 13-121
• “Code Analysis” on page 13-121
• “Special Cases” on page 13-122
13-120
Analyze Model Dependencies
Analysis Limitations
The analysis might not find all files required by your model (for examples,
see “Code Analysis” on page 13-121).
The analysis might not report certain blocksets or toolboxes required by a
model. You should be aware of this limitation when sending a model to
another user. Blocksets that do not introduce dependence on any files (such
as Simulink Fixed Point™) cannot be detected. Some SimEvents blocks do
not introduce a detectable dependence on SimEvents.
To include dependencies that the analysis cannot detect, you can add
additional file dependencies to a manifest file using the View/Edit Manifest
Contents option (see “Edit Manifests” on page 13-114).
Code Analysis
When the Simulink Manifest Tools encounter MATLAB code, for example in
a model or block callback, or in a .m file S-function, they attempt to identify
the files it references. If those files contain MATLAB code, and the analysis
scope option Analyze MATLAB files is selected, the referenced files are also
analyzed. This function is similar to depfun but with some enhancements:
• Files that are in MathWorks toolboxes are not analyzed.
• Strings passed into calls to eval, evalc, and evalin are analyzed.
• File names passed to load, fopen, xlsread, importdata, dlmread,
wk1read, and imread are identified.
File names passed to load, etc., are identified only if they are literal strings.
For example:
load('mydatafile')
load mydatafile
The following example, and anything more complicated, is not identified as a
file dependency:
str = 'mydatafile';
load(str);
Similarly, arguments to eval, etc., are analyzed only if they are literal strings.
13-121
13
Managing Projects
The Simulink Manifest Tools look inside MAT-files to find the names of
variables to be loaded. This enables them to distinguish reliably between
variable names and function names in block callbacks.
If a model depends upon a file for which both .m and .p files exist, then the
manifest reports both, and, if the Analyze MATLAB files option is selected,
the .m file is analyzed.
Special Cases
The following list contains additional information about specific cases:
• If your model references a user-defined MATLAB class created using the
Data Class Designer, for example called MyPackage.MyClass, all files
inside the folder MyPackage and its subfolders are added to the manifest.
Warning The analysis adds all files in the class, which includes
any source control files such as .svn or .cvs. You may want to edit
the manifest to remove these files.
• A user-defined toolbox must have a properly configured Contents.m file.
The Simulink Manifest Tools search user-defined toolboxes as follows:
-
If you have a Contents.m file in folder X, any file inside a subfolder of X
is considered part of your toolbox.
-
If you have a Contents.m file in folder X/X, any file inside all subfolders
of the “outer” folder X will be considered part of your toolbox.
For more information on the format of a Contents.m file, see ver.
• If your S-functions require TLC files, these are detected.
• If you have Simscape, your Simscape components are analyzed. See also
“Required Toolboxes” on page 13-126 for other effects of your installed
products on manifests.
• If you create a UI using GUIDE and add this to a model callback, then the
dependency analysis detects the .m and .fig file dependencies.
• If you have a dependence on source code, such as .c, .h files, these files are
not analyzed at all to find any files that they depend upon. For example,
subsequent #include calls inside .h files are not detected. To make such
files detectable, you can add them as dependent files to the "header file"
13-122
Analyze Model Dependencies
section of the Custom Code pane of the Simulink Coder section of the
Configuration Parameters dialog box (or specify them with rtwmakecfg).
Alternatively, to include dependencies that the analysis cannot detect, you
can add additional file dependencies to a manifest file using the View/Edit
Manifest Contents option (see “Edit Manifests” on page 13-114).
• Various blocksets and toolboxes can introduce a dependence on a file
through their additional source blocks. If the analysis scope option Find
data files (e.g. in “From File” blocks) is selected, the analysis detects
file dependencies introduced by the following blocks:
Product
Blocks
DSP System Toolbox
From Wave File (Obsolete) block
(Microsoft Windows operating
system only)
From Multimedia File block
(Windows only)
Computer Vision System Toolbox™
Image From File block
Read Binary File block
Simulink 3D Animation™
VR Sink block
The option Find data files also detects dependencies introduced by setting
a "Model Workspace" for a model to either MAT-File or MATLAB Code.
Best Practices for Dependency Analysis
The starting point for dependency analysis is the model itself. Make sure
that the model refers to any data files it needs, even if you would normally
load these manually. For example, add code to the model’s PreLoadFcn to
load them automatically, e.g.,
load mydatafile
load('my_other_data_file.mat')
This way, the Simulink Manifest Tools can add them to the manifest. For
more detail on callback analysis, see the notes on code analysis (see “Code
Analysis” on page 13-121).
13-123
13
Managing Projects
More generally, ensure that the model creates or loads any variables it uses,
either in model callbacks or in scripts called from model callbacks. This
reduces the possibility of the Simulink Manifest Tools confusing variable
names with function names when analyzing block callbacks.
If you plan to export the manifest after creating it, ensure that the model does
not refer to any files by their absolute paths, for example:
load C:\mymodel\mydata\mydatafile.mat
Absolute paths can become invalid when you export the model to another
machine. If referring to files in other folders, do it by relative path, for
example:
load mydata\mydatafile.mat
Select Preserve folder hierarchy when exporting, so that the exported files
are in the same locations relative to each other. Also, choose a root folder so
that all the files listed in the manifest are inside it. Otherwise, any files
outside the root are copied into a new folder called external underneath the
root, and relative paths to those files become invalid.
If you are exporting a model that uses a .m file inside a MATLAB class (in a
folder called @myclass, for example), you must select the Preserve folder
hierarchy check box when exporting, to maintain the folder structure of
the class.
Always test exported ZIP files by extracting the contents to a new location on
your computer and testing the model. Be aware that in some cases required
files may be on your path but not in the ZIP file, if your path contains
references to folders other than MathWorks toolboxes.
Use the Model Manifest Report
• “Report Sections” on page 13-125
• “Required Toolboxes” on page 13-126
• “Example Model Manifest Report” on page 13-126
13-124
Analyze Model Dependencies
Report Sections
If you selected View HTML report on completion in the Generate Model
Manifest dialog box, the Model Manifest Report appears after Simulink
generates the manifest. The report shows:
• Analysis date
• Actions panel — Provides links to conveniently regenerate, edit or
compare the manifest, and export the files in the manifest to a ZIP file.
• Model Reference and Library Link Hierarchy — Links you can click
to open models.
• Files used by this model — Required files, with paths relative to the
projectroot.
You can sort the results by clicking the report column headers.
• Toolboxes required by this model. For details see “Required Toolboxes”
on page 13-126.
• References in this model — This section provides details of references to
other files so you can identify where dependencies arise. You control the
scope of this section with the Report file dependency locations options
on the Generate Manifest dialog box. You can choose to include references
to user files only, all files or no files. See “Generate Manifests” on page
13-105. Use this section of the report to trace dependencies to understand
why a particular file or toolbox is required by a model. If you need to
analyze many references, it can be helpful to sort the results by clicking
the report column headers.
• Folders referenced by this model
• Orphaned base workspace variables — If you selected the analysis
option Find orphaned base workspace data, this section reports any
base workspace variables the model requires that are not defined in a file
in this manifest.
• Warnings generated while analyzing MATLAB code — You can
opt out of this section by clearing the Store MATLAB code analysis
warnings in manifest analysis option.
• Dependency analysis settings — Records the details of the analysis
scope options.
13-125
13
Managing Projects
See the examples shown in “Example Model Manifest Report” on page 13-126.
Required Toolboxes
In the report, the “Toolboxes required by this model” section lists all products
required by the model that the analysis can detect. Be aware that the analysis
might not report certain blocksets or toolboxes required by a model, e.g.,
blocksets that do not introduce dependence on any files (such as Simulink
Fixed Point) cannot be detected. Some MathWorks files under toolbox/shared
can report only requiring MATLAB instead of their associated toolbox.
The results reported can be affected by your analysis scope settings and your
installed products. For example:
• If you have code generation products and select the scope option “Find
files required for code generation”, then:
-
Simulink Coder software is always reported as required.
If you also have an .ert system target file selected then Embedded
Coder software is always reported as required.
• If you clear the Find library links option, then the analysis cannot find
a dependence on, for example, someBlockSet, and so no dependence is
reported upon the block set.
• If you clear the Analyze MATLAB files option, then the analysis cannot
find a dependence upon fuzzy.m, and so no dependence is reported upon
the Fuzzy Logic Toolbox™.
Example Model Manifest Report
You should always check the Dependency analysis settings section in the
Model Manifest Report to see the scope of analysis settings used to generate it.
Following are portions of a sample report.
13-126
Analyze Model Dependencies
13-127
13
Managing Projects
13-128
Analyze Model Dependencies
13-129
13
Managing Projects
13-130
Simulating Dynamic Systems
• Chapter 14, “Running Simulations”
• Chapter 15, “Running a Simulation Programmatically”
• Chapter 16, “Visualizing and Comparing Simulation Results”
• Chapter 17, “Inspecting and Comparing Logged Signal Data”
• Chapter 18, “Analyzing Simulation Results”
• Chapter 19, “Improving Simulation Performance and Accuracy”
• Chapter 20, “Performance Advisor”
• Chapter 21, “Simulink Debugger”
• Chapter 22, “Accelerating Models”
14
Running Simulations
• “Simulation Basics” on page 14-2
• “Control Execution of a Simulation” on page 14-3
• “Specify Simulation Start and Stop Time” on page 14-8
• “Choose a Solver” on page 14-9
• “Interact with a Running Simulation” on page 14-31
• “Save and Restore Simulation State as SimState” on page 14-32
• “Diagnose Simulation Errors” on page 14-39
14
Running Simulations
Simulation Basics
You can simulate a model at any time simply by clicking the Run button on
the Model Editor displaying the model. See “Start a Simulation” on page 14-3.
However, before starting the simulation, you might want to specify various
simulation options, such as the simulation’s start and stop time and the type
of solver used to solve the model at each simulation time step.
With Simulink software, you can create multiple model configurations,
called configuration sets, modify existing configuration sets, and switch
configuration sets with a click of a mouse button (see “Manage a Configuration
Set” on page 10-12 for information on creating and selecting configuration
sets).
Once you have defined or selected a model configuration set that meets your
needs, you can start the simulation. The simulation runs from the specified
start time to the specified stop time. While the simulation is running, you can
interact with the simulation in various ways, stop or pause the simulation
(see “Pause or Stop a Simulation” on page 14-5), and launch simulations of
other models.
If an error occurs during a simulation, Simulink halts the simulation and
the Simulation Diagnostics Viewer pops up that helps you to determine the
cause of the error.
14-2
Control Execution of a Simulation
Control Execution of a Simulation
In this section...
“Start a Simulation” on page 14-3
“Pause or Stop a Simulation” on page 14-5
“Use Blocks to Stop or Pause a Simulation” on page 14-5
Start a Simulation
This sections explains how to run a simulation interactively using this model.
See “Run Simulation Using the sim Command” on page 15-3 and “Control
Simulation using the set_param Command” on page 15-7 for information
on running a simulation from a program, an S-function, or the MATLAB
command line.
To start the execution of a model, from the Simulation menu of the Model
Editor, select Run or click the Run button on the model toolbar.
Run button
14-3
14
Running Simulations
Note A common mistake is to start a simulation while the Simulink block
library is the active window. Make sure that your model window is the active
window before starting a simulation.
The model execution begins at the start time that you specify on the
Configuration Parameters dialog box. Execution continues until an error
occurs, until you pause or terminate the simulation, or until the simulation
reaches the stop time as specified on the Configuration Parameters dialog box.
While the simulation is running, a progress bar at the bottom of the model
window shows how far the simulation has progressed. A Pause command
replaces the Run command on the Simulation menu. A Pause command
appears on the menu and replaces the Run button on the model toolbar.
Stop button
Pause button
Time
Your computer beeps to signal the completion of the simulation.
14-4
Control Execution of a Simulation
Pause or Stop a Simulation
Select the Pause command or button to pause the simulation. Once Simulink
completes the execution of the current time step, it suspends the simulation.
When you select Pause, the menu item and the button change to Continue.
(The button has the same appearance as the Run button). You can resume a
suspended simulation at the next time step by choosing Continue.
To terminate execution of the model, select the Stop button or the Stop
Simulation menu item. Simulink completes the execution of the current time
step and then terminates the simulation. Subsequently selecting the Run
menu item or button restarts the simulation at the first time step specified on
the Configuration Parameters dialog box.
If the model includes any blocks that write output to a file or to the workspace,
or if you select output options on the Configuration Parameters dialog box,
the Simulink software writes the data when the simulation is terminated
or suspended.
Use Blocks to Stop or Pause a Simulation
Using Stop Blocks
You can use the Stop Simulation block to terminate a simulation when the
input to the block is nonzero. To use the Stop Simulation block:
1 Drag a copy of the Stop Simulation block from the Sinks library and drop it
into your model.
2 Connect the Stop Simulation block to a signal whose value becomes nonzero
at the specified stop time.
For example, this model stops the simulation when the input signal reaches
10.
14-5
14
Running Simulations
If the block input is a vector, any nonzero element causes the simulation
to terminate.
Creating Pause Blocks
You can use an Assertion block to pause the simulation when the input signal
to the block is zero. To create a pause block:
1 Drag a copy of the Assertion block from the Model Verification library and
drop it into your model.
2 Connect the Assertion block to a signal whose value becomes zero at the
desired pause time.
3 Open the Block Parameters dialog box of the Assertion block .
• Enter the following commands into the Simulation callback when
assertion fails field:
set_param(bdroot,'SimulationCommand','pause'),
disp(sprintf('\nSimulation paused.'))
• Uncheck the Stop simulation when assertion fails option.
4 Click OK to apply the changes and close this dialog box.
The following model uses a similarly configured Assertion block, in
conjunction with the Relational Operator block, to pause the simulation when
the simulation time reaches 5.
14-6
Control Execution of a Simulation
When the simulation pauses, the Assertion block displays the following
message at the MATLAB command line.
Simulation paused
Warning: Assertion detected in 'assertion_as_pause/
Assertion Used to Pause Simulation' at time 5.000000
You can resume the suspended simulation by choosing Continue from the
Simulation menu on the model editor, or by selecting the Continue button
in the toolbar.
Note The Assertion block uses the set_param command to pause the
simulation. See “Control Simulation using the set_param Command” on page
15-7 for more information on using the set_param command to control the
execution of a Simulink model.
14-7
14
Running Simulations
Specify Simulation Start and Stop Time
By default, simulations start at 0.0 s and end at 10.0 s.
Note In the Simulink software, time and all related parameters (such as
sample times) are implicitly in seconds. If you choose to use a different time
unit, you must scale all parameters accordingly.
The Solver configuration pane allows you to specify other start and stop times
for the currently selected simulation configuration. See “Solver Pane” for more
information. On computers running the Microsoft Windows operating system,
you can also specify the simulation stop time in the Simulation menu.
Note Simulation time and actual clock time are not the same. For example,
if running a simulation for 10 s usually does not take 10 s as measured on a
clock. The amount of time it actually takes to run a simulation depends on
many factors including the complexity of the model, the step sizes, and the
computer speed.
14-8
Choose a Solver
Choose a Solver
In this section...
“What Is a Solver?” on page 14-9
“Choosing a Solver Type” on page 14-10
“Choosing a Fixed-Step Solver” on page 14-13
“Choosing a Variable-Step Solver” on page 14-17
“Choosing a Jacobian Method for an Implicit Solver” on page 14-24
What Is a Solver?
A solver is a component of the Simulink software. The Simulink product
provides an extensive library of solvers, each of which determines the time
of the next simulation step and applies a numerical method to solve the set
of ordinary differential equations that represent the model. In the process
of solving this initial value problem, the solver also satisfies the accuracy
requirements that you specify. To help you choose the solver best suited for
your application, “Choosing a Solver Type” on page 14-10 provides background
on the different types of solvers while “Choosing a Fixed-Step Solver” on page
14-13 and “Choosing a Variable-Step Solver” on page 14-17 provide guidance
on choosing a specific fixed-step or variable-step solver, respectively.
The following table summarizes the types of solvers in the Simulink library
and provides links to specific categories. All of these solvers can work with
the algebraic loop solver.
Discrete
Fixed-Step
Continuous
Variable-Order
Explicit Not Applicable
“Explicit Fixed-Step
Continuous Solvers”
on page 14-14
Not Applicable
Implicit Not Applicable
“Implicit Fixed-Step
Continuous Solvers”
on page 14-16
Not Applicable
14-9
14
Running Simulations
Discrete
Variable-Step Explicit “Choosing a
Variable-Step Solver”
on page 14-17
Implicit
Continuous
Variable-Order
“Explicit Continuous
Variable-Step Solvers”
on page 14-18
“Variable-Order
Solvers” on page 14-13
“Implicit Continuous
Variable-Step Solvers”
on page 14-19
“Variable-Order
Solvers” on page 14-13
Note
1 The fixed-step discrete solvers do not solve for discrete states; each
block calculates its discrete states independent of the solver. For more
information, see “Discrete versus Continuous Solvers” on page 14-12
2 Every solver in the Simulink library can perform on models that contain
algebraic loops.
For information on tailoring the selected solver to your model, see “Improve
Simulation Accuracy” on page 19-11.
Choosing a Solver Type
The Simulink library of solvers is divided into two major types in the “Solver
Pane”: fixed-step and variable-step. You can further divide the solvers
within each of these categories as: discrete or continuous, explicit or implicit,
one-step or multistep, and single-order or variable-order.
Fixed-Step versus Variable-Step Solvers
Both fixed-step and variable-step solvers compute the next simulation time
as the sum of the current simulation time and a quantity known as the step
size. With a fixed-step solver, the step size remains constant throughout
the simulation. In contrast, with a variable-step solver, the step size can
vary from step to step, depending on the model dynamics. In particular,
a variable-step solver increases or reduces the step size to meet the error
14-10
Choose a Solver
tolerances that you specify. The Type control on the Simulink Solver
configuration pane allows you to select either of these two types of solvers.
The choice between the two types depends on how you plan to deploy your
model and the model dynamics. If you plan to generate code from your model
and run the code on a real-time computer system, choose a fixed-step solver
to simulate the model because you cannot map the variable-step size to the
real-time clock.
If you do not plan to deploy your model as generated code, the choice between
a variable-step and a fixed-step solver depends on the dynamics of your
model. A variable-step solver might shorten the simulation time of your model
significantly. A variable-step solver allows this savings because, for a given
level of accuracy, the solver can dynamically adjust the step size as necessary
and thus reduce the number of steps. Whereas the fixed-step solver must
use a single step size throughout the simulation based upon the accuracy
requirements. To satisfy these requirements throughout the simulation, the
fixed-step solver might require a very small step.
The following model shows how a variable-step solver can shorten simulation
time for a multirate discrete model.
This model generates outputs at two different rates: every 0.5 s and every
0.75 s. To capture both outputs, the fixed-step solver must take a time step
every 0.25 s (the fundamental sample time for the model).
[0.0 0.25 0.5 0.75 1.0 1.25 1.5 ...]
By contrast, the variable-step solver needs to take a step only when the model
generates an output.
14-11
14
Running Simulations
[0.0 0.5 0.75 1.0 1.5 ...]
This scheme significantly reduces the number of time steps required to
simulate the model.
If you wish to achieve evenly spaced steps, you must use the format 0.4*[0.0:
100.0] rather than [0.0:0.4:40].
Discrete versus Continuous Solvers
When you set the Type control of the Solver configuration pane to
fixed-step or to variable-step, the adjacent Solver control allows you to
choose a specific solver. Both sets of solvers comprise two types: discrete
and continuous. Discrete and continuous solvers rely on the model blocks
to compute the values of any discrete states. Blocks that define discrete
states are responsible for computing the values of those states at each time
step. However, unlike discrete solvers, continuous solvers use numerical
integration to compute the continuous states that the blocks define .
Therefore, when choosing a solver, you must first determine whether you
need to use a discrete solver or a continuous solver.
If your model has no continuous states, then Simulink switches to either the
fixed-step discrete solver or the variable-step discrete solver. If instead your
model has continuous states, you must choose a continuous solver from the
remaining solver choices based on the dynamics of your model. Otherwise,
an error occurs.
Explicit versus Implicit Solvers
While you can apply either an implicit or explicit continuous solver, the
implicit solvers are designed specifically for solving stiff problems whereas
explicit solvers are used to solve nonstiff problems. A generally accepted
definition of a stiff system is a system that has extremely different time scales.
Compared to the explicit solvers, the implicit solvers provide greater stability
for oscillatory behavior, but they are also computationally more expensive;
they generate the Jacobian matrix and solve the set of algebraic equations at
every time step using a Newton-like method. To reduce this extra cost, the
implicit solvers offer a Solver Jacobian method parameter that allows you
to improve the simulation performance of implicit solvers. See “Choosing a
Jacobian Method for an Implicit Solver” on page 14-24 for more information.
14-12
Choose a Solver
One-Step versus Multistep Solvers
The Simulink solver library provides both one-step and multistep solvers.
The one-step solvers estimate y(tn) using the solution at the immediately
preceding time point, y(tn-1), and the values of the derivative at a number of
points between tn and tn-1. These points are minor steps.
The multistep solvers use the results at several preceding time steps to
compute the current solution. Simulink provides one explicit multistep solver,
ode113, and one implicit multistep solver, ode15s. Both are variable-step
solvers.
Variable-Order Solvers
Two variable-order solvers, ode15s and ode113, are part of the solver
library. These solvers use multiple orders to solve the system of equations.
Specifically, the implicit, variable-step ode15s solver uses first-order through
fifth-order equations while the explicit, variable-step ode113 solver uses
first-order through thirteenth-order. For ode15s, you can limit the highest
order applied via the Maximum Order parameter. For more information, see
“Maximum Order” on page 14-20.
Choosing a Fixed-Step Solver
About the Fixed-Step Discrete Solver
The fixed-step discrete solver computes the time of the next simulation step
by adding a fixed step size to the current time. The accuracy and the length of
time of the resulting simulation depends on the size of the steps taken by the
simulation: the smaller the step size, the more accurate the results are but the
longer the simulation takes. You can allow the Simulink software to choose
the size of the step (the default) or you can choose the step size yourself. If you
choose the default setting of auto, and if the model has discrete sample times,
then Simulink sets the step size to the fundamental sample time of the model.
Otherwise, if no discrete rates exist, Simulink sets the size to the result of
dividing the difference between the simulation start and stop times by 50.
14-13
14
Running Simulations
Note If you try to use the fixed-step discrete solver to update or simulate a
model that has continuous states, an error message appears. Thus, selecting
a fixed-step solver and then updating or simulating a model is a quick way to
determine whether the model has continuous states.
About Fixed-Step Continuous Solvers
The fixed-step continuous solvers, like the fixed-step discrete solver, compute
the next simulation time by adding a fixed-size time step to the current time.
For each of these steps, the continuous solvers use numerical integration to
compute the values of the continuous states for the model. These values are
calculated using the continuous states at the previous time step and the state
derivatives at intermediate points (minor steps) between the current and the
previous time step. The fixed-step continuous solvers can, therefore, handle
models that contain both continuous and discrete states.
Note In theory, a fixed-step continuous solver can handle models that
contain no continuous states. However, that would impose an unnecessary
computational burden on the simulation. Consequently, Simulink uses the
fixed-step discrete solver for a model that contains no states or only discrete
states, even if you specify a fixed-step continuous solver for the model.
Two types of fixed-step continuous solvers that Simulink provides are: explicit
and implicit. (See “Explicit versus Implicit Solvers” on page 14-12 for more
information). The difference between these two types lies in the speed and
the stability. An implicit solver requires more computation per step than an
explicit solver but is more stable. Therefore, the implicit fixed-step solver that
Simulink provides is more adept at solving a stiff system than the fixed-step
explicit solvers.
Explicit Fixed-Step Continuous Solvers. Explicit solvers compute the
value of a state at the next time step as an explicit function of the current
values of both the state and the state derivative. Expressed mathematically
for a fixed-step explicit solver:
x(n + 1) = x(n) + h ∗ Dx(n)
14-14
Choose a Solver
where x is the state, Dx is a solver-dependent function that estimates the
state derivative, h is the step size, and n indicates the current time step.
Simulink provides a set of explicit fixed-step continuous solvers. The solvers
differ in the specific numerical integration technique that they use to compute
the state derivatives of the model. The following table lists each solver and
the integration technique it uses.
Solver
Integration Technique
Order of Accuracy
ode1
Euler’s Method
First
ode2
Heun’s Method
Second
ode3
Bogacki-Shampine Formula
Third
ode4
Fourth-Order Runge-Kutta
(RK4) Formula
Fourth
ode5
Dormand-Prince (RK5)
Formula
Fifth
ode8
Dormand-Prince RK8(7)
Formula
Eighth
The table lists the solvers in order of the computational complexity of the
integration methods they use, from the least complex (ode1) to the most
complex (ode8).
None of these solvers has an error control mechanism. Therefore, the
accuracy and the duration of a simulation depends directly on the size of the
steps taken by the solver. As you decrease the step size, the results become
more accurate, but the simulation takes longer. Also, for any given step size,
the more computationally complex the solver is, the more accurate are the
simulation results.
If you specify a fixed-step solver type for a model, then by default, Simulink
selects the ode3 solver, which can handle both continuous and discrete states
with moderate computational effort. As with the discrete solver, if the model
has discrete rates (sample times), then Simulink sets the step size to the
fundamental sample time of the model by default. If the model has no discrete
rates, Simulink automatically uses the result of dividing the simulation total
duration by 50. Consequently, the solver takes a step at each simulation
14-15
14
Running Simulations
time at which Simulink must update the discrete states of the model at its
specified sample rates. However, it does not guarantee that the default solver
accurately computes the continuous states of a model. Therefore, you might
need to choose another solver, a different fixed step size, or both to achieve
acceptable accuracy and an acceptable simulation time.
Implicit Fixed-Step Continuous Solvers. An implicit fixed-step solver
computes the state at the next time step as an implicit function of the state
at the current time step and the state derivative at the next time step. In
other words:
x(n + 1) − x(n) − h ∗ Dx(n + 1) = 0
Simulink provides one implicit fixed-step solver : ode14x. This solver uses a
combination of Newton’s method and extrapolation from the current value to
compute the value of a state at the next time step. You can specify the number
of Newton’s method iterations and the extrapolation order that the solver uses
to compute the next value of a model state (see “Fixed-step size (fundamental
sample time)”). The more iterations and the higher the extrapolation
order that you select, the greater the accuracy you obtain. However, you
simultaneously create a greater computational burden per step size.
Process for Choosing a Fixed-Step Continuous Solver
Any of the fixed-step continuous solvers in the Simulink product can simulate
a model to any desired level of accuracy, given a small enough step size.
Unfortunately, it generally is not possible, or at least not practical, to decide a
priori which combination of solver and step size will yield acceptable results
for the continuous states in the shortest time. Determining the best solver for
a particular model generally requires experimentation.
Following is the most efficient way to choose the best fixed-step solver for
your model experimentally.
1 Choose error tolerances. For more information, see “Specifying Error
Tolerances for Variable-Step Solvers” on page 14-22.
2 Use one of the variable-step solvers to simulate your model to the level of
accuracy that you desire. Start with ode45. If your model runs slowly,
your problem might be stiff and need an implicit solver. The results of this
14-16
Choose a Solver
step give a good approximation of the correct simulation results and the
appropriate fixed step size.
3 Use ode1 to simulate your model at the default step size for your model.
Compare the simulation results for ode1 with the simulation for the
variable-step solver. If the results are the same for the specified level of
accuracy, you have found the best fixed-step solver for your model, namely
ode1. You can draw this conclusion because ode1 is the simplest of the
fixed-step solvers and hence yields the shortest simulation time for the
current step size.
4 If ode1 does not give satisfactory results, repeat the preceding steps
with each of the other fixed-step solvers until you find the one that gives
accurate results with the least computational effort. The most efficient way
to perform this task is to use a binary search technique:
a Try ode3.
b If ode3 gives accurate results, try ode2. If ode2 gives accurate results, it
is the best solver for your model; otherwise, ode3 is the best.
c If ode3 does not give accurate results, try ode5. If ode5 gives accurate
results, try ode4. If ode4 gives accurate results, select it as the solver for
your model; otherwise, select ode5.
d If ode5 does not give accurate results, reduce the simulation step size and
repeat the preceding process. Continue in this way until you find a solver
that solves your model accurately with the least computational effort.
Choosing a Variable-Step Solver
When you set the Type control of the Solver configuration pane to
Variable-step, the Solver control allows you to choose one of the
variable-step solvers. As with fixed-step solvers, the set of variable-step
solvers comprises a discrete solver and a subset of continuous solvers.
However, unlike the fixed-step solvers, the step size varies dynamically based
on the local error.
The choice between the two types of variable-step solvers depends on whether
the blocks in your model define states and, if so, the type of states that they
14-17
14
Running Simulations
define. If your model defines no states or defines only discrete states, select
the discrete solver. In fact, if a model has no states or only discrete states,
Simulink uses the discrete solver to simulate the model even if you specify a
continuous solver. If the model has continuous states, the continuous solvers
use numerical integration to compute the values of the continuous states
at the next time step.
About Variable-Step Continuous Solvers
The variable-step solvers in the Simulink product dynamically vary the step
size during the simulation. Each of these solvers increases or reduces the step
size using its local error control to achieve the tolerances that you specify.
Computing the step size at each time step adds to the computational overhead
but can reduce the total number of steps, and the simulation time required to
maintain a specified level of accuracy.
You can further categorize the variable-step continuous solvers as: one-step
or multistep, single-order or variable-order, and explicit or implicit. (See
“Choosing a Solver Type” on page 14-10 for more information.)
Explicit Continuous Variable-Step Solvers
The explicit variable-step solvers are designed for nonstiff problems. Simulink
provides three such solvers: ode45, ode23, and ode113.
ODE
Solver
Method
ode45
X
Medium
ode23
X
Low
Runge-Kutta (2,3) pair of
Bogacki & Shampine
Variable,
Low to
High
PECE Implementation of
Adams-Bashforth-Moutlon
ode113
14-18
One-Step Multistep Order of
Method
Method Accuracy
X
Runge-Kutta,
Dormand-Prince (4,5)
pair
Choose a Solver
ODE
Solver
Tips on When to Use
ode45
In general, the ode45 solver is the best to apply as a first try for
most problems. For this reason, ode45 is the default solver for
models with continuous states. This Runge-Kutta (4,5) solver is
a fifth-order method that performs a fourth-order estimate of
the error. This solver also uses a fourth-order “free” interpolant,
which allows for event location and smoother plots.
The ode45 is more accurate and faster than ode23. If the ode45
is slow computationally, your problem may be stiff and thus in
need of an implicit solver.
ode23
The ode23 can be more efficient than the ode45 solver at crude
error tolerances and in the presence of mild stiffness. This solver
provides accurate solutions for “free” by applying a cubic Hermite
interpolation to the values and slopes computed at the ends of
a step.
ode113
For problems with stringent error tolerances or
for computationally intensive problems, the
Adams-Bashforth-Moulton PECE solver can be more
efficient than ode45.
Implicit Continuous Variable-Step Solvers
If your problem is stiff, try using one of the implicit variable-step solvers:
ode15s, ode23s, ode23t, or ode23tb.
ODE
Solver
One-Step Multistep
Method Method
X
ode15s
ode23s
X
Order
Solver
of
Reset
Accuracy Method
Variable,
Low to
Medium
Low
X
Max.
Order
Method
X
Numerical Differentiation
Formulas (NDFs)
Second-order, modified
Rosenbrock formula
14-19
14
Running Simulations
ODE
Solver
One-Step Multistep
Method Method
Order
Solver
of
Reset
Accuracy Method
Max.
Order
Method
ode23t
X
Low
X
Trapezoidal rule using a
“free” interpolant
ode23tb
X
Low
X
TR-BDF2
Solver Reset Method. For three of the stiff solvers — ode15s, ode23t, and
ode23tb— a drop-down menu for the Solver reset method appears on the
Solver Configuration pane. This parameter controls how the solver treats a
reset caused, for example, by a zero-crossing detection. The options allowed
are Fast and Robust. The former setting specifies that the solver does not
recompute the Jacobian for a solver reset, whereas the latter setting specifies
that the solver does. Consequently, the Fast setting is faster computationally
but might use a small step size for certain cases. To test for such cases, run
the simulation with each setting and compare the results. If there is no
difference, you can safely use the Fast setting and save time. If the results
differ significantly, try reducing the step size for the fast simulation.
Maximum Order. For the ode15s solver, you can choose the maximum
order of the numerical differentiation formulas (NDFs) that the solver applies.
Since the ode15s uses first- through fifth-order formulas, the Maximum order
parameter allows you to choose 1 through 5. For a stiff problem, you may
want to start with order 2.
Tips for Choosing a Variable-Step Implicit Solver. The following table
provides tips relating to the application of variable-step implicit solvers. For
an example comparing the behavior of these solvers, see sldemo_solvers.
14-20
Choose a Solver
ODE
Solver
Tips on When to Use
ode15s
ode15s is a variable-order solver based on the numerical
differentiation formulas (NDFs). NDFs are related to, but
are more efficient than the backward differentiation formulas
(BDFs), which are also known as Gear’s method. The ode15s
solver numerically generates the Jacobian matrices. If you
suspect that a problem is stiff, or if ode45 failed or was highly
inefficient, try ode15s. As a rule, start by limiting the maximum
order of the NDFs to 2.
ode23s
ode23s is based on a modified Rosenbrock formula of order 2.
Because it is a one-step solver, it can be more efficient than
ode15s at crude tolerances. Like ode15s, ode23s numerically
generates the Jacobian matrix for you. However, it can solve
certain kinds of stiff problems for which ode15s is not effective.
ode23t
The ode23t solver is an implementation of the trapezoidal rule
using a “free” interpolant. Use this solver if your model is only
moderately stiff and you need a solution without numerical
damping. (Energy is not dissipated when you model oscillatory
motion.)
ode23tb
ode23tb is an implementation of TR-BDF2, an implicit
Runge-Kutta formula with two stages. The first stage is a
trapezoidal rule step while the second stage uses a backward
differentiation formula of order 2. By construction, the method
uses the same iteration matrix in evaluating both stages. Like
ode23s, this solver can be more efficient than ode15s at crude
tolerances.
Note For a stiff problem, solutions can change on a time scale that is very
small as compared to the interval of integration, while the solution of interest
changes on a much longer time scale. Methods that are not designed for
stiff problems are ineffective on intervals where the solution changes slowly
because these methods use time steps small enough to resolve the fastest
possible change. For more information, see Shampine, L. F., Numerical
Solution of Ordinary Differential Equations, Chapman & Hall, 1994.
14-21
14
Running Simulations
Support for Zero-Crossing Detection
Both the variable-step discrete and continuous solvers use zero-crossing
detection (see “Zero-Crossing Detection” on page 3-23) to handle continuous
signals.
Specifying Error Tolerances for Variable-Step Solvers
Local Error. The variable-step solvers use standard control techniques to
monitor the local error at each time step. During each time step, the solvers
compute the state values at the end of the step and determine the local
error—the estimated error of these state values. They then compare the
local error to the acceptable error, which is a function of both the relative
tolerance (rtol) and the absolute tolerance (atol). If the local error is greater
than the acceptable error for any one state, the solver reduces the step size
and tries again.
• The Relative tolerance measures the error relative to the size of each state.
The relative tolerance represents a percentage of the state value. The
default, 1e-3, means that the computed state is accurate to within 0.1%.
• Absolute tolerance is a threshold error value. This tolerance represents the
acceptable error as the value of the measured state approaches zero.
The solvers require the error for the ith state, ei, to satisfy:
ei ≤ max(rtol × xi , atoli ).
The following figure shows a plot of a state and the regions in which the
relative tolerance and the absolute tolerance determine the acceptable error.
14-22
Choose a Solver
Absolute Tolerances. Your model has a global absolute tolerance that you
can set on the Solver pane of the Configuration Parameters dialog box. This
tolerance applies to all states in the model. You can specify auto or a real
scalar. If you specify auto (the default), Simulink initially sets the absolute
tolerance for each state to 1e-6. As the simulation progresses, the absolute
tolerance for each state resets to the maximum value that the state has
assumed so far, times the relative tolerance for that state. Thus, if a state
changes from 0 to 1 and reltol is 1e-3, then by the end of the simulation,
abstol becomes 1e-3 also. If a state goes from 0 to 1000, then abstol changes
to 1.
If the computed setting is not suitable, you can determine an appropriate
setting yourself. You might have to run a simulation more than once to
determine an appropriate value for the absolute tolerance.
Several blocks allow you to specify absolute tolerance values for solving the
model states that they compute or that determine their output:
• Integrator
• Second-Order Integrator Limited
• Variable Transport Delay
• Transfer Fcn
• State-Space
• Zero-Pole
The absolute tolerance values that you specify for these blocks override the
global settings in the Configuration Parameters dialog box. You might want
to override the global setting if, for example, the global setting does not
provide sufficient error control for all of your model states because they vary
widely in magnitude. The block absolute tolerance can be set to:
• auto
• –1 (same as auto)
• real scalar
• real vector (having a dimension equal to the number of corresponding
continuous states in the block)
14-23
14
Running Simulations
Tips. If you do choose to set the absolute tolerance, keep in mind that too low
of a value causes the solver to take too many steps in the vicinity of near-zero
state values. As a result, the simulation is slower.
On the other hand, if you choose too high of an absolute tolerance, your
results can be inaccurate as one or more continuous states in your model
approach zero.
Once the simulation is complete, you can verify the accuracy of your results
by reducing the absolute tolerance and running the simulation again. If the
results of these two simulations are satisfactorily close, then you can feel
confident about their accuracy.
Choosing a Jacobian Method for an Implicit Solver
About the Solver Jacobian
For implicit solvers, Simulink must compute the solver Jacobian, which
is a submatrix of the Jacobian matrix associated with the continuous
representation of a Simulink model. In general, this continuous
representation is of the form:
x = f ( x, t, u)
y = g( x, t, u).
The Jacobian, J, formed from this system of equations is:
⎛ ∂f
⎜
J = ⎜ ∂x
⎜ ∂g
⎜
⎝ ∂x
∂f ⎞
∂u ⎟⎟ = ⎛ A
⎜
∂g ⎟ ⎝ C
⎟
∂u ⎠
B⎞
⎟.
D⎠
In turn, the solver Jacobian is the submatrix, J x .
Jx = A =
14-24
∂f
.
∂x
Choose a Solver
Sparsity of Jacobian. For many physical systems, the solver Jacobian Jx is
sparse, meaning that many of the elements of Jx are zero.
Consider the following system of equations:
x1 = f1 ( x1 , x3 )
x 2 = f2 ( x2 )
x 3 = f3 ( x2 ).
From this system, you can derive a sparsity pattern that reflects the structure
of the equations. The pattern, a Boolean matrix, has a 1 for each xi that
appears explicitly on the right-hand side of an equation. You thereby attain:
J x, pattern
⎛1 0 1⎞
⎜
⎟
= ⎜0 1 0⎟
⎜0 1 0⎟
⎝
⎠
As discussed in “Full and Sparse Perturbation Methods” on page 14-28 and
“Full and Sparse Analytical Methods” on page 14-30 respectively, the Sparse
Perturbation Method and the Sparse Analytical Method may be able to take
advantage of this sparsity pattern to reduce the number of computations
necessary and thereby improve performance.
Solver Jacobian Methods
When you choose an implicit solver from the Solver pane of the Configuration
Parameters dialog box, a parameter called Solver Jacobian method and
a drop-down menu appear. This menu has five options for computing the
solver Jacobian: auto, Sparse perturbation, Full perturbation, Sparse
analytical, and Full analytical.
14-25
14
Running Simulations
Note If you set Automatic solver parameter selection to warning or
error in the Solver Diagnostics pane, and you choose a different solver
method than Simulink, you might receive a warning or an error.
Limitations. The solver Jacobian methods have the following limitations
associated with them.
• If you select an analytical Jacobian method, but one or more blocks in
the model do not have an analytical Jacobian, then Simulink applies a
perturbation method.
14-26
Choose a Solver
• If you select sparse perturbation and your model contains data store blocks,
Simulink applies the full perturbation method.
Heuristic ’auto’ Method
The default setting for the Solver Jacobian method is auto. Selecting this
choice causes Simulink to perform a heuristic to determine which of the
remaining four methods best suits your model. This algorithm is depicted in
the following flowchart.
14-27
14
Running Simulations
Because the sparse methods are beneficial for models having a large number
of states, the heuristic chooses a sparse method if more than 50 states exist
in your model. The logic also leads to a sparse method if you specify ode23s
because, unlike other implicit solvers, ode23s generates a new Jacobian at
every time step. A sparse analytical or a sparse perturbation method is,
therefore, highly advantageous. The heuristic also ensures that the analytical
methods are used only if every block in your model can generate an analytical
Jacobian.
Full and Sparse Perturbation Methods
The full perturbation method was the standard numerical method that
Simulink used to solve a system. For this method, Simulink solves the full set
of perturbation equations and uses LAPACK for linear algebraic operations.
This method is costly from a computational standpoint, but it remains the
recommended method for establishing baseline results.
The sparse perturbation method attempts to improve the run-time
performance by taking mathematical advantage of the sparse Jacobian
pattern. Returning to the sample system of three equations and three states,
x1 = f1 ( x1 , x3 )
x 2 = f2 ( x2 )
x 3 = f3 ( x2 ).
The solver Jacobian is:
14-28
Choose a Solver
⎛ ∂f1
⎜
⎜ ∂x1
⎜ ∂f
Jx = ⎜ 2
⎜ ∂x1
⎜ ∂f
⎜ 3
⎜ ∂x
⎝ 1
⎛ f1 ( x1
⎜
⎜
⎜ f (x
=⎜ 2 1
⎜
⎜ f (x
⎜ 3 1
⎜
⎝
∂f1
∂x2
∂f2
∂x2
∂f3
∂x2
∂f1 ⎞
⎟
∂x3 ⎟
∂f2 ⎟
⎟
∂x3 ⎟
∂f3 ⎟
⎟
∂x3 ⎟⎠
+ Δx1 , x2 , x3 ) − f1
Δx1
f1 ( x1 , x2 + Δx2 , x3 ) − f1
Δx2
+ Δx1 , x2 , x3 ) − f2
Δx1
f2 ( x1 , x2 + Δx2 , x3 ) − f2
Δx2
+ Δx1 , x2 , x3 ) − f3
Δx1
f3 ( x1 , x2 + Δx2 , x3 ) − f3
Δx2
f1 ( x1 , x2 , x3 + Δx3 ) − f1 ⎞
⎟
Δx3
⎟
f2 ( x1 , x2 , x3 + Δx3 ) − f2 ⎟
⎟
Δx3
⎟
f3 ( x1 , x2 , x3 + Δx3 ) − f3 ⎟
⎟
⎟
Δx3
⎠
It is, therefore, necessary to perturb each of the three states three times and
to evaluate the derivative function three times. For a system with n states,
this method perturbs the states n times.
By applying the sparsity pattern and perturbing states x1 and x 2 together,
this matrix reduces to:
⎛ f1 ( x1 + Δx1 , x2 + Δx2 , x3 ) − f1
⎜
Δx1
⎜
⎜
Jx = ⎜
0
⎜
⎜
⎜
0
⎜
⎝
0
f2 ( x1 + Δx1 , x2 + Δx2 , x3 ) − f2
Δx2
f3 ( x1 + Δx1 , x2 + Δx2 , x3 ) − f3
Δx2
f1 ( x1 , x2 , x3 + Δx3 ) − f1 ⎞
⎟
Δx3
⎟
⎟
0
⎟
⎟
⎟
⎟
0
⎟
⎠
The solver can now solve columns 1 and 2 in one sweep. While the sparse
perturbation method saves significant computation, it also adds overhead to
compilation. It might even slow down the simulation if the system does not
have a large number of continuous states. A tipping point exists for which you
14-29
14
Running Simulations
obtain increased performance by applying this method. In general, systems
having a large number of continuous states are usually sparse and benefit
from the sparse method.
The sparse perturbation method, like the sparse analytical method, uses
UMFPACK to perform linear algebraic operations. Also, the sparse
perturbation method supports both RSim and Rapid Accelerator mode.
Full and Sparse Analytical Methods
The full and sparse analytical methods attempt to improve performance
by calculating the Jacobian using analytical equations rather than the
perturbation equations. The sparse analytical method, also uses the sparsity
information to accelerate the linear algebraic operations required to solve
the ordinary differential equations.
Sparsity Pattern
For details on how to access and interpret the sparsity pattern in MATLAB,
see sldemo_metro.
Support for Code Generation
While the sparse perturbation method supports RSim, the sparse analytical
method does not. Consequently, regardless of which sparse method you select,
any generated code uses the sparse perturbation method.
14-30
Interact with a Running Simulation
Interact with a Running Simulation
You can perform certain operations interactively while a simulation is
running. You can do the following:
• Modify some configuration parameters, including the stop time and the
maximum step size
• Click a line to see the signal carried on that line on a floating (unconnected)
Scope or Display block
• Modify the parameters of a block, as long as you do not cause a change in
the:
-
Number of states, inputs, or outputs
Sample time
Number of zero crossings
Vector length of any block parameters
Length of the internal block work vectors
Dimension of any signals
• Display block data tips (see “Block Tool Tips” on page 23-2)
You cannot make changes to the structure of the model, such as adding or
deleting lines or blocks, during a simulation. To make these kinds of changes,
stop the simulation, make the change, then start the simulation again to
see the results of the change.
14-31
14
Running Simulations
Save and Restore Simulation State as SimState
In this section...
“Overview of the SimState” on page 14-32
“Save the SimState” on page 14-33
“Restore the SimState” on page 14-35
“Change the States of a Block within the SimState” on page 14-37
“SimState Interface Checksum Diagnostic” on page 14-37
“Limitations of the SimState” on page 14-38
“Using SimState within S-Functions” on page 14-38
Overview of the SimState
In real-world applications, you simulate a Simulink model repeatedly to
analyze the behavior of a system for different input, boundary conditions, or
operating conditions. In many applications, a start-up phase with significant
dynamic behavior is common to multiple simulations. For example, the
cold start take-off of a gas turbine engine occurs before each set of aircraft
maneuvers. Ideally, you would simulate this start-up phase once, save the
simulation state at the end of the start-up phase, and then use this simulation
state or SimState as the initial state for each set of conditions or maneuvers.
The Simulink SimState feature allows you to save all run-time data necessary
for restoring the simulation state of a model. A SimState includes both the
logged and internal state of every block (e.g., continuous states, discrete
states, work vectors, zero-crossing states) and the internal state of the
Simulink engine (e.g., the data of the ODE solver).
You can save a SimState:
• At the final Stop time
• When you interrupt a simulation with the Pause or Stop button
• When you use a block (e.g., the Stop block) to stop a simulation
14-32
Save and Restore Simulation State as SimState
At a later time, you can restore the SimState and use it as the initial
conditions for any number of simulations.
Note The Final states option of the Data Import/Export pane in Simulink
saves only logged states—the continuous and discrete states of blocks—which
are a subset of the complete simulation state of the model. Hence you cannot
use the Final states to save and restore the complete simulation state as
the initial state of a new simulation.
Save the SimState
Saving the SimState Interactively
To save the complete SimState at the beginning of the final step:
1 In the Simulink model window, select Simulation > Configuration
Parameters.
2 Navigate to the Data Import/Export pane.
3 Select the Final states check box. The Save complete SimState in final
state check box becomes active.
4 Select the Save complete SimState in final state check box.
5 In the adjacent field, enter a variable name for the SimState.
6 Simulate the model by selecting Simulation > Run.
14-33
14
Running Simulations
Saving the SimState Programmatically
You can save the SimState at the beginning of the final step programmatically
using the sim command in conjunction with the set_param command with the
SaveCompleteFinalSimState parameter set to on:
set_param(mdl, 'SaveFinalState', 'on', 'FinalStateName',...
[mdl 'SimState'],'SaveCompleteFinalSimState', 'on')
simOut = sim(mdl, 'StopTime', tstop)
set_param(mdl, 'SaveFinalState', 'off')
14-34
Save and Restore Simulation State as SimState
Restore the SimState
Restoring the SimState Interactively
You can restore the SimState interactively.
In the Data Import/Export pane:
1 Under Load from workspace, select the check box next to Initial state.
The adjacent field becomes active.
2 Enter the name of the variable containing the SimState in the field.
In the Solver pane of the Configuration Parameters window:
14-35
14
Running Simulations
1 Keep the Start time set to its original value.
2 Set the Stop time to the sum of the original simulation time plus the new
additional simulation time.
3 Click OK.
The Start time must maintain its original value because it is a reference
value for all time and time-dependent variables in both the original and the
current simulations. For example, a block may save and restore the number
of sample time hits that occurred since the beginning of simulation as the
SimState . For clarity, consider a model that you ran from 0 s to 100 s and
that you now wish to run from 100 s to 200 s. The Start time is 0 s for both
the original simulation (0 s to 100 s) and for the current simulation (100 s to
200 s). And 100 s is the initial time of the current simulation. Also, if the block
had ten sample time hits during the original simulation, Simulink recognizes
that the next sample time hit will be the eleventh relevant to 0 s (not 100 s).
Restoring the SimState Programmatically
Use the set_param command to specify the initial condition as the SimState.
set_param(mdl, 'LoadInitialState', 'on', 'InitialState',...
[mdl 'SimState']);
simOut = sim(mdl, 'StopTime', tstop)
Restoring a SimState Saved in an Earlier Version of Simulink
You can now use SimState objects saved in earlier releases (R2010a or later)
to restore the SimState of a model. You can see the version of Simulink used
to save the SimState by examining the ’version’ field of the SimState object.
Simulink detects if the SimState object provided as the initial state was
saved in the current release. By default, the Simulink software reports an
error message if the SimState was not saved in the current release. You
may configure the diagnostic to allow Simulink to report the message as a
warning and try to restore as many of the values as possible. To enable
this best-effort restoration, go to the Diagnostics pane of the Configuration
Parameter dialog box and set the message for SimState object from earlier
release to warning. You can also set the diagnostic programmatically using
the set_param command.
14-36
Save and Restore Simulation State as SimState
set_param(mdl,
'SimStateOlderReleaseMsg', 'warning');
Change the States of a Block within the SimState
You can use the loggedStates to get or set the SimState. The loggedStates
field has the same structure as xout.signals if xout is the state log that
Simulink exports to the workspace.
SimState Interface Checksum Diagnostic
The SimState interface checksum is primarily based upon the configuration
settings of your model. A diagnostic, ’SimState interface checksum mismatch’,
resides on the Diagnostics pane of the Configuration Parameters dialog box.
You can set this diagnostic to ’none’, ’warning’, or ’error” to receive a warning
or an error if the interface checksum of the restored SimState does not match
the current interface checksum of the model. Such mismatches may occur
when you try to simulate using a solver that is different from the one that
14-37
14
Running Simulations
generated the saved SimState. Simulink permits such solver changes. For
example, you can use a solver such as ode15s, to solve the initial stiff portion
of a simulation, save the final SimState, and then continue the simulation
with the restored SimState and using ode45. In other words, this diagnostic
is purely to serve your own purposes for detecting solver changes.
Limitations of the SimState
Several limitations exist for the SimState:
• You can use only the Normal or the Accelerator mode of simulation.
• You cannot save the SimState in Normal mode and restore it in Accelerator
mode, or vice versa.
• You can save the SimState only at the final stop time or at the execution
time at which you pause or stop the simulation.
• By design, Simulink does not save user data, run-time parameters, or logs
of the model.
• The SimState feature does not support code generation, including Model
Reference in accelerated modes.
• You cannot make any structural changes to the model between the time
at which you save the SimState and the time at which you restore the
simulation using the SimState. For example, you cannot add or remove
a block after saving the SimState without repeating the simulation and
saving the new SimState.
• You cannot input the SimState to model functions.
Using SimState within S-Functions
Special APIs for C and Level-2 MATLAB S-functions are available, which
enable the S-functions to work with the SimState. For information on how
to implement these APIs within S-functions, see “S-Function Compliance
with the SimState”.
14-38
Diagnose Simulation Errors
Diagnose Simulation Errors
In this section...
“Response to Run-Time Errors” on page 14-39
“Simulation Diagnostics Viewer” on page 14-39
“Create Custom Simulation Error Messages” on page 14-41
Response to Run-Time Errors
If errors occur during a simulation, the Simulink software halts the
simulation, opens the subsystems that caused the error (if necessary), and
displays the errors in the Simulation Diagnostics Viewer. The following
sections explain how to use the viewer to determine the cause of the errors,
and how to create custom error messages.
Simulation Diagnostics Viewer
The viewer comprises an Error Summary pane and an Error Message pane.
14-39
14
Running Simulations
Click to display
error source.
Error Summary Pane
The upper pane lists the errors that caused the simulation to terminate. The
pane displays the following information for each error.
Message. Message type (for example, block error, warning, or log)
Source. Name of the model element (for example, a block) that caused the
error
Reported By. Component that reported the error (for example, the Simulink
product, the Stateflow product, or the Simulink Coder product).
Summary. Error message, abbreviated to fit in the column
14-40
Diagnose Simulation Errors
You can remove any of these columns of information to make room for
other columns. To remove a column, select the View menu and uncheck
the corresponding item.
Error Message Pane
The lower pane initially contains the contents of the first error message listed
in the top pane. You can display the contents of other messages by clicking
their entries in the upper pane.
In addition to displaying the viewer, the Simulink software opens (if
necessary) the subsystem that contains the first error source and highlights
the source.
You can display the sources of other errors by clicking: anywhere in the error
message in the upper pane; the name of the error source in the error message
(highlighted in blue); or the Open button on the viewer.
Changing Font Size
To change the size of the font used to display errors, select Increase Font
Size or Decrease Font Size from the Font Size menu of the viewer.
Create Custom Simulation Error Messages
The Simulation Diagnostics Viewer displays the output of any instance of
the MATLAB error function executed during a simulation. Such instances
include those invoked by block or model callbacks, or by S-functions that you
create or that the MATLAB Function block executes.
14-41
14
Running Simulations
You can use the MATLAB error function in callbacks, S-functions or the
MATLAB Function block to create custom error messages specific to your
application. Capabilities available for messages include:
• Display the contents of a text string
• Include hyperlinks to an object
• Link to an HTML file
Displaying A Text String
To display the contents of a text string, pass the string enclosed by quotation
marks to the error function.
The following example shows how you can make the user-created function
check_signal display the string Signal is negative.
The MATLAB Function block invokes the following function:
function y=check_signal(x)
if x<0
error('Signal is negative');
else
y=x;
end
Executing this model causes a runtime error and starts the debugger when
you click the OK button of the runtime error message. When you quit the
debugger, an error message in the Simulation Diagnostics window.
14-42
Diagnose Simulation Errors
Creating Hyperlinks to Files, Directories, or Blocks
To include a hyperlink to a block, file, or folder in the error message, include
the path to the item enclosed in quotation marks.
• error ('Error evaluating parameter in block "mymodel/Mu"')
displays a text hyperlink to the block Mu in the model “mymodel”. Clicking
the hyperlink displays the block in the model window.
• error ('Error reading data from "c:/work/test.data"')
displays a text hyperlink to the file test.data in the error message.
Clicking the link displays the file in your preferred MATLAB editor.
• error ('Could not find data in folder "c:/work"')
displays a text hyperlink to the c:/work folder. Clicking the link opens a
system command window (shell) and sets its working folder to c:/work.
14-43
14
Running Simulations
Creating Programmatic Hyperlinks
You can create a hyperlink that, when clicked, causes the evaluation of a
MATLAB expression. For example, the following model InitFcn callback
displays an error, when the model starts, with a hyperlink to help for the
find_system command.
error('See help for the find_system
In this example, the Simulation Diagnostics window displays a hyperlink
labeled find_system. Clicking the link opens the documentation for the
find_system command in the MATLAB Help browser.
14-44
15
Running a Simulation
Programmatically
• “About Programmatic Simulation” on page 15-2
• “Run Simulation Using the sim Command” on page 15-3
• “Control Simulation using the set_param Command” on page 15-7
• “Run Parallel Simulations” on page 15-8
• “Error Handling in Simulink Using MSLException” on page 15-15
15
Running a Simulation Programmatically
About Programmatic Simulation
Entering simulation commands in the MATLAB Command Window or
from a MATLAB file enables you to run unattended simulations. You can
perform Monte Carlo analysis by changing the parameters randomly and
executing simulations in a loop. You can use either the sim command or
the set_param command to run a simulation programmatically. To run
simulations simultaneously, you can call sim from within a parfor loop under
specific conditions.
15-2
Run Simulation Using the sim Command
Run Simulation Using the sim Command
In this section...
“Single-Output Syntax for the sim Command” on page 15-3
“Examples of Implementing the sim Command” on page 15-4
“Calling sim from within parfor” on page 15-5
“Backwards Compatible Syntax” on page 15-5
Single-Output Syntax for the sim Command
The general form of the command syntax for running a simulation is:
SimOut = sim('model', Parameters)
where model is the name of the block diagram and Parameters can be
a list of parameter name-value pairs, a structure containing parameter
settings, or a configuration set. The sim command returns, SimOut, a single
Simulink.SimulationOutput object that contains all of the simulation
outputs (logged time, states, and signals). This syntax is the “single-output
format” of the sim command.
SimOut = sim('model', 'Param1', Value1, 'Param2', Value2...);
SimOut = sim('model', ParameterStruct);
SimOut = sim('model', ConfigSet);
During simulation, the specified parameters override the values in the block
diagram configuration set. The original configuration values are restored at
the end of simulation. If you wish to simulate the model without overriding
any parameters, and you want the simulation results returned in the
single-output format, then you must do one of the following:
• select Save simulation output as single object on the Data
Import/Export pane of the Configuration Parameters dialog box
• specify the ReturnWorkspaceOutputs parameter value as ’on’ in the sim
command:
SimOut = sim('model', 'ReturnWorkspaceOutputs', 'on');
15-3
15
Running a Simulation Programmatically
To log the model time, states, or outputs, use the Configuration Parameters
Data Import/Export dialog box. To log signals, either use a block such as
the To Workspace block or the Scope block, or use the Signal and Scope
Manager to log results directly.
For complete details of the sim command syntax, see the sim reference page.
Examples of Implementing the sim Command
Following are examples that show the application of each of the three formats
for specifying parameter values using the single-output format of the sim
command.
Specifying Parameter Name-Value Pairs
In the following example, the sim syntax specifies the model name, vdp,
followed by consecutive pairs of parameter name and parameter value. For
example, the value of the SimulationMode parameter is rapid.
simOut = sim('vdp','SimulationMode','rapid','AbsTol','1e-5',...
'SaveState','on','StateSaveName','xoutNew',...
'SaveOutput','on','OutputSaveName','youtNew');
simOutVars = simOut.who;
yout = simOut.get('youtNew');
Specifying a Parameter Structure
The following example shows how to specify parameter name-value pairs
as a structure to the sim command.
paramNameValStruct.SimulationMode = 'rapid';
paramNameValStruct.AbsTol
= '1e-5';
paramNameValStruct.SaveState
= 'on';
paramNameValStruct.StateSaveName = 'xoutNew';
paramNameValStruct.SaveOutput
= 'on';
paramNameValStruct.OutputSaveName = 'youtNew';
simOut = sim('vdp',paramNameValStruct);
15-4
Run Simulation Using the sim Command
Specifying a Configuration Set
The following example shows how to create a configuration set and use it
with the sim syntax.
model = 'vdp';
load_system(model)
simMode = get_param(model, 'SimulationMode');
set_param(model, 'SimulationMode', 'rapid')
cs = getActiveConfigSet(model);
model_cs = cs.copy;
set_param(model_cs,'AbsTol','1e-5',...
'SaveState','on','StateSaveName','xoutNew',...
'SaveOutput','on','OutputSaveName','youtNew')
simOut = sim(model, model_cs);
set_param(model, 'SimulationMode', simMode)
The block diagram parameter, SimulationMode, is not part of the
configuration set, but is associated with the model. Therefore, the set_param
command saves and restores the original simulation mode by passing the
model rather than the configuration set.
Calling sim from within parfor
For information on how to run simultaneous simulations by calling sim from
within parfor, see “Run Parallel Simulations” on page 15-8.
Backwards Compatible Syntax
The following syntax is now obsolete but will be maintained for backwards
compatibility with Simulink Versions 7.3 or earlier releases.
[T,X,Y] =sim('model',Timespan, Options, UT)
[T,X,Y1,...,Yn] =sim('model',Timespan, Options, UT)
If only one right-hand side argument exists, then Simulink automatically
saves the time, the state and the output to the specified left-hand side
arguments. You can explicitly switch to the single-output format by changing
the defaults.
15-5
15
Running a Simulation Programmatically
If you do not specify any left-hand side arguments, then Simulink
determines what data to log based on the workspace I/O settings of the Data
Import/Export pane of the Configuration Parameters dialog box.
T
The time vector returned.
X
The state returned in matrix or structure format. The
state matrix contains continuous states followed by
discrete states.
Y
The output returned in matrix or structure format.
For block diagram models, this variable contains all
root-level blocks.
Y1,...,Yn
The outports, which can only be specified for diagram
models. Here n must be the number of root-level blocks.
Each outport will be returned in the Y1,...,Yn variables.
’model’
The name of a block diagram model.
Timespan
The timespan can be one of the following: TFinal,
[TStart TFinal], or [TStart OutputTimes TFinal].
Output times are time points which will be returned in
T, but in general T will include additional time points.
Options
Optional simulation parameters created in a structure
by the simset command using name-value pairs.
UT
Optional external inputs. For supported expressions, see
“Enable Data Import” on page 45-77.
Simulink only requires the first parameter. Simulink takes all defaults from
the block diagram, including unspecified options. If you specify any optional
arguments, your specified settings override the settings in the block diagram.
Specifying the right-hand side argument of sim as the empty matrix, [ ],
causes Simulink to use the default for the argument.
To specify the single-output format for sim(’model’, Timespan, Options, UT),
set the ’ReturnWorkspaceOutputs’ option of the options structure to ’on’.
See also simset and simget.
15-6
Control Simulation using the set_param Command
Control Simulation using the set_param Command
You can use the set_param command to start, stop, pause, or continue a
simulation, to update a block diagram, or to write all data logging variables to
the base workspace. The format of the set_param command is:
set_param('sys', 'SimulationCommand', 'cmd')
where 'sys' is the name of the system and 'cmd' is 'start', 'stop',
'pause', 'continue', 'update', or 'WriteDataLogs'.
Similarly, you can use the get_param command to check the status of a
simulation. The format of the get_param function call for this use is
get_param('sys', 'SimulationStatus')
The Simulink software returns 'stopped', 'initializing', 'running',
'paused', 'updating', 'terminating', or 'external' (used with the
Simulink Coder product).
Note If you use matlab -nodisplay to start a session, then you cannot use
set_param to run your simulation session.
Run Simulation from an S-Function
S-functions can use the set_param command to control simulation execution.
A C MEX S-function can use the mexCallMATLAB macro to call the set_param
command itself.
15-7
15
Running a Simulation Programmatically
Run Parallel Simulations
In this section...
“Overview of Calling sim from within parfor” on page 15-8
“sim in parfor with Rapid Accelerator Mode” on page 15-9
“Workspace Access Issues” on page 15-10
“Resolving Workspace Access Issues” on page 15-11
“Data Concurrency Issues” on page 15-12
“Resolving Data Concurrency Issues” on page 15-13
Overview of Calling sim from within parfor
The MATLAB parfor command allows you to run parallel Simulink
simulations. Calling sim from within a parfor loop is often advantageous for
performing multiple simulation runs of the same model for different inputs
or for different parameter settings. For example, you may save significant
simulation time performing parameter sweeps and Monte Carlo analyses
by running them in parallel. Note that running parallel simulations using
parfor does not currently support decomposing your model into smaller
connected pieces and running the individual pieces simultaneously on
multiple workers.
Normal, Accelerator, and Rapid Accelerator simulation modes are supported
by sim in parfor. (See “Choosing a Simulation Mode” on page 22-11 for
details on selecting a simulation mode and “Design Your Model for Effective
Acceleration” on page 22-16 for optimizing simulation run times.) For other
simulations modes, you need to address any workspace access issues and
data concurrency issues in order to produce useful results. Specifically, the
simulations need to create separately named output files and workspace
variables; otherwise, each simulation will overwrite the same workspace
variables and files, or possibly have collisions trying to write variables and
files simultaneously.
For more information on code regeneration and parameter handling in Rapid
Accelerator mode, see “Parameter Handling in Rapid Accelerator Mode” on
page 22-8.
15-8
Run Parallel Simulations
For details about the parfor command, see parfor.
Note All simulation modes require a homogeneous file system. The workers
and the callers must be on the same operating system and have the same type
of file system (for example, NTFS or FAT).
Note If you open models inside a parfor statement you should close them
again using bdclose all to avoid leaving temporary files behind.
sim in parfor with Rapid Accelerator Mode
Running Rapid Accelerator simulations in parfor combines speed with
automatic distribution of a prebuilt executable to the parfor workers. As a
result, this mode eliminates duplication of the update diagram phase.
To run parallel simulations in Rapid Accelerator simulation mode using the
sim and parfor commands, you must:
• Configure the model to run in Rapid Accelerator simulation mode
• Ensure that the Rapid Accelerator target is already built and up to date
• Disable the Rapid Accelerator target up-to-date check by setting the sim
command option RapidAcceleratorUpToDateCheck to ’off’.
To satisfy the second condition, you can only change parameters between
simulations that do not require a model rebuild. In other words, the structural
checksum of the model must remain the same. Hence, you can change only
tunable block diagram parameters and tunable run-time block parameters
between simulations. For a discussion on tunable parameters that do not
require a rebuild subsequent to their modifications, see “Determining If the
Simulation Will Rebuild” on page 22-7.
As for the third condition, the following sample code shows how to disable the
up-to-date check using the sim command.
15-9
15
Running a Simulation Programmatically
matlabpool open
% Load the model and set parameters
model = 'vdp';
load_system(model)
% Build the Rapid Accelerator target
rtp = Simulink.BlockDiagram.buildRapidAcceleratorTarget(model);
% Run parallel simulations
parfor i=1:4
simOut{i} = sim(model,'SimulationMode', 'rapid',...
'RapidAcceleratorUpToDateCheck', 'off',...
'SaveTime', 'on',...
'StopTime', num2str(10*i));
end
matlabpool close
In this example, the call to the buildRapidAcceleratorTarget
function generates code once. Subsequent calls to sim with the
RapidAcceleratorUpToDateCheck option off guarantees that code is not
regenerated. Data concurrency issues are thus resolved.
For a detailed example of this method of running parallel simulations, refer to
the Rapid Accelerator Simulations Using PARFOR.
Workspace Access Issues
In order to run sim in parfor, you must first open a MATLAB pool of workers
using the matlabpool command. The parfor command then runs the code
within the parfor loop in these MATLAB worker sessions. The MATLAB
workers, however, do not have access to the workspace of the MATLAB client
session where the model and its associated workspace variables have been
loaded. Hence, if you load a model and define its associated workspace
variables outside of and before a parfor loop, then neither is the model
loaded, nor are the workspace variables defined in the MATLAB worker
sessions where the parfor iterations are executed. This is typically the case
when you define model parameters or external inputs in the base workspace
of the client session. These scenarios constitute workspace access issues.
15-10
Run Parallel Simulations
Resolving Workspace Access Issues
When a Simulink model is loaded into memory in a MATLAB client session,
it is only visible and accessible in that MATLAB session; it is not accessible
in the memory of the MATLAB worker sessions. Similarly, the workspace
variables associated with a model that are defined in a MATLAB client
session (such as parameters and external inputs) are not automatically
available in the worker sessions. You must therefore ensure that the model is
loaded and that the workspace variables referenced in the model are defined
in the MATLAB worker session by using the following two methods.
• In the parfor loop, use the sim command to load the model and to set
parameters that change with each iteration. (Alternative: load the model
and then use the g(s)et_param command(s) to set the parameters in the
parfor loop)
• In the parfor loop, use the MATLAB evalin and assignin commands
to assign data values to variables.
Alternatively, you can simplify the management of workspace variables
by defining them in the model workspace. These variables will then be
automatically loaded when the model is loaded into the worker sessions.
There are, however, limitations to this method. For example, you cannot have
tunable parameters in a model workspace. For a detailed discussion on the
model workspace, see “Model Workspaces” on page 4-67.
Specifying Parameter Values Using the sim Command
Use the sim command in the parfor loop to set parameters that change
with each iteration.
% Run parallel simulations of a model that does not
% result in data concurrency issues
model = 'vdp';
paramName = 'StopTime';
paramValue = {'10', '20', '30', '40'};
parfor i=1:4
simOut{i} = sim(model, ...
paramName, paramValue{i}, ...
'SaveTime', 'on');
end
15-11
15
Running a Simulation Programmatically
An equivalent method is to load the model and then use the set_param
command to set the paramName in the parfor loop.
Specifying Variable Values Using the assignin Command
You can pass the values of model or simulation variables to the MATLAB
workers by using the assignin or the evalin command. The following
example illustrates how to use this method to load variable values into the
appropriate workspace of the MATLAB workers.
parfor i = 1:4
assignin('base', 'extInp', externalInput{i})
% 'extInp' is the name of the variable in the base
% workspace which contains the External Input data
simOut{i} = sim(model, 'ExternalInput', 'extInp');
end
For further details, see the Rapid Accelerator Simulations Using PARFOR
example.
Data Concurrency Issues
Data concurrency issues refer to scenarios for which software makes
simultaneous attempts to access the same file for data input or output. In
Simulink, they primarily occur as a result of the nonsequential nature of
the parfor loop during simultaneous execution of Simulink models. The
most common incidences arise when code is generated or updated for a
simulation target of a Stateflow, Model block or MATLAB Function block
during parallel computing. The cause, in this case, is that Simulink tries to
concurrently access target data from multiple worker sessions. Similarly,
To File blocks may simultaneously attempt to log data to the same files
during parallel simulations and thus cause I/O errors. Or a third-party
blockset or user-written S-function may cause a data concurrency issue while
simultaneously generating code or files.
A secondary cause of data concurrency is due to the unprotected access of
network ports. This type of error occurs, for example, when a Simulink
product provides blocks that communicate via TCP/IP with other applications
during simulation. One such product is the HDL Verifier™ for use with the
Mentor Graphics® ModelSim® HDL simulator.
15-12
Run Parallel Simulations
Resolving Data Concurrency Issues
The core requirement of parfor is the independence of the different
iterations of the parfor body. This restriction is not compatible with the core
requirement of simulation via incremental code generation, for which the
simulation target from a prior simulation is reused or updated for the current
simulation. Hence during the parallel simulation of a model that involves
code generation (such as Accelerator mode simulation), Simulink makes
concurrent attempts to access (update) the simulation target . However, you
can avoid such data concurrency issues by creating a temporary folder within
the parfor loop and then adding several lines of MATLAB code to the loop to
perform the following steps:
1 Change the current folder to the temporary, writable folder.
2 In the temporary folder, load the model, set parameters and input vectors,
and simulate the model.
3 Return to the original, current folder.
4 Remove the temporary folder and temporary path.
In this manner, you avoid concurrency issues by loading and simulating the
model within a separate temporary folder. Following are examples that use
this method to resolve common concurrency issues.
A Model with Stateflow, MATLAB Function Block, or Model
Block
In this example, either the model is configured to simulate in Accelerator mode
or it contains a Stateflow, a MATLAB Function block, or a Model block (for
example, sf_bounce, sldemo_autotrans, or sldemo_modelref_basic). For these
cases, Simulink generates code during the initialization phase of simulation.
Simulating such a model in parfor would cause code to be generated to the
same files, while the initialization phase is running on the worker sessions.
As illustrated below, you can avoid such data concurrency issues by running
each iteration of the parfor body in a different temporary folder.
parfor i=1:4
15-13
15
Running a Simulation Programmatically
cwd = pwd;
addpath(cwd)
tmpdir = tempname;
mkdir(tmpdir)
cd(tmpdir)
load_system(model)
% set the block parameters, e.g., filename of To File block
set_param(someBlkInMdl, blkParamName, blkParamValue{i})
% set the model parameters by passing them to the sim command
out{i} = sim(model, mdlParamName, mdlParamValue{i});
cd(cwd)
rmdir(tmpdir,'s')
rmpath(cwd)
end
Note that you can also avoid other concurrency issues due to file I/O errors by
using a temporary folder for each iteration of the parfor body.
A Model with To File Blocks
If you simulate a model with To File blocks from inside of a parfor loop, the
nonsequential nature of the loop may cause file I/O errors. To avoid such
errors during parallel simulations, you can either use the temporary folder
idea above or use the sim command in Rapid Accelerator mode with the option
to append a suffix to the file names specified in the model To File blocks.
By providing a unique suffix for each iteration of the parfor body, you can
avoid the concurrency issue.
parfor i=1:4
sim(model, ...
'ConcurrencyResolvingToFileSuffix', num2str(i),...
'SimulationMode', 'rapid');
end
15-14
Error Handling in Simulink® Using MSLException
Error Handling in Simulink Using MSLException
Error Reporting in a Simulink Application
Simulink allows you to report an error by throwing an exception using the
MSLException object , which is a subclass of the MATLAB MException class.
As with the MATLAB MException object, you can use a try-catch block with
a MSLException object construct to capture information about the error. The
primary distinction between the MSLException and the MException objects is
that the MSLException object has the additional property of handles. These
handles allow you to identify the object associated with the error.
The MSLException Class
The MSLException class has five properties: identifier, message, stack,
cause, and handles. The first four of these properties are identical to those
of MException. For detailed information about them, see “Properties of the
MException Class”. The fifth property, handles, is a cell array with elements
that are double array. These elements contain the handles to the Simulink
objects (blocks or block diagrams) associated with the error.
Methods of the MSLException Class
The methods for the MSLException class are identical to those of the
MException class. For details of these methods, see MException.
Capturing Information about the Error
The structure of the Simulink try-catch block for capturing an exception is:
try
Perform one or more operations
catch E
if isa(E, 'MSLException')
...
end
If an operation within the try statement causes an error, the catch statement
catches the exception (E). Next, an if isa conditional statement tests to
15-15
15
Running a Simulation Programmatically
determine if the exception is Simulink specific, i.e., an MSLException. In
other words, an MSLException is a type of MException.
The following code example how to get the handles associated with an error.
errHndls = [];
try
sim('ModelName', ParamStruct);
catch e
if isa(e,'MSLException')
errHndls = e.handles{1}
end
end
You can see the results by examining e. They will be similar to the following
output:
e =
MSLException
Properties:
handles:
identifier:
message:
cause:
stack:
{[7.0010]}
'Simulink:Parameters:BlkParamUndefined'
[1x87 char]
{0x1 cell}
[0x1 struct]
Methods, Superclasses
To identify the name of the block that threw the error, use the getfullname
command. For the present example, enter the following command at the
MATLAB command line:
getfullname(errHndls)
If a block named Mu threw an error from a model named vdp, MATLAB
would respond to the getfullname command with:
ans =
15-16
Error Handling in Simulink® Using MSLException
vdp/Mu
15-17
15
15-18
Running a Simulation Programmatically
16
Visualizing and Comparing
Simulation Results
• “View Simulation Results” on page 16-2
• “Signal Viewer Tasks” on page 16-6
• “Scope Signal Viewer Tasks” on page 16-11
• “Scope Signal Viewer Characteristics” on page 16-14
• “Signal Generator Tasks” on page 16-21
• “Signal and Scope Manager” on page 16-23
• “Signal Selector” on page 16-27
16
Visualizing and Comparing Simulation Results
View Simulation Results
In this section...
“What Are Scope Blocks, Signal Viewers, Test Points and Data Logging?”
on page 16-2
“Scope Block and Scope Signal Viewer Differences” on page 16-3
“Why Use Signal Generators and Signal Viewers Instead of Source Blocks
and Scope Blocks?” on page 16-4
What Are Scope Blocks, Signal Viewers, Test Points
and Data Logging?
Scope blocks, signal viewers, test points, and data logging provide ways for
you to display and capture results from your simulations.
These icons represent the various data display and data capture devices:
• To perform basic signal viewer tasks, see “Signal Viewer Tasks” on page
16-6 and “Scope Signal Viewer Tasks” on page 16-11.
• For detailed information on signal viewers, see “Signal and Scope Manager”
on page 16-23.
• For information on signal logging, see “Export Signal Data Using Signal
Logging” on page 45-19.
16-2
View Simulation Results
• For information on signal Test Points, see “Test Points” on page 47-58.
• For information on Scope Blocks, see Scope.
Scope Block and Scope Signal Viewer Differences
Use Scope blocks and scope signal viewers to display simulation results, but
as shown in this table, they have different characteristics.
Characteristic Scope Signal Viewer
Scope Block
Interface
Drag from Library Browser
Attach to signal using Signal
Selector or context menu
See “Signal Selector” on
page 16-27
See “Scope Signal Viewer
Context Menu” on page
16-15
Scope of
Control
All viewers centrally
managed from Signal
and Scope Manager
Each managed individually
See “Signal and Scope
Manager” on page 16-23.
Signals per
axis
Multiple
One nonbus signal per
axis or multiple signals fed
through a mux or a bus
Axes per
scope
Multiple
Multiple
Data
handling
Save data to a signal logging
object
“Creating a Multiple Axes
Scope Signal Viewer” on
page 16-11
Save variable data to
workspace as structures or
arrays
16-3
16
Visualizing and Comparing Simulation Results
Characteristic Scope Signal Viewer
Scope Block
Data logging
None
Log data to model-wide data
object
See
Simulink.SimulationData.Dataset
and
Simulink.ModelDataLogs
Scrolling
display data
capability
Yes
No
Display
• Data markers
Color and line codes
distinguish signals
• Legends
• Color and line codes
distinguish signals
Graph
Refresh
Period
Adjustable
Fixed
Display of
Minor Steps
The viewer does not display
minor steps regardless of
the value of the Refine
parameter setting.
Only displays major
time step values. The
scope displays additional
interpolated points between
major time steps if specified
by the refine parameter.
Why Use Signal Generators and Signal Viewers
Instead of Source Blocks and Scope Blocks?
You should use signal generators and signal viewers instead of Source and
Scope blocks when you want to:
• Navigate to and attach signal generators or signal viewers deep within a
model hierarchy.
• Centrally manage all signal generators and signal viewers present in
your model.
16-4
View Simulation Results
• Use the display features provided by signal viewers that are not available
in Scope blocks.
• Reduce clutter in your block diagram. Because signal viewers attach
directly to signals, it is not necessary for you to route them to a Scope block.
This results in fewer signal routes in your block diagram.
• View data from referenced models. See “Test Points” on page 47-58 for
more information.
16-5
16
Visualizing and Comparing Simulation Results
Signal Viewer Tasks
In this section...
“About Signal Viewers” on page 16-6
“Attaching a Signal Viewer” on page 16-6
“Adding Signals to a Signal Viewer” on page 16-8
“Displaying a Signal Viewer” on page 16-9
“Saving Data to MATLAB Workspace” on page 16-10
“Plotting the Viewer Data” on page 16-10
About Signal Viewers
• Signal viewers are not the same as Scope blocks. For an explanation of
the differences, see “Scope Block and Scope Signal Viewer Differences”
on page 16-3.
• Signal viewers do not show signal labels on the axis, display the simulation
minor time step values, or work with Simulink Report Generator.
• Not all signal viewer features are supported when you simulate your model
in Rapid Accelerator mode. See “Behavior of Scopes and Viewers with
Rapid Accelerator Mode” on page 22-18.
• The Help button for a signal viewer is located on the parameters dialog box
for a specific viewer type. For more information, see“Scope Signal Viewer
Parameters Dialog Box” on page 16-16 .
Signal viewer
Attaching a Signal Viewer
If you want to,
• Quickly connect or disconnect a scope signal viewer, use the context menu.
• Review all of the signal viewers and the signals connected to them, use the
Signal and Scope Manager.
16-6
Signal Viewer Tasks
Using the Context Menu
To attach a signal viewer with the signal content menu,
1 On your Simulink block diagram, right-click a signal, and then from the
context menu, select Create & Connect Viewer.
2 From the list that appears, select the type of signal viewer you want to
attach.
If you attach a scope signal viewer, a viewer window opens. You must run
the simulation after you attach the viewer for the information to be plotted.
Using the Signal and Scope Manager
To attach a scope signal viewer using the Scope & Signal Manager,
1 On your Simulink block diagram, right-click a signal, and then from the
context menu, select Signal & Scope Manager. The Signal & Scope
Manager dialog box opens.
2 In the Types pane and under the Viewers node, expand a product node to
show the viewers installed and available to you.
Note The Simulink Scope displayed in the Signal and Scope Manager
Types pane is not the same as the Simulink Scope Block. For an
explanation of the differences, see “Scope Block and Scope Signal Viewer
Differences” on page 16-3.
16-7
16
Visualizing and Comparing Simulation Results
3 Under an expanded product node, select a viewer, and then click the
Attach to model button.
The viewer is added to a table in the Viewers tab in the Generators/Viewers
in model pane. The table lists the viewers in your model.
Each row corresponds to a viewer. The columns specify each viewer name,
type, and number of inputs. If a viewer accepts a variable number of
inputs, the # in entry for the viewer contains a pull-down list that displays
the range of inputs that the viewer can accept. To change the number of
inputs accepted by the viewer, select a value from the pull-down list.
Adding Signals to a Signal Viewer
To add additional traces to an existing signal viewer,
1 In the Simulink Editor, right-click a signal.
16-8
Signal Viewer Tasks
2 From the signal context menu, point to Create & Connect Viewer, and
then from the submenu, point to a product.
3 From the list, select the signal viewer you want to attach to the signal.
A viewer ion
is added to the signal line.
You can also add signals to a signal viewer with the Signal and Scope
Manager. See “Signal and Scope Manager” on page 16-23.
Note You must run a simulation for the new signal trace to display in a
viewer.
Note If you add or remove signals from a Signal Viewer, the Signal Viewer
title and legends update only when you run a simulation, and then open the
viewer.
Displaying a Signal Viewer
1 Right-click a signal viewer icon. From the context menu, point to Open
Viewer, and then select a viewer from the list.
Depending on the type of signal viewer, the following happens:
• Scope and Floating Scope — A Viewer: Scope window opens with a graph
of the signals attached to the viewer.
16-9
16
Visualizing and Comparing Simulation Results
• XY Graph — A Sink Block Parameters dialog box opens. After running a
simulation, a Viewer: XY Graph window opens with a graph of the X and
Y signals attached to the viewer.
2 Customize the signal viewer to better visualize the simulation results.
Saving Data to MATLAB Workspace
To save the data displayed on the viewer to the MATLAB workspace, perform
the following steps:
1 In the Viewer toolbar, click the parameters icon
.
2 Click the History tab.
3 Select Save to model signal logging object (logsout).
4 In the Logging name field, enter a logging variable name.
5 Assign a name to the signal in the block diagram, for example, x1.
6 Run the simulation by selecting Simulation > Start.
You can now view the data in the MATLAB Command Window by entering
the following commands:
logsout.unpack('all')
data = x1.Data
x1.time
where x1 is the name of the signal.
Plotting the Viewer Data
You can plot the data interactively or programmatically.
• Simulation Data Inspector — plot the data as explained in “Inspect
Signal Data” on page 17-11.
• Simplot — plot the data from the command line using the simplot
command (see simplot). The resulting figure looks identical to the viewer
window and can be annotated using the Plot Editing Tools.
16-10
Scope Signal Viewer Tasks
Scope Signal Viewer Tasks
In this section...
“Adding a Legend to a Scope Signal Viewer” on page 16-11
“Creating a Multiple Axes Scope Signal Viewer” on page 16-11
Adding a Legend to a Scope Signal Viewer
1 In a Scope signal viewer window, right-click.
2 From the context menu, select Legends.
The viewer draws a box and identifies each signal with the name of the
signal. If a signal does not have a name, the legend uses the name of the
originating block or subsystem.
3 To move a legend to another location on the graph, left-click and drag the
legend box.
For information about the color and line styles in the Viewer window, see
“Line Styles with Scope Signal Viewer” on page 16-19.
Creating a Multiple Axes Scope Signal Viewer
You can add multiple plots (called axes) to a scope signal viewer. Each axes
can have different y-axis settings.
To create a viewer with more than one axes.
1 Open the Signal and Scope manager. Add a signal Scope or Floating Scope
signal viewer to your model. See “Attaching a Signal Viewer” on page 16-6.
2 From the # in drop-down list, select the total number of axes for the graph.
16-11
16
Visualizing and Comparing Simulation Results
3 In the Signals connected to Generator/Viewer section, select the first
axis.
4 Click the Signal Selector button
. The Signal Selector dialog box
opens.
5 Select the signal or signals to add to this axis, and then close the dialog.
6 Repeat steps 3 to 5 until you have added signals to all of the axes.
7 Click the parameters icon
run the simulation.
16-12
to display the scope signal viewer, and then
Scope Signal Viewer Tasks
16-13
16
Visualizing and Comparing Simulation Results
Scope Signal Viewer Characteristics
In this section...
“Scope Signal Viewer Toolbar” on page 16-14
“Scope Signal Viewer Context Menu” on page 16-15
“Scope Signal Viewer Parameters Dialog Box” on page 16-16
“Line Styles with Scope Signal Viewer” on page 16-19
“Parameter Settings and Performance with Scope Signal Viewer” on page
16-20
Scope Signal Viewer Toolbar
The signal viewer toolbar is attached to each scope signal viewer. It has the
following controls.
Icon
Function
Opens the Print dialog box so you can print the contents of a
Scope Viewer window.
Opens the Scope parameters dialog for modifying display
characteristics. For details, see “Scope Signal Viewer Parameters
Dialog Box” on page 16-16.
Simultaneously zooms in on the x and y axes. The zoom feature
is not active while the simulation is running.
Use this button to zoom in on the x axis only. The zoom feature is
not active while the simulation is running.
Use this button to zoom in on the y axis only. The zoom feature is
not active while the simulation is running.
Automatically scales the axis to fully display all signals.
Stores the current axis settings so you can apply them to the
next simulation.
Restores the graph setting values saved by the most recent Save
axes settings command.
16-14
Scope Signal Viewer Characteristics
Icon
Function
Activates the Signal Selector. For more information, see “Signal
Selector” on page 16-27.
Docks and undocks the Scope Viewer. When you dock the Scope
Viewer, it is placed within the MATLAB Command Window and
automatically resized.
Scope Signal Viewer Context Menu
The scope signal viewer context menu is a convenient way to make simple
changes to a viewer without navigating to a Scope or Floating Scope
parameters dialog box.
Within a Scope signal viewer window, right-click to display the context menu.
It contains the following controls.
Control
Function
Legends
Adds a legend to your scope viewer.
Autoscale
Automatically scales the viewer axis.
Signal selection
Displays the Signal Selector dialog.
For information, see “Signal
Selector” on page 16-27
Axes properties
Displays the Axis Properties dialog.
You can manually set the minimum
and maximum range for the y axis
here.
16-15
16
Visualizing and Comparing Simulation Results
Control
Function
Scope parameters
Displays the Scope parameters
dialog.
For information, see “Scope Signal
Viewer Parameters Dialog Box” on
page 16-16.
Tick labels
Displays the Tick Labels dialog.
From here you can turn on and off
various tick options.
Scope Signal Viewer Parameters Dialog Box
To open a Scope or Floating Scope parameters dialog box,
• On the scope toolbar, click
There are three tabs on the dialog box:
• General — set the axis characteristics and the sampling decimation value
• History — control the amount of stored and displayed data
• Performance — control the scope refresh rate.
General Tab
With this tab you control the number of axes, the time range, and the
appearance of your graph.
Number of axes. Set the number of axes in this data field. Each axis is
displayed as a separate graph within a single Scope Viewer.
An example of this is shown in “Adding Signals to a Signal Viewer” on page
16-8.
Time Range. Change the x-axis limits by entering a number or auto in
the Time range field.
16-16
Scope Signal Viewer Characteristics
Entering a number of seconds causes each screen to display the amount of
data that corresponds to that number of seconds. Enter auto to set the x-axis
to the duration of the simulation.
Note Do not enter variable names in these fields.
Tick labels. Specifies whether to label axes ticks. The options are:
Option
Effect
all
Places ticks on the outside of all axes
inside
Places tick labels inside all axes
(available only on signal viewers)
bottom axis only
Places tick labels outside the bottom
axes
Scroll. When you select this option, the scope continuously scrolls the
displayed signals to the left to keep as much data in view as will fit on the
screen at any one time.
In contrast, when this option is not selected, the scope draws a screen full of
data from left to right until the screen is full, erases the screen, and draws
the next screen full of data. This loop is repeated until the end of simulation
time. The effects of this option are discernible only when drawing is slow, for
example, when the model is very large or has a very small step size.
Note In some cases, the simulation slows when the simulation runs with the
scroll option selected. See “Parameter Settings and Performance with Scope
Signal Viewer” on page 16-20.
Data markers. Displays a marker at each data point on the Scope Viewer
screen.
Legends. Displays a legend on the scope that indicates the line style used
to display each signal.
16-17
16
Visualizing and Comparing Simulation Results
Decimation. Logs every Nth data point, where N is the number entered
in the edit field.
For example, suppose that the input signal to your Scope block has a fixed
sample time of 0.1 s. If you enter a value of 2, data points for this viewer will
be recorded at times 0.0, 0.2, 0.4....
History Tab
With this tab you control the amount of data that the Scope signal viewer
stores, displays and stores to the workspace. The values that appear in these
fields are the values that are used in the next simulation.
Limit data points to last. Limits the number of data points saved to the
workspace. Select the Limit data points to last check box and enter a value
in its data field.
The Scope relies on its data history for zooming and autoscaling operations. If
the number of data points is limited to 1,000 and the simulation generates
2,000 data points, only the last 1,000 are available for regenerating the
display.
Save to model signal logging object. At the end of the simulation, this
option saves the data displayed on the Scope Viewer . The data is saved in the
Simulink.ModelDataLogs object used to log data for the model (see “Export
Signal Data Using Signal Logging” on page 45-19 for more information).
For this option to take effect, you must also enable signal logging for the
model as a whole. To do this, check the Signal logging option on the Data
Import/Export pane of the Model Configuration Parameters dialog box.
For new models, use the Dataset logging format. If you use the Dataset
format for signal logging, then Simulink does not log the signals configured to
be logged in the Signal Viewer. Explicitly mark the signal for signal logging
by using the Signal Properties dialog box. To access the Signal Properties
dialog box, right-click a signal and from the context menu, select Properties.
16-18
Scope Signal Viewer Characteristics
Logging Name. Specifies the name under which to store the viewer’s
data in the model’s Simulink.ModelDataLogs object. The name must
be different from the log names specified by other signal viewers or for
other signals, subsystems, or model references logged in the model’s
Simulink.ModelDataLogs object.
Performance Tab
Controls how frequently the Scope signal viewer is refreshed. Reducing the
refresh rate can speed up the simulation in some cases.
Note For information about additional scope signal viewer parameters that
can affect performance, see “Parameter Settings and Performance with Scope
Signal Viewer” on page 16-20.
This tab contains the following controls.
Refresh Period. Select the units in which the refresh period is expressed.
Options are either seconds or frames, where a frame is the width of the scope’s
screen in seconds. This is the value of the scope’s Time range parameter.
Refresh Slider. Sets the refresh rate.
Drag the slider button to the right to increase the refresh period and hence
decrease the refresh rate.
Freeze Button. Controls refresh.
Click the button to freeze (stop refreshing) or unfreeze the Scope Viewer.
Line Styles with Scope Signal Viewer
If a signal contains multiple elements such as a vector or matrix, the viewer
distinguishes the elements with different line styles. If a signal has more
than four elements, the viewer cycles through the line styles. The line styles
retain the color of the signal.
16-19
16
Visualizing and Comparing Simulation Results
Signal Element
Scope Viewer
1
2
3
4
Parameter Settings and Performance with Scope
Signal Viewer
In some cases, when a Scope signal viewer needs to display a large number
of data points, the simulation slows down. When this happens, you can
improve simulation performance by adjusting the settings of some of the
viewer parameters. Try one or a combination of the following until you are
satisfied with the simulation performance.
• Turn off scroll mode.
• Reduce the time range.
• Use decimation to reduce the number of data points.
• Increase the refresh period to decrease the refresh rate.
• Limit the number of data points that the viewer saves to the workspace.
16-20
Signal Generator Tasks
Signal Generator Tasks
In this section...
“Attaching a Signal Generator.” on page 16-21
“Removing a Generator” on page 16-22
Attaching a Signal Generator.
If you want to,
• Quickly connect or disconnect a Signal Generator, use the context menu.
• Review all of the Signal Generators and their signals, use the Signal and
Scope Manager.
Using the Context Menu
To add additional traces to an existing signal viewer,
1 In the Simulink Editor, right-click the input to a block.
2 From the context menu, point to Create & Connect Generator, and then
from the submenu, point to a product.
3 From the list, select the generator you want as input to the block.
The name of the generator you choose appears in a box connected to the
block input.
4 Double-click the name to edit the generator name.
5 Right-click the name and select Generator Parameters to display a
dialog box where you can change the generator parameters.
6 Right-click the name and select Properties to display a dialog box where
you can change the signal properties.
Using the Signal and Scope Manager
To attach a Signal Generator using the Signal and Scope Manager,
16-21
16
Visualizing and Comparing Simulation Results
1 Right-click the input to a block, and then from the signal context menu
select Signal & Scope Manager.
2 In the Types pane and under the Generators node, expand a product node
to show the generator installed and available to you.
3 Under an expanded product node, select a generator, and then click the
Attach to model button.
The viewer is added to a table in the Generators tab in the
Generators/Viewers in model pane. The table lists the generators in your
model.
Each row corresponds to a generator. The columns specify each generator
name and type.
Clicking on the name of a generator displays the connected signals. For
instance, the constant is shown connected to the second input of the sum
block.
Removing a Generator
To remove the generator from the block diagram.
1 Right-click a generator.
2 From the context menu, select Disconnect Generator.
16-22
Signal and Scope Manager
Signal and Scope Manager
In this section...
“About the Signal & Scope Manager” on page 16-23
“Opening the Signal and Scope Manager” on page 16-24
“Changing Generator or Viewer Parameters” on page 16-25
“Adding Signals to a Viewer” on page 16-25
“Removing a Generator or Viewer from a Simulink Model” on page 16-25
“Viewing Test Point Data” on page 16-26
About the Signal & Scope Manager
The Signal & Scope Manager is a user interface to Signal Generator and
Viewer objects. Using the Signal and Scope Manager you can manage from
a central place all signal generators and viewers.
Note The Signal and Scope Manager requires that you have Java enabled
when you start MATLAB. This is the default.
Signal Generator and Viewer Objects
The small icons identifying a viewer or generator are called Viewer and
Generator Objects. These objects are not the same as scope blocks or signal
blocks. Generator and Viewer Objects are managed by the Signal and Scope
Manager, and are placed on signals. Blocks are dragged from the Library
browser and are not managed by the Signal and Scope manager.
16-23
16
Visualizing and Comparing Simulation Results
Opening the Signal and Scope Manager
1 In the Simulink Editor window, select Diagram > Signals &
Ports > Signal & Scope Manager.
The Signal & Scope Manger window opens.
16-24
Signal and Scope Manager
Alternatively within your model, right click a signal line and from the
context menu, select Signal & Scope Manager.
Changing Generator or Viewer Parameters
1 Open the Signal & Scope Manager window.
2 To the right side of the Generators/Viewers pane, click the parameters
.
button
The generator or viewer window opens.
3 From the toolbar, select the parameters button
. Review and change
parameters.
Adding Signals to a Viewer
Use the Signal Selector to add signals to a Viewer.
1 To the right side of the Generators/Viewers pane, click the Signal Selector
button
.
The Signal Selector window opens. Use the Signal Selector to connect and
disconnect generators and viewers.
2 From the signals pane, select the check boxes for the signals you want to
display in the selected viewer.
Tip After adding the new signals, run a simulation to make them visible.
Removing a Generator or Viewer from a Simulink
Model
1 In the Generators/Viewers pane, select either a listed generator for viewer.
2 On the right side, click the Delete button
.
16-25
16
Visualizing and Comparing Simulation Results
The selected generator or viewer is removed from the table.
Viewing Test Point Data
You can use a Signal Viewer available from the Signal and Scope Manager
to view any signal that is defined as a test point in a submodel. A test point
is a signal that is guaranteed to be observable when using a signal viewer
in a model.
Note With some signal viewers (for example, XY Graph, To Video Display,
Matrix Viewer, Spectrum Scope, and Vector Scope), you cannot use the Signal
Selector to select signals with test points in referenced models.
For more information, see “Test Points” on page 47-58.
16-26
Signal Selector
Signal Selector
In this section...
“About the Signal Selector” on page 16-27
“Select signals for object” on page 16-28
“Model Hierarchy” on page 16-28
“Inputs/Signals List” on page 16-28
About the Signal Selector
The Signal Selector allows you to connect a generator or viewer object (see
“Attaching a Signal Viewer” on page 16-6 and “Attaching a Signal Generator.”
on page 16-21) or a Floating Scope block to other block inputs and outputs.
It appears when you click the Signal selection button for a generator or
viewer object in the Signal & Scope Manager or on the toolbar of the Floating
Scope window.
The Signal Selector that appears when you click the Signal selection button
applies only to the currently selected generator or viewer object (or the
Floating Scope). If you want to connect blocks to another generator or viewer
object, you must select the object in the Signal & Scope Manager and launch
another instance of the Signal Selector. The object used to launch a particular
instance of the Signal Selector is called that instance’s owner.
16-27
16
Visualizing and Comparing Simulation Results
Select signals for object
This list box allows you to select the owner output port (in the case of signal
generators) or display axis (in the case of signal viewers) to which you want to
connect blocks in your model.
The list box is enabled only if the signal generator has multiple outputs or
the signal viewer has multiple axes.
Model Hierarchy
This tree-structured list lets you select any subsystem in your model.
Selecting a subsystem causes the adjacent port list to display the ports
available for connection in the selected subsystem. To display subsystems
included as library links in your model, click the Follow links button at
the top of the Model hierarchy control. To display subsystems contained
by masked subsystems, click the Look under masks button at the top
of the panel.
Inputs/Signals List
The contents of this panel displays input ports available for connection to the
Signal Selector’s owner if the owner is a signal generator or signals available
for connection to the owner if the owner is a signal viewer.
If the Signal Selector’s owner is a signal generator, the inputs/signals list by
default lists each input port in the system selected in the model hierarchy tree
that is either unconnected or connected to a signal generator.
16-28
Signal Selector
The label for each entry indicates the name of the block of which the port is an
input. If the block has more than one input, the label indicates the number of
the displayed port. A greyed label indicates that the port is connected to a
signal generator other than the Signal Selectors’ owner. Selecting the check
box next to a port’s entry in the list connects the Signal Selector’s owner to
the port, replacing, if necessary, the signal generator previously connected
to the port.
To display more information on each signal, click the Detailed view button
at the top of the pane. The detailed view shows the path and data type of
each signal and whether the signal is a test point. The controls at the top
and bottom of the panel let you restrict the amount of information shown
in the ports list.
• To show named signals only, select Named signals only from the List
contents control at the top of the pane.
• To show only signals selected in the Signal Selector, select Selected
signals only from the List contents control.
• To show test point signals only, select Testpointed/Logged signals only
from the List contents control.
16-29
16
Visualizing and Comparing Simulation Results
• To show only signals whose signals match a specified string of characters,
enter the characters in the Show signals matching control at the bottom
of the Signals pane and press the Enter key.
• To show the selected types of signals for all subsystems below the currently
selected subsystem in the model hierarchy, click the Current and Below
button at the top of the Signals pane.
To select or deselect a signal in the Signals pane, click its entry or use the
arrow keys to move the selection highlight to the signal entry and press the
Enter key. You can also move the selection highlight to a signal entry by
typing the first few characters of its name (enough to uniquely identify it).
Note You can continue to select and deselect signals on the block diagram
with the Signal Selector open. For example, shift-clicking a line in the block
diagram adds the corresponding signal to the set of signals that you previously
selected with the Signal Selector. If the simulation is running when you open
and use the Signal Selector, Simulink updates the Signal Selector to reflect
signal selection changes you have made on the block diagram. However, the
changes do not appear until you select the Signal Selector window itself. You
can also use the Signal Selector before running a model. If no simulation is
running, selecting a signal in the model does not change the Signal Selector.
16-30
17
Inspecting and Comparing
Logged Signal Data
• “Inspect Signal Data with Simulation Data Inspector” on page 17-2
• “Requirements for Recording Data” on page 17-4
• “Record Simulation Data” on page 17-5
• “Import Logged Signal Data” on page 17-7
• “Load Previously Recorded Data from a MAT-file” on page 17-10
• “Inspect Signal Data” on page 17-11
• “Compare Signal Data” on page 17-23
• “Comparison of One Signal From Multiple Simulations” on page 17-25
• “Compare All Logged Signal Data From Multiple Simulations” on page
17-28
• “Create Simulation Data Inspector Report” on page 17-32
• “Export Results in the Simulation Data Inspector Tool” on page 17-34
• “How the Simulation Data Inspector Tool Aligns Signals” on page 17-35
• “How the Simulation Data Inspector Tool Compares Time Series Data” on
page 17-37
• “Customize the Simulation Data Inspector Interface” on page 17-38
• “Limitations of the Simulation Data Inspector Tool” on page 17-54
• “Record and Inspect Signal Data Programmatically” on page 17-55
17
Inspecting and Comparing Logged Signal Data
Inspect Signal Data with Simulation Data Inspector
The Simulation Data Inspector software provides the capability to inspect and
compare time series data at several stages of your workflow:
• Model design: Inspect and compare simulation data after making changes
to the model diagram or its configuration.
• Testing your model: Compare simulation data with different input data
• Code generation: Compare simulation data and generated code output of
your model
You can compare variable-step data, fixed-step solver data from Simulink
and Simulink Coder, and fixed-step output with external data. “How the
Simulation Data Inspector Tool Aligns Signals” on page 17-35 describes how
signals are aligned between runs. “How the Simulation Data Inspector Tool
Compares Time Series Data” on page 17-37 describes how aligned signal
data are compared.
A typical workflow for inspecting and comparing signal data is:
1 Set up your model to log signal data, as in “Export Signal Data Using
Signal Logging” on page 45-19.
2 Open the Simulation Data Inspector tool, as described in “Open the
Simulation Data Inspector Tool” on page 17-39.
3 Simulate your model and record simulation data or import logged signal
data, as described in “Record Simulation Data” on page 17-5 and “Import
Logged Signal Data” on page 17-7.
4 Configure the Signal Browser table and specify how you want to graph the
data, as described in “Customize the Simulation Data Inspector Interface”
on page 17-38.
5 Inspect signals to quickly determine if the run satisfies requirements, as
described in “Inspect Signal Data” on page 17-11.
6 If the run is unsatisfactory, delete it. Repeat steps 3 and 4 to collect the
desired simulation runs for comparing data.
17-2
Inspect Signal Data with Simulation Data Inspector
7 Optionally assign tolerances to signals and graphically inspect the applied
tolerances.
8 Compare individual signals in the same run, or from different runs, as
described in “Compare Signal Data” on page 17-23.
9 Compare all of the imported signal data from multiple runs, as described
in “Compare All Logged Signal Data From Multiple Simulations” on page
17-28.
10 Determine which signals have discrepancies within the specified tolerances.
Plot and analyze the discrepancies of any two signals.
11 Save the imported signal data and comparison results, as described in
“Export Results in the Simulation Data Inspector Tool” on page 17-34.
The Simulation Data Inspector software provides a command-line interface.
For more information, see “Record and Inspect Signal Data Programmatically”
on page 17-55
.
17-3
17
Inspecting and Comparing Logged Signal Data
Requirements for Recording Data
The Simulation Data Inspector tool records the following data configured on
the “Data Import/Export Pane” of the Configuration Parameter dialog box:
• States and Output, if Format is Structure with time, or if Format is
Array or Structure and Time is logged.
• Signal logging
• Data stores
The Simulation Data Inspector tool supports the following data imported from
MAT-files and the MATLAB base workspace:
• Simulink.Timeseries and MATLAB timeseries objects
• Simulink.SimulationData.Dataset or Simulink.ModelDataLogs objects
• Data in Structure with time format
The Simulation Data Inspector supports output from the following blocks:
• Scope (Structure with time and Array format)
• To File (Timeseries format)
• To Workspace (Timeseries or Structure With Time format)
17-4
Record Simulation Data
Record Simulation Data
To set the Simulation Data Inspector to automatically import data after a
simulation run:
1 Set up your model to log signal data, as in “Export Signal Data Using
Signal Logging” on page 45-19.
2 Select Simulation > Model Configuration Parameters to open the
Configuration Parameters dialog box.
3 On the Data Import/Export pane:
• Select the Signal logging parameter.
• Select the Record and inspect simulation output parameter.
4 On the Simulink Editor toolbar, click the Record button arrow.
Select Simulation Data Inspector from the list. The Simulation Data
Inspector opens.
5 On the Simulink Editor toolbar, the Record button is already pressed
because in step 3 you selected the configuration parameter Data
Import/Export > Record and inspect simulation output. You can
click the Record button to toggle on and off recording data for a simulation.
6 Simulate your model. When the simulation is done, the data automatically
appears within a new run in the Simulation Data Inspector tool. To modify
the run name, see “Rename a Run” on page 17-44.
7 To import another simulation run, leave the Record button selected, and
simulate your model again. When the simulation is done, the data appears
as another new run.
8 When you are done importing data for your simulations, click the Record
button. If the Record button is not selected, data from simulations
are not imported into the tool and the configuration parameter Data
17-5
17
Inspecting and Comparing Logged Signal Data
Import/Export > Record and inspect simulation output is not
selected.
17-6
Import Logged Signal Data
Import Logged Signal Data
Before importing data into the Simulation Data Inspector tool, you must
have previously logged signal data to the base workspace or to a MAT-file.
For information on how to log signal data, see “Export Signal Data Using
Signal Logging” on page 45-19.
Import Signal Data from the Base Workspace
Using the Data Import tool, you can import data from the base workspace.
1 Open the Data Import tool by selecting the Import Data button
or
selecting File > Import Data.
2 Select Base Workspace. Data from logsout, xout, and yout appear in
the table.
17-7
17
Inspecting and Comparing Logged Signal Data
3 Select the Import check box to import a signal. Clear the Import check
box for signals that you do not want. You can also use the Select All and
Clear All buttons for mass selection or clearing of all signals.
17-8
Import Logged Signal Data
4 Click OK. The selected signals are displayed in the Signal Browser table.
Import Signal Data from a MAT-File
With the Data Import tool, you can select a subset of signals from a MAT-file
to import into the Simulation Data Inspector tool. Follow the steps to import
a MAT-File.
1 Open the Data Import tool by selecting the Import Data button
or
selecting File > Import Data.
2 For Import From, select MAT file. The File name parameter is enabled.
3 The Data Import tool locates a MAT-file in the current directory.
Alternatively, click the Open folder button to browse for your MAT-file.
The data from the MAT-file populates the data table.
4 Specify Import To by selecting New Run or Existing Run. If you select
Existing Run, select a run from the Run Name list.
5 Select the Import check box to import signals. Clear the Import check
box for signals that you do not want. You can also use the Select All and
Clear All buttons for selection or clearing of all the signals.
6 Click OK.
17-9
17
Inspecting and Comparing Logged Signal Data
Load Previously Recorded Data from a MAT-file
To load signal data from a MAT-file, which was created from the Simulation
Data Inspector tool:
1 On the Simulation Data Inspector toolbar, click the Open button
select File > Open.
2 Select the name of the MAT-file.
3 Click OK. Data stored in the MAT-file is displayed in the Simulation
Data Inspector tool.
17-10
or
Inspect Signal Data
Inspect Signal Data
Overview
On the Inspect Signals tab you can inspect logged signal data. On the left
pane you can open the Signal Browser table to view and configure signal and
run properties (see “Customize the Simulation Data Inspector Interface” on
page 17-38). On the right pane you can create different plot views. With a
view of multiple plots, you can group signals to better view your data. For
example, you can group the same signal from different simulation runs, group
signals with a similar range of values, or normalize a subset of your signal
data. The following examples use the sldemo_f14 model.
• “View Signal Data” on page 17-11
• “Create a View of Multiple Plots” on page 17-13
• “Explore Signal Data in a Multiple Plot View” on page 17-16
• “Replace a Run in a View” on page 17-17
• “Copy a View in the Inspect Signals Tab” on page 17-20
• “Delete a View in the Inspect Signals Tab” on page 17-21
• “Export a View in the Inspect Signals Tab” on page 17-22
• “Import a View in the Inspect Signals Tab” on page 17-22
View Signal Data
1 Configure a model to log signal data. This example uses the sldemo_f14
model configured to log signals: q, rad/sec, Stick, and NzPilot, g.
For more information, see “Export Signal Data Using Signal Logging” on
page 45-19.
2 On the Simulink Editor, click the Record button arrow and select
Simulation Data Inspector from the list.
3 To record simulation data, click the Record button so that it is selected.
17-11
17
Inspecting and Comparing Logged Signal Data
4 Simulate your model. The Simulation Data Inspector tool records and
displays the simulation data. Instead of recording data from a simulation,
you can import signal data from previous simulation runs, see “Import
Logged Signal Data” on page 17-7.
5 If the Inspect Signals tab is not already selected, select it. By default, the
Inspect Signals tab displays the Signal Browser table which contains
a row for each signal, organized by simulation runs. You can expand or
collapse any of the runs to view the logged signals in a run. For more
information, see “Customize the Simulation Data Inspector Interface” on
page 17-38.
6 Right-click the Signal Browser table title bar. Select Columns and uncheck
Block Name and Block Path.
7 Right-click the Signal Browser table title bar. Select Group Signals. In
the Group Signal dialog box, in the first drop-down box, select Logged
Variable. Select None in the second drop-down box. Click OK.
8 Expand logsout to view the logged signals.
9 “Specify the Line Configuration” on page 17-45 for each signal.
10 To specify the synchronization method, right-click the Signal Browser table
title bar. Select Columns and check Synchronization Method. The Sync
Method column is displayed in the table. For each signal, click the field
for the Sync Method column and select a method from the list. In this
example, the synchronization method is union.
17-12
Inspect Signal Data
11 Repeat step 5 for the Interpolation Method.
12 Click the Plot column for a signal. On the right pane of the Simulation
Data Inspector tool, the signal data is displayed in the graph.
13 To select multiple signals, hold down Ctrl and select each signal by clicking
a row. In the Plot column, select a check box. All of the highlighted signals
are now selected for plotting.
14 To create a report of the results, see “Create Simulation Data Inspector
Report” on page 17-32.
Create a View of Multiple Plots
Before creating a view of multiple plots, the Simulation Data Inspector tool
must contain signal data. You can obtain signal data by either recording
simulation data or importing data into the Simulation Data Inspector tool.
17-13
17
Inspecting and Comparing Logged Signal Data
For more information, see “Record Simulation Data” on page 17-5 or “Import
Logged Signal Data” on page 17-7.
1 On the right pane, on the View toolbar, click Show Details.
2 In the View Name column, click the field which displays Default. Type in
a new name for the view. In this example, the name is sldemo_f14_plot4.
3 In the Layout column, click the field that displays 1x1. A plot matrix
opens. To create a view of 4 plots, select the 2x2 matrix.
17-14
Inspect Signal Data
4 To select a plot, click it. The selected plot is outlined in blue.
5 Once a plot is selected, on the left pane in the Signal Browser table, select a
signal in the Plot column to add to the selected plot. In this example, a
signal from Run 1 is displayed in each plot in the sldemo_f14_plot1 view.
17-15
17
Inspecting and Comparing Logged Signal Data
For the selected plot [2,2], the signal or signals are shaded in the Inspect
Signals table to indicate which signals are in the selected plot.
Explore Signal Data in a Multiple Plot View
Linked Plots in a View
Plots within a view can be linked together to enable synchronized panning
and zooming. When you create a view, by default, plots in a view are linked
together. The following toolbar operations synchronize across linked plots:
• Pan along the time axis:
17-16
Inspect Signal Data
• Zoom on the time axis:
• Zoom on the time and data value axis:
• Zoom out:
To determine if a plot in a view is linked, at the top of each plot, locate the
. If a plot is unlinked, the broken link icon
link icon
and the plot pans and zooms independently.
is displayed
Move Signals Between Plots in a View
To move a signal from one plot to another, click and hold a signal (markers
appear).
Drag the signal to another plot, and the signal is now displayed in the other
plot.
For more information on working with plots, see “Modify a Plot in the
Simulation Data Inspector Tool” on page 17-49.
Replace a Run in a View
In this example, the Simulation Data Inspector tool contains three runs of
data. To quickly swap out the data from one run with data from another
run, do the following:
17-17
17
Inspecting and Comparing Logged Signal Data
1 Select a view. In this example, the view is sldemo_f14_plot1.
2 Click Replace runs..., which opens the Replace runs dialog box.
3 To replace the signal data in Run 2 with the signal data from another run,
in the Runs in current view list, select Run 2:
signals in the view are replaced
4 In the Replace with list, select Run 3:
sldemo_f14. Only the
sldemo_f14.
5 To specify how the signal data in Run 2 is replaced with Run 3, expand
Advanced options. In this example, the Simulation Data Inspector first
attempts to align the signals by Data Source, then by Block Path, and
17-18
Inspect Signal Data
lastly by Signal Name. For more information on aligning signals, see “How
the Simulation Data Inspector Tool Aligns Signals” on page 17-35.
6 Click OK. The data from Run 2 is replaced with data from Run 3.
17-19
17
Inspecting and Comparing Logged Signal Data
The View Details table now includes Run 3 instead of Run 2. Run 3 lists
for a signal that
signals from Run 2. The Match column displays a
aligned with a signal in Run 3. If a signal did not align, the Match column
displays a
.
Copy a View in the Inspect Signals Tab
To copy a view:
1 On the right pane, in the View toolbar, click Show Details to open the
View Details table.
17-20
Inspect Signal Data
2 Select the view to copy. Be sure to select the option button next to the
View Name in the table.
3 Click the New view from current button. A new view is displayed in
the View Details table
4 Select the new view, Copy of sldemo_f14_plot4, and rename it.
Delete a View in the Inspect Signals Tab
To delete a view:
1 On the right pane, in the View toolbar, click Show Details to open the
View Details table.
2 In the View Details table, select the view to delete by selecting the
corresponding option button.
3 Click the Delete View button.
17-21
17
Inspecting and Comparing Logged Signal Data
Note The View Details table always includes one view.
Export a View in the Inspect Signals Tab
To export a view to a MAT-file:
1 On the right pane, in the View toolbar, click Show Details to open the
View Details table.
2 Click the Export button and specify a file.
3 This saves the view, but not the data, into a MAT-file. To save the data and
the view, see “Export Results in the Simulation Data Inspector Tool” on
page 17-34.
Import a View in the Inspect Signals Tab
To reload a saved view from a MAT-file:
1 On the right pane, in the View toolbar, click Show Details to open the
View Details table.
2 Click the Import button and specify a file.
Note This only imports the configuration of the view, which is how the
signal data is plotted among the multiple plots. The actual signal data
is not imported.
3 To include signal data in the Simulation Data Inspector tool, you can record
simulation data (see “Record Simulation Data” on page 17-5), or import
data (see “Import Logged Signal Data” on page 17-7).
17-22
Compare Signal Data
Compare Signal Data
In the Simulation Data Inspector tool, you can use the Compare Signals tab
of the Signal Browser table for comparing two signals. To compare two signals:
1 Open the Simulation Data Inspector tool. See “Open the Simulation Data
Inspector Tool” on page 17-39.
2 Record simulation data or import data into the Simulation Data Inspector
tool. See “Record Simulation Data” on page 17-5 or “Import Logged Signal
Data” on page 17-7.
3 If it is not already selected, select the Compare Signals tab. By default,
Signal Browser table on the Compare Signals tab displays a row for each
signal data, organized by simulation runs. For more information, see
“Customize the Simulation Data Inspector Interface” on page 17-38.
4 “Specify the Line Configuration” on page 17-45 for the signals that you
are comparing.
5 In the Sig 1 column, click one signal for plotting. In this column, you can
select only one signal.
6 In the Sig 2 column, click one signal for plotting. In this column, you can
select only one signal.
The Signals graph displays the signal data and the Difference graph
displays the difference and tolerance values.
17-23
17
Inspecting and Comparing Logged Signal Data
For information on manipulating the graphs, see “Customize the
Simulation Data Inspector Interface” on page 17-38.
7 To create a report of the results, see “Create Simulation Data Inspector
Report” on page 17-32.
17-24
Comparison of One Signal From Multiple Simulations
Comparison of One Signal From Multiple Simulations
In the Simulation Data Inspector tool, you can use the Compare Signals tab
to compare the same signal from two different simulation runs. To compare
two data runs for a signal:
1 Open the Simulation Data Inspector tool. See “Open the Simulation Data
Inspector Tool” on page 17-39.
2 Record simulation data or import data for two simulation runs. For more
information, see “Record Simulation Data” on page 17-5 or “Import Logged
Signal Data” on page 17-7.
3 Select the Compare Signals tab. By default, the Signal Browser table on
the Compare Signals tab displays a row for each signal data, organized
by simulation runs. For more information on modifying the Signal Browser
table, see “Customize the Simulation Data Inspector Interface” on page
17-38.
4 “Specify the Line Configuration” on page 17-45 for the signals that you
are comparing.
5 To change the relative tolerance and absolute tolerance, add the Rel
Tol and Abs Tol columns to the Signal Browser table. Double-click the
corresponding fields for a signal and type in a value.
6 In the Sig 1 column, click one signal from the first simulation run for
plotting. In this column, you can select only one signal.
7 In the Sig 2 column, click a signal from another simulation run for plotting.
In this column, you can select only one signal.
17-25
17
Inspecting and Comparing Logged Signal Data
Once two signals are selected, the Signals graph displays the signal data
and the Difference graph displays the difference and tolerance values.
17-26
Comparison of One Signal From Multiple Simulations
For information on manipulating the graphs, see “Customize the
Simulation Data Inspector Interface” on page 17-38.
8 To create a report of the results, see “Create Simulation Data Inspector
Report” on page 17-32.
17-27
17
Inspecting and Comparing Logged Signal Data
Compare All Logged Signal Data From Multiple Simulations
In the Simulation Data Inspector tool, you can use the Compare Runs tab
to compare all signal data from two different simulation runs. To compare
two runs:
1 Open the Simulation Data Inspector tool. See “Open the Simulation Data
Inspector Tool” on page 17-39.
2 Record simulation data or import data from multiple simulation runs, for
more information, see “Record Simulation Data” on page 17-5 or “Import
Logged Signal Data” on page 17-7.
3 Select the Compare Runs tab.
4 From the Run 1 and Run 2 drop-down lists, select two different runs.
Note The number in a column name indicates the run number. For
example, Abs Tol 1 refers to the absolute tolerance values for signals of
the run specified for Run 1. Abs Tol 2 refers to the absolute tolerance
values for signals of the run specified for Run 2.
5 Select the Options button to specify the signal alignment.
17-28
Compare All Logged Signal Data From Multiple Simulations
The Simulation Data Inspector aligns signals according to Align By and
Then By parameters. For more information on signal alignment, see “How
the Simulation Data Inspector Tool Aligns Signals” on page 17-35.
6 Click the Compare button. The Comparison Results table lists all signals
from Run 1 with a result. In this example, the comparison results of the
aligned signals did not match.
The Simulation Data Inspector only compares signals from Run 1 that are
aligned with a signal from Run 2. If a signal from Run 1 did not align with
a signal from Run 2, then the Run 1 signal is listed in the Comparison
Results table with a warning
.
7 To modify the relative tolerance and absolute tolerance, add the Abs Tol 1
column to the Signal Browser table. Double-click the corresponding fields
for a signal and type in a value.
17-29
17
Inspecting and Comparing Logged Signal Data
Note Tolerances specified in the other tab views do not carry over to the
Compare Runs tab.
8 To see a signal that is within the acceptable tolerance across two simulation
runs, set the absolute tolerance in column Abs Tol 1 to .35.
9 To plot a signal, in the plot column select the option button for
sldemo_f14/Pilot G-force calculation. The Signals graph displays
the signal data for the two runs. The Difference graph displays the
difference and tolerance values.
17-30
Compare All Logged Signal Data From Multiple Simulations
For information on manipulating the graph, see “Customize the Simulation
Data Inspector Interface” on page 17-38.
10 To create a report of the results, see “Create Simulation Data Inspector
Report” on page 17-32.
17-31
17
Inspecting and Comparing Logged Signal Data
Create Simulation Data Inspector Report
To create a report of the current view and data in the Simulation Data
Inspector:
1 In the Menu Bar, select File > Generate Report. The Report Setup
dialog box opens.
2 In the Include in report section, specify which tab to include in the report.
For the Compare Runs tab, you can select Report only mismatched
signals only to shorten the report or select Report all signals which
includes all logged signals in the designated runs.
3 Specify the File name and Folder, or use the default.
17-32
Create Simulation Data Inspector Report
4 Optionally, select If report exists, increment file name to prevent
overwriting, which appends and increments a number to the file name of
the report to preserve earlier versions of the report file.
5 Optionally, select Display partial block path
(modelname/.../blockname), which shortens the block path string
generated for the report.
6 Click Generate. The report opens automatically.
17-33
17
Inspecting and Comparing Logged Signal Data
Export Results in the Simulation Data Inspector Tool
The Simulation Data Inspector tool provides the capability to save data
collected by the tool to a MAT-file that you can later reload. The format of
the MAT-file is different from the format of a MAT-file created from the
base workspace.
Save Data to a MAT-File
To save signal data and views to a MAT-File, do the following:
1 Click Save or select File > Save.
2 Type the name of the file.
3 Click OK. Your data and views are now saved in a MAT-file that you can
load back into the Simulation Data Inspector.
17-34
How the Simulation Data Inspector Tool Aligns Signals
How the Simulation Data Inspector Tool Aligns Signals
When the Simulation Data Inspector tool aligns signals across simulation
runs, it attempts to match signals between runs by using metadata stored
for each signal. You can specify the metadata used to align signals. The
metadata options are: Data Source, Path, SID, and Signal Name. By default,
the Simulation Data Inspector tool is configured to first align signals by Data
Source, then by Path, and then by Signal Name.
To modify the signal alignment specifications see “Inspect Signals: Aligning
Signals for Replacing a Run” on page 17-35 or “Compare Runs: Aligning
Signals for Comparing Signal Data” on page 17-36.
Inspect Signals: Aligning Signals for Replacing a Run
To modify how signals are aligned on the Inspect Signals tab, do the
following:
1 Click the Inspect Signals tab.
2 On the right pane, click Show details.
3 Click the Replace runs... button. The Replace Runs dialog opens.
4 Select Advanced options, which displays the Align By and Then By
parameters.
5 Specify the Align By and Then By parameters from the drop-down lists.
When replacing a run, the Simulation Data Inspector tool attempts to align
only the signals selected in the current view. Once those signals are aligned,
in the view, the aligned signal data from the first run is replaced with signal
data from another run. The View Details table displays the signals from
the replaced run as follows:
17-35
17
Inspecting and Comparing Logged Signal Data
Status
Result
• Signal aligned
• Signal data is replaced in the view
Signal not aligned
Compare Runs: Aligning Signals for Comparing
Signal Data
To modify how signals are aligned on the Compare Runs tab, do the
following:
1 Click the Compare Runs tab.
2 Select the Options button, which displays the Align By and Then By
parameters.
3 Specify the Align By and Then By parameters from the drop-down lists.
4 Click Compare, to align the signal data and compare the aligned signal
data.
After signals are aligned from Run 1 with signals from Run 2, the Simulation
Data Inspector tool compares only the aligned signals. The Comparison
Results table displays the results of all signals from Run 1 as follows:
Status
Comparison Result
• Signal aligned
• Signal data from two runs
matched within the tolerance
• Signal aligned
• Signal data from two runs did not
match within the tolerance
Signal from Run 1 did not align with
a signal from Run 2
17-36
How the Simulation Data Inspector Tool Compares Time Series Data
How the Simulation Data Inspector Tool Compares Time
Series Data
To compare time series data, the Simulation Data Inspector:
1 Converts Simulink time series data to MATLAB time series data.
2 Aligns the time vectors using the default synchronization method union.
To change the synchronization method for a signal, add the Sync Method
column to the Signal Browser table and choose a method.
3 Aligns the data vectors using the default interpolation method, zoh
(zero-order hold). To change the interpolation method for a signal, add the
Interp Method column to the Signal Browser table and choose a method.
4 Differences the data.
5 Applies the specified tolerances for plotting the Difference . For more
information, see “How Tolerances Are Applied” on page 17-37.
How Tolerances Are Applied
The default values for the relative tolerance and absolute tolerance for a
signal is 0. If you specify tolerances, then the Simulation Data Inspector tool
calculates the tolerances as follows:
tolerance = max(absoluteTolerance, relativeTolerance*abs(baselineData));
To change the relative tolerance and absolute tolerance, add the Rel Tol and
Abs Tol columns to the Signal Browser table. Double-click the corresponding
fields for a signal and type in a value.
17-37
17
Inspecting and Comparing Logged Signal Data
Customize the Simulation Data Inspector Interface
Overview
The Simulation Data Inspector tool provides the capability to inspect and
compare time series data. There are several methods for launching the
Simulation Data Inspector tool, see “Open the Simulation Data Inspector
Tool” on page 17-39 to choose the method that best supports your workflow.
The Simulation Data Inspector tool appears as follows,
The Simulation Data Inspector Window includes the following elements:
• Menu Bar
• “Toolbar” on page 17-51
• Three tabs: Inspect Signals, Compare Signals, and Compare Runs
The Signal Browser table appears on the three tabs: Inspect Signals,
Compare Signals, and Compare Runs. You can customize the information
displayed in the Signal Browser table by performing the following tasks:
17-38
Customize the Simulation Data Inspector Interface
• “Add/Delete a Column in the Signal Browser Table” on page 17-40
• “Modify Grouping in Signal Browser Table” on page 17-42
• “Rename a Run” on page 17-44
• “Select a Run or Signal Option in the Signal Browser Table” on page 17-46
• “Display Run Properties” on page 17-49
The Plot View displays in the right pane of the Simulation Data Inspector
tool. To modify a plot, refer to the following:
• “Specify the Line Configuration” on page 17-45
• “Modify a Plot in the Simulation Data Inspector Tool” on page 17-49
Open the Simulation Data Inspector Tool
To launch the Simulation Data Inspector tool, choose one of the following
methods:
• MATLAB command-line: Enter
Simulink.sdi.view
• Simulink Editor: Click the Record button arrow.
Select Simulation Data Inspector from the list.
Why Is the Simulation Data Inspector Tool Empty?
There are several methods for populating the Simulation Data Inspector
with data.
• If you are using the record button to simulate and record data, you must
specify your model to export signals. For more information, see:
-
“Export Simulation Data” on page 45-4
“Export Signal Data Using Signal Logging” on page 45-19
17-39
17
Inspecting and Comparing Logged Signal Data
After your model is configured to export signal data, see “Record Simulation
Data” on page 17-5.
• If you want to view previously logged signal data, see “Import Logged
Signal Data” on page 17-7.
For a list of Simulink data export formats that are not supported in the
Simulation Data Inspector, see “Limitations of the Simulation Data Inspector
Tool” on page 17-54.
Add/Delete a Column in the Signal Browser Table
To add or remove a column, right-click the Signal Browser table title bar.
Select Columns and click an option on the list. The column is displayed in
the table.
17-40
Customize the Simulation Data Inspector Interface
Column Options for the Inspect Signals and Compare Signals Tabs
Column Option
Value
Run
Name of a simulation run
Block Path
Path to the source block for the
signal
Block Name
Name of the source block
Line
Line style
Absolute Tolerance
Positive number (user-specified)
Relative Tolerance
Positive number (user-specified)
Synchronization Method
Method to align time vector:
union, intersection, uniform
(user-specified)
Interpolation Method
Method to align data: zoh, linear
(user-specified)
Data Source
Name for the data
(logsout.Stick.Data)
Model
Model name for the signal data
Signal
Signal name for the data (Stick)
Time Series Root
String signifying the name of
the Simulink.Timeseries object
(logsout.Stick.Time)
Time Source
String signifying the array
containing the time data
(logsout.Stick.Time)
Port
Index of the output port that emits
the signal logged
Dimensions
Number of dimensions of the signal
Channel
Channel of matrix data
17-41
17
Inspecting and Comparing Logged Signal Data
Column Options for Compare Runs Tab
Column Option
Value
Result
Result of the comparison for the
signal across the specified runs
Block Path
• Run 1: Block Path
• Run 2: Block Path
Data Source
String identifying the data source
• Run 1: Data Source
• Run 2: Data Source
SID
“Simulink Identifier”
• Run 1: SID
• Run 2: SID
Absolute Tolerance
Positive number (user-specified)
Relative Tolerance
Positive number (user specified)
Synchronization Method
Method to align time vector:
union, intersection, uniform
(user-specified)
Interpolation Method
Method to align data: zoh, linear
(user-specified)
Channel 1
Channel of matrix data
After selecting a column option, the new column is added to the table in the
order that it appears in the options list.
Modify Grouping in Signal Browser Table
You can customize the organization of your logged data in the Signal Browser
table. By default, data is first organized by run. You can then organize your
data by model hierarchy, logged variable, or no hierarchy.
If your model contains referenced models to view, you can group your data by
model hierarchy and then by the logged variables. To change the grouping
in the Signal Browser table:
17-42
Customize the Simulation Data Inspector Interface
1 Right-click the Signal Browser table and select Group Signals.
2 In the Group Signals dialog box, in the first Then By list, select Model
Hierarchy.
3 In the second Then By list, select Logged Variable.
4 Click OK. The Signal Browser table groups the signal data by model and
then by the logged variables.
17-43
17
Inspecting and Comparing Logged Signal Data
To remove the hierarchy and display a simple list of logged signals, you can
select None in the Group Signals dialog box.
Rename a Run
To rename a run name:
1 If the Signal Browser table is not grouped by run, right-click the table and
in the menu select Group By > Run.
2 Double-click the Run row.
17-44
Customize the Simulation Data Inspector Interface
3 Type the new run name and press Enter.
Specify the Line Configuration
1 Click in the Line column of a signal and click the down arrow. The Line
dialog box opens.
17-45
17
Inspecting and Comparing Logged Signal Data
2 Specify the color, Line Style, and Marker for the signal.
3 Click OK.
Select a Run or Signal Option in the Signal Browser
Table
In the Signal Browser table, right-click a run or signal for a menu list of
options.
17-46
Customize the Simulation Data Inspector Interface
To...
Select...
Display the list of Column options.
See Column Options for the Inspect
Signals and Compare Signals Tabs
on page 17-41
Columns
Group signal data by the specified
options: Run, Block Path, Data
Source, Model, and Signal Name
(this option does not appear in the
Compare Runs tab)
Group By
Highlight the source of the selected
signal in the model diagram
Highlight signal source in model
Open the Variable Editor and
display the selected signal data
Export signal to variable editor
Save signal data in the run to the
base workspace
Export run to base workspace
17-47
17
Inspecting and Comparing Logged Signal Data
To...
Select...
Delete the highlighted signal in the
Signal Browser table (this option
does not appear in the Compare
Runs tab)
Delete
Display the signal properties of the
selected signal
Properties
The Signal Properties dialog box displays the following signal information.
17-48
Customize the Simulation Data Inspector Interface
Display Run Properties
In the Signal Browser table, right-click a run name to view a list of options. To
open the Run Properties dialog box, from the options list, select Properties.
Modify a Plot in the Simulation Data Inspector Tool
To modify a plot, you can:
• Toolbar: Select icons to zoom into data, move the plot, or add a data
point to the plot. For more information on these icons, see the “Toolbar”
on page 17-51 section.
• Plot options: Click
the data.
on the plot to select alternatives for plotting
17-49
17
Inspecting and Comparing Logged Signal Data
To...
Simulation Data Inspector...
Original Axes
Plots the data according to the
maximum and minimum values of
the data points. (default)
Normalized Axes
Normalizes the data for each signal
from 1 to 1 along the y-axis. If the
data is already within that range,
the data is displayed as a constant
at 1.
Stairstep
Plots the data as a stairstep plot.
(default)
Line
Interpolates the data points and
produces a linear plot.
Plot in New Figure
Launches the graph in a MATLAB
figure window.
on the plot and select Plot in New Figure. The
• New figure: Click
plot opens in a new figure window.
17-50
Customize the Simulation Data Inspector Interface
For more information on plotting and customizing your data plots using
the GUI tools, see “Figures, Plots, and Graphs”.
To view an example, see “Create, Save, and Print a Figure”.
Toolbar
The toolbar contains the following command buttons.
17-51
17
17-52
Inspecting and Comparing Logged Signal Data
To...
Click...
Clear the Simulation Data Inspector of all
data.
New
Open a MAT-file previously saved from the
Simulation Data Inspector.
Open
Save data in Simulation Data Inspector to
a MAT-file.
Save
Launches the Data Import tool.
Import Data
Zoom in along the time axis. After selecting
the icon, on the graph, click and hold the left
mouse button and drag the mouse to select
an area to enlarge.
Zoom in T
Zoom in along the data value axis. After
selecting the icon, on the graph, click and
hold the left mouse button and drag the
mouse to select an area to enlarge.
Zoom in T
Zoom in on a section of the graph along both
axes. After selecting the icon, on the graph,
click and hold the left mouse button, and
drag the mouse to select an area to enlarge.
Zoom in T and Y
Zoom out from the graph. After selecting
the icon, click the graph to incrementally
zoom out.
Zoom Out
Fit the plot to the graph. After selecting the
icon, click the graph to enlarge the plot to
fill the graph.
Fit to View
Customize the Simulation Data Inspector Interface
To...
Click...
Move the plot in the graph up, down, left, or
right. After selecting the icon, on the graph,
click and hold the left mouse button and
move the mouse to the area of the graph
that you want to view.
Pan
Display the T and Y values of a data point
in the plot. After selecting the icon, click a
point on the line to view a data point.
Data Cursor
17-53
17
Inspecting and Comparing Logged Signal Data
Limitations of the Simulation Data Inspector Tool
The following Simulink data export formats are not supported if time is not
logged:
• Structure
• Array
The following Simulink data types are not supported:
• Complex data, int64 and unit64
• Enumerated data types
The Simulation Data Inspector tool supports up to 3–dimensional time series
data.
17-54
Record and Inspect Signal Data Programmatically
Record and Inspect Signal Data Programmatically
Overview
Using the Simulation Data Inspector API, you can plot signal data, compare
two signals, and compare two simulation runs of data. You can use the
Simulink.sdi.createRun function to add simulation output data to the
Simulation Data Inspector. Once the Simulation Data Inspector contains
signal data, you can perform the following tasks:
To...
Use...
View signal data, open the
Simulation Data Inspector tool
Simulink.sdi.view
Compare the data of two signals
Simulink.sdi.compareSignals
Compare the output of two
simulation runs
Simulink.sdi.compareRuns
Run Management
Simulation Data Inspector software creates and manages a list of simulation
runs. Each run is an instance of a Simulink.sdi.Run object. This object
contains all of the simulation data and metadata for that simulation run.
To...
Use...
Get the number of runs currently in
the Simulation Data Inspector
Simulink.sdi.getRunCount
Get the run ID from the list of
simulation runs in the Simulation
Data Inspector
Simulink.sdi.getRunIDByIndex
Determine if a run ID corresponds
to a run currently in the Simulation
Data Inspector
Simulink.sdi.isValidRunID
Add more data to a run currently in
the Simulation Data Inspector
Simulink.sdi.addToRun
17-55
17
Inspecting and Comparing Logged Signal Data
To...
Use...
Make a copy of a run currently in the
Simulation Data Inspector
Simulink.sdi.copyRun
Delete a run from the Simulation
Data Inspector
Simulink.sdi.deleteRun
Get simulation data for a run in the
Simulation Data Inspector
Simulink.sdi.getRun
Manages output signal data and
metadata of a simulation run
Simulink.sdi.Run class
Get the Simulink.sdi.Signal object
corresponding to the given signal ID
Simulink.sdi.Run.getSignal method
Get the Simulink.sdi.Signal object
corresponding to the index into the
array signals in the run
Simulink.sdi.Run.getSignalByIndex
method
Get the signal ID corresponding to
the index into the array signals in
the run
Simulink.sdi.Run.getSignalIDByIndex
method
Determine if a signal ID corresponds
to a signal currently in the run
Simulink.sdi.Run.isValidSignalID
method
Signal Management
Each Simulink.sdi.Run object contains a Simulink.sdi.Signal object for each
output signal data. This object contains all of the simulation data for the
signal and its metadata.
17-56
To...
Use...
Get the simulation data and
metadata for a signal from one
simulation run.
Simulink.sdi.getSignal
Manages a signal’s time series data
and metadata for one simulation
run.
Simulink.sdi.Signal class
Record and Inspect Signal Data Programmatically
Import/Export Data
To...
Use...
Save signal data currently in the
Simulation Data Inspector
Simulink.sdi.save
Load previously saved Simulation
Data Inspector session
Simulink.sdi.load
Clear all data from the Simulation
Data Inspector
Simulink.sdi.clear
Comparison Results
To...
Use...
Manage the results of
comparing two runs
(Simulink.sdi.compareRuns creates
the Simulink.sdi.DiffRunResult
object)
Simulink.sdi.DiffRunResult class
Manage the results of
comparing two signals (
Simulink.sdi.compareSignals
creates the
Simulink.sdi.DiffSignalResult class
Simulink.sdi.DiffSignalResult
object)
Create a Run in the Simulation Data Inspector
To populate the Simulation Data Inspector with runs of simulation data,
you must first simulate your model and then call Simulink.sdi.createRun.
When using the API, the Simulation Data Inspector does not automatically
record simulation data. To create a run of simulation data, you can use the
following code:
% Open the model 'sldemo_f14'
load_system('sldemo_f14');
17-57
17
Inspecting and Comparing Logged Signal Data
% Configure model "sldemo_f14" for logging and simulate
simOut = sim('sldemo_f14', 'SaveOutput','on', ...
'SaveFormat', 'StructureWithTime', ...
'ReturnWorkspaceOutputs', 'on');
% Create a Simulation Data Inspector run
[runID,runIndex,signalIDs] = Simulink.sdi.createRun('My Run',...
'namevalue',{'MyData'},{simOut});
Compare Signal Data
To compare the simulation data for two signals, you can use the following code:
% Configure model "f14" for logging and simulate
simOut = sim('sldemo_f14', 'SaveOutput','on', ...
'SaveFormat', 'StructureWithTime', ...
'ReturnWorkspaceOutputs','on');
% Create a Simulation Data Inspector run and get signal IDs
[~, ~, signalIDs] = Simulink.sdi.createRun('My Run', ...
'namevalue', {'MyData'}, {simOut});
sig1 = signalIDs(1);
sig2 = signalIDs(2);
% Compare two signals, which returns the results in an instance of
% Simulink.sdi.diffSignalResult
diff = Simulink.sdi.compareSignals(sig1, sig2);
% Find if the signal data match
match = diff.match;
% Get the tolerance used in Simulink.sdi.compareSignals
tolerance = diff.tol;
Compare Runs of Simulation Data
To compare the signal data between two simulation runs, you can use the
following code:
% Configure model "sldemo_f14" for logging and simulate
set_param('sldemo_f14/Pilot','WaveForm','square');
17-58
Record and Inspect Signal Data Programmatically
simOut = sim('sldemo_f14', 'SaveOutput','on', ...
'SaveFormat', 'StructureWithTime', ...
'ReturnWorkspaceOutputs', 'on');
% Create a Simulation Data Inspector run, Simulink.sdi.Run, from
% simOut in the base workspace
runID1 = Simulink.sdi.createRun('First Run','namevalue',{'simOut'},...
{simOut});
% Simulate again
set_param('sldemo_f14/Pilot','WaveForm','sawtooth');
simOut = sim('sldemo_f14', 'SaveOutput','on', ...
'SaveFormat', 'StructureWithTime', ...
'ReturnWorkspaceOutputs', 'on');
% Create another Simulation Data Inspector run
runID2 = Simulink.sdi.createRun('Second Run','namevalue',{'simOut'},...
{simOut});
% Compare two runs, the result is stored in a
% Simulink.sdi.DiffRunResult object
difference = Simulink.sdi.compareRuns(runID1, runID2);
% Number of comparisons in result
numComparisons = difference.count;
% Iterate through each result element
for i = 1:numComparisons
% Get signal result at index i
signalResult = difference.getResultByIndex(i);
% Get signal IDs for each comparison result
sig1 = signalResult.signalID1;
sig2 = signalResult.signalID2;
% Display if signals match or not
displayStr = 'Signals with IDs %d and %d %s \n';
if signalResult.match
fprintf(displayStr, sig1, sig2, 'match');
else
17-59
17
Inspecting and Comparing Logged Signal Data
fprintf(displayStr, sig1, sig2, 'do not match');
end
end
Record Data During Parallel Simulations
To record and view the results from parallel simulations, use the following
methods to get and set the location of the Simulation Data Inspector
repository:
• Simulink.sdi.getSource
• Simulink.sdi.setSource
• Simulink.sdi.refresh
This example shows how to run multiple simulations in a parfor loop and
record each run in the Simulation Data Inspector tool.
Open the Simulation Data Inspector.
Simulink.sdi.view;
Load the model.
mdl = 'sldemo_f14';
load_system(mdl);
Get the location of the simulation data repository.
src = Simulink.sdi.getSource();
Open MATLAB pool with 4 workers.
matlabpool(4);
Run the simulation in a parfor loop.
parfor i=1:4
% Set the location of the simulation data repository of this
% worker to be the same for aggregating the data
Simulink.sdi.setSource(src);
% Run the simulation
17-60
Record and Inspect Signal Data Programmatically
simOut = sim(mdl,'SaveOutput','on',...
'SaveFormat','StructureWithTime',...
'ReturnWorkspaceOutputs','on');
% Create a simulation run in the Simulink Data Inspector
Simulink.sdi.createRun(['Run' num2str(i)],'namevalue',...
{'simout'},{simOut});
end
Close the MATLAB pool and all of the models.
matlabpool close;
bdclose all;
Refresh the Simulation Data Inspector
Simulink.sdi.refresh();
17-61
17
17-62
Inspecting and Comparing Logged Signal Data
18
Analyzing Simulation
Results
• “Viewing Output Trajectories” on page 18-2
• “Linearizing Models” on page 18-5
• “Finding Steady-State Points” on page 18-11
18
Analyzing Simulation Results
Viewing Output Trajectories
In this section...
“Viewing and Exporting Simulation Data” on page 18-2
“Using the Scope Block” on page 18-2
“Using Return Variables” on page 18-3
“Using the To Workspace Block” on page 18-3
“Using the Simulation Data Inspector Tool” on page 18-4
Viewing and Exporting Simulation Data
You can use several approaches to view output trajectories. Some approaches
display output trajectories during simulation. Other approaches export signal
values to the MATLAB workspace during simulation for later retrieval and
analysis.
The following sections describe several approaches for viewing output
trajectories. For additional information about exporting simulation data, see
“Export Simulation Data” on page 45-4.
Using the Scope Block
You can display output trajectories on a Scope block during simulation as
illustrated by the following model.
The display on the Scope shows the output trajectory. The Scope block enables
you to zoom in on an area of interest or save the data to the workspace.
The XY Graph block enables you to plot one signal against another.
18-2
Viewing Output Trajectories
Using Return Variables
By returning time and output histories, you can use the plotting commands
provided in the MATLAB software to display and annotate the output
trajectories.
The block labeled Out is an Outport block from the Ports & Subsystems
library. The output trajectory, yout, is returned by the integration solver. For
more information, see “Data Import/Export Pane”.
You can also run this simulation from the Simulation menu by specifying
variables for the time, output, and states on the Data Import/Export pane
of the Configuration Parameters dialog box. You can then plot these results
using
plot(tout,yout)
Using the To Workspace Block
The To Workspace block can be used to return output trajectories to the
workspace. The following model illustrates this use:
The variables y and t appear in the workspace when the simulation is
complete. You store the time vector by feeding a Clock block into a To
18-3
18
Analyzing Simulation Results
Workspace block. You can also acquire the time vector by entering a variable
name for the time on the Data Import/Export pane of the Configuration
Parameters dialog box, for menu-driven simulations, or by returning it using
the sim command (see “Data Import/Export Pane” for more information).
The To Workspace block can accept an array input, with each input element’s
trajectory stored in the resulting workspace variable.
Using the Simulation Data Inspector Tool
By configuring your model to log signal data to the base workspace, you
can view the output in the Simulation Data Inspector tool. On the Data
Import/Export pane of the Configuration Parameters dialog box
Select the following parameters:
• Time: enable
• States: enable
• Output: enable
• Signal logging: enable
• Format: specify Structure with time
For more information on the Simulation Data Inspector tool, see “Inspect
Signal Data with Simulation Data Inspector” on page 17-2.
18-4
Linearizing Models
Linearizing Models
In this section...
“About Linearizing Models” on page 18-5
“Linearization with Referenced Models” on page 18-7
“Linearization Using the ’v5’ Algorithm” on page 18-9
About Linearizing Models
The Simulink product provides the linmod, linmod2, and dlinmod functions to
extract linear models in the form of the state-space matrices A, B, C, and D.
State-space matrices describe the linear input-output relationship as
x = Ax + Bu
y = Cx + Du,
where x, u, and y are state, input, and output vectors, respectively. For
example, the following model is called lmod.
18-5
18
Analyzing Simulation Results
To extract the linear model of this system, enter this command.
[A,B,C,D] = linmod('lmod')
A =
-2
1
0
-1
0
1
-1
0
-1
1
0
0
-1
B =
1
0
0
C =
0
0
D =
0
1
Inputs and outputs must be defined using Inport and Outport blocks from the
Ports & Subsystems library. Source and sink blocks do not act as inputs and
outputs. Inport blocks can be used in conjunction with source blocks, using
a Sum block. Once the data is in the state-space form or converted to an
LTI object, you can apply functions in the Control System Toolbox product
for further analysis:
• Conversion to an LTI object
sys = ss(A,B,C,D);
• Bode phase and magnitude frequency plot
bode(A,B,C,D) or bode(sys)
• Linearized time response
step(A,B,C,D) or step(sys)
impulse(A,B,C,D) or impulse(sys)
lsim(A,B,C,D,u,t) or lsim(sys,u,t)
18-6
Linearizing Models
You can use other functions in the Control System Toolbox and the Robust
Control Toolbox™ products for linear control system design.
When the model is nonlinear, an operating point can be chosen at which
to extract the linearized model. Extra arguments to linmod specify the
operating point.
[A,B,C,D] = linmod('sys', x, u)
For discrete systems or mixed continuous and discrete systems, use the
function dlinmod for linearization. This function has the same calling syntax
as linmod except that the second right-hand argument must contain a sample
time at which to perform the linearization.
Linearization with Referenced Models
You can use linmod to extract a linear model from a Simulink environment
that contains Model blocks.
Note In Normal mode, the linmod command applies the block-by-block
linearization algorithm on blocks inside the referenced model. If the
Model block is in Accelerator mode, the linmod command uses numerical
perturbation to linearize the referenced model. Due to limitations on
linearizing multirate Model blocks in Accelerator mode, you should use
Normal mode simulation for all models referenced by Model blocks when
linearizing with referenced models. For an explanation of the block-by-block
linearization algorithm, see the Simulink Control Design™ documentation.
For example, consider the f14 model mdlref_f14. The Aircraft Dynamics
Model block refers to the model mdlref_dynamics.
18-7
18
Analyzing Simulation Results
To linearize the mdlref_f14 model, call the linmod command on the top
mdlref_f14 model as follows.
[A,B,C,D] = linmod('mdlref_f14')
The resulting state-space model corresponds to the complete f14 model,
including the referenced model.
You can call linmod with a state and input operating point for models that
contain Model blocks. When using operating points, the state vector x refers
to the total state vector for the top model and any referenced models. You
18-8
Linearizing Models
must enter the state vector using the structure format. To get the complete
state vector, call
x = Simulink.BlockDiagram.getInitialState(topModelName)
Linearization Using the ’v5’ Algorithm
Calling the linmod command with the 'v5' argument invokes the
perturbation algorithm created prior to MATLAB software version 5.3. This
algorithm also allows you to specify the perturbation values used to perform
the perturbation of all the states and inputs of the model.
[A,B,C,D]=linmod('sys',x,u,para,xpert,upert,'v5')
Using linmod with the 'v5' option to linearize a model that contains
Derivative or Transport Delay blocks can be troublesome. Before linearizing,
replace these blocks with specially designed blocks that avoid the problems.
These blocks are in the Simulink Extras library in the Linearization
sublibrary.
You access the Extras library by opening the Blocksets & Toolboxes icon:
• For the Derivative block, use the Switched derivative for linearization.
• For the Transport Delay block, use the Switched transport delay for
linearization. (Using this block requires that you have the Control System
Toolbox product.)
When using a Derivative block, you can also try to incorporate the derivative
term in other blocks. For example, if you have a Derivative block in series
with a Transfer Fcn block, it is better implemented (although this is not
always possible) with a single Transfer Fcn block of the form
s
.
s+ a
In this example, the blocks on the left of this figure can be replaced by the
block on the right.
18-9
18
18-10
Analyzing Simulation Results
Finding Steady-State Points
Finding Steady-State Points
The Simulink trim function uses a model to determine steady-state points of
a dynamic system that satisfy input, output, and state conditions that you
specify. Consider, for example, this model, called ex_lmod.
You can use the trim function to find the values of the input and the states
that set both outputs to 1. First, make initial guesses for the state variables
(x) and input values (u), then set the desired value for the output (y).
x = [0; 0; 0];
u = 0;
y = [1; 1];
Use index variables to indicate which variables are fixed and which can vary.
ix = [];
iu = [];
iy = [1;2];
% Don't fix any of the states
% Don't fix the input
% Fix both output 1 and output 2
18-11
18
Analyzing Simulation Results
Invoking trim returns the solution. Your results might differ because of
roundoff error.
[x,u,y,dx] = trim('lmod',x,u,y,ix,iu,iy)
x =
0.0000
1.0000
1.0000
u =
2
y =
1.0000
1.0000
dx =
1.0e-015 *
-0.2220
-0.0227
0.3331
Note that there might be no solution to equilibrium point problems. If that
is the case, trim returns a solution that minimizes the maximum deviation
from the desired result after first trying to set the derivatives to zero. For a
description of the trim syntax, see trim.
18-12
19
Improving Simulation
Performance and Accuracy
• “About Improving Performance and Accuracy” on page 19-2
• “Speed Up Simulation” on page 19-3
• “Comparing Performance” on page 19-5
• “Improve Acceleration Mode Performance” on page 19-9
• “Improve Simulation Accuracy” on page 19-11
19
Improving Simulation Performance and Accuracy
About Improving Performance and Accuracy
Simulation performance and accuracy can be affected by many things,
including the model design and choice of configuration parameters.
The solvers handle most model simulations accurately and efficiently with
their default parameter values. However, some models yield better results
if you adjust solver parameters. Also, if you know information about your
model’s behavior, your simulation results can be improved if you provide
this information to the solver.
19-2
Speed Up Simulation
Speed Up Simulation
Slow simulation speed can have many causes. Here are a few:
• Your model includes an Interpreted MATLAB Function block. When a
model includes an Interpreted MATLAB Function block, the MATLAB
interpreter is called at each time step, drastically slowing down the
simulation. Use the built-in Fcn block or the Math Function block
whenever possible.
• Your model includes a MATLAB file S-function. MATLAB file S-functions
also cause the MATLAB interpreter to be called at each time step.
Consider either converting the S-function to a subsystem or to a C-MEX file
S-function.
• Your model includes a Memory block. Using a Memory block causes the
variable-order solvers (ode15s and ode113) to be reset back to order 1 at
each time step.
• The maximum step size is too small. If you changed the maximum step
size, try running the simulation again with the default value (auto).
• Did you ask for too much accuracy? The default relative tolerance (0.1%
accuracy) is usually sufficient. For models with states that go to zero, if
the absolute tolerance parameter is too small, the simulation can take too
many steps around the near-zero state values. See the discussion of error
in “Maximum order”.
• The time scale might be too long. Reduce the time interval.
• The problem might be stiff, but you are using a nonstiff solver. Try using
ode15s.
• The model uses sample times that are not multiples of each other. Mixing
sample times that are not multiples of each other causes the solver to take
small enough steps to ensure sample time hits for all sample times.
• The model contains an algebraic loop. The solutions to algebraic loops are
iteratively computed at every time step. Therefore, they severely degrade
performance. For more information, see “Algebraic Loops” on page 3-39.
• Your model feeds a Random Number block into an Integrator block. For
continuous systems, use the Band-Limited White Noise block in the
Sources library.
19-3
19
Improving Simulation Performance and Accuracy
• Your model contains a scope viewer that displays a large number of
data points. Try adjusting the viewer parameter settings that can
affect performance. For more information, see “Parameter Settings and
Performance with Scope Signal Viewer” on page 16-20.
19-4
Comparing Performance
Comparing Performance
In this section...
“Performance of the Simulation Modes” on page 19-5
“Measure Performance” on page 19-7
Performance of the Simulation Modes
The Accelerator and Rapid Accelerator modes give the best speed
improvement compared to Normal mode when simulation execution time
exceeds the time required for code generation. For this reason, the Accelerator
and Rapid Accelerator modes generally perform better than Normal mode
when simulation execution times are several minutes or more. However,
models with a significant number of Stateflow or MATLAB Function blocks
might show only a small speed improvement over Normal mode because in
Normal mode these blocks also simulate through code generation.
Including tunable parameters in your model can also increase the simulation
time.
The figure shows in general terms the performance of a hypothetical model
simulated in Normal, Accelerator, and Rapid Accelerator modes.
19-5
19
Improving Simulation Performance and Accuracy
Normal
Accelerator
Rapid Accelerator
minutes
all targets
out of date
Elapsed Time
Normal
Accelerator
seconds
Rapid Accelerator
all targets
up to date
Simulation Stop Time or Number of Major Time Steps
Performance When the Target Must Be Rebuilt
The solid lines in the figure show performance when the target code must be
rebuilt (“all targets out of date”). For this hypothetical model, the time scale
is on the order of minutes, but it could be longer for more complex models.
As generalized in the figure, the time required to compile the model in Normal
mode is less than the time required to build either the Accelerator target or
Rapid Accelerator executable. It is evident from the figure that for small
simulation stop times Normal mode results in quicker overall simulation
times than either Accelerator mode or Rapid Accelerator mode.
The crossover point where Accelerator mode or Rapid Accelerator mode result
in faster execution times depends on the complexity and content of your
model. For instance, those models running in Accelerator mode containing
19-6
Comparing Performance
large numbers of blocks using interpreted code (see “Select Blocks for
Accelerator Mode” on page 22-16) might not run much faster than they would
in Normal mode unless the simulation stop time is very large. Similarly,
models with a large number of Stateflow Chart blocks or MATLAB Function
blocks might not show much speed improvement over Normal mode unless
the simulation stop times are long.
For illustration purposes, the graphic represents a model with a large number
of Stateflow Chart blocks or MATLAB Function blocks. The curve labeled
“Normal” would have much smaller initial elapsed time than shown if the
model did not contain these blocks.
Performance When the Targets Are Up to Date
As shown by the broken lines in the figure (“all targets up to date”) the time
for the Simulink software to determine if the Accelerator target or the Rapid
Accelerator executable are up to date is significantly less than the time
required to generate code (“all targets out of date”). You can take advantage
of this characteristic when you wish to test various design tradeoffs.
For instance, you can generate the Accelerator mode target code once and use
it to simulate your model with a series of gain settings. This is an especially
efficient way to use the Accelerator or Rapid Accelerator modes because this
type of change does not result in the target code being regenerated. This
means the target code is generated the first time the model runs, but on
subsequent runs the Simulink code spends only the time necessary to verify
that the target is up to date. This process is much faster than generating
code, so subsequent runs can be significantly faster than the initial run.
Because checking the targets is quicker than code generation, the crossover
point is smaller when the target is up to date than when code must be
generated. This means subsequent runs of your model might simulate faster
in Accelerator or Rapid Accelerator mode when compared to Normal mode,
even for short stop times.
Measure Performance
You can use the tic, toc, and sim commands to compare Accelerator mode or
Rapid Accelerator mode execution times to Normal mode.
19-7
19
Improving Simulation Performance and Accuracy
1 Use load_system to load your model into memory without opening a
window.
2 From the Simulation > Mode menu, select Normal.
3 Use the tic, toc, and sim commands at the command line prompt to
measure how long the model takes to simulate in Normal mode:
tic,[t,x,y]=sim('myModel',10000);toc
tic and toc work together to record and return the elapsed time and
display a message such as the following:
Elapsed time is 17.789364 seconds.
4 Select either Accelerator or Rapid Accelerator from the
Simulation > Mode menu, and build an executable for the model by
clicking the Run button. The acceleration modes use this executable
in subsequent simulations as long as the model remains structurally
unchanged. “Code Regeneration in Accelerated Models” on page 22-7
discusses the things that cause your model to rebuild.
5 Rerun the compiled model at the command prompt:
tic,[t,x,y]=sim('myModel',10000);toc
6 The elapsed time displayed shows the run time for the accelerated model.
For example:
Elapsed time is 12.419914 seconds.
The difference in elapsed times (5.369450 seconds in this example) shows the
improvement obtained by accelerating your model.
19-8
Improve Acceleration Mode Performance
Improve Acceleration Mode Performance
In this section...
“Techniques” on page 19-9
“C Compilers” on page 19-10
Techniques
To get the best performance when accelerating your models:
• Verify that the Configuration Parameters dialog box settings are as follows:
On this pane...
Set...
To...
Solver Diagnostics
Solver data
inconsistency
none
Data Validity
Diagnostics
Array bounds
exceeded
none
Optimization
Signal storage reuse
selected
• Disable Stateflow debugging and animation.
• Inline user-written S-functions (these are TLC files that direct the Simulink
Coder software to create C code for the S-function). See “Control S-Function
Execution” on page 22-17 for a discussion on how the Accelerator mode and
Rapid Accelerator mode work with inlined S-functions.
For information on how to inline S-functions, consult “Insert S-Function
Code”.
• When logging large amounts of data (for instance, when using the
Workspace I/O, To Workspace, To File, or Scope blocks), use decimation or
limit the output to display only the last part of the simulation.
• Customize the code generation process to improve simulation speed. See
“Customize the Build Process” on page 22-22 for details.
19-9
19
Improving Simulation Performance and Accuracy
C Compilers
On computers running the Microsoft Windows operating system, the
Accelerator and Rapid Accelerator modes use the default 32-bit C compiler
supplied by MathWorks to compile your model. If you have a C compiler
installed on your PC, you can configure the mex command to use it instead.
You might choose to do this if your C compiler produces highly optimized
code since this would further improve acceleration, or if you wish to use a
64-bit compiler.
Note For an up-to-date list of 32- and 64-bit C compilers that are compatible
with MATLAB software for all supported computing platforms, see:
http://www.mathworks.com/support/compilers/current_release/
19-10
Improve Simulation Accuracy
Improve Simulation Accuracy
To check your simulation accuracy, run the simulation over a reasonable time
span. Then, either reduce the relative tolerance to 1e-4 (the default is 1e-3)
or reduce the absolute tolerance and run it again. Compare the results of
both simulations. If the results are not significantly different, you can feel
confident that the solution has converged.
If the simulation misses significant behavior at its start, reduce the initial step
size to ensure that the simulation does not step over the significant behavior.
If the simulation results become unstable over time,
• Your system might be unstable.
• If you are using ode15s, you might need to restrict the maximum order to
2 (the maximum order for which the solver is A-stable) or try using the
ode23s solver.
If the simulation results do not appear to be accurate,
• For a model that has states whose values approach zero, if the absolute
tolerance parameter is too large, the simulation takes too few steps around
areas of near-zero state values. Reduce this parameter value or adjust it
for individual states in the Integrator dialog box.
• If reducing the absolute tolerances does not sufficiently improve the
accuracy, reduce the size of the relative tolerance parameter to reduce the
acceptable error and force smaller step sizes and more steps.
Certain modeling constructs can also produce unexpected or inaccurate
simulation results.
• A Source block that inherits its sample time can produce different
simulation results if, for example, the sample times of the downstream
blocks are modified (see “How Propagation Affects Inherited Sample
Times” on page 5-29).
• A Derivative block found in an algebraic loop can result in a loss in solver
accuracy.
19-11
19
19-12
Improving Simulation Performance and Accuracy
20
Performance Advisor
20
Performance Advisor
Consult the Performance Advisor
In this section...
“About the Performance Advisor” on page 20-2
“Prepare to Use Performance Advisor” on page 20-3
“Start the Performance Advisor” on page 20-3
“Overview of the Performance Advisor Window” on page 20-3
“Performance Advisor Workflow” on page 20-6
“Create Baseline” on page 20-6
“Run Performance Advisor Checks” on page 20-8
“View and Save Performance Advisor Reports” on page 20-11
“Understand Performance Advisor Analysis Results” on page 20-14
“Fix a Warning” on page 20-16
“Review the Actions Taken” on page 20-16
“Save Your Model” on page 20-17
“Performance Advisor Limitations” on page 20-17
About the Performance Advisor
Whatever the level of complexity of the model, you might want to improve
simulation performance. The Performance Advisor checks a model for
conditions and configuration settings that can result in slower simulation of
the system that the model represents. The Performance Advisor produces a
report that lists the suboptimal conditions or settings that it finds, suggesting
better model configuration settings where appropriate. The Performance
Advisor provides mechanisms for automatically fixing warning or allowing
you to fix them manually. For more information on individual Performance
Advisor checks, see “Simulink Performance Advisor Checks”.
For more guidelines, see Improving Simulation Performance in Simulink.
20-2
Consult the Performance Advisor
Prepare to Use Performance Advisor
Before you use the Performance Advisor:
• Make a backup copy of your original model.
• Check that the original model can simulate without error.
• Close all applications, including Web browsers. Only the MATLAB
Command Window, the model you want to analyze, and the Performance
Advisor tool should be running. The running of other applications can
change the performance of model simulation and the ability of Performance
Advisor to measure accurately.
Start the Performance Advisor
Start the Performance Advisor in one of the following ways:
• To start the Performance Advisor from the Simulink Editor menus, select
Analysis > Performance Tools > Performance Advisor.
• To start the Performance Advisor from the Simulink Editor toolbar, on the
Simulink Editor, on the
drop-down list, select Performance Advisor.
• To start the Performance Advisor from the MATLAB Command Window,
type performanceadvisor('model_name'). For example:
performanceadvisor('vdp')
Overview of the Performance Advisor Window
When you start the Performance Advisor, the Performance Advisor window
displays two panes. The left pane lists the folders in the Performance Advisor.
Expanding the folders displays the available checks. The right pane provides
instructions on how to view and specify which checks you want to run. It also
provides a legend describing the displayed symbols.
20-3
20
Performance Advisor
From the left pane, you can:
• Select by category and expand the folder to display checks related to
specific tasks, such as creating a baseline for future checks or checks based
on Simulation actions.
• Select some or all of the checks using the check boxes or context menus
associated with the checks, then run an individual check or all selected
checks in a folder.
20-4
Consult the Performance Advisor
To find checks and folders, enter text in the Find field and click the Find
Next button (
). The Performance Advisor searches check names and
folder names for the text.
After running checks, the Performance Advisor displays the results in the
right pane. Additionally, the Performance Advisor generates an HTML report
of the check results. You can optionally view this report in a separate browser
window by clicking the Show report after run check box in the right pane
before the check has run.
The right pane is contextual. It changes depending on your actions. From
the right pane:
When you
select a...
The right pane displays a Performance Advisor
tab with...
Folder
Analysis pane, containing:
• Run Selected Checks button — Click to run the
selected checks in the folder or its subfolders.
• Show report after run check box — Select to display
an HTML report of the check results after the check
has run.
Tips and Legends sections, containing brief descriptions
on using the checks.
Check
Analysis pane, containing:
• Input Parameters section — Before running checks,
specify how you want checks to run (for more
information, see “Run Performance Advisor Checks”
on page 20-8).
• Result section — Display results after check run.
Action pane, containing:
• Modify button — Click this button to perform
recommended actions.
• Result section — Display results after performing
recommended actions.
20-5
20
Performance Advisor
Performance Advisor Workflow
Your expected workflow when using Performance Advisor is:
1 When you determine that the performance of a model is slower than
expected, use Performance Advisor to help identify and resolve bottlenecks.
2 Have Performance Advisor
a Create a baseline against it will compare measurements.
b Run the checks you selected.
c Make suggested changes.
d Run the checks again.
• If performance is improved, you can stop.
• If performance is worse than the baseline data, Performance Advisor
reinstates the model to the settings it had before the check was run.
Create Baseline
Create a baseline before running checks in Performance Advisor. A baseline
is a set of simulation measurements against which Performance Advisor
measure check results.
To create the baseline, in the Performance Advisor:
1 Before creating the baseline, you need to verify and possibly set
configuration parameters to enable data logging using the Structured
with time format. To set configuration parameters, in the model, select
Simulation > Model Configuration Parameters.
2 In the Configuration Parameters dialog box:
• Set Data Import/Export > Format to Structure with time.
• Set up signal logging. For an easy example, select the Data
Import/Export > States or Output check box.
• Click the Configure Signals to Log button to select the signals to log.
20-6
Consult the Performance Advisor
Note Select only the signals you are most interested in. Minimizing the
number of signals you want to log can help performance. Selecting too
many signals might cause the Performance Advisor to run for a longer
time.
3 Click OK.
4 Run the model once and check that the simulation runtime is not too long.
5 If the Performance Advisor is not started, start it now.
6 In the left pane, select Create Baseline.
7 In the right pane, in the Input Parameters section:
• In Stop Time, enter a stop time for the simulation for the baseline
creation. By default, if the model stop time is less than 10, Performance
Advisor uses that value as the stop time. Otherwise, it uses 10. You
should avoid entering a large stop time because the simulation might
be too large.
• Click the Click to view baseline signals and set their tolerances
check box to see and change the baseline signal tolerance. Performance
Advisor calculates a default tolerance for the model based on the solver
setting.
After the Performance Advisor runs the check, it starts the Simulation
Data Inspector. With this tool, you can compare signals and adjust
tolerance levels. For more information, see “Inspect Signal Data with
Simulation Data Inspector” on page 17-2.
For more information on input parameters, see “Run Performance Advisor
Checks” on page 20-8.
8 In the right pane, click Run This Check.
Upon successful creation of a baseline, a message like the following is
displayed in the Analysis Result section:
20-7
20
Performance Advisor
Observe that Performance Advisor has filled the Stop Time parameter
with the stop time of the model.
Note Alternatively, you can create the baseline when you run your selected
Performance Advisor checks.
You can now run Performance Advisor checks (see “Run Performance Advisor
Checks” on page 20-8).
Run Performance Advisor Checks
This topic assumes that you have created a baseline. If you have not yet done
so, see “Create Baseline” on page 20-6.
1 Select checks to run:
• Click a folder, such as Simulation or Simulation Targets, to display
checks related to specific tasks.
• In a folder, select some or all of the checks using the check boxes or
context menus associated with the checks, and then run an individual
check or all selected checks. By default, the first time you run, all checks
are selected.
Tip If you are unsure of which checks apply, you can select and run all
checks, then clear the checks you are not interested in.
– To select an individual check, in the right pane, select the check. The
right pane updates with information particular to this check.
– To run all selected checks in a folder, in the left pane, select the folder
(for example, Simulation).
20-8
Consult the Performance Advisor
– To select all selected checks for all the categories, in the left pane,
select Performance Advisor. Performance Advisor creates the
baseline, even if it has already been created, and runs the selected
checks.
• To find checks and folders, enter text in the Find field and click the
Find Next button (
). The Performance Advisor searches in check
names, folder names, and analysis descriptions for the text.
The right pane changes depending on your selection in the left pane.
2 In the right pane, specify input parameters for checks to run.
Input
Parameter
Description
Take action
based on
advice
automatically — Default. Allow Performance Advisor
to make the change for you.
manually — Make the recommended changes yourself
or review the changes first. This option allows you to
review the recommended change first. You then have
the option of making the change yourself, or clicking a
modify button that allows Performance Advisor to make
changes for you.
Validate
and revert
changes
if time of
simulation
increases
Select this check box to have Performance Advisor rerun
the simulation and verify that the change made based
on the advice improves simulation time. If the change
does not improve simulation time, Performance Advisor
reverts the changes.
Clear this check box if you do not want Performance
Advisor to run the simulation and verify the results.
20-9
20
Performance Advisor
Input
Parameter
Description
Validate
and revert
changes if
degree of
accuracy is
greater than
tolerance
Select this check box to have Performance Advisor rerun
the simulation and verify that after the change, the
model results are still within tolerance. If the result
is outside tolerance, Performance Advisor reverts the
changes.
Note If you select only this check box, Performance
Advisor compares just the signal to see that it is within
tolerance.
Clear this check box if you do not want Performance
Advisor to rerun the simulation and verify that the
results are within tolerance.
Quick
estimation
of model
build time
Click this check box to allow Performance Advisor to use
the number of blocks of a referenced model to estimate
model build time. Performance Advisor performs this
quick estimate as follows:
1 Search the model for referenced models that do not
refer to other referenced models.
2 Calculate the average number of blocks in each of the
referenced models that do not refer to other referenced
models.
3 Of the list of referenced models that do not refer to
others, select a referenced model whose number of
blocks is closest to the calculated average.
4 Build this model to obtain the build time.
5 Based on the number of blocks and the build time for
this referenced model, estimate the build time for all
other referenced models.
6 Based on these build times, estimate the parallel build
time for the top model.
3 To run a check, in the right pane, click the Run This Check button.
Alternatively, in the menu bar, select Run > Run Selected Checks.
20-10
Consult the Performance Advisor
After running checks, the Performance Advisor displays the results in
the right pane. Additionally, the Performance Advisor generates an
HTML report of the current check results in a file with a name like
model_name\report_#.html
You can optionally view this report in a separate browser window by clicking
the Report link in the right pane of the folder node.
Note When you open the Performance Advisor for a model that you have
previously checked, the Performance Advisor initially displays the check
results generated the last time you checked the model. If you recheck the
model, the new results replace the previous results in the Performance
Advisor window.
After you run your checks, you can:
• “View and Save Performance Advisor Reports” on page 20-11
• “Understand Performance Advisor Analysis Results” on page 20-14
View and Save Performance Advisor Reports
When the Performance Advisor runs checks, it generates an HTML report
of check results.
View Performance Advisor Reports
You can access any report by selecting a folder and clicking the link in the
Report box.
Tip While you can fix warnings and failures through Performance Advisor
reports, use the Performance Advisor window for interactive fixing.
Performance Advisor reports are best for viewing a summary of checks.
As you run checks, the Performance Advisor updates the reports with the
latest information for each check in the folder. A message appears in the
report when you run the checks at different times. Time stamps indicate
20-11
20
Performance Advisor
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.
You can manipulate the report to show only what you are interested in
viewing as follows:
• The check boxes next to the Run Summary status allow you to view only
the checks with the status that you are interested in viewing. For example,
you can remove the checks that have not run by clearing the check box
next to the Not Run status.
Some checks have input parameters specified in the right pane of the
Performance Advisor. For example, Identify resource intensive
diagnostic settings has several input parameters. When you run checks
with input parameters, the Performance Advisor displays the values of the
input parameters in the HTML report:
20-12
Consult the Performance Advisor
Save Performance Advisor Reports
You can archive a Performance Advisor report by saving it to a new location.
To save a report:
1 In the Performance Advisor window, navigate to the folder that contains
the report you want to save.
2 Select the folder that you want. The right pane of the Performance 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 Performance Advisor saves the report and
its image graphics to the new location. Performance Advisor does not save
its action results to a report.
Note If you rerun the Performance Advisor, the report is updated in the
working folder, not in the save location.
20-13
20
Performance Advisor
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 with a structure like the following
slprj/modeladvisor/com_2emathworks_2eSimulink_2ePerformanceAdvisor_2ePerformanceAdvisor_/
model_name/report_xxx.html
Understand Performance Advisor Analysis Results
After the Performance Advisor runs checks, it updates the right pane of the
GUI to reflect the results, for example:
Analysis
Action
20-14
Consult the Performance Advisor
To view the results of a check, in the left pane, select the check that you
ran. The right pane updates with the results of the check. This pane has
the following sections:
Section
Description
Analysis
Input section contains the input parameters that control the
actions.
Result section contains a description of the check and the
advice action to change the model.
Action
Result section lists the status of the check, action taken or
recommended, and a summary of the checks in a table.
• If you set the Take action based on advice parameter to
automatically, Performance Advisor has made the change
for you. You can click the links on the table to evaluate
the changes.
• If you Take action based on advice parameter to
manually. Performance Advisor has not made the change
for you. To make the changes yourself, click the links and
make the recommended changes.
Tip The modify button action changes depending on the
Input Parameter settings. It can only make recommended
changes (Modify all), or it can make recommended changes
and verify (Modify all and validate).
• Action section lists a summary of the actions that
Performance Advisor took based on recommendations listed
in the Result section of the Analysis section. If the tool also
performed validation actions, this section lists the results
in a summary table. If performance has not improved,
Performance Advisor reinstates the model to the settings it
had before the check was run.
When you are done, see “Fix a Warning” on page 20-16.
20-15
20
Performance Advisor
Fix a Warning
The top of the Analysis Result section displays text that describes actions
that Performance Advisor suggests. Based on your settings in the Input
Parameters section.
• If you set the Take action based on advice parameter to automatically,
Performance Advisor has made the recommended changes for you.
• If you set the Take action based on advice parameter to manually, you
can perform the change yourself, or have Performance Advisor make the
change for you by clicking the Modify button.
The bottom part of the Analysis Result section contains a table that lists the
results of the checks.
Severity
Description
The model setting is optimal.
The model setting is suboptimal. You can choose to fix
the reported issue, or move on to the next check. For best
performance, make the recommended change. For more
information on why a specific check does not pass, see the
check documentation.
For a description of the actions that Performance Advisor takes, see “Review
the Actions Taken” on page 20-16.
Review the Actions Taken
The Action Result section contains a summary of the actions that Performance
Advisor took based on Input Parameters setting. If the tool also performed
validation actions, this section lists the results in a summary table.
20-16
Consult the Performance Advisor
Severity
Description
The actions succeeded. The table lists the percentage of
improvement.
The actions failed. For example, if Performance Advisor
cannot make a recommended change, it flags this as failed. It
also flags a check as failed if performance was not improved
and reinstates the model to the settings it had before the
check was run.
Save Your Model
Performance Advisor does not automatically save your model after it makes
changes. When you are satisfied with the changes to your model from
Performance Advisor, save the model.
Performance Advisor Limitations
When you use the Performance Advisor to check systems, the following
limitations apply:
• If you rename a system, you must restart the Performance Advisor to check
that system.
• Use Performance Advisor on top models. Performance Advisor does not
traverse referenced models or library links.
• Remember to save your model after Performance Advisor makes changes to
the model. Performance Advisor does not save the model.
20-17
20
Performance Advisor
For limitations that apply to specific checks, see the Limitations section
within the documentation of each check.
20-18
21
Simulink Debugger
• “Introduction to the Debugger” on page 21-2
• “Debugger Graphical User Interface” on page 21-3
• “Debugger Command-Line Interface” on page 21-10
• “Debugger Online Help” on page 21-12
• “Start the Simulink Debugger” on page 21-13
• “Start a Simulation” on page 21-15
• “Run a Simulation Step by Step” on page 21-17
• “Set Breakpoints” on page 21-22
• “Display Information About the Simulation” on page 21-28
• “Display Information About the Model” on page 21-33
21
Simulink® Debugger
Introduction to the Debugger
With the debugger, you run your simulation method by method. You can
stop after each method to examine the execution results. In this way, you
can pinpoint problems in your model to specific blocks, parameters, or
interconnections.
Note Methods are functions that the Simulink software uses to solve a model
at each time step during the simulation. Blocks are made up of multiple
methods. “Block execution” in this documentation is shorthand for “block
methods execution.” Block diagram execution is a multi-step operation that
requires execution of the different block methods in all the blocks in a diagram
at various points during the process of solving a model at each time step
during simulation, as specified by the simulation loop.
The debugger has both a graphical and a command-line user interface. The
graphical interface allows you to access the most commonly used features
of the debugger. The command-line interface gives you access to all of the
capabilities in the debugger. If you can use either to perform a task, the
documentation shows you first how to use the graphical interface, then the
command-line interface.
21-2
Debugger Graphical User Interface
Debugger Graphical User Interface
In this section...
“Displaying the Graphical Interface” on page 21-3
“Toolbar” on page 21-4
“Breakpoints Pane” on page 21-5
“Simulation Loop Pane” on page 21-6
“Outputs Pane” on page 21-7
“Sorted List Pane” on page 21-8
“Status Pane” on page 21-9
Displaying the Graphical Interface
Select Debug Model from a model window Simulation > Debug menu to
display the debugger graphical interface.
21-3
21
Simulink® Debugger
Note The debugger graphical user interface does not display state or solver
information. The command line interface does provide this information. See
“Display System States” on page 21-31 and “Display Solver Information” on
page 21-32.
Toolbar
The debugger toolbar appears at the top of the debugger window.
From left to right, the toolbar contains the following command buttons:
Button
Purpose
Step into the next method (see “Stepping Commands” on
page 21-19 for more information on this command, and the
following stepping commands).
Step over the next method.
Step out of the current method.
Step to the first method at the start of next time step.
Step to the next block method.
Start or continue the simulation.
Pause the simulation.
Stop the simulation.
21-4
Debugger Graphical User Interface
Button
Purpose
Break before the selected block.
Display inputs and outputs of the selected block when
executed (same as trace gcb).
Display the current inputs and outputs of selected block
(same as probe gcb).
Display help for the debugger.
Close the debugger.
Breakpoints Pane
To display the Breakpoints pane, select the Break Points tab on the
debugger window.
Breakpoint pane
The Breakpoints pane allows you to specify block methods or conditions at
which to stop a simulation. See “Set Breakpoints” on page 21-22 for more
information.
21-5
21
Simulink® Debugger
Simulation Loop Pane
To display the Simulation Loop pane, select the Simulation Loop tab on
the debugger window.
Simulation loop pane
The Simulation Loop pane contains three columns:
• Method
• Breakpoints
• ID
Method Column
The Method column lists the methods that have been called thus far in the
simulation as a method tree with expandable/collapsible nodes. Each node
of the tree represents a method that calls other methods. Expanding a node
shows the methods that the block method calls. Clicking a block method name
highlights the corresponding block in the model diagram.
Whenever the simulation stops, the debugger highlights the name of the
method where the simulation has stopped as well as the methods that invoked
it. The highlighted method names indicate the current state of the method
call stack.
21-6
Debugger Graphical User Interface
Breakpoints Column
The breakpoints column consists of check boxes. Selecting a check box sets a
breakpoint at the method whose name appears to the left of the check box.
See “Setting Breakpoints from the Simulation Loop Pane” on page 21-24
for more information.
ID Column
The ID column lists the IDs of the methods listed in the Methods column.
See “Method ID” on page 21-10 for more information.
Outputs Pane
To display the Outputs pane, select the Outputs tab on the debugger
window.
Output pane
The Outputs pane displays the same debugger output that would appear in the
MATLAB command window if the debugger were running in command-line
mode. The output includes the debugger command prompt and the inputs,
outputs, and states of the block at whose method the simulation is currently
paused (see “Block Data Output” on page 21-18). The command prompt
displays current simulation time and the name and index of the method in
which the debugger is currently stopped (see “Block ID” on page 21-10).
21-7
21
Simulink® Debugger
Sorted List Pane
To display the Sorted List pane, select the Sorted List tab on the debugger
window.
Sorted list pane
The Sorted List pane displays the sorted lists for the model being debugged.
See “Display Model’s Sorted Lists” on page 21-33 for more information.
21-8
Debugger Graphical User Interface
Status Pane
To display the Status pane, select the Status tab on the debugger window.
Status pane
The Status pane displays the values of various debugger options and other
status information.
21-9
21
Simulink® Debugger
Debugger Command-Line Interface
In this section...
“Controlling the Debugger” on page 21-10
“Method ID” on page 21-10
“Block ID” on page 21-10
“Accessing the MATLAB Workspace” on page 21-11
Controlling the Debugger
In command-line mode, you control the debugger by entering commands at the
debugger command line in the MATLAB Command Window. The debugger
accepts abbreviations for debugger commands. See sldebug to access a list of
command abbreviations and repeatable commands.
Note You can repeat some commands by entering an empty command (i.e.,
by pressing the Enter key) at the command line.
Method ID
Some of the Simulink software commands and messages use method IDs
to refer to methods. A method ID is an integer assigned to a method the
first time the method is invoked. The debugger assigns method indexes
sequentially, starting with 0.
Block ID
Some of the debugger commands and messages use block IDs to refer to
blocks. Block IDs are assigned to blocks while generating the model’s sorted
lists during the compilation phase of the simulation. A block ID has the form
sysIdx:blkIdx, where sysIdx is an integer identifying the system that
contains the block (either the root system or a nonvirtual subsystem) and
blkIdx is the position of the block in the system’s sorted list. For example,
the block ID0:1 refers to the first block in the model’s root system. The slist
command shows the block ID for each debugged block in the model.
21-10
Debugger Command-Line Interface
Accessing the MATLAB Workspace
You can enter any MATLAB expression at the sldebug prompt. For example,
suppose you are at a breakpoint and you are logging time and output of your
model as tout and yout. The following command creates a plot.
(sldebug ...) plot(tout, yout)
You cannot display the value of a workspace variable whose name is partially
or entirely the same as that of a debugger command by entering it at the
debugger command prompt. You can, however, use the eval command to
work around this problem. For example, use eval('s') to determine the
value of s rather then s(tep) the simulation.
21-11
21
Simulink® Debugger
Debugger Online Help
You can get online help on using the debugger by clicking the Help button on
the debugger toolbar. Clicking the Help button displays help for the debugger
in the MATLAB product Help browser.
Help button
In command-line mode, you can get a brief description of the debugger
commands by typing help at the debug prompt.
21-12
Start the Simulink® Debugger
Start the Simulink Debugger
You can start the debugger from either a Simulink model window or from the
MATLAB Command Window.
In this section...
“Starting from a Model Window” on page 21-13
“Starting from the Command Window” on page 21-13
Starting from a Model Window
1 In a model window, select Simulation > Debug > Debug Model > .
The debugger graphical user interface opens. See “Debugger Graphical
User Interface” on page 21-3.
2 Continue selecting toolbar buttons.
Note When running the debugger in graphical user interface (GUI) mode,
you must explicitly start the simulation. For more information, see“Start a
Simulation” on page 21-15.
Starting from the Command Window
1 In the MATLAB Command Window, enter either
• the sim command. For example, enter
sim('vdp', 'StopTime', '10', 'debug', 'on')
• or the sldebug command. For example, enter
sldebug 'vdp'
In both cases, the example model vdp loads into memory, starts the
simulation, and stops the simulation at the first block in the model
execution list.
21-13
21
Simulink® Debugger
2 Continue entering debugger commands.
21-14
Start a Simulation
Start a Simulation
To start the simulation, click the Start/Continue button on the debugger
toolbar.
Start/Continue button
The simulation starts and stops at the first simulation method that is to be
executed. It displays the name of the method in its Simulation Loop pane.
At this point, you can
• Set breakpoints.
• Run the simulation step by step.
• Continue the simulation to the next breakpoint or end.
• Examine data.
• Perform other debugging tasks.
21-15
21
Simulink® Debugger
The debugger displays the name of the method in the Simulation Loop pane,
as shown in the following figure:
The following sections explain how to use the debugger controls to perform
these debugging tasks.
Note When you start the debugger in GUI mode, the debugger command-line
interface is also active in the MATLAB Command Window. However, to
prevent synchronization errors between the graphical and command-line
interfaces, you should avoid using the command-line interface.
21-16
Run a Simulation Step by Step
Run a Simulation Step by Step
In this section...
“Introduction” on page 21-17
“Block Data Output” on page 21-18
“Stepping Commands” on page 21-19
“Continuing a Simulation” on page 21-20
“Running a Simulation Nonstop” on page 21-20
Introduction
The debugger provides various commands that let you advance a simulation
from the method where it is currently suspended (the next method) by various
increments (see “Stepping Commands” on page 21-19). For example, you
can advance the simulation
• Into or over the next method
• Out of the current method
• To the top of the simulation loop.
After each advance, the debugger displays information that enables you to
determine the point to which the simulation has advanced and the results of
advancing the simulation to that point.
For example, in GUI mode, after each step command, the debugger highlights
the current method call stack in the Simulation Loop pane. The call stack
comprises the next method and the methods that invoked the next method
either directly or indirectly. The debugger highlights the call stack by
highlighting the names of the methods that make up the call stack in the
Simulation Loop pane.
21-17
21
Simulink® Debugger
Next method
In command-line mode, you can use the where command to display the
method call stack.
Block Data Output
After executing a block method, the debugger prints any or all of the following
block data in the debugger Output panel (in GUI mode) or, if in command
line mode, the MATLAB Command Window:
• Un = v
where v is the current value of the block’s nth input.
• Yn = v
where v is the current value of the block’s nth output.
• CSTATE = v
where v is the value of the block’s continuous state vector.
• DSTATE = v
21-18
Run a Simulation Step by Step
where v is the value of the block’s discrete state vector.
The debugger also displays the current time, the ID and name of the next
method to be executed, and the name of the block to which the method applies
in the MATLAB Command Window. The following example illustrates typical
debugger outputs after a step command.
Current time
Next method
Stepping Commands
Command-line mode provides the following commands for advancing a
simulation incrementally:
This command...
Advances the simulation...
step [in into]
Into the next method, stopping at the first method
in the next method or, if the next method does not
contain any methods, at the end of the next method
step over
To the method that follows the next method, executing
all methods invoked directly or indirectly by the next
method
step out
To the end of the current method, executing any
remaining methods invoked by the current method
step top
To the first method of the next time step (i.e., the top
of the simulation loop)
21-19
21
Simulink® Debugger
This command...
Advances the simulation...
step blockmth
To the next block method to be executed, executing all
intervening model- and system-level methods
next
Same as step over
Buttons in the debugger toolbar allow you to access these commands in GUI
mode.
Step
Step
out
Step
over
Next block
method
Step
top
Clicking a button has the same effect as entering the corresponding command
at the debugger command line.
Continuing a Simulation
In GUI mode, the Stop button turns red when the debugger suspends
the simulation for any reason. To continue the simulation, click the
Start/Continue button. In command-line mode, enter continue to continue
the simulation. By default, the debugger runs the simulation to the next
breakpoint (see “Set Breakpoints” on page 21-22) or to the end of the
simulation, whichever comes first.
Running a Simulation Nonstop
The run command lets you run a simulation to the end of the simulation,
skipping any intervening breakpoints. At the end of the simulation, the
debugger returns you to the command line. To continue debugging a model,
you must restart the debugger.
21-20
Run a Simulation Step by Step
Note The GUI mode does not provide a graphical version of the run command.
To run the simulation to the end, you must first clear all breakpoints and
then click the Start/Continue button.
21-21
21
Simulink® Debugger
Set Breakpoints
In this section...
“About Breakpoints” on page 21-22
“Setting Unconditional Breakpoints” on page 21-22
“Setting Conditional Breakpoints” on page 21-25
About Breakpoints
The debugger allows you to define stopping points called breakpoints in a
simulation. You can then run a simulation from breakpoint to breakpoint,
using the debugger continue command. The debugger lets you define two
types of breakpoints: unconditional and conditional. An unconditional
breakpoint occurs whenever a simulation reaches a method that you specified
previously. A conditional breakpoint occurs when a condition that you
specified in advance arises in the simulation.
Breakpoints are useful when you know that a problem occurs at a certain
point in your program or when a certain condition occurs. By defining
an appropriate breakpoint and running the simulation via the continue
command, you can skip immediately to the point in the simulation where the
problem occurs.
Setting Unconditional Breakpoints
You can set unconditional breakpoints from the:
• Debugger toolbar
• Simulation Loop pane
• MATLAB product Command Window (command-line mode only)
Setting Breakpoints from the Debugger Toolbar
To set a breakpoint on a block’s methods, select the block and then click
the Breakpoint button on the debugger toolbar. If you set a break point
on a block, the debugger stops at any method that the execution reaches in
the block.
21-22
Set Breakpoints
Breakpoint
The debugger displays the name of the selected block in the Break/Display
points panel of the Breakpoints pane.
Note Clicking the Breakpoint button on the toolbar sets breakpoints on the
invocations of a block’s methods in major time steps.
You can temporarily disable the breakpoints on a block by deselecting the
check box in the breakpoints column of the panel. To clear the breakpoints on
a block and remove its entry from the panel,
1 Select the entry.
2 Click the Remove selected point button on the panel.
21-23
21
Simulink® Debugger
Note You cannot set a breakpoint on a virtual block. A virtual block is
purely graphical: it indicates a grouping or relationship among a model’s
computational blocks. The debugger warns you if you try to set a breakpoint
on a virtual block. You can get a listing of a model’s nonvirtual blocks, using
the slist command (see “Displaying a Model’s Nonvirtual Blocks” on page
21-35).
Setting Breakpoints from the Simulation Loop Pane
To set a breakpoint at a particular invocation of a method displayed in the
Simulation Loop pane, select the check box next to the method’s name in
the breakpoint column of the pane.
Breakpoint
To clear the breakpoint, deselect the check box.
21-24
Set Breakpoints
Setting Breakpoints from the Command Window
In command-line mode, use the break and bafter commands to set
breakpoints before or after a specified method, respectively. Use the clear
command to clear breakpoints.
Setting Conditional Breakpoints
You can use either the Break on conditions controls group on the debugger
Breakpoints pane
or the following commands (in command-line mode) to set conditional
breakpoints.
This
command...
Causes the Simulation to Stop...
tbreak [t]
At a simulation time step
ebreak
At a recoverable error in the model
nanbreak
At the occurrence of an underflow or overflow (NaN) or
infinite (Inf) value
xbreak
When the simulation reaches the state that determines
the simulation step size
zcbreak
When a zero crossing occurs between simulation time steps
Setting Breakpoints at Time Steps
To set a breakpoint at a time step, enter a time in the debugger Break at
time field (GUI mode) or enter the time using the tbreak command. This
21-25
21
Simulink® Debugger
causes the debugger to stop the simulation at the Outputs.Major method of
the model at the first time step that follows the specified time. For example,
starting vdp in debug mode and entering the commands
tbreak 2
continue
causes the debugger to halt the simulation at the vdp.Outputs.Major method
of time step 2.078 as indicated by the output of the continue command.
%----------------------------------------------------------------%
[Tm = 2.034340153847549
] vdp.Outputs.Minor
(sldebug @37):
Breaking on Nonfinite Values
Selecting the debugger NaN values option or entering the nanbreak
command causes the simulation to stop when a computed value is infinite or
outside the range of values that is supported by the machine running the
simulation. This option is useful for pinpointing computational errors in
a model.
Breaking on Step-Size Limiting Steps
Selecting the Step size limited by state option or entering the xbreak
command causes the debugger to stop the simulation when the model uses a
variable-step solver and the solver encounters a state that limits the size of
the steps that it can take. This command is useful in debugging models that
appear to require an excessive number of simulation time steps to solve.
Breaking at Zero Crossings
Selecting the Zero crossings option or entering the zcbreak command
causes the simulation to halt when a nonsampled zero crossing is detected in
a model that includes blocks where zero crossings can arise. After halting,
the ID, type, and name of the block in which the zero crossing was detected is
displayed. The block ID (s:b:p) consists of a system index s, block index b,
and port index p separated by colons (see “Block ID” on page 21-10).
21-26
Set Breakpoints
For example, setting a zero-crossing break at the start of execution of the
zeroxing example model,
>> sldebug zeroxing
%-------------------------------------------------------------%
[TM = 0
] zeroxing.Simulate
(sldebug @0): >> zcbreak
Break at zero crossing events
: enabled
and continuing the simulation
(sldebug @0): >> continue
results in a zero-crossing break at
Interrupting model execution before running mdlOutputs at the left post of
(major time step just before) zero crossing event detected at the following location:
6[-0]
0:5:2
Saturate
'zeroxing/Saturation'
%----------------------------------------------------------------%
[TzL= 0.3435011087932808
] zeroxing.Outputs.Major
(sldebug @16): >>
If a model does not include blocks capable of producing nonsampled zero
crossings, the command prints a message advising you of this fact.
Breaking on Solver Errors
Selecting the debugger Solver Errors option or entering the ebreak
command causes the simulation to stop if the solver detects a recoverable error
in the model. If you do not set or disable this breakpoint, the solver recovers
from the error and proceeds with the simulation without notifying you.
21-27
21
Simulink® Debugger
Display Information About the Simulation
In this section...
“Display Block I/O” on page 21-28
“Display Algebraic Loop Information” on page 21-30
“Display System States” on page 21-31
“Display Solver Information” on page 21-32
Display Block I/O
The debugger allows you to display block I/O by clicking the appropriate
buttons on the debugger toolbar
Watch
block I/O
Display
block I/O
or by entering the appropriate debugger command.
This
command... Displays a Blocks I/O...
probe
Immediately
disp
At every breakpoint any time execution stops
trace
Whenever the block executes
Note The two debugger toolbar buttons, Watch Block I/O (
) and Display
Block I/O (
) correspond, respectively, to trace gcb and probe gcb. The
probe and disp commands do not have a one-to-one correspondence with
the debugger toolbar buttons.
21-28
Display Information About the Simulation
Displaying I/O of a Selected Block
To display the I/O of a block, select the block and click
in GUI mode or
enter the probe command in command-line mode. In the following table,
the probe gcb command has a corresponding toolbar button. The other
commands do not.
Command
Description
probe
Enter or exit probe mode. Typing any command causes
the debugger to exit probe mode.
probe gcb
probe s:b
Display I/O of selected block. Same as
.
Print the I/O of the block specified by system number s
and block number b.
The debugger prints the current inputs, outputs, and states of the selected
block in the debugger Outputs pane (GUI mode) or the Command Window of
the MATLAB product.
The probe command is useful when you need to examine the I/O of a block
whose I/O is not otherwise displayed. For example, suppose you are using the
step command to run a model method by method. Each time you step the
simulation, the debugger displays the inputs and outputs of the current block.
The probe command lets you examine the I/O of other blocks as well.
Displaying Block I/O Automatically at Breakpoints
The disp command causes the debugger to display a specified block’s inputs
and outputs whenever it halts the simulation. You can specify a block by
entering its block index and entering gcb as the disp command argument.
You can remove any block from the debugger list of display points, using the
undisp command. For example, to remove block 0:0, enter undisp 0:0.
Note Automatic display of block I/O at breakpoints is not available in the
debugger GUI mode.
21-29
21
Simulink® Debugger
The disp command is useful when you need to monitor the I/O of a specific
block or set of blocks as you step through a simulation. Using the disp
command, you can specify the blocks you want to monitor and the debugger
will then redisplay the I/O of those blocks on every step. Note that the
debugger always displays the I/O of the current block when you step through
a model block by block, using the step command. You do not need to use the
disp command if you are interested in watching only the I/O of the current
block.
Watching Block I/O
To watch a block, select the block and click
in the debugger toolbar or
enter the trace command. In GUI mode, if a breakpoint exists on the block,
you can set a watch on it as well by selecting the check box for the block in
the watch column
of the Break/Display points pane. In command-line
mode, you can also specify the block by specifying its block index in the trace
command. You can remove a block from the debugger list of trace points
using the untrace command.
The debugger displays a watched block’s I/O whenever the block executes.
Watching a block allows you obtain a complete record of the block’s I/O
without having to stop the simulation.
Display Algebraic Loop Information
The atrace command causes the debugger to display information about a
model’s algebraic loops (see “Algebraic Loops” on page 3-39) each time they
are solved. The command takes a single argument that specifies the amount
of information to display.
21-30
This
command...
Displays for each algebraic loop...
atrace 0
No information
atrace 1
The loop variable solution, the number of iterations
required to solve the loop, and the estimated solution error
atrace 2
Same as level 1
atrace 3
Level 2 plus the Jacobian matrix used to solve the loop
atrace 4
Level 3 plus intermediate solutions of the loop variable
Display Information About the Simulation
Display System States
The states debug command lists the current values of the system states in
the MATLAB Command Window. For example, the following sequence of
commands shows the states of the bouncing ball example (sldemo_bounce)
after its first, second, and third time steps. However, before entering the
debugger, open the Configuration Parameters dialog box, clear the Block
reduction check box on the Optimization pane, and clear the Signal storage
reuse check box on the Optimization > Signals and Parameters pane.
sldebug sldemo_bounce
%----------------------------------------------------------------%
[TM = 0
] simulate(sldemo_bounce)
(sldebug @0): >> step top
%----------------------------------------------------------------%
[TM = 0
] sldemo_bounce.Outputs.Major
(sldebug @16): >> next
%----------------------------------------------------------------%
[TM = 0
] sldemo_bounce.Update
(sldebug @23): >> states
Continuous States:
Idx
0
Value
(system:block:element
10
(0:4:0
1. 15
CSTATE
Name
'BlockName')
'sldemo_bounce/Second-Order
Integrator')
(0:4:1)
(sldebug @23): >> next
%----------------------------------------------------------------%
[Tm = 0
] solverPhase
(sldebug @26): >> states
Continuous States:
Idx
0
Value
(system:block:element
10
(0:4:0
1. 15
CSTATE
Name
'BlockName')
'sldemo_bounce/Second-Order
Integrator')
(0:4:1)
(sldebug @26): >> next
%----------------------------------------------------------------%
[TM = 0.01
] sldemo_bounce.Outputs.Major
(sldebug @16): >> states
21-31
21
Simulink® Debugger
Continuous States:
Idx
0
Value
(system:block:element
10.1495095
(0:4:0
1. 14.9019
CSTATE
Name
'BlockName')
'sldemo_bounce/Second-Order
Integrator')
(0:4:1)
Display Solver Information
The strace command allows you to pinpoint problems in solving a models
differential equations that can slow down simulation performance. Executing
this command causes the debugger to display solver-related information at
the command line of the MATLAB product when you run or step through
a simulation. The information includes the sizes of the steps taken by the
solver, the estimated integration error resulting from the step size, whether
a step size succeeded (i.e., met the accuracy requirements that the model
specifies), the times at which solver resets occur, etc. If you are concerned
about the time required to simulate your model, this information can help you
to decide whether the solver you have chosen is the culprit and hence whether
choosing another solver might shorten the time required to solve the model.
21-32
Display Information About the Model
Display Information About the Model
In this section...
“Display Model’s Sorted Lists” on page 21-33
“Display a Block” on page 21-34
Display Model’s Sorted Lists
In GUI mode, the debugger Sorted List pane displays lists of blocks for
a models root system and each nonvirtual subsystem. Each list lists the
blocks that the subsystems contains sorted according to their computational
dependencies, alphabetical order, and other block sorting rules. In
command-line mode, you can use the slist command to display a model’s
sorted lists.
---- Sorted list for 'vdp' [9 nonvirtual blocks, directFeed=0]
0:0
'vdp/x1' (Integrator)
0:1
'vdp/Out1' (Outport)
0:2
'vdp/x2' (Integrator)
0:3
'vdp/Out2' (Outport)
0:4
'vdp/Scope' (Scope)
0:5
'vdp/Fcn' (Fcn)
0:6
'vdp/Product' (Product)
0:7
'vdp/Mu' (Gain)
0:8
'vdp/Sum' (Sum)
These displays include the block index for each command. You can use them
to determine the block IDs of the models blocks. Some debugger commands
accept block IDs as arguments.
Identifying Blocks in Algebraic Loops
If a block belongs to an algebraic list, the slist command displays an
algebraic loop identifier in the entry for the block in the sorted list. The
identifier has the form
algId=s#n
21-33
21
Simulink® Debugger
where s is the index of the subsystem containing the algebraic loop and n is
the index of the algebraic loop in the subsystem. For example, the following
entry for an Integrator block indicates that it participates in the first algebraic
loop at the root level of the model.
0:1 'test/ss/I1' (Integrator, tid=0) [algId=0#1, discontinuity]
You can use the debugger ashow command to highlight the blocks and lines
that make up an algebraic loop. See “Displaying Algebraic Loops” on page
21-36 for more information.
Display a Block
To determine the block in a models diagram that corresponds to a particular
index, enter bshow s:b at the command prompt, where s:b is the block index.
The bshow command opens the system containing the block (if necessary) and
selects the block in the systems window.
Displaying a Model’s Nonvirtual Systems
The systems command displays a list of the nonvirtual systems in the model
that you are debugging. For example, the sldemo_clutch) model contains
the following systems:
open_system('sldemo_clutch')
set_param(gcs, 'OptimizeBlockIOStorage','off')
sldebug sldemo_clutch
(sldebug @0): %----------------------------------------------------------------%
[TM = 0
(sldebug @0): >> systems
21-34
0
'sldemo_clutch'
1
'sldemo_clutch/Locked'
2
'sldemo_clutch/Unlocked'
] simulate(sldemo_clutch)
Display Information About the Model
Note The systems command does not list subsystems that are purely
graphical. That is, subsystems that the model diagram represents as
Subsystem blocks but that are solved as part of a parent system. are
not listed. In Simulink models, the root system and triggered or enabled
subsystems are true systems. All other subsystems are virtual (that is,
graphical) and do not appear in the listing from the systems command.
Displaying a Model’s Nonvirtual Blocks
The slist command displays a list of the nonvirtual blocks in a model. The
listing groups the blocks by system. For example, the following sequence of
commands produces a list of the nonvirtual blocks in the Van der Pol (vdp)
example model.
sldebug vdp
%----------------------------------------------------------------%
[TM = 0
] simulate(vdp)
sldebug @0): >> slist
---- Sorted list for 'vdp' [9 nonvirtual blocks, directFeed=0]
0:0
'vdp/x1' (Integrator)
0:1
'vdp/Out1' (Outport)
0:2
'vdp/x2' (Integrator)
0:3
'vdp/Out2' (Outport)
0:4
'vdp/Scope' (Scope)
0:5
'vdp/Fcn' (Fcn)
0:6
'vdp/Product' (Product)
0:7
'vdp/Mu' (Gain)
0:8
'vdp/Sum' (Sum)
Note The slist command does not list blocks that are purely graphical.
That is, blocks that indicate relationships between or groupings among
computational blocks.
21-35
21
Simulink® Debugger
Displaying Blocks with Potential Zero Crossings
The zclist command displays a list of blocks in which nonsampled zero
crossings can occur during a simulation. For example, zclist displays the
following list for the clutch sample model:
(sldebug @0): >> zclist
0
0:4:0
F
HitCross
'sldemo_clutch/Friction Mode Logic/Lockup
Detection/Velocities Match'
1
0:4:1
2
0:10:0
F
F
Abs
'sldemo_clutch/Friction Mode Logic/Lockup
Detection/Required Friction for Lockup/Abs'
3
0:12:0
F
RelationalOperator
'sldemo_clutch/Friction Mode
Logic/Lockup Detection/Required Friction for Lockup/Relational Operator'
4
0:19:0
F
Abs
'sldemo_clutch/Friction Mode Logic/Break Apart
F
RelationalOperator
Detection/Abs'
5
0:20:0
'sldemo_clutch/Friction Mode
Logic/Break Apart Detection/Relational Operator'
6
2:3:0
F
Signum
'sldemo_clutch/Unlocked/slip direction'
Displaying Algebraic Loops
The ashow command highlights a specified algebraic loop or the algebraic
loop that contains a specified block. To highlight a specified algebraic loop,
enter ashow s#n, where s is the index of the system (see “Identifying Blocks
in Algebraic Loops” on page 21-33) that contains the loop and n is the index
of the loop in the system. To display the loop that contains the currently
selected block, enter ashow gcb. To show a loop that contains a specified
block, enter ashow s:b, where s:b is the block’s index. To clear algebraic-loop
highlighting from the model diagram, enter ashow clear.
Displaying Debugger Status
In GUI mode, the debugger displays the settings of various debug options,
such as conditional breakpoints, in its Status panel. In command-line mode,
the status command displays debugger settings. For example, the following
sequence of commands displays the initial debug settings for the vdp model:
sim('vdp', 'StopTime', '10', 'debug', 'on')
%----------------------------------------------------------------%
[TM = 0
] simulate(vdp)
(sldebug @0): >> status
21-36
Display Information About the Model
%----------------------------------------------------------------%
Current simulation time
: 0.0 (MajorTimeStep)
Solver needs reset
: no
Solver derivatives cache needs reset
: no
Zero crossing signals cache needs reset
: no
Default command to execute on return/enter : ""
Break at zero crossing events
: disabled
Break on solver error
: disabled
Break on failed integration step
: disabled
Time break point
: disabled
Break on non-finite (NaN,Inf) values
: disabled
Break on solver reset request
: disabled
Display level for disp, trace, probe
: 1 (i/o, states)
Solver trace level
: 0
Algebraic loop tracing level
: 0
Animation Mode
: off
Window reuse
: not supported
Execution Mode
: Normal
Display level for etrace
: 0 (disabled)
Break points
: none installed
Display points
: none installed
Trace points
: none installed
21-37
21
21-38
Simulink® Debugger
22
Accelerating Models
• “What Is Acceleration?” on page 22-2
• “How Acceleration Modes Work” on page 22-3
• “Code Regeneration in Accelerated Models” on page 22-7
• “Choosing a Simulation Mode” on page 22-11
• “Design Your Model for Effective Acceleration” on page 22-16
• “Perform Acceleration” on page 22-22
• “Interact with the Acceleration Modes Programmatically” on page 22-26
• “Run Accelerator Mode with the Simulink Debugger” on page 22-29
• “Capture Performance Data” on page 22-31
22
Accelerating Models
What Is Acceleration?
Acceleration is a mode of operation in the Simulink product that you can use
to speed up the execution of your model. The Simulink software includes two
modes of acceleration: Accelerator mode and the Rapid Accelerator mode.
Both modes replace the normal interpreted code with compiled target code.
Using compiled code speeds up simulation of many models, especially those
where run time is long compared to the time associated with compilation and
checking to see if the target is up to date.
The Accelerator mode works with any model, but performance decreases if a
model contains blocks that do not support acceleration. The Accelerator mode
supports the Simulink debugger and profiler. These tools assist in debugging
and determining relative performance of various parts of your model. For
more information, see “Run Accelerator Mode with the Simulink Debugger”
on page 22-29 and “Capture Performance Data” on page 22-31.
The Rapid Accelerator mode works with only those models containing blocks
that support code generation of a standalone executable. For this reason,
Rapid Accelerator mode does not support the debugger or profiler. However,
this mode generally results in faster execution than the Accelerator mode.
When used with dual-core processors, the Rapid Accelerator mode runs
Simulink and the MATLAB technical computing environment from one core
while the rapid accelerator target runs as a separate process on a second core.
For more information about the performance characteristics of the Accelerator
and Rapid Accelerator modes, and how to measure the difference in
performance, see “Comparing Performance” on page 19-5.
22-2
How Acceleration Modes Work
How Acceleration Modes Work
In this section...
“Overview” on page 22-3
“Normal Mode” on page 22-3
“Accelerator Mode” on page 22-4
“Rapid Accelerator Mode” on page 22-5
Overview
The Accelerator and Rapid Accelerator modes use portions of the Simulink
Coder product to create an executable. These modes replace the interpreted
code normally used in Simulink simulations, shortening model run time.
Although the acceleration modes use some Simulink Coder code generation
technology, you do not need the Simulink Coder software installed to
accelerate your model.
Note The code generated by the Accelerator and Rapid Accelerator modes is
suitable only for speeding the simulation of your model. You must use the
Simulink Coder product if you want to generate code for other purposes.
Normal Mode
In Normal mode, the MATLAB technical computing environment is the
foundation on which the Simulink software is built. Simulink controls the
solver and model methods used during simulation. Model methods include
such things as computation of model outputs. Normal mode runs in one
process.
22-3
22
Accelerating Models
Solver
Simulink
Model
Methods
MATLAB
One Process
Accelerator Mode
The Accelerator mode generates and links code into a C-MEX S-function.
Simulink uses this acceleration target code to perform the simulation, and the
code remains available for use in later simulations.
Simulink checks that the acceleration target code is up to date before reusing
it. As explained in “Code Regeneration in Accelerated Models” on page 22-7,
the target code regenerates if it is not up to date.
In Accelerator mode, the model methods are separate from the Simulink
software and are part of the Acceleration target code. A C-MEX S-function
API communicates with the Simulink software, and a MEX API communicates
with MATLAB. The target code executes in the same process as MATLAB
and Simulink.
22-4
How Acceleration Modes Work
Acceleration
target code
Simulink
Solver
C-MEX
S-function
API
Model
Methods
MEX API
MATLAB
One Process
Rapid Accelerator Mode
The Rapid Accelerator mode creates a Rapid Accelerator standalone executable
from your model. This executable includes the solver and model methods,
but it resides outside of MATLAB and Simulink. It uses External mode (see
“Host/Target Communication”) to communicate with Simulink.
22-5
22
Accelerating Models
Rapid Accelerator
Standalone executable
External
Mode
Solver
Simulink
Model
Methods
MATLAB
One Process
Second Process
MATLAB and Simulink run in one process, and if a second processing core is
available, the standalone executable runs there.
22-6
Code Regeneration in Accelerated Models
Code Regeneration in Accelerated Models
In this section...
“Structural Changes That Cause Rebuilds” on page 22-7
“Determining If the Simulation Will Rebuild” on page 22-7
Structural Changes That Cause Rebuilds
Changing the structure of your model causes the Rapid Accelerator mode
to regenerate the standalone executable, and for the Accelerator mode to
regenerate the target code and update (overwrite) the existing MEX-file.
Examples of model structure changes that result in a rebuild include:
• Changing the solver type, for example from Variable-step to Fixed-step
• Adding or deleting blocks or connections between blocks
• Changing the values of nontunable block parameters, for example, the
Seed parameter of the Random Number block
• Changing the number of inputs or outputs of blocks, even if the connectivity
is vectorized
• Changing the number of states in the model
• Selecting a different function in the Trigonometric Function block
• Changing signs used in a Sum block
• Adding a Target Language Compiler (TLC) file to inline an S-function
• Changing the sim command output argument when using Rapid
Accelerator mode
• Changing solver parameters such as stop time or rel tol when using
Rapid Accelerator mode
Determining If the Simulation Will Rebuild
The Accelerator and Rapid Accelerator modes use a checksum to determine if
the model has changed, indicating that the code should be regenerated. The
22-7
22
Accelerating Models
checksum is an array of four integers computed using an MD5 checksum
algorithm based on attributes of the model and the blocks it contains.
Use the Simulink.BlockDiagram.getChecksum command to obtain the
checksum for your model. For example:
cs1 = Simulink.BlockDiagram.getChecksum('myModel');
Obtain a second checksum after you have altered your model. The code
regenerates if the new checksum does not match the previous checksum. You
can use the information in the checksum to determine why the simulation
target rebuilt. For a detailed explanation of this procedure, see the example
model slAccelDemoWhyRebuild.
Parameter Handling in Rapid Accelerator Mode
In model rebuilds, Rapid Accelerator Mode handles block diagram and
run-time parameters differently than other parameters. You can change
some block diagram parameters during simulation without causing a rebuild.
These block diagram parameters include the following:
Block Diagram Parameters That Do Not Require Rapid
Accelerator Rebuild
Solver Parameters
22-8
Loading and Logging Parameters
AbsTol
Decimation
ConsecutiveZCsStepRelTol
FinalStateName
ExtrapolationOrder
InitialState
InitialStep
LimitDataPoints
MaxConsecutiveMinStep
LoadExternalInput
MaxConsecutiveZCs
LoadInitialState
MaxNumMinSteps
MaxDataPoints
MaxOrder
OutputOption
MaxStep
OutputSaveName
MinStep
SaveFinalState
Code Regeneration in Accelerated Models
Block Diagram Parameters That Do Not Require Rapid
Accelerator Rebuild
NumberNwtonIterations
SaveFormat
OutputTimes
SaveOutput
Refine
SaveState
RelTol
SaveTime
SolverName
SignalLogging
StartTime
SignalLoggingName
StopTime
StateSaveName
ZCDetectionTol
TimeSaveName
For run-time parameters that you change graphically via the block diagram
or programmatically with the set_param command, you will need to
recompile the model. Recompilation might cause parts of the model to rebuild.
Alternatively, you can programmatically change tunable run-time parameters
without rebuilding parts of the model:
1 Collect the run-time parameters in a run-time parameter structure
while building a rapid accelerator target executable using the
Simulink.BlockDiagram.buildRapidAcceleratorTarget function.
2 To change the parameters, use the
Simulink.BlockDiagram.modifyTunableParameters function.
3 To specify the modified parameters to the sim command, use the
RapidAcceleratorParameterSets and RapidAcceleratorUpToDateCheck
parameters.
For more information, see “sim in parfor with Rapid Accelerator Mode” on
page 15-9.
All other parameter changes might necessitate a rebuild of the model.
22-9
22
22-10
Accelerating Models
Parameter Changes:
Passed Directly to
sim command
Passed Graphically
via Block Diagram
or via set_param
command
Run-time
Rebuild not required
Rebuild might be
required
Block diagram
(solver and logging
parameters)
Rebuild not required
Rebuild not required
Other
Rebuild might be
required
Rebuild might be
required
Choosing a Simulation Mode
Choosing a Simulation Mode
In this section...
“Simulation Mode Tradeoffs” on page 22-11
“Comparing Modes” on page 22-12
“Decision Tree” on page 22-14
Simulation Mode Tradeoffs
In general, you must trade off simulation speed against flexibility when
choosing either Accelerator mode or Rapid Accelerator mode instead of
Normal mode.
Normal
mode
. Debugger
. MATLAB file support
. Scopes and viewers
. Scopes and viewers
Flexibility
from command line
. Run time diagnostics
. Tune parameters
. Interpreted code
Accelerator mode
. Algebraic loops
. Debugger
. MATLAB file support
. Scopes and viewers
. Scopes and viewers
Rapid
Accelerator mode
from command line
. Monte Carlo
. Scopes and viewers
(where necessary)
. Tune parameters
. C code
. Tune parameters
. C code and interpreted
(only from menu)
Speed
22-11
22
Accelerating Models
Normal mode offers the greatest flexibility for making model adjustments and
displaying results, but it runs the slowest. Rapid Accelerator mode runs the
fastest, but this mode does not support the debugger or profiler, and works
only with those models for which C code is available for all of the blocks in
the model. In addition, Rapid Accelerator mode does not support 3-D signals.
If your model has 3-D signals, use Normal or Accelerator mode instead.
Accelerator mode lies between these two in performance and in interaction
with your model.
Note An exception to this rule occurs when you run multiple simulations,
each of which executes in less than one second in Normal mode. For example:
for i=1:100
sim(model); % executes in less than one second in Normal mode
end
For this set of conditions, you will typically obtain the best performance by
simulating the model in Normal mode.
Tip To gain additional flexibility, consider using model referencing to
componentize your model. If the top-level model uses Normal mode, then you
can simulate a referenced model in a different simulation mode than you use
for other portions of a model. During the model development process, you
can choose different simulation modes for different portions of a model. For
details, see “Referenced Model Simulation Modes” on page 6-21.
Comparing Modes
The following table compares the characteristics of Normal mode, Accelerator
mode, and Rapid Accelerator mode.
22-12
Choosing a Simulation Mode
Then use this mode...
If you want to...
Normal
Accelerator
Rapid
Accelerator
Performance
Run your model in a separate address space
Efficiently run batch and Monte Carlo
simulations
Model Adjustment
Change model parameters such as solver type,
stop time without rebuilding
Change block tunable parameters such as gain
Model Requirement
Accelerate your model even if C code is not used
for all blocks
Support MATLAB S-Function blocks
Permit algebraic loops in your model
Have your model work with the debugger or
profiler
Have your model include C++ code
Data Display
Use scopes and signal viewers
See “Behavior
of Scopes
and Viewers
with Rapid
Accelerator
Mode” on
page 22-18
Use scopes and signal viewers when running
your model from the command line
22-13
22
Accelerating Models
Note Scopes and viewers do not update if you run your model from the
command line in Rapid Accelerator mode.
Decision Tree
The following decision tree can help you select between Normal mode,
Accelerator mode, or Rapid Accelerator mode.
See “Comparing Performance” on page 19-5 to understand how effective the
accelerator modes will be in improving the performance of your model.
22-14
Choosing a Simulation Mode
Begin
Use the debugger
or profiler?
Yes
Use scopes
from the
command line?
No
Yes
No
Pause simulation or make
simple changes without
rebuilding?
No
Yes
MATLAB S-function
support?
No
Yes
Is C code available
for all blocks used
in model?
No
Use
Accelerator mode
Yes
Use Rapid
Accelerator mode
22-15
22
Accelerating Models
Design Your Model for Effective Acceleration
In this section...
“Select Blocks for Accelerator Mode” on page 22-16
“Select Blocks for Rapid Accelerator Mode” on page 22-17
“Control S-Function Execution” on page 22-17
“Accelerator and Rapid Accelerator Mode Data Type Considerations” on
page 22-18
“Behavior of Scopes and Viewers with Rapid Accelerator Mode” on page
22-18
“Factors Inhibiting Acceleration” on page 22-19
Select Blocks for Accelerator Mode
The Accelerator simulation mode runs the following blocks as if you were
running Normal mode because these blocks do not generate code for the
accelerator build. Consequently, if your model contains a high percentage
of these blocks, the Accelerator mode may not increase performance
significantly. All of these Simulink blocks use interpreted code.
• Display
• From File
• From Workspace
• Inport (root level only)
• Interpreted MATLAB Function
• MATLAB Function
• Outport (root level only)
• Scope
• To File
• To Workspace
• Transport Delay
22-16
Design Your Model for Effective Acceleration
• Variable Transport Delay
• XY Graph
Note In some instances, Normal mode output might not precisely match the
output from Accelerator mode because of slight differences in the numerical
precision between the interpreted and compiled versions of a model.
Select Blocks for Rapid Accelerator Mode
Blocks that do not support code generation (such as SimEvents) or blocks
that generate code only for a specific target (such as vxWorks), cannot be
simulated in Rapid Accelerator mode.
Additionally, Rapid Accelerator mode does not work if your model contains
any of the following blocks:
• Interpreted MATLAB Function
• Device driver S-functions, such as blocks from the xPC Target product, or
those targeting Freescale™ MPC555
Note In some instances, Normal mode output might not precisely match
the output from Rapid Accelerator mode because of slight differences in the
numerical precision between the interpreted and compiled versions of a model.
Control S-Function Execution
Inlining S-functions using the Target Language Compiler increases
performance with the Accelerator mode by eliminating unnecessary calls to
the Simulink application program interface (API). By default, however, the
Accelerator mode ignores an inlining TLC file for an S-function, even though
the file exists. The Rapid Accelerator mode always uses the TLC file if one
is available.
A device driver S-Function block written to access specific hardware registers
on an I/O board is one example of why this behavior was chosen as the
default. Because the Simulink software runs on the host system rather than
22-17
22
Accelerating Models
the target, it cannot access the targets I/O registers and so would fail when
attempting to do so.
To direct the Accelerator mode to use the TLC file instead of the
S-function MEX-file, specify SS_OPTION_USE_TLC_WITH_ACCELERATOR in the
mdlInitializeSizes function of the S-function, as in this example:
static void mdlInitializeSizes(SimStruct *S)
{
/* Code deleted */
ssSetOptions(S, SS_OPTION_USE_TLC_WITH_ACCELERATOR);
}
Accelerator and Rapid Accelerator Mode Data Type
Considerations
• Accelerator mode supports fixed-point signals and vectors up to 128 bits.
• Rapid Accelerator mode does not support fixed-point signals or vectors
greater than 32 bits.
• Rapid Accelerator mode supports fixed-point parameters up to 128 bits.
• Rapid Accelerator mode supports fixed-point root inputs up to 32 bits
• Rapid Accelerator mode supports root inputs of Enumerated data type
• Rapid Accelerator mode does not support fixed-point data for the From
Workspace block.
• Rapid Accelerator mode supports bus objects as parameters.
• The Accelerator mode and Rapid Accelerator mode store integers as
compactly as possible.
• Simulink Fixed Point does not collect min, max, or overflow data in the
Accelerator or Rapid Accelerator modes.
Behavior of Scopes and Viewers with Rapid
Accelerator Mode
Running the simulation from the command line or the menu determines the
behavior of scopes and viewers in Rapid Accelerator mode.
22-18
Design Your Model for Effective Acceleration
Scope or
Viewer Type
Simulation Run from
Menu
Simulation Run from
Command Line
Simulink Scope
blocks
Same support as Normal
mode
• Logging is supported
Simulink signal
viewer scopes
Graphics are updated, but
logging is not supported
Not supported
Other signal
viewer scopes
Support limited to that
available in External mode
Not supported
Signal logging
Not supported
Not supported
Multirate signal
viewers
Not supported
Not supported
Stateflow Chart
blocks
Same support for chart
animation as Normal mode
Not supported
• Scope window is not
updated
Rapid Accelerator mode does not support multirate signal viewers such as
the DSP System Toolbox spectrum scope or the Communications System
Toolbox™ scatterplot, signal trajectory, or eye diagram scopes.
Note Although scopes and viewers do not update when you run Rapid
Accelerator mode from the command line, they do update when you use
the menu. “Run Acceleration Mode from the User Interface” on page 22-23
shows how to run Rapid Accelerator mode from the menu. “Interact with the
Acceleration Modes Programmatically” on page 22-26 shows how to run the
simulation from the command line.
Factors Inhibiting Acceleration
You cannot use the Accelerator or Rapid Accelerator mode if your model:
• Passes array parameters to MATLAB S-functions that are not numeric,
logical, or character arrays, are sparse arrays, or that have more than
two dimensions
• Uses Fcn blocks containing trigonometric functions having complex inputs
22-19
22
Accelerating Models
Rapid Accelerator mode does not support targets written in C++.
For Rapid Accelerator mode, model parameters must be one of these data
types:
• boolean
• uint8 or int8
• uint16 or int16
• uint32 or int32
• single or double
• fixed-point
• Enumerated
Reserved Keywords
Certain words are reserved for use by the Simulink Coder code language and
by Accelerator mode and Rapid Accelerator mode. These keywords must not
appear as function or variable names on a subsystem, or as exported global
signal names. Using the reserved keywords results in the Simulink software
reporting an error, and the model cannot be compiled or run.
The keywords reserved for the Simulink Coder product are listed in
“Configure Generated Identifiers”. Additional keywords that apply only to
the Accelerator and Rapid accelerator modes are:
22-20
muDoubleScalarAbs
muDoubleScalarCos
muDoubleScalarMod
muDoubleScalarAcos
muDoubleScalarCosh
muDoubleScalarPower
muDoubleScalarAcosh
muDoubleScalarExp
muDoubleScalarRound
muDoubleScalarAsin
muDoubleScalarFloor
muDoubleScalarSign
muDoubleScalarAsinh
muDoubleScalarHypot
muDoubleScalarSin
muDoubleScalarAtan,
muDoubleScalarLog
muDoubleScalarSinh
muDoubleScalarAtan2
muDoubleScalarLog10
muDoubleScalarSqrt
Design Your Model for Effective Acceleration
muDoubleScalarAtanh
muDoubleScalarMax
muDoubleScalarTan
muDoubleScalarCeil
muDoubleScalarMin
muDoubleScalarTanh
22-21
22
Accelerating Models
Perform Acceleration
In this section...
“Customize the Build Process” on page 22-22
“Run Acceleration Mode from the User Interface” on page 22-23
“Making Run-Time Changes” on page 22-25
Customize the Build Process
Compiler optimizations are off by default. This results in faster build times,
but slower simulation times. You can optimize the build process toward a
faster simulation.
1 From the Simulation menu, select Model Configuration Parameters.
2 In the left pane of the Configuration Parameters dialog box, select
Optimization, and then from the Compiler optimization level
drop-down list, select Optimizations on (faster runs).
Code generation takes longer with this option, but the model simulation
runs faster.
3 Select Verbose accelerator builds to display progress information using
code generation, and to see the compiler options in use.
Changing the Name of the Generated File Location
By default, the Accelerator mode places the generated code in a subfolder
of the working folder called slprj/accel/modelname (for example,
slprj/accel/f14), and places a compiled MEX-file in the current working
folder. To change the name of the folder into which the Accelerator Mode
writes generated code:
22-22
Perform Acceleration
1 In the Simulink editor window, select File > Simulink Preferences.
The Simulink Preferences window appears.
2 In the Simulink Preferences window, navigate to the Simulation cache
folder parameter.
3 Enter the absolute or relative path to your subfolder and click Apply.
Run Acceleration Mode from the User Interface
To accelerate a model, first open it, and then from the Simulation > Mode
menu, select either Accelerator or Rapid Accelerator. Then start the
simulation.
The following example shows how to accelerate the already opened f14 model
using the Accelerator mode:
1 From the Simulation > Mode menu, select Accelerator.
Alternatively, you can select Accelerator from the model editor’s toolbar.
22-23
22
Accelerating Models
2 From the Simulation menu, select Run.
The Accelerator and Rapid Accelerator modes first check to see if code
was previously compiled for your model. If code was created previously,
the Accelerator or Rapid Accelerator mode runs the model. If code was
not previously built, they first generate and compile the C code, and then
run the model.
For an explanation of why these modes rebuild your model, see “Code
Regeneration in Accelerated Models” on page 22-7.
The Accelerator mode places the generated code in a subfolder of the working
folder called slprj/accel/modelname (for example, slprj/accel/f14), and
places a compiled MEX-file in the current working folder. If you want to
change this path, see “Changing the Name of the Generated File Location” on
page 22-22.
22-24
Perform Acceleration
The Rapid Accelerator mode places the generated code in a subfolder
of the working folder called slprj/raccel/modelname (for example,
slprj/raccel/f14).
Note The warnings that blocks generate during simulation (such as
divide-by-zero and integer overflow) are not displayed when your model runs
in Accelerator or Rapid Accelerator mode.
Making Run-Time Changes
A feature of the Accelerator and Rapid Accelerator modes is that simple
adjustments (such as changing the value of a Gain or Constant block) can
be made to the model while the simulation is still running. More complex
changes (for example, changing from a sin to tan function) are not allowed
during run time.
The Simulink software issues a warning if you attempt to make a change
that is not permitted. The absence of a warning indicates that the change
was accepted. The warning does not stop the current simulation, and the
simulation continues with the previous values. If you wish to alter the model
in ways that are not permitted during run time, you must first stop the
simulation, make the change, and then restart the simulation.
In general, simple model changes are more likely to result in code regeneration
when in Rapid Accelerator mode than when in Accelerator mode. For
instance, changing the stop time in Rapid Accelerator mode causes code to
regenerate, but does not cause Accelerator mode to regenerate code.
22-25
22
Accelerating Models
Interact with the Acceleration Modes Programmatically
In this section...
“Why Interact Programmatically?” on page 22-26
“Build Accelerator Mode MEX-files” on page 22-26
“Control Simulation” on page 22-26
“Simulate Your Model” on page 22-27
“Customize the Acceleration Build Process” on page 22-28
Why Interact Programmatically?
You can build an accelerated model, select the simulation mode, and run the
simulation from the command prompt or from MATLAB script. With this
flexibility, you can create Accelerator mode MEX-files in batch mode, allowing
you to build the C code and executable before running the simulations. When
you use the Accelerator mode interactively at a later time, it will not be
necessary to generate or compile MEX-files at the start of the accelerated
simulations.
Build Accelerator Mode MEX-files
With the accelbuild command, you can build the Accelerator mode MEX-file
without actually simulating the model. For example, to build an Accelerator
mode simulation of myModel:
accelbuild myModel
Control Simulation
You can control the simulation mode from the command line prompt by using
the set_param command:
set_param('modelname','SimulationMode','mode')
The simulation mode can be normal, accelerator, rapid, or external.
For example, to simulate your model with the Accelerator mode, you would
use:
22-26
Interact with the Acceleration Modes Programmatically
set_param('myModel','SimulationMode','accelerator')
However, a preferable method is to specify the simulation mode within the
sim command:
simOut = sim('myModel', 'SimulationMode', 'accelerator');
You can use gcs (“get current system”) to set parameters for the currently
active model (that is, the active model window) rather than modelname if you
do not wish to explicitly specify the model name.
For example, to simulate the currently opened system in the Rapid Accelerator
mode, you would use:
simOut = sim(gcs,'SimulationMode','rapid');
Simulate Your Model
You can use set_param to configure the model parameters (such as the
simulation mode and the stop time), and use the sim command to start the
simulation:
sim('modelname', 'ReturnWorkspaceOutputs', 'on');
However, the preferred method is to configure model parameters directly
using the sim command, as shown in the previous section.
You can substitute gcs for modelname if you do not want to explicitly specify
the model name.
Unless target code has already been generated, the sim command first builds
the executable and then runs the simulation. However, if the target code
has already been generated and no significant changes have been made to
the model (see “Code Regeneration in Accelerated Models” on page 22-7
for a description), the sim command executes the generated code without
regenerating the code. This process lets you run your model after making
simple changes without having to wait for the model to rebuild.
22-27
22
Accelerating Models
Simulation Example
The following sequence shows how to programmatically simulate myModel in
Rapid Accelerator mode for 10,000 seconds.
First open myModel, and then type the following in the Command Window:
simOut = sim('myModel', 'SimulationMode', 'rapid'...
'StopTime', '10000');
Use the sim command again to resimulate after making a change to your
model. If the change is minor (adjusting the gain of a gain block, for instance),
the simulation runs without regenerating code.
Customize the Acceleration Build Process
You can programmatically control the Accelerator mode and Rapid Accelerator
mode build process and the amount of information displayed during the build
process. See “Customize the Build Process” on page 22-22 for details on why
doing so might be advantageous.
Controlling the Build Process
Use the SimCompilerOptimization parameter to control the acceleration
build process. The permitted values are on or off. The default is off.
Enter the following at the command prompt to turn on compiler optimization:
set_param('myModel', 'SimCompilerOptimization', 'on')
Controlling Verbosity During Code Generation
Use the AccelVerboseBuild parameter to display progress information
during code generation. The permitted values are on or off. The default is
off.
Enter the following at the command prompt to turn on verbose build:
set_param('myModel', 'AccelVerboseBuild', 'on')
22-28
Run Accelerator Mode with the Simulink® Debugger
Run Accelerator Mode with the Simulink Debugger
In this section...
“Advantages of Using Accelerator Mode with the Debugger” on page 22-29
“How to Run the Debugger” on page 22-29
“When to Switch Back to Normal Mode” on page 22-30
Advantages of Using Accelerator Mode with the
Debugger
The Accelerator mode can shorten the length of your debugging sessions if
you have large and complex models. For example, you can use the Accelerator
mode to simulate a large model and quickly reach a distant break point.
For more information, see “Run Accelerator Mode with the Simulink
Debugger” on page 22-29.
Note You cannot use the Rapid Accelerator mode with the debugger.
How to Run the Debugger
To run your model in the Accelerator mode with the debugger:
1 From the Simulation > Mode menu, select Accelerator.
2 At the command prompt, enter:
sldebug modelname
3 At the debugger prompt, set a time break:
tbreak 10000
continue
4 Once you reach the breakpoint, use the debugger command emode (execution
mode) to toggle between Accelerator and Normal mode.
22-29
22
Accelerating Models
When to Switch Back to Normal Mode
You must switch to Normal mode to step through the simulation by blocks,
and when you want to use the following debug commands:
• trace
• break
• zcbreak
• nanbreak
22-30
Capture Performance Data
Capture Performance Data
In this section...
“What Is the Profiler?” on page 22-31
“How the Profiler Works” on page 22-31
“Enabling the Profiler” on page 22-33
“How to Save Simulink Profiler Results” on page 22-36
What Is the Profiler?
The profiler captures data while your model runs and identifies the parts of
your model requiring the most time to simulate. You use this information to
decide where to focus your model optimization efforts.
Note You cannot use the Rapid Accelerator mode with the Profiler.
Performance data showing the time spent executing each function in your
model is placed in a report called the simulation profile.
How the Profiler Works
The following pseudocode summarizes the execution model on which the
Profiler is based.
Sim()
ModelInitialize().
ModelExecute()
for t = tStart to tEnd
Output()
Update()
Integrate()
Compute states from derivs by repeatedly calling:
MinorOutput()
MinorDeriv()
Locate any zero crossings by repeatedly calling:
MinorOutput()
22-31
22
Accelerating Models
MinorZeroCrossings()
EndIntegrate
Set time t = tNew.
EndModelExecute
ModelTerminate
EndSim
According to this conceptual model, your model is executed by invoking the
following functions zero, one, or more times, depending on the function and
the model.
22-32
Function
Purpose
Level
sim
Simulate the model. This
top-level function invokes the
other functions required to
simulate the model. The time
spent in this function is the total
time required to simulate the
model.
System
ModelInitialize
Set up the model for simulation.
System
ModelExecute
Execute the model by invoking
the output, update, integrate,
etc., functions for each block at
each time step from the start to
the end of simulation.
System
Output
Compute the outputs of a block at
the current time step.
Block
Update
Update a block’s state at the
current time step.
Block
Integrate
Compute a block’s continuous
states by integrating the state
derivatives at the current time
step.
Block
MinorOutput
Compute a block’s output at a
minor time step.
Block
Capture Performance Data
Function
Purpose
Level
MinorDeriv
Compute a block’s state
derivatives at a minor time
step.
Block
MinorZeroCrossings
Compute a block’s zero-crossing
values at a minor time step.
Block
ModelTerminate
Free memory and perform any
other end-of-simulation cleanup.
System
Nonvirtual Subsystem
Compute the output of a
nonvirtual subsystem at the
current time step by invoking
the output, update, integrate,
etc., functions for each block
that it contains. The time
spent in this function is the
time required to execute the
nonvirtual subsystem.
Block
The Profiler measures the time required to execute each invocation of these
functions and generates a report at the end of the model that describes how
much time was spent in each function.
Enabling the Profiler
To profile a model, open the model and select Show Profiler Report from
the Analysis > Performance Tools menu. Then start the simulation.
When the simulation finishes, the Simulink code generates and displays the
simulation profile for the model in the Help browser.
22-33
22
22-34
Accelerating Models
Capture Performance Data
Summary Section
The summary file displays the following performance totals.
Item
Description
Total Recorded Time
Total time required to simulate the model
Number of Block Methods
Total number of invocations of block-level
functions (e.g., Output())
Number of Internal
Methods
Total number of invocations of system-level
functions (e.g., ModelExecute)
Number of Nonvirtual
Subsystem Methods
Total number of invocations of nonvirtual
subsystem functions
Clock Precision
Precision of the profiler’s time measurement
The summary section then shows summary profiles for each function invoked
to simulate the model. For each function listed, the summary profile specifies
the following information.
Item
Description
Name
Name of function. This item is a hyperlink. Clicking it
displays a detailed profile of this function.
Time
Total time spent executing all invocations of this function
as an absolute value and as a percentage of the total
simulation time
Calls
Number of times this function was invoked
Time/Call
Average time required for each invocation of this function,
including the time spent in functions invoked by this
function
22-35
22
Accelerating Models
Item
Description
Self Time
Average time required to execute this function, excluding
time spent in functions called by this function
Location
Specifies the block or model executed for which this
function is invoked. This item is a hyperlink. Clicking it
highlights the corresponding icon in the model diagram.
The link works only if you are viewing the profile in the
Help browser.
Detailed Profile Section
This section contains detailed profiles for each function invoked to simulate
the model. Each detailed profile contains all the information shown in the
summary profile for the function. In addition, the detailed profile displays the
function (parent function) that invoked the profiled function and the functions
(child functions) invoked by the profiled function. Clicking the name of the
parent or a child function takes you to the detailed profile for that function.
Note Enabling the Profiler on a parent model does not enable profiling for
referenced models. You must enable profiling separately for each submodel.
Profiling occurs only if the submodel executes in Normal mode. See “Normal
Mode” on page 6-21 for more information.
How to Save Simulink Profiler Results
You can save the Profiler report to a variable in the MATLAB workspace, and
subsequently, to a mat file. At a later time, you can regenerate and review
the report.
To save the Profiler report for a model vdp to the variable profile1 and to the
data file report1.mat, complete the following steps:
1 In the Simulink Profiler Report window, click click here. Simulink
saves the report data to the variable vdpProfileData.
2 Navigate to the MATLAB command window.
22-36
Capture Performance Data
3 To review the report, at the command line enter:
slprofreport(vdpProfileData)
4 To save the data to a variable named profile1 in the base workspace, enter:
profile1 = vdpProfileData;
5 To save the data to a mat file named report1, enter:
save report1 profile1
To view the report at a later time, from the MATLAB command window, enter:
% Load the mat file and recreate the profile1 object
load report1
% Recreate the html report from the object
slprofreport(profile1);
22-37
22
22-38
Accelerating Models
Managing Blocks
• Chapter 23, “Working with Blocks”
• Chapter 24, “Working with Block Parameters”
• Chapter 25, “Working with Lookup Tables”
• Chapter 26, “Working with Block Masks”
• Chapter 27, “Creating Custom Blocks”
• Chapter 28, “Working with Block Libraries”
• Chapter 29, “Using the MATLAB Function Block”
• Chapter 30, “Design Considerations for C/C++ Code Generation”
• Chapter 31, “Functions Supported for Code Generation”
• Chapter 32, “System Objects Supported for Code Generation”
• Chapter 33, “Defining MATLAB Variables for C/C++ Code
Generation”
• Chapter 34, “Defining Data for Code Generation”
• Chapter 35, “Code Generation for Variable-Size Data”
• Chapter 36, “Code Generation for MATLAB Structures”
• Chapter 37, “Code Generation for Enumerated Data”
• Chapter 38, “Code Generation for MATLAB Classes”
• Chapter 39, “Code Generation for Function Handles”
• Chapter 40, “Defining Functions for Code Generation”
• Chapter 41, “Calling Functions for Code Generation”
• Chapter 42, “Generating Efficient and Reusable Code”
23
Working with Blocks
• “About Blocks” on page 23-2
• “Add Blocks” on page 23-4
• “Edit Blocks” on page 23-9
• “Set Block Properties” on page 23-15
• “Change the Appearance of a Block” on page 23-22
• “Display Port Values” on page 23-29
• “Control and Displaying the Sorted Order” on page 23-35
• “Access Block Data During Simulation” on page 23-53
• “Configure a Block for Code Generation” on page 23-57
23
Working with Blocks
About Blocks
In this section...
“What Are Blocks?” on page 23-2
“Block Tool Tips” on page 23-2
“Virtual Blocks” on page 23-2
What Are Blocks?
Blocks are the elements from which the Simulink software builds models.
You can model virtually any dynamic system by creating and interconnecting
blocks in appropriate ways. This section discusses how to use blocks to build
models of dynamic systems. Most blocks contain fields called block parameters
that you can use to enter values that customize the behavior of the block. Be
careful not to confuse block parameters with Simulink parameters, which are
objects of type simulink.parameter that exist in the base workspace. See
“About Block Parameters” on page 24-2 and “Set Block Parameters” on page
24-4 for information about setting and changing block parameters.
Block Tool Tips
Information about a block is displayed in a tool tip when you hover the mouse
pointer over the block in the diagram view. To disable this feature, or control
what information the tool tip displays, select Display > Blocks > Tool Tip
Options in the Simulink Editor.
Virtual Blocks
When creating models, you need to be aware that Simulink blocks fall into two
basic categories: nonvirtual blocks and virtual blocks. Nonvirtual blocks play
an active role in the simulation of a system. If you add or remove a nonvirtual
block, you change the model’s behavior. Virtual blocks, by contrast, play no
active role in the simulation; they help organize a model graphically. Some
Simulink blocks are virtual in some circumstances and nonvirtual in others.
Such blocks are called conditionally virtual blocks. The following table lists
Simulink virtual and conditionally virtual blocks.
23-2
About Blocks
Block Name
Condition Under Which Block Is Virtual
Bus Assignment
Virtual if input bus is virtual.
Bus Creator
Virtual if output bus is virtual.
Bus Selector
Virtual if input bus is virtual.
Demux
Always virtual.
Enable
Virtual unless connected directly to an Outport
block.
From
Always virtual.
Goto
Always virtual.
Goto Tag Visibility
Always virtual.
Ground
Always virtual.
Inport
Virtual unless the block resides in a conditionally
executed or atomic subsystem and has a direct
connection to an Outport block.
Mux
Always virtual.
Outport
Virtual when the block resides within any
subsystem block (conditional or not), and does not
reside in the root (top-level) Simulink window.
Selector
Virtual only when Number of input dimensions
specifies 1 and Index Option specifies Select
all, Index vector (dialog), or Starting index
(dialog).
Signal Specification
Always virtual.
Subsystem
Virtual unless the block is conditionally executed or
the Treat as atomic unit check box is selected.
You can check if a block is virtual with the
IsSubsystemVirtual block property. See
“Block-Specific Parameters”.
Terminator
Always virtual.
Trigger
Virtual when the output port is not present.
23-3
23
Working with Blocks
Add Blocks
In this section...
“Ways to Add Blocks” on page 23-4
“Add Blocks by Browsing or Searching with the Library Browser” on page
23-5
“Copy Blocks from a Model” on page 23-5
“Add Frequently Used Blocks” on page 23-6
“Add Blocks Programmatically” on page 23-8
Ways to Add Blocks
You can add blocks to a model in several ways.
Method
When to Use
Browse or search libraries with the
Library Browser
• You are not sure which block to
add.
• You do not have a familiar model
from which to copy blocks.
Copy blocks from a model
• You know where in a model a
block is that you want to copy.
• You want to replicate many of the
parameter settings of an existing
block.
23-4
Add Blocks
Method
When to Use
Use the Most Frequently Used
Blocks pane or context menu
• You want to add a block that you
have used frequently and recently.
• You are working on multiple
models that share several of the
same blocks.
• You do not have a familiar model
from which to copy similar blocks.
Add blocks programmatically with
the add_block function
• You want to replicate most of the
parameter settings of a block.
• You are working on multiple
models that share several of the
same blocks.
Add Blocks by Browsing or Searching with the
Library Browser
To browse or search for a block from a block library installed on your system,
use the Library Browser. You can browse a list of block libraries or search for
blocks whose names include the search string you specify.
When you find the block you want, select that block in the Library Browser
and drag the block into your model. See “Populate a Model” on page 4-4 for
more information.
Copy Blocks from a Model
To copy a block from a model in the Simulink Editor:
1 Select the block that you want to copy from a model.
2 Choose Edit > Copy.
3 In the model window in which you want to place the copied block, choose
Edit > Paste.
You can copy a block:
23-5
23
Working with Blocks
• Within the same model window
• Between multiple systems open in one Simulink Editor instance
• Between systems open in multiple Simulink Editor instances
When you copy a block, the parameters use default values.
For details, see “Copy Blocks Between Windows” on page 23-10.
Add Frequently Used Blocks
When using the same block repeatedly, you can save time by using the Most
Frequently Used Blocks feature in the Library Browser or Model Editor.
Selecting Your Most Frequently Used Blocks From the Library
Browser
Open the Most Frequently Used Blocks pane with the third tab in the
Library Browser.
23-6
Add Blocks
To add a block to a model, select the block from the list and do either one of
the following from the Library Browser:
• Drag the block into your model.
• Right-click the block, and from the context menu select Add to
.
Select Most Frequently Used Blocks from the Model Editor
In the Simulink Editor, you can view a list of your most frequently used
blocks. Right-click anywhere in the model except with the cursor directly on a
block or signal. In the context menu, select Most Frequently Used Blocks.
23-7
23
Working with Blocks
What Blocks Appear in the Most Frequently Used Blocks Lists
The Most Frequently Used Blocks pane lists blocks that you have added most
often, with the most frequently used block at the top. The list reflects your
ongoing modeling activity. For example, if you add several Gain blocks, the
Gain block appears in the list if the list:
• Does not already include the Gain block
• Has less than 25 blocks
• Has 25 blocks, but you added more Gain blocks than the number of
instances of the least frequently used block in the list
The list displays blocks that you rename as instances of the library block. For
example, if you rename several Gain blocks to be MyGain1, MyGain2, and so
on, those blocks count as Gain blocks.
When you close and reopen the Library Browser, the list reflects the blocks
that you added up through the previous session. The list updates only when
the Library Browser is open.
The list does not reflect blocks that you:
• Add programmatically
• Include in subsystems
If you add a subsystem that uses a specific type of block repeatedly, the list
does not reflect that activity.
The list in the Model Editor is the same as the Library Browser list, except
that the Model Editor list includes only five blocks.
Add Blocks Programmatically
To add a block programmatically, use the add_block function.
The add_block function copies the parameter values of the source block to
the new block. You can use add_block to specify values for parameters
of the new block.
23-8
Edit Blocks
Edit Blocks
In this section...
“Copy Blocks in a Model” on page 23-9
“Copy Blocks Between Windows” on page 23-10
“Move Blocks” on page 23-11
“Delete Blocks” on page 23-13
“Comment Out Blocks” on page 23-14
Copy Blocks in a Model
To copy a blocks in a model:
1 In the Simulink Editor, select the block.
2 Press right mouse button.
3 Drag the block to a new location and release the mouse button.
You can also do this by using the Ctrl key:
1 In the Simulink Editor, press and hold the Ctrl key.
2 Select the block with the left mouse button.
3 Drag the block to a new location and release the mouse button.
Copies of blocks have the same parameter values as the original blocks.
Sequence numbers are added to the new block names.
Note Simulink sorts block names alphabetically when generating names for
copies pasted into a model. This action can cause the names of pasted blocks to
be out of order. For example, suppose you copy a row of 16 gain blocks named
Gain, Gain1, Gain2...Gain15 and paste them into the model. The names of the
pasted blocks occur in the following order: Gain16, Gain17, Gain18...Gain31.
23-9
23
Working with Blocks
Copy Blocks Between Windows
As you build your model, you often copy blocks from Simulink block libraries
or other libraries or models into your model window. To do this:
1 Open the appropriate block library or model window.
2 Drag the block to copy into the target model window. To drag a block,
position the cursor over the block, then press and hold down the mouse
button. Move the cursor into the target window, then release the mouse
button.
You can also drag blocks from the Simulink Library Browser into a model
window. See “Browse Block Libraries” on page 4-4 for more information.
Note The names of Sum, Mux, Demux, Bus Creator, and Bus Selector blocks
are hidden when you copy them from the Simulink block library to a model.
This is done to avoid unnecessarily cluttering the model diagram. (The shapes
of these blocks clearly indicate their respective functions.)
You can also copy blocks by using the Simulink Editor:
1 Select the block you want to copy.
2 Select Edit > Copy.
3 Make the target model window the active window.
4 Choose Edit > Paste.
Simulink assigns a name to each copied block. If it is the first block of its type
in the model, its name is the same as its name in the source window. For
example, if you copy the Gain block from the Math library into your model
window, the name of the new block is Gain. If your model already contains
a block named Gain, Simulink adds a sequence number to the block name
(for example, Gain1, Gain2). You can rename blocks; see “Manipulate Block
Names” on page 23-26.
23-10
Edit Blocks
When you copy a block, the new block inherits all the original block’s
parameter values.
For more ways to add blocks, see “Add Blocks” on page 23-4.
add blocks
Move Blocks
To move a single block from one place to another in a model window, drag the
block to a new location. Simulink automatically repositions lines connected to
the moved block.
To move more than one block, including connecting lines:
1 Select the blocks and lines. For information about how to select more than
one block, see “Select Multiple Objects” on page 4-6.
2 Drag the objects to their new location and release the mouse button.
To move a block, disconnecting lines:
1 Select the block.
2 Press the Shift key, then drag the block to its new location and release
the mouse button.
You can also move a block by selecting the block and pressing the arrow keys.
You cannot move a block between:
• Multiple systems open in one Simulink Editor instance
• Systems open in multiple Simulink Editor instances
If you drag a block between Simulink Editor instances, the block is copied
to the target Simulink Editor model window.
23-11
23
Working with Blocks
Align Blocks
You can manually align blocks. You can also use commands that align a
group of blocks automatically (see “Align, Distribute, and Resize Groups of
Blocks” on page 4-22 for details).
Smart Guides. You can enable smart guides to help you align blocks and
lines. When you move a block, smart guides appear to indicate when the
block ports, center, or edges are aligned with the ports, centers, and edges of
other blocks in the same diagram.
To display smart guides, in the Simulink Editor, select View > Smart
Guides. The setting applies to all open instances of the Simulink Editor.
For example, the following figure shows a snapshot of a Gain block that
you drag from one position in a diagram to another. The blue smart guides
indicate that if you drop the Gain block at this position, its left edge is aligned
with the left edge of the Subsystem block and its output port is aligned with
the input port of the Saturation block.
When you drag a block, one of its alignment features, for example, a port,
may match more than one alignment feature of another block. In this case,
Simulink displays a line for one of the features, using the following precedence
order: ports, centers, edges. For example, in the following drag-and-drop
snapshot, the Gain block center aligns with the Subsystem block center
and the Gain block output port aligns with the Saturation block input port.
23-12
Edit Blocks
However, because ports take precedence over centers, Simulink draws a guide
only for the ports.
Position Blocks Programmatically
You can position (and resize) a block programmatically, using its Position
parameter. For example, the following command
set_param(gcb, 'Position', [5 5 20 20]);
moves the currently selected block to a location 5 points down and 5 points to
the right of the top left corner of the block diagram and sets the block’s height
and width to 20 points, respectively.
Note The maximum size of a block diagram’s height and width is 32767
points. An error message appears if you try to move or resize a block to a
position that exceeds the diagram’s boundaries.
Delete Blocks
To delete one or more blocks, select the blocks to be deleted and press the
Delete or Backspace key.
As an alternative, you can select Edit > ClearClear or Edit > Cut.
The Cut command writes the blocks into the clipboard, which enables you to
paste them into a model. Using the Delete or Backspace key or the Clear
command does not enable you to paste the block later.
To replace a deleted block, use the Edit > Undo command.
23-13
23
Working with Blocks
Comment Out Blocks
Comment out blocks in your model if you want to exclude them during
simulation. To exclude a block, right-click the selected block and select
Comment out.
Commenting out blocks may be useful for several tasks, such as:
• Incrementally testing parts of a model under development
• Debugging a model without having to delete and restore blocks between
simulation runs
• Testing and verifying the effects of certain model blocks on simulation
results
• Improving simulation performance
23-14
Set Block Properties
Set Block Properties
For each block in a model, you can set general block properties, such as:
• A description of the block
• The block’s order of execution
• A block annotation
• Block callback functions
Block Properties Dialog Box
To set these block properties, open the Block Properties dialog box.
1 In the Simulink Editor, select the block.
2 Select Diagram > Properties.
The Block Properties dialog box opens, with the General tab open. For
example:
23-15
23
Working with Blocks
General Block Properties
Description
Enter a brief description of the purpose of the block or any other descriptive
information.
23-16
Set Block Properties
Priority
Specify the execution priority of this block relative to other blocks in the
model. For more information, see “Assign Block Priorities” on page 23-47.
Tag
You can use a tag to create your own block-specific label for a block. Specify
text that Simulink assigns to the block’s Tag parameter and saves with the
block in the model.
Block Annotation Properties
Use the Block Annotation tab to display the values of selected block
parameters in an annotation that appears beneath the block’s icon.
23-17
23
Working with Blocks
Enter the text of the annotation in the text field that appears on the right
side of the pane. The text can include any of the block property tokens that
appear in the list on the left side of the pane. A block property token is simply
the name of a block parameter preceded by %< and followed by >. When
displaying the annotation, Simulink replaces the tokens with the values of
the corresponding block parameters. For example, suppose that you enter the
following text and tokens for a Product block:
23-18
Set Block Properties
Multiplication = %
Sample time = %
In the Simulink Editor model window, the annotation appears as follows:
The block property token list on the left side of the pane lists all the
parameters that are valid for the currently selected block (see “Common Block
Parameters” and “Block-Specific Parameters”). To add one of the listed tokens
to the text field on the right side of the pane, select the token and then click
the button between the list and the text field.
You can also create block annotations programmatically. See “Create Block
Annotations Programmatically” on page 23-21.
Block Callbacks
Use the Callbacks tab to specify implementations for a block’s callbacks (see
“Callback Functions” on page 4-54).
23-19
23
Working with Blocks
To specify an implementation for a callback, select the callback in the callback
list on the left side of the pane. Then enter MATLAB commands that
implement the callback in the right-hand field. Click OK or Apply to save the
change. Simulink appends an asterisk to the name of the saved callback to
indicate that it has been implemented.
23-20
Set Block Properties
Create Block Annotations Programmatically
You can use a block’s AttributesFormatString parameter to display selected
block parameters beneath the block as an “attributes format string,” which is
a string that specifies values of the block’s attributes (parameters). “Common
Block Parameters” and “Block-Specific Parameters” describe the parameters
that a block can have. Use the Simulink set_param function to set this
parameter to the desired attributes format string.
The attributes format string can be any text string that has embedded
parameter names. An embedded parameter name is a parameter name
preceded by %< and followed by >, for example, %. Simulink
displays the attributes format string beneath the block’s icon, replacing
each parameter name with the corresponding parameter value. You can use
line-feed characters (\n) to display each parameter on a separate line. For
example, enter the following at the MATLAB command prompt:
The Gain block displays the following block annotation:
If a parameter’s value is not a string or an integer, Simulink displays N/S
(not supported) for the parameter’s value. If the parameter name is invalid,
Simulink displays ??? as the parameter value.
23-21
23
Working with Blocks
Change the Appearance of a Block
In this section...
“Change a Block Orientation” on page 23-22
“Resize a Block” on page 23-24
“Displaying Parameters Beneath a Block” on page 23-25
“Drop Shadows” on page 23-25
“Manipulate Block Names” on page 23-26
“Specify Block Color” on page 23-28
Change a Block Orientation
By default, a block is oriented so that its input ports are on the left, and its
output ports are on the right. You can change the orientation of a block by
rotating it 90 degrees around its center or by flipping it 180 degrees around
its horizontal or vertical axis.
• “How to Rotate a Block” on page 23-22
• “How to Flip a Block” on page 23-24
How to Rotate a Block
You can rotate a block 90 degrees by selecting one of these commands from
the Diagram menu:
• Rotate & Flip > Clockwise (or Ctrl+R)
• Rotate & Flip > Counterclockwise
A rotation command effectively moves a block’s ports from its sides to its top
and bottom or from its top and bottom to its size, depending on the initial
orientation of the block. The final positions of the block ports depend on the
block’s port rotation type.
23-22
Change the Appearance of a Block
Port Rotation Type. After rotating a block clockwise, Simulink may,
depending on the block, reposition the block’s ports to maintain a left-to-right
port numbering order for ports along the top and bottom of the block and a
top-to-bottom port numbering order for ports along the left and right sides
of the block. A block whose ports are reordered after a clockwise rotation is
said to have a default port rotation type. This policy helps to maintain the
left-right and top-down block diagram orientation convention used in control
system modeling applications. All nonmasked blocks and all masked blocks
by default have the default rotation policy. The following figure shows the
effect of using the Rotate & FlipClockwise command on a block with the
default rotation policy.
A masked block can optionally specify that its ports not be reordered after a
clockwise rotation (see “Port Rotation”). Such a block is said to have a physical
port rotation type. This policy facilitates layout of diagrams in mechanical
and hydraulic systems modeling and other applications where diagrams do
not have a preferred orientation. The following figure shows the effect of
clockwise rotation on a block with a physical port rotation type
23-23
23
Working with Blocks
How to Flip a Block
Simulink provides a set of commands that allow you to flip a block 180 degrees
about its horizontal or vertical axis. The commands effectively move a block’s
input and output ports to opposite sides of the block or reverse the ordering of
the ports, depending on the block’s port rotation type.
A block with the default rotation type has one flip command:
Diagram > Rotate & Flip > Flip Block (Ctr+I). This command effectively
moves the block’s input and output ports to the side of the block opposite to
the side on which they are initially located, i.e., from the left to the right side
or from the top to the bottom side.
Resize a Block
To change the size of a block, select it, then drag any of its selection handles.
While you hold down the mouse button, a dotted rectangle shows the new
block size. When you release the mouse button, the block is resized.
For example, the following figure below shows a Signal Generator block
being resized. The lower-right handle was selected and dragged to the cursor
position. When the mouse button is released, the block takes its new size.
23-24
Change the Appearance of a Block
Tip Use the model editor’s resize blocks commands to make one block the
same size as another (see “Align, Distribute, and Resize Groups of Blocks”
on page 4-22).
Displaying Parameters Beneath a Block
You can cause Simulink to display one or more of a block’s parameters
beneath the block. Specify the parameters to be displayed by using one of the
following approaches:
• Enter an attributes format string in the Attributes format string field of
the block’s Properties dialog box (see “Set Block Properties” on page 23-15)
• Set the value of the block’s AttributesFormatString property to the
format string, using set_param
Drop Shadows
By default, blocks appear with a drop shadow.
To increase the depth of a block drop shadow:
1 Select the block.
2 Select Diagram > Format > Block Shadow.
For example, in this model, the Constant1 block has the Block Shadow
option enabled, and the Constant2 block uses the default drop shadow.
23-25
23
Working with Blocks
To remove the default drop shadows for all blocks, select File > Simulink
Preferences > Editor Defaults > Use classic diagram theme.
Manipulate Block Names
All block names in a model must be unique and must contain at least one
character. By default, block names appear below blocks whose ports are on
the sides, and to the left of blocks whose ports are on the top and bottom, as
the following figure shows:
Note Simulink commands interprets a forward slash (/) as a block path
delimiter. For example, the path vdp/Mu designates a block named Mu in the
model named vdp. Therefore, avoid using forward slashes (/) in block names
to avoid causing Simulink to interpret the names as paths.
Change Block Names
You can edit a block name in one of these ways:
• To replace the block name, click the block name, select the entire name,
and then enter the new name.
• 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.
23-26
Change the Appearance of a Block
When you click the pointer anywhere else in the model or take any other
action, the name is accepted or rejected. If you try to change the name of a
block to a name that already exists, Simulink displays an error message.
Note If you change the name of a library block, all links to that block become
unresolved.
Change Font of Block Name
To modify the font used in a block name by selecting the block, then choosing
the Font Style menu item from the Diagram > Format menu.
1 Select the block name.
2 Select Diagram > Format > Font Style.
The Select Font dialog box opens.
3 Select a font and specify other font characteristics, such as the font size.
Note Changing the block name font also changes the font of any text that
appears inside the block.
This procedure also changes the font of any text that appears inside the block.
Change the Location of a Block Name
To change the location of the name of a selected block, use one of these
approaches:
• Drag the block name to the opposite side of the block.
• Choose Diagram > Rotate & Flip > Flip Block Name. This command
changes the location of the block name to the opposite side of the block.
For more information about block orientation, see “How to Rotate a Block” on
page 23-22.
23-27
23
Working with Blocks
Hide a Block Name
By default the Simulink Editor displays the names of blocks (except for a few
blocks, such as the Bus Creator block). To hide the name of a selected block,
clear the Diagram > Format > Show Block Name menu option.
Specify Block Color
See “Specify Block Diagram Colors” on page 4-8 for information on how to
set the color of a block.
23-28
Display Port Values
Display Port Values
In this section...
“Port Value Data Tips” on page 23-29
“Display Value for a Port” on page 23-30
“Control the Port Value Display” on page 23-31
“Displayed Value When No Data Is Available” on page 23-32
“Port Value Display Limitations” on page 23-33
Port Value Data Tips
Signals can be data signals or non-data signals. For many blocks with data
signals, Simulink can display port values (block output) as data tips on the
block diagram while a simulation is running. The following model shows a
port value data tip for the Fcn block, displaying an output value of 3.03.
Displaying port value data tips can be helpful during interactive debugging of
a model. The data tips do not persist when you save a model, so do not rely on
data tips as a form of built-in documentation for the model.
23-29
23
Working with Blocks
In some cases, data signals are not accessible for display. In those cases, a
label such as wait might be displayed for optimized signals, or action might
be displayed for an action subsystem.
Note The port value display feature has limitations for models with:
• Accelerated modes
• Signal storage reuse
• Signals with some complex data types, such as bus signals
See “Port Value Display Limitations” on page 23-33.
Display Value for a Port
To display a data tip that shows the value of a port:
1 In the Simulink Editor model window, select a port.
2 Specify when the port value appears.
• To display the port value when you click on a port, select Display >
Data Display in Simulation > Show Value Label of Selected Port.
The data tip remains until you remove it.
• To display the port value when you hover the cursor over the port, select
Display > Data Display in Simulation > Show Value Labels
When Hovering. When you move the cursor away from the port, the
data tip disappears.
• To toggle between displaying and hiding the port value, select Display >
Data Display in Simulation > Toggle Value Labels When Clicked.
Reselecting that block turns off the display. If you select a block with
this port value display method, then change the display method to Show
When Hovering, the port value for that block continues to display.
To remove the all displayed port value data tips, select Display > Data
Display in Simulation > Remove All Value Labels.
23-30
Display Port Values
Control the Port Value Display
To specify port value display formatting and how frequently the display
updates:
1 In the Simulink Editor model window, select a port.
2 Select Display > Data Display in Simulation > Options. The Value
Label Display Options dialog box opens.
3 In the Value Label Display Options dialog box, select the appropriate
option.
Port Value Data Tip Display
Characteristic
What You Specify
When to display the port value
Choose Show When Hovering,
Toggle When Clicked, or Remove
All. For details, see “Display Value
for a Port” on page 23-30.
Text size
To increase the size of the output
display text, move the Font size
slider to the right.
23-31
23
Working with Blocks
Port Value Data Tip Display
Characteristic
What You Specify
Floating point data format
Choose a floating point format from
the Floating point list.
Fixed-point data format
Choose a fixed-point format from the
Fix point list.
Refresh interval (rate at which
Simulink updates the output
display)
To increase the interval, move the
Approximate refresh interval:
1.0 slider to the right.
The refresh rate is approximate and
is independent of simulation time.
Number of elements in port value
display
To change the number of elements
to display in the port value display,
move the Maximum number of
elements per label: 3 slider to the
left or right. This setting affects the
number of elements displayed for
vector or matrix signals with signal
widths greater than 1. This setting
does not affect scalar signals.
Displayed Value When No Data Is Available
Simulink displays an empty box when you toggle or hover on a block,
indicating that no port value is available. You see the empty box if you did
not run the simulation.
Also, if you toggle or hover on a block that Simulink optimizes out of a
simulation (such as a virtual subsystem block), the model displays a wait
string before displaying the port value during simulation.
To prevent the optimization delay of the port value display, designate
the signal as a test point. This enables the port value display to update
immediately.
23-32
Display Port Values
Port Value Display Limitations
Performance
Enabling the hovering option, or toggling at least one block, slows down the
simulation.
Accelerated Modes
Port values display as follows.
Accelerated
Mode
Port Values...
Accelerator
Display as in Normal mode. See “Port Value Data Tips”
on page 23-29.
Rapid
Accelerator
Do not display. The limitation exists whether the model
itself specifies accelerated simulation or the model is
subordinate to a model that specifies accelerated simulation.
For more information, see “Rapid Simulations”.
Signal Storage Reuse
Invoking the port value displays the text optimized when the software cannot
determine the signal value, if you:
• Select Show When Hovering or Toggle When Clicked.
• Enable the Configuration Parameters > Optimization > Signals and
Parameters > Signal storage reuse parameter.
Disabling signal storage reuse increases the amount of memory used during
simulation.
Signal Data Types
Simulink displays the port value for ports connected to most kinds of signals,
including signals with built-in data types (such as double, int32, or Boolean),
DYNAMICALLY_TYPED, and several other data types. However, Simulink does
not display data for signals with some complex data types, such as bus
23-33
23
Working with Blocks
signals. In addition, the software shows the floating and fixed-point formats
for only non-complex signal value displays.
23-34
Control and Displaying the Sorted Order
Control and Displaying the Sorted Order
In this section...
“What Is Sorted Order?” on page 23-35
“Display the Sorted Order” on page 23-35
“Sorted Order Notation” on page 23-36
“How Simulink Determines the Sorted Order” on page 23-45
“Assign Block Priorities” on page 23-47
“Rules for Block Priorities” on page 23-48
“Block Priority Violations” on page 23-51
What Is Sorted Order?
During the updating phase of simulation, Simulink determines the order in
which to invoke the block methods during simulation. This block invocation
ordering is the sorted order.
You cannot set this order, but you can assign priorities to nonvirtual blocks to
indicate to Simulink their execution order relative to other blocks. Simulink
always honors block priority settings, unless there is a conflict with data
dependencies. To confirm the results of priorities that you have set, or to
debug your model, display and review the sorted order of your nonvirtual
blocks and subsystems.
Note For more information about block methods and execution, see:
• “Block Methods” on page 3-16
• “Conditional Execution Behavior” on page 7-32
Display the Sorted Order
To display the sorted order of the vdp model:
23-35
23
Working with Blocks
1 Open the van der Pol equation model:
vdp
2 In the model window, select Format > Block Displays > Sorted Order.
Simulink displays a notation in the top-right corner of each nonvirtual block
and each nonvirtual subsystem. These numbers indicate the order in which
the blocks execute. The first block to execute has a sorted order of 0.
For example, in the van der Pol equation model, the Integrator block with the
sorted order 0:0 executes first. The Out1 block, with the sorted order 0:1,
executes second. Similarly, the remaining blocks execute in numeric order
from 0:2 to 0:8.
You can save the sorted order setting with your model. To display the sorted
order when you reopen the model, select Simulation > Update diagram.
Sorted Order Notation
The sorted order notation varies depending on the type of block. The following
table summarizes the different formats of sorted order notation. Each format
is described in detail in the sections that follows the table.
23-36
Control and Displaying the Sorted Order
Block Type
Sorted Order Notation
Description
“Nonvirtual
Blocks” on page
23-38
s:b
• s is the system index of the model or
subsystem. For root-level models, s is
always 0.
• b specifies the block position within the
sorted order for the designated execution
context.
“Nonvirtual
Subsystems” on
page 23-39
s:b{ si}
• s is the system index of the model or
subsystem.
• b specifies the block position within the
sorted order for the designated execution
context.
• si is the subsystem index.
“Virtual Blocks
and Subsystems”
on page 23-41
Not applicable
Virtual blocks do not execute.
“Function-Call
Subsystems” on
page 23-42
One initiator:
• s is the system index of the model or
subsystem.
s:F{ si}
• F indicates a function-call subsystem.
• si is the subsystem index.
Two or more initiators:
• s:F{ si} when the initiators
all execute at the same
level of the model hierarchy
• M:F{si}, when the initiators
execute at different levels
of the model hierarchy
• s is the system index of the initiators.
• F indicates a function-call subsystem.
• si is the subsystem index.
• M indicates that the initiators execute at
different levels of the model hierarchy.
23-37
23
Working with Blocks
Block Type
Sorted Order Notation
Description
“Function-Call
Split Blocks” on
page 23-44
s:Bb
• s is a system index of the model or
subsystem.
• B indicates a branch of the function-call
signal.
• b specifies the index of each subsystem
connected to each branch of the given
function-call signal.
“Bus-Capable
Blocks” on page
23-45
s:B
• s is a system index of the model or
subsystem.
• B indicates a bus-capable block.
• “Nonvirtual Blocks” on page 23-38
• “Nonvirtual Subsystems” on page 23-39
• “Virtual Blocks and Subsystems” on page 23-41
• “Function-Call Subsystems” on page 23-42
• “Function-Call Split Blocks” on page 23-44
• “Bus-Capable Blocks” on page 23-45
Nonvirtual Blocks
In the van der Pol equation model, all the nonvirtual blocks in the model have
a sorted order. The system index for the top-level model is 0, and the block
execution order ranges from 0 to 8.
23-38
Control and Displaying the Sorted Order
Nonvirtual Subsystems
The following model contains an atomic, nonvirtual subsystem named
Discrete Cruise Controller.
When you enable the sorted order display for the root-level system, Simulink
displays the sorted order of the blocks.
The Scope block in this model has the lowest sorted order, but its input
depends on the output of the Car Dynamics subsystem. The Car Dynamics
subsystem is virtual, so it does not have a sorted order and does not execute
as an atomic unit. However, the blocks within the subsystem execute at the
root level, so the Integrator block in the Car Dynamics subsystem executes
first. The Integrator block sends its output to the Scope block in the root-level
model, which executes second.
23-39
23
Working with Blocks
The Discrete Cruise Controller subsystem has a sorted order of 0:5{1}:
• 0 indicates that this atomic subsystem is part of the root level of
the hierarchal system comprised of the primary system and the two
subsystems.
• 5 indicates that the atomic subsystem is the sixth block that Simulink
executes relative to the blocks within the root level.
• {1} represents the subsystem index. This index does not indicate the
relative order in which the atomic subsystem runs.
The sorted order of each block inside the Discrete Cruise Controller subsystem
has the form 1:b, where:
• 1 is the system index for that subsystem.
• b is the block position in the execution order. In the Discrete Cruise
Controller subsystem, the sorted order ranges from 0 to 8.
23-40
Control and Displaying the Sorted Order
Virtual Blocks and Subsystems
Virtual blocks, such as the Mux block, exist only graphically and do not
execute. Consequently, they are not part of the sorted order and do not
display any sorted order notation.
Virtual subsystems do not execute as a unit, and like a virtual block, are not
part of the sorted order. The blocks inside the virtual subsystem are part of
the root-level system sorted order, and therefore share the system index.
In the model in “Nonvirtual Subsystems” on page 23-39, the virtual subsystem
Car Dynamics does not have a sorted order. However, the blocks inside
the subsystem have a sorted order in the execution context of the root-level
model. The blocks have the same system index as the root-level model. The
Integrator block inside the Car Dynamics subsystem has a sorted order of
0:0, indicating that the Integrator block is the first block executed in the
context of the top-level model.
23-41
23
Working with Blocks
Function-Call Subsystems
Single Initiator. For each function-call subsystem or model attached to a
single initiator, Simulink assigns the block position F. The function-call
subsystem (or model) executes when the initiator invokes the function-call
subsystem (or model) and, therefore, does not have a sorted order independent
of its initiator. Specifically, for a subsystem that connects to one initiator,
Simulink uses the notation s:F{ si}, where s is the index of the system that
contains the initiator.
For example, the sorted order for the ThresholdCalculation subsystem is
1:F{2}:
• 1 is the index of the system that contains the initiator, in this case, the
ShiftLogic Stateflow chart.
• F indicates that this function-call subsystem connects to one initiator.
• 2 is the system index for the ThresholdCalculation subsystem.
23-42
Control and Displaying the Sorted Order
Multiple Initiators. For a function-call subsystem that connects to more
than one initiator, the sorted order notation depends on the execution context
of the initiators:
• If the initiators all execute at the same level of the model hierarchy, the
notation is s:F{si}.
• If the initiators execute at different levels of the model hierarchy, the
notation is M:F{si}
For example, open the sl_subsysm_fcncall6 model. The f subsystem has
three initiators, two from the Stateflow chart, Chart1, and one from the
Stateflow chart, Chart.
Because Chart1 has a system index of 2 and Chart has a system index of
1, the initiators execute at different levels in the model hierarchy. The
Function-Call Subsystem f has a sorted order notation of M:F{3}.
23-43
23
Working with Blocks
Function-Call Split Blocks
When a function-call signal is branched using a Function-Call Split block,
Simulink displays the order in which subsystems (or models) that connect to
the branches execute when the initiator invokes the function call. Simulink
uses the notation s:Bb to indicate this order, where B stands for branch. The
block position b ranges from 0 to one less than the total number of subsystems
(or models) that connect to branches (B0, B1, etc.). When the function-call is
invoked, the subsystems execute in ascending order based on this number.
For example, open the sl_subsys_fcncall11 model and display the sorted
order. The sorted order indicates that the subsystem f (B0) executes before
the subsystem g (B1).
23-44
Control and Displaying the Sorted Order
Bus-Capable Blocks
A bus-capable block does not execute as a unit and therefore does not have
a unique sorted order. Such a block displays its sorted order as s:B where
B stands for bus.
For example, open the sldemo_bus_arrays model and display the sorted
order. Open the For Each Subsystem to see that the sorted order for the
Bus Assignment block appears as 1:B.
For more information, see “Bus-Capable Blocks” on page 48-19.
How Simulink Determines the Sorted Order
Direct-Feedthrough Ports Impact on Sorted Order
To ensure that the sorted order reflects data dependencies among blocks,
Simulink categorizes block input ports according to the dependency of the
block outputs on the block input ports. An input port whose current value
determines the current value of one of the block outputs is a direct-feedthrough
port. Examples of blocks that have direct-feedthrough ports include:
• Gain
• Product
• Sum
Examples of blocks that have non-direct-feedthrough inputs:
• Integrator — Output is a function of its state.
• Constant — Does not have an input.
23-45
23
Working with Blocks
• Memory — Output depends on its input from the previous time step.
Rules for Sorting Blocks
To sort blocks, Simulink uses the following rules:
• If a block drives the direct-feedthrough port of another block, the block
must appear in the sorted order ahead of the block that it drives.
This rule ensures that the direct-feedthrough inputs to blocks are valid
when Simulink invokes block methods that require current inputs.
• Blocks that do not have direct-feedthrough inputs can appear anywhere
in the sorted order as long as they precede any direct-feedthrough blocks
that they drive.
Placing all blocks that do not have direct-feedthrough ports at the
beginning of the sorted order satisfies this rule. This arrangement allows
Simulink to ignore these blocks during the sorting process.
Applying these rules results in the sorted order. Blocks without
direct-feedthrough ports appear at the beginning of the list in no particular
order. These blocks are followed by blocks with direct-feedthrough ports
arranged such that they can supply valid inputs to the blocks which they drive.
The following model, from “Nonvirtual Subsystems” on page 23-39, illustrates
this result. The following blocks do not have direct-feedthrough and therefore
appear at the beginning of the sorted order of the root-level system:
• Integrator block in the Car Dynamics virtual subsystem
• Speed block in the root-level model
23-46
Control and Displaying the Sorted Order
Inside the Discrete Cruise Controller subsystem, all the Gain blocks, which
have direct-feedthrough ports, run before the Sum block that they drive.
Assign Block Priorities
You can assign a priority to a nonvirtual block or to an entire subsystem.
Higher priority blocks appear before lower priority blocks in the sorted order.
The lower the number, the higher the priority.
• “Assigning Block Priorities Programmatically” on page 23-48
• “Assigning Block Priorities Interactively” on page 23-48
23-47
23
Working with Blocks
Assigning Block Priorities Programmatically
To set priorities programmatically, use the command:
set_param(b,'Priority','n')
where
• b is the block path.
• n is any valid integer. (Negative integers and 0 are valid priority values.)
Assigning Block Priorities Interactively
To set the priority of a block or subsystem interactively:
1 Right-click the block and select Properties.
2 On the General tab, in the Priority field, enter the priority.
Rules for Block Priorities
Simulink honors the block priorities that you specify unless they violate data
dependencies. (“Block Priority Violations” on page 23-51 describes situations
that cause block property violations.)
In assessing priority assignments, Simulink attempts to create a sorted order
such that the priorities for the individual blocks within the root-level system
or within a nonvirtual subsystem are honored relative to one another.
Three rules pertain to priorities:
• “Priorities Are Relative” on page 23-48
• “Priorities Are Hierarchical” on page 23-50
• “Lack of Priority May Not Result in Low Priority” on page 23-51
Priorities Are Relative
Priorities are relative; the priority of a block is relative to the priority of the
blocks within the same system or subsystem.
23-48
Control and Displaying the Sorted Order
For example, suppose you set the following priorities in the Discrete Cruise
Controller subsystem in the model in “Nonvirtual Subsystems” on page 23-39.
Block
Priority
Gain
3
Gain1
2
Gain2
1
After updating the diagram, the sorted order for the Gain blocks is as follows.
The sorted order values of the Gain, Gain1, and Gain2 blocks reflect the
respective priorities assigned: Gain2 has highest priority and executes
before Gain1 and Gain; Gain1 has second priority and executes after Gain2;
and Gain executes after Gain1. Simulink takes into account the assigned
priorities relative to the other blocks in that subsystem.
The Gain blocks are not the first, second, and third blocks to execute. Nor
do they have consecutive sorted orders. The sorted order values do not
23-49
23
Working with Blocks
necessarily correspond to the priority values. Simulink arranges the blocks so
that their priorities are honored relative to each other.
Priorities Are Hierarchical
In the Car Dynamics virtual subsystem, suppose you set the priorities of
the Gain blocks as follows.
Block
Priority
Gain
2
Gain1
1
After updating the diagram, the sorted order for the Gain blocks is as
illustrated. With these priorities, Gain1 always executes before Gain.
You can set a priority of 1 to one block in each of the two subsystems because
of the hierarchal nature of the subsystems within a model. Simulink never
compares the priorities of the blocks in one subsystem to the priorities of
blocks in any other subsystem.
For example, consider this model again.
23-50
Control and Displaying the Sorted Order
The blocks within the Car Dynamics virtual subsystem are part of the
root-level system hierarchy and are part of the root-level sorted order. The
Discrete Cruise Controller subsystem has an independent sorted order with
the blocks arranged consecutively from 1:0 to 1:7.
Lack of Priority May Not Result in Low Priority
A lack of priority does not necessarily result in a low priority (higher sorting
order) for a given block. Blocks that do not have direct-feedthrough ports
execute before blocks that have direct-feedthrough ports, regardless of their
priority.
If a model has two atomic subsystems, A and B, you can assign priorities of
1 and 2 respectively to A and B. This priority causes all the blocks in A to
execute before any of the blocks in B. The blocks within an atomic subsystem
execute as a single unit, so the subsystem has its own system index and its
own sorted order.
Block Priority Violations
Simulink software honors the block priorities that you specify unless they
violate data dependencies. If Simulink is unable to honor a block priority, it
displays a Block Priority Violation diagnostic message.
As an example:
1 Open the sldemo_bounce model.
Notice that the output of the Memory block provides the input to the
Coefficient of Restitution Gain block.
23-51
23
Working with Blocks
2 Set the priority of the Coefficient of Restitution block to 1, and set the
priority of the Memory block to 2.
Setting these priorities specifies that the Coefficient of Restitution block
execute before the Memory block. However, the Coefficient of Restitution
block depends on the output of the Memory block, so the priorities you just
set violate the data dependencies.
3 In the model window, enable sorted order by selecting Format > Block
displays > Sorted Order.
4 Select Simulation > Update Diagram.
The block priority violation warning appears in the MATLAB Command
Window. The warning includes the priority for the respective blocks:
Warning: Unable to honor user-specified priorities.
'sldemo_bounce/Memory' (pri=[2]) has to execute
before 'sldemo_bounce/Coefficient of Restitution'
(pri=[1]) to satisfy data dependencies
5 Remove the priorities from the Coefficient of Restitution and Memory
blocks and update the diagram again to see the correct sorted order.
23-52
Access Block Data During Simulation
Access Block Data During Simulation
In this section...
“About Block Run-Time Objects” on page 23-53
“Access a Run-Time Object” on page 23-53
“Listen for Method Execution Events” on page 23-54
“Synchronizing Run-Time Objects and Simulink Execution” on page 23-55
About Block Run-Time Objects
Simulink provides an application programming interface, called the block
run-time interface, that enables programmatic access to block data, such
as block inputs and outputs, parameters, states, and work vectors, while a
simulation is running. You can use this interface to access block run-time
data from the MATLAB command line, the Simulink Debugger, and from
Level-2 MATLAB S-functions (see “Write Level-2 MATLAB S-Functions” in
the online Simulink documentation).
Note You can use this interface even when the model is paused or is running
or paused in the debugger.
The block run-time interface consists of a set of Simulink data object classes
(see “Data Objects” on page 43-37) whose instances provide data about
the blocks in a running model. In particular, the interface associates an
instance of Simulink.RunTimeBlock, called the block’s run-time object, with
each nonvirtual block in the running model. A run-time object’s methods
and properties provide access to run-time data about the block’s I/O ports,
parameters, sample times, and states.
Access a Run-Time Object
Every nonvirtual block in a running model has a RuntimeObject parameter
whose value, while the simulation is running, is a handle for the blocks’
run-time object. This allows you to use get_param to obtain a block’s run-time
object. For example, the following statement
23-53
23
Working with Blocks
rto = get_param(gcb,'RuntimeObject');
returns the run-time object of the currently selected block.
Note Virtual blocks (see “Virtual Blocks” on page 23-2) do not have run-time
objects. Blocks eliminated during model compilation as an optimization also
do not have run-time objects (see “Block reduction”). A run-time object exists
only while the model containing the block is running or paused. If the model
is stopped, get_param returns an empty handle. When you stop or pause a
model, all existing handles for run-time objects become empty.
Listen for Method Execution Events
One application for the block run-time API is to collect diagnostic data at
key points during simulation, such as the value of block states before or
after blocks compute their outputs or derivatives. The block run-time API
provides an event-listener mechanism that facilitates such applications. For
more information, see the documentation for the add_exec_event_listener
command. For an example of using method execution events, enter
sldemo_msfcn_lms
at the MATLAB command line. This Simulink model contains the S-function
adapt_lms.m, which performs a system identification to determine the
coefficients of an FIR filter. The S-function’s PostPropagationSetup method
initializes the block run-time object’s DWork vector such that the second
vector stores the filter coefficients calculated at each time step.
In the Simulink model, double-clicking on the annotation below the S-function
block executes its OpenFcn. This function first opens a figure for plotting the
FIR filter coefficients. It then executes the function add_adapt_coef_plot.m
to add a PostOutputs method execution event to the S-function’s block
run-time object using the following lines of code.
% Get the full path to the S-function block
blk = 'sldemo_msfcn_lms/LMS Adaptive';
% Attach the event-listener function to the S-function
h
= add_exec_event_listener(blk, ...
23-54
Access Block Data During Simulation
'PostOutputs', @plot_adapt_coefs);
The function plot_adapt_coefs.m is registered as an event listener that is
executed after every call to the S-function’s Outputs method. The function
accesses the block run-time object’s DWork vector and plots the filter
coefficients calculated in the Outputs method. The calling syntax used in
plot_adapt_coefs.m follows the standard needed for any listener. The first
input argument is the S-function’s block run-time object, and the second
argument is a structure of event data, as shown below.
function plot_adapt_coefs(block, eventData)
% The figure's handle is stored in the block's UserData
hFig = get_param(block.BlockHandle,'UserData');
tAxis = findobj(hFig, 'Type','axes');
tAxis = tAxis(2);
tLines = findobj(tAxis, 'Type','Line');
% The filter coefficients are stored in the block run-time
%
object's second DWork vector.
est = block.Dwork(2).Data;
set(tLines(3),'YData',est);
Synchronizing Run-Time Objects and Simulink
Execution
You can use run-time objects to obtain the value of a block output and display
in the MATLAB Command Window by entering the following commands.
rto = get_param(gcb,'RuntimeObject')
rto.OutputPort(1).Data
However, the displayed data may not be the true block output if the run-time
object is not synchronized with the Simulink execution. Simulink only
ensures the run-time object and Simulink execution are synchronized when
the run-time object is used either within a Level-2 MATLAB S-function or
in an event listener callback. When called from the MATLAB Command
Window, the run-time object can return incorrect output data if other blocks
in the model are allowed to share memory.
23-55
23
Working with Blocks
To ensure the Data field contains the correct block output, open the
Configuration Parameters dialog box, and then clear the Signal storage
reuse check box on the Optimization > Signals and Parameters pane
(see “Signal storage reuse”).
23-56
Configure a Block for Code Generation
Configure a Block for Code Generation
Use the State Attributes pane of a Block Parameters dialog box to specify
Simulink Coder code generation options for blocks with discrete states. See
“States” in the Simulink Coder documentation.
23-57
23
23-58
Working with Blocks
24
Working with Block
Parameters
• “About Block Parameters” on page 24-2
• “Set Block Parameters” on page 24-4
• “Specify Parameter Values” on page 24-6
• “Check Parameter Values” on page 24-9
• “Tunable Parameters” on page 24-13
• “Inline Parameters” on page 24-14
• “Structure Parameters” on page 24-16
24
Working with Block Parameters
About Block Parameters
Most Simulink blocks have attributes whose values you can specify to
customize the block. Some attributes are common to all Simulink blocks, such
as a block’s name and foreground color. Other attributes are specific to a
block, such as the gain of a Gain block. Simulink associates a block parameter
with each user-specifiable attribute of a block. Block parameters fall into
two categories. A mathematical parameter is a parameter used to compute
the value of a block’s output, such as a Gain block’s Gain parameter. All
other parameters are configuration parameters, such as a Gain block’s Name
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.
You specify a block attribute value by setting its associated block parameter.
For example, to set the foreground color of a block to red, you set the value
of its foreground color parameter to the string 'red'. You can set the value
programmatically, using the set_param command, or by using the block
parameters dialog box. See “Common Block Parameters” and “Block-Specific
Parameters” for the names, usages, and valid settings for Simulink block
parameters.
You can use MATLAB expressions to specify block parameter values.
The expressions can include the names of workspace variables. Simulink
evaluates the expressions before running a simulation, resolving any names
to values as described in “Symbol Resolution” on page 4-76. Do not confuse
Simulink block parameters with Simulink parameter objects. See “Block
Parameters” on page 3-9 and Simulink.Parameter for more information.
A tunable parameter is a block parameter whose value can be changed during
simulation without recompiling the model. In general, you can change the
values of mathematical parameters, but not configuration parameters. If a
parameter is not tunable and simulation is running, the dialog box control
that sets the parameter value is disabled.
24-2
About Block Parameters
If you change a tunable parameter value programmatically while simulation
is running, Simulink pauses the simulation, makes the change, then resumes
the simulation after the change is complete. Tunable parameter changes take
effect at the start of the next time step after simulation resumes.
You can use the Inline parameters check box on the
Optimization > Signals and Parameters pane of the Configuration
Parameters dialog box to specify that all parameters in your model are
nontunable except for those that you specify. This action can speed
up execution of large models and enable generation of faster code from
your model. See “Optimization Pane: Signals and Parameters” for more
information.
You can separately define each MATLAB variable intended for use in block
parameter expressions. However, this technique has several disadvantages,
such as cluttering the base workspace and providing no convenient way to
group related parameters. To avoid these disadvantages, you can combine
numeric base workspace variables into a MATLAB structure, then:
• Dereference the structure fields to provide values used in block parameter
expressions
• Pass a whole structure as an argument to a masked subsystem or a
referenced model
• Set the structure to be tunable or nontunable as you could a separately
defined variable
A structure used for any of these purposed can contain only numeric data. See
“Structure Parameters” on page 24-16 for more information.
24-3
24
Working with Block Parameters
Set Block Parameters
You can use the Simulink set_param command to set the value of any
Simulink block parameter. In addition, you can set many block parameters
via Simulink dialog boxes and menus. These include:
• Format menu
The Simulink Editor’s Diagram > Format menu allows you to specify
attributes of the currently selected block that are visible on the model’s
block diagram, such as the block’s name and color (see “Change the
Appearance of a Block” on page 23-22 for more information).
• Block Properties dialog box
Specifies various attributes that are common to all blocks (see “Set Block
Properties” on page 23-15 for more information).
• Block Parameter dialog box
Every block has a dialog box that allows you to specify values for attributes
that are specific to that type of block. See “Display a Block Parameter
Dialog Box” on page 24-4 for information on displaying a block’s parameter
dialog box.
• Model Explorer
The Model Explorer allows you to quickly find one or more blocks and set
their properties, thus facilitating global changes to a model, for example,
changing the gain of all of a model’s Gain blocks. See “Model Explorer
Overview” on page 9-2 for more information.
Display a Block Parameter Dialog Box
To display a block’s parameter dialog box, double-click the block in the
model or library window. You can also display a block’s parameter dialog
box by selecting the block in the model’s block diagram and choosing Block
Parameters from the Simulink Editor’s Diagram menu or from the block’s
context (right-click) menu.
24-4
Set Block Parameters
Note Double-clicking a block to display its parameter dialog box works for all
blocks with parameter dialog boxes except for Subsystem blocks and the Model
block. You must use the Simulink Editor’s Diagram menu or the block’s
context menu to display a Subsystem or Model block’s parameter dialog box.
24-5
24
Working with Block Parameters
Specify Parameter Values
In this section...
“About Parameter Values” on page 24-6
“Use Workspace Variables in Parameter Expressions” on page 24-6
“Resolve Variable References in Block Parameter Expressions” on page 24-7
“Use Parameter Objects to Specify Parameter Values” on page 24-7
“Determine Parameter Data Types” on page 24-7
About Parameter Values
Many block parameters, including mathematical parameters, accept MATLAB
expression strings as values. When Simulink compiles a model, for example,
at the start of a simulation or when you update the model, Simulink sets the
compiled values of the parameters to the result of evaluating the expressions.
Use Workspace Variables in Parameter Expressions
Block parameter expressions can include variables defined in the model’s
mask and model workspaces and in the MATLAB workspace. Using a
workspace variable facilitates updating a model that sets multiple block
parameters to the same value, i.e., it allows you to update multiple parameters
by setting the value of a single workspace variable. For more information,
see “Symbol Resolution” on page 4-76 and “Numeric Values with Symbols”
on page 4-78.
Using a workspace variable also allows you to change the value of a parameter
during simulation without having to open a block’s parameter dialog box. For
more information, see “Tunable Parameters” on page 24-13.
Note If you have a Simulink Coder license, and you plan to generate code
from a model, you can use workspace variables to specify the name, data type,
scope, volatility, tunability, and other attributes of variables used to represent
the parameter in the generated code. For more information, see “Parameters”
in the Simulink Coder documentation.
24-6
Specify Parameter Values
Resolve Variable References in Block Parameter
Expressions
When evaluating a block parameter expression that contains a variable,
Simulink by default searches the workspace hierarchy. If the variable is
not defined in any workspace, Simulink halts compilation of the model
and displays an error message. See “Symbol Resolution” on page 4-76 and
“Numeric Values with Symbols” on page 4-78 for more information.
Use Parameter Objects to Specify Parameter Values
You can use Simulink.Parameter objects in parameter expressions
to specify parameter values. For example, K and 2*K are both valid
parameter expressions where K is a workspace variable that references a
Simulink.Parameter object. In both cases, Simulink uses the parameter
object’s Value property as the value of K. See “Symbol Resolution” on page
4-76 and “Numeric Values with Symbols” on page 4-78for more information.
Using parameter objects to specify parameters can facilitate tuning
parameters in some applications. See “Using a Parameter Object to Specify
a Parameter As Noninlined” on page 24-15 and “Parameterize Model
References” on page 6-52 for more information.
Note Do not use expressions of the form p.Value where p is a parameter
object in block parameter expressions. Such expressions cause evaluation
errors when Simulink compiles the model.
Determine Parameter Data Types
When Simulink compiles a model, each of the model’s blocks determines a
data type for storing the values of its parameters whose values are specified
by MATLAB parameter expressions.
Most blocks use internal rules to determine the data type assigned to a
specific parameter. Exceptions include the Gain block, whose parameter
dialog box allows you to specify the data type assigned to the compiled value
of its Gain parameter. You can configure your model to check whether the
data type assigned to a parameter can accommodate the parameter value
specified by the model (see “Data Validity Diagnostics Overview”).
24-7
24
Working with Block Parameters
Obtain Parameter Information
You can use get_param to find the system and block parameter values for
your model. See “Model Parameters” and “Common Block Parameters” for
arguments get_param accepts.
The model’s signal attributes and parameter expressions must be evaluated
before some parameters are properly reported. This evaluation occurs during
the simulation compilation phase. Alternatively, you can compile your
model without first running it, and then obtain parameter information. For
instance, to access the port width, data types, and dimensions of the blocks in
your model, enter the following at the command prompt:
modelname([],[],[],'compile')
q=get_param(gcb,'PortHandles');
get_param(q.Inport,'CompiledPortDataType')
get_param(q.Inport,'CompiledPortWidth')
get_param(q.Inport,'CompiledPortDimensions')
modelname([],[],[],'term')
24-8
Check Parameter Values
Check Parameter Values
In this section...
“About Value Checking” on page 24-9
“Blocks That Perform Parameter Range Checking” on page 24-9
“Specify Ranges for Parameters” on page 24-10
“Perform Parameter Range Checking” on page 24-11
About Value Checking
Many blocks perform range checking of their mathematical parameters.
Generally, blocks that allow you to enter minimum and maximum values
check to ensure that the values of applicable parameters lie within the
specified range.
Blocks That Perform Parameter Range Checking
The following blocks perform range checking for their parameters:
Block
Parameters Checked
Constant
Constant value
Data Store Memory
Initial value
Gain
Gain
Interpolation Using Prelookup
Table data
1-D Lookup Table
Table data
2-D Lookup Table
Table data
n-D Lookup Table
Table data
Relay
Output when on
Output when off
Repeating Sequence Interpolated
Vector of output values
24-9
24
Working with Block Parameters
Block
Parameters Checked
Repeating Sequence Stair
Vector of output values
Saturation
Upper limit
Lower limit
Specify Ranges for Parameters
In general, use the Output minimum and Output maximum parameters
that appear on a block parameter dialog box to specify a range of valid values
for the block parameters. The following exceptions apply:
• For the Gain block, use the Parameter minimum and Parameter
maximum fields to specify a range for the Gain parameter.
• For the Data Store Memory block, use the Minimum and Maximum fields
to specify a range for the Initial value parameter.
When specifying minimum and maximum values that constitute a range,
enter only expressions that evaluate to a finite, scalar, real number with
double data type. The default values for the minimum and maximum are []
(unspecified). The scalar values that you specify are subject to expansion, for
example, when the block parameters that Simulink checks are nonscalar (see
“Scalar Expansion of Inputs and Parameters” on page 47-38).
Note You cannot specify the minimum or maximum value as NaN, inf, or
inf.
Specifying Ranges for Complex Numbers
When you specify a minimum or maximum value for a parameter that is a
complex number, the specified minimum and maximum apply separately
to the real part and to the imaginary part of the complex number. If the
value of either part of the number is less than the minimum, or greater than
the maximum, the complex number is outside the specified range. No range
checking occurs against any combination of the real and imaginary parts,
such as (sqrt(a^2+b^2))
24-10
Check Parameter Values
Perform Parameter Range Checking
You can initiate parameter range checking in the following ways:
• When you click the OK or Apply button on a block parameter dialog box,
the block performs range checking for its parameters. However, the block
checks only the parameters that it can readily evaluate. For example, the
block does not check parameters that use an undefined workspace variable.
• In the Simulink Editor, when you start a simulation or select
Simulation > Update Diagram, Simulink performs parameter range
checking for all blocks in that model.
Simulink performs parameter range checking by comparing the values of
applicable block parameters with both the specified range (see “Specify
Ranges for Parameters” on page 24-10) and the block data type. That is,
Simulink performs the following check:
DataTypeMin
MinValue
VALUE
MaxValue
DataTypeMax
where
• DataTypeMin is the minimum value representable by the block data type.
• MinValue is the minimum value the block should output, specified by, e.g.,
Output minimum.
• VALUE is the numeric value of a block parameter.
• MaxValue is the maximum value the block should output, specified by, e.g.,
Output maximum.
• DataTypeMax is the maximum value representable by the block data type.
When Simulink detects a parameter value that violates the check, it displays
an error message. For example, consider a model that contains a Constant
block whose
• Constant value parameter specifies the variable const, which you have
yet to define in a workspace.
• Output minimum and Output maximum parameters are set to 2 and
8, respectively.
24-11
24
Working with Block Parameters
• Output data type parameter is set to uint8.
In this situation, Simulink does not perform parameter range checking when
you click the OK button on the Constant block dialog box because the variable
const is undefined. But suppose you define its value by entering
const = 10
at the MATLAB prompt, and then you update the diagram (see “Update a
Block Diagram” on page 1-25). Simulink displays the following error message:
24-12
Tunable Parameters
Tunable Parameters
In this section...
“About Tunable Parameters” on page 24-13
“Tune a Block Parameter” on page 24-13
About Tunable Parameters
Simulink lets you change the values of many block parameters during
simulation. Such parameters are called tunable parameters. In general,
only parameters that represent mathematical variables, such as the Gain
parameter of the Gain block, are tunable. Parameters that specify the
appearance or structure of a block, e.g., the number of inputs of a Sum block,
or when it is evaluated, e.g., a block’s sample time or priority, are not tunable.
You can tell whether a particular parameter is tunable by examining its edit
control in the block’s dialog box or Model Explorer during simulation. If the
control is disabled, the parameter is nontunable. You cannot tune inline
parameters. See “Inline Parameters” on page 24-14 for more information.
Tune a Block Parameter
You can use a block’s dialog box or the Model Explorer to modify the tunable
parameters of any block. To use the block’s parameter dialog box, open the
block’s parameter dialog box, change the value displayed in the dialog box,
and click the dialog box’s OK or Apply button.
You can also tune a parameter at the MATLAB command line, using either
the set_param command or by assigning a new value to the MATLAB
workspace variable that specifies the parameter’s value. In either case, you
must update the model’s block diagram for the change to take effect (see
“Update a Block Diagram” on page 1-25).
24-13
24
Working with Block Parameters
Inline Parameters
In this section...
“About Inlined Parameters” on page 24-14
“Specify Some Parameters as Noninline” on page 24-14
About Inlined Parameters
The Inline parameters option (see “Inline parameters” ) controls how
mathematical block parameters appear in code generated from the model.
When this optimization is off (the default), a model’s mathematical block
parameters appear as variables in the generated code. As a result, you can
tune the parameters both during simulation and when executing the code.
When Inline parameters is selected, the parameters appear in the generated
code as inlined numeric constants. This reduces the generated code’s memory
and processing requirements. However, because the inlined parameters
appear as constants in the generated code, you cannot tune them during
code execution. To ensure that simulation and generated code execution
fully correspond, Simulink prevents you from changing the values of block
parameters during simulation when Inline parameters is selected.
Note Simulink ignores tunable parameter specifications in the Model
Parameter Configuration dialog box if the model is a referenced model or
contains any Model blocks. 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. If you define tunable parameters using Simulink.Parameter
objects, you can tune the top model and reference model parameters.
Specify Some Parameters as Noninline
Suppose that you want to take advantage of the Inline parameters
optimization while retaining the ability to tune some of your model
parameters. You can do this by declaring some parameters as noninline,
using either the “Model Parameter Configuration Dialog Box” or a
24-14
Inline Parameters
Simulink.Parameter object. In either case, you must use a workspace
variable to specify the value of the parameter.
If you have a Simulink Coder license, when compiling a model with the inline
parameters option on, Simulink checks to ensure that the data types of the
workspace variables used to specify the model’s noninline parameters are
compatible with code generation. If not, Simulink halts the compilation and
displays an error. For more information, see “Tunable Workspace Parameter
Data Type Considerations”.
Note The documentation for the Simulink Coder refers to workspace
variables used to specify the value of noninline parameters as tunable
workspace parameters. In this context, the term parameter refers to a
workspace variable used to specify a parameter as opposed to the parameter
itself.
Using a Parameter Object to Specify a Parameter As
Noninlined
If you use a parameter object to specify a parameter’s value (see “Use
Parameter Objects to Specify Parameter Values” on page 24-7), you can
also use the object to specify the parameter as noninlined. To do this, set
the parameter object’s CoderInfo.StorageClass property to any value but
'Auto' (the default).
K=Simulink.Parameter;
K.CoderInfo.StorageClass = 'SimulinkGlobal';
If you set the CoderInfo.StorageClass property to any value other than
Auto, you should not include the parameter in the tunable parameters table
in the Model Parameter Configuration dialog box.
Note Simulink halts model compilation and displays an error message if
it detects a conflict between the properties of a parameter as specified by
a parameter object and the properties of the parameter as specified in the
Model Parameter Configuration dialog box.
24-15
24
Working with Block Parameters
Structure Parameters
In this section...
“About Structure Parameters” on page 24-16
“Define Structure Parameters” on page 24-17
“Referencing Structure Parameters” on page 24-17
“Structure Parameter Arguments” on page 24-18
“Tunable Structure Parameters” on page 24-19
“Parameter Structure Limitations” on page 24-20
About Structure Parameters
Separately defining all base workspace variables used in block parameter
expressions can clutter the base workspace and result in very long lists of
arguments to subsystems and referenced models. The technique provides no
way to conveniently group related base workspace variables, or to configure
generated code to reflect the variables’ relationships.
To minimize the disadvantages of separately defining workspace variables
used by block parameters, you can group numeric variables by specifying their
names and values as the fields of a MATLAB structure in the base workspace.
A MATLAB structure that Simulink uses in block parameter expressions is
called a structure parameter. You can use structure parameters to:
• Simplify and modularize the base workspace by using multiple structures
to group related variables and to prevent name conflicts
• Dereference the structure in block parameter expressions to provide values
from structure fields rather than separate variables
• Pass all the fields in a structure to a subsystem or referenced model with a
single argument.
• Improve generated code to use structures rather multiple separate
variables
For information about creating and using MATLAB structures, see Structures
in the MATLAB documentation. You can use all the techniques described
24-16
Structure Parameters
there to manipulate structure parameters. This section assumes that you
know those techniques, and provides only information that is specific to
Simulink.
For information on structure parameters in the context of generated code for
a model, see “Structure Parameters and Generated Code”. For an example
of how to convert a model that uses unstructured workspace variables to a
model that uses structure parameters, see sldemo_applyVarStruct.
Define Structure Parameters
Defining a structure parameter is syntactically the same as defining any
MATLAB structure, as described in Structures. Every field in a MATLAB
structure that functions as a structure parameter must have a numeric data
type, even if Simulink never uses the field. Different fields can have different
numeric types.
In structure parameters, numeric types include enumerated types, by virtue
of their underlying integers. The value of a structure parameter field, can
be a real or complex scalar, vector, or multidimensional array. However, a
structure that contains any multidimensional array cannot be tuned. See
“Tunable Structure Parameters” on page 24-19.
MATLAB structures, including those used as structure parameters, can
have substructures to any depth. Structures and substructures at any level
behave identically, so the following instructions refer only to structures unless
substructures are specifically the point.
Referencing Structure Parameters
You can use MATLAB syntax, as described in Structures, to dereference a
structure parameter field anywhere in a block parameter expression that
a MATLAB variable can appear. You cannot specify a structure name in
a mathematical block parameter expression, because that would pass a
structure rather than a number. For example, suppose you have defined
the following parameter structure:
A
|__x
|__y
/* Root structure
/* Numeric field
/* Numeric field
24-17
24
Working with Block Parameters
|__z
|__ m
|__ n
|__ k
/* Substructure
/* Numeric field
/* Numeric field
/* Numeric field
Given this structure, you can specify an individual field, such as A.x, in a
block parameter expression, thereby passing only x to the block. The effect
is exactly the same as if x were a separate base workspace variable whose
value was the same as the value of A.x. Similarly, you could reference A.z.m,
A.z.n, etc. The next figure shows an example that uses a Gain block:
The Gain block’s Gain parameter is the value of A.x + A.z.k, a numeric
expression. You could not reference A or A.z to provide a Gain parameter
value, because neither resolves to a numeric value.
Structure Parameter Arguments
You can use a parameter structure field as a masked subsystem or model
reference argument by referencing the field, as described in the previous
section, in Subsystem block mask, or Model block. For example, suppose you
have defined the parameter structure used in the previous example:
A
|__x
|__y
|__z
|__ m
|__ n
|__ k
/* Root structure
/* Numeric field
/* Numeric field
/* Substructure
/* Numeric field
/* Numeric field
/* Numeric field
You could then:
24-18
Structure Parameters
1 Use a whole structure parameter as a masked subsystem argument or a
referenced model argument by referencing the structure’s name
2 Dereference the structure as needed in the subsystem mask code, the
subsystem itself, or the referenced model.
For example, you could pass A, providing access to everything in the
root structure, or A.z, providing access only to that substructure. The
dereferencing syntax for arguments is the same as in any other context, as
described in Structures.
When you pass a structure parameter to a referenced model, the structure
definitions must be identical in the parent model and the submodel, including
any unused fields. See “Systems and Subsystems” on page 3-11, “Masking”,
and “Using Model Arguments” on page 6-53 more information about passing
and using arguments.
Tunable Structure Parameters
Declare a structure parameter to be tunable using one of the following
techniques.
• Clear Model Configuration Parameters > Optimization > Signals
and Parameters > Inline parameters. See “Inline parameters” for more
information.
• Set Inline parameters, and then specify the parameter structure as
tunable in the Model Parameter Configuration Dialog Box.
• Associate a Simulink.Parameter object with the structure parameter,
and specify the object’s storage class as anything other than Auto. In the
following example, the structure parameter myStruct is associated with a
Simulink.Parameter object.
myStruct = Simulink.Parameter;
myStruct.Value = [1 2 3];
myStruct.CoderInfo.StorageClass = 'ExportedGlobal';
A tunable structure parameter can contain a nontunable numeric field (like
a multidimensional array) without affecting the tunability of the rest of the
structure. You cannot define individual substructures or fields within a
24-19
24
Working with Block Parameters
structure parameter to be tunable. Only the name of the root level of the
structure appears in the Model Configuration Parameter dialog box, and only
the root can have a Simulink.Parameter object assigned to it.
For more information about tunability, see “Inline Parameters” on page 24-14
and “Tunable Parameters” on page 24-13. For simplicity, those sections
mention only separately defined base workspace variables, but all of the
information applies without change to tunable structure parameters.
Parameter Structure Limitations
• You cannot define individual substructures or fields within a structure
parameter as tunable.
• Tunable structure parameters do not support context sensitivity.
24-20
25
Working with Lookup
Tables
• “About Lookup Table Blocks” on page 25-2
• “Anatomy of a Lookup Table” on page 25-4
• “Lookup Tables Block Library” on page 25-5
• “Guidelines for Choosing a Lookup Table” on page 25-7
• “Enter Breakpoints and Table Data” on page 25-11
• “Characteristics of Lookup Table Data” on page 25-18
• “Methods for Estimating Missing Points” on page 25-23
• “Edit Existing LookupTables” on page 25-28
• “Create a Logarithm Lookup Table” on page 25-63
• “Prelookup and Interpolation Blocks” on page 25-66
• “Optimize Generated Code for Lookup Table Blocks” on page 25-67
• “Update Lookup Table Blocks to New Versions” on page 25-71
• “Lookup Table Glossary” on page 25-77
25
Working with Lookup Tables
About Lookup Table Blocks
A lookup table block uses an array of data to map input values to output
values, approximating a mathematical function. Given input values, Simulink
performs a “lookup” operation to retrieve the corresponding output values
from the table. If the lookup table does not define the input values, the block
estimates the output values based on nearby table values.
The following example illustrates a one-dimensional lookup table that
approximates the function y = x3. The lookup table defines its output (y) data
discretely over the input (x) range [-3, 3]. The following table and graph
illustrate the input/output relationship:
An input of -2 enables the table to look up and retrieve the corresponding
output value (-8). Likewise, the lookup table outputs 27 in response to an
input of 3.
When the lookup table block encounters an input that does not match any
of the table’s x values, it can interpolate or extrapolate the answer. For
instance, the lookup table does not define an input value of -1.5; however, the
block can linearly interpolate the nearest data points (-2, -8) and (-1, -1) to
estimate and return a value of -4.5.
25-2
About Lookup Table Blocks
Similarly, although the lookup table does not include data for x values beyond
the range of [-3, 3], the block can extrapolate values using a pair of data
points at either end of the table. Given an input value of 4, the lookup
table block linearly extrapolates the nearest data points (2, 8) and (3, 27) to
estimate an output value of 46.
Since table lookups and simple estimations can be faster than mathematical
function evaluations, using lookup table blocks might result in speed
gains when simulating a model. Consider using lookup tables in lieu of
mathematical function evaluations when:
• An analytical expression is expensive to compute.
• No analytical expression exists, but the relationship has been determined
empirically.
Simulink provides a broad assortment of lookup table blocks, each geared
for a particular type of application. The sections that follow outline the
different offerings, suggest how to choose the lookup table best suited to your
application, and explain how to interact with the various lookup table blocks.
25-3
25
Working with Lookup Tables
Anatomy of a Lookup Table
The following figure illustrates the anatomy of a two-dimensional lookup
table. Vectors or breakpoint data sets and an array, referred to as table data,
constitute the lookup table.
Each breakpoint data set is an index of input values for a particular
dimension of the lookup table. The array of table data serves as a sampled
representation of a function evaluated at the breakpoint values. Lookup table
blocks use breakpoint data sets to relate a table’s input values to the output
values that it returns.
25-4
Lookup Tables Block Library
Lookup Tables Block Library
Several lookup table blocks appear in the Lookup Tables block library.
25-5
25
Working with Lookup Tables
The following table summarizes the purpose of each block in the library.
25-6
Block Name
Description
1-D Lookup Table
Approximate a one-dimensional function.
2-D Lookup Table
Approximate a two-dimensional function.
n-D Lookup Table
Approximate an N-dimensional function.
Prelookup
Compute index and fraction for Interpolation Using Prelookup block.
Interpolation Using
Prelookup
Use precalculated index and fraction values to accelerate approximation
of N-dimensional function.
Direct Lookup Table
(n-D)
Index into an N-dimensional table to retrieve the corresponding outputs.
Lookup Table
Dynamic
Approximate a one-dimensional function using a dynamically specified
table.
Sine
Use a fixed-point lookup table to approximate the sine wave function.
Cosine
Use a fixed-point lookup table to approximate the cosine wave function.
Guidelines for Choosing a Lookup Table
Guidelines for Choosing a Lookup Table
In this section...
“Data Set Dimensionality” on page 25-7
“Data Set Numeric and Data Types” on page 25-7
“Data Accuracy and Smoothness” on page 25-8
“Dynamics of Table Inputs” on page 25-8
“Efficiency of Performance” on page 25-8
“Summary of Lookup Table Block Features” on page 25-10
Data Set Dimensionality
In some cases, the dimensions of your data set dictate which of the lookup
table blocks is right for your application. If you are approximating a
one-dimensional function, consider using either the 1-D Lookup Table or
Lookup Table Dynamic block. If you are approximating a two-dimensional
function, consider the 2-D Lookup Table block. Blocks such as the n-D Lookup
Table and Direct Lookup Table (n-D) allow you to approximate a function of
N variables.
Data Set Numeric and Data Types
The numeric and data types of your data set influence the decision of which
lookup table block is most appropriate. Although all lookup table blocks
support real numbers, the Direct Lookup Table (n-D), 1-D Lookup Table, 2-D
Lookup Table, and n-D Lookup Table blocks also support complex table data.
All lookup table blocks support integer and fixed-point data in addition to
double and single data types.
Note For the Direct Lookup Table (n-D) block, fixed-point types are
supported for the table data, output port, and optional table input port.
25-7
25
Working with Lookup Tables
Data Accuracy and Smoothness
The desired accuracy and smoothness of the data returned by a lookup table
determine which of the blocks you should use. Most blocks provide options
to perform interpolation and extrapolation, improving the accuracy of values
that fall between or outside of the table data, respectively. For instance, the
Lookup Table Dynamic block performs linear interpolation and extrapolation,
while the n-D Lookup Table block performs either linear or cubic spline
interpolation and extrapolation. In contrast, the Direct Lookup Table (n-D)
block performs table lookups without any interpolation or extrapolation. You
can achieve a mix of interpolation and extrapolation methods by using the
Prelookup block with the Interpolation Using Prelookup block.
Dynamics of Table Inputs
The dynamics of the lookup table inputs impact which of the lookup table
blocks is ideal for your application. The blocks use a variety of index search
methods to relate the lookup table inputs to the table’s breakpoint data
sets. Most of the lookup table blocks offer a binary search algorithm, which
performs well if the inputs change significantly from one time step to the next.
The 1-D Lookup Table, 2-D Lookup Table, n-D Lookup Table, and Prelookup
blocks offer a linear search algorithm. Using this algorithm with the option
that resumes searching from the previous result performs well if the inputs
change slowly. Some lookup table blocks also provide a search algorithm that
works best for breakpoint data sets composed of evenly spaced breakpoints.
You can achieve a mix of index search methods by using the Prelookup block
with the Interpolation Using Prelookup block.
Efficiency of Performance
When the efficiency with which lookup tables operate is important, consider
using the Prelookup block with the Interpolation Using Prelookup block.
These blocks separate the table lookup process into two components — an
index search that relates inputs to the table data, followed by an interpolation
and extrapolation stage that computes outputs. These blocks enable you to
perform a single index search and then reuse the results to look up data in
multiple tables. Also, the Interpolation Using Prelookup block can perform
sub-table selection, where the block interpolates a portion of the table data
instead of the entire table. For example, if your 3-D table data constitutes a
stack of 2-D tables to be interpolated, you can specify a selection port input to
select one or more of the 2-D tables from the stack for interpolation. A full 3-D
25-8
Guidelines for Choosing a Lookup Table
interpolation has 7 sub-interpolations but a 2-D interpolation requires only 3
sub-interpolations. As a result, significant speed improvements are possible
when some dimensions of a table are used for data stacking and not intended
for interpolation. These features make table lookup operations more efficient,
reducing computational effort and simulation time.
25-9
25
Working with Lookup Tables
Summary of Lookup Table Block Features
Use the following table to identify features that correspond to particular
lookup table blocks, then select the block that best meets your requirements.
Feature
Prelookup
Interp.
1-D
2-D
Lookup
n-D
Direct
Lookup
Lookup
Table
Lookup
Lookup
Using
Table
Table
Dynamic
Table
Table (n-D)
Prelookup
Interpolation Methods
Flat
•
•
•
•
Linear
•
•
•
•
Cubic spline
•
•
•
•
•
•
•
•
•
•
•
•
Extrapolation Methods
Clip
•
•
•
•
•
Linear
•
•
•
•
Cubic spline
•
•
•
•
•
Numeric & Data Type Support
Complex
•
•
Double, Single
•
•
•
•
•
•
•
Integer
•
•
•
•
•
•
•
Fixed point
•
•
•
•
•
•
•
•
•
•
•
Index Search Methods
Binary
•
•
Linear
•
•
•
•
•
•
•
•
•
Evenly spaced
points
Start at
previous index
•
•
•
Miscellaneous
Sub-table
•
selection
Dynamic
•
breakpoint data
Dynamic table
25-10
•
data
Input range
checking
•
•
•
•
•
•
•
•
•
Enter Breakpoints and Table Data
Enter Breakpoints and Table Data
In this section...
“Entering Data in a Block Parameter Dialog Box” on page 25-11
“Entering Data in the Lookup Table Editor” on page 25-13
“Entering Data Using Inports of the Lookup Table Dynamic Block” on
page 25-16
Entering Data in a Block Parameter Dialog Box
Use the following procedure to populate a 1-D Lookup Table block using the
parameter dialog box. In this example, the lookup table approximates the
function y = x3 over the range [-3, 3].
1 Copy a 1-D Lookup Table block from the Lookup Tables block library to a
Simulink model.
2 In the model window, double-click the 1-D Lookup Table block.
25-11
25
Working with Lookup Tables
The block parameter dialog box appears.
The dialog box displays the default values for the block.
3 Enter the table dimensions, table data, and breakpoint data set in the
specified fields of the dialog box:
• In the Number of table dimensions field, enter 1.
• In the Table data field, enter [-27 -8 -1 0 1 8 27].
• In the Breakpoints 1 field, enter [-3:3].
• Click Apply.
25-12
Enter Breakpoints and Table Data
The block dialog box looks something like this:
4 Click OK to apply the changes and close the dialog box.
Entering Data in the Lookup Table Editor
Use the following procedure to populate a 2-D Lookup Table block using the
Lookup Table Editor. In this example, the lookup table approximates the
function z = x2 + y2 over the input ranges x = [0, 2] and y = [0, 2].
1 Copy a 2-D Lookup Table block from the Lookup Tables block library to a
Simulink model.
25-13
25
Working with Lookup Tables
2 Open the Lookup Table Editor by selecting Lookup Table Editor from
the Simulink Edit menu or by clicking Edit table and breakpoints on
the dialog box of the 2-D Lookup Table block.
The Lookup Table Editor appears.
It displays the default data for the 2-D Lookup Table block.
3 Under Viewing "Lookup Table (n-D)" block data, enter the breakpoint
data sets and table data in the appropriate cells. To change the default
data, double-click a cell, enter the new value, and then press Enter or click
outside the field to confirm the change:
25-14
Enter Breakpoints and Table Data
• In the cells associated with the Row Breakpoints, enter each of the
values [0 1 2].
• In the cells associated with the Column Breakpoints, enter each of
the values [0 1 2].
• In the table data cells, enter the values in the array [0 1 4; 1 2 5;
4 5 8].
The Lookup Table Editor should look like this:
4 In the Lookup Table Editor, select File > Update Block Data to update
the data in the 2-D Lookup Table block.
5 Close the Lookup Table Editor.
25-15
25
Working with Lookup Tables
Entering Data Using Inports of the Lookup Table
Dynamic Block
Use the following procedure to populate a Lookup Table Dynamic block using
that block’s inports. In this example, the lookup table approximates the
function y = 3x2 over the range [0, 10].
1 Copy a Lookup Table Dynamic block from the Lookup Tables block library
to a Simulink model.
2 Copy the blocks needed to implement the equation y = 3x2 to the Simulink
model:
• One Constant block to define the input range, from the Sources library
• One Math Function block to square the input range, from the Math
Operations library
• One Gain block to multiply the signal by 3, also from the Math
Operations library
3 Assign the following parameter values to the Constant, Math Function, and
Gain blocks using their dialog boxes:
Block
Parameter
Value
Constant
Constant value
0:10
Math Function
Function
square
Gain
Gain
3
4 Input the breakpoint data set to the Lookup Table Dynamic block by
connecting the outport of the Constant block to the inport of the Lookup
Table Dynamic block labeled xdat. This signal is the input breakpoint
data set for x.
5 Input the table data to the Lookup Table Dynamic block by branching
the output signal from the Constant block and connecting it to the Math
Function block. Then connect the Math Function block to the Gain block.
Finally, connect the Gain block to the inport of the Lookup Table Dynamic
block labeled ydat. This signal is the table data for y.
25-16
Enter Breakpoints and Table Data
The model should look something like this:
25-17
25
Working with Lookup Tables
Characteristics of Lookup Table Data
In this section...
“Sizes of Breakpoint Data Sets and Table Data” on page 25-18
“Monotonicity of Breakpoint Data Sets” on page 25-19
“Representation of Discontinuities in Lookup Tables” on page 25-20
“Formulation of Evenly Spaced Breakpoints” on page 25-22
Sizes of Breakpoint Data Sets and Table Data
The following constraints apply to the sizes of breakpoint data sets and table
data associated with lookup table blocks:
• The memory limitations of your system constrain the overall size of a
lookup table.
• Lookup tables must use consistent dimensions so that the overall size of
the table data reflects the size of each breakpoint data set.
To illustrate the second constraint, consider the following vectors of input and
output values that create the relationship in the plot.
Vector of input values:
Vector of output values:
[-3 -2 -1 0 1 2 3]
[-3 -1 0 -1 0 1 3]
In this example, the input and output data are the same size (1-by-7), making
the data consistently dimensioned for a 1-D lookup table.
25-18
Characteristics of Lookup Table Data
The following input and output values define the 2-D lookup table that is
graphically shown.
Row index input values:
[1 2 3]
Column index input values: [1 2 3 4]
Table data:
[11 12 13 14; 21 22 23 24; 31 32 33 34]
In this example, the sizes of the vectors representing the row and column
indices are 1-by-3 and 1-by-4, respectively. Consequently, the output table
must be of size 3-by-4 for consistent dimensions.
Monotonicity of Breakpoint Data Sets
The first stage of a table lookup operation involves relating inputs to the
breakpoint data sets. The search algorithm requires that input breakpoint
sets be monotonically increasing, that is, each successive element is equal to
or greater than its preceding element. For example, the vector
A = [0
0.5
1
1.9
2
2
2
2.1
3]
repeats the value 2 while all other elements are increasingly larger than their
predecessors; hence, A is monotonically increasing.
For lookup tables with data types other than double or single, the search
algorithm requires an additional constraint due to quantization effects. In
such cases, the input breakpoint data sets must be strictly monotonically
increasing, that is, each successive element must be greater than its preceding
element. Consider the vector
B = [0
0.5
1
1.9
2
2.1
2.17
3]
25-19
25
Working with Lookup Tables
in which each successive element is greater than its preceding element,
making B strictly monotonically increasing.
Note Although a breakpoint data set is strictly monotonic in double format,
it might not be so after conversion to a fixed-point data type.
Representation of Discontinuities in Lookup Tables
You can represent discontinuities in lookup tables that have monotonically
increasing breakpoint data sets. To create a discontinuity, repeat an input
value in the breakpoint data set with different output values in the table data.
For example, these vectors of input (x) and output (y) values associated with a
1-D lookup table create the step transitions depicted in the plot that follows.
Vector of input values:
Vector of output values:
[-2 -1 -1 0 0 1 1 2]
[-1 -1 -2 -2 2 2 1 1]
This example has discontinuities at x = –1, 0, and +1.
When there are two output values for a given input value, the block chooses
the output according to these rules:
25-20
Characteristics of Lookup Table Data
• If the input signal is less than zero, the block returns the output value
associated with the last occurrence of the input value in the breakpoint data
set. In this example, if the input is –1, y is –2, marked with a solid circle.
• If the input signal is greater than zero, the block returns the output value
associated with the first occurrence of the input value in the breakpoint
data set. In this example, if the input is 1, y is 2, marked with a solid circle.
• If the input signal is zero and there are two output values specified at
the origin, the block returns the average of those output values. In this
example, if the input is 0, y is 0, the average of the two output values –2
and 2 specified at x = 0.
When there are three points specified at the origin, the block generates the
output associated with the middle point. The following example demonstrates
this special rule.
Vector of input values:
Vector of output values:
[-2 -1 -1 0 0 0 1 1 2]
[-1 -1 -2 -2 1 2 2 1 1]
In this example, three points define the discontinuity at the origin. When the
input is 0, y is 1, the value of the middle point.
You can apply this same method to create discontinuities in breakpoint data
sets associated with multidimensional lookup tables.
25-21
25
Working with Lookup Tables
Formulation of Evenly Spaced Breakpoints
You can represent evenly spaced breakpoints in a data set by using one
of these methods.
Formulation
Example
When to Use This
Formulation
[first_value:spacing:last_value]
[10:10:200]
The lookup table does
not use double or
single.
first_value + spacing *
[0:(last_value-first_value)/spacing]
1 + (0.02 *
[0:450])
The lookup table uses
double or single.
Because floating-point data types cannot precisely represent some numbers,
the second formulation works better for double and single. For example,
use 1 + (0.02 * [0:450]) instead of [1:0.02:10]. For a list of lookup table
blocks that support evenly spaced breakpoints, see “Summary of Lookup
Table Block Features” on page 25-10.
Among other advantages, evenly spaced breakpoints can make the generated
code division-free and reduce memory usage. For more information, see:
• fixpt_evenspace_cleanup in the Simulink documentation
• “Effects of Spacing on Speed, Error, and Memory Usage” in the Simulink
Fixed Point documentation
• “Identify questionable fixed-point operations” in the Simulink Coder
documentation
Tip Do not use the MATLAB linspace function to define evenly spaced
breakpoints. Simulink uses a tighter tolerance to check whether a breakpoint
set has even spacing. If you use linspace to define breakpoints for your
lookup table, Simulink considers the breakpoints to be unevenly spaced.
25-22
Methods for Estimating Missing Points
Methods for Estimating Missing Points
In this section...
“About Estimating Missing Points” on page 25-23
“Interpolation Methods” on page 25-23
“Extrapolation Methods” on page 25-24
“Rounding Methods” on page 25-25
“Example Output for Lookup Methods” on page 25-26
About Estimating Missing Points
The second stage of a table lookup operation involves generating outputs that
correspond to the supplied inputs. If the inputs match the values of indices
specified in breakpoint data sets, the block outputs the corresponding values.
However, if the inputs fail to match index values in the breakpoint data sets,
Simulink estimates the output. In the block parameter dialog box, you can
specify how to compute the output in this situation. The available lookup
methods are described in the following sections.
Interpolation Methods
When an input falls between breakpoint values, the block interpolates the
output value using neighboring breakpoints. Most lookup table blocks have
the following interpolation methods available:
• Flat — Disables interpolation and uses the rounding operation titled Use
Input Below. For more information, see “Rounding Methods” on page
25-25.
• Linear — Fits a line between the adjacent breakpoints, and returns the
point on that line corresponding to the input.
• Cubic spline — Fits a cubic spline to the adjacent breakpoints, and
returns the point on that spline corresponding to the input.
25-23
25
Working with Lookup Tables
Note The Lookup Table Dynamic block does not let you select an
interpolation method. The Interpolation-Extrapolation option in the
Lookup Method field of the block parameter dialog box performs linear
interpolation.
Each interpolation method includes a trade-off between computation time
and the smoothness of the result. Although rounding is quickest, it is the
least smooth. Linear interpolation is slower than rounding but generates
smoother results, except at breakpoints where the slope changes. Cubic spline
interpolation is the slowest method but produces the smoothest results.
Extrapolation Methods
When an input falls outside the range of a breakpoint data set, the block
extrapolates the output value from a pair of values at the end of the
breakpoint data set. Most lookup table blocks have the following extrapolation
methods available:
• Clip — Disables extrapolation and returns the table data corresponding to
the end of the breakpoint data set range.
• Linear — Fits a line between the first or last pair of breakpoints, depending
if the input is less than the first or greater than the last breakpoint,
respectively. This method returns the point on that line corresponding
to the input.
• Cubic spline — Fits a cubic spline to the first or last pair of breakpoints,
depending if the input is less than the first or greater than the last
breakpoint, respectively. This method returns the point on that spline
corresponding to the input.
Note The Lookup Table Dynamic block does not let you select an
extrapolation method. The Interpolation-Extrapolation option in the
Lookup Method field of the block parameter dialog box performs linear
extrapolation.
25-24
Methods for Estimating Missing Points
In addition to these methods, some lookup table blocks, such as the
n-D Lookup Table block, allow you to select an action to perform when
encountering situations that require extrapolation. For instance, you can
specify that Simulink generate either a warning or an error when the lookup
table inputs are outside the ranges of the breakpoint data sets. To specify
such an action, select it from the Diagnostic for out-of-range input list
on the block parameter dialog box.
Rounding Methods
If an input falls between breakpoint values or outside the range of a
breakpoint data set and you do not specify interpolation or extrapolation,
the block rounds the value to an adjacent breakpoint and returns the
corresponding output value. For example, the Lookup Table Dynamic block
lets you select one of the following rounding methods:
• Use Input Nearest — Returns the output value corresponding to the
nearest input value.
• Use Input Below — Returns the output value corresponding to the
breakpoint value that is immediately less than the input value. If no
breakpoint value exists below the input value, it returns the breakpoint
value nearest the input value.
• Use Input Above — Returns the output value corresponding to the
breakpoint value that is immediately greater than the input value. If no
breakpoint value exists above the input value, it returns the breakpoint
value nearest the input value.
25-25
25
Working with Lookup Tables
Example Output for Lookup Methods
In the following model, the Lookup Table Dynamic block accepts a vector
of breakpoint data given by [-5:5] and a vector of table data given by
sinh([-5:5]).
25-26
Methods for Estimating Missing Points
The Lookup Table Dynamic block outputs the following values when using the
specified lookup methods and inputs.
Lookup Method
Input
Output
Comment
InterpolationExtrapolation
1.4
2.156
N/A
5.2
83.59
N/A
InterpolationUse End Values
1.4
2.156
N/A
5.2
74.2
The block uses the value
for sinh(5.0).
1.4
3.627
The block uses the value
for sinh(2.0).
5.2
74.2
The block uses the value
for sinh(5.0).
1.4
1.175
The block uses the value
for sinh(1.0).
-5.2
-74.2
The block uses the value
for sinh(-5.0).
1.4
1.175
The block uses the value
for sinh(1.0).
Use Input Above
Use Input Below
Use Input Nearest
25-27
25
Working with Lookup Tables
Edit Existing LookupTables
In this section...
“When to Use the Lookup Table Editor” on page 25-28
“Layout of the Lookup Table Editor” on page 25-28
“Browsing Lookup Table Blocks” on page 25-29
“Editing Table Values” on page 25-30
“Working with Table Data of Standard Format” on page 25-32
“Working with Table Data of Nonstandard Format” on page 25-36
“Importing Data from an Excel Spreadsheet” on page 25-53
“Adding and Removing Rows and Columns in a Table” on page 25-55
“Displaying N-Dimensional Tables in the Editor” on page 25-56
“Plotting Lookup Tables” on page 25-57
“Editing Custom Lookup Table Blocks” on page 25-61
When to Use the Lookup Table Editor
Use the Lookup Table Editor to inspect and change the table elements of any
lookup table block in a model, including custom blocks that you create using
the Simulink Mask Editor (see “Editing Custom Lookup Table Blocks” on
page 25-61). You can also use a block parameter dialog box to edit a table.
However, you must open the subsystem containing the block first and then its
parameter dialog box. With the Lookup Table Editor, you can skip these steps.
Tip You cannot use the Lookup Table Editor to change the dimensions of a
lookup table. You must use the block parameter dialog box for this purpose.
Layout of the Lookup Table Editor
To open the editor, select Lookup Table Editor from the Simulink Edit
menu. The editor appears.
25-28
Edit Existing LookupTables
The editor contains two panes and a toolbar.
• Use the left pane to browse and select lookup table blocks in any open
model (see “Browsing Lookup Table Blocks” on page 25-29).
• Use the right pane to edit the lookup table of the selected block (see
“Editing Table Values” on page 25-30).
• Use the toolbar for one-click access to frequently-used commands in the
editor. Each toolbar button has a tooltip that explains its function.
Browsing Lookup Table Blocks
The Models list in the upper-left corner of the Lookup Table Editor lists
the names of all models open in the current MATLAB session. To browse
25-29
25
Working with Lookup Tables
lookup table blocks for any open models, select the model name from the list.
A tree-structured view of lookup table blocks for the selected model appears in
the Table blocks field beneath the Models list.
The tree view initially lists all lookup table blocks that reside at the model
root level. It also displays any subsystems that contain lookup table blocks.
Clicking the expand button (+) to the left of the subsystem name expands
the tree to show lookup table blocks in that subsystem. The expanded view
also shows any subsystems in the expanded subsystem. You can continue
expanding subsystem nodes to display lookup table blocks at any level in
the model hierarchy.
Clicking any lookup table block in the tree view displays the lookup table
for that block in the right pane, so that you can edit the table (see “Editing
Table Values” on page 25-30).
Note If you want to browse the lookup table blocks in a model that is not
currently open, you can tell the Lookup Table Editor to open the model. To
do this, select File > Open Model in the editor.
Editing Table Values
In the Viewing “Lookup Table (n-D)” block data table view of the Lookup
Table Editor, you can edit the lookup table of the block currently selected in
the adjacent tree view.
25-30
Edit Existing LookupTables
The table view displays the entire table if it is one- or two-dimensional or a
two-dimensional slice of the table if the table has more than two dimensions
(see “Displaying N-Dimensional Tables in the Editor” on page 25-56). To
change any value that appears, double-click the value. The Lookup Table
Editor replaces the value with an edit field containing the value. Edit the
value and then press Enter or click outside the field to confirm the change.
In the Data Type below the table, you can specify the data type by row or
column, or for the entire table. By default, the data type is double. To change
the data type, select the pop-up index list for the table element for which
you want to change the data type.
The Lookup Table Editor records your changes by maintaining a copy
of the table. To update the copy that the lookup table block maintains,
select File > Update Block Data in the Lookup Table Editor. To restore
the Lookup Table Editor’s copy to the values stored in the block, select
File > Reload Block Data.
25-31
25
Working with Lookup Tables
Working with Table Data of Standard Format
Suppose that you specify a 3-D lookup table in your n-D Lookup Table block.
You use workspace variables to define the breakpoint and table data:
25-32
Edit Existing LookupTables
The table data uses the default Simulink format:
table3d_map(:,:,1) =
1
5
2
6
3
7
4
8
table3d_map(:,:,2) =
11
15
12
16
13
17
14
18
table3d_map(:,:,3) =
111
115
112
116
113
117
114
118
The breakpoint sets have the following values:
bp3d_y =
400
6400
bp3d_x =
0
10
20
10
20
30
bp3d_z =
0
25-33
25
Working with Lookup Tables
When you click Edit table and breakpoints to open the Lookup Table
Editor, you see:
25-34
Edit Existing LookupTables
Suppose that you change a value in the Lookup Table Editor as follows:
When you select File > Update Block Data, you can propagate the change
to table3d_map, the workspace variable that contains the table data for the
n-D Lookup Table block. To propagate the change, click Yes in the pop-up
window that asks if you want to overwrite the workspace variable:
25-35
25
Working with Lookup Tables
Working with Table Data of Nonstandard Format
Suppose that you specify a 3-D lookup table in your n-D Lookup Table block.
25-36
Edit Existing LookupTables
You use workspace variables to define the breakpoint and table data:
The table data uses a nonstandard format for representing 3-D table data that
differs from the default Simulink format:
table3d_map_custom =
1
5
11
15
111
115
2
6
12
16
112
116
3
7
13
17
113
117
4
8
14
18
114
118
The expression in the Table data field converts the table data from a
nonstandard format to the default Simulink format.
25-37
25
Working with Lookup Tables
The breakpoint sets have the following values:
bp3d_y =
400
6400
bp3d_x =
0
10
20
10
20
bp3d_z =
0
25-38
30
Edit Existing LookupTables
When you click Edit table and breakpoints to open the Lookup Table
Editor, you see:
25-39
25
Working with Lookup Tables
Suppose that you change a value in the Lookup Table Editor as follows:
When you select File > Update Block Data, you cannot propagate the
change to table3d_map_custom, the workspace variable that contains the
nonstandard table data for the n-D Lookup Table block. To propagate the
change, you must register a customization function that resides on the
MATLAB search path. For details, see “Example of Propagating a Change for
Table Data of Nonstandard Format” on page 25-45.
25-40
Edit Existing LookupTables
How to Propagate Changes in the Lookup Table Editor to
Workspace Variables of Nonstandard Format
Step
Task
Reference
1
Register a customization
function for the Lookup Table
Editor.
“How to Register a
Customization Function for
the Lookup Table Editor” on
page 25-41
2
Select the appropriate responses
when prompted in the Lookup
Table Editor.
“How to Respond to Prompts
in the Lookup Table Editor” on
page 25-45
How to Register a Customization Function for the Lookup Table
Editor
To register a customization function for the Lookup Table Editor:
1 In MATLAB, create a file named sl_customization.m to register your
customization:
function sl_customization(cm)
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle{end+1} = ...
@myConversionInfoFunction;
end
The string myConversionInfoFunction represents a function name of
your choice.
2 In your sl_customization.m file, define a function that returns a blkInfo
object.
function blkInfo = myConversionInfoFunction(blk, tableStr)
blkInfo.allowTableConvertLocal = false;
blkInfo.tableWorkSpaceVarName = '';
blkInfo.tableConvertFcnHandle = [];
25-41
25
Working with Lookup Tables
% Directions for converting table data of block type 1
if strcmp(get_param(blk, 'BlockType'), 'block_type_1')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'variable_name_1';
end
% Directions for converting table data of block type 2
if strcmp(get_param(blk, 'BlockType'), 'block_type_2')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'variable_name_2';
end
......
% Directions for converting table data of block type N
if strcmp(get_param(blk, 'BlockType'), 'block_type_N')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'variable_name_N';
end
if blkInfo.allowTableConvertLocal
blkInfo.tableConvertFcnHandle = @myConvertTableDataFcn;
end
end
For each type of lookup table block that contains nonstandard table data,
specify the following three properties:
• allowTableConvertLocal — tells the Lookup Table Editor if table data
conversion is allowed for a block
• tableWorkSpaceVarName — specifies the name of the workspace variable
that has a nonstandard table format
• tableConvertFcnHandle — specifies the handle for the conversion
function
25-42
Edit Existing LookupTables
Tip You can specify more restrictive if conditions in this function. For
example, to specify that table data conversion occur for a block with a given
name, you can use:
if strcmp(strrep(blk,sprintf('\n'), ' '), 'full_block_path')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'variable_name';
end
When the allowTableConvertLocal property is true:
• The table data for that block can be converted to the nonstandard format
of the workspace variable whose name matches tableWorkSpaceVarName.
• The function that converts table data corresponds to the handle that
tableConvertFcnHandle specifies.
You can use any alphanumeric name for the conversion function. The
string myConvertTableDataFcn represents a function name of your
choice.
3 In your sl_customization.m file, define the function that converts table
data from the Lookup Table Editor format to the nonstandard format of
your workspace variable.
4 Verify that your sl_customization.m file is complete.
5 Put sl_customization.m on the MATLAB search path.
Note You can have multiple files with the name sl_customization.m
on the search path.
6 At the MATLAB prompt, enter the following command to refresh all
Simulink customizations.
sl_refresh_customizations
25-43
25
Working with Lookup Tables
What Happens When Multiple Customization Functions Exist
If you have multiple sl_customization.m files on the search path, the
following happens:
• At the start of a MATLAB session, Simulink loads each customization file
on the path and executes the function at the top. Executing each function
establishes the customizations for that session.
• When you select File > Update Block Data in the Lookup Table Editor,
the editor checks the list of function handles in the cell array for
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle.
If the cell array...
Changes in the Lookup Table
Editor...
Is empty
Cannot propagate to workspace
variables with nonstandard format
Contains one or more function
handles
Can propagate to workspace
variables with nonstandard format,
depending on the value of the
allowTableConvertLocal property
• The allowTableConvertLocal property controls whether or not table data
for a block is converted from the standard format in the Lookup Table
Editor to a nonstandard format in a workspace variable.
25-44
If a customization function
specifies this block property to
be...
Then table data is...
true
Converted to the nonstandard
format in the workspace variable
false
Not converted to the nonstandard
format in the workspace variable
true, but another customization
function specifies the property to
be false
Not converted and the Lookup
Table Editor issues an error
Edit Existing LookupTables
How to Respond to Prompts in the Lookup Table Editor
When you select File > Update Block Data in the Lookup Table Editor,
several prompts appear. Click Yes when asked if you want to:
• Overwrite workspace variables for breakpoint data
• Overwrite workspace variables for table data
Example of Propagating a Change for Table Data of
Nonstandard Format
Suppose that you want to propagate a change from the Lookup Table Editor
to the workspace variable table3d_map_custom, which uses a nonstandard
format. Follow these steps:
1 Create a file named sl_customization.m with the following contents:
function sl_customization(cm)
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle{end+1} = ...
@myGetTableConvertInfoFcn;
end
In this file:
• The sl_customization function takes a single argument cm, which is
the handle to a customization manager object.
• The handle @myGetTableConvertInfoFcn is added
to the list of function handles in the cell array for
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle.
You can use any alphanumeric name for the function whose handle
you add to the cell array. In this example, the function name is
myGetTableConvertInfoFcn.
2 In your sl_customization.m file, define the myGetTableConvertInfoFcn
function.
function blkInfo = myGetTableConvertInfoFcn(blk, tableStr)
25-45
25
Working with Lookup Tables
blkInfo.allowTableConvertLocal = false;
blkInfo.tableWorkSpaceVarName = '';
blkInfo.tableConvertFcnHandle = [];
% Convert table data for n-D Lookup Table blocks
if strcmp(get_param(blk, 'BlockType'), 'Lookup_n-D')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table3d_map_custom';
end
% Convert table data for Interpolation Using Prelookup blocks
if strcmp(get_param(blk, 'BlockType'), 'Interpolation_n-D')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table4d_map_custom';
end
% Convert table data for Direct Lookup Table (n-D) blocks
if strcmp(get_param(blk, 'BlockType'), 'LookupNDDirect')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table4d_map_custom';
end
if blkInfo.allowTableConvertLocal
blkInfo.tableConvertFcnHandle = @myConvertTableFcn;
end
end
The myGetTableConvertInfoFcn function returns the blkInfo object,
which contains three fields:
• allowTableConvertLocal — tells the Lookup Table Editor if table data
conversion is allowed for a block
• tableWorkSpaceVarName — specifies the name of the workspace variable
that has a nonstandard table format
• tableConvertFcnHandle — specifies the handle for the conversion
function
When the allowTableConvertLocal property is true:
25-46
Edit Existing LookupTables
• The table data for that block is converted to the nonstandard format of
the workspace variable whose name matches tableWorkSpaceVarName.
• The function that converts table data corresponds to the handle that
tableConvertFcnHandle specifies.
You can use any alphanumeric name for the conversion function. In this
example, the function name is myConvertTableFcn.
3 In your sl_customization.m file, define the myConvertTableFcn function,
which includes a separate function call to convertTable_3D. An example of
an implementation is shown below:
% This function converts LUT block table from Simulink format to
% nonstandard format used in workspace variable (for 1D to 4D table)
function cMap = myConvertTableFcn(data)
mapDim = size(data);
numDim = length(mapDim);
if numDim < 3
cMap = data;
elseif numDim == 3
cMap = convertTable_3D(data);
else % numDim == 4 , currently only supports up to 4D
for i = 1:mapDim(numDim)
dataSub = data(:,:,:,i);
iStart = (i-1)*mapDim(1)*mapDim(3) + 1;
iEnd = i*mapDim(1)*mapDim(3);
cMap(iStart:iEnd,:) = convertTable_3D(dataSub);
end
end
end
% This function converts LUT block table from Simulink format to
% nonstandard format used in workspace variable (for 3D table)
function cMap = convertTable_3D(data)
% figure out the row and column number of the 3D table data
mapDim = size(data);
25-47
25
Working with Lookup Tables
numCol = mapDim(2);
numRow = mapDim(1)*mapDim(3);
cMap = zeros(numRow, numCol);
for i = 1:mapDim(3)
rowBegin = (i-1)*mapDim(1)+1;
rowEnd = i*mapDim(1);
cMap(rowBegin:rowEnd, :) = data(:,:,i);
end
end
4 Verify that your sl_customization.m file is complete:
function sl_customization(cm)
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle{end+1} = ...
@myGetTableConvertInfoFcn;
% This function converts LUT block table from Simulink format to
% nonstandard format used in workspace variable (for 1D to 4D table)
function cMap = myConvertTableFcn(data)
mapDim = size(data);
numDim = length(mapDim);
if numDim < 3
cMap = data;
elseif numDim == 3
cMap = convertTable_3D(data);
else % numDim == 4 , currently only supports up to 4D
for i = 1:mapDim(numDim)
dataSub = data(:,:,:,i);
iStart = (i-1)*mapDim(1)*mapDim(3) + 1;
iEnd = i*mapDim(1)*mapDim(3);
cMap(iStart:iEnd,:) = convertTable_3D(dataSub);
end
end
25-48
Edit Existing LookupTables
end
% This function converts LUT block table from Simulink format to
% nonstandard format used in workspace variable (for 3D table)
function cMap = convertTable_3D(data)
% figure out the row and column number of the 3D table data
mapDim = size(data);
numCol = mapDim(2);
numRow = mapDim(1)*mapDim(3);
cMap = zeros(numRow, numCol);
for i = 1:mapDim(3)
rowBegin = (i-1)*mapDim(1)+1;
rowEnd = i*mapDim(1);
cMap(rowBegin:rowEnd, :) = data(:,:,i);
end
end
function blkInfo = myGetTableConvertInfoFcn(blk, tableStr)
blkInfo.allowTableConvertLocal = false;
blkInfo.tableWorkSpaceVarName = '';
blkInfo.tableConvertFcnHandle = [];
% Convert table data for n-D Lookup Table blocks
if strcmp(get_param(blk, 'BlockType'), 'Lookup_n-D')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table3d_map_custom';
end
% Convert table data for Interpolation Using Prelookup blocks
if strcmp(get_param(blk, 'BlockType'), 'Interpolation_n-D')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table4d_map_custom';
end
% Convert table data for Direct Lookup Table (n-D) blocks
25-49
25
Working with Lookup Tables
if strcmp(get_param(blk, 'BlockType'), 'LookupNDDirect')
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table4d_map_custom';
end
if blkInfo.allowTableConvertLocal
blkInfo.tableConvertFcnHandle = @myConvertTableFcn;
end
end
end
5 Put sl_customization.m on the MATLAB search path.
6 At the MATLAB prompt, enter the following command to refresh all
Simulink customizations.
sl_refresh_customizations
7 In the Lookup Table Editor, select File > Update Block Data. Several
pop-up windows appear:
a Click Yes to overwrite the workspace variable bp3d_y.
b Click Yes to overwrite the workspace variable bp3d_x.
25-50
Edit Existing LookupTables
c Click Yes to overwrite the workspace variable table3d_map_custom.
8 If you check the value of table3d_map_custom in the base workspace, you
now see:
table3d_map_custom =
33
5
11
15
111
115
2
6
12
16
112
116
3
7
13
17
113
117
4
8
14
18
114
118
The change that you make to the table data in the Lookup Table Editor
propagates to the workspace variable.
25-51
25
Working with Lookup Tables
Note If you click No to the question of whether to overwrite the workspace
variable table3d_map_custom, you get another question:
25-52
If you click...
Then...
Yes
The block dialog box replaces the expression in the Table data field with
numeric data.
No
Your Lookup Table Editor changes for the table data do not appear in
the block dialog box.
Edit Existing LookupTables
Importing Data from an Excel Spreadsheet
If you have table data in a Microsoft Excel spreadsheet, you can import the
data into the Lookup Table Editor.
How to Import Data from the Spreadsheet
To import data into the Lookup Table Editor:
1 Save the Excel file in a folder on the MATLAB path.
2 Open the model that contains a lookup table block.
3 Save the model with a different name.
4 Open the Model Properties dialog box, for example, by selecting
File > Model Properties.
5 Click the Callbacks tab and enter code for the model post-load function.
For a 2-D lookup table, the commands look something like this:
%%% BEGIN NEW CODE %%%
% Import the data from Excel for a lookup table
data = xlsread('name_of_spreadsheet','sheet_name');
% Row indices for lookup table
breakpoints1 = data(2:end,1)';
% Column indices for lookup table
breakpoints2 = data(1,2:end);
% Output values for lookup table
table_data = data(2:end,2:end);
%%% END NEW CODE %%%
For more information about using xlsread, see the MATLAB
documentation.
6 Save the model again.
25-53
25
Working with Lookup Tables
Example of Importing Data from an Excel Spreadsheet
Suppose that you have table data in an Excel spreadsheet named
airflow_tables.xls and you want to import the data into the Lookup Table
Editor.
1 Save airflow_tables.xls in a folder on the MATLAB path. Enter the
following command at the MATLAB prompt and replace destination with
a location that is on the search path:
copyfile((docpath(fullfile(docroot,'toolbox','simulink','examples','airflow_tables.xls'))),...
'destination','f')
For example, C:\MyFiles\airflow_tables.xls might be a valid value
for destination.
2 Open the sldemo_fuelsys model, which contains a lookup table block
named Pumping Constant.
3 Save the model with a different name, such as my_fuelsys.
4 Open the Model Properties dialog box, for example, by selecting
File > Model Properties.
5 Click the Callbacks tab and add the following commands under the
existing code for the post-load function:
%%% BEGIN NEW CODE %%%
% Import the data from Excel for a lookup table
data = xlsread('airflow_tables', 'Pumping Constant');
% Row indices for Pumping Constant data
SpeedVect = data(2:end,1)';
% Column indices for Pumping Constant data
PressVect = data(1,2:end);
% Output values for Pumping Constant data
PumpCon = data(2:end,2:end);
%%% END NEW CODE %%%
6 Save the model again.
Whenever you open my_fuelsys, Simulink imports the table data for the
Pumping Constant block from the Excel spreadsheet.
25-54
Edit Existing LookupTables
Adding and Removing Rows and Columns in a Table
In the Lookup Table Editor, you can add and remove rows or columns of a
table in the following cases:
• Tables that are one- or two-dimensional
• Tables defined only by breakpoints (that are inherently one-dimensional)
In those cases, follow these instructions to add or remove columns of a table
in the Lookup Table Editor.
To perform this action:
Use one of these methods:
Add a row or column to a table that
appears in the table view
• Select Edit > Add Row or
Edit > Add Column in the
editor.
• Click the Add Row button
the Add Column button
the toolbar.
Remove a row or column from the
table that appears in the table view
or
in
• Highlight the row or column
to remove and then select
Edit > Remove Row(s) or
Edit > Remove Column(s) in
the editor.
• Highlight the row or column to
remove and then click the Remove
Row button
Column button
or the Remove
in the toolbar.
The menu items and toolbar buttons for adding and removing rows and
columns are not available for any other cases. To add or remove a row or
column for a table with more than two dimensions, you must use the block
parameter dialog box.
25-55
25
Working with Lookup Tables
Displaying N-Dimensional Tables in the Editor
If the lookup table of the block currently selected in the Lookup Table
Editor’s tree view has more than two dimensions, the table view displays a
two-dimensional slice of the lookup table.
The Dimension Selector specifies which slice currently appears and lets you
select another slice. The selector consists of a 2-by-N array of controls, where N
is the number of dimensions in the lookup table. Each column corresponds
to a dimension of the lookup table. The first column corresponds to the first
dimension of the table, the second column to the second dimension of the
table, and so on. The Dimension size row of the selector array displays the
size of each dimension. The Select 2-D slice row specifies which dimensions
25-56
Edit Existing LookupTables
of the table correspond to the row and column axes of the slice and the indices
that select the slice from the remaining dimensions.
To select another slice of the table, specify the row and column axes of the
slice in the first two columns of the Select 2-D slice row. Then select the
indices of the slice from the pop-up index lists in the remaining columns.
For example, the following selector displays slice (:,:,1) of a 3-D lookup table.
To transpose the table display, select the Transpose display check box.
Plotting Lookup Tables
To display a linear or mesh plot of the table or table slice in the Lookup Table
Editor, select Plot > Linear or Plot > Mesh.
25-57
25
Working with Lookup Tables
Suppose that you have the following lookup table open:
25-58
Edit Existing LookupTables
A linear plot of the table looks something like this:
25-59
25
Working with Lookup Tables
A mesh plot of the table looks something like this:
25-60
Edit Existing LookupTables
Editing Custom Lookup Table Blocks
You can use the Lookup Table Editor to edit custom lookup table blocks that
you or others have created. To do this, you must first configure the Lookup
Table Editor to recognize the custom lookup table blocks in your model. After
you configure the Lookup Table Editor to recognize custom blocks, you can
edit them as if they were standard blocks.
To configure the Lookup Table Editor to recognize custom blocks, select
File > Configure. The Lookup Table Blocks Type Configuration dialog box
appears.
By default, the dialog box displays a table of the lookup table block types
that the Lookup Table Editor currently recognizes. This table includes the
25-61
25
Working with Lookup Tables
standard blocks. Each row of the table displays key attributes of a lookup
table block type.
Adding a Custom Lookup Table Block Type
To add a custom block to the list of recognized types:
1 Click Add on the dialog box.
A new row appears at the bottom of the block type table.
2 Enter information for the custom block in the new row under these
headings.
Field Name
Description
Block type
Block type of the custom block. The block
type is the value of the block’s BlockType
parameter.
Mask type
Mask type of the custom block. The mask
type is the value of the block’s MaskType
parameter.
Breakpoint name
Names of the block parameters that store
the breakpoints.
Table name
Name of the block parameter that stores the
table data.
Number of dimensions
Leave empty.
Explicit dimensions
Leave empty.
3 Click OK.
Removing Custom Lookup Table Block Types
To remove a custom lookup table block type from the list that the Lookup
Table Editor recognizes, select the custom entry in the table of the Lookup
Table Blocks Type Configuration dialog box. Then click Remove.
To remove all custom lookup table block types, select the Use Simulink
default lookup table blocks list check box at the top of the dialog box.
25-62
Create a Logarithm Lookup Table
Create a Logarithm Lookup Table
Suppose you want to approximate the common logarithm (base 10) over the
input range [1, 10] without performing an expensive computation. You can
perform this approximation using a lookup table block as described in the
following procedure.
1 Copy the following blocks to a Simulink model:
• One Constant block to input the signal, from the Sources library
• One n-D Lookup Table block to approximate the common logarithm,
from the Lookup Tables library
• One Display block to display the output, from the Sinks library
2 Assign the table data and breakpoint data set to the n-D Lookup Table
block:
a In the Number of table dimensions field, enter 1.
b In the Table data field, enter
[0 .301 .477 .602 .699 .778 .845 .903 .954 1].
c In the Breakpoints 1 field, enter [1:10].
d Click Apply.
25-63
25
Working with Lookup Tables
The dialog box looks something like this:
3 Double-click the Constant block to open the parameter dialog box, and
change the Constant value parameter to 5. Click OK to apply the changes
and close the dialog box.
4 Connect the blocks as follows.
5 Start simulation.
25-64
Create a Logarithm Lookup Table
The following behavior applies to the n-D Lookup Table block.
Value of the
Constant Block
Action by the n-D
Lookup Table Block
Equals a breakpoint
Example of Block Behavior
Input Value
Output Value
Returns the
corresponding output
value
5
0.699
Falls between
breakpoints
Linearly interpolates
the output value
using neighboring
breakpoints
7.5
0.874
Falls outside the range
of the breakpoint data
set
Linearly extrapolates
the output value from
a pair of values at the
end of the breakpoint
data set
10.5
1.023
For the n-D Lookup Table block, the default settings for Interpolation
method and Extrapolation method are both Linear.
25-65
25
Working with Lookup Tables
Prelookup and Interpolation Blocks
The following examples show the benefits of using Prelookup and
Interpolation Using Prelookup blocks.
Action
Benefit
Example
Use an index search to
relate inputs to table data,
followed by an interpolation
and extrapolation stage that
computes outputs
Enables reuse of index search
results to look up data in
multiple tables, which reduces
simulation time
To open the model, type
sldemo_bpcheck at the
command prompt.
Set breakpoint and table data
types explicitly
Lowers memory required to
store:
To open the model, type
sldemo_interp_memory at the
command prompt.
• Breakpoint data that uses a
smaller type than the input
signal
• Table data that uses a
smaller type than the
output signal
Provides easier sharing of:
To open the model, type
fxpdemo_lookup_shared_param
• Breakpoint data among
Prelookup blocks
at the command prompt.
• Table data among
Interpolation Using
Prelookup blocks
Set the data type for
intermediate results explicitly
25-66
Enables reuse of utility
functions in the generated
code
To open the model, type
Enables use of higher precision
for internal computations than
for table data or output data
To open the model, type
fxpdemo_prelookup_utilfcn
at the command prompt.
fxpdemo_interp_precision
at the command prompt.
Optimize Generated Code for Lookup Table Blocks
Optimize Generated Code for Lookup Table Blocks
In this section...
“Remove Code That Checks for Out-of-Range Inputs” on page 25-67
“Optimize Breakpoint Spacing in Lookup Tables” on page 25-69
Remove Code That Checks for Out-of-Range Inputs
By default, generated code for the following lookup table blocks include
conditional statements that check for out-of-range breakpoint or index inputs:
• 1-D Lookup Table
• 2-D Lookup Table
• n-D Lookup Table
• Prelookup
• Interpolation Using Prelookup
To generate code that is more efficient, you can remove the conditional
statements that protect against out-of-range input values.
Block
Check Box to Select
1-D Lookup Table
Remove protection against out-of-range
input in generated code
2-D Lookup Table
n-D Lookup Table
Prelookup
Interpolation Using
Prelookup
Remove protection against out-of-range
index in generated code
Selecting the check box on the block dialog box improves code efficiency
because there are fewer statements to execute. However, if you are generating
code for safety-critical applications, you should not remove the range-checking
code.
25-67
25
Working with Lookup Tables
To verify the usage of the check box, run the following Model Advisor checks
and perform the recommended actions.
Model Advisor Check
When to Run the Check
By Product > Embedded Coder >
Identify lookup table blocks that
generate expensive out-of-range
checking code
For code efficiency
By Product > Simulink
Verification and Validation
> Modeling Standards >
DO-178C/DO-331 Checks >
Check usage of lookup table
blocks
For safety-critical applications
For more information about the Model Advisor, see “Consult the Model
Advisor” on page 4-81 in the Simulink documentation.
25-68
Optimize Generated Code for Lookup Table Blocks
Optimize Breakpoint Spacing in Lookup Tables
When breakpoints in a lookup table are tunable, the spacing does not affect
efficiency or memory usage of the generated code. When breakpoints are not
tunable, the type of spacing can affect the following factors.
Factor
Even Power of 2
Spaced Data
Evenly Spaced Data
Unevenly Spaced
Data
Execution speed
The execution speed
is the fastest. The
position search and
interpolation are
the same as for
evenly-spaced data.
However, to increase
speed a bit more for
fixed-point types, a
bit shift replaces the
position search, and a
bit mask replaces the
interpolation.
The execution speed
is faster than that for
unevenly-spaced data
because the position
search is faster and
the interpolation uses
a simple division.
The execution speed
is the slowest of the
different spacings
because the position
search is slower, and
the interpolation
requires more
operations.
Error
The error can be
larger than that for
unevenly-spaced
data because
approximating
a function with
nonuniform curvature
requires more points
to achieve the same
accuracy.
The error can be
larger than that for
unevenly-spaced
data because
approximating
a function with
nonuniform curvature
requires more points
to achieve the same
accuracy.
The error can be
smaller because
approximating
a function with
nonuniform curvature
requires fewer points
to achieve the same
accuracy.
ROM usage
Uses less command
ROM, but more data
ROM.
Uses less command
ROM, but more data
ROM.
Uses more command
ROM, but less data
ROM.
RAM usage
Not significant.
Not significant.
Not significant.
25-69
25
Working with Lookup Tables
Follow these guidelines:
• For fixed-point data types, use breakpoints with even, power-of-2 spacing.
• For non-fixed-point data types, use breakpoints with even spacing.
To identify opportunities for improving code efficiency in lookup table blocks,
run the following Model Advisor checks and perform the recommended
actions:
• By Product > Embedded Coder > Identify questionable fixed-point
operations
• By Product > Embedded Coder > Identify blocks that generate
expensive saturation and rounding code
For more information about the Model Advisor, see “Consult the Model
Advisor” on page 4-81 in the Simulink documentation.
25-70
Update Lookup Table Blocks to New Versions
Update Lookup Table Blocks to New Versions
In this section...
“Comparison of Blocks with Current Versions” on page 25-71
“Compatibility of Models with Older Versions of Lookup Table Blocks” on
page 25-72
“How to Update Your Model” on page 25-73
“What to Expect from the Model Advisor Check” on page 25-74
Comparison of Blocks with Current Versions
In R2011a, the following lookup table blocks were replaced with newer
versions in the Simulink library:
Block
Changes
Enhancements
Lookup
Table
• Block renamed as 1-D
Lookup Table
• Default integer rounding mode changed from
Floor to Simplest
• Icon changed
• Support for the following features:
-
Specification of parameter data types different
from input or output signal types
-
Reduced memory use and faster code execution
for nontunable breakpoints with even spacing
-
Cubic-spline interpolation and extrapolation
-
Specification of data types for fraction and
intermediate results
-
Specification of index search method
Table data with complex values
Fixed-point data types with word lengths up
to 128 bits
Specification of diagnostic for out-of-range
inputs
25-71
25
Working with Lookup Tables
Block
Changes
Enhancements
Lookup
Table
(2-D)
• Block renamed as 2-D
Lookup Table
• Default integer rounding mode changed from
Floor to Simplest
• Icon changed
• Support for the following features:
-
Specification of parameter data types different
from input or output signal types
-
Reduced memory use and faster code execution
for nontunable breakpoints with even spacing
-
Cubic-spline interpolation and extrapolation
-
Specification of data types for fraction and
intermediate results
-
Specification of index search method
Table data with complex values
Fixed-point data types with word lengths up
to 128 bits
Specification of diagnostic for out-of-range
inputs
• Check box for Require all inputs to have the
same data type now selected by default
Lookup
Table
(n-D)
• Block renamed as n-D
Lookup Table
• Default integer rounding mode changed from
Floor to Simplest
• Icon changed
Compatibility of Models with Older Versions of
Lookup Table Blocks
When you load existing models that contain the Lookup Table, Lookup Table
(2-D), and Lookup Table (n-D) blocks, those versions of the blocks appear. The
current versions of the lookup table blocks appear only when you drag the
blocks from the Simulink Library Browser into new models.
25-72
Update Lookup Table Blocks to New Versions
If you use the add_block function to add the Lookup Table, Lookup Table
(2-D), or Lookup Table (n-D) blocks to a model, those versions of the blocks
appear. If you want to add the current versions of the blocks to your model,
change the source block path for add_block:
Block
Old Block Path
New Block Path
Lookup Table
simulink/Lookup Tables/Lookup
Table
simulink/Lookup Tables/1-D
Lookup Table
Lookup Table (2-D)
simulink/Lookup Tables/Lookup
Table (2-D)
simulink/Lookup Tables/2-D
Lookup Table
Lookup Table (n-D)
simulink/Lookup Tables/Lookup
Table (n-D)
simulink/Lookup Tables/n-D
Lookup Table
How to Update Your Model
To update your model to use current versions of the lookup table blocks,
follow these steps:
Step
Action
Reason
1
Run this Model Advisor check: By
Product > Simulink > Check model,
local libraries, and referenced models
for known upgrade issues requiring
compile time information.
Identify blocks that do not have compatible
settings with the 1-D Lookup Table and
2-D Lookup Table blocks.
2
For each block that does not have
compatible settings:
Modify each Lookup Table or Lookup Table
(2-D) block to ensure compatibility with
the current versions.
• Decide how to address each warning.
• Adjust block parameters as needed.
3
Repeat steps 1 and 2 until you are satisfied
with the results of the Model Advisor
check.
Ensure that block replacement works for
the entire model.
4
Run the slupdate function on your model.
Perform block replacement with the 1-D
Lookup Table and 2-D Lookup Table
blocks.
25-73
25
Working with Lookup Tables
After block replacement, the block names that appear in the model remain
the same. However, the block icons match the ones for the 1-D Lookup Table
and 2-D Lookup Table blocks. For more information about the Model Advisor,
see “Consult the Model Advisor” on page 4-81 in the Simulink documentation.
What to Expect from the Model Advisor Check
The Model Advisor check groups all Lookup Table and Lookup Table (2-D)
blocks into three categories:
• Blocks that have compatible settings with the 1-D Lookup Table and 2-D
Lookup Table blocks
• Blocks that have incompatible settings with the 1-D Lookup Table and 2-D
Lookup Table blocks
• Blocks that have repeated breakpoints
Blocks with Compatible Settings
When a block has compatible parameter settings, automatic block replacement
can occur without backward incompatibilities.
Lookup Method in the
Lookup Table or Lookup
Table (2-D) Block
Parameter Settings After Automatic Block Replacement
Interpolation
Extrapolation
Interpolation-Extrapolation Linear
Linear
Interpolation-Use End
Values
Linear
Clip
Use Input Below
Flat
Not applicable
Depending on breakpoint spacing, one of two index search methods can apply.
Breakpoint Spacing in the Lookup Table
or Lookup Table (2-D) Block
Index Search Method After Automatic
Block Replacement
Not evenly spaced
Binary search
Evenly spaced and tunable
Evenly spaced and not tunable
25-74
A prompt appears, asking you to select Binary
search or Evenly spaced points.
Update Lookup Table Blocks to New Versions
Blocks with Incompatible Settings
When a block has incompatible parameter settings, the Model Advisor shows
a warning and a recommended action, if applicable.
• If you perform the recommended action, you can avoid incompatibility
during block replacement.
• If you use automatic block replacement without performing the
recommended action, you might see numerical differences in your results.
Incompatibility Warning
Recommended Action
What Happens for
Automatic Block
Replacement
The Lookup Method is Use
Input Nearest or Use Input
Above. The replacement block
does not support these lookup
methods.
Change the lookup method to
one of the following options:
The Lookup Method changes
to Interpolation - Use End
Values.
• Interpolation -
In the replacement block, this
setting corresponds to:
Extrapolation
• Interpolation - Use End
Values
• Use Input Below
The Lookup Method
is Interpolation Extrapolation, but the
input and output are not the
same floating-point type. The
replacement block supports
linear extrapolation only when
all inputs and outputs are the
same floating-point type.
Change the extrapolation
method or the port data types
of the block.
The block uses small
fixed-point word lengths,
so that interpolation uses
only one rounding operation.
The replacement block uses
two rounding operations for
interpolation.
None
• Interpolation set to
Linear
• Extrapolation set to Clip
You also see a message that
explains possible numerical
differences.
You see a message that
explains possible numerical
differences.
25-75
25
Working with Lookup Tables
Blocks with Repeated Breakpoints
When a block has repeated breakpoints, the Model Advisor recommends that
you change the breakpoint data and rerun the check. You cannot perform
automatic block replacement for blocks with repeated breakpoints.
25-76
Lookup Table Glossary
Lookup Table Glossary
The following table summarizes the terminology used to describe lookup
tables in the Simulink user interface and documentation.
Term
Meaning
breakpoint
A single element of a breakpoint
data set. A breakpoint represents
a particular input value to which a
corresponding output value in the
table data is mapped.
breakpoint data set
A vector of input values that indexes
a particular dimension of a lookup
table. A lookup table uses breakpoint
data sets to relate its input values to
the output values that it returns.
extrapolation
A process for estimating values that
lie beyond the range of known data
points.
interpolation
A process for estimating values that
lie between known data points.
lookup table
An array of data that maps input
values to output values, thereby
approximating a mathematical
function. Given a set of input values,
a “lookup” operation retrieves the
corresponding output values from
the table. If the lookup table does
not explicitly define the input
values, Simulink can estimate an
output value using interpolation,
extrapolation, or rounding.
monotonically increasing
The elements of a set are ordered
such that each successive element is
greater than or equal to its preceding
element.
25-77
25
25-78
Working with Lookup Tables
Term
Meaning
rounding
A process for approximating a value
by altering its digits according to a
known rule.
strictly monotonically increasing
The elements of a set are ordered
such that each successive element is
greater than its preceding element.
table data
An array that serves as a sampled
representation of a function
evaluated at a lookup table’s
breakpoint values. A lookup table
uses breakpoint data sets to index
the table data, ultimately returning
an output value.
26
Working with Block Masks
• “Block Masks” on page 26-2
• “How Mask Parameters Work” on page 26-4
• “Mask Code Execution” on page 26-7
• “Mask Terminology” on page 26-11
• “Mask a Block” on page 26-12
• “Draw Mask Icon” on page 26-15
• “Create Mask Documentation” on page 26-17
• “Initialize Mask” on page 26-19
• “Best Practices for Masking” on page 26-22
• “Considerations for Masking Model Blocks” on page 26-23
• “Masks on Blocks in User Libraries” on page 26-25
• “Promote Underlying Block Parameters to Mask” on page 26-27
• “Create Custom Interface for Simulink Blocks” on page 26-31
• “Rules for Promoting Parameters” on page 26-36
• “Mask Blocks and Promote Parameters” on page 26-38
• “Operate on Existing Masks” on page 26-42
• “Calculate Values Used Under the Mask” on page 26-46
• “Control Masks Programmatically” on page 26-49
• “Create Dynamic Mask Dialog Boxes” on page 26-56
• “Create Dynamic Masked Subsystems” on page 26-61
• “How Do I Debug Masks That Use MATLAB Code?” on page 26-67
26
Working with Block Masks
Block Masks
In this section...
“What Are Masks?” on page 26-2
“When to Use Masks?” on page 26-2
What Are Masks?
Masks are custom interfaces you can apply to Simulink blocks. A mask hides
the user interface of the block, and instead displays a custom dialog to control
specific parameters of the masked block.
When you mask a block, you change only the interface to the block, not its
underlying characteristics. Masking a nonatomic subsystem does not make it
act as an atomic subsystem, and masking a virtual block does not convert it
to a nonvirtual block.
Note You cannot save a mask separately from the block that it masks. You
can also not create an isolated mask definition and apply it to more than
one block.
The mask icon and Mask Parameters dialog box are analogous to the block
icon and block Parameters dialog, respectively.
When you set mask parameter values, the mask can use the values to
dynamically change the mask icon and dialog box and to calculate values to
be used under the mask. A mask on a subsystem can dynamically change the
subsystem to reflect mask parameter values.
When to Use Masks?
Masks are useful for customizing block interfaces, encapsulating logic, and
providing restricted access to data.
26-2
Block Masks
Masks are comparable to subsystems, in that they both simplify the graphical
appearance of a model. However, subsystems do not offer an interface for
users to interact with underlying block parameters.
Consider masking a Simulink block when you want to
• display a meaningful dynamic icon that reflects values within a block
• define customized parameters whose names reflect the purpose of a block
• provide a dialog box that lets users access only select parameters of the
underlying blocks
• provide users customized documentation that is specific to the masked block
26-3
26
Working with Block Masks
How Mask Parameters Work
A masked block is a custom interface to underlying blocks that are governed
by block parameters. Mask parameters are the links to these underlying
block parameters.
Mask parameters are defined in the mask workspace, while block parameters
may be defined in the model or base workspace.
You can provide access to one or more underlying block parameters by
defining the corresponding number of mask parameters. Mask parameters
appear in the Mask Parameters dialog box as editable fields. Simulink
applies the value of a mask parameter to the value of the corresponding block
parameter during simulation.
Consider the Mask Parameters dialog box of model masking_example.
This dialog contains fields for mask parameters Slope and Intercept, both
defined in the Mask Editor.
26-4
How Mask Parameters Work
Slope corresponds to mask workspace variable m, and Intercept, to mask
workspace variable b. Moreover, variable names m and b correspond to the
Gain and Constant value parameters of the underlying blocks.
In the Mask Parameters dialog box, when you set Slope and Intercept
to 5 and 2, respectively, Simulink assigns these values to mask workspace
variables m and b.
Before simulation begins, Simulink searches up the workspace hierarchy,
looking in the mask workspace first, for values to resolve the Gain parameter
26-5
26
Working with Block Masks
m and Constant value parameter b. Since variables m and b are defined in
the mask workspace, Simulink applies their values to the block parameters.
Without a mask for the same subsystem, no mask workspace would exist. In
that case, Simulink would continue searching up the workspace hierarchy for
definitions of m and b.
26-6
Mask Code Execution
Mask Code Execution
In this section...
“Mask Code Placement” on page 26-7
“Drawing Command Execution” on page 26-7
“Initialization Command Execution” on page 26-8
“Callback Code Execution” on page 26-9
Mask Code Placement
You can use MATLAB code to initialize a mask as well as to draw mask icons.
Since the location of code affects model performance, place your code to reflect
the functionality you need.
Purpose
Placement in Mask
Editor
Programmatic
Specification
Initialize the mask
Initialization pane
MaskInitialization
Draw mask icon
Icon & Ports pane
MaskDisplay
Callback code for mask
parameters
Parameters pane
MaskCallbacks
parameter
parameter
parameter
Drawing Command Execution
Place MATLAB code for drawing mask icons in the Icon Drawing
Commands section of the Icon & Ports pane. Simulink executes these
commands sequentially to redraw the mask icon in the following cases:
• The drawing commands are dependent on mask parameters and the values
of these mask parameters change.
• The block’s appearance is altered due to rotation or other changes.
26-7
26
Working with Block Masks
Note If you place MATLAB code for drawing mask icons in the Initialization
pane, model performance is affected, because Simulink redraws the icon each
time the masked block is evaluated in the model.
Initialization Command Execution
When you open a model, Simulink locates visible masked blocks that reside at
the top level of the model or in an open subsystem. Simulink only executes the
initialization commands for these visible masked blocks if they meet either
of the following conditions:
• The masked block has icon drawing commands.
Note Simulink does not initialize masked blocks that do not have icon
drawing commands, even if they have initialization commands.
• The masked subsystem belongs to a library and has the Allow library
block to modify its contents parameter enabled.
Simulink initializes masked blocks that are not initially visible when you
open the subsystem or model that contains these blocks.
When you load a model into memory without displaying it graphically, no
initialization commands initially run for any masked blocks. See “Load a
Model” on page 1-7 and load_system for information about loading a model
without displaying it.
Initialization commands for all masked blocks in a model that have drawing
commands run when you:
• Update the diagram
• Start simulation
• Start code generation
Initialization commands for an individual masked block run when you:
26-8
Mask Code Execution
• Change any of the parameters that define the mask, such as MaskDisplay
and MaskInitialization, by using the Mask Editor or set_param.
• Rotate or flip the masked block, if the icon depends on initialization
commands.
• Cause the icon to be drawn or redrawn, and the icon drawing depends
on initialization code.
• Change the value of a mask parameter by using the block dialog box or
set_param.
• Copy the masked block within the same model or between different models.
Callback Code Execution
Simulink executes the callback commands in the following cases:
• You open the Mask Parameters dialog box. Callback commands execute
sequentially, starting with the top mask dialog box parameter.
• You modify a parameter value in the Mask Parameters dialog box and
then change the cursor’s focus (that is, you press the Tab key or click into
another field in the dialog box).
Note When you modify the parameter value by using the set_param
command, the callback commands do not execute.
• You modify the parameter value, either in the Mask Parameters dialog
box or using set_param, and then apply the change by clicking Apply or
OK. Mask initialization commands execute after callback commands (See
“Initialization Pane”).
• You hover over a masked block to see the data tip for the block, when the
data tip contains parameter names and values. The callback executes
again when the block data tip disappears.
Note Callback commands do not execute if the Mask Parameters dialog
box is open when the block data tip appears.
26-9
26
Working with Block Masks
• Update a diagram (for example, by pressing Ctrl+D or by selecting
Simulation > Update diagram in the Simulink Editor).
26-10
Mask Terminology
Mask Terminology
Term
Description
Mask icon
The masked block icon generated using drawing
commands. This icon may be static or change
dynamically with underlying block parameter
values.
Parameters
defined in the Mask Editor that link
to underlying block parameters. Setting a mask
parameter sets the corresponding block parameter.
Mask parameters
Mask initialization
code
MATLAB code that initializes a masked block or
reflects current parameter values.
Mask callback code
MATLAB code that runs when the value of a mask
parameter changes. Use callback code to modify
a mask dialog box to reflect current parameter
values.
Mask
documentation
Description and usage information for a masked
block defined in the Mask Editor.
Mask dialog
A dialog box that contains fields for setting
mask parameter values and provides mask
documentation.
Mask workspace
Masks that define mask parameters or contain
initialization code have a mask workspace. This
workspace stores mask parameters and temporary
values used by the mask.
26-11
26
Working with Block Masks
Mask a Block
This example shows how to create a block mask and define its parameters.
Create mask
1 Open the model subsystem_example. Alternately, execute the following
command in MATLAB:
open_system([docroot '/toolbox/simulink/ug/examples/masking/subsystem_exa
This model contains a Subsystem block that models the equation for a
line: y = mx + b.
2 Double-click the subsystem block to open it.
Notice that this subsystem contains the following blocks that are controlled
by parameters.
• Gain block, named Slope, with parameter m
• Constant block, named Intercept, with parameter b
3 Return to the top-level model, right-click the subsystem block, and select
Mask > Create Mask.
The Mask Editor appears.
Define mask parameters
Define parameters to control the underlying blocks.
1 In the Mask Editor, click the Parameters tab.
2 In the Dialog parameters pane, click the Add parameter icon.
3 In the row that appears, specify the parameters as follows.
26-12
Mask a Block
4 Click Apply.
Set mask parameter values
Provide values to the parameters.
1 Double-click the mask to view the mask parameter dialog.
2 Set Slope and Intercept as 5 and 2, respectively.
To control the underlying blocks, change these parameters.
26-13
26
Working with Block Masks
3 Click OK.
26-14
Draw Mask Icon
Draw Mask Icon
This example shows how to use drawing commands to create a mask icon. You
can create icons that update when you change the mask parameters, thereby
reflecting the purpose of the block.
Draw static icon
A static mask icon remains unchanged, independent of the value of the mask
parameters.
1 Right-click the masked block that requires the icon and select Mask > Edit
Mask.
The Mask Editor appears.
2 In the Icons & Ports tab, enter the following command in the Icon
Drawing commands pane:
% Use specified image as mask icon
image(imread('engine.jpg'))
The image file must be on the MATLAB path.
Note For more examples of drawing command syntax, explore the
Command drop-down list in the Examples of drawing commands pane.
Draw dynamic icon
A dynamic icon changes with the values of the mask parameters. Use it to
represent the purpose of the masked block.
1 Right-click the masked block that requires the icon and select Mask > Edit
Mask.
The Mask Editor appears.
2 In the Icons & Ports tab, enter the following command in the Icon
Drawing commands pane:
26-15
26
Working with Block Masks
pos = get_param(gcb, 'Position');
width = pos(3) - pos(1);
x = [0, width];
y = m*x + b;
plot(x,y)
3 Under Options, set Icon Units to Pixels.
The drop-down lists under Options allow you to specify icon frame
visibility, icon transparency, drawing context, icon rotation, and port
rotation.
4 Click Apply.
Note If Simulink cannot evaluate all commands in the Icon Drawing
commands pane to generate an icon, three question marks (? ? ?)
appear on the mask.
See model masking_example to view the icon generated.
Additional examples
See model slexMaskDisplayAndInitializationExample for more examples
of icon drawing commands. This model shows how to draw:
• a static mask
• a dynamic shape mask
• a dynamic text mask
• an image mask
26-16
Create Mask Documentation
Create Mask Documentation
This example shows how to create mask documentation for display in the
Mask Parameters dialog box.
1 Right-click the masked block to document and select Mask > Edit Mask.
The Mask Editor appears.
2 In the Documentation tab, enter the following information:
• Mask type: The name of the mask. This name appears at the top of the
Mask Parameters dialog box. Newlines are not permitted.
• Mask description: A summary of what the mask does. This description
appears below the mask name, and it contain newlines as well as spaces.
• Mask help: Additional mask information that appears when you click
Help in the Mask Parameters dialog box. You can use plain text, HTML
and graphics, URLs, and web or eval commands.
26-17
26
26-18
Working with Block Masks
Initialize Mask
Initialize Mask
The initialization code is MATLAB code that you specify and that Simulink
runs to initialize the masked subsystem at critical times, such as model
loading and the start of a simulation run (see “Initialization Command
Execution” on page 26-8). You can use the initialization code to set the initial
values of the mask parameters.
The masked subsystem initialization code can refer only to variables in its
local workspace.
When you reference the block within, or copy the block into, a model, the
Mask Parameters dialog box displays the specified default values. You cannot
use mask initialization code to change mask parameter default values in a
library block or any other block.
Mask Editor Initialization Pane
Use the Mask Editor Initialization pane to enter MATLAB commands that
initialize a masked block. Reference information about the Initialization
pane appears in “Initialization Pane”.
The Initialization pane has two sections:
• Dialog variables list
• Initialization commands edit area
26-19
26
Working with Block Masks
Dialog variables
The Dialog variables list displays the names of the variables associated
with the mask parameters of the subsystem (that is, the parameters defined
in the Parameters pane).
You can copy the name of a parameter from this list and paste it into the
adjacent Initialization commands field, using the Simulink keyboard copy
and paste commands.
You can also use the list to change the names of mask parameter variables.
To change a name, double-click the name in the list. An edit field containing
the existing name appears. Edit the existing name and press Enter or click
outside the edit field to confirm your changes.
26-20
Initialize Mask
Initialization Commands
Enter the initialization commands in this field. You can enter any valid
MATLAB expression, consisting of MATLAB functions and scripts, operators,
and variables defined in the mask workspace. Initialization commands cannot
access base workspace variables.
Terminate initialization commands with a semicolon to avoid echoing results
to the MATLAB Command Window.
For information on debugging initialization commands, see “Initialization
Command Limitations” on page 26-21and “How Do I Debug Masks That Use
MATLAB Code?” on page 26-67.
Initialization Command Limitations
Mask initialization commands must observe the following rules:
• Do not use initialization code to create dynamic mask dialog boxes (that
is, dialog boxes whose appearance or control settings change depending on
changes made to other control settings). Instead, use the mask callbacks
that are specifically for this purpose. For more information, see “Create
Dynamic Mask Dialog Boxes” on page 26-56.
• Avoid using set_param commands on blocks residing in another masked
subsystem that you are initializing. Trying to set parameters of blocks in
lower-level masked subsystems can trigger unresolvable symbol errors if
lower-level masked subsystems reference symbols defined by higher-level
masked subsystems. Suppose, for example, a masked subsystem A contains
masked subsystem B, which contains Gain block C, whose Gain parameter
references a variable defined by B. Suppose also that subsystem A has
initialization code that contains the following command:
set_param([gcb '/B/C'], 'SampleTime', '-1');
Simulating or updating a model containing A causes an unresolvable
symbol error.
26-21
26
Working with Block Masks
Best Practices for Masking
These examples show best practices for masking Simulink blocks. There are
also some examples that show practices to avoid.
In this section...
“Use These Best Practices” on page 26-22
“Avoid These Practices” on page 26-22
Use These Best Practices
• Set mask parameters
• Group parameters under tabs
• Promote mask parameters
• Sequence mask callbacks
• Define mask display and initialization
• Create dynamic mask dialog boxes
• Use self-modifying library masks
• Use handle graphics in masking
Avoid These Practices
• Unsafe mask callbacks
• Unsafe nested mask callbacks
26-22
Considerations for Masking Model Blocks
Considerations for Masking Model Blocks
In this section...
“Referenced Model Name” on page 26-23
“Variable Workspace” on page 26-24
Referenced Model Name
You can use a mask parameter to specify the name of a model referenced by
• a masked Model block, or
• a Model block in a masked subsystem
In these cases, the mask parameter should receive the name of the reference
model literally, without being evaluated, because Simulink updates model
reference targets before mask parameters.
Use one of the following approaches to obtain the literal name of the
referenced model:
• Restricted model names: In the Parameters pane of the Mask Editor,
select the parameter that stores the referenced model name. Set its Type
to popup and clear the check box for Evaluate.
With this approach, users can only select a model name from a drop-down
list in the Mask Parameters dialog box. Further, since the Evaluate option
is cleared, the name is provided literally and not numerically evaluated.
• Unrestricted model names: In the Parameters pane of the Mask
Editor, select the parameter that stores the referenced model name. Set its
Type to edit and clear the check box for Evaluate.
With this approach, users can type the model name in the Mask Parameters
dialog box. However, since the Evaluate option is cleared, the name is
provided literally and not numerically evaluated.
See “Control Types” for more information about Pop-Up and Edit controls.
26-23
26
Working with Block Masks
Variable Workspace
When you mask a Model block that references another model, the referenced
model cannot access the mask workspace of the Model block.
Therefore, variables used by the referenced model must resolve either to
workspaces defined by the referenced model or to the base workspace.
26-24
Masks on Blocks in User Libraries
Masks on Blocks in User Libraries
In this section...
“About Masks and User-Defined Libraries” on page 26-25
“Masking a Block for Inclusion in a User Library” on page 26-25
“Masking a Block that Resides in a User Library” on page 26-25
“Masking a Block Copied from a User Library” on page 26-26
About Masks and User-Defined Libraries
You can mask a block that will be included in a user library or already
resides in a user library, or you can mask an instance of a user library block
that you have copied into a model. For example, a user library block might
provide the capabilities that a model needs, but its native interface might be
inappropriate or unhelpful in the context of the particular model. Masking
the block could give it a more appropriate user interface.
Masking a Block for Inclusion in a User Library
You can create a custom block by encapsulating a block diagram that defines
the block’s behavior in a masked subsystem and then placing the masked
subsystem in a library. You can also apply a mask to any other type of block
that supports masking, then include the block in a library.
Masking a block that will later be included in a library requires no special
provisions. Create the block and its mask as described in this chapter, and
include the block in the library as described in “Create Block Libraries” on
page 28-20.
Masking a Block that Resides in a User Library
Creating or changing a library block mask immediately changes the block
interface in all models that access the block using a library reference, but has
no effect on instances of the block that already exist as separate copies.
To apply or change a library block mask, open the library that contains the
block. Apply, change, or remove a mask as you could if the block did not
26-25
26
Working with Block Masks
reside in a library. In addition, you can specify non-default values for block
mask parameters. When the block is referenced within or copied into a model,
the specified default values appear on the block’s Mask Parameters dialog
box. By default, edit fields have a value of zero, check boxes are cleared,
and drop-down lists select the first item in the list. To change the default
for any field:
1 Fill in the desired default values or change check box or drop-down list
settings
2 Click Apply or OK to save the changed values into the library block mask.
Be sure to save the library after changing the mask of any block that it
contains. Additional information relating to masked library blocks appears in
“Create Block Libraries” on page 28-20.
Masking a Block Copied from a User Library
A block that was copied from a user library, as distinct from a block accessed
by using a library reference, has no special status with respect to masking.
You can add a mask to the copied block, or change or remove any mask that it
already has.
26-26
Promote Underlying Block Parameters to Mask
Promote Underlying Block Parameters to Mask
This example shows to promote the parameters of underlying blocks to the
mask. See model slexMaskParameterPromotionExample for more examples
of parameter promotion.
1 Right-click a block or subsystem in your model and select Mask > Create
Mask.
The Mask Editor appears.
2 Select the Parameters pane.
3 Choose one or more parameters for promotion.
a Create a new mask parameter. Click Add Parameter.
b Click the Promote button.
The Promoted parameter selector dialog box opens.
26-27
26
Working with Block Masks
c Choose underlying block parameters to promote to the currently selected
mask parameter.
• Select a parameter in the Promotable parameters table and click
the right arrow button to add to the Promoted parameters list.
Tip View the tooltips on promotable parameters to see key fields
such as Type.
• When masking a subsystem, you can use the Child blocks list or the
Search box to find underlying block parameters to promote.
• (Optional) When masking a subsystem, you can associate multiple
promoted parameters with the currently selected mask parameter,
provided they are of the same type.
For example, you can promote multiple Gain parameters in a
subsystem to a single prompt on your mask.
d Click OK to return to the Mask Editor.
26-28
Promote Underlying Block Parameters to Mask
4 Observe that the Type field is now disabled because you have promoted
a parameter to this mask parameter. Type is always disabled. Variable
is also disabled if you are directly masking a built-in block and not a
subsystem.
The Relative block path table shows you the location of the underlying
original block (where . means self ). Click the link under Relative
block path to open the underlying block.
5 Edit the prompt names for the mask, if desired. You cannot edit the
variable names of built-in block parameters. See “Rules for Promoting
Parameters” on page 26-36.
6 Repeat step 3 to add mask parameters and add or edit additional promoted
parameters.
26-29
26
Working with Block Masks
Tip If you want to promote many parameters from a built-in block, click
Promote All
.
The Promote All button is only available for block masks, not subsystem
masks.
All the parameters appear in the Mask Editor. To remove any unwanted
parameters, use the Delete Parameter button.
7 Click OK to finish editing the mask.
Now whenever you set a mask parameter, you also set the value of the
underlying promoted parameters.
26-30
Create Custom Interface for Simulink® Blocks
Create Custom Interface for Simulink Blocks
This example shows how to mask the Gain block and promote only the Gain
parameter to the mask, while hiding the other options and adding custom
parameters.
1 Right-click a Gain block in your model and select Mask > Create Mask.
The Mask Editor appears.
2 Select the Parameters pane.
3 Create a new mask parameter. Click Add Parameter.
4 Click the Promote button.
.
The Promoted parameter selector dialog box opens.
5 Select the Gain parameter in the Promotable parameters table and click
the right-arrow button to add to the Promoted parameters list.
26-31
26
Working with Block Masks
6 Click OK to return to the Mask Editor.
7 Observe that fields such as Variable and Type are now disabled because
you have promoted a built-in parameter to this mask parameter, and
the Relative block path table shows you the location of the underlying
original block (where ./ means self ). Click the link in the Relative
block path table to open the underlying Gain block.
8 (Optional) Add custom mask parameters by clicking Add Parameter. For
example, you can add an edit box to capture company notes.
26-32
Create Custom Interface for Simulink® Blocks
9 Click OK to finish creating the mask.
10 Double-click the Gain block. The new mask opens, showing only the
promoted Gain parameter and custom parameter.
26-33
26
Working with Block Masks
11 Look under the mask to see the underlying Gain block dialog box. You can
see that the Gain parameter is now disabled because you have promoted
it to the mask.
26-34
Create Custom Interface for Simulink® Blocks
26-35
26
Working with Block Masks
Rules for Promoting Parameters
In this section...
“General Rules” on page 26-36
“Promotion from directly masked block” on page 26-36
“Promotion from child blocks within subsystems” on page 26-37
“Links created from masked blocks” on page 26-37
General Rules
• You cannot mask blocks that already have masks. For example, some
Simulink blocks like the Ramp and Chirp Signal in the Sources library
cannot be masked.
• Some parameters with certain attributes cannot be promoted, and if you
try, an error message appears.
• After you promote a parameter to the mask, the following rule apply.
-
The parameter is disabled on the block dialog box. If you try to directly
edit promoted parameters, either in the dialog or at the command line,
an error message appears.
-
You cannot promote the same parameter again to a different mask
parameter.
-
The mask parameter inherits the Evaluate property from the parameter
promoted to it, and you cannot change it. Any mismatch between the
Evaluate property of the mask parameter and the promoted parameter
results in an error message.
Promotion from directly masked block
• The mask parameter must have the same variable name as that of
the parameter promoted to it. You cannot change the promoted mask
parameter variable names because they are strictly inherited from the
underlying built-in block parameter.
26-36
Rules for Promoting Parameters
• The mask tries to retain the dynamic dialog behavior, if any, of the
promoted parameter. You can specify your own dynamic dialog behavior of
the mask parameter. If you do, the mask first executes the dynamic dialog
callback of the promoted parameter, followed by the user-specified dynamic
dialog callback of the mask parameter.
• You cannot promote multiple parameters to a single mask parameter.
Promotion from child blocks within subsystems
• You can associate multiple parameters provided they are of the same type.
If the parameter is of type popup or DataType then the options must also be
the same for them to be promoted together. The Evaluate property among
the parameters to be promoted together must be similar.
Tip View the tooltips on promotable parameters to see key fields such as
Type and Evaluate.
• If a child block is masked, you cannot promote the underlying block dialog
parameters.
• For child blocks, you cannot view or promote parameters from inside a
masked block.
• For child blocks, you cannot view or promote parameters from inside a
linked block.
Links created from masked blocks
• The underneath block dialog opens completely disabled for the links of
masked blocks. You can edit values only from the mask dialog.
• If the mask author decides not to promote a parameter, its value in the
linked blocks is tied to the library value for that parameter as specified in
the library.
26-37
26
Working with Block Masks
Mask Blocks and Promote Parameters
In this section...
“Mask Built-In Blocks Directly and Within Subsystems” on page 26-38
“Create Custom Interface for Multiple Parameters in Subsystem” on page
26-38
Mask Built-In Blocks Directly and Within Subsystems
You can directly mask built-in blocks with the Mask Editor to provide custom
icons and dialog boxes. In the Mask Editor, you can choose to promote any
underlying parameter of any block to the mask. For subsystems, you can
choose to promote parameters from any child blocks. For a subsystem
block, you can associate a single mask parameter with multiple promoted
parameters if they are of the same type. Changing the value of the mask
parameter also sets the value of the associated promoted parameters.
You can use masking in the following use cases:
• You can directly mask a built-in block to simplify the interface and add
custom parameters.
• You can promote multiple parameters from child blocks to a single mask
parameter for a subsystem block.
• You can promote all parameters for a directly masked built-in block, and
then choose a subset of the parameters to keep in the mask.
Create Custom Interface for Multiple Parameters in
Subsystem
You can promote multiple parameters from child blocks to a single mask
parameter for a subsystem block. This enables you to use a simplified single
setting in the mask to set multiple child block parameters (of the same type)
in the subsystem.
The following example demonstrates this capability. It recreates the functions
of the Ramp block by using other blocks in a subsystem, and then masking
the subsystem to create a simplified custom interface.
26-38
Mask Blocks and Promote Parameters
The Mask Editor contains a selection of promoted parameters from underlying
blocks within the subsystem. The selected parameter has three underlying
parameters of the same type promoted to the same mask parameter.
The Promoted parameter selector dialog shown next demonstrates how to
specify this setup. Three parameters of the same type, from different child
blocks, are added to the Promoted parameters list to promote to the
currently selected mask parameter.
26-39
26
Working with Block Masks
The mask shows the four parameters specified in the Mask Editor.
26-40
Mask Blocks and Promote Parameters
When you select the Interpret vector parameters as 1-D check box on
the mask, you also set the underlying promoted parameters in the three
child blocks.
26-41
26
Working with Block Masks
Operate on Existing Masks
In this section...
“Change a Block Mask” on page 26-42
“View Mask Parameters” on page 26-42
“Look Under Block Mask” on page 26-43
“Remove and Cache Mask” on page 26-43
“Restore Cached Mask” on page 26-45
“Permanently Delete Mask” on page 26-45
Change a Block Mask
You can change an existing mask by reopening the Mask Editor and using the
same techniques that you used to create the mask:
1 Select the masked block.
2 Select Mask > Edit Mask.
The Mask Editor reopens, showing the existing mask definition. Change the
mask as needed. After you change a mask, be sure to save the model before
closing it, or the changes will be lost.
View Mask Parameters
To display a masked block’s Mask Parameters dialog box, double-click
the block. Alternatively, right-click the block and select Mask > Mask
Parameters.
To display the Block Parameters dialog box that double-clicking would
display if no mask existed, right-click the masked block and select Block
Parameters (BlockType).
26-42
Operate on Existing Masks
Look Under Block Mask
To see the block diagram under a masked Subsystem block, built-in block,
or the model referenced by a masked Model block, right-click the block and
select Mask > Look Under Mask.
Remove and Cache Mask
To remove a mask from a block and cache it for possible restoration later:
1 Right-click the block.
2 Select Mask > Edit Mask.
The Mask Editor opens and displays the existing mask, for example:
26-43
26
Working with Block Masks
3 Click Unmask in the lower left corner of the Mask Editor.
The Mask Editor removes the mask from the block, saves the mask in a cache
for possible restoration, then closes. The editor caches masks separately for
each block, so removing a mask from one block has no effect on a mask cached
for any other block. Closing the Mask Editor has no effect on cached masks.
When you have removed and cached a mask, you can later restore it, as
described in “Restore Cached Mask” on page 26-45, or delete it, as described
in “Permanently Delete Mask” on page 26-45. The removed cached mask has
no further effect unless you restore it.
26-44
Operate on Existing Masks
Restore Cached Mask
As long as a model remains open, you can restore a mask that you removed as
described in “Remove and Cache Mask” on page 26-43.
1 Right-click the block.
2 Select Mask > Create Mask.
The Mask Editor reopens, showing the cached masked definition.
3 Modify the definition if needed, using the techniques in “Mask a Block” on
page 26-12
4 Click Apply or OK to restore the mask, including any changes that you
made.
If you made any changes, be sure to save the model before closing it, or the
changes will be lost.
Permanently Delete Mask
To delete a mask permanently, first remove it as described in “Remove and
Cache Mask” on page 26-43, then save and close the model. You do not need
to close the model immediately after removing a mask that you intend to
delete. The removed mask remains in the cache and has no further effect
unless you restore it.
26-45
26
Working with Block Masks
Calculate Values Used Under the Mask
The masking_example assigns the values input using the Mask Parameters
dialog box directly to block parameters underneath the mask, as described in
“How Mask Parameters Work” on page 26-4. The assignment occurs because
the block parameter and the mask parameter have the same name, so the
search that always occurs when a block parameter needs a value finds the
mask parameter value automatically, as described in “Symbol Resolution”
on page 4-76.
You can use the Mask Editor to insert any desired calculation between a value
in the Mask Parameters dialog box and an underlying block parameter:
26-46
Calculate Values Used Under the Mask
See the “Initialization Pane” reference for reference information about all
Initialization pane capabilities. This section shows you how to use it for
calculating block parameter values.
To calculate a value for a block parameter, first break the link between the
mask and block parameters by giving them different names. To facilitate
such changes, the Dialog variables subpane lists all mask parameters. The
Initialization pane looks like this:
You cannot use mask initialization code to change mask parameter default
values in a library block or any other block.
26-47
26
Working with Block Masks
You can use the initialization code for a masked block to link mask parameters
indirectly to block parameters. In this approach, the initialization code
creates variables in the mask workspace whose values are functions of the
mask parameters and that appear in expressions that set the values of
parameters of blocks concealed by the mask.
If you need both the string entered and the evaluated value, clear the
Evaluate option. To get the value of a base workspace variable entered as
the literal value of the mask parameter, use the MATLAB evalin command
in the mask initialization code. For example, suppose the user enters the
string 'gain' as the literal value of the mask parameter k where gain is the
name of a base workspace variable. To obtain the value of the base workspace
variable, use the following command in the initialization code for the mask:
value = evalin('base', k)
These values are stored in variables in the mask workspace. A masked
block can access variables in its mask workspace. A workspace is associated
with each masked subsystem that you create. The current values of the
subsystem’s parameters are stored in the workspace as well as any variables
created by the block’s initialization code and parameter callbacks.
Tip 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.
26-48
Control Masks Programmatically
Control Masks Programmatically
In this section...
“Use Simulink.Mask and Simulink.MaskParameter” on page 26-49
“Use get_param and set_param” on page 26-50
“Predefined Masked Dialog Box Parameters” on page 26-52
“Notes on Mask Parameter Storage” on page 26-54
Use Simulink.Mask and Simulink.MaskParameter
Use instances of Simulink.Mask and Simulink.MaskParameter to perform
the following mask operations:
• Create, copy, and delete masks
• Create, edit, and delete mask parameters
• Determine the block that owns the mask
• Get workspace variables defined for a mask
In this example, the variable pmask stores the mask object obtained using
Simulink.Mask.get.
pmask = Simulink.Mask.get(gcbh);
pmask =
Simulink.Mask handle
Package: Simulink
Properties:
Type:
Description:
Help:
Initialization:
SelfModifiable:
Display:
IconFrame:
''
''
''
''
'off'
'fprintf('myMask')'
'on'
26-49
26
Working with Block Masks
IconOpaque:
RunInitForIconRedraw:
IconRotate:
PortRotate:
IconUnits:
Parameters:
'on'
'off'
'none'
'default'
'autoscale'
[]
In this example, the variable aparam stores a mask parameter and is used to set
the properties of the mask parameter using Simulink.MaskParameter.set.
aparam = pmask.Parameters(1);
aparam =
Simulink.MaskParameter handle
Package: Simulink
Properties:
Type:
TypeOptions:
Name:
Prompt:
Value:
Evaluate:
Tunable:
Enabled:
Visible:
ToolTip:
Callback:
Alias:
TabName:
'edit'
{0x1 cell}
'Myparam'
''
'[]'
'on'
'on'
'on'
'on'
'on'
''
''
''
aparam.set('Name','MyParam');
For more examples, see Simulink.Mask and Simulink.MaskParameter.
Use get_param and set_param
The Simulink software defines a set of masked block parameters that
define the current state of the masked block dialog box. You can use the
26-50
Control Masks Programmatically
Mask Editor to inspect and set many of these parameters. The get_param
and set_param commands also let you inspect and set mask dialog box
parameters. The set_param command allows you to set parameters that
change the appearance of a dialog box while the dialog box is open. This
ability to change the appearance of the dialog box while the dialog box is open
allows you to create dynamic masked dialog box.
For example, you can use the set_param command in mask callback functions
to be invoked when a user changes the values of user-defined parameters.
The callback functions, in turn, can use set_param commands to change the
values of predefined parameters of the masked block dialog box, and hence its
state. For example, the callback function can hide, show, enable, or disable a
user-defined parameter control.
Use the 'mask' option of the open_system command to open the Mask
Parameters dialog box for a block at the MATLAB command line or in a
MATLAB program.
You can customize every feature of the Mask Parameters dialog box, including
which parameters appear on the dialog box, the order in which they appear,
parameter prompts, the controls used to edit the parameters, and the
parameter callbacks (code used to process parameter values entered by the
user).
However, changing the mask parameter value with set_param does not
change the value of the underlying block variable. You cannot use get_param
or set_param to access the value of the underlying variable, because it is
hidden by the mask.
The set_param and get_param commands are insensitive to case differences
in mask variable names. For example, suppose a model named MyModel
contains a masked subsystem named A that defines a mask variable named
Volume. Then, the following line of code returns the value of the Volume
parameter.
get_param('MyModel/A', 'voLUME')
However, case does matter when using a mask variable as the value of a
block parameter inside the masked subsystem. For example, suppose a
Gain block inside the masked subsystem A specifies VOLUME as the value of
26-51
26
Working with Block Masks
its Gain parameter. This variable name does not resolve in the masked
subsystem’s workspace, as it contains a mask variable named Volume. If
the base workspace does not contain a variable named VOLUME, simulating
MyModel produces an error.
Predefined Masked Dialog Box Parameters
The following predefined parameters are associated with masked dialog boxes.
MaskCallbacks
The value of this parameter is a cell array of strings that specify callback
expressions for the user-defined parameter controls for the dialog box. The
first cell defines the callback for the first parameter control, the second for
the second parameter control, etc. The callbacks can be any valid MATLAB
expressions, including expressions that invoke MATLAB commands. This
capability means that you can implement complex callbacks as MATLAB
program files.
You can use either the Mask Editor or the MATLAB command line to specify
mask callbacks. To use the Mask Editor to enter a callback for a parameter,
enter the callback in the Callback field for the parameter.
The easiest way to set callbacks for a mask dialog box at the MATLAB
command is to first select the corresponding masked dialog box in a model
or library window and then to issue a set_param command at the MATLAB
command line. For example, the following code
set_param(gcb,'MaskCallbacks',{'parm1_callback', '',...
'parm3_callback'});
defines callbacks for the first and third parameters of the masked dialog box
for the currently selected block. To save the callback settings, save the model
or library containing the masked block.
MaskDescription
The value of this parameter is a string specifying the description of this block.
You can change a masked block’s description dynamically by setting this
parameter in a mask callback.
26-52
Control Masks Programmatically
MaskDisplay
The value of this parameter is string that specifies the MATLAB code for
the block icon.
MaskEnables
The value of this parameter is a cell array of strings that define the enabled
state of the user-defined parameter controls for this dialog box. The first cell
defines the enabled state of the control for the first parameter, the second for
the second parameter, etc. A value of 'on' indicates that the corresponding
control is enabled for user input; a value of 'off' indicates that the control
is disabled.
You can enable or disable user input dynamically by setting this parameter in
a callback. For example, the following command in a callback
set_param(gcb,'MaskEnables',{'on','on','off'});
disables the third control of the dialog box of the currently open masked block.
Disabled controls are colored gray to indicate visually that they are disabled.
MaskInitialization
The value of this parameter is string that specifies the initialization
commands for the mask workspace.
MaskPrompts
The value of this parameter is a cell array of strings that specify prompts
for user-defined parameters. The first cell defines the prompt for the first
parameter, the second for the second parameter, and so on.
MaskType
The value of this parameter is the mask type of the block associated with
this dialog box.
26-53
26
Working with Block Masks
MaskValues
The value of this parameter is a cell array of strings that specify the values of
user-defined parameters for this dialog box. The first cell defines the value for
the first parameter, the second for the second parameter, and so on.
MaskVisibilities
The value of this parameter is a cell array of strings that specify the visibility
of the user-defined parameter controls for this dialog box. The first cell
defines the visibility of the control for the first parameter, the second for
the second parameter, etc. A value of 'on' indicates that the corresponding
control is visible; a value of 'off' indicates that the control is hidden.
You can hide or show user-defined parameter controls dynamically by setting
this parameter in the callback for a control. For example, the following
command in a callback
set_param(gcb,'MaskVisibilities',{'on','off','on'});
would hide the control for the currently selected block’s second user-defined
mask parameter. Simulink expands or shrinks a dialog box to show or hide a
control, respectively.
Note For a full list of predefined masked block parameters see the Mask
Parameters reference page.
Notes on Mask Parameter Storage
1 The MaskPromptString parameter stores the Prompt field values for all
mask dialog box parameters as a string, with individual values separated
by vertical bars (|), for example:
"Slope:|Intercept:"
2 The MaskStyleString parameter stores the Type field values for all mask
dialog box parameters as a string, with individual values separated by
commas. The Popup strings values appear after the popup type, as shown
in this example:
26-54
Control Masks Programmatically
"edit,checkbox,popup(red|blue|green)"
3 The MaskValueString parameter stores the values of all mask dialog box
parameters as a string, with individual values separated by a vertical
bar (|). The order of the values is the same as the order in which the
parameters appear on the dialog box, for example:
"2|5"
4 The MaskVariables parameter stores the Variable field values for all
mask dialog box parameters as a string, with individual assignments
separated by semicolons. A sequence number indicates the prompt that is
associated with a variable. A special character preceding the sequence
number indicates whether the parameter value is evaluated or used
literally. An at-sign (@) indicates evaluation; an ampersand (&) indicates
literal usage. For example:
"a=@1;b=&2;"
This string defines two Variable field values:
• The value entered in the first parameter field is evaluated in the
MATLAB workspace, and the result is assigned to variable a in the
mask workspace.
• The value entered in the second parameter field is not evaluated, but is
assigned literally to variable b in the mask workspace.
Note You cannot set the MaskVariables parameter from the mask
initialization code.
26-55
26
Working with Block Masks
Create Dynamic Mask Dialog Boxes
In this section...
“About Dynamic Masked Dialog Boxes” on page 26-56
“Show parameter” on page 26-57
“Enable parameter” on page 26-57
“Setting Masked Block Dialog Box Parameters” on page 26-57
“Setting Nested Masked Block Parameters” on page 26-59
About Dynamic Masked Dialog Boxes
You can create dialogs for masked blocks whose appearance changes in
response to user input. Features of masked dialog boxes that can change in
this way include
• Visibility of parameter controls
Changing a parameter can cause the control for another parameter to
appear or disappear. The dialog expands or shrinks when a control appears
or disappears, respectively.
• Enabled state of parameter controls
Changing a parameter can cause the control for another parameter to be
enabled or disabled for input. A disabled control is grayed to indicate
visually that it is disabled.
• Parameter values
Changing a mask dialog box parameter can cause related mask dialog box
parameters to be set to appropriate values.
Creating a dynamic masked dialog box entails using the Mask Editor in
combination with the set_param command. Specifically, you use the Mask
Editor to define parameters of the dialog box, both static and dynamic.
For each dynamic parameter, you enter a callback function that defines
how the dialog box responds to changes to that parameter (see “Callback
Code Execution” on page 26-9). The callback function can in turn use the
set_param command to set mask dialog box parameters that affect the
26-56
Create Dynamic Mask Dialog Boxes
appearance and settings of other controls on the dialog box (see “Setting
Masked Block Dialog Box Parameters” on page 26-57). Finally, you save the
model or library containing the masked subsystem to complete the creation
of the dynamic masked dialog box.
Show parameter
The selected parameter appears on the Mask Parameters dialog box only if
this option is checked (the default).
Enable parameter
Clearing this option grays the prompt of the selected parameter and disables
the edit control of the prompt.
Setting Masked Block Dialog Box Parameters
The following example creates a mask dialog box with two parameters. The
first parameter is a pop-up menu that selects one of three gain values: 2, 5, or
User-defined. The selection in this pop-up menu determines the visibility of
an edit field for specifying the gain.
1 Mask a subsystem: Right-click the block and select Mask > Create Mask.
2 Select the Parameters pane on the Mask Editor.
3 Add a parameter.
• Enter Gain: in the Prompt field
• Enter gain in the Variable field
• Select popup in the Type field
• Uncheck Evaluate to use the literal value from the pop-up menu options.
4 Enter the following three values in the Popups (one per line) field:
2
5
User-defined
5 Enter the following code in the Dialog callback field:
26-57
26
Working with Block Masks
% Get the mask parameter values. This is a cell
%
array of strings.
maskStr = get_param(gcb,'MaskValues');
% The pop-up menu is the first mask parameter.
%
Check the value selected in the pop-up
if strcmp(maskStr{1}(1),'U'),
% Set the visibility of both parameters on when
%
User-defined is selected in the pop-up.
set_param(gcb,'MaskVisibilities',{'on';'on'}),
else
% Turn off the visibility of the Value field
%
when User-defined is not selected.
set_param(gcb,'MaskVisibilities',{'on';'off'}),
% Set the string in the Values field equal to the
% string selected in the Gain pop-up menu.
maskStr{2}=maskStr{1};
set_param(gcb,'MaskValues',maskStr);
end
6 Add a second parameter.
• Enter Value: in the Prompt field
• Enter val in the Variable field
• Uncheck Show parameter in the Dialog options for selected
parameter group. This step turns the visibility of this parameter off,
by default.
7 Select Apply on the Mask Editor. The Mask Editor now looks like this
when the gain parameter is selected and comments are removed from the
mask callback code:
26-58
Create Dynamic Mask Dialog Boxes
Double-clicking on the new masked subsystem opens the Mask Parameters
dialog box. Selecting 2 or 5 for the Gain parameter hides the Value
parameter, while selecting User-defined makes the Value parameter
visible. Note that any blocks in the masked subsystem that need the gain
value should reference the mask variable val as the set_param in the else
code assures that val contains the current value of the gain when 2 or 5 is
selected in the popup.
Setting Nested Masked Block Parameters
Avoid using set_param commands to set parameters of blocks residing in
masked subsystems that reside in the masked subsystem being initialized.
Trying to set parameters of blocks in lower-level masked subsystems can
trigger unresolvable symbol errors if lower-level masked subsystems reference
symbols defined by higher-level masked subsystems. Suppose, for example,
a masked subsystem A contains masked subsystem B, which contains Gain
26-59
26
Working with Block Masks
block C, whose Gain parameter references a variable defined by B. Suppose
also that subsystem A’s initialization code contains the command
set_param([gcb '/B/C'], 'SampleTime', '-1');
Simulating or updating a model containing A causes an unresolvable symbol
error.
26-60
Create Dynamic Masked Subsystems
Create Dynamic Masked Subsystems
In this section...
“Allow library block to modify its contents” on page 26-61
“Create Self-Modifying Masks for Library Blocks” on page 26-61
“Evaluate Blocks Under Self-Modifying Mask” on page 26-65
Allow library block to modify its contents
This check box is enabled only if the masked subsystem resides in a library.
Checking this option allows the block initialization code to modify the
contents of the masked subsystem (that is, it lets the code add or delete blocks
and set the parameters of those blocks). Otherwise, an error is generated
when a masked library block tries to modify its contents in any way. To set
this option at the MATLAB prompt, select the self-modifying block and enter
the following command.
set_param(gcb, 'MaskSelfModifiable', 'on');
Then save the block.
Create Self-Modifying Masks for Library Blocks
You can create masked library blocks that can modify their structural
contents. These self-modifying masks allow you to:
• Modify the contents of a masked subsystem based on parameters in the
Mask Parameters dialog box or when the subsystem is initially dragged
from the library into a new model.
• Vary the number of ports on a multiport S-Function block that resides
in a library.
Creating Self-Modifying Masks Using the Mask Editor
To create a self-modifying mask using the Mask Editor:
1 Unlock the library (see “Modify and Lock Libraries” on page 28-21).
26-61
26
Working with Block Masks
2 Right-click the block in the library.
3 Select Mask > Edit Mask. The Mask Editor opens.
4 In the Mask Editor’s Initialization pane, select the Allow library block
to modify its contents option.
5 Enter the code that modifies the masked subsystem in the mask’s
Initialization pane.
Note Do not enter code that structurally modifies the masked subsystem
in a dialog parameter callback (see “Mask Code Placement” on page 26-7).
Doing so triggers an error when a user edits the parameter.
6 Click Apply to apply the change or OK to apply the change and dismiss
the Mask Editor.
7 Lock the library.
Creating Self-Modifying Masks from the Command Line
To create a self-modifying mask from the command line:
1 Unlock the library using the following command:
set_param(gcs,'Lock','off')
2 Specify that the block is self-modifying by using the following command:
set_param(block_name,'MaskSelfModifiable','on')
where block_name is the full path to the block in the library.
Self-Modifying Mask Example
The library selfModifying_example contains a masked subsystem that
modifies its number of input ports based on a selection made in the
subsystem’s Mask Parameters dialog box.
26-62
Create Dynamic Masked Subsystems
Right-click the subsystem then select Mask > Edit Mask. The Mask Editor
opens. The Mask Editor Parameters pane defines one mask parameter
variable numIn that stores the value for the Number of inports option. This
Mask Parameters dialog box callback adds or removes Input ports inside the
masked subsystem based on the selection made in the Number of inports
list.
26-63
26
Working with Block Masks
To allow the dialog box callback to function properly, the Allow library
block to modify its contents option on the Mask Editor Initialization
pane is selected. If this option were not selected, copies of the library block
could not modify their structural contents and changing the selection in the
Number of inports list would produce an error.
26-64
Create Dynamic Masked Subsystems
Evaluate Blocks Under Self-Modifying Mask
This example shows how to force Simulink to evaluate blocks inside
self-modifying masks.
Simulink evaluates elements of models containing masks in the following
order:
1 Mask Parameters dialog box
2 Mask initialization code
3 Blocks or masked subsystems under the mask
Consider the following case:
A block named myBlock inside subsystem mySubsys masked by a
self-modifying mask depends on mask parameter myParam to update itself.
myParam is exposed to the user through the Mask Parameters dialog
box. mySubsys is updated through MATLAB code written in the Mask
Initialization pane.
In this model, the sequence of updates is as follows:
1 A user makes modifies myParam through the Mask Parameters dialog box.
2 The mask initialization code receives this change and modifies mySubsys
under the mask.
3 myBlock, which lies under mySubsys, modifies itself based on the change
to myParam.
In this sequence, myBlock, which lies under mySubsys, will not be evaluated
when the mask initialization code executes. Instead, only the masked
subsystem mySubsys is evaluated at that time and gets updated. Meanwhile,
myBlock, which needs to change, remains unmodified.
You can force Simulink to evaluate such blocks earlier by using the
Simulink.Mask.eval method in the masked subsystem’s initialization code:
26-65
26
Working with Block Masks
Simulink.Block.eval(mySubsys/myBlock);
26-66
How Do I Debug Masks That Use MATLAB® Code?
How Do I Debug Masks That Use MATLAB Code?
In this section...
“Code Written in Mask Editor” on page 26-67
“Code Written Using MATLAB Editor/Debugger” on page 26-67
Code Written in Mask Editor
Debug initialization commands and parameter callbacks entered directly into
the Mask Editor in one of the following ways:
• Remove the terminating semicolon from a command to echo its results to
the MATLAB Command Window.
• Place a keyboard command in the code to stop execution and give control
to the keyboard.
Code Written Using MATLAB Editor/Debugger
Note You cannot debug icon drawing commands using the MATLAB
Editor/Debugger. Use the syntax examples provided in the Mask Editor’s
Icons & Ports pane to help solve errors in the icon drawing commands.
Debug initialization commands and parameter callbacks written in files using
the MATLAB Editor/Debugger in the same way that you would with any
other MATLAB program file.
When debugging initialization commands, you can view the contents of the
mask workspace. However, when debugging parameter callbacks, you can
only access the base workspace of the block. If you need the value of a mask
parameter, use get_param.
26-67
26
26-68
Working with Block Masks
27
Creating Custom Blocks
• “When to Create Custom Blocks” on page 27-2
• “Types of Custom Blocks” on page 27-3
• “Comparison of Custom Block Functionality” on page 27-7
• “Expanding Custom Block Functionality” on page 27-17
• “Create a Custom Block” on page 27-18
• “Custom Block Examples” on page 27-43
27
Creating Custom Blocks
When to Create Custom Blocks
Custom blocks expand the modeling functionality provided with the Simulink
product. Use a custom block to:
• Model behaviors that are not provided with a Simulink built-in solution.
• Build more advanced models.
• Encapsulate model components into a library block that you can copy into
multiple models.
• Provide custom graphical user interfaces or analysis routines.
27-2
Types of Custom Blocks
Types of Custom Blocks
In this section...
“MATLAB Function Blocks” on page 27-3
“Subsystem Blocks” on page 27-4
“S-Function Blocks” on page 27-4
MATLAB Function Blocks
A MATLAB Function block allows you to use the MATLAB language to define
custom functionality. These blocks are a good starting point for creating a
custom block if:
• You have an existing MATLAB function that models the custom
functionality.
• You find it easier to model custom functionality using a MATLAB function
than using a Simulink block diagram.
• The custom functionality does not include continuous or discrete dynamic
states.
You can create a custom block from a MATLAB function using one of the
following types of MATLAB function blocks.
• The Fcn block allows you to use a MATLAB expression to define a
single-input, single-output (SISO) block.
• The Interpreted MATLAB Function block allows you to use a MATLAB
function to define a SISO block.
• The MATLAB Function block allows you to define a custom block with
multiple inputs and outputs that you can deploy to an embedded processor.
Each of these blocks has advantages in particular modeling applications. For
example, you can generate code from models containing MATLAB Function
blocks while you cannot generate code for models containing an Fcn block.
27-3
27
Creating Custom Blocks
Subsystem Blocks
Subsystem blocks allow you to build a Simulink diagram to define custom
functionality. These blocks serve as a good starting point for creating a
custom block if:
• You have an existing Simulink diagram that models custom functionality.
• You find it easier to model custom functionality using a graphical
representation rather than using hand-written code.
• The custom functionality is a function of continuous or discrete system
states.
• You can model the custom functionality using existing Simulink blocks.
Once you have a Simulink subsystem that models the required behavior, you
can convert it into a custom block by:
1 Masking the block to hide the block contents and provide a custom block
dialog.
2 Placing the block in a library to prohibit modifications and allow for easily
updating copies of the block.
For more information, see “Libraries” and “Masking”.
S-Function Blocks
S-function blocks allow you to write MATLAB, C, or C++ code to define
custom functionality. These blocks serve as a good starting point for creating
a custom block if:
• You have existing MATLAB, C, or C++ code that models custom
functionality.
• You need to model continuous or discrete dynamic states or other system
behaviors that require access to the S-function API.
• You cannot model the custom functionality using existing Simulink blocks.
You can create a custom block from an S-function using one of the following
types of S-function blocks.
27-4
Types of Custom Blocks
• The Level-2 MATLAB S-Function block allows you to write your S-function
using the MATLAB language. (See“Write Level-2 MATLAB S-Functions”).
You can debug a MATLAB S-function during a simulation using the
MATLAB debugger.
• The S-Function block allows you to write your S-function in C or C++, or to
incorporate existing code into your model using a C MEX wrapper. (See
“C/C++ S-Functions”.)
• The S-Function Builder block assists you in creating a new C MEX
S-function or a wrapper function to incorporate legacy C or C++ code. (See
“C/C++ S-Functions”.)
• The Legacy Code Tool transforms existing C or C++ functions into C MEX
S-functions. (See “Integrate C Functions Using Legacy Code Tool”.)
The S-function target in the Simulink Coder product automatically generates
a C MEX S-function from a graphical subsystem. If you want to build your
custom block in a Simulink subsystem, but implement the final version of
the block in an S-function, you can use the S-function target to convert
the subsystem to an S-function. See “Generated S-Function Block” in
the Simulink Coder User’s Guide for details and limitations on using the
S-function target.
Comparing MATLAB S-Functions to MATLAB Functions for Code
Generation
MATLAB S-functions and MATLAB functions for code generation have some
fundamental differences.
• The Simulink Coder product can generate code for both MATLAB
S-functions and MATLAB functions for code generation. However,
MATLAB S-functions require a Target Language Compiler (TLC) file for
code generation. MATLAB functions for code generation do not require
a TLC-file.
• MATLAB S-functions can use any MATLAB function while MATLAB
functions for code generation are a subset of the MATLAB language. For a
list of supported functions for code generation, see “Functions Supported
for Code Generation — Alphabetical List” on page 31-2.
• MATLAB S-functions can model discrete and continuous state dynamics
while MATLAB functions for code generation cannot model state dynamics.
27-5
27
Creating Custom Blocks
Using S-Function Blocks to Incorporate Legacy Code
Each S-function block allows you to incorporate legacy code into your model,
as follows.
• A MATLAB S-function accesses legacy code through its TLC-file. Therefore,
the legacy code is available only in the generated code, not during
simulation.
• A C MEX S-functions directly calls legacy C or C++ code.
• The S-Function Builder generates a wrapper function that calls the legacy
C or C++ code.
• The Legacy Code Tool generates a C MEX S-function to call the legacy C
or C++ code, which is optimized for embedded systems. See “Integrate C
Functions Using Legacy Code Tool” for more information.
See “Integration Options” in the Simulink Coder User’s Guide for more
information.
See “S-Functions Incorporate Legacy C Code” in the Simulink Developing
S-Functions for an example.
27-6
Comparison of Custom Block Functionality
Comparison of Custom Block Functionality
In this section...
“Custom Block Considerations” on page 27-7
“Modeling Requirements” on page 27-10
“Speed and Code Generation Requirements” on page 27-13
Custom Block Considerations
When creating a custom block, you may want to consider the following.
• Does the custom block need multiple input and output ports?
• Does the block need to model continuous or discrete state behavior?
• Will the block inputs and outputs have various data attributes, such as
data types or complexity?
• How important is the affect of the custom block on the speed of updating
the Simulink diagram or simulating the Simulink model?
• Do you need to generate code for a model containing the custom block?
The following two tables provide an overview of how each custom block
type addresses the previous questions. More detailed information for each
consideration follows these two tables.
Modeling Requirements
Custom Block
Type
Supports Multiple
Inputs and Outputs
Models State
Dynamics
Supports Various Data
Attributes
Subsystem
Yes, including bus
signals.
Yes.
Yes, including all data types,
numeric types, and dimensions
supported by the Simulink
software. Also supports
frame-based signals.
Fcn
No. Must have a single
vector input and scalar
output.
No.
Supports only real scalar
signals with a data type of
double or single.
27-7
27
Creating Custom Blocks
Modeling Requirements (Continued)
Custom Block
Type
Supports Multiple
Inputs and Outputs
Models State
Dynamics
Supports Various Data
Attributes
Interpreted
MATLAB Function
No. Must have a
single vector input and
output.
No.
Supports only n-D, real, or
complex signals with a data
type of double.
MATLAB Function
Yes, including bus
signals.
No.
Yes, including all data types,
numeric types, and dimensions
supported by the Simulink
software. Also supports
frame-based signals.
Level-2 MATLAB
S-function
Yes.
Yes, including
limited access
to other
S-function
APIs.
Yes, including all data types,
numeric types, and dimensions
supported by the Simulink
software. Also supports
frame-based signals.
C MEX S-function
Yes, including bus
signals if using the
Legacy Code Tool to
generate the S-function.
Yes, including
full access to
all S-function
APIs.
Yes, including all data types,
numeric types, and dimensions
supported by the Simulink
software. Also supports
frame-based signals.
Speed and Code Generation Requirements
27-8
Custom Block
Type
Speed of Updating
the Diagram
Simulation Overhead
Code Generation
Support
Subsystem
Proportional to the
complexity of the
subsystem. For
library blocks, can
be slower the first
Proportional to the
complexity of the
subsystem. Library
Natively supported.
Comparison of Custom Block Functionality
Speed and Code Generation Requirements (Continued)
Speed of Updating
the Diagram
Simulation Overhead
time the library is
loaded.
blocks introduce no
additional overhead.
Fcn
Very fast.
Minimal, but these
blocks also provide
limited functionality.
Natively supported.
Interpreted
MATLAB Function
Fast.
High and incurred
when calling out to the
MATLAB interpreter.
These calls add overhead
that should be avoided
if simulation speed is a
concern.
Not supported.
MATLAB Function
Can be slower if code
must be generated to
update the diagram.
Minimal if the MATLAB
interpreter is not called.
Simulation speed is
equivalent to C MEX
S-functions when the
MATLAB interpreter is
not called.
Natively supported,
with exceptions. See
“Code Generation” on
page 27-16 for more
information.
Level-2 MATLAB
S-function
Can be slower if the
S-function overrides
methods executed
when updating the
diagram.
Higher than for
Interpreted MATLAB
Function blocks
because the MATLAB
interpreter is called for
every S-function method
used. Very flexible, but
very costly.
MATLAB S-functions
initialized as a
Can be slower if the
S-function overrides
methods executed
Minimal, but
proportional to the
complexity of the
Might require a
TLC-file.
Custom Block
Type
C MEX S-function
Code Generation
Support
SimViewingDevice
do not generate code.
Otherwise, MATLAB
S-functions require
a TLC-file for code
generation.
27-9
27
Creating Custom Blocks
Speed and Code Generation Requirements (Continued)
Custom Block
Type
Speed of Updating
the Diagram
Simulation Overhead
when updating the
diagram.
algorithm and the
efficiency of the code.
Code Generation
Support
Modeling Requirements
Multiple Input and Output Ports
The following types of custom blocks support multiple input and output ports.
27-10
Custom
Block Type
Multiple Input and Output Port Support
Subsystem
Supports multiple input and output ports, including bus
signals. In addition, you can modify the number of input
and output ports based on user-defined parameters. See
“Self-Modifying Linked Subsystems” on page 28-7 for more
information.
Fcn,
Interpreted
MATLAB
Function
Supports only a single input and a single output port. You
must use a Mux block to combine the inputs and a Demux
block to separate the outputs if you need to pass multiple
signals into or out of these blocks.
MATLAB
Function
Supports multiple input and output ports, including bus
signals. See “How Structure Inputs and Outputs Interface
with Bus Signals” on page 29-81 for more information.
S-function
(MATLAB or
C MEX)
Supports multiple input and output ports. In addition, you
can modify the number of input and output ports based on
user-defined parameters. S-functions generated using the
Legacy Code Tool also accept Simulink bus signals. See
“Integrate C Functions Using Legacy Code Tool” for more
information.
Comparison of Custom Block Functionality
State Behavior and the S-Function API
Simulink blocks communicate with the Simulink engine through the
S-function API, a set of methods that fully specifies the behavior of blocks.
Each custom block type accesses a different sets of the S-function APIs, as
follows.
Custom
Block Type
S-Function API Support
Subsystem
Communicates directly with the engine. You can model
state behaviors using appropriate blocks from the
Continuous and Discrete Simulink block libraries.
Fcn,
Interpreted
MATLAB
Function,
MATLAB
Function
All create an mdlOutputs method to calculate the value
of the outputs given the value of the inputs. You cannot
access any other S-function API methods using one of these
blocks and, therefore, cannot model state behavior.
MATLAB
S-function
Accesses a larger subset of the S-function APIs, including
the methods needed to model continuous and discrete
states. For a list of supported methods, see “Level-2
MATLAB S-Function Callback Methods” in “Writing
S-Functions”.
C MEX
S-function
Accesses the complete set of S-function APIs.
Data Attribute Support
All custom block types support real scalar inputs and outputs with a data
type of double.
27-11
27
27-12
Creating Custom Blocks
Custom
Block Type
Data Attribute Support
Subsystem
Supports any data type supported by the Simulink
software, including fixed-point types. Also supports
complex, 2-D, n-D, and frame-based signals.
Fcn
Supports only double or single data types. In addition, the
input and output cannot be complex and the output must
be a scalar signal. Does not support frame-based signals.
Interpreted
MATLAB
Function
Supports 2-D, n-D, and complex signals, but the signal
must have a data type of double. Does not support
frame-based signals.
MATLAB
Function
Supports any data type supported by the Simulink
software, including fixed-point types. Also supports
complex, 2-D, n-D, and frame-based signals.
S-function
(MATLAB or
C MEX)
Supports any data type supported by the Simulink
software, including fixed-point types. Also supports
complex, 2-D, n-D, and frame-based signals.
Comparison of Custom Block Functionality
Speed and Code Generation Requirements
Updating the Simulink Diagram
The Simulink software updates the diagram before every simulation and
whenever requested by the user. Every block introduces some overhead into
the “update diagram” process.
Custom
Block Type
Speed of Updating the Diagram
Subsystem
The speed is proportional to the complexity of the
algorithm implemented in the subsystem. If the subsystem
is contained in a library, some cost is incurred when the
Simulink software loads any unloaded libraries the first
time the diagram is updated or readied for simulation.
If all referenced library blocks remain unchanged, the
Simulink software does not subsequently reload the library
and compiling the model becomes faster than if the model
did not use libraries.
Fcn,
Interpreted
MATLAB
Function
Does not incur greater update cost than other Simulink
blocks.
MATLAB
Function
Performs simulation through code generation, so these
blocks might take a significant amount of time when first
updated. However, because code generation is incremental,
if the block and the signals connected to it have not
changed, Simulink does not repeatedly update the block.
S-function
(MATLAB or
C MEX)
Incurs greater costs than other Simulink blocks only if it
overrides methods executed when updating the diagram.
If these methods become complex, they can contribute
significantly to the time it takes to update the diagram.
For a list of methods executed when updating the diagram,
see the process view in “Simulink Engine Interaction with
C S-Functions”. When updating the diagram, the Simulink
software invokes all relevant methods in the model
initialization phase up to, but not including, mdlStart.
27-13
27
Creating Custom Blocks
Simulation Overhead
For most applications, any of the custom block types provide acceptable
simulation performance. Use the Simulink profiler to obtain an indication
of the actual performance. See “Capture Performance Data” on page 22-31
for more information.
You can break simulation performance into two categories. The interface
cost is the time it takes to move data from the Simulink engine into the
block. The algorithm cost is the time needed to perform the algorithm that
the block implements.
Custom
Block Type
Simulation Overhead
Subsystem
If included in a library, introduces no interface or algorithm
costs beyond what would normally be incurred if the block
existed as a regular subsystem in the model.
Fcn
Has the least simulation overhead. The block is tightly
integrated with the Simulink engine and implements
a rudimentary expression language that is efficiently
interpreted.
Interpreted
MATLAB
Function
Has a higher interface cost than most blocks and the same
algorithm cost as a MATLAB function.
When block data (such as inputs and outputs) is accessed
or returned from an Interpreted MATLAB Function block,
the Simulink engine packages this data into MATLAB
arrays. This packaging takes additional time and causes a
temporary increase in memory during communication. If
you pass large amounts of data across this interface, such
as, frames or arrays, this overhead can be substantial.
Once the data has been converted, the MATLAB
interpreter executes the algorithm. As a result, the
algorithm cost is the same as for MATLAB function.
Efficient code can be competitive with C code if MATLAB is
able to optimize it, or if the code uses the highly optimized
MATLAB library functions.
27-14
Comparison of Custom Block Functionality
Custom
Block Type
Simulation Overhead
MATLAB
Function
Performs simulation through code generation and so incurs
the same interface cost as standard blocks.
The algorithm cost of this block is harder to analyze
because of the block’s implementation. On average, a
function for this block and a MATLAB function run at
about the same speed. To further reduce the algorithm
cost, you can disable debugging for all the MATLAB
Function blocks in your model.
If the MATLAB Function block uses simulation-only
capabilities to call out to the MATLAB interpreter,
it incurs all the costs that a MATLAB S-function or
Interpreted MATLAB Function block incur. Calling out
to the MATLAB interpreter from a MATLAB Function
block produces a warning to prevent you from doing so
unintentionally.
MATLAB
S-function
Incurs the same algorithm costs as the Interpreted
MATLAB Function block, but with a slightly higher
interface cost. Because MATLAB S-functions can handle
multiple inputs and outputs, the packaging is more
complicated than for the Interpreted MATLAB Function
block. In addition, the Simulink engine calls the MATLAB
interpreter for each block method you implement whereas
for the Interpreted MATLAB Function block, it calls the
MATLAB interpreter only for the mdlOutputs method.
C MEX
S-function
Simulates via the compiled code and so incurs the same
interface cost as standard blocks. The algorithm cost
depends on the complexity of the S-function.
27-15
27
Creating Custom Blocks
Code Generation
Not all custom block types support code generation with Simulink Coder.
27-16
Custom
Block Type
Code Generation Support
Subsystem
Supports code generation.
Fcn
Supports code generation.
Interpreted
MATLAB
Function
Does not support code generation.
MATLAB
Function
Supports code generation. However, if your MATLAB
Function block calls out to the MATLAB interpreter, it
will build with the Simulink Coder product only if the
calls to the MATLAB interpreter do not affect the block
outputs. Under this condition, the Simulink Coder product
omits these calls from the generated C code. This feature
allows you to leave visualization code in place, even when
generating embedded code.
MATLAB
S-function
Generates code only if you implement the algorithm using a
Target Language Compiler (TLC) function. In accelerated
and external mode simulations, you can choose to execute
the S-function in interpretive mode by calling back to the
MATLAB interpreter without implementing the algorithm
in TLC. If the MATLAB S-function is a SimViewingDevice,
the Simulink Coder product automatically omits the block
during code generation.
C MEX
S-function
Supports code generation. For noninlined S-functions, the
Simulink Coder product uses the C MEX function during
code generation. However, you must write a TLC-file for
the S-function if you need to either inline the S-function
or create a wrapper for hand-written code. See “Insert
S-Function Code” in the Simulink Coder User’s Guide for
more information.
Expanding Custom Block Functionality
Expanding Custom Block Functionality
You can expand the functionality of any custom block using callbacks and
Handle Graphics.
Block callbacks perform user-defined actions at specific points in the
simulation. For example, the callback can load data into the MATLAB
workspace before the simulation or generate a graph of simulation data at the
end of the simulation. You can assign block callbacks to any of the custom
block types. For a list of available callbacks and more information on how to
use them, see “Create Block Callback Functions” on page 4-58.
GUIDE, the MATLAB graphical user interface development environment,
provides tools for easily creating custom user interfaces. See “GUI Building”
for more information on using GUIDE.
27-17
27
Creating Custom Blocks
Create a Custom Block
In this section...
“How to Design a Custom Block” on page 27-18
“Defining Custom Block Behavior” on page 27-20
“Deciding on a Custom Block Type” on page 27-21
“Placing Custom Blocks in a Library” on page 27-27
“Adding a Graphical User Interface to a Custom Block” on page 27-28
“Adding Block Functionality Using Block Callbacks” on page 27-37
How to Design a Custom Block
In general, use the following process to design a custom block:
1 “Defining Custom Block Behavior” on page 27-20
2 “Deciding on a Custom Block Type” on page 27-21
3 “Placing Custom Blocks in a Library” on page 27-27
4 “Adding a Graphical User Interface to a Custom Block” on page 27-28
Suppose you want to create a customized saturation block that limits the
upper and lower bounds of a signal based on either a block parameter or the
value of an input signal. In a second version of the block, you want the option
to plot the saturation limits after the simulation is finished. The following
tutorial steps you through designing these blocks. The library customsat_lib
contains the two versions of the customized saturation block.
27-18
Create a Custom Block
The example model sldemo_customsat uses the basic version of the block.
27-19
27
Creating Custom Blocks
Defining Custom Block Behavior
Begin by defining the features and limitations of your custom block. In this
example, the block supports the following features:
• Turning on and off the upper or lower saturation limit.
• Setting the upper and/or lower limits via a block parameters.
27-20
Create a Custom Block
• Setting the upper and/or lower limits using an input signal.
It also has the following restrictions:
• The input signal under saturation must be a scalar.
• The input signal and saturation limits must all have a data type of double.
• Code generation is not required.
Deciding on a Custom Block Type
Based on the custom block features, the implementation needs to support
the following:
• Multiple input ports
• A relatively simple algorithm
• No continuous or discrete system states
Therefore, this tutorial implements the custom block using a Level-2 MATLAB
S-function. MATLAB S-functions support multiple inputs and, because
the algorithm is simple, do not have significant overhead when updating
the diagram or simulating the model. See “Comparison of Custom Block
Functionality” on page 27-7 for a description of the different functionality
provided by MATLAB S-functions as compared to other types of custom blocks.
Parameterizing the MATLAB S-Function
Begin by defining the S-function parameters. This example requires four
parameters:
• The first parameter indicates how the upper saturation limit is set. The
limit can be off, set via a block parameter, or set via an input signal.
• The second parameter is the value of the upper saturation limit. This value
is used only if the upper saturation limit is set via a block parameter. In the
event this parameter is used, you should be able to change the parameter
value during the simulation, i.e., the parameter is tunable.
• The third parameter indicates how the lower saturation limit is set. The
limit can be off, set via a block parameter, or set via an input signal.
27-21
27
Creating Custom Blocks
• The fourth parameter is the value of the lower saturation limit. This value
is used only if the lower saturation limit is set via a block parameter. As
with the upper saturation limit, this parameter is tunable when in use.
The first and third S-function parameters represent modes that must be
translated into values the S-function can recognize. Therefore, define the
following values for the upper and lower saturation limit modes:
• 1 indicates that the saturation limit is off.
• 2 indicates that the saturation limit is set via a block parameter.
• 3 indicates that the saturation limit is set via an input signal.
Writing the MATLAB S-Function
After you define the S-function parameters and functionality, write the
S-function. The template msfuntmpl.m provides a starting point for writing a
Level-2 MATLAB S-function. You can find a completed version of the custom
saturation block in the file custom_sat.m. Save this file to your working
folder before continuing with this tutorial.
This S-function modifies the S-function template as follows:
• The setup function initializes the number of input ports based on the
values entered for the upper and lower saturation limit modes. If the limits
are set via input signals, the method adds input ports to the block. The
setup method then indicates there are four S-function parameters and sets
the parameter tunability. Finally, the method registers the S-function
methods used during simulation.
function setup(block)
% The Simulink engine passes an instance of the Simulink.MSFcnRunTimeBlock
% class to the setup method in the input argument "block". This is known as
% the S-function block's run-time object.
% Register original number of input ports based on the S-function
% parameter values
try % Wrap in a try/catch, in case no S-function parameters are entered
27-22
Create a Custom Block
lowMode
= block.DialogPrm(1).Data;
upMode
= block.DialogPrm(3).Data;
numInPorts = 1 + isequal(lowMode,3) + isequal(upMode,3);
catch
numInPorts=1;
end % try/catch
block.NumInputPorts = numInPorts;
block.NumOutputPorts = 1;
% Setup port properties to be inherited or dynamic
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
% Override input port properties
block.InputPort(1).DatatypeID
= 0;
block.InputPort(1).Complexity
= 'Real';
% double
% Override output port properties
block.OutputPort(1).DatatypeID
= 0; % double
block.OutputPort(1).Complexity
= 'Real';
% Register parameters. In order:
% -- If the upper bound is off (1) or on and set via a block parameter (2)
%
or input signal (3)
% -- The upper limit value. Should be empty if the upper limit is off or
%
set via an input signal
% -- If the lower bound is off (1) or on and set via a block parameter (2)
%
or input signal (3)
% -- The lower limit value. Should be empty if the lower limit is off or
%
set via an input signal
block.NumDialogPrms
= 4;
block.DialogPrmsTunable = {'Nontunable','Tunable','Nontunable', ...
'Tunable'};
% Register continuous sample times [0 offset]
block.SampleTimes = [0 0];
%% ----------------------------------------------------------------%% Options
%% -----------------------------------------------------------------
27-23
27
Creating Custom Blocks
% Specify if Accelerator should use TLC or call back into
% MATLAB script
block.SetAccelRunOnTLC(false);
%% ----------------------------------------------------------------%% Register methods called during update diagram/compilation
%% ----------------------------------------------------------------block.RegBlockMethod('CheckParameters',
@CheckPrms);
block.RegBlockMethod('ProcessParameters',
@ProcessPrms);
block.RegBlockMethod('PostPropagationSetup', @DoPostPropSetup);
block.RegBlockMethod('Outputs',
@Outputs);
block.RegBlockMethod('Terminate',
@Terminate);
%end setup function
• The CheckParameters method verifies the values entered into the Level-2
MATLAB S-Function block.
function CheckPrms(block)
lowMode = block.DialogPrm(1).Data;
lowVal
= block.DialogPrm(2).Data;
upMode
= block.DialogPrm(3).Data;
upVal
= block.DialogPrm(4).Data;
% The first and third dialog parameters must have values of 1-3
if ~any(upMode == [1 2 3]);
error('The first dialog parameter must be a value of 1, 2, or 3');
end
if ~any(lowMode == [1 2 3]);
error('The first dialog parameter must be a value of 1, 2, or 3');
end
% If the upper or lower bound is specified via a dialog, make sure there
% is a specified bound. Also, check that the value is of type double
if isequal(upMode,2),
if isempty(upVal),
error('Enter a value for the upper saturation limit.');
end
27-24
Create a Custom Block
if ~strcmp(class(upVal), 'double')
error('The upper saturation limit must be of type double.');
end
end
if isequal(lowMode,2),
if isempty(lowVal),
error('Enter a value for the lower saturation limit.');
end
if ~strcmp(class(lowVal), 'double')
error('The lower saturation limit must be of type double.');
end
end
% If a lower and upper limit are specified, make sure the specified
% limits are compatible.
if isequal(upMode,2) && isequal(lowMode,2),
if lowVal >= upVal,
error('The lower bound must be less than the upper bound.');
end
end
%end CheckPrms function
• The ProcessParameters and PostPropagationSetup methods handle
the S-function parameter tuning.
function ProcessPrms(block)
%% Update run time parameters
block.AutoUpdateRuntimePrms;
%end ProcessPrms function
function DoPostPropSetup(block)
%% Register all tunable parameters as runtime parameters.
block.AutoRegRuntimePrms;
27-25
27
Creating Custom Blocks
%end DoPostPropSetup function
• The Outputs method calculates the block’s output based on the S-function
parameter settings and any input signals.
function Outputs(block)
lowMode
= block.DialogPrm(1).Data;
upMode
= block.DialogPrm(3).Data;
sigVal
= block.InputPort(1).Data;
lowPortNum = 2; % Initialize potential input number for lower saturation limit
% Check upper saturation limit
if isequal(upMode,2), % Set via a block parameter
upVal = block.RuntimePrm(2).Data;
elseif isequal(upMode,3), % Set via an input port
upVal = block.InputPort(2).Data;
lowPortNum = 3; % Move lower boundary down one port number
else
upVal = inf;
end
% Check lower saturation limit
if isequal(lowMode,2), % Set via a block parameter
lowVal = block.RuntimePrm(1).Data;
elseif isequal(lowMode,3), % Set via an input port
lowVal = block.InputPort(lowPortNum).Data;
else
lowVal = -inf;
end
% Assign new value to signal
if sigVal > upVal,
sigVal = upVal;
elseif sigVal < lowVal,
sigVal=lowVal;
end
block.OutputPort(1).Data = sigVal;
27-26
Create a Custom Block
%end Outputs function
Placing Custom Blocks in a Library
Libraries allow you to share your custom blocks with other users, easily
update the functionality of copies of the custom block, and collect blocks for
a particular project into a single location. This example places the custom
saturation block into a library as follows:
1 In the Simulink Library Browser window, select File > New > Library. A
new library window opens.
2 From the User-Defined Functions library, drag a new Level-2 MATLAB
S-Function block into your new library. Save your library with the filename
saturation_lib.
3 Double-click the block to open its Function Block Parameters dialog box.
4 In the S-function name box, enter the name of the S-function. For
example, enter custom_sat. In the Parameters box enter the following
default values 2,-1,2,1.
27-27
27
Creating Custom Blocks
5 Click OK. The parameters changes you entered are saved and the dialog
box closes.
At this point, you have created a custom saturation block that you can share
with other users. You can make the block easier to use by adding a customized
graphical user interface.
Adding a Graphical User Interface to a Custom Block
You can create a simple block dialog for the custom saturation block using
the provided masking capabilities. Masking the block also allows you to
add port labels to indicate which ports corresponds to the input signal and
the saturation limits.
To mask the block:
1 Open the custom library you created, saturation_lib. Right-click
the custom saturation block, and from the context menu, select
Diagram > Mask→Create Mask . The Mask Editor opens.
27-28
Create a Custom Block
2 On the Icon & Ports pane and in the Icons Drawing commands box,
enter the following.
port_label('input',1,'uSig')
This command labels the default port as the input signal under saturation.
3 On the Parameters pane, add four parameters corresponding to the four
S-function parameters. For each new parameter, click the Add parameter
button, and set up each of the parameter properties as follows.
Prompt
Type
Tunable Popups
Action for Dialog
Callback
upMode
Upper
boundary:
popup
No
No limit | Enter limit as
parameter | Limit using
input signal
'upperbound_callback'
Upper
limit:
edit
Yes
N/A
'upperparam_callback'
Variable
upVal
27-29
27
Creating Custom Blocks
Prompt
Type
Tunable Popups
Action for Dialog
Callback
lowMode
Lower
boundary:
popup
No
No limit | Enter limit as
parameter | Limit using
input signal
'lowerbound_callback'
Lower
limit:
edit
Yes
N/A
'lowerparam_callback'
Variable
lowVal
The dialog callback is invoked using the action string in the following
command:
customsat_callback(action,gcb)
The MATLAB script customsat_callback.m contains the mask parameter
callbacks. If you are stepping through this tutorial, open this file and save
it to your working folder. This MATLAB script described in detail later,
has two input arguments. The first input argument is a string indicating
which mask parameter invoked the callback. The second input argument is
the handle to the associated Level-2 MATLAB S-Function block.
The following figure shows the final Parameters pane in the Mask Editor.
27-30
Create a Custom Block
4 On the Mask Editor’s Initialization pane, select the check box Allow
library block to modify its contents. This setting allows the S-function
to change the number of ports on the block.
27-31
27
Creating Custom Blocks
5 On the Documentation pane:
• Enter Customized Saturation into the Mask type field.
• Enter the following into the Mask description field.
Limit the input signal to an upper and lower saturation value
set either through a block parameter or input signal.
6 On the Mask Editor dialog box, click OK to complete the mask parameters
dialog.
7 To map the S-function parameters to the mask parameters, right-click the
Level-2 MATLAB S-Function block and select Mask > Look Under Mask.
The Function Block Parameters dialog box opens.
8 Change the entry in the Parameters field as follows.
lowMode,lowVal,upMode,upVal
The following figure shows the new Block Parameters dialog.
27-32
Create a Custom Block
9 Click OK . Double-clicking the new version of the customized saturation
block opens the mask parameter dialog box shown in the following figure.
To create a more complicated graphical user interface, place a Handle
Graphics user interface on top of the masked block. The block’s OpenFcn
would invoke the Handle Graphics user interface, which uses calls to
set_param to modify the S-function block’s parameters based on settings
in the user interface.
Writing the Mask Callback
The function customsat_callback.m contains the mask callback code for the
custom saturation block mask parameter dialog box. This function invokes
local functions corresponding to each mask parameter through a call to feval.
The following local function controls the visibility of the upper saturation
limit’s field based on the selection for the upper saturation limit’s mode. The
callback begins by obtaining values for all mask parameters using a call to
27-33
27
Creating Custom Blocks
get_param with the property name MaskValues. If the callback needed the
value of only one mask parameter, it could call get_param with the specific
mask parameter name, for example, get_param(block,'upMode'). Because
this example needs two of the mask parameter values, it uses the MaskValues
property to reduce the calls to get_param.
The callback then obtains the visibilities of the mask parameters using a call
to get_param with the property name MaskVisbilities. This call returns
a cell array of strings indicating the visibility of each mask parameter. The
callback alters the values for the mask visibilities based on the selection for
the upper saturation limit’s mode and then updates the port label string.
The callback finally uses the set_param command to update the block’s
MaskDisplay property to label the block’s input ports.
function customsat_callback(action,block)
% CUSTOMSAT_CALLBACK contains callbacks for custom saturation block
%
Copyright 2003-2007 The MathWorks, Inc.
%% Use function handle to call appropriate callback
feval(action,block)
%% Upper bound callback
function upperbound_callback(block)
vals = get_param(block,'MaskValues');
vis = get_param(block,'MaskVisibilities');
portStr = {'port_label(''input'',1,''uSig'')'};
switch vals{1}
case 'No limit'
set_param(block,'MaskVisibilities',[vis(1);{'off'};vis(3:4)]);
case 'Enter limit as parameter'
set_param(block,'MaskVisibilities',[vis(1);{'on'};vis(3:4)]);
case 'Limit using input signal'
set_param(block,'MaskVisibilities',[vis(1);{'off'};vis(3:4)]);
portStr = [portStr;{'port_label(''input'',2,''up'')'}];
end
if strcmp(vals{3},'Limit using input signal'),
portStr = [portStr;{['port_label(''input'',',num2str(length(portStr)+1), ...
27-34
Create a Custom Block
',''low'')']}];
end
set_param(block,'MaskDisplay',char(portStr));
The final call to set_param invokes the setup function in the MATLAB
S-function custom_sat.m. Therefore, the setup function can be modified to
set the number of input ports based on the mask parameter values instead of
on the S-function parameter values. This change to the setup function keeps
the number of ports on the Level-2 MATLAB S-Function block consistent with
the values shown in the mask parameter dialog box.
The modified MATLAB S-function custom_sat_final.m contains the
following new setup function. If you are stepping through this tutorial, open
the file and save it to your working folder.
%% Function: setup ===================================================
function setup(block)
% Register original number of ports based on settings in Mask Dialog
ud = getPortVisibility(block);
numInPorts = 1 + isequal(ud(1),3) + isequal(ud(2),3);
block.NumInputPorts = numInPorts;
block.NumOutputPorts = 1;
% Setup port properties to be inherited or dynamic
block.SetPreCompInpPortInfoToDynamic;
block.SetPreCompOutPortInfoToDynamic;
% Override input port properties
block.InputPort(1).DatatypeID
= 0;
block.InputPort(1).Complexity
= 'Real';
% double
% Override output port properties
block.OutputPort(1).DatatypeID
= 0; % double
block.OutputPort(1).Complexity
= 'Real';
% Register parameters. In order:
% -- If the upper bound is off (1) or on and set via a block parameter (2)
%
or input signal (3)
27-35
27
Creating Custom Blocks
% -- The upper limit value. Should be empty if the upper limit is off or
%
set via an input signal
% -- If the lower bound is off (1) or on and set via a block parameter (2)
%
or input signal (3)
% -- The lower limit value. Should be empty if the lower limit is off or
%
set via an input signal
block.NumDialogPrms
= 4;
block.DialogPrmsTunable = {'Nontunable','Tunable','Nontunable','Tunable'};
% Register continuous sample times [0 offset]
block.SampleTimes = [0 0];
%% ----------------------------------------------------------------%% Options
%% ----------------------------------------------------------------% Specify if Accelerator should use TLC or call back into
% MATLAB script
block.SetAccelRunOnTLC(false);
%% ----------------------------------------------------------------%% Register methods called during update diagram/compilation
%% ----------------------------------------------------------------block.RegBlockMethod('CheckParameters',
@CheckPrms);
block.RegBlockMethod('ProcessParameters',
@ProcessPrms);
block.RegBlockMethod('PostPropagationSetup', @DoPostPropSetup);
block.RegBlockMethod('Outputs',
@Outputs);
block.RegBlockMethod('Terminate',
@Terminate);
%endfunction
The getPortVisibility local function in custom_sat_final.m uses the
saturation limit modes to construct a flag that is passed back to the setup
function. The setup function uses this flag to determine the necessary
number of input ports.
%% Function: Get Port Visibilities =======================================
function ud = getPortVisibility(block)
ud = [0 0];
27-36
Create a Custom Block
vals = get_param(block.BlockHandle,'MaskValues');
switch vals{1}
case 'No limit'
ud(2) = 1;
case 'Enter limit as parameter'
ud(2) = 2;
case 'Limit using input signal'
ud(2) = 3;
end
switch vals{3}
case 'No limit'
ud(1) = 1;
case 'Enter limit as parameter'
ud(1) = 2;
case 'Limit using input signal'
ud(1) = 3;
end
Adding Block Functionality Using Block Callbacks
The User-Defined Saturation with Plotting block in customsat_lib uses block
callbacks to add functionality to the original custom saturation block. This
block provides an option to plot the saturation limits when the simulation
ends. The following steps show how to modify the original custom saturation
block to create this new block.
1 Add a check box to the mask parameter dialog box to toggle the plotting
option on and off.
a Right-click the Level-2 MATLAB S-Function block in saturation_lib
and select Edit Mask.
b On the Mask Editor Parameters pane, add a fifth mask parameter
with the following properties.
Prompt VariableType Tunable
Popups
Action for Dialog
Callback
plotcheck
checkbox
No
Plot
saturation
limits
customsat_callback('plotsaturation
NA
27-37
27
Creating Custom Blocks
c Click OK.
2 Write a callback for the new check box. The callback initializes a
structure to store the saturation limit values during simulation in the
Level-2 MATLAB S-Function block UserData. The MATLAB script
customsat_plotcallback.m contains this new callback, as well as modified
versions of the previous callbacks to handle the new mask parameter. If
you are following through this example, open customsat_plotcallback.m
and copy its local functions over the previous local functions in
customsat_callback.m.
%% Plotting checkbox callback
function plotsaturation(block)
% Reinitialize the block's userdata
vals = get_param(block,'MaskValues');
27-38
Create a Custom Block
ud = struct('time',[],'upBound',[],'upVal',[],'lowBound',[],'lowVal',[]);
if strcmp(vals{1},'No limit'),
ud.upBound = 'off';
else
ud.upBound = 'on';
end
if strcmp(vals{3},'No limit'),
ud.lowBound = 'off';
else
ud.lowBound = 'on';
end
set_param(gcb,'UserData',ud);
3 Update the MATLAB S-function Outputs method to store the
saturation limits, if applicable, as done in the new MATLAB S-function
custom_sat_plot.m. If you are following through this example, copy the
Outputs method in custom_sat_plot.m over the original Outputs method
in custom_sat_final.m
%% Function: Outputs ===================================================
function Outputs(block)
lowMode
= block.DialogPrm(1).Data;
upMode
= block.DialogPrm(3).Data;
sigVal
= block.InputPort(1).Data;
vals = get_param(block.BlockHandle,'MaskValues');
plotFlag = vals{5};
lowPortNum = 2;
% Check upper saturation limit
if isequal(upMode,2)
upVal = block.RuntimePrm(2).Data;
elseif isequal(upMode,3)
upVal = block.InputPort(2).Data;
lowPortNum = 3; % Move lower boundary down one port number
else
upVal = inf;
27-39
27
Creating Custom Blocks
end
% Check lower saturation limit
if isequal(lowMode,2),
lowVal = block.RuntimePrm(1).Data;
elseif isequal(lowMode,3)
lowVal = block.InputPort(lowPortNum).Data;
else
lowVal = -inf;
end
% Use userdata to store limits, if plotFlag is on
if strcmp(plotFlag,'on');
ud = get_param(block.BlockHandle,'UserData');
ud.lowVal = [ud.lowVal;lowVal];
ud.upVal = [ud.upVal;upVal];
ud.time = [ud.time;block.CurrentTime];
set_param(block.BlockHandle,'UserData',ud)
end
% Assign new value to signal
if sigVal > upVal,
sigVal = upVal;
elseif sigVal < lowVal,
sigVal=lowVal;
end
block.OutputPort(1).Data = sigVal;
%endfunction
4 Write the function plotsat.m to plot the saturation limits. This function
takes the handle to the Level-2 MATLAB S-Function block and uses this
handle to retrieve the block’s UserData. If you are following through this
tutorial, save plotsat.m to your working folder.
function plotSat(block)
% PLOTSAT contains the plotting routine for custom_sat_plot
%
27-40
This routine is called by the S-function block's StopFcn.
Create a Custom Block
ud = get_param(block,'UserData');
fig=[];
if ~isempty(ud.time)
if strcmp(ud.upBound,'on')
fig = figure;
plot(ud.time,ud.upVal,'r');
hold on
end
if strcmp(ud.lowBound,'on')
if isempty(fig),
fig = figure;
end
plot(ud.time,ud.lowVal,'b');
end
if ~isempty(fig)
title('Upper bound in red. Lower bound in blue.')
end
% Reinitialize userdata
ud.upVal=[];
ud.lowVal=[];
ud.time = [];
set_param(block,'UserData',ud);
end
5 Right-click the Level-2 MATLAB S-Function block and select Properties.
The Block Properties dialog box opens. On the Callbacks pane, modify
the StopFcn to call the plotting callback as shown in the following figure,
then click OK.
27-41
27
27-42
Creating Custom Blocks
Custom Block Examples
Custom Block Examples
In this section...
“Creating Custom Blocks from Masked Library Blocks” on page 27-43
“Creating Custom Blocks from MATLAB Functions” on page 27-43
“Creating Custom Blocks from S-Functions” on page 27-44
Creating Custom Blocks from Masked Library Blocks
The Additional Math and Discrete Simulink library is a group of custom
blocks created by extending the functionality of built-in Simulink blocks. The
Additional Discrete library contains a number of masked blocks that extend
the functionality of the standard Unit Delay block. See “Libraries” for more
general information on Simulink libraries.
Creating Custom Blocks from MATLAB Functions
The Simulink product provides a number of examples that show how to
incorporate MATLAB functions into a custom block.
• The Single Hydraulic Cylinder Simulation, sldemo_hydcyl, uses a Fcn
block to model the control valve flow. In addition, the Control Valve Flow
block is a library link to one of a number of custom blocks in the library
hydlib.
• The Radar Tracking Model, sldemo_radar, uses an Interpreted MATLAB
Function block to model an extended Kalman filter. The MATLAB
function aero_extkalman.m implements the Kalman filter found inside the
Radar Kalman Filter subsystem. In this example, the MATLAB function
requires three inputs, which are bundled together using a Mux block in
the Simulink model.
• The Spiral Galaxy Formation example, sldemo_eml_galaxy, uses several
MATLAB Function blocks to construct two galaxies and calculate the
effects of gravity as these two galaxies nearly collide. The example also
uses MATLAB Function blocks to plot the simulation results using a subset
of MATLAB functions not supported for code generation. However, because
these MATLAB Function blocks have no outputs, the Simulink Coder
product optimizes them away during code generation.
27-43
27
Creating Custom Blocks
Creating Custom Blocks from S-Functions
The Simulink model sfundemos contains various examples of MATLAB and C
MEX S-functions. For more information on writing MATLAB S-functions, see
“Write Level-2 MATLAB S-Functions”. For more information on writing C
MEX S-functions, see “C/C++ S-Functions”. For a list of available S-function
examples, see “S-Function Examples” in Writing S-Functions.
27-44
28
Working with Block
Libraries
• “About Block Libraries and Linked Blocks” on page 28-2
• “Create and Work with Linked Blocks” on page 28-4
• “Work with Library Links” on page 28-8
• “Create Block Libraries” on page 28-20
• “Add Libraries to the Library Browser” on page 28-32
28
Working with Block Libraries
About Block Libraries and Linked Blocks
Block Libraries
A block library is a collection of blocks that serve as prototypes for instances
of blocks in a Simulink model.
Simulink comes with two built-in block libraries: the Simulink block library
and the Simulink Coder block library. The latter is included with Simulink to
support sharing models that contain Simulink Coder blocks. Many additional
MathWorks products and associated block libraries are available. You cannot
change a built-in block library in any way.
Benefits of Block Libraries
Block libraries are a useful componentization technique for:
• Providing frequently-used, and seldom changed, modeling utilities
• Reusing components repeatedly in a model or in multiple models
For additional information about how libraries compare to other Simulink
componentization techniques, see “Componentization Guidelines” on page
12-17.
Library Browser
Simulink provides a Library Browser that you can use to display block
libraries, search for blocks by name, and copy library blocks into models.
All installed libraries appear in the Library Browser when you open it. See
“Populate a Model” on page 4-4 for information about how to use the Simulink
Library Browser.
Linked Blocks
When you copy a block from a library into a model, Simulink creates a linked
block in the model, and connects it to the library block using a library link.
The library block is the prototype block, and the linked block in the model is
an instance of the library block. The linked block appearance and behavior
28-2
About Block Libraries and Linked Blocks
are the same as the library block. For most purposes, you can ignore the
underlying link and just think of a linked block as a clone of the library block.
Copying a block from a library to another library or model does not always
create a linked block. Library blocks that support linking include subsystems,
masked blocks, and charts. However, the block author can choose not to make
the copy a linked block by modifying the CopyFcn, as done by the Simulink
Subsystem block.
28-3
28
Working with Block Libraries
Create and Work with Linked Blocks
In this section...
“About Linked Blocks” on page 28-4
“Create a Linked Block” on page 28-4
“Update a Linked Block” on page 28-5
“Modify Linked Blocks” on page 28-6
“Find a Linked Block’s Prototype” on page 28-7
“Find Linked Blocks in a Model” on page 28-7
About Linked Blocks
A linked block is an instance of a library block and contains a link to that
library block that serves as the block type’s prototype. The link consists of
the path of the library block that serves as the instance’s prototype. The link
allows the linked block to update whenever the corresponding prototype in the
library changes (“Update a Linked Block” on page 28-5). This ensures that
your model always uses the latest version of the block.
Note The data tip for a linked block shows the name of the library block it
references (see “Block Tool Tips” on page 23-2).
You can change the values of a linked block’s parameters (including in an
existing mask). You cannot add a new mask for linked blocks or edit the mask
setup, that is, add or remove mask parameters or change mask behavior.
Also, you cannot set callback parameters for a linked block. If the linked
block’s prototype is a subsystem, you can make nonstructural changes to the
contents of the linked subsystem (see “Modify Linked Blocks” on page 28-6).
Create a Linked Block
To create a linked block in a model or another library:
28-4
Create and Work with Linked Blocks
1 Open your model.
2 Open the Simulink Library Browser (see “Copy Blocks to Your Model” on
page 4-4), or another library.
3 Use the Library Browser to find the library block that serves as a prototype
of the block you want to create (see “Browse Block Libraries” on page 4-4
and “Search Block Libraries” on page 4-5).
4 Drag the library block from the Library Browser’s Library pane and drop
it into your model.
Update a Linked Block
Simulink updates out-of-date linked blocks in a model or library when you:
• Load the model or library.
• Run the simulation.
• Use the find_system command.
• Query the LinkStatus parameter of a block, using the get_param command
(see “Check and Set Link Status Programmatically” on page 28-16 ).
Note Querying the StaticLinkStatus parameter of a block does not
update any out-of-date linked blocks.
• Save changes to a library block, then Simulink automatically refreshes all
links to the block in open Model Editor windows.
When you edit a library block (in the Model Editor or at the command line),
then Simulink indicates stale links which are open in the Model Editor by
displaying the linked blocks grayed out. Simulink refreshes any stale links
to edited blocks when you activate the Model Editor window, even if you
have not saved the library yet.
To manually refresh links:
• Select Simulation > Update Diagram (or press Ctrl+D).
28-5
28
Working with Block Libraries
• Select Diagram > Refresh Blocks (or press Ctrl+K) to refresh links.
• Select Go To Library Link.
Modify Linked Blocks
You cannot make structural changes to linked blocks, such as adding or
deleting lines or blocks to the block diagram of a masked subsystem. If you
want to make such changes, you must disable the linked block’s link to its
library prototype (see “Disable Links to Library Blocks” on page 28-11 ).
Parameterized Links
If you change parameter values inside a linked block, you create a
parameterized link. You can change the values of any masked subsystem
linked block parameter that does not alter the block’s structure, e.g., by
adding or deleting lines, blocks, or ports. An example of a nonstructural
change is a change to the value of a mathematical block parameter, such
as the Gain parameter of the Gain block. A linked subsystem block whose
parameter values of inner blocks differ from their corresponding library
blocks is called a parameterized link. Changing the top-level mask values
does not create a parameterized link.
When saving a model containing a parameterized link, Simulink saves the
changes to the local copy of the subsystem together with the path to the
library copy in the model’s file. When you reopen the system, Simulink copies
the library block into the loaded model and applies the saved changes.
Tip To determine whether a linked block’s parameter values differ from those
of its library prototype, open the linked block’s block diagram in an editor
window. The linked block’s library link indicator (if displayed) changes to a
red arrow and the title bar of the editor window displaying the subsystem
displays “Parameterized Link” if the linked block’s parameter values differ
from the library block’s parameter values.
See “Display Library Links” on page 28-8.
28-6
Create and Work with Linked Blocks
Self-Modifying Linked Subsystems
Simulink allows linked subsystems to change their own structural contents
without disabling the link. This allows you to create masked subsystems that
modify their structural contents based on mask parameter dialog box values.
Find a Linked Block’s Prototype
To find the source library and the prototype of a linked block, right-click the
linked block and select Library Link > Go To Library Link.
Alternatively, select the linked block and select Diagram > Library Link
> Go To Library Link.
If the library is open, Simulink selects and highlights the library block
and makes the source library the active window. If the library is not open,
Simulink first opens it and then selects the library block.
Find Linked Blocks in a Model
Use the libinfo command to get information about the linked blocks in the
model and which library blocks they link to. The ReferenceBlock property
gives the path of the library block to which a block links.
28-7
28
Working with Block Libraries
Work with Library Links
In this section...
“Display Library Links” on page 28-8
“Lock Links to Blocks in a Library” on page 28-9
“Disable Links to Library Blocks” on page 28-11
“Restore Disabled or Parameterized Links” on page 28-12
“Check and Set Link Status Programmatically” on page 28-16
“Break a Link to a Library Block” on page 28-18
“Fix Unresolved Library Links” on page 28-19
Display Library Links
A model can have a block linked to a library block, or it can have a local
instance of a block that is not linked. To enable the display of library links:
1 In the Model Editor window, select Display > Library Links and from
the submenu, select one of these options:
a None — displays no links
b Disabled — displays only disabled links (the default for new models)
c User Defined — displays only links to user libraries
d All — displays all links
2 Observe the library link indicators.
The library link indicator is a badge in the bottom left corner of each block.
You can right-click the link badge to access link menu options.
28-8
Work with Library Links
The color and icon of the link badge indicates the status of the link. If you
open a linked block, the Model Editor displays the same link badge at bottom
left. You can right-click the link badge in the corner of the canvas to access
link options such as Go To Library Block.
Link Badge
Status
Black links
Active link
Grey
separated
links
Inactive link
Black links
with a red
star icon
Active and modified (parameterized link)
White
links, black
background
Locked link
Lock Links to Blocks in a Library
You can lock links to a library. Lockable library links enable control of end
user editing, to prevent unintentional disabling of these links. This ensures
robust usage of mature stable libraries.
To lock links to a library, either:
• In your library window, select Diagram > Lock Links To Library.
• At the command line, use the LockLinksToLibrary property:
28-9
28
Working with Block Libraries
set_param('MyModelName', 'LockLinksToLibrary', 'on')
where MyModelName is the library file.
When you copy a block to a model from a library with locked links:
• The link is locked.
• You cannot disable locked links from the Model Editor.
If you select Diagram or right-click the linked block, you see the Library
Link menu has changed to Locked Library Link, and the only enabled
option is now Go To Library Block.
• If you display library links, the locked link icon has a black background.
• If you open a locked link, the window title is Locked Link: blockname.
The bottom left corner shows a lock icon and a link badge.
• You cannot edit locked link contents. If you try to make a structural
change to a locked link (such as editing the diagram), you see a message
stating that you cannot modify the link because it is either locked or inside
another locked link.
28-10
Work with Library Links
-
The mask and block parameter dialogs are disabled for blocks inside
locked links. For a resolved linked block with a mask, its parameter
dialog is always disabled.
-
You cannot parameterize locked links in the Model Editor.
• You can disable locked links only from the command line as follows:
set_param(gcb, 'LinkStatus', 'inactive')
To unlock links to a library:
• In your library window, select Diagram > Unlock Links To Library
• At the command line:
set_param('MyModelName', 'LockLinksToLibrary', 'off')
The status of a link (locked or not) is determined by the library state when
you copy the block. If you copy a block from a library with locked links, the
link is locked. If you later unlock the library links, any existing linked
blocks do not change to unlocked links until you refresh links.
If you use sublibraries as an organizational tool, when you lock links to a
library, you might want also to lock links to any sublibraries.
Disable Links to Library Blocks
To make a structural change to a linked block, you need to disable the link
between the block and the library block that serves as its prototype.
You cannot disable locked links from the Model Editor. See “Lock Links to
Blocks in a Library” on page 28-9.
28-11
28
Working with Block Libraries
Note When you use the Model Editor to make a structural change (such as
editing the diagram) to a block with an active library link, Simulink offers
to disable the library link for you (unless the link is locked). If you accept,
Simulink disables the link and allows you to make changes to the subsystem
block.
Do not use set_param to make a structural change to an active link; the result
of this type of change is undefined.
To disable a link:
1 In the Model Editor window, right-click a linked block and select Library
Link > Disable Link.
2 Alternatively, select a linked block and select the menu item
Diagram > Library Link > Disable Link.
The library link is disabled and the library link indicator changes to gray.
When a library block is disabled and it is within another library block (a
child of a parent library block), the model also disables the parent block
containing the child block.
To disable a link from the command-line, set the LinkStatus property to
inactive as follows:
set_param(gcb, 'LinkStatus', 'inactive')
Restore Disabled or Parameterized Links
After you make changes to a disabled linked block, you may want to restore
its link to the library block and resolve any differences between the two
blocks. The Links Tool helps you with this task.
1 In the Model Editor window, select a linked block with a disabled library
link.
2 From the Diagram menu (or right-click context menu), select Library
Link > Resolve Link.
28-12
Work with Library Links
The Links Tool window opens.
The Edited links table has the following columns:
• Linked block — List of linked blocks. The list of links includes library
links with structural changes (disabled links), parameterized library
links (edited links), and library links that were actively chosen to be
resolved.
• Action — Select an action to perform on the linked block or library.
• Library — List of library names and version numbers.
3 Select the check box Show all disabled links if you want to view disabled
links as well as parameterized links.
28-13
28
Working with Block Libraries
4 Under Push/Restore Mode, choose a mode of action:
• If you want to act on individual links, select Individual.
• If you want to act on the whole link hierarchy, leave the default setting
on Hierarchy. See “Pushing or Restoring Link Hierarchies” on page
28-15.
5 From the Linked block list, select a block name.
The Links Tool updates the Paths for selected link panel with links to
the linked block in the model and in the library.
6 From the Action list, select Push or Restore for the currently selected
block.
Action Choice
Links Tool Action
Push
The Links Tool looks for all changes in the link
hierarchy and pushes all links with changes to their
libraries.
Push replaces the version of the block in the library
with the version in the model.
Restore
The Links Tool looks for all disabled or edited links
in the link hierarchy and restores them all with
their corresponding library blocks.
Restore replaces the version of the block in the
model with the version in the library.
Push Individual
In Individual mode, the disabled or edited block is
pushed to the library, preserving the changes inside
it without acting on the hierarchy. All other links
are unaffected.
Restore
Inidividual
In Individual mode, the disabled or edited block is
restored from the library, and all other links are
unaffected.
To select the same action for all linked blocks, click Push all, Restore
all, or Clear all.
28-14
Work with Library Links
7 When you click OK or Apply, the Links Tool performs the push or restore
actions you selected in the edited links table.
After resolving a link, the versions in the library and the linked block now
match.
Note Changes you push to the library are not saved until you actively
save the library.
before it, the model has
If a linked block name has a cautionary icon
other instances of this block linked from the same library block, and they
have different changes. Choose one of the instances to push changes to the
library block and restore links to the other blocks , or choose to restore all of
them with the library version.
Pushing or Restoring Link Hierarchies
Caution Be cautious using Push or Restore in hierarchy mode if you have a
large hierarchy of edited and disabled links. Ensure that you want to push or
restore the whole hierarchy of links.
Pushing a hierarchy of disabled links affects the disabled links inside and
outside in the hierarchy for a given link. If you push changes from a disabled
link in the middle of a hierarchy, the inside links are pushed and the outside
links are restored if without changes. This operation does not affect outside
(parent) links with changes unless you also explicitly selected them for push.
The Links Tool starts from the lowest links (the deepest inside) and then
moves upward in the hierarchy.
Some simple examples:
1 Link A contains link B and both have changes.
• Push A. The Links Tool pushes both A and B.
• Push B. The Links Tool pushes B and not A.
28-15
28
Working with Block Libraries
2 Link A contains link B. A has no changes, and B has changes.
• Push B. The Links Tool pushes B and restores A. When parent links
are unmodified, they are restored.
If you have a hierarchy of parameterized links, the Links Tool can manipulate
only the top level.
Check and Set Link Status Programmatically
All blocks have a LinkStatus parameter and a StaticLinkStatus parameter
that indicate whether the block is a linked block.
Use get_param(gcb, 'StaticLinkStatus') to query the link status without
updating out-of-date linked blocks.
Use get_param and set_param to query and set the LinkStatus, which can
have the following values.
28-16
Get LinkStatus
Value
Description
none
Block is not a linked block.
resolved
Resolved link.
unresolved
Unresolved link.
implicit
Block resides in library block and is itself not a link to
a library block. For example, suppose that A is a link
to a subsystem in a library that contains a Gain block.
Further, suppose that you open A and select the Gain
block. Then, get_param(gcb, 'LinkStatus') returns
implicit.
inactive
Disabled link.
Work with Library Links
Set LinkStatus
Value
Description
none
Breaks link. Use none to break a link, e.g.,
set_param(gcb, 'LinkStatus', 'none')
inactive
Disables link. Use Inactive to disable a link, e.g.,
set_param(gcb, 'LinkStatus', 'inactive')
restore
Restores an inactive or disabled link to a library block
and discards any changes made to the local copy of
the library block. For example, set_param(gcb,
'LinkStatus', 'restore') replaces the selected block
with a link to a library block of the same type, discarding
any changes in the local copy of the library block.
This is equivalent to Restore Individual in the Links
Tool.
propagate
Pushes any changes made to the disabled link to the
library block and re-establishes its link.
This is equivalent to Push Individual in the Links
Tool.
restoreHierarchy Restores all disabled links in the hierarchy with their
corresponding library blocks. This is equivalent to
Restore in hierarchy mode in the Links Tool.
propagateHierarchy
Pushes all links with changes in the hierarchy to their
libraries. This is equivalent to Push in hierarchy mode in
the Links Tool. See “Restore Disabled or Parameterized
Links” on page 28-12.
Note Using get_param to query a block’s LinkStatus also resolves any
out-of-date block links. Use get_param to update library links in a model
programmatically. Querying the StaticLinkStatus property does not resolve
any out-of-date links. Query the StaticLinkStatus property when the call to
get_param is in the callback of a child block querying the link status of its
parent.
28-17
28
Working with Block Libraries
If you call get_param on a block inside a library link, Simulink resolves the
link if necessary. This operation may involve loading part of the library and
executing callbacks.
Break a Link to a Library Block
You can break the link between a linked block and its library block to cause
the linked block to become a simple copy of the library block, unlinked to the
library block. Changes to the library block no longer affect the block. Breaking
links to library blocks may enable you to transport a masked subsystem model
as a standalone model, without the libraries (see “Masking”).
To break the link between a linked block and its library block, you can use
any of the following actions.
• Disable the link, then right-click the block and choose Library
Link > Break Link .
• At the command line, change the value of the LinkStatus parameter to
'none' using this command:
set_param(gcb, 'LinkStatus', 'none')
• Right-click and drag to copy a block, and you see an offer to break links,
unless the parent library has LockLinksToLibrary set to on. If your copied
block will be a locked link, then you do not see the option to break links.
To copy and break links to multiple blocks simultaneously, select multiple
blocks and then drag. Any locked links are ignored and not broken.
• When saving the model, you can break links by supplying arguments to
the save_system command. See save_system.
Note Breaking library links in a model does not guarantee that you can run
the model standalone, especially if the model includes blocks from third-party
libraries or optional Simulink blocksets. It is possible that a library block
invokes functions supplied with the library and hence can run only if the
library is installed on the system running the model. Further, breaking a
link can cause a model to fail when you install a new version of the library
on a system.
28-18
Work with Library Links
For example, suppose a block invokes a function that is supplied with the
library. Now suppose that a new version of the library eliminates the function.
Running a model with an unlinked copy of the block results in invocation of
a now nonexistent function, causing the simulation to fail. To avoid such
problems, you should generally avoid breaking links to libraries.
Fix Unresolved Library Links
If Simulink is unable to find either the library block or the source library on
your MATLAB path when it attempts to update the linked block, the link
becomes unresolved. Simulink issues an error message and displays these
blocks using red dashed lines. The error message is
Failed to find block "source-block-name"
in library "source-library-name"
referenced by block
"linked-block-path".
The unresolved linked block appears like this (colored red).
To fix a bad link, you must do one of the following:
• Delete the unresolved block and copy the library block back into your model.
• Add the folder that contains the required library to the MATLAB path
and select either Diagram > Update Diagram or Diagram > Refresh
Blocks.
• Double-click the unresolved block to open its dialog box (see the Bad
Link block reference page). On the dialog box that appears, correct the
pathname in the Source block field and click OK.
28-19
28
Working with Block Libraries
Create Block Libraries
In this section...
“Create a Library” on page 28-20
“Create a Sublibrary” on page 28-21
“Modify and Lock Libraries” on page 28-21
“Make Backward-Compatible Changes to Libraries” on page 28-22
Create a Library
You can create your own block library and add it to the Simulink Library
Browser (see “Add Libraries to the Library Browser” on page 28-32). To
create a library:
1 Select Library from the New submenu of the File menu.
Simulink creates a model file for storing the new library and displays the
file in a new model editor window.
Tip You can also use the new_system command to create the library and
the open_system command to open the new library.
2 Drag blocks from models or other libraries into the new library.
Note If you want to be able to create links in models to a block in the
library, you may need to provide a mask (see “Masking”) for the block. You
can also provide a mask for a subsystem in a library, but you do not need to
have a mask to create links to it in models.
3 Save the library’s file under a new name.
28-20
Create Block Libraries
Create a Sublibrary
If your library contains many blocks, consider grouping the blocks into a
hierarchy of sublibraries. Creating a sublibrary entails inserting a reference
in the Simulink model file of one library to the model file of another library.
The referenced file is called a sublibrary of the parent (i.e., referencing)
library. The sublibrary is said to be included by reference in the parent
library.
To include a library in another library as a sublibrary:
1 Open the parent library.
2 Add a Subsystem block to the parent library.
3 Delete the subsystem’s default input and output ports.
4 Create a mask for the subsystem that displays text or an image that
conveys the sublibrary’s purpose.
5 Set the subsystem’s OpenFcn parameter to the name of the sublibrary’s
model file.
6 Save the parent library.
Modify and Lock Libraries
When you open a library, it is automatically locked and you cannot modify its
contents. To unlock the library, select Diagram > Unlock Library.
When you close the library window, Simulink locks the library.
Locking a library prevents a user from inadvertently modifying a library, for
example, by moving a block in the library or adding or deleting a block from
the library. If you attempt to modify a locked library, Simulink displays a
dialog box that allows you to unlock the library and make the change.
To unlock a block library from the MATLAB command line, use the following
command:
set_param('library_name', 'Lock', 'off');
28-21
28
Working with Block Libraries
You must then relock the library from the MATLAB command line to prevent
further changes. Use the following command to relock a block library:
set_param('library_name', 'Lock', 'on');
If you want to control end user editing of linked blocks and prevent
unintentional disabling of links, you can lock links to a library. See “Lock
Links to Blocks in a Library” on page 28-9.
When you save a library, Simulink checks file permissions and offers to try to
make the library writable if necessary.
Make Backward-Compatible Changes to Libraries
Simulink provides the following features to facilitate making changes to
library blocks without invalidating models that use the library blocks.
Forwarding Tables
You can create forwarding tables for libraries to specify how to update links
in models to reflect changes in the parameters. Use the Forwarding Table to
map old library blocks to new library blocks. For example, if you rename or
move a block in a library, you can use a forwarding table to enable Simulink
to update models that link to the block.
After you specify the forwarding table entry in a library, any links to old
library blocks will be updated when you load a model containing links to
old blocks. Library authors can use the forwarding tables to automatically
transform old links into updated links without any loss of functionality and
data. Use the forwarding table to solve compatibility issues with models
containing old links that cannot load in the current version of Simulink.
Library authors do not need to run slupdate to upgrade old links, and can
reduce maintenance of legacy blocks.
To set up a forwarding table for a library,
1 Select Diagram > Unlock Library.
2 Select File > Library Properties > Library Properties. The Library
Properties dialog box opens.
28-22
Create Block Libraries
3 Select the Forwarding Table tab.
4 Define the mapping from old library blocks to new library blocks.
a Click the Add New Entry button. A new row appears in the table.
b Enter values in Old Block Path and New Block Path columns.
Click GCB to get the path of the currently selected block.
If you select identical old and new library block names and paths, the
Forwarding Table automatically populates library version numbers
in the Version columns. The LibraryVersion property is the model
version of the library at the time the link was created.
c (Optional ) You can define a transformation function to update old link
parameter data using a MATLAB file on the path. Specify the function
in the Transformation Function column. Transforming old link
parameter data for the new library block enables you to load old links
and preserve parameter data.
28-23
28
Working with Block Libraries
If you do not want to specify a transformation function, do not edit
the field. When you save the library, the column will display No
Transformation.
5 Click OK to apply changes and close the dialog box.
After specifying the forwarding table mapping, when you open a model
containing links to the library, links to old library blocks will be updated.
To view an example of a forwarding table:
1 Enter
open_system('simulink')
2 Select File > Library Properties > Library Properties
3 Click the Forwarding Table tab.
4 View how the forwarding table specifies the mapping of old blocks to new
blocks. You cannot make changes because the library is locked. Do not edit
the forwarding table for your Simulink library.
28-24
Create Block Libraries
5 Click OK to close the dialog
The following example shows a forwarding table that defines:
• A block with the same name moving to a different library (Constant A)
• A block changing name in the same library (Block X to Block Y)
• A block changing name, moving library, and applying a transformation
function (Gain A to Gain B)
• A block with three version updates (Block A) using a transformation
function. When you select identical old and new library block names and
paths, the Forwarding Table automatically populates version numbers
in the Version columns. If this is the first entry with identical names,
version starts at 0, and the new version number is set to the ModelVersion
of the library. For subsequent entries, the first version is set to the
previous entry’s new version, and the new version is set to the current
ModelVersion of the library.
28-25
28
Working with Block Libraries
At the command line you can create a simple forwarding table specifying
the old locations and new locations of blocks that have moved within the
library or to another library. You associate a forwarding table with a library
by setting its ForwardingTable parameter to a cell array of two-element
cell arrays, each of which specifies the old and new path of a block that has
moved. For example, the following command creates a forwarding table and
assigns it to a library named Lib1.
set_param('Lib1', 'ForwardingTable', {{'Lib1/A', 'Lib2/A'}
{'Lib1/B', 'Lib1/C'}});
The forwarding table specifies that block A has moved from Lib1 to Lib2. and
that block B is now named C. Suppose that you open a model that contains
links to Lib1/A and Lib1/B. Simulink updates the link to Lib1/A to refer
to Lib2/A and the link to Lib1/B to refer to Lib1/C. The changes become
permanent when you subsequently save the model.
Writing Transformation Functions. You can use transformation functions
to add or remove parameters and define parameter values. Transforming old
link parameter data for the new library block enables you to load old links
and preserve parameter data that differs from library values. Define your
transformation function using a MATLAB file on the path, then specify the
function in the Forwarding Table Transformation Function column.
The transformation function in your MATLAB file must be like the following:
function outData = TransformationFcn(inData)
where inData is a structure with fields ForwardingTableEntry and
InstanceData, and ForwardingTableEntry is a structure with fields
__slOldName__, __slNewName__, __slOldVersion__ , __slNewVersion__.
28-26
Create Block Libraries
This general transformation function can have many local functions defined
in it. The function calls the appropriate local functions based on old block
names and versions. Use this to combine many local functions into a single
transformation function, to avoid having many transformation functions on
the MATLAB path.
InstanceData and NewInstanceData are structures with fields Name and
Value. Instance data means the names and values of parameters that are
different from the library values.
outData is a structure with fields NewInstanceData and NewBlockPath.
The following example code shows how to define a transformation function
that adds a parameter with value uint8 to update a Compare To Constant
block:
function [outData] = TransformationCompConstBlk(inData)
% Example transformation Function for old 'Compare To Const' block.
%
% If instanceData of old 'Compare To Const' block does not have
% the 'OutDataTypestr' parameter,
% add the parameter with value 'uint8'.
%
% In the Simulink library the 'ForwardingTableEntry' would be of type:
% ||__slOldName__||A||__slNewName__||B||__slTransformationFcn__||TX
%
% Exact entry is:
% ||__slOldName__||fixpt_lib_4/Logic & Comparison/Compare\nTo Constant||__slNewName__||
% simulink/Logic and Bit\nOperations/Compare\nTo Constant||__slTransformationFcn__||TransformationCompConstB
%
%
outData.NewBlockPath = '';
outData.NewInstanceData = [];
instanceData = inData.InstanceData;
% Get the field type 'Name' from instanceData
[ParameterNames{1:length(instanceData)}] = instanceData.Name;
if (~ismember('OutDataTypeStr',ParameterNames))
28-27
28
Working with Block Libraries
% OutDataTypeStr parameter is not present in old link. Add it and set value uint8
instanceData(end+1).Name = 'OutDataTypeStr';
instanceData(end).Value = 'uint8';
end
outData.NewInstanceData = instanceData;
Creating Aliases for Mask Parameters
Simulink lets you create aliases, i.e., alternate names, for a mask’s
parameters. A model can then refer to the mask parameter by either its
name or its alias. This allows you to change the name of a mask parameter
in a library block without having to recreate links to the block in existing
models (see “Using Mask Parameter Aliases to Create Backward-Compatible
Parameter Name Changes” on page 28-28).
To create aliases for a masked block’s mask parameters, use the set_param
command to set the block’s MaskVarAliases parameter to a cell array that
specifies the names of the aliases in the same order as the mask names
appear in the block’s MaskVariables parameter.
Using Mask Parameter Aliases to Create Backward-Compatible
Parameter Name Changes. The following example illustrates the use
of mask parameter aliases to create backward-compatible parameter name
changes.
1 Create a new library. File > New > Library
2 Open the model masking_example described in “How Mask Parameters
Work” on page 26-4. Drag the masked block named mx+b into your new
library and rename it to Line.
3 Right-click the block and select Properties. In the Block Properties dialog,
select the Block Annotation tab. In the Enter text and tokens for
annotation box, enter
m = %
b = %
The block displays the value of its m and b parameters,
28-28
Create Block Libraries
4 Right-click the block, and select Mask > Mask Parameters. In the Block
Parameter dialog, enter 0.5 for the Slope and 0 for the Intercept.
5 Save the new library with the filename mylibrary.
6 Create a new Simulink model. File > New > Model.
7 From the mylibrary window, drag an instance of the Line block to your
new model. Rename the instance LineA.
8 Right-click the block and select Mask > Mask Parameters. In the Block
Parameters dialog, change the value Slope to -0.5. and change the value
Intercept. to 30. Select Display > Library Links > User Defined.
9 Add a Scope and Clock block to your model and connect them to your block.
Save the new model with the filename mymodel.
10 From the Simulation menu, select Model Configuration Parameters.
From the Type list, select Fixed-step. From the Solver list, select
discrete (no continuous states. In the Fixed-step size box, enter
0.1. Simulate model.
Note that the model simulates without error.
11 Save and close mymodel.
12 Open mylibrary.
13 Edit mask. Right-click block, select Edit mask. In the Mask Editor dialog,
• Select the Parameters tab. In the Dialog parameters section and
Variable column, change the variable m to slope and b to intercept.
• Select the Icon & Ports tab. In the Icon Drawing commends box, change
the variable m to slope and b to intercept.
14 Right-click the Line block, select Properties. In the Block Properties
dialog, .
• Select the Block Annotation tab . In the Enter text and tokens of
annotation box, rename the m parameter to slope and the b parameter
to intercept.
28-29
28
Working with Block Libraries
15 Click Ok and save mylibrary.
16 Reopen mymodel.
Note that LineA icon has reverted to the appearance of its library master
(i.e., mylib/Line) and that its annotation displays question marks for the
values of m and b. These changes reflect the parameter name changes in
the library block. In particular, Simulink cannot find any parameters
named m and b in the library block and hence does not know what to do
with the instance values for those parameters. As a result, LineA reverts
to the default values for the slope and intercept parameters, thereby
inadvertently changing the behavior of the model. The following steps show
how to use parameter aliases to avoid this inadvertent change of behavior.
17 Close mymodel.
18 In the Library:
mylibrary window, select the Line block.
19 Execute the following command at the MATLAB command line.
set_param(gcb, 'MaskVarAliases',{'m', 'b'})
This specifies that m and b are aliases for the Line block slope and
intercept parameters.
20 Reopen mymodel.
Note that LineA appearance, not the annotation, now reflects the value of
the slope parameter under its original name, i.e., m. This is because when
Simulink opened the model, it found that m is an alias for slope and assigned
the value of m stored in the model file to the LineA slope parameter.
21 Change LineA block annotation property to reflect LineA parameter name
changes, replace
m = %
b = %
with
m = %
b = %
28-30
Create Block Libraries
LineA now appears with m = -0.5 and b = 30.
Note that LineA annotation shows that, thanks to parameter aliasing,
Simulink has correctly applied the parameter values stored for LineA in
the mymodels file to the block renamed parameters.
28-31
28
Working with Block Libraries
Add Libraries to the Library Browser
In this section...
“Display a Library in the Library Browser” on page 28-32
“Example of a Minimal slblocks.m File” on page 28-32
“Add More Descriptive Information in slblocks.m” on page 28-33
Display a Library in the Library Browser
1 Create a folder in the MATLAB path for the top-level library and its
sublibraries.
You must store each top-level library that you want to appear in the
Library Browser in its own folder on the MATLAB path. Two top-level
libraries cannot exist in the same folder.
2 Create or copy the top-level library and its sublibraries into the folder you
created in the MATLAB path.
3 In the folder for the top-level library, include a slblocks.m file.
The approach you use to create the slblocks.m file depends on your
requirements for describing the library:
• If a minimal slblocks.m file meets your needs, then create a new
slblocks.m file, based on the example below
• If you want to describe the library more fully, consider copying an
existing slblocks.m file to use as a template, editing the copy to describe
your library (see below).
Example of a Minimal slblocks.m File
To display a library in the Library Browser, at a minimum you must include
these lines (adjusted to describe your library; comments are not required) in
the slblocks.m file.
function blkStruct = slblocks
% Specify that the product should appear in the library browser
28-32
Add Libraries to the Library Browser
% and be cached in its repository
Browser.Library = 'mylib';
Browser.Name
= 'My Library';
blkStruct.Browser = Browser;
Add More Descriptive Information in slblocks.m
You can review other descriptive information you may wish to include in
your slblocks.m file by examining the comments in the Simulink library
slblocks.m file: matlabroot/toolbox/simulink/blocks/slblocks.m.
28-33
28
28-34
Working with Block Libraries
29
Using the MATLAB
Function Block
• “Integrate MATLAB Algorithm in Model” on page 29-4
• “What Is a MATLAB Function Block?” on page 29-6
• “Why Use MATLAB Function Blocks?” on page 29-8
• “Create Model That Uses MATLAB Function Block” on page 29-9
• “Code Generation Readiness Tool” on page 29-16
• “Check Code Using the Code Generation Readiness Tool” on page 29-22
• “Debugging a MATLAB Function Block” on page 29-23
• “MATLAB Function Block Editor” on page 29-33
• “MATLAB Function Reports” on page 29-51
• “Type Function Arguments” on page 29-64
• “Size Function Arguments” on page 29-72
• “Add Parameter Arguments” on page 29-75
• “Resolve Signal Objects for Output Data” on page 29-76
• “Types of Structures in MATLAB Function Blocks” on page 29-78
• “Attach Bus Signals to MATLAB Function Blocks” on page 29-79
• “How Structure Inputs and Outputs Interface with Bus Signals” on page
29-81
• “Rules for Defining Structures in MATLAB Function Blocks” on page 29-82
• “Index Substructures and Fields” on page 29-83
29
Using the MATLAB Function Block
• “Create Structures in MATLAB Function Blocks” on page 29-84
• “Assign Values to Structures and Fields” on page 29-86
• “Initialize a Matrix Using a Non-Tunable Structure Parameter” on page
29-88
• “Define and Use Structure Parameters” on page 29-91
• “Limitations of Structures and Buses in MATLAB Function Blocks” on
page 29-93
• “What Is Variable-Size Data?” on page 29-94
• “How MATLAB Function Blocks Implement Variable-Size Data” on page
29-95
• “Enable Support for Variable-Size Data” on page 29-96
• “Declare Variable-Size Inputs and Outputs” on page 29-97
• “Filter a Variable-Size Signal” on page 29-98
• “Enumerated Types Supported in MATLAB Function Blocks” on page
29-105
• “Define Enumerated Data Types for MATLAB Function Blocks” on page
29-106
• “Add Inputs, Outputs, and Parameters as Enumerated Data” on page
29-107
• “Basic Approach for Adding Enumerated Data to MATLAB Function
Blocks” on page 29-109
• “Instantiate Enumerated Data in MATLAB Function Blocks” on page
29-110
• “Control an LED Display” on page 29-111
• “Operations on Enumerated Data” on page 29-115
• “Using Enumerated Data in MATLAB Function Blocks” on page 29-116
• “Share Data Globally” on page 29-117
• “Add Frame-Based Signals” on page 29-126
• “Create Custom Block Libraries” on page 29-132
29-2
• “Use Traceability in MATLAB Function Blocks” on page 29-151
• “Include MATLAB Code as Comments in Generated Code” on page 29-156
• “Enhance Code Readability for MATLAB Function Blocks” on page 29-162
• “Speed Up Simulation with Basic Linear Algebra Subprograms” on page
29-171
• “Control Run-Time Checks” on page 29-173
• “Track Object Using MATLAB Code” on page 29-175
• “Filter Audio Signal Using MATLAB Code” on page 29-203
29-3
29
Using the MATLAB Function Block
Integrate MATLAB Algorithm in Model
Here is an example of a Simulink model that contains a MATLAB Function
block:
The MATLAB Function block contains the following algorithm:
function [mean,stdev] = stats(vals)
% #codegen
% calculates a statistical mean and a standard
% deviation for the values in vals.
len = length(vals);
mean = avg(vals,len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
plot(vals,'-+');
function mean = avg(array,size)
mean = sum(array)/size;
You will build this model in “Create Model That Uses MATLAB Function
Block” on page 29-9.
Defining Local Variables for Code Generation
If you intend to generate code from the MATLAB algorithm in a MATLAB
Function block, you must explicitly assign the class, size, and complexity of
local variables before using them in operations or returning them as outputs
(see “Data Definition for Code Generation” on page 34-2. In the example
29-4
Integrate MATLAB® Algorithm in Model
function stats, the local variable len is defined before being used to calculate
mean and standard deviation:
len = length(vals);
Generally, once you assign properties to a variable, you cannot redefine
its class, size, or complexity elsewhere in the function body, but there are
exceptions (see “Reassignment of Variable Properties” on page 33-9).
29-5
29
Using the MATLAB Function Block
What Is a MATLAB Function Block?
The MATLAB Function block allows you to add MATLAB functions to
Simulink models for deployment to desktop and embedded processors. This
capability is useful for coding algorithms that are better stated in the textual
language of the MATLAB software than in the graphical language of the
Simulink product. From the MATLAB Function block, you can generate
readable, efficient, and compact C/C++ code for deployment to desktop and
embedded applications. .
Calling Functions in MATLAB Function Blocks
MATLAB Function blocks can call any of the following types of functions:
• Local functions
Local functions are defined in the body of the MATLAB Function block. In
the preceding example, avg is a local function. See “Call Local Functions”
on page 41-9.
• MATLAB toolbox functions that support code generation
From MATLAB Function blocks, you can call toolbox functions that support
code generation. When you build your model with Simulink Coder, these
functions generate C code that is optimized to meet the memory and
performance requirements of desktop and embedded environments. In the
preceding example, length, sqrt, and sum are examples of toolbox functions
that support code generation. See “Call Supported Toolbox Functions”
on page 41-10. For a complete list of supported functions, see “Functions
Supported for Code Generation — Alphabetical List” on page 31-2.
• MATLAB functions that do not support code generation
From MATLAB Function blocks, you can also call extrinsic functions.
These are functions on the MATLAB path that the compiler dispatches
to MATLAB software for execution because the target language does not
support them. These functions do not generate code; they execute only in
the MATLAB workspace during simulation of the model. The Simulink
Coder software attempts to compile all MATLAB functions unless you
explicitly declare them to be extrinsic by using coder.extrinsic. See
“Declaring MATLAB Functions as Extrinsic Functions” on page 41-12.
29-6
What Is a MATLAB Function Block?
The code generation software detects calls to many common visualization
functions, such as plot, disp, and figure. For MEX code generation, it
automatically calls out to MATLAB for these functions. For standalone
code generation, it does not generate code for these visualization functions.
This capability removes the requirement to declare these functions
extrinsic using the coder.extrinsic function.
See “Resolution of Function Calls in MATLAB Generated Code” on page
41-2.
29-7
29
Using the MATLAB Function Block
Why Use MATLAB Function Blocks?
MATLAB Function blocks provide the following capabilities:
• Allow you to build MATLAB functions into embeddable
applications — MATLAB Function blocks support a subset of MATLAB
toolbox functions that generate efficient C/C++ code (see “Functions
Supported for Code Generation”). With this support, you can use Simulink
Coder to generate embeddable C code from MATLAB Function blocks that
implement a variety of sophisticated mathematical applications. In this
way, you can build executables that harness MATLAB functionality, but
run outside the MATLAB environment.
• Inherit properties from Simulink input and output signals — By
default, both the size and type of input and output signals to a MATLAB
Function block are inherited from Simulink signals. You can also choose to
specify the size and type of inputs and outputs explicitly in the Ports and
Data Manager (see “Ports and Data Manager” on page 29-37) or in the
Model Explorer (see “Model Explorer Overview” on page 9-2).
29-8
Create Model That Uses MATLAB Function Block
Create Model That Uses MATLAB Function Block
In this section...
“Adding a MATLAB Function Block to a Model” on page 29-9
“Programming the MATLAB Function Block” on page 29-10
“Building the Function and Checking for Errors” on page 29-12
“Defining Inputs and Outputs” on page 29-14
Adding a MATLAB Function Block to a Model
1 Create a new model with the Simulink product and add a MATLAB
Function block to it from the User-Defined Function library:
2 Add the following Source and Sink blocks to the model:
• From the Sources library, add a Constant block to the left of the
MATLAB Function block and set its value to the vector [2 3 4 5].
• From the Sinks library, add two Display blocks to the right of the
MATLAB Function block.
The model should now have the following appearance:
29-9
29
Using the MATLAB Function Block
3 In the Simulink Editor, select File > Save As and save the model as
call_stats_block1.
Programming the MATLAB Function Block
The following exercise shows you how to program the block to calculate the
mean and standard deviation for a vector of values:
1 Open the call_stats_block1 model that you saved at the end of “Adding
a MATLAB Function Block to a Model” on page 29-9. Double-click the
MATLAB Function block fcn to open it for editing.
A default function signature appears, along with the %#codegen directive.
The directive indicates that you intend to generate code from this algorithm
and turns on appropriate error checking (see “Compilation Directive
%#codegen” on page 41-8.
2 Edit the function header line as follows:
function [mean,stdev] = stats(vals)
%#codegen
The function stats calculates a statistical mean and standard deviation
for the values in the vector vals. The function header declares vals as an
argument to the stats function, with mean and stdev as return values.
3 Save the model as call_stats_block2.
4 Complete the connections to the MATLAB Function block as shown.
29-10
Create Model That Uses MATLAB Function Block
5 In the MATLAB Function Block Editor, enter a line space after the function
header and add the following code:
% calculates a statistical mean and a standard
% deviation for the values in vals.
len = length(vals);
mean = avg(vals,len);
stdev = sqrt(sum(((vals-avg(vals,len)).^2))/len);
plot(vals,'-+');
function mean = avg(array,size)
mean = sum(array)/size;
More about length
The function length is an example of a toolbox function that supports code
generation. When you simulate this model, C code is generated for this
function in the simulation application.
More about len
The class, size, and complexity of local variable len matches the output of
the toolbox function length, which returns a real scalar of type double.
By default, implicitly declared local variables like len are temporary. They
come into existence only when the function is called and cease to exist
when the function is exited. To make implicitly declared variables persist
between function calls, see “Define and Initialize Persistent Variables” on
page 33-10.
More about plot
The function plot is not supported for code generation. The code generation
software detects calls to many common visualization functions, such as
plot, disp, and figure. For MEX code generation, it automatically calls
out to MATLAB for these functions. For standalone code generation, it does
not generate code for these visualization functions.
6 Save the model as call_stats_block2.
29-11
29
Using the MATLAB Function Block
Building the Function and Checking for Errors
After programming a MATLAB Function block in a Simulink model, you can
build the function and test for errors. This section describes the steps:
1 Set up your compiler.
2 Build the function.
3 Locate and fix errors.
Setting Up Your Compiler
Before building your MATLAB Function block, you must set up your
C compiler by running the mex -setup command, as described in the
documentation for mex. You must run this command even if you use the
default C compiler that comes with the MATLAB product for Microsoft
Windows platforms. You can also use mex to choose and configure a different
C compiler, as described in “Build MEX-Files”.
Supported Compilers for Simulation Builds. To view a list of compilers
for building models containing MATLAB Function blocks for simulation:
1 Navigate to the Supported and Compatible Compilers Web page.
2 Select your platform.
3 In the table for Simulink and related products, find the compilers checked
in the column titled Simulink for MATLAB Function blocks.
Supported Compilers for Code Generation. To generate code for models
that contain MATLAB Function blocks, you can use any of the C compilers
supported by Simulink software for code generation with Simulink Coder.
For a list of these compilers:
1 Navigate to the Supported and Compatible Compilers Web page.
2 Select your platform.
3 In the table for Simulink and related products, find the compilers checked
in the column titled Simulink Coder.
29-12
Create Model That Uses MATLAB Function Block
How to Generate Code for the MATLAB Function Block
1 Open the call_stats_block2 model that you saved at the end of
“Programming the MATLAB Function Block” on page 29-10.
2 Double-click its MATLAB Function block stats to open it for editing.
3 In the MATLAB Function Block Editor, select Build Model > Build to
compile and build the example model.
If no errors occur, the Simulation Diagnostics window displays a
message indicating success. Otherwise, this window helps you locate
errors, as described in “How to Locate and Fix Errors” on page 29-13.
How to Locate and Fix Errors
If errors occur during the build process, the Simulation Diagnostics window
lists the errors with links to the offending code.
The following exercise shows how to locate and fix an error in a MATLAB
Function block.
1 In the stats function, change the local function avg to a fictitious local
function aug and then compile again to see the following messages in
window:
The Simulation Diagnostics window displays each detected error with a
red button.
2 Click the first error line to display its diagnostic message in the bottom
error window.
The message also links to a report about compile-time type information for
variables and expressions in your MATLAB functions. This information
helps you diagnose error messages and understand type propagation rules.
For more information about the report, see “MATLAB Function Reports”
on page 29-51.
3 In the diagnostic message for the selected error, click the blue link after
the function name to display the offending code.
29-13
29
Using the MATLAB Function Block
The offending line appears highlighted in the MATLAB Function Block
editor:
4 Correct the error by changing aug back to avg and recompile.
Defining Inputs and Outputs
In the stats function header for the MATLAB Function block you defined in
“Programming the MATLAB Function Block” on page 29-10, the function
argument vals is an input, and mean and stdev are outputs. By default,
function inputs and outputs inherit their data type and size from the signals
attached to their ports. In this topic, you examine input and output data for
the MATLAB Function block to verify that it inherits the correct type and size.
1 Open the call_stats_block2 model that you saved at the end of
“Programming the MATLAB Function Block” on page 29-10. Double-click
the MATLAB Function block stats to open it for editing.
2 In the MATLAB Function Block editor, select Edit Data.
The Ports and Data Manager opens to help you define arguments for
MATLAB Function blocks.
The left pane displays the argument vals and the return values mean and
stdev that you have already created for the MATLAB Function block.
Notice that vals is assigned a Scope of Input, which is short for Input
from Simulink. mean and stdev are assigned the Scope of Output, which
is short for Output to Simulink.
3 In the left pane of the Ports and Data Manager, click anywhere in the
row for vals to highlight it.
The right pane displays the Data properties dialog box for vals. By
default, the class, size, and complexity of input and output arguments
are inherited from the signals attached to each input or output port.
Inheritance is specified by setting Size to -1, Complexity to Inherited,
and Type to Inherit: Same as Simulink.
The actual inherited values for size and type are set during compilation
of the model, and are reported in the Compiled Type and Compiled
Size columns of the left pane.
29-14
Create Model That Uses MATLAB Function Block
You can specify the type of an input or output argument by selecting a type
in the Type field of the Data properties dialog box, for example, double.
You can also specify the size of an input or output argument by entering an
expression in the Size field. For example, you can enter [2 3] in the Size
field to specify vals as a 2-by-3 matrix. See “Type Function Arguments”
on page 29-64 and “Size Function Arguments” on page 29-72 for more
information on the expressions that you can enter for type and size.
Note The default first index for any arrays that you add to a MATLAB
Function block function is 1, just as it would be in MATLAB.
For more information, see “Ports and Data Manager” on page 29-37).
29-15
29
Using the MATLAB Function Block
Code Generation Readiness Tool
In this section...
“What Information Does the Code Generation Readiness Tool Provide?” on
page 29-16
“Summary Tab” on page 29-17
“Code Structure Tab” on page 29-18
“See Also” on page 29-21
What Information Does the Code Generation
Readiness Tool Provide?
The code generation readiness tool screens MATLAB code for features and
functions that are not supported for code generation. The tool provides a
report that lists the source files that contain unsupported features and
functions. The report also provides an indication of how much work you
must do to make the MATLAB code suitable for code generation. The tool
might not detect all code generation issues. Under certain circumstances, it
might report false errors. Because the tool might not detect all issues, or
might report false errors, generate a MEX function to verify that your code is
suitable for code generation before generating C code.
29-16
Code Generation Readiness Tool
Summary Tab
The Summary tab provides a Code Generation Readiness Score which
ranges from 1 to 5. A score of 1 indicates that the tool has detected issues that
require extensive changes to the MATLAB code to make it suitable for code
generation. A score of 5 indicates that the tool has not detected any code
generation issues; the code is ready to use with no or minimal changes.
29-17
29
Using the MATLAB Function Block
On this tab, the tool also provides information about:
• MATLAB syntax issues. These issues are reported in the MATLAB editor.
Use the code analyzer to learn more about the issues and how to fix them.
• Unsupported MATLAB function calls.
• Unsupported MATLAB language features, such as recursion, cell arrays,
nested functions, and function handles.
• Unsupported data types.
Code Structure Tab
29-18
Code Generation Readiness Tool
If the code that you are checking calls other MATLAB functions, or you
are checking multiple entry-point functions, the tool displays the Code
Structure Tab.
This tab provides information about the relative size of each file and how
suitable each file is for code generation.
Code Distribution
The Code Distribution pane provides a pie chart that shows the relative
sizes of the files and how suitable each file is for code generation. This
information is useful during the planning phase of a project for estimation
and scheduling purposes. If the report indicates that there are multiple files
not yet suitable for code generation, consider fixing files that require minor
changes before addressing files with significant issues.
Call Tree
The Call Tree pane provides information on the nesting of function calls. For
each called function, the report provides a Code Generation Readiness
score which ranges from 1 to 5. A score of 1 indicates that the tool has detected
issues that require extensive changes to the MATLAB code to make it suitable
for code generation. A score of 5 indicates that the tool has not detected any
code generation issues; the code is ready to use with no or minimal changes.
The report also lists the number of lines of code in each file.
Show MATLAB Functions. If you select Show MATLAB Functions, the
report also lists all the MATLAB functions called by your function code.
For each of these MATLAB functions, if the function is supported for code
generation, the report sets Code Generation Readiness to Yes.
29-19
29
29-20
Using the MATLAB Function Block
Code Generation Readiness Tool
See Also
• “Check Code Using the Code Generation Readiness Tool” on page 29-22
29-21
29
Using the MATLAB Function Block
Check Code Using the Code Generation Readiness Tool
In this section...
“Run Code Generation Readiness Tool at the Command Line” on page 29-22
“Run the Code Generation Readiness Tool From the Current Folder
Browser” on page 29-22
Run Code Generation Readiness Tool at the
Command Line
1 Navigate to the folder that contains the file that you want to check for
code generation readiness.
2 At the MATLAB command prompt, enter:
coder.screener('filename')
The Code Generation Readiness tool opens for the file named filename,
provides a code generation readiness score, and lists issues that must be
fixed prior to code generation.
Run the Code Generation Readiness Tool From the
Current Folder Browser
1 In the current folder browser, right-click the file that you want to check for
code generation readiness.
2 From the context menu, select Check Code Generation Readiness.
The Code Generation Readiness tool opens for the selected file and
provides a code generation readiness score and lists issues that must be
fixed prior to code generation.
29-22
Debugging a MATLAB Function Block
Debugging a MATLAB Function Block
In this section...
“How Debugging Affects Simulation Speed” on page 29-23
“Enabling and Disabling Debugging” on page 29-23
“Debugging the Function in Simulation” on page 29-23
“Watching Function Variables During Simulation” on page 29-27
“Checking for Data Range Violations” on page 29-29
“Debugging Tools” on page 29-29
How Debugging Affects Simulation Speed
Debugging a MATLAB Function block slows simulation. For maximum
simulation speed, disable debugging as described in “Enabling and Disabling
Debugging” on page 29-23.
Enabling and Disabling Debugging
There are two levels of debugging available when using MATLAB Function
blocks, model level debugging and block level debugging.
Disable debugging for an entire model by clearing the Enable
debugging/animation check box in the Simulation Target pane in the
Configuration Parameters dialog. Disable debugging for an individual
MATLAB Function block by clicking Breakpoints > Enable Debugging in
the MATLAB Function Block Editor. If Enable Debugging is unavailable,
then the Simulation Target pane in the Configuration Parameters dialog is
controlling debugging.
Debugging the Function in Simulation
In “Create Model That Uses MATLAB Function Block” on page 29-9, you
created an example model with a MATLAB Function block that calculates the
mean and standard deviation for a set of input values.
To debug the MATLAB Function in this model:
29-23
29
Using the MATLAB Function Block
1 Open thecall_stats_block2 model and double-click its MATLAB
Function block stats to open it for editing.
2 In the MATLAB Function Block Editor, click the dash (-) character in
the left margin of the line:
len = length(vals);
A small red ball appears in the margin of this line, indicating that you
have set a breakpoint.
29-24
Debugging a MATLAB Function Block
3 Begin simulating the model:
If you get any errors or warnings, make corrections before you try to
simulate again. Otherwise, simulation pauses when execution reaches
the breakpoint you set. This is indicated by a small green arrow in the
left margin.
4 Select Step to advance execution.
The execution arrow advances to the next line of stats, which calls the
local function avg.
5 Select Step In.
Execution advances to enter the local function avg. Once you are in a local
function, you can use the Step or Step In commands to advance execution.
If the local function calls another local function, use the Step In icon to
enter it. If you want to execute the remaining lines of the local function,
use Step Out.
6 Select Step to execute the only line in the local function avg. When the
local function avg finishes executing, a green arrow pointing down under
its last line appears.
7 Select Step again to return to the function stats.
29-25
29
Using the MATLAB Function Block
Execution advances to the line after the call to the local function avg.
8 Step again twice to calculate the stdev and to execute the plot function.
The plot function executes in MATLAB:
In the MATLAB Function Block Editor, a green arrow points down under
the last line of code, indicating the completion of the function stats.
9 Select Continue to continue execution of the model.
The computed values of mean and stdev now appear in the Display blocks.
29-26
Debugging a MATLAB Function Block
10 In the MATLAB Function Block Editor, select Quit Debugging to stop
simulation.
Watching Function Variables During Simulation
While you simulate a MATLAB Function block, you can use several tools to
keep track of variable values in the function.
Watching with the Interactive Display
To display the value of a variable in the function of a MATLAB Function
block during simulation:
1 In the MATLAB Function Block Editor, place the mouse cursor over the
variable text and observe the pop-up display.
For example, to watch the variable len during simulation, place the mouse
cursor over the text len in the code. The value of len appears adjacent to
the cursor, as shown:
Watching with the Command Line Debugger
You can report the values for a function variable with the Command Line
Debugger utility in the MATLAB window during simulation. When you reach
a breakpoint, the Command Line Debugger prompt, debug>>, appears. At
this prompt, you can see the value of a variable defined for the MATLAB
Function block by entering its name:
debug>> stdev
1.1180
debug>>
29-27
29
Using the MATLAB Function Block
The Command Line Debugger also provides the following commands during
simulation:
Command
Description
ctrl-c
Quit debugging and terminate simulation.
dbcont
Continue execution to next breakpoint.
dbquit
Quit debugging and terminate simulation.
dbstep
[in|out]
Advance to next program step after a breakpoint is
encountered. Step over or step into/out of a MATLAB local
function.
help
Display help for command line debugging.
print
Display the value of the variable var in the current scope. If
var is a vector or matrix, you can also index into var. For
example, var(1,2).
save
Saves all variables in the current scope to the specified file.
Follows the syntax of the MATLAB save command. To
retrieve variables to the MATLAB base workspace, use load
command after simulation has been ended.
Equivalent to "print " if variable is in the current
scope.
who
Display the variables in the current scope.
whos
Display the size and class (type) of all variables in the
current scope.
You can issue any other MATLAB command at the debug>> prompt, but the
results are executed in the workspace of the MATLAB Function block. To
issue a command in the MATLAB base workspace at the debug>> prompt, use
the evalin command with the first argument 'base' followed by the second
argument command string, for example, evalin('base','whos'). To return
to the MATLAB base workspace, use the dbquit command.
29-28
Debugging a MATLAB Function Block
Watching with MATLAB
You can display the execution result of a MATLAB Function block line by
omitting the terminating semicolon. If you do, execution results for the line
are echoed to the MATLAB window during simulation.
Display Size Limits
The MATLAB Function Block Editor does not display the contents of matrices
that have more than two dimensions or more than 200 elements. For matrices
that exceed these limits, the MATLAB Function Block Editor displays the
shape and base type only.
Checking for Data Range Violations
When you enable debugging, MATLAB Function blocks automatically check
input and output data for data range violations when the values enter or
leave the blocks.
Specifying a Range
To specify a range for input and output data, follow these steps:
1 In the Ports and Data Manager, select the input or output of interest.
The data properties dialog box opens.
2 In the data properties dialog box, select the General tab and enter a limit
range, as described in “Setting General Properties” on page 29-44.
Debugging Tools
Use the following tools during a MATLAB Function block debugging session:
29-29
29
Using the MATLAB Function Block
Tool Button
Description
Access this tool from the Editor tab by
selecting Build Model > Build.
Build
Update
Diagram
Update Ports
Run Model
Stop Model
29-30
Shortcut
Key
Ctrl+B
Check for errors and build a simulation
application (if no errors are found) for the
model containing this MATLAB Function
block.
Access this tool from the Editor tab
by selecting Build Model > Update
Diagram.
Ctrl+D
Check for errors based on the latest
changes you make to the MATLAB
Function block.
Access this tool from the Editor tab by
selecting Build Model > Update Ports.
Ctrl+Shift+A
Updates the ports of the MATLAB
Function block with the latest changes
made to the function argument and
return values without closing the
MATLAB Function Block Editor.
Start simulation of the model containing
the MATLAB Function block. If execution
is paused at a breakpoint, continues
debugging.
F5
Stop simulation of the model containing
the MATLAB Function block.
Alternatively, from the Editor tab,
select Quit Debugging if execution is
paused at a breakpoint.
Shift+F5
Debugging a MATLAB Function Block
Tool Button
Description
Access this tool by selecting
Breakpoints > Set/Clear.
Set/Clear
Shortcut
Key
F12
Set a new breakpoint or clear an existing
breakpoint for the selected line of code
in the MATLAB Function block. The
presence of the text cursor or highlighted
text selects the line. A breakpoint
indicator appears in the on the selected
line.
Alternatively, click the hyphen character
(-) next to the line number. A breakpoint
indicator appears in place of the hyphen.
Click the breakpoint indicator to clear
the breakpoint.
Access this tool by selecting
Breakpoints > Clear All.
Clear All
Step
Step In
None
Clear all existing breakpoints in the
MATLAB Function block code.
Step through the execution of the next
line of code in the MATLAB Function
block. This tool steps past function calls
and does not enter called functions for
line-by-line execution. You can use this
tool only after execution has stopped at a
breakpoint.
F10
Step through the execution of the next
line of code in the MATLAB Function
block. If the line calls a local function,
step into the first line of the local
function. You can use this tool only after
execution has stopped at a breakpoint.
F11
29-31
29
Using the MATLAB Function Block
Tool Button
Step Out
Continue
Quit Debugging
29-32
Description
Shortcut
Key
Step out of line-by-line execution of the
current function or local function. If in
a local function, the debugger continues
to the line following the call to this local
function. You can use this tool only after
execution has stopped at a breakpoint.
Shift+F11
Continue debugging after a pause, such
as stopping at a breakpoint. You can use
this tool only after execution has stopped
at a breakpoint.
F5
Exit debug mode. You can use this tool
only after execution has stopped at a
breakpoint.
Shift+F5
MATLAB Function Block Editor
MATLAB Function Block Editor
In this section...
“Customizing the MATLAB Function Block Editor” on page 29-33
“MATLAB Function Block Editor Tools” on page 29-33
“Editing and Debugging MATLAB Function Block Code” on page 29-34
“Ports and Data Manager” on page 29-37
Customizing the MATLAB Function Block Editor
Use the toolbar icons to customize the appearance of the MATLAB Function
Block Editor in the same manner as the MATLAB editor. See “Adjust Desktop
Appearance”.
MATLAB Function Block Editor Tools
Use the following tools to work with the MATLAB Function block:
Tool Button
Description
Edit Data
Opens the Ports and Data Manager dialog to add or
modify arguments for the current MATLAB Function
block (see “Ports and Data Manager” on page 29-37).
View Report
Opens the MATLAB Function report for the MATLAB
Function block. For more information, see “MATLAB
Function Reports” on page 29-51.
29-33
29
Using the MATLAB Function Block
Tool Button
Description
Simulation
Target
Opens the Simulation Target pane in the
Configuration Parameters dialog to enable
debugging or include custom code. See “Enabling
and Disabling Debugging” on page 29-23 for more
information on debugging
Displays the MATLAB function in its native diagram
without closing the editor.
Go To Diagram
See “Defining Inputs and Outputs” on page 29-14 for an example of defining
an input argument for a MATLAB Function block.
Editing and Debugging MATLAB Function Block Code
Commenting Out a Block of Code
To comment out a block of code in the MATLAB Function Block Editor:
1 Highlight the text that you would like to comment out.
2 Hold the mouse over the highlighted text and then right-click and select
Comment from the context menu. (Alternatively, select a Comment tool
from the Editor tab.
Note To uncomment a block of code, follow the same steps, but select
Uncomment instead of Comment.
Manual Indenting
To indent a block of code manually:
1 Highlight the text that you would like to indent.
2 Select one of the Indent tools on the Editor tab:
29-34
MATLAB Function Block Editor
Tool
Description
Applies smart indenting to selected
text.
Move selected text right one indent
level.
Move selected text left one indent
level.
Opening a Selection
You can open a local function, function, file, or variable from within a file in
the MATLAB Function Block Editor.
To open a selection:
1 Position the cursor in the name of the item you would like to open.
2 Right-click and select Open from the context menu.
The Editor chooses the appropriate tool to open the selection. For more
information, refer to “Opening Files and Functions in the Command Window”.
Note If you open a MATLAB Function block input or output parameter, the
Ports and Data Manager opens with the selected parameter highlighted. You
can use the Ports and Data Manager to modify parameter attributes. For
more information, refer to “Ports and Data Manager” on page 29-37.
Evaluating a Selection
You can use the Evaluate a Selection menu option to report the value for
a MATLAB function variable or equation in the MATLAB window during
simulation.
To evaluate a selection:
1 Highlight the variable or equation that you would like to evaluate.
29-35
29
Using the MATLAB Function Block
2 Hold the mouse over the highlighted text and then right-click and select
Evaluate Selection from the context menu. (Alternatively, select
Evaluate Selection from the Text menu).
When you reach a breakpoint, the MATLAB command Window displays the
value of the variable or equation at the Command Line Debugger prompt.
debug>> stdev
1.1180
debug>>
Note You cannot evaluate a selection while MATLAB is busy, for example,
running a MATLAB file.
Setting Data Scope
To set the data scope of a MATLAB Function block input parameter:
1 Highlight the input parameter that you would like to modify.
2 Hold the mouse over the highlighted text and then right-click and select
Data Scope for from the context menu.
3 Select:
• Input if your input data is provided by the Simulink model via an input
port to the MATLAB Function block.
• Parameter if your input is a variable of the same name in the MATLAB
or model workspace or in the workspace of a masked subsystem
containing this block.
For more information, refer to “Setting General Properties” on page 29-44.
29-36
MATLAB Function Block Editor
Ports and Data Manager
The Ports and Data Manager provides a convenient method for defining
objects and modifying their properties in a MATLAB Function block that
is open and has focus.
The Ports and Data Manager provides the same data definition capabilities
for individual MATLAB Function blocks. as the Model Explorer provides
across the model hierarchy (see “Model Explorer Overview” on page 9-2).
Ports and Data Manager Dialog Box
The Ports and Data Manager dialog box allows you to add and define data
arguments, input triggers, and function call outputs for MATLAB Function
blocks. Using this dialog, you can also modify properties for the MATLAB
Function block and the objects it contains.
The dialog box consists of two panes:
• The Contents (left) pane lists the objects that have been defined for the
MATLAB Function block.
• The Dialog (right) pane displays fields for modifying the properties of the
selected object.
Properties vary according to the scope and type of the object. Therefore, the
Ports and Data Manager properties dialogs are dynamic, displaying only the
property fields that are relevant for the object you add or modify.
When you first open the dialog box, it displays the properties of the MATLAB
Function block.
Opening the Ports and Data Manager
To open the Ports and Data Manager from the MATLAB Function Block
Editor, select Edit Data on the Editor tab. The Ports and Data Manager
appears for the MATLAB Function block that is open and has focus.
Ports and Data Manager Tools
The following tools are specific to the Ports and Data Manager:
29-37
29
Using the MATLAB Function Block
Tool Button
Description
Displays the MATLAB function in the MATLAB
Function Block Editor.
Go to Block
Editor
Show Block
Dialog
Displays the default MATLAB function properties (see
“MATLAB Function Block Properties” on page 29-38).
Use this button to return to the settings used by the
block after viewing data associated with the block
arguments.
MATLAB Function Block Properties
This section describes each property of a MATLAB Function block.
Name. Name of the MATLAB Function block, following the same naming
conventions as for Simulink blocks (see “Manipulate Block Names” on page
23-26).
Update method. Method for activating the MATLAB Function block. You
can choose from the following update methods:
Update
Method
Description
Inherited
(default)
Input from the Simulink model activates the MATLAB
Function block.
If you define an input trigger, the MATLAB Function block
executes in response to a Simulink signal or function-call
event on the trigger port. If you do not define an input trigger,
the MATLAB Function block implicitly inherits triggers
from the model. These implicit events are the sample times
(discrete or continuous) of the signals that provide inputs to
the chart.
If you define data inputs, the MATLAB Function block
samples at the rate of the fastest data input. If you do not
29-38
MATLAB Function Block Editor
Update
Method
Description
define data inputs, the MATLAB Function block samples as
defined by its parent subsystem’s execution behavior.
Discrete
The MATLAB Function block is sampled at the rate you
specify as the block’s Sample Time property. An implicit
event is generated at regular time intervals corresponding to
the specified rate. The sample time is in the same units as
the Simulink simulation time. Note that other blocks in the
model can have different sample times.
Continuous The Simulink software wakes up (samples) the MATLAB
Function block at each step in the simulation, as well as at
intermediate time points that can be requested by the solver.
This method is consistent with the continuous method.
Saturate on integer overflow. Option that determines how the MATLAB
Function block handles overflow conditions during integer operations:
Setting
Action When Overflow Occurs
Enabled
(default)
Saturates an integer by setting it to the maximum positive or
negative value allowed by the word size. Matches MATLAB
behavior.
Disabled
In simulation mode, generates a run-time error. For Simulink
Coder code generation, the behavior depends on your C
language compiler.
Note The Saturate on integer overflow option is relevant only for integer
arithmetic. It has no effect on fixed-point or double-precision arithmetic.
When you enable Saturate on integer overflow, MATLAB adds additional
checks during code generation to detect integer overflow or underflow.
Therefore, it is more efficient to disable this option if you are sure that integer
overflow and underflow will not occur in your MATLAB Function block code.
29-39
29
Using the MATLAB Function Block
Even when you disable this option, the code for a simulation target checks for
integer overflow and underflow. If either condition occurs, simulation stops
and an error is generated. If you enable debugging for the MATLAB Function
block, the debugger displays the error and lets you examine the data.
If you did not enable debugging, the block generates a run-time error:
Overflow detected. Enable debugging for more information.
Note that the code generated by Simulink Coder does not check for integer
overflow or underflow and, therefore, may produce unpredictable results
when Saturate on integer overflow is disabled. In this situation, it is
recommended that you simulate first to test for overflow and underflow before
generating code.
Lock Editor. Option for locking the MATLAB Function Block Editor. When
enabled, this option prevents users from making changes to the MATLAB
Function block.
Treat these inherited Simulink signal types as fi objects.
Setting that determines whether to treat inherited fixed-point and integer
signals as Fixed-Point Toolbox™ fi objects (“Ways to Construct fi Objects”).
• When you select Fixed-point, the MATLAB Function block treats all
fixed-point inputs as Fixed-Point Toolbox fi objects.
• When you select Fixed-point & Integer, the MATLAB Function block
treats all fixed-point and integer inputs as Fixed-Point Toolbox fi objects.
MATLAB Function block fimath. Setting that defines fimath properties
for the MATLAB Function block. The block associates the fimath properties
you specify with the following objects:
• All fixed-point and integer input signals to the MATLAB Function block
that you choose to treat as fi objects.
• All fi and fimath objects constructed in the MATLAB Function block.
You can select one of the following options for the MATLAB Function block
fimath.
29-40
MATLAB Function Block Editor
Setting
Description
Same as
MATLAB
When you select this option, the block uses the same fimath properties as
the current default fimath. The edit box appears dimmed and displays the
current global fimath in read-only form.
29-41
29
Using the MATLAB Function Block
Setting
Description
Specify other
When you select this option, you can specify your own fimath object in the
edit box. You can do so in one of two ways:
• Constructing the fimath object inside the edit box.
• Constructing the fimath object in the MATLAB or model workspace and
then entering its variable name in the edit box. If you use this option
and plan to share your model with others, make sure you define the
variable in the model workspace. See “Sharing Models with Fixed-Point
MATLAB Function Blocks”.
For more information on fimath objects, see “fimath Object Construction”.
Description. Description of the MATLAB Function block.
Document link. Link to documentation for the MATLAB Function block. To
document a MATLAB Function block, set the Document link property to a
Web URL address or MATLAB expression that displays documentation in a
suitable format (for example, an HTML file or text in the MATLAB Command
Window). The MATLAB Function block evaluates the expression when you
click the blue Document link text.
Adding Data to a MATLAB Function Block
You can define data arguments for MATLAB Function blocks using the
following methods:
29-42
Method
For Defining
Reference
Define data directly in
the MATLAB Function
block code
Input and output data
See “Defining Inputs
and Outputs” on page
29-14.
Use the Ports and Data
Manager
Input, output, and
parameter data in the
MATLAB Function
See “Defining Data in
the Ports and Data
MATLAB Function Block Editor
Method
Use the Model Explorer
For Defining
Reference
block that is open and
has focus
Manager” on page
29-43.
Input, output, and
parameter data in
MATLAB Function
blocks at all levels of
the model hierarchy
See “Model Explorer
Overview” on page 9-2
Defining Data in the Ports and Data Manager. To add a data argument
and modify its properties, follow these steps:
1 In the Ports and Data Manager, select Add > Data
The Ports and Data Manager adds a default definition of the data to the
MATLAB Function block.
29-43
29
Using the MATLAB Function Block
2 Modify data properties.
3 Return to the MATLAB Function block properties at any time by selecting
Tools > Block Dialog.
Setting General Properties. You can set the following properties in the
General tab:
Property
Description
Name
Name of the data argument, following the same naming conventions used
in MATLAB.
Scope
Where data resides in memory, relative to its parent. Scope determines the
range of functionality of the data argument. You can set scope to one of the
following values:
• Parameter— Specifies that the source for this data is a variable of the
same name in the MATLAB or model workspace or in the workspace of
a masked subsystem containing this block. If a variable of the same
name exists in more than one of the workspaces visible to the block, the
variable closest to the block in the workspace hierarchy is used (see “Model
Workspaces” on page 4-67).
• Input— Data provided by the model via an input port to the MATLAB
Function block.
• Output— Data provided by the MATLAB Function block via an output
port to the model.
• Data Store Memory— Data provided by a Data Store Memory block in
the model.
For more information, see “Defining Inputs and Outputs” on page 29-14 and
“Add Parameter Arguments” on page 29-75.
Port
29-44
Index of the port associated with the data argument. This property applies
only to input and output data.
MATLAB Function Block Editor
Property
Description
Tunable
Indicates whether the parameter used as the source of this data item is
tunable (see “Tunable Parameters” on page 3-9). This property applies only
to parameter data. Clear this option if the parameter must be a constant
expression, such as for MATLAB toolbox functions supported for code
generation (see “Functions Supported for Code Generation — Alphabetical
List” on page 31-2).
Data must
resolve to
Simulink
signal object
Specifies that the data argument must resolve to a Simulink signal object.
This property applies only to output data. See “Symbol Resolution” on page
4-76 for more information.
Size
Size of the data argument. Size can be a scalar value or a MATLAB vector of
values. Size defaults to –1, which means that it is inherited, as described in
“Inheriting Argument Sizes from Simulink” on page 29-72. This property does
not apply to Data Store Memory data. For more details, see “Size Function
Arguments” on page 29-72.
Variable Size
Indicates whether the size of this data item is variable. This property does
not apply to Data Store Memory data.
Complexity
Indicates real or complex data arguments. You can set complexity to one of
the following values:
• Off— Data argument is a real number
• On— Data argument is a complex number
• Inherited— Data argument inherits complexity based on its scope. Input
and output data inherit complexity from the Simulink signals connected
to them; parameter data inherits complexity from the parameter to which
it is bound.
Sampling
mode
Specifies how an output signal propagates through a model. This property
applies only to data with scope equal to Output. You can set sampling mode
to one of the following values:
• Sample based: Propagate the signal sample by sample (default)
• Frame based: Propagate the signal in batches of samples
29-45
29
Using the MATLAB Function Block
Property
Description
Type
Type of data object. You can specify the data type by:
• Selecting a built-in type from the Type drop down list.
• Entering an expression in the Type field that evaluates to a data type (see
“Data Types” on page 43-2).
• Using the Data Type Assistant to specify a data Mode, then specifying
the data type based on that mode.
Note To display the Data Type Assistant, click the Show data type
assistant button:
For more information, see “Specifying Argument Types” on page 29-64.
Lock data type
setting against
changes by
the fixed-point
tools
Specify whether you want to prevent replacement of the current data
type with a type chosen by the Fixed-Point Tool or Fixed-Point Advisor.
The default setting allows replacement. See Scaling for instructions on
autoscaling fixed-point data.
Limit range
Specify the range of acceptable values for input or output data. The MATLAB
Function block uses this range to validate the input or output as it enters or
leaves the block. You can enter an expression or parameter that evaluates to
a numeric scalar value.
• Minimum — The smallest value allowed for the data item during
simulation. The default value is -inf.
• Maximum — The largest value allowed for the data item during
simulation. The default value is inf.
Setting Description Properties. You can set the following properties on the
Description tab:
29-46
MATLAB Function Block Editor
Property
Description
Save final
value
to base
workspace
The MATLAB Function block assigns the value of the data
argument to a variable of the same name in the MATLAB
base workspace at the end of simulation.
Description Description of the data argument.
Document
link
Link to documentation for the data argument. You can enter
a Web URL address or a MATLAB command that displays
documentation in a suitable format, such as an HTML file or
text in the MATLAB Command Window. When you click
the blue text, Document link, displayed at the bottom of
the Data properties dialog, the MATLAB Function block
evaluates the link and displays the documentation.
Adding Input Triggers to a MATLAB Function Block
An input trigger is an event on the input port that causes the MATLAB
Function block to execute. See “Triggered Subsystems” on page 7-20.
You can define the following types of triggers in MATLAB Function blocks:
• Rising
• Falling
• Either (rising or falling)
• Function call
For a description of each trigger type, see “Setting Input Trigger Properties”
on page 29-48.
Use the Ports and Data Manager to add input triggers to a MATLAB Function
block that is open and has focus. To add an input trigger and modify its
properties, follow these steps:
1 In the Ports and Data Manager, select Add > Input Trigger.
29-47
29
Using the MATLAB Function Block
The Ports and Data Manager adds a default definition of the new input
trigger to the MATLAB Function block and displays the Trigger properties
dialog.
2 Modify trigger properties.
3 Return to the MATLAB Function block properties at any time by selecting
Tools > Block Dialog.
The Trigger Properties Dialog. The Trigger properties dialog in the Ports
and Data Manager allows you to set and modify the properties of input
triggers in MATLAB Function blocks.
To open the Trigger properties dialog, select an input trigger in the Contents
pane.
Setting Input Trigger Properties. You can set the following properties in
the Trigger properties dialog:
Property
Description
Name
Name of the input trigger, following the same naming
conventions used in MATLAB.
Port
Index of the port associated with the input trigger. The
default value is 1.
Trigger
Type of event that triggers execution of the MATLAB
Function block. You can select one of the following types
of triggers:
• Rising (default) — Triggers execution of the MATLAB
Function block when the control signal rises from a
negative or zero value to a positive value (or zero if the
initial value is negative).
• Falling— Triggers execution of the MATLAB Function
block when the control signal falls from a positive or zero
value to a negative value (or zero if the initial value is
positive).
• Either— Triggers execution of the MATLAB Function
block when the control signal is either rising or falling.
29-48
MATLAB Function Block Editor
Property
Description
• Function call— Triggers execution of the MATLAB
Function block from a block that outputs function-call
events, or from an S-function
Description
Description of the input trigger.
Document
link
Link to documentation for the input trigger. You can
enter a Web URL address or a MATLAB command that
displays documentation in a suitable format, such as an
HTML file or text in the MATLAB Command Window.
When you click the blue text that reads Document link
displayed at the bottom of the Trigger properties dialog,
the MATLAB Function block evaluates the link and
displays the documentation.
Adding Function Call Outputs to a MATLAB Function Block
A function call output is an event on the output port of a MATLAB Function
block that causes a function-call subsystem in the Simulink model to execute.
A function-call subsystem is a subsystem that another block can invoke
directly during a simulation. See “Function-Call Subsystems” on page 7-30.
Use the Ports and Data Manager to add and modify function call outputs to a
MATLAB Function block that is open and has focus. To add a function call
output and modify its properties, follow these steps:
1 In the Ports and Data Manager, select Add > Function Call Output.
The Ports and Data Manager adds a default definition of the new function
call output to the MATLAB Function block and displays the Function Call
properties dialog.
2 Modify function call output properties.
3 Return to the MATLAB Function block properties at any time by selecting
Tools > Block Dialog.
29-49
29
Using the MATLAB Function Block
The Function Call Properties Dialog. The Function Call properties dialog
in the Ports and Data Manager allows you to edit the properties of function
call outputs in MATLAB Function blocks.
To open the Function Call properties dialog, select a function call output
in the Contents pane.
Setting Function Call Output Properties. You can set the following
properties in the Function Call properties dialog:
Property
Description
Name
Name of the function call output, following the same naming
conventions used in MATLAB.
Port
Index of the port associated with the function call output.
Function call output ports are numbered sequentially after
input and output ports.
Description Description of the function call output.
Document
link
29-50
Link to documentation for the function call output. You
can enter a Web URL address or a MATLAB command
that displays documentation in a suitable format, such as
an HTML file or text in the MATLAB Command Window.
When you click Document link displayed at the bottom of
the Function Call properties dialog, the MATLAB Function
block evaluates the link and displays the documentation.
MATLAB Function Reports
MATLAB Function Reports
In this section...
“About MATLAB Function Reports” on page 29-51
“Location of MATLAB Function Reports” on page 29-51
“Opening MATLAB Function Reports” on page 29-52
“Description of MATLAB Function Reports” on page 29-52
“Viewing Your MATLAB Function Code” on page 29-52
“Viewing Call Stack Information” on page 29-54
“Viewing the Compilation Summary Information” on page 29-54
“Viewing Error and Warning Messages” on page 29-54
“Viewing Variables in Your MATLAB Code” on page 29-56
“Keyboard Shortcuts for the MATLAB Function Report” on page 29-61
“Report Limitations” on page 29-62
About MATLAB Function Reports
Whenever you build a Simulink model that contains MATLAB Function
blocks, Simulink automatically generates a report in HTML format for each
MATLAB Function block in your model. The report helps you debug your
MATLAB functions and verify that they are suitable for code generation.
The report provides links to your MATLAB functions and compile-time type
information for the variables and expressions in these functions. If your model
fails to build, this information simplifies finding sources of error messages
and aids understanding of type propagation rules.
Note If you have a Stateflow license, there is one report for each Stateflow
chart, regardless of the number of MATLAB functions it contains.
Location of MATLAB Function Reports
The code generation software provides a report for each MATLAB Function
block in the model model_name at the following location:
29-51
29
Using the MATLAB Function Block
slprj/_sfprj/
model_name/_self/
sfun/html/
Opening MATLAB Function Reports
Use one of the following methods:
• In the MATLAB Function Block Editor, select View Report.
• In the Simulation Diagnostics window, select the report link if
compilation errors occur.
Description of MATLAB Function Reports
When you build the MATLAB function, the code generation software
generates an HTML report. The report provides the following information,
as applicable:
• MATLAB code information, including a list of all functions and their
compilation status
• Call stack information, providing information on the nesting of function
calls
• Summary of compilation results, including type of target and number of
warnings or errors
• List of all error and warning messages
• List of all variables in your MATLAB function
Viewing Your MATLAB Function Code
To view your MATLAB function code, click the MATLAB code tab. The report
displays the MATLAB code for the function highlighted in the list on this tab.
The MATLAB code tab provides:
• A list of the MATLAB functions that have been compiled. The report
displays icons next to each function name to indicate whether compilation
was successful:
-
29-52
Errors in function.
MATLAB Function Reports
-
Warnings in function.
Successful compilation, no errors or warnings.
• A filter control that you can use to sort your functions by:
-
Size
Complexity
Class
Viewing Local Functions
The report annotates the local function with the name of the parent function
in the list of functions on the MATLAB code tab.
For example, if the MATLAB function fcn1 contains the local function subfcn
and fcn2 contains the local function subfcn2, the report displays:
fcn1 > subfcn1
fcn2 > subfcn2
Viewing Specializations
If your MATLAB function calls the same function with different types of
inputs, the report numbers each of these specializations in the list of
functions on the MATLAB code tab.
For example, if the function fcn calls the function subfcn with different
types of inputs:
function y = fcn(u) %#codegen
% Specializations
y = y + subfcn(single(u));
y = y + subfcn(double(u));
The report numbers the specializations in the list of functions.
fcn > subfcn > 1
fcn > subfcn > 2
29-53
29
Using the MATLAB Function Block
Viewing Call Stack Information
The report provides call stack information:
• On the Call stack tab.
• In the list of Callers.
If a function is called from more than one function, this list provides details
of each call site. Otherwise, the list is disabled.
Viewing Call Stack Information on the Call Stack Tab
To view call stack information, click the Call stack tab. The call stack lists
the functions in the order that the top-level function calls them. It also lists
the local functions that each function calls.
Viewing Function Call Sites in the Callers List
If a function is called from more than one function, this list provides details
of each call site. To navigate between call sites, select a call site from the
Callers list. If the function is not called more than once, this list is disabled.
Viewing the Compilation Summary Information
To view a summary of the compilation results, including type of target and
number of errors or warnings, click the Summary tab.
Viewing Error and Warning Messages
The report provides information about errors and warnings. If errors occur
during simulation of a Simulink model, simulation stops. If warnings occur,
but no errors, simulation of the model continues.
The report provides information about warnings and errors by listing all
errors and warnings in chronological order in the All Messages tab.
29-54
MATLAB Function Reports
Viewing Errors and Warnings in the All Messages Tab
If errors or warnings occurred during compilation, click the All Messages tab
to view a complete list of these messages. The report lists the messages in
the order that the compiler detects them. It is best practice to address the
first message in the list, because often subsequent errors and warnings are
related to the first message.
To locate the offending line of code for an error or warning in the list, click
the message in the list. The report highlights errors in the list and MATLAB
code in red and warnings in orange. Click the blue line number next to the
offending line of code in the MATLAB code pane to go to the error in the
source file.
Note You can fix errors only in the source file.
29-55
29
Using the MATLAB Function Block
Viewing Error and Warning Information in Your MATLAB Code
If errors or warnings occurred during compilation, the report underlines them
in your MATLAB code. The report underlines errors in red and warnings in
orange. To learn more about a particular error or warning, place your pointer
over the underlined text.
Viewing Variables in Your MATLAB Code
The report provides compile-time type information for the variables and
expressions in your MATLAB code, including name, type, size, complexity,
and class. It also provides type information for fixed-point data types,
including word length and fraction length. You can use this type information
to find sources of error messages and to understand type propagation rules.
You can view information about the variables in your MATLAB code:
• On the Variables tab, view the list
• In your MATLAB code, place your pointer over the variable name
Viewing Variables in the Variables Tab
To view a list of all the variables in your MATLAB function, click the
Variables tab. The report displays a complete list of variables in the order
that they appear in the function selected on the MATLAB code tab. Clicking
a variable in the list highlights all instances of that variable, and scrolls the
MATLAB code pane so that you can view the first instance.
The report provides the following information about each variable, as
applicable.
• Order
• Name
• Type
• Size
• Complexity
• Class
29-56
MATLAB Function Reports
• DataTypeMode (DT mode) — for fixed-point data types only. For more
information, see “DataTypeMode”.
• Signed — sign information for built-in data types, signedness information
for fixed-point data types
• Word length (WL) — for fixed-point data types only
• Fraction length (FL) — for fixed-point data types only
Note For more information on viewing fixed-point data types, see “Create
and Use Fixed-Point Code Generation Reports”.
It only displays a column if at least one variable in the code has information
in that column. For example, if the code does not contain any fixed-point data
types, the report does not display the DT mode, WL or FL columns.
Sorting Variables in the Variables Tab. By default, the report lists the
variables in the order that they appear in the selected function.
You can sort the variables by clicking the column headings on the Variables
tab. To sort the variables by multiple columns, hold down the Shift key when
clicking the column headings.
To restore the list to the original order, click the Order column heading.
Viewing Structures on the Variables Tab. You can expand structures
listed on the Variables tab to display the field properties.
29-57
29
Using the MATLAB Function Block
If you sort the variables by type, size, complexity or class, a structure and its
fields might not appear sequentially in the list. To restore the list to the
original order, click the Order column heading.
Viewing Information About Variable-Size Arrays in the Variables
Tab. For variable-size arrays, the Size field includes information on the
computed maximum size of the array. The size of each array dimension that
varies is prefixed with a colon :.
In the following report, variable A is variable-size. Its maximum computed
size is 1×100.
If the code generation software cannot compute the maximum size of a
variable-size array, the report displays the size as :?.
If you declare a variable-size array and then subsequently fix the dimensions
of this array in the code, the report appends * to the size of the variable. In
the generated C code, this variable appears as a variable-size array, but the
size of its dimensions do not change during execution.
29-58
MATLAB Function Reports
For more information on how to use the size information for variable-sized
arrays, see “Variable-Size Data Definition for Code Generation”.
Viewing Renamed Variables in the Variables Tab. If your MATLAB
function reuses a variable with different size, type, or complexity, the code
generation software attempts to create separate, uniquely named variables
in the generated code. For more information, see “Reuse the Same Variable
with Different Properties”. The report numbers the renamed variables in
the list on the Variables tab. When you place your pointer over a renamed
variable, the report highlights only the instances of this variable that share
the same data type, size, and complexity.
For example, suppose your code uses the variable t in a for-loop to hold a
scalar double, and reuses it outside the for-loop to hold a 5x5 matrix. The
report displays two variables, t>1 and t>2 in the list on the Variables tab.
29-59
29
Using the MATLAB Function Block
Viewing Simulation Minimum and Maximum Values in the Variables
Tab. If you have a Simulink Fixed Point license, and you simulate your
model using the Fixed-Point Tool set up to log the minimum and maximum
values, you can view these values in the MATLAB Function Report. For
more information, see “Log Simulation Minimum and Maximum Values for a
MATLAB Function Block”.
Viewing Information About Variables and Expressions in Your
MATLAB Function Code
To view information about a particular variable or expression in your
MATLAB function code, on the MATLAB code pane, place your pointer
over the variable name or expression. The report highlights variables and
expressions in different colors:
Green, when the variable has data type information at this location
in the code.
For variable-size arrays, the Size field includes information on the computed
maximum size of the array. The size of each array dimension that varies is
prefixed with a colon :. Here the array A is variable-sized with a maximum
computed size of 1 x 100.
29-60
MATLAB Function Reports
Pink, when the variable has no data type information.
Purple, information about expressions. You can also view information
about expressions in your MATLAB code. On the MATLAB code pane, place
your pointer over an expression . The report highlights expressions in purple
and provides more detailed information.
Red, when there is error information for an expression. If the code
generation software cannot compute the maximum size of a variable-size
array, the report underlines the variable name and provides error information.
Keyboard Shortcuts for the MATLAB Function Report
You can use the following keyboard shortcuts to navigate between the
different panes in the MATLAB Function report. Once you have selected a
pane, use the Tab key to advance through data in that pane.
29-61
29
Using the MATLAB Function Block
To select:
Use:
MATLAB Code Tab
Ctrl+m
Call Stack Tab
Ctrl+k
MATLAB Code Pane
Ctrl+w
Summary Tab
Ctrl+s
All Messages Tab
Ctrl+a
Variables Tab
Ctrl+v
Report Limitations
The report displays information about the variables and expressions in your
MATLAB code with the following limitations:
varargin and varargout
The report does not support varargin and varargout arrays.
Loop Unrolling
The report does not display full information for unrolled loops. It displays
data types of one arbitrary iteration.
Dead Code
The report does not display information about any dead code.
Structures
The report does not provide complete information about structures.
• On the MATLAB code pane, the report does not provide information about
all structure fields in the struct() constructor.
• On the MATLAB code pane, if a structure has a nonscalar field, and an
expression accesses an element of this field, the report does not provide
information for the field.
29-62
MATLAB Function Reports
Column Headings on Variables Tab
If you scroll through the list of variables, the report does not display the
column headings on the Variables tab.
Multiline Matrices
On the MATLAB code pane, the report does not support selection of
multiline matrices. It supports only selection of individual lines at a time.
For example, if you place your pointer over the following matrix, you cannot
select the entire matrix.
out1 = [1 2 3;
4 5 6];
The report does support selection of single line matrices.
out1 = [1 2 3; 4 5 6];
29-63
29
Using the MATLAB Function Block
Type Function Arguments
In this section...
“About Function Arguments” on page 29-64
“Specifying Argument Types” on page 29-64
“Inheriting Argument Data Types” on page 29-66
“Built-In Data Types for Arguments” on page 29-67
“Specifying Argument Types with Expressions” on page 29-68
“Specifying Simulink® Fixed Point™ Data Properties” on page 29-68
About Function Arguments
You create function arguments for a MATLAB Function block by entering
them in its function header in the MATLAB Function Block Editor. When you
define arguments, the Simulink software creates corresponding ports on the
MATLAB Function block that you can attach to signals. You can select a data
type mode for each argument that you define for a MATLAB Function block.
Each data type mode presents its own set of options for selecting a data type.
By default, the data type mode for MATLAB Function block function
arguments is Inherited. This means that the function argument inherits
its data type from the incoming or outgoing signal. To override the default
type, you first choose a data type mode and then select a data type based
on the mode.
Specifying Argument Types
To specify the type of a MATLAB Function block function argument:
1 From the MATLAB Function Block Editor, select Edit Data to open the
Ports and Data Manager.
29-64
Type Function Arguments
2 In the left pane, select the argument of interest.
3 In the Data properties dialog box (right pane), click the Show data type
to display the Data Type Assistant. Then, choose
assistant button
an option from the Mode drop-down menu.
The Data properties dialog box changes dynamically to display additional
fields for specifying the data type associated with the mode.
4 Based on the mode you select, specify a desired data type:
Mode
What to Specify
Inherit (default)
You cannot specify a value. The data type is inherited from previously-defined
data, based on the scope you selected for the MATLAB Function block
function argument:
• If scope is Input, data type is inherited from the input signal on the
designated port.
• If scope is Output, data type is inherited from the output signal on the
designated port.
• If scope is Parameter, data type is inherited from the associated
parameter, which can be defined in the Simulink masked subsystem or
the MATLAB workspace.
See “Inheriting Argument Data Types” on page 29-66.
Built in
Select from the drop-down list of supported data types, as described in
“Built-In Data Types for Arguments” on page 29-67.
Fixed point
Specify the fixed-point data properties as described in “Specifying Simulink®
Fixed Point™ Data Properties” on page 29-68.
Expression
Enter an expression that evaluates to a data type, as described in “Specifying
Argument Types with Expressions” on page 29-68.
29-65
29
Using the MATLAB Function Block
Mode
What to Specify
Bus Object
In the Bus object field, enter the name of a Simulink.Bus object to define
the properties of a MATLAB structure. You must define the bus object in
the base workspace. See “How Structure Inputs and Outputs Interface with
Bus Signals” on page 29-81.
Note You can click the Edit button to create or modify Simulink.Bus
objects using the Simulink Bus Editor (see “Manage Bus Objects with the
Bus Editor” on page 48-24).
Enumerated
In the Enumerated field, enter the name of a Simulink.IntEnumType object
that you define in the base workspace. See “Enumerated Types Supported in
MATLAB Function Blocks” on page 29-105 and “Define Enumerated Data
Types for MATLAB Function Blocks” on page 29-106.
Inheriting Argument Data Types
MATLAB Function block function arguments can inherit their data types,
including fixed point types, from the signals to which they are connected. ,
and set data type mode using one of these methods:
1 Select the argument of interest in the Ports and Data Manager
2 In the Data properties dialog, select Inherit:
Same as Simulink from
the Type drop-down menu.
See “Built-In Data Types for Arguments” on page 29-67 for a list of supported
data types.
Note An argument can also inherit its complexity (whether its value is a
real or complex number) from the signal that is connected to it. To inherit
complexity, set the Complexity field on the Data properties dialog to
Inherited.
29-66
Type Function Arguments
After you build the model, the Compiled Type column of the Ports and
Data Manager gives the actual type inherited from Simulink in the compiled
simulation application.
The inherited type of output data is inferred from diagram actions that store
values in the specified output. In the preceding example, the variables
mean and stdev are computed from operations with double operands, which
yield results of type double. If the expected type matches the inferred type,
inheritance is successful. In all other cases, a mismatch occurs during build
time.
Note Library MATLAB Function blocks can have inherited data types,
sizes, and complexities like ordinary MATLAB Function blocks. However,
all instances of the library block in a given model must have inputs with
the same properties.
Built-In Data Types for Arguments
When you select Built-in for Data type mode, the Data properties dialog
displays a Data type field that provides a drop-down list of supported data
types. You can also choose a data type from the Data Type column in the
Ports and Data Manager. The supported data types are:
Data Type
Description
double
64-bit double-precision floating point
single
32-bit single-precision floating point
int32
32-bit signed integer
int16
16-bit signed integer
int8
8-bit signed integer
uint32
32-bit unsigned integer
uint16
16-bit unsigned integer
uint8
8-bit unsigned integer
boolean
Boolean (1 = true; 0 = false)
29-67
29
Using the MATLAB Function Block
Specifying Argument Types with Expressions
You can specify the types of MATLAB Function block function arguments as
expressions in the Ports and Data Manager.
1 Select from the Type drop-down menu of the
Data properties dialog.
2 In the Type field, replace “” with an expression
that evaluates to a data type. The following expressions are allowed:
• Alias type from the MATLAB workspace, as described in “Creating
a Data Type Alias”.
• fixdt function to create a Simulink.NumericType object describing a
fixed-point or floating-point data type
• type operator, to base the type on previously defined data
Specifying Simulink Fixed Point Data Properties
MATLAB Function blocks can represent signals and parameter values
as fixed-point numbers. To simulate models that use fixed-point data in
MATLAB Function blocks, you must install the Simulink Fixed Point product
on your system.
You can set the following fixed-point properties:
Signedness. Select whether you want the fixed-point data to be Signed
or Unsigned. Signed data can represent positive and negative quantities.
Unsigned data represents positive values only. The default is Signed.
Word length. Specify the size (in bits) of the word that will hold the
quantized integer. Large word sizes represent large quantities with greater
precision than small word sizes. Word length can be any integer between 0
and 128 bits. The default is 16.
Scaling. Specify the method for scaling your fixed point data to avoid
overflow conditions and minimize quantization errors. You can select the
following scaling modes:
29-68
Type Function Arguments
Scaling
Mode
Description
Binary
point
If you select this mode, the Data Type Assistant displays the Fraction Length
field, specifying the binary point location.
(default)
Binary points can be positive or negative integers. A positive integer moves the
binary point left of the rightmost bit by that amount. For example, an entry of 2
sets the binary point in front of the second bit from the right. A negative integer
moves the binary point further right of the rightmost bit by that amount, as
in this example:
The default is 0.
Slope and
bias
If you select this mode, the Data Type Assistant displays fields for entering
the Slope and Bias.
• Slope can be any positive real number. The default is 1.0.
• Bias can be any real number. The default value is 0.0.
You can enter slope and bias as expressions that contain parameters defined
in the MATLAB workspace.
Note You should use binary-point scaling whenever possible to simplify
the implementation of fixed-point data in generated code. Operations with
fixed-point data using binary-point scaling are performed with simple bit
shifts and eliminate the expensive code implementations required for separate
slope and bias values.
Data type override. Specify whether the data type override setting is
Inherit (default) or Off.
29-69
29
Using the MATLAB Function Block
Calculate Best-Precision Scaling. The Simulink software can automatically
calculate “best-precision” values for both Binary point and Slope and
bias scaling, based on the Limit range properties you specify on the Value
Attributes tab.
To automatically calculate best precision scaling values:
1 Specify Minimum, Maximum, or both Limit range properties.
2 Click Calculate Best-Precision Scaling.
The Simulink software calculates the scaling values, then displays them in
either the Fraction Length, or Slope and Bias fields.
Note The Limit range properties do not apply to Constant or Parameter
scopes. Therefore, Simulink cannot calculate best-precision scaling for these
scopes.
Fixed-point Details. You can view the following Fixed-point details:
29-70
Fixed-point Detail
Description
Representable maximum
The maximum number that can be
represented by the chosen data type,
sign, word length and fraction length
(or data type, sign, slope and bias).
Maximum
The maximum value specified on the
Value Attributes tab.
Minimum
The minimum value specified on the
Value Attributes tab.
Representable minimum
The minimum number that can be
represented by the chosen data type,
sign, word length and fraction length
(or data type, sign, slope and bias).
Precision
The precision for the given word
length and fraction length (or slope
and bias).
Type Function Arguments
Lock data type setting against changes by the fixed-point tools.
Specify whether you want to prevent replacement of the current data
type with a type chosen by the Fixed-Point Tool or Fixed-Point Advisor.
The default setting allows replacement. For instructions on autoscaling
fixed-point data, see “Scaling”.
Using Data Type Override with the MATLAB Function Block
If you set the Data Type Override mode to Double or Single in Simulink,
the MATLAB Function block sets the type of all inherited input signals and
parameters to fi double or fi single objects respectively (see “MATLAB
Function Block with Data Type Override” for more information). You must
check the data types of your inherited input signals and parameters and
use the Ports and Data Manager (see “Ports and Data Manager” on page
29-37) to set explicit types for any inputs that should not be fixed-point. Some
operations, such as sin, are not applicable to fixed-point objects.
Note If you do not set the correct input types explicitly, you may encounter
compilation problems after setting Data Type Override.
How Do I Set Data Type Override?
To set Data Type Override, follow these steps:
1 From the Simulink Analysis menu, select Fixed-Point Tool.
2 Set the value of the Data type override parameter to Double or Single.
29-71
29
Using the MATLAB Function Block
Size Function Arguments
In this section...
“Specifying Argument Size” on page 29-72
“Inheriting Argument Sizes from Simulink” on page 29-72
“Specifying Argument Sizes with Expressions” on page 29-73
Specifying Argument Size
To examine or specify the size of an argument, follow these steps:
1 From the MATLAB Function Block Editor, select Edit Data.
2 Enter the size of the argument in the Size field of the Data properties
dialog, located in the General pane.
Note The default value is -1, indicating that size is inherited, as described
in “Inheriting Argument Sizes from Simulink” on page 29-72.
Inheriting Argument Sizes from Simulink
Size defaults to -1, which means that the data argument inherits its size from
Simulink based on its scope:
For Scope
Inherits Size
Input
From the Simulink input signal connected to the argument.
Output
From the Simulink output signal connected to the argument.
Parameter
From the Simulink or MATLAB parameter to which it is
bound. See “Add Parameter Arguments” on page 29-75.
After you compile the model, the Compiled Size column in the Contents
pane displays the actual size used in the compiled simulation application.
The size of an output argument is the size of the value that is assigned to it. If
the expected size in the Simulink model does not match, a mismatch error
occurs during compilation of the model.
29-72
Size Function Arguments
Note No arguments with inherited sizes are allowed for MATLAB Function
blocks in a library.
Specifying Argument Sizes with Expressions
The size of a data argument can be a scalar value or a MATLAB vector of
values.
To specify size as a scalar, set the Size field to 1 or leave it blank. To specify
Size as a vector, enter an array of up to two dimensions in [row column]
format where
• Number of dimensions equals the length of the vector.
• Size of each dimension corresponds to the value of each element of the
vector.
For example, a value of [2 4] defines a 2-by-4 matrix. To define a row vector
of size 5, set the Size field to [1 5]. To define a column vector of size 6, set
the Size field to [6 1] or just 6. You can enter a MATLAB expression for
each [row column] element in the Size field. Each expression can use one
or more of the following elements:
• Numeric constants
• Arithmetic operators, restricted to +, -, *, and /
• Parameters defined in the MATLAB Workspace or the parent Simulink
masked subsystem
• Calls to the MATLAB functions min, max, and size
The following examples are valid expressions for Size:
k+1
size(x)
min(size(y),k)
In these examples, k, x, and y are variables of scope Parameter.
29-73
29
Using the MATLAB Function Block
Once you build the model, the Compiled Size column displays the actual size
used in the compiled simulation application.
29-74
Add Parameter Arguments
Add Parameter Arguments
Parameter arguments for MATLAB Function blocks do not take their
values from signals in the Simulink model. Instead, their values come from
parameters defined in a parent Simulink masked subsystem or variables
defined in the MATLAB base workspace. Using parameters allows you to pass
read-only constants in the Simulink model to the MATLAB Function block.
To add a parameter argument to a function for a MATLAB Function block.
1 In the MATLAB Function Block Editor, add an argument to the function
header of the MATLAB Function block.
The name of the argument must be identical to the name of the masked
subsystem parameter or MATLAB variable that you want to pass to the
MATLAB Function block. For information on declaring parameters for
masked subsystems, see “How Mask Parameters Work” on page 26-4.
2 Bring focus to the MATLAB Function block.
The new argument appears as an input port in the Simulink diagram.
3 In the MATLAB Function Block Editor, select Edit Data.
4 Select the new argument.
5 Set Scope to Parameter.
6 Examine the MATLAB Function block.
The input port no longer appears for the parameter argument.
Note Parameter arguments appear as arguments in the function header
of the MATLAB Function block to maintain MATLAB consistency. As a
result, you can test functions in a MATLAB Function block by copying and
pasting them to MATLAB.
29-75
29
Using the MATLAB Function Block
Resolve Signal Objects for Output Data
In this section...
“Implicit Signal Resolution” on page 29-76
“Eliminating Warnings for Implicit Signal Resolution in the Model” on
page 29-76
“Disabling Implicit Signal Resolution for a MATLAB Function Block” on
page 29-77
“Forcing Explicit Signal Resolution for an Output Data Signal” on page
29-77
Implicit Signal Resolution
MATLAB Function blocks participate in signal resolution with Simulink
signal objects. By default, output data from MATLAB Function blocks become
associated with Simulink signal objects of the same name during a process
called implicit signal resolution, as described in Simulink.Signal.
By default, implicit signal resolution generates a warning when you update
the chart in the Simulink model. The following sections show you how to
manage implicit signal resolution at various levels of the model hierarchy.
See “Symbol Resolution” on page 4-76 and “Explicit and Implicit Symbol
Resolution” on page 4-80 for more information.
Eliminating Warnings for Implicit Signal Resolution
in the Model
To enable implicit signal resolution for all signals in a model, but eliminate
the attendant warnings, follow these steps:
1 In the Simulink Model Editor, select Simulation > Model Configuration
Parameters.
The Configuration Parameters dialog appears.
2 In the left pane of the Configuration Parameters dialog, under Diagnostics,
select Data Validity.
29-76
Resolve Signal Objects for Output Data
Data Validity configuration parameters appear in the right pane.
3 In the Signal resolution field, select Explicit and implicit.
Disabling Implicit Signal Resolution for a MATLAB
Function Block
To disable implicit signal resolution for a MATLAB Function block in your
model, follow these steps:
1 Right-click the MATLAB Function block and select Block Parameters
(Subsystem) in the context menu.
The Block Parameters dialog opens.
2 In the Permit hierarchical resolution field, select ExplicitOnly or None,
and click OK.
Forcing Explicit Signal Resolution for an Output Data
Signal
To force signal resolution for an output signal in a MATLAB Function block,
follow these steps:
1 In the Simulink model, right-click the signal line connected to the output
that you want to resolve and select Properties from the context menu.
2 In the Signal Properties dialog, enter a name for the signal that corresponds
to the signal object.
3 Select the Signal name must resolve to Simulink signal object check
box and click OK.
29-77
29
Using the MATLAB Function Block
Types of Structures in MATLAB Function Blocks
In MATLAB Function blocks, you can define structure data as inputs or
outputs that interact with bus signals. MATLAB Function blocks also support
arrays of buses (for more information, see “Combine Buses into an Array
of Buses” on page 48-77). You can also define structures inside MATLAB
functions that are not part of MATLAB Function blocks (see “Structure
Definition for Code Generation” on page 36-2.
The following table summarizes how to create different types of structures in
MATLAB Function blocks:
Scope
Input
How to Create
Details
Create structure data with scope of
You can create structure
data as inputs or outputs
in the top-level MATLAB
function for interfacing
to other environments.
See “Create Structures
in MATLAB Function
Blocks” on page 29-84.
Input.
Output
Create structure data with scope of
Output.
Local
Create a local variable implicitly in
a MATLAB function.
See “Define Scalar
Structures for Code
Generation” on page
36-4.
Persistent
Declare a variable to be persistent
in a MATLAB function.
See “Make Structures
Persistent” on page 36-9.
Parameter Create structure data with scope of
Parameter
See “Define and Use
Structure Parameters”
on page 29-91.
Structures in MATLAB Function blocks can contain fields of any type and
size, including muxed signals, buses, and arrays of structures.
29-78
Attach Bus Signals to MATLAB Function Blocks
Attach Bus Signals to MATLAB Function Blocks
For an example of how to use structures in a MATLAB Function block, open
the model emldemo_bus_struct.
In this model, a MATLAB Function block receives a bus signal using the
structure inbus at input port 1 and outputs two bus signals from the
structures outbus at output port 1 and outbus1 at output port 2. The input
signal comes from the Bus Creator block MainBusCreator, which bundles
signals ele1, ele2, and ele3. The signal ele3 is the output of another
Bus Creator block SubBusCreator, which bundles the signals a1 and a2.
The structure outbus connects to a Bus Selector block BusSelector1; the
structure outbus1 connects to another Bus Selector block BusSelector3.
To explore the MATLAB function fcn, double-click the MATLAB Function
block. Notice that the code implicitly defines a local structure variable
mystruct using the struct function, and uses this local structure variable to
initialize the value of the first output outbus. It initializes the second output
outbus1 to the value of field ele3 of structure inbus.
Structure Definitions in Example
Here are the definitions of the structures in the MATLAB Function block in
the example, as they appear in the Ports and Data Manager:
Bus Objects Define Structure Inputs and Outputs
Each structure input and output must be defined by a Simulink.Bus object
in the base workspace (see “Create Structures in MATLAB Function Blocks”
on page 29-84). This means that the structure shares the same properties as
the bus object, including number, name, type, and sequence of fields. In this
example, the following bus objects define the structure inputs and outputs:
29-79
29
Using the MATLAB Function Block
The Simulink.Bus object MainBus defines structure input inbus and
structure output outbus. The Simulink.Bus object SubBus defines structure
output outbus1. Based on these definitions, inbus and outbus have the
same properties as MainBus and, therefore, reference their fields by the same
names as the fields in MainBus, using dot notation (see “Index Substructures
and Fields” on page 29-83). Similarly, outbus1 references its fields by the
same names as the fields in SubBus. Here are the field references for each
structure in this example:
Structure
First Field
Second Field
Third Field
inbus
inbus.ele1
inbus.ele2
inbus.ele3
outbus
outbus.ele1
outbus.ele2
outbus.ele3
outbus1
outbus1.a1
outbus1.a2
—
To learn how to define structures in MATLAB Function blocks, see “Create
Structures in MATLAB Function Blocks” on page 29-84.
29-80
How Structure Inputs and Outputs Interface with Bus Signals
How Structure Inputs and Outputs Interface with Bus
Signals
Buses in a Simulink model appear inside the MATLAB Function block as
structures; structure outputs from the MATLAB Function block appear as
buses in Simulink models. When you create structure inputs, the MATLAB
Function block determines the type, size, and complexity of the structure from
the input signal. When you create structure outputs, you must define their
type, size, and complexity in the MATLAB function.
You connect structure inputs and outputs from MATLAB Function blocks
to any bus signal, including:
• Blocks that output bus signals — such as Bus Creator blocks
• Blocks that accept bus signals as input — such as Bus Selector and Gain
blocks
• S-Function blocks
• Other MATLAB Function blocks
Working with Virtual and Nonvirtual Buses
MATLAB Function blocks supports nonvirtual buses only (see “Virtual and
Nonvirtual Buses” on page 48-10). When models that contain MATLAB
Function block inputs and outputs are built, hidden converter blocks are used
to convert bus signals for code generation from MATLAB, as follows:
• Converts incoming virtual bus signals to nonvirtual buses for inputs to
structures in MATLAB Function blocks
• Converts outgoing nonvirtual bus signals from MATLAB Function blocks
to virtual bus signals
29-81
29
Using the MATLAB Function Block
Rules for Defining Structures in MATLAB Function Blocks
Follow these rules when defining structures in MATLAB Function blocks:
• For each structure input or output in a MATLAB Function block, you must
define a Simulink.Bus object in the base workspace to specify its type. For
more information, see Simulink.Bus.
• MATLAB Function blocks support nonvirtual buses only (see “Working
with Virtual and Nonvirtual Buses” on page 29-81).
29-82
Index Substructures and Fields
Index Substructures and Fields
As in MATLAB, you index substructures and fields structures in MATLAB
Function blocks by using dot notation. However, for code generation from
MATLAB, you must reference field values individually (see “Structure
Definition for Code Generation” on page 36-2).
For example, in the emldemo_bus_struct model described in “Attach Bus
Signals to MATLAB Function Blocks” on page 29-79, the MATLAB function
uses dot notation to index fields and substructures:
function [outbus, outbus1] = fcn(inbus)
%#codegen
substruct.a1 = inbus.ele3.a1;
substruct.a2 = int8([1 2;3 4]);
mystruct = struct('ele1',20.5,'ele2',single(100),
'ele3',substruct);
outbus = mystruct;
outbus.ele3.a2 = 2*(substruct.a2);
outbus1 = inbus.ele3;
The following table shows how the code generation software resolves symbols
in dot notation for indexing elements of the structures in this example:
Dot Notation
Symbol Resolution
substruct.a1
Field a1 of local structure substruct
inbus.ele3.a1
Value of field a1 of field ele3, a substructure of
structure inputinbus
inbus.ele3.a2(1,1)
Value in row 1, column 1 of field a2 of field ele3,
a substructure of structure input inbus
29-83
29
Using the MATLAB Function Block
Create Structures in MATLAB Function Blocks
Here is the workflow for creating a structure in a MATLAB Function block:
1 Decide on the type (or scope) of the structure (see “Types of Structures in
MATLAB Function Blocks” on page 29-78).
2 Based on the scope, follow these guidelines for creating the structure:
For Structure
Scope:
Follow These Steps:
Input
1 Create a Simulink.Bus object in the base workspace to define the structure
input.
2 Add data to the MATLAB Function block, as described in “Adding Data
to a MATLAB Function Block” on page 29-42. The data should have the
following properties
• Scope = Input
• Type = Bus:
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.5 Linearized : Yes Author : batserve Create Date : 2012:08:03 22:31:58-04:00 Modify Date : 2012:08:03 22:31:58-04:00 XMP Toolkit : Adobe XMP Core 4.2.1-c041 52.342996, 2008/05/07-20:48:00 Producer : Acrobat Distiller 9.0.0 (Windows) Creator Tool : PScript5.dll Version 5.2.2 Format : application/pdf Title : Print Preview - C:\TEMP\Apdf_2541_3068\home\AppData\Local\PTC\Arbortext\Editor\.aptcache\ae384hih/tf384yff Creator : batserve Document ID : uuid:d476f9f4-3ae4-4ff6-bc72-f20b23ed0f60 Instance ID : uuid:f750291c-85c7-4a9e-836d-ae60b8996361 Page Count : 2839EXIF Metadata provided by EXIF.tools