0% found this document useful (0 votes)
26 views4,850 pages

HDsudung Simulink

The Simulink User's Guide for R2024a provides comprehensive information on using Simulink software, including programmatic modeling basics, keyboard shortcuts, and model management techniques. It also outlines contact information for MathWorks, licensing terms, and patent information. The document includes a detailed revision history and covers various functionalities for creating and managing models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views4,850 pages

HDsudung Simulink

The Simulink User's Guide for R2024a provides comprehensive information on using Simulink software, including programmatic modeling basics, keyboard shortcuts, and model management techniques. It also outlines contact information for MathWorks, licensing terms, and patent information. The document includes a detailed revision history and covers various functionalities for creating and managing models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4850

Simulink®

User's Guide

R2024a
How to Contact MathWorks

Latest news: www.mathworks.com

Sales and services: www.mathworks.com/sales_and_services

User community: www.mathworks.com/matlabcentral

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

Phone: 508-647-7000

The MathWorks, Inc.


1 Apple Hill Drive
Natick, MA 01760-2098
Simulink® User's Guide
© COPYRIGHT 1990–2024 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 First printing New for Simulink 1
December 1996 Second printing Revised for Simulink 2
January 1999 Third printing Revised for Simulink 3 (Release 11)
November 2000 Fourth printing Revised for Simulink 4 (Release 12)
July 2002 Fifth printing Revised for Simulink 5 (Release 13)
April 2003 Online only Revised for Simulink 5.1 (Release 13SP1)
April 2004 Online only Revised for Simulink 5.1.1 (Release 13SP1+)
June 2004 Sixth printing Revised for Simulink 5.0 (Release 14)
October 2004 Seventh printing Revised for Simulink 6.1 (Release 14SP1)
March 2005 Online only Revised for Simulink 6.2 (Release 14SP2)
September 2005 Eighth printing Revised for Simulink 6.3 (Release 14SP3)
March 2006 Online only Revised for Simulink 6.4 (Release 2006a)
March 2006 Ninth printing Revised for Simulink 6.4 (Release 2006a)
September 2006 Online only Revised for Simulink 6.5 (Release 2006b)
March 2007 Online only Revised for Simulink 6.6 (Release 2007a)
September 2007 Online only Revised for Simulink 7.0 (Release 2007b)
March 2008 Online only Revised for Simulink 7.1 (Release 2008a)
October 2008 Online only Revised for Simulink 7.2 (Release 2008b)
March 2009 Online only Revised for Simulink 7.3 (Release 2009a)
September 2009 Online only Revised for Simulink 7.4 (Release 2009b)
March 2010 Online only Revised for Simulink 7.5 (Release 2010a)
September 2010 Online only Revised for Simulink 7.6 (Release 2010b)
April 2011 Online only Revised for Simulink 7.7 (Release 2011a)
September 2011 Online only Revised for Simulink 7.8 (Release 2011b)
March 2012 Online only Revised for Simulink 7.9 (Release 2012a)
September 2012 Online only Revised for Simulink 8.0 (Release 2012b)
March 2013 Online only Revised for Simulink 8.1 (Release 2013a)
September 2013 Online only Revised for Simulink 8.2 (Release 2013b)
March 2014 Online only Revised for Simulink 8.3 (Release 2014a)
October 2014 Online only Revised for Simulink 8.4 (Release 2014b)
March 2015 Online only Revised for Simulink 8.5 (Release 2015a)
September 2015 Online only Revised for Simulink 8.6 (Release 2015b)
October 2015 Online only Rereleased for Simulink 8.5.1 (Release 2015aSP1)
March 2016 Online only Revised for Simulink 8.7 (Release 2016a)
September 2016 Online only Revised for Simulink 8.8 (Release 2016b)
March 2017 Online only Revised for Simulink 8.9 (Release 2017a)
September 2017 Online only Revised for Simulink 9.0 (Release 2017b)
March 2018 Online only Revised for Simulink 9.1 (Release 2018a)
September 2018 Online only Revised for Simulink 9.2 (Release 2018b)
March 2019 Online only Revised for Simulink 9.3 (Release 2019a)
September 2019 Online only Revised for Simulink 10.0 (Release 2019b)
March 2020 Online only Revised for Simulink 10.1 (Release 2020a)
September 2020 Online only Revised for Simulink 10.2 (Release 2020b)
March 2021 Online only Revised for Simulink 10.3 (Release 2021a)
September 2021 Online only Revised for Simulink 10.4 (Release 2021b)
March 2022 Online only Revised for Simulink 10.5 (Release 2022a)
September 2022 Online only Revised for Simulink 10.6 (Release 2022b)
March 2023 Online only Revised for Simulink 10.7 (Release 2023a)
September 2023 Online only Revised for Version 23.2 (R2023b)
March 2024 Online only Revised for Version 24.1 (R2024a)
Contents

Introduction to Simulink

Simulink Basics
1
Programmatic Modeling Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Load a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-2
Create a Model and Specify Parameter Settings . . . . . . . . . . . . . . . . 1-2
Programmatically Load Variables When Opening a Model . . . . . . . . . 1-3
Programmatically Add and Connect Blocks . . . . . . . . . . . . . . . . . . . . 1-3
Programmatically Comment Out or Comment Through Blocks . . . . . 1-5
Name a Signal Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-5
Arrange Model Layouts Automatically . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Open the Same Model in Multiple Windows . . . . . . . . . . . . . . . . . . . 1-6
Use Model Finder to Index and Search Models and Improve Their
Discoverability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6
Locate Diagram Elements Using Highlighting . . . . . . . . . . . . . . . . . . 1-6
Specify Colors Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-6

Keyboard Shortcuts and Mouse Actions for Simulink Modeling . . . . 1-8


View Keyboard Shortcuts in Editor . . . . . . . . . . . . . . . . . . . . . . . . . . 1-8
Perform File and Clipboard Actions . . . . . . . . . . . . . . . . . . . . . . . . 1-10
Zoom and Pan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Navigate Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-11
Select and Move Model Elements . . . . . . . . . . . . . . . . . . . . . . . . . . 1-12
Add and Edit Model Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-13
Connect Model Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-15
Name Model Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Format Block Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-16
Perform Generic Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17
Simulate, Update, and Generate Code for Models . . . . . . . . . . . . . . 1-17
Debug Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-17

Open Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19


Open Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Open Blank Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Open Saved Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-19
Load Model Variables and Data from MAT-File . . . . . . . . . . . . . . . . 1-20
Automatically Initialize Variables and Load Data . . . . . . . . . . . . . . . 1-20
Set Default Template for New Models . . . . . . . . . . . . . . . . . . . . . . . 1-22
Set Favorite Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-23
Clear Recent Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-24
Open Model with Different Character Encoding . . . . . . . . . . . . . . . 1-24

v
Save Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-26
Determine Whether a Model Has Unsaved Changes . . . . . . . . . . . . 1-26
Save Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Choose Valid Model File Names . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Save Model Variables and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-27
Specify Code That Runs Before or After Saving Model . . . . . . . . . . 1-28
Convert Model File Format to SLX . . . . . . . . . . . . . . . . . . . . . . . . . 1-29
Export Model to Previous Version of Simulink . . . . . . . . . . . . . . . . . 1-30

Add Blocks to Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-32


Add Blocks to Models Using Quick Insert Menu . . . . . . . . . . . . . . . 1-32
Add Blocks to Models Using Library Browser . . . . . . . . . . . . . . . . . 1-33
Explore Available Blocks Using Library Browser . . . . . . . . . . . . . . . 1-34

Connect Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36


Connect Blocks with Signal Lines . . . . . . . . . . . . . . . . . . . . . . . . . . 1-36
Connect Single Output Port to Multiple Input Ports . . . . . . . . . . . . . 1-38
Connect Output Ports of Multiple Blocks to Single Block . . . . . . . . . 1-39
Connect Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-41
Connect Blocks Without Signal Lines . . . . . . . . . . . . . . . . . . . . . . . 1-43
Convert Signal Lines to Goto and From Block Sets . . . . . . . . . . . . . 1-45
Comment Out and Comment Through Blocks . . . . . . . . . . . . . . . . . 1-46

Edit Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48


Edit Parameters on Block Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-48
Edit Parameters Using the Property Inspector . . . . . . . . . . . . . . . . 1-50
Edit Parameters Using the Block Parameters Dialog Box . . . . . . . . . 1-51
Edit Parameters Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . 1-52
Specify Block Parameters as Variables . . . . . . . . . . . . . . . . . . . . . . 1-52

Configure Model Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-56


Improve Model Layout with Auto Arrange . . . . . . . . . . . . . . . . . . . . 1-56
Move Multiple Model Elements Simultaneously . . . . . . . . . . . . . . . 1-57
Resize Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-58
Preserve Signal Line Shape When Moving and Resizing Blocks . . . . 1-58
Flip or Rotate Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-59
Move Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-62

Configure Model Element Names and Labels . . . . . . . . . . . . . . . . . . 1-64


Label Signal Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Move Signal Line Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Change Block Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Hide or Display Block Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-64
Move Block Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-65

Configure Model Style Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67


Customize Model Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-67
Customize Model Fonts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-68
Copy Formatting Between Model Elements . . . . . . . . . . . . . . . . . . . 1-68
Increase Drop Shadow Depth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-69

Customize Block Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-70

Visually Organize Models Using Areas . . . . . . . . . . . . . . . . . . . . . . . 1-72

vi Contents
Annotate Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-76
Create Text Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-76
Add Equations to Text Annotations . . . . . . . . . . . . . . . . . . . . . . . . . 1-77
Add Symbols to Text Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . 1-78
Create Image Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-80
Associate Annotations with Blocks and Areas . . . . . . . . . . . . . . . . . 1-81
Hide Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-82
Add Hyperlinks to Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-82

Bookmark Your Place in Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-85


Create a Viewmark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-86
Open and Navigate Viewmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-86
Manage Viewmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-86
Save a Viewmark to the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-86
Refresh a Viewmark . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-87

Search Model Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-88


Keyword Search for Model Elements and Parameters . . . . . . . . . . . 1-88
Search for Blocks Connected Without Signal Lines . . . . . . . . . . . . . 1-90

Keyword Search for Simulink Editor Actions . . . . . . . . . . . . . . . . . . 1-92

Preview Content of Model Components . . . . . . . . . . . . . . . . . . . . . . . 1-93

Exchange Messages with Block Comments . . . . . . . . . . . . . . . . . . . . 1-95


Determine Whether Model Has Open Comments . . . . . . . . . . . . . . 1-95
View Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-96
Add Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-96
Edit, Reply to, and Resolve Comments . . . . . . . . . . . . . . . . . . . . . . 1-97
Hide and Delete Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-97

Print Model Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-98


Print Models Using Default Settings . . . . . . . . . . . . . . . . . . . . . . . . 1-98
Specify Paper Size and Orientation . . . . . . . . . . . . . . . . . . . . . . . . . 1-98
Specify Background Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-98
Specify Print Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-99
Select the Systems to Print . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-99
Print Large Diagrams over Multiple Pages . . . . . . . . . . . . . . . . . . 1-100
Add Log of Printed Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-102
Add Sample Time Legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-102
Configure Print Job . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-103
Print Models to PDFs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-103
Copy Diagrams as Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-103

Print Model Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-105

Programmatically Print Models from MATLAB Command Window


.................................................... 1-107
Printing Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1-107
Print Systems with Multiline Names or Names with Spaces . . . . . 1-108
Set Paper Orientation and Type . . . . . . . . . . . . . . . . . . . . . . . . . . 1-109
Print Diagrams over Multiple Pages . . . . . . . . . . . . . . . . . . . . . . . 1-109
Print Models to Image File Formats . . . . . . . . . . . . . . . . . . . . . . . 1-110

vii
Index and Search Models with Model Finder . . . . . . . . . . . . . . . . . 1-112
Configure and Search Databases . . . . . . . . . . . . . . . . . . . . . . . . . 1-112

Step Through Simulations


2
Step Through Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Open and Configure Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-2
Step Forward One Step at a Time . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-3
Step Forward Multiple Time Steps at a Time . . . . . . . . . . . . . . . . . . . 2-4
Step Back in Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-4
Finish or Stop Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-5

How Stepping Through Simulation Works . . . . . . . . . . . . . . . . . . . . . 2-7


Stepping Forward . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-7
Capturing Simulation Snapshots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-8
Stepping Back . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Pausing on Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-9
Additional Considerations for Stepping Through Simulation . . . . . . 2-10

Debug Simulation Using Signal Breakpoints . . . . . . . . . . . . . . . . . . 2-12


Open and Configure Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
Specify Time to Pause Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . 2-12
View Signal Values in Block Diagram . . . . . . . . . . . . . . . . . . . . . . . 2-13
Step Through Time Steps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-13
Set Breakpoint to Pause Simulation . . . . . . . . . . . . . . . . . . . . . . . . 2-14
Step Block by Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-16
View Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2-17
End Simulation Debugging Session . . . . . . . . . . . . . . . . . . . . . . . . . 2-19

How Simulink Works


3
Simulation Phases in Dynamic Systems . . . . . . . . . . . . . . . . . . . . . . . 3-2
Model Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Link Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-2
Simulation Loop Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-3

Compare Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-6


Fixed-Step Versus Variable-Step Solvers . . . . . . . . . . . . . . . . . . . . . . 3-6
Continuous Versus Discrete Solvers . . . . . . . . . . . . . . . . . . . . . . . . . 3-7
Explicit Versus Implicit Continuous Solvers . . . . . . . . . . . . . . . . . . . . 3-7
One-Step Versus Multistep Continuous Solvers . . . . . . . . . . . . . . . . . 3-8
Single-Order Versus Variable-Order Continuous Solvers . . . . . . . . . . 3-8

Zero-Crossing Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-10


Demonstrating Effects of Excessive Zero-Crossing Detection . . . . . 3-10
Preventing Excessive Zero Crossings . . . . . . . . . . . . . . . . . . . . . . . 3-18
How the Simulator Can Miss Zero-Crossing Events . . . . . . . . . . . . . 3-19

viii Contents
Zero-Crossing Detection in Blocks . . . . . . . . . . . . . . . . . . . . . . . . . 3-22

Zero-Crossing Detection with Fixed-Step Simulation . . . . . . . . . . . 3-25


Effects of Zero-Crossing Detection in Fixed-Step . . . . . . . . . . . . . . . 3-25
Simulate in Fixed-Step Without Zero-Crossing Detection . . . . . . . . 3-26
Enable Fixed-Step Zero-Crossing Detection . . . . . . . . . . . . . . . . . . 3-28
Set Parameters for Zero-Crossing Detection . . . . . . . . . . . . . . . . . . 3-29

Zero-Crossing Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-37


Signal Threshold for Adaptive Zero-Crossing Detection . . . . . . . . . . 3-37

Algebraic Loop Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-39


Mathematical Interpretation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-40
Physical Interpretation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-41
Artificial Algebraic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-41
How the Algebraic Loop Solver Works . . . . . . . . . . . . . . . . . . . . . . 3-42
Implications of Algebraic Loops in a Model . . . . . . . . . . . . . . . . . . . 3-44

Identify Algebraic Loops in Your Model . . . . . . . . . . . . . . . . . . . . . . . 3-45


Highlight Algebraic Loops in the Model . . . . . . . . . . . . . . . . . . . . . 3-46
Use the Algebraic Loop Diagnostic . . . . . . . . . . . . . . . . . . . . . . . . . 3-46

Remove Algebraic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-48


Remove Algebraic Loops by Introducing Delay . . . . . . . . . . . . . . . . 3-48
Solve Algebraic Loops Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-51
How the Software Eliminates Artificial Algebraic Loops . . . . . . . . . 3-51
Eliminate Artificial Algebraic Loops Caused by Atomic Subsystems
................................................. 3-56
Bundled Signals That Create Artificial Algebraic Loops . . . . . . . . . . 3-57
Model and Block Parameters to Diagnose and Eliminate Artificial
Algebraic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-60
Block Reduction and Artificial Algebraic Loops . . . . . . . . . . . . . . . . 3-60

Modeling Considerations with Algebraic Loops . . . . . . . . . . . . . . . . 3-63


Managing Large Models with Artificial Algebraic Loops . . . . . . . . . 3-63
Model Blocks and Direct Feedthrough . . . . . . . . . . . . . . . . . . . . . . 3-63
Changing Block Priorities When Using Algebraic Loop Solver . . . . . 3-64

Use Model Name as Programmatic Interface . . . . . . . . . . . . . . . . . . 3-65


Model Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-65
Input Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-65
Execute Size Computation Phase . . . . . . . . . . . . . . . . . . . . . . . . . . 3-66
Execute Compilation Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-66
Compute Discrete State Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-67
Compute Output Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-67
Compute Continuous State Derivatives . . . . . . . . . . . . . . . . . . . . . . 3-68
Execute Termination Phase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3-68

ix
Modeling Dynamic Systems

Creating a Model
4
Create Template from Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Edit a Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2

Write In-Model Documentation Using Notes . . . . . . . . . . . . . . . . . . . 4-4


View Notes and Load Notes Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Add and Edit Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-5
Hide and Show Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-7

Create and Edit Annotations Programmatically . . . . . . . . . . . . . . . . . 4-9


Create Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Find and Modify Annotations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-9
Delete Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-11
Create Annotations That Contain Hyperlinks . . . . . . . . . . . . . . . . . 4-12
Add Image to Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-13
Create Area . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-14
Create and Hide Markup Annotation . . . . . . . . . . . . . . . . . . . . . . . . 4-15
Find Annotation Executing Callback Function . . . . . . . . . . . . . . . . . 4-16

Explore Types of Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-17

Group Blocks into Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20


Create Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-20
Replace Subsystem with Its Contents . . . . . . . . . . . . . . . . . . . . . . . 4-22
Specify Whether Subsystem Is Atomic . . . . . . . . . . . . . . . . . . . . . . 4-22
Specify Subsystem Read/Write Permissions . . . . . . . . . . . . . . . . . . 4-23
Customize Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-24

Connect Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-25


Add Ports to Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-25
Change Port Locations on Subsystem Blocks . . . . . . . . . . . . . . . . . . 4-26
Edit Port Labels on Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . 4-26
Port Editing Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-29

Expand Subsystem Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-30


Why Expand a Subsystem? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-31
What Subsystems Can You Expand? . . . . . . . . . . . . . . . . . . . . . . . . 4-31
Expand a Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-32
Results of Expanding a Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . 4-32

Navigate Model Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-34


Navigate Down in Canvas . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35
Navigate Up Using Explorer Bar . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-35
Navigate by Selecting Destination in Model Hierarchy Tree . . . . . . 4-35
Navigate to Previously Viewed Level . . . . . . . . . . . . . . . . . . . . . . . . 4-36
Navigate Up to Level of Parent Component . . . . . . . . . . . . . . . . . . . 4-37
Navigate to Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-37
Open Referenced Model Outside Model Hierarchy . . . . . . . . . . . . . 4-37

x Contents
Create and Use Referenced Subsystems in Models . . . . . . . . . . . . . 4-38
What is a Subsystem Reference? . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-38
Advantages of Using Subsystem Reference . . . . . . . . . . . . . . . . . . . 4-38
Reference a Subsystem File in a Model . . . . . . . . . . . . . . . . . . . . . . 4-39
Subsystem Reference Compatibility with Previous Versions of Simulink
................................................. 4-45

Convert Subsystem to a Referenced Subsystem . . . . . . . . . . . . . . . . 4-46

Mask a Subsystem File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-49


Add a System Mask to a Subsystem File . . . . . . . . . . . . . . . . . . . . . 4-49
Create Self-Modifiable Subsystem Reference Using System Mask . . 4-49

Control Subsystem Reference Programmatically . . . . . . . . . . . . . . . 4-52


Create a Referenced Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-52
Find Subsystem Reference in a Model . . . . . . . . . . . . . . . . . . . . . . 4-52
Change the Referenced File for a Subsystem . . . . . . . . . . . . . . . . . 4-52
Check if the SLX or MDL File is a Subsystem Block Diagram Type . 4-52

Change Subsystem Reference Component Dynamically Using InitFcn


..................................................... 4-54

Define Subsystem Reference Interfaces Using Test Harnesses and


Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57
Video Walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57
Validate Subsystem Reference Use in Model and Generate Reusable
Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-57

Subsystem Reference Demos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-61

Use Control Flow Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-62


What is a Control Flow Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . 4-62
Equivalent C Language Statements . . . . . . . . . . . . . . . . . . . . . . . . 4-62
Conditional Control Flow Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-62
While and For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-64

Customize Model Behavior with Callbacks . . . . . . . . . . . . . . . . . . . . 4-68


What You Can Do with Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . 4-68
Types of Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-68
Callback Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-68

Model Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-70


Create Model Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-70
Model Callback Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-71
Referenced Model Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-72

Block Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-75


Block Opening Callback Parameters . . . . . . . . . . . . . . . . . . . . . . . . 4-75
Block Editing Callback Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 4-75
Block Compilation and Simulation Callback Parameters . . . . . . . . . 4-77
Block Saving and Closing Callback Parameters . . . . . . . . . . . . . . . . 4-77
Subsystem Block Callback Parameters . . . . . . . . . . . . . . . . . . . . . . 4-78

Port Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-81

xi
Initialization Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-82
Model InitFcn Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-82
Block InitFcn Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-84

Manage Model Versions and Specify Model Properties . . . . . . . . . . 4-86


Model File Change Notification . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-86
Manage Model Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-86
Access Model Information Programmatically . . . . . . . . . . . . . . . . . 4-88

Model Discretizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-91


What Is the Model Discretizer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-91
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-91
Discretize a Model with the Model Discretizer . . . . . . . . . . . . . . . . 4-91
Model Discretizer Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-92
View the Discretized Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-96
Discretize Blocks from the Simulink Model . . . . . . . . . . . . . . . . . . . 4-99
Discretize a Model with the sldiscmdl Function . . . . . . . . . . . . . . 4-106

Create Model That Performs Neighborhood Processing . . . . . . . . 4-107


Import Image and Output Results . . . . . . . . . . . . . . . . . . . . . . . . . 4-107
Configure Neighborhood Processing Subsystem . . . . . . . . . . . . . . 4-107
Simulate and View Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-108

Specify Region of Interest for Neighborhood Processing . . . . . . . 4-111


Import Image and Output Results . . . . . . . . . . . . . . . . . . . . . . . . . 4-111
Configure Neighborhood Processing Subsystem . . . . . . . . . . . . . . 4-111
Simulate and View Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-112

Use Neighborhood Processing Subsystem Block Padding Options


with Region of Interest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-114
Overview of Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-114
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-114

Model Advisor
5
Check Your Model Using the Model Advisor . . . . . . . . . . . . . . . . . . . . 5-2
Model Advisor Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-2
Run Model Advisor Checks and Review Results . . . . . . . . . . . . . . . . . 5-4
Run Model Checks Programmatically . . . . . . . . . . . . . . . . . . . . . . . . 5-5

Find Model Advisor Check IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-6

Address Model Check Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5-7


Fix a Model Advisor Check Warning or Failure . . . . . . . . . . . . . . . . . 5-7

Save and View Model Advisor Check Reports . . . . . . . . . . . . . . . . . . . 5-8


Save Model Advisor Check Reports . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8
View Model Advisor Check Reports . . . . . . . . . . . . . . . . . . . . . . . . . . 5-8

xii Contents
Upgrade Advisor
6
Upgrade Models Using Upgrade Advisor . . . . . . . . . . . . . . . . . . . . . . . 6-2
Open Upgrade Advisor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Select and Run Upgrade Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6-2
Investigate and Fix Check Warnings and Failures . . . . . . . . . . . . . . . 6-4

Working with Sample Times


7
What Is Sample Time? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-2

Union Rate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-3

Specify Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10


Designate Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-10
Specify Block-Based Sample Times Interactively . . . . . . . . . . . . . . . 7-11
Specify Port-Based Sample Times Interactively . . . . . . . . . . . . . . . . 7-12
Specify Block-Based Sample Times Programmatically . . . . . . . . . . . 7-13
Specify Port-Based Sample Times Programmatically . . . . . . . . . . . . 7-13
Access Sample Time Information Programmatically . . . . . . . . . . . . 7-13
Specify Sample Times for a Custom Block . . . . . . . . . . . . . . . . . . . . 7-13
Determining Sample Time Units . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-13
Change the Sample Time After Simulation Start Time . . . . . . . . . . . 7-13

View Sample Time Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-15


Inspect Sample Time Using Timing Legend . . . . . . . . . . . . . . . . . . . 7-15
Inspect Sample Times Throughout a Model . . . . . . . . . . . . . . . . . . . 7-17

Types of Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18


Discrete Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-18
Continuous Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-19
Events and Asynchronous Sample Times . . . . . . . . . . . . . . . . . . . . . 7-19
Other Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-20
Multirate Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Dataflow Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-21
Initialize, Reinitialize, Terminate Sample Times . . . . . . . . . . . . . . . 7-22

Blocks for Which Sample Time Is Not Recommended . . . . . . . . . . . 7-23


Best Practice to Model Sample Times . . . . . . . . . . . . . . . . . . . . . . . 7-23
Appropriate Blocks for the Sample Time Parameter . . . . . . . . . . . . 7-23
Specify Sample Time in Blocks Where Hidden . . . . . . . . . . . . . . . . 7-24

Block Compiled Sample Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-25

Sample Times in Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-28

Sample Times in Systems and Subsystems . . . . . . . . . . . . . . . . . . . . 7-29


Purely Discrete Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-29
Hybrid Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-31

xiii
Sample Time in Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32

Resolve Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34


Automatic Rate Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-34
Visualize Inserted Rate Transition Blocks . . . . . . . . . . . . . . . . . . . . 7-34

How Propagation Affects Inherited Sample Times . . . . . . . . . . . . . . 7-37


Process for Sample Time Propagation . . . . . . . . . . . . . . . . . . . . . . . 7-37
Simulink Rules for Assigning Sample Times . . . . . . . . . . . . . . . . . . 7-37
Backpropagation in Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . 7-38

Backpropagation in Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . 7-40

Modeling for Multitasking Execution . . . . . . . . . . . . . . . . . . . . . . . . 7-41


Multitasking and Pseudomultitasking Modes . . . . . . . . . . . . . . . . . 7-41
Build a Program for Multitasking Execution . . . . . . . . . . . . . . . . . . 7-43
Execute Multitasking Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-43
Multitasking Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-44

Rate Transitions and Asynchronous Blocks . . . . . . . . . . . . . . . . . . . 7-49


About Rate Transitions and Asynchronous Blocks . . . . . . . . . . . . . . 7-49
Handle Rate Transitions for Asynchronous Tasks . . . . . . . . . . . . . . 7-50
Handle Multiple Asynchronous Interrupts . . . . . . . . . . . . . . . . . . . . 7-50
Protect Data Integrity with volatile Keyword . . . . . . . . . . . . . . . . . . 7-52

Handle Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-53


Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-53
Data Transfer Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-54
Data Transfer Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-54
Rate Transition Block Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-55
Automatic Rate Transition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-56
Visualize Inserted Rate Transition Blocks . . . . . . . . . . . . . . . . . . . . 7-57
Periodic Sample Rate Transitions . . . . . . . . . . . . . . . . . . . . . . . . . . 7-59
Protect Data Integrity with volatile Keyword . . . . . . . . . . . . . . . . . . 7-63

Specify Execution Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-64


Domain Specification Badge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-64
Types of Execution Domains . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-64
Set Execution Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-66
Enforce Discrete Execution Domain for a Subsystem . . . . . . . . . . . 7-67

Referencing a Model
8
Model Reference Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Model Reference Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-2
Model Reference Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-4
Model Reference Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-5
Model Workspaces and Data Dictionaries . . . . . . . . . . . . . . . . . . . . . 8-7
Model Reference Behavior and Execution . . . . . . . . . . . . . . . . . . . . . 8-7
Model Reference Simulation and Code Generation . . . . . . . . . . . . . . 8-8

xiv Contents
Model Reference Requirements and Limitations . . . . . . . . . . . . . . . 8-11
Model Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11
Model Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-11
S-Functions in Referenced Models . . . . . . . . . . . . . . . . . . . . . . . . . 8-11
Model Architecture Requirements and Limitations . . . . . . . . . . . . . 8-13
Signal Requirements and Limitations . . . . . . . . . . . . . . . . . . . . . . . 8-14
Simulation Requirements and Limitations . . . . . . . . . . . . . . . . . . . . 8-15
Code Generation Requirements and Limitations . . . . . . . . . . . . . . . 8-15

Reference Existing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-16


Connect Model Block Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-17
Configure Model Block Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 8-17

Reference Protected Models from Third Parties . . . . . . . . . . . . . . . 8-18


Load Supporting Files for Protected Model . . . . . . . . . . . . . . . . . . . 8-18
Verify Digital Signature of Protected Model . . . . . . . . . . . . . . . . . . 8-18
View Protected Model Contents . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
Test Protected Model in Isolated Environment . . . . . . . . . . . . . . . . 8-19
Reference Protected Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-19
Use Models Protected in Previous Releases . . . . . . . . . . . . . . . . . . 8-20

Convert Subsystems to Referenced Models . . . . . . . . . . . . . . . . . . . . 8-23


Prepare Subsystem for Conversion . . . . . . . . . . . . . . . . . . . . . . . . . 8-23
Convert Subsystems to Referenced Models . . . . . . . . . . . . . . . . . . . 8-24
Conversion Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-25
Compare Simulation Results Before and After Conversion . . . . . . . . 8-26
Revert Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-26
Integrate Referenced Model into Parent Model . . . . . . . . . . . . . . . . 8-27

Conditionally Execute Referenced Models . . . . . . . . . . . . . . . . . . . . 8-28


Conditional Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-28
Requirements for Conditional Models . . . . . . . . . . . . . . . . . . . . . . . 8-29
Modify a Referenced Model for Conditional Execution . . . . . . . . . . 8-30

Inspect Model Hierarchies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32


Content Preview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32
Model Dependency Graph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-32
List of Model References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-33
Model Version Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-33

Define Model Reference Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . 8-35


Add Ports to Model Reference Interface . . . . . . . . . . . . . . . . . . . . . 8-36
Refresh Model Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-38
Define Signal Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Use Buses at Model Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Log Signals in Referenced Models . . . . . . . . . . . . . . . . . . . . . . . . . 8-39
Configure Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-40
Share Data Among Referenced Model Instances . . . . . . . . . . . . . . . 8-40

Referenced Model Sample Times . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-41


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

xv
Sample Time Consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-43
Sample Rates and Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44

Choose Simulation Modes for Model Hierarchies . . . . . . . . . . . . . . 8-45


Model Reference Simulation Modes . . . . . . . . . . . . . . . . . . . . . . . . 8-45
Overridden Simulation Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-48

Override Model Reference Simulation Modes . . . . . . . . . . . . . . . . . . 8-50

Simulate Conditionally Executed Referenced Models . . . . . . . . . . . 8-58


Triggered, Enabled, and Triggered and Enabled Models . . . . . . . . . 8-58
Function-Call Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-58

Simulate Multiple Referenced Model Instances in Normal Mode . . 8-59


Normal Mode Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-59
Examine Multiple Referenced Model Instances . . . . . . . . . . . . . . . . 8-59
Determine Which Instance Has Normal Mode Visibility Enabled . . . 8-62
Specify Which Instance Has Normal Mode Visibility Enabled . . . . . 8-63

Manage Simulation Targets for Referenced Models . . . . . . . . . . . . . 8-66


Reduce Time Spent Checking For Changes . . . . . . . . . . . . . . . . . . . 8-66
Specify Programming Language of Simulation Targets . . . . . . . . . . 8-67
Use Custom Code for Simulation Targets . . . . . . . . . . . . . . . . . . . . 8-67
Control Location of Simulation Targets . . . . . . . . . . . . . . . . . . . . . . 8-67

Reduce Update Time for Referenced Models by Using Parallel Builds


..................................................... 8-69

Share Simulink Cache Files for Faster Simulation . . . . . . . . . . . . . . 8-70


Inspect Simulink Cache File Contents . . . . . . . . . . . . . . . . . . . . . . . 8-70
Use Simulink Cache Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-72
Check for Simulink Cache Files in Projects . . . . . . . . . . . . . . . . . . . 8-73

Set Configuration Parameters for Model Hierarchies . . . . . . . . . . . 8-75


Manage Configuration Parameters by Using Configuration References
................................................. 8-75
Review Configuration Requirements for Simulation of Model Reference
Hierarchies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-75
Specify Compatible Solver Settings . . . . . . . . . . . . . . . . . . . . . . . . 8-77
Configure Local Solver Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-78
Diagnostics That Are Ignored in Accelerator Mode . . . . . . . . . . . . . 8-78

Parameterize Instances of a Reusable Referenced Model . . . . . . . . 8-80


Specify a Different Value for Each Instance of a Reusable Model . . . 8-80
Define Model Arguments Without Specifying a Default Value . . . . . 8-80
Combine Multiple Arguments into a Structure . . . . . . . . . . . . . . . . 8-81
Parameterize a Referenced Model . . . . . . . . . . . . . . . . . . . . . . . . . 8-81
Change Model Argument Name or Value . . . . . . . . . . . . . . . . . . . . . 8-86
Customize User Interface for Reusable Components . . . . . . . . . . . . 8-87
Configure Instance-Specific Data for Simulink.LookupTable and
Simulink.Breakpoint Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-87

Parameterize a Referenced Model Programmatically . . . . . . . . . . . 8-93

Group Multiple Model Arguments into a Single Structure . . . . . . . 8-95

xvi Contents
Configure Instance-Specific Data for Lookup Tables
Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-98

Simulink Units
9
Unit Specification in Simulink Models . . . . . . . . . . . . . . . . . . . . . . . . 9-2
Guidelines for Unitless, Dimensionless, and No Unit Quantities . . . . 9-3
Specify Physical Quantities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Specify Units in Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-4
Specify Units for Temperature Signals . . . . . . . . . . . . . . . . . . . . . . . 9-5
Specify Units in MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . 9-6
Specify Units in Constant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6
Specify Units for Logging and Loading Signal Data . . . . . . . . . . . . . . 9-6
Restricting Unit Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-6

Displaying Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-8

Unit Consistency Checking and Propagation . . . . . . . . . . . . . . . . . . 9-10


Unit Consistency Checking and Model Arguments . . . . . . . . . . . . . 9-12
Unit Propagation Between Simulink and Simscape . . . . . . . . . . . . . 9-12

Converting Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-14


Automatic Unit Conversion Limitations . . . . . . . . . . . . . . . . . . . . . . 9-14

Update an Existing Model to Use Units . . . . . . . . . . . . . . . . . . . . . . . 9-16


Model for Updating Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-16
Incrementally Work Through the Model to Set Units . . . . . . . . . . . . 9-16

Working with Custom Unit Databases . . . . . . . . . . . . . . . . . . . . . . . . 9-23


Custom Units Spreadsheet Format . . . . . . . . . . . . . . . . . . . . . . . . . 9-23
Define Custom Units in Excel Spreadsheet . . . . . . . . . . . . . . . . . . . 9-24
Create and Load Custom Unit Database . . . . . . . . . . . . . . . . . . . . . 9-24

Troubleshooting Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26


Undefined Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26
Overflow and Underflow Errors or Warning . . . . . . . . . . . . . . . . . . 9-26
Mismatched Units Detected . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-26
Mismatched Units Detected Between Model Argument Definition and
Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-27
Mismatched Units Detected While Loading . . . . . . . . . . . . . . . . . . . 9-27
Disallowed Unit Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-27
Automatic Unit Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9-27
Unsuccessful Automatic Unit Conversions . . . . . . . . . . . . . . . . . . . 9-27
Simscape Unit Specification Incompatible with Simulink . . . . . . . . 9-27

xvii
Conditional Subsystems
10
Conditionally Executed Subsystems Overview . . . . . . . . . . . . . . . . . 10-3

Ensure Output Port Is Virtual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-5


Merged Conditional Output Signals . . . . . . . . . . . . . . . . . . . . . . . . 10-5
Merged Partial-Write Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-8

Using Enabled Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-12


Create an Enabled Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-12
Blocks in Enabled Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-13
Alternately Executing Enabled Subsystem Blocks . . . . . . . . . . . . . 10-15
Model Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-17

Using Triggered Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18


Create a Triggered Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-18
Triggering with Discrete Time Systems . . . . . . . . . . . . . . . . . . . . 10-19
Triggered Model Versus a Triggered Subsystem . . . . . . . . . . . . . . 10-20
Blocks in a Triggered Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . 10-20
Model Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-20

Using Enabled and Triggered Subsystems . . . . . . . . . . . . . . . . . . . 10-21


Creating an Enabled and Triggered Subsystem . . . . . . . . . . . . . . . 10-22
Blocks in an Enabled and Triggered Subsystem . . . . . . . . . . . . . . 10-23
Model Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-23

Select Subsystem Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-25


Models with If-Else Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-25
Models with Switch Case Structure . . . . . . . . . . . . . . . . . . . . . . . 10-27

Iterate Subsystem Execution with While Iterator and For Iterator


Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-29
Models with While Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-29
Model with For Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-31

Repeat an Algorithm Using a For-Each Subsystem . . . . . . . . . . . . 10-34


Explore Example Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-34
Identify Opportunities to Simplify Model . . . . . . . . . . . . . . . . . . . . 10-36
Remove Redundant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-36
Simplify Interfaces with Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-37
Repeat an Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-40
Organize Parameters into Arrays of Structures . . . . . . . . . . . . . . . 10-42
Inspect Converted Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-44
Additional Examples of Working with For-Each Subsystems . . . . . 10-44
Limitations of For-Each Subsystems . . . . . . . . . . . . . . . . . . . . . . . 10-50

Using Function-Call Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-53


Creating a Function-Call Subsystem . . . . . . . . . . . . . . . . . . . . . . . 10-53
Sample Time Propagation in a Function-Call Subsystem . . . . . . . . 10-54
Latched Input Data for Function-Call Subsystems . . . . . . . . . . . . . 10-54

Conditional Subsystem Initial Output Values . . . . . . . . . . . . . . . . . 10-57


Inherit Initial Output Values from Input Signals . . . . . . . . . . . . . . 10-57

xviii Contents
Specify Initial Output Values Using Dialog Parameters . . . . . . . . . 10-58

Schedule Components to Avoid Data Dependency Issues . . . . . . . 10-59

Create Rate-Based Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-60


Rate-Based Model with Scheduled Subsystem Blocks . . . . . . . . . . 10-60

Test Rate-Based Model Simulation Using Function-Call Generators


.................................................... 10-62
Create Test Model That References Rate-Based Model . . . . . . . . . 10-62
Simulate Test Harness for Rate-Based Model . . . . . . . . . . . . . . . . 10-62
Avoid Common Compile and Run-Time Errors . . . . . . . . . . . . . . . . 10-63

Generate Code from Rate-Based Model . . . . . . . . . . . . . . . . . . . . . . 10-65


Code Generation Report for Rate-Based Models . . . . . . . . . . . . . . 10-65
Generated Code Entry Points for Rate-Based Models . . . . . . . . . . 10-65

Sorting Rules for Explicitly Scheduled Model Components . . . . . 10-68


Export-Function Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-68
Test Harness for Export Function Models with Strict Scheduling . 10-69
Test Harness for Export-Function Models Without Strict Scheduling
................................................ 10-69
Data Dependency Error Caused by Data Sorting Rules . . . . . . . . . 10-70
Test Harness for Models with Initialize, Reset, and Terminate Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-72
Initiators for Model Block in Test Harness . . . . . . . . . . . . . . . . . . 10-72

Conditional Subsystem Output Values When Disabled . . . . . . . . . 10-75

Simplified Initialization Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-76


When to Use Simplified Initialization . . . . . . . . . . . . . . . . . . . . . . 10-76
Set Initialization Mode to Simplified . . . . . . . . . . . . . . . . . . . . . . . 10-76

Classic Initialization Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-78


Set Initialization Mode to Classic . . . . . . . . . . . . . . . . . . . . . . . . . 10-78
Classic Initialization Issues and Limitations . . . . . . . . . . . . . . . . . 10-78
Identity Transformation Can Change Model Behavior . . . . . . . . . . 10-79
Inconsistent Output with Discrete-Time Integrator or S-Function Block
................................................ 10-82
Execution Order Affecting Merge Block Output . . . . . . . . . . . . . . 10-84
Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-95
State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-95
Simulink does not provide correct consistency check . . . . . . . . . . 10-96

Convert from Classic to Simplified Initialization Mode . . . . . . . . . 10-97


Blocks to Consider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-97

Create Export-Function Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-98


Designate Model as Export-Function Model and Satisfy Export-
Function Model Requirements . . . . . . . . . . . . . . . . . . . . . . . . . 10-98
Create Model Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-98
Add Function-Call Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-99
Export-Function Model with Unit Delay and Square Functions . . . 10-99
Test Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-100

xix
Test Export-Function Model Simulation Using Input Matrix . . . . 10-101
Create Function-Call Inputs and Data Inputs . . . . . . . . . . . . . . . 10-101
Simulate Export-Function Model . . . . . . . . . . . . . . . . . . . . . . . . 10-102

Test Export-Function Model Simulation Using Function-Call


Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-105
Reference an Export-Function Model . . . . . . . . . . . . . . . . . . . . . 10-105
Create Test Model (Harness) for Simulation . . . . . . . . . . . . . . . . 10-105
Prepare Export-Function Model for Simulation . . . . . . . . . . . . . . 10-106
Test Export-Function Model with Function-Call Generator Blocks
............................................... 10-107

Test Export-Function Model Simulation Using Stateflow Chart . 10-109


Reference an Export-Function Model . . . . . . . . . . . . . . . . . . . . . 10-109
Create Periodic Scheduler Using Stateflow Chart . . . . . . . . . . . . 10-109
Create Test Model (Harness) for Simulation . . . . . . . . . . . . . . . . 10-110
Prepare Export-Function Model for Simulation . . . . . . . . . . . . . . 10-111
Test Export-Function Model Using Stateflow Chart . . . . . . . . . . . 10-112

Test Export-Function Model Simulation Using Schedule Editor 10-114


Create Test Model (Harness) for Simulation . . . . . . . . . . . . . . . . 10-114
Create Function-Call Events Using the Schedule Editor . . . . . . . 10-115
Prepare Export-Function Model for Simulation . . . . . . . . . . . . . . 10-116
Test Export-Function Model Using Schedule Editor . . . . . . . . . . 10-116

Generate Code for Export-Function Model . . . . . . . . . . . . . . . . . . 10-118


Generate Code for Exported Functions . . . . . . . . . . . . . . . . . . . . 10-118

Generate Code for Export-Function Model with Rate-Based Model


................................................... 10-121
Create Export-Function Model with Scheduled Subsystems and Rate-
Based Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-121
Generate Code for Export-Function Model with Rate-Based Model
............................................... 10-123

Export-Function Models Overview . . . . . . . . . . . . . . . . . . . . . . . . . 10-125


Workflows for Export-Function Models . . . . . . . . . . . . . . . . . . . . 10-126
Blocks Allowed at Top Level of Export-Function Models . . . . . . . 10-126
Requirements for Export-Function Models . . . . . . . . . . . . . . . . . 10-127
Designating an Export-Function Model . . . . . . . . . . . . . . . . . . . . 10-128
Sample Time for Function-Call Subsystems . . . . . . . . . . . . . . . . 10-129
Execution Order for Root-Level Function-Call Inport Blocks . . . . 10-129
Nested Export-Function Models . . . . . . . . . . . . . . . . . . . . . . . . . 10-133
Export-Function Model with a Multi-Instanced Function-Call Model
............................................... 10-134
Export-Function Models and Models with Asynchronous Function-Call
Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-135

Using Resettable Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-137


Behavior of Resettable Subsystems . . . . . . . . . . . . . . . . . . . . . . 10-137
Comparison of Resettable Subsystems and Enabled Subsystems 10-139
Model Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-141

Simulink Functions Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-142


What Are Simulink Functions? . . . . . . . . . . . . . . . . . . . . . . . . . . 10-142

xx Contents
What Are Simulink Function Callers? . . . . . . . . . . . . . . . . . . . . . 10-142
Connect to Local Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-142
Reusable Logic with Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 10-143
Input/Output Argument Behavior . . . . . . . . . . . . . . . . . . . . . . . . 10-143
Shared Resources with Functions . . . . . . . . . . . . . . . . . . . . . . . . 10-144
How a Function Caller Identifies a Function . . . . . . . . . . . . . . . . 10-145
Reasons to Use a Simulink Function Block . . . . . . . . . . . . . . . . . 10-146
Choose a Simulink Function or Reusable Subsystem . . . . . . . . . . 10-146
When Not to Use a Simulink Function Block . . . . . . . . . . . . . . . . 10-146
Tracing Simulink Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-147
Highlight and Animate Function Calls . . . . . . . . . . . . . . . . . . . . . 10-149

Add a Simulink Function to a Model . . . . . . . . . . . . . . . . . . . . . . . 10-151


Simulink Functions and Function Callers . . . . . . . . . . . . . . . . . . 10-151
Create Simulink Function Using Simulink Function Block . . . . . . 10-153
Create Simulink Function Using Exported Graphical Function from
Stateflow Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-153
Create Simulink Function Using Exported MATLAB Function from
Stateflow Chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-156

Call a Simulink Function from a Model . . . . . . . . . . . . . . . . . . . . . 10-159


Simulink Functions and Function Callers . . . . . . . . . . . . . . . . . . 10-159
Use a Function Caller Block to Call a Simulink Function Block . . 10-161
Use a MATLAB Function Block to Call a Simulink Function Block
............................................... 10-162
Use a Stateflow Chart to Call a Simulink Function Block . . . . . . . 10-163
Call a Simulink Function Block from Multiple Sites . . . . . . . . . . . 10-165

Argument Specification for Simulink Function Blocks . . . . . . . . 10-168


Example Argument Specifications for Data Types . . . . . . . . . . . . 10-168
Input Argument Specification for Bus Data Type . . . . . . . . . . . . . 10-169
Input Argument Specification for Enumerated Data Type . . . . . . 10-169
Input Argument Specification for an Alias Data Type . . . . . . . . . 10-169

Simulink Function Blocks in Referenced Models . . . . . . . . . . . . . 10-171


Simulink Function Block in Referenced Model . . . . . . . . . . . . . . 10-171
Function Caller Block in Referenced Model . . . . . . . . . . . . . . . . 10-172
Function and Function Caller Blocks in Separate Referenced Models
............................................... 10-173
Function and Function Caller in Same Model . . . . . . . . . . . . . . . 10-174

Scoped, Global, and Port-Scoped Simulink Function Blocks Overview


................................................... 10-177

Scoped Simulink Function Blocks in Subsystems . . . . . . . . . . . . 10-181


Resolve to a Function Hierarchically . . . . . . . . . . . . . . . . . . . . . . 10-181
Resolve to a Function by Qualification . . . . . . . . . . . . . . . . . . . . 10-183

Scoped Simulink Function Blocks in Models . . . . . . . . . . . . . . . . 10-188


Resolve to a Function Hierarchically . . . . . . . . . . . . . . . . . . . . . . 10-188
Resolve to a Function by Qualification . . . . . . . . . . . . . . . . . . . . 10-189
Multi-Instance Modeling with Simulink Functions . . . . . . . . . . . . 10-192

Model Client-Server Communication Using Function Ports . . . . 10-195


Model Server Component with Function Element Block . . . . . . . 10-195

xxi
Model Client that Requires Services . . . . . . . . . . . . . . . . . . . . . . 10-197
Configure Asynchronous Execution with Function Ports . . . . . . . 10-198

Define Diagnostic Services Using Simulink Functions . . . . . . . . . 10-200


Diagnostic Messaging with Simulink Functions . . . . . . . . . . . . . 10-200
Client-Server Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-200
Modifier Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-201
Observer Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-202

Resolve Error: Block Is Unable to Call The Scoped Simulink Function


................................................... 10-204
Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-204
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-204

Using Initialize, Reinitialize, Reset, and Terminate Functions . . 10-208


Create Model Component with State . . . . . . . . . . . . . . . . . . . . . 10-208
Initialize Block State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-209
Reset Block State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-212
Read and Save Block State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-214
Prepare Model Component for Testing . . . . . . . . . . . . . . . . . . . . 10-217
Create an Export-Function Model . . . . . . . . . . . . . . . . . . . . . . . . 10-218

Create Test Harness to Generate Function Calls . . . . . . . . . . . . . 10-221


Reference the Export-Function Model . . . . . . . . . . . . . . . . . . . . . 10-221
Model an Event Scheduler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-223
Connect Chart to Test Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-224

Initialize and Reset Parameter Values . . . . . . . . . . . . . . . . . . . . . . 10-226


Adding a Parameter Writer Block . . . . . . . . . . . . . . . . . . . . . . . . 10-226
Writing to Tunable Block Parameters . . . . . . . . . . . . . . . . . . . . . 10-227
Writing to Model Instance Parameters . . . . . . . . . . . . . . . . . . . . 10-228
Writing to Masked Subsystem Parameters . . . . . . . . . . . . . . . . . 10-230
Writing to Model Workspace Variables . . . . . . . . . . . . . . . . . . . . 10-231

Initialize, Reinitialize, Reset, and Terminate Function Limitations


................................................... 10-232
Unsupported Blocks and Signals . . . . . . . . . . . . . . . . . . . . . . . . . 10-232
Unsupported Modeling Patterns . . . . . . . . . . . . . . . . . . . . . . . . . 10-232

Reinitialize States of Blocks in Subsystem . . . . . . . . . . . . . . . . . . 10-235

Common Uses of the Initialize Function Block . . . . . . . . . . . . . . . 10-238

Model House Heating System . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-251


Open Completed House System Model . . . . . . . . . . . . . . . . . . . . 10-251
Define a House Heating System . . . . . . . . . . . . . . . . . . . . . . . . . 10-251
Model House Heating System . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-255
Integrate a House Heating Model . . . . . . . . . . . . . . . . . . . . . . . . 10-268
Prepare for Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-276
Run and Evaluate Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-278

Wireless Tire Pressure Monitoring System with Fault Logging . 10-284

Prepare Sensor and Controller Models in a Distributed Monitoring


System for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-289

xxii Contents
Fixed-Point Data Type Support for If Block . . . . . . . . . . . . . . . . . . 10-293
Floating-Point Model without Fixed-Point Data . . . . . . . . . . . . . . 10-293
Block and Model Configurations . . . . . . . . . . . . . . . . . . . . . . . . . 10-293
Model with If Action Subsystems and Fixed-Point Data Types . . . 10-294
Model Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10-295

Messages in Simulink
11
Simulink Messages Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-2
Model Message Send and Receive Interfaces and Generate Code
................................................. 11-3
Model Event-Driven Receive Interfaces . . . . . . . . . . . . . . . . . . . . . . 11-4
Simulate Middleware Effects on a Distributed Architecture . . . . . . 11-4

Animate and Understand Sending and Receiving Messages . . . . . . 11-6

Use a Queue Block to Manage Messages . . . . . . . . . . . . . . . . . . . . 11-13

Establish Message Send and Receive Interfaces Between Software


Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-23

Connect Message Receive Interface with Simulink Functions . . . 11-27

Modeling Message Communication Patterns with SimEvents . . . . 11-30

Build a Shared Communication Channel with Multiple Senders and


Receivers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-32

Model Wireless Message Communication with Packet Loss and


Channel Failure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-38

Model an Ethernet Communication Network with CSMA/CD Protocol


.................................................... 11-48

Send and Receive Messages Carrying Bus Data . . . . . . . . . . . . . . . 11-59

Use Virtual Buses with Message Elements for Component


Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-61

Merge Message Lines Using a Message Merge Block . . . . . . . . . . 11-69

Specify Queue Properties for Message Interface . . . . . . . . . . . . . . 11-71


Specify Queue Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-71
Queue Expansion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-74
Virtual Buses with Message Elements in Architecture Models . . . . 11-74

Use the Sequence Viewer to Visualize Messages, Events, and Entities


.................................................... 11-77
Components of the Sequence Viewer Window . . . . . . . . . . . . . . . . 11-78
Navigate the Lifeline Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . 11-80
View State Activity and Transitions . . . . . . . . . . . . . . . . . . . . . . . . 11-82

xxiii
View Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11-83
Simulation Time in the Sequence Viewer Window . . . . . . . . . . . . . 11-84
Redisplay of Information in the Sequence Viewer Window . . . . . . 11-85

Using Message Polling and Message Triggered Subsystems . . . . . 11-87

Asynchronous Message Handling in Adaptive Cruise Control . . . . 11-94

Temperature Control System Communicating with Messages . . 11-101

Modeling Variant Systems


12
What Are Variants and When to Use Them . . . . . . . . . . . . . . . . . . . . 12-3
What Are Variants? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3
Advantages of Using Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-3
When to Use Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-4
Types of Variants in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-5
Variant Blocks in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-6
Use Variants to Create One Model for Many Systems . . . . . . . . . . . 12-8
Working with Variants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-10

Variant Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-20


Command Line Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-21
Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-33

Define and Configure Variant Sources and Sinks . . . . . . . . . . . . . . 12-35


Represent Variant Choices in Variant Source and Variant Sink Blocks
................................................ 12-35
Generate Code for Variant Source and Variant Sink Blocks . . . . . . 12-39

Visualize Variant Implementations in a Single Layer . . . . . . . . . . . 12-41


How Variant Sources and Sinks Work . . . . . . . . . . . . . . . . . . . . . . 12-41
Advantages of Using Variant Sources and Sinks . . . . . . . . . . . . . . 12-41
Limitations of Using Variant Sources and Sinks . . . . . . . . . . . . . . 12-42
Generate Code for Variant Source and Variant Sink Blocks . . . . . . 12-42

Provide Variation in Signal Source and Destination Using Manual


Variant Source and Manual Variant Sink Blocks . . . . . . . . . . . . 12-43

Create a Simple Variant Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-45

Implement Variations in Separate Hierarchy Using Variant


Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-48

Working with Variant Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-59


Default Variant Choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-60
Active Variant Choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-60
Inactive Variant Choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-60
Empty Variant Choice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-60
List of Variant Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-61
Open Active Variant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-61

xxiv Contents
Introduction to Variant Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-62

Variant Control Modes in Variant Blocks . . . . . . . . . . . . . . . . . . . . 12-64


Types of Variant Control Modes in Variant Blocks . . . . . . . . . . . . . 12-64
Switch Between Choices Using Condition Expressions in Variant
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-65
Switch Between Choices Using Labels in Variant Blocks . . . . . . . . 12-71
Switch Between Choices for Simulation and Code Generation
Workflows Without Using Control Variables in Variant Blocks . . 12-73
Compare Different Types of Variant Control Modes in Variant Blocks
................................................ 12-74
Variant Activation Times for Different Variant Control Modes in Variant
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-77

Use Variant Control Variables in Variant Blocks . . . . . . . . . . . . . . . 12-78


Simulink.VariantControl Variables for Coherent Switching of Choices
in Variant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-78
Scalar Variant Control Variables for Rapid Prototyping in Variant
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-80
Simulink.Parameter Type of Variant Control Variables for Code
Generation in Variant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 12-81
Enumerated Types To Improve Code Readability of Variant Control
Variables of Variant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-83
Simulink.VariantExpression Objects for Variant Condition Reuse of
Variant Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-86
Structures to Group Related Variant Control Variables of Variant
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-87

Create Variant Controls Programmatically . . . . . . . . . . . . . . . . . . . 12-91


Create and Export Variant Controls . . . . . . . . . . . . . . . . . . . . . . . 12-91
Reuse Variant Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-91
Enumerated Types as Variant Controls . . . . . . . . . . . . . . . . . . . . . 12-91

Activate Variant During Different Stages of Simulation and Code


Generation Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-93
Stages to Set Active Choices in Variant Blocks and Variant Parameters
................................................ 12-94
Types of Variant Activation Time in Variant Blocks and Variant
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-95
Variant Activation Time for Variant Blocks . . . . . . . . . . . . . . . . . . 12-99
Variant Activation Time in Variant Parameters . . . . . . . . . . . . . . 12-101
Storage Classes for Different Variant Activation Times . . . . . . . . 12-103

Verify and Validate Variant Models with Code Compile Activation


Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-105

Simulate Variant Subsystem with Startup Activation Using parsim


................................................... 12-110

Simulate a Protected Model with Code Compile or Startup Activation


Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-113

Simulate Variant Blocks in Accelerator and Rapid Accelerator Modes


with Startup Activation Time . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-116

xxv
Run Iterative Simulations Without Recompiling Model for Variant
Systems Using Fast Restart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-118

Verify and Validate Variant Models with Startup Activation Time


................................................... 12-124

Known Limitations of startup variant activation time . . . . . . . . . 12-129

Considerations and Limitations for startup Variant Activation Time


................................................... 12-130
Combining startup and code compile Variant Activation Times in
Variant Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-130
Use of Variant Control Variables with startup Variant Activation Time
in Another Variant Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-132

Propagate Variant Conditions to Define Variant Regions with Variant


Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-133
Visualize Propagated Variant Conditions in Variant Conditions Legend
............................................... 12-133
Propagate Variant Conditions from Variant Blocks Upstream and
Downstream . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-135
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-136

Assemble Variant Conditions Propagated from Variant Blocks . . 12-137


Cross-Coupling of Inputs and Outputs . . . . . . . . . . . . . . . . . . . . 12-137
Cascading Blocks and Compounding Conditions . . . . . . . . . . . . . 12-137
Hierarchical Nesting of Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 12-138

Propagate Variant Conditions to Define Variant Regions Outside


Variant Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-140
Factors That Affect Propagation of Variant Conditions Outside of
Variant Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-140
Adaptive Interface for Variant Subsystems . . . . . . . . . . . . . . . . . 12-141
Propagation with Different Activation Times . . . . . . . . . . . . . . . . 12-142
Propagation Without Inport and Outport Blocks . . . . . . . . . . . . . 12-148
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-148

Propagate Variant Conditions to Define Variant Regions Using


Variant Source and Variant Sink Blocks . . . . . . . . . . . . . . . . . . 12-150
Variant Source and Variant Sink Blocks . . . . . . . . . . . . . . . . . . . 12-150
Generate Code for Variant Source and Variant Sink Blocks . . . . . 12-154

Variant Elements Within Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-155

Propagate Variant Conditions to Define Variant Regions in Virtual


and Nonvirtual Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-157

Propagate Variant Conditions to Control Execution of Conditional


Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-162
Variant Signals from Variant Source Outport to Function-Call
Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-162
Variant Signals from Variant Subsystem Inport to Function-Call
Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-164
Variant Signals from Variant Subsystem Outport to Function-Call
Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-167

xxvi Contents
Propagate Variant Conditions to Enable or Disable Model or
Subsystem References in Hierarchy . . . . . . . . . . . . . . . . . . . . . 12-170

Conditionally Execute Custom Initialize, Reinitialize, Reset, and


Terminate Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-173

Conditionally Execute Simulink Functions . . . . . . . . . . . . . . . . . . 12-176

Approaches to Control Active Variant Choice of a Variant Block Using


Mask or Model Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-178

Control Structural Variations Using Mask Parameters and Model


Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-183

Prevent Creation of Unused Variables for Unconditional and


Conditional Variant Choices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-186

Prevent Creation of Unused Variables for Lenient Variant Choices


................................................... 12-189

Control Active Choice of Locked Custom Library Variant Subsystem


Using Mask Parameter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-192
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-192
Switch Between Active Choices . . . . . . . . . . . . . . . . . . . . . . . . . 12-193

Add or Remove Variant Choices of Variant Assembly Subsystem


Blocks Using External Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-195
Manipulate Variant Choices of Variant Assembly Subsystem Block in
Label Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-195
Manipulate Variant Choices of Variant Assembly Subsystem Block in
Expression Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-201
Generate Code for Variant Subsystems . . . . . . . . . . . . . . . . . . . . 12-207

Control Variant Choices in Masked Variant Assembly Subsystem


Block Using Mask Parameter Object . . . . . . . . . . . . . . . . . . . . . 12-208
Switch Between Variant Choices of Masked Variant Assembly
Subsystem Block in Label Mode . . . . . . . . . . . . . . . . . . . . . . . 12-208
Switch Between Variant Choices of Masked Variant Assembly
Subsystem Block in Expression Mode . . . . . . . . . . . . . . . . . . . 12-212

Automatic Mask Icon Promotion in Variant Subsystems . . . . . . . 12-217

Prepare Variant-Containing Model for Code Generation . . . . . . . 12-220


Convert Variant Control Variables into Simulink.Parameter Objects
............................................... 12-220
Configure Model for Generating Preprocessor Conditionals . . . . 12-221

Generate Code from Nested Variant Subsystem with Code Compile


and Startup Activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-225

Create Real-Time Applications Using Variants and Simulink Real-


Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-229

Create Standalone Executables with Variants Using Simulink


Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-235

xxvii
Export and Import Function Mockup Unit (FMU) from Model with
Variant Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-239

Simulink Variant Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-242

V-Model for System Development with Simulink Variants . . . . . . 12-243


System-Level Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-244
Components — Create Models with Structural Variations . . . . . . 12-244
Components — Create Models with Parameter Value Variations . 12-249
Components — Create Models with Variations in Transition Paths
............................................... 12-251
Components — Create Models with Variations in Dimensions . . . 12-251
Components — Create Models with Variations in AUTOSAR Interfaces
............................................... 12-252
Components — Manage Structural Variations in a Model . . . . . . 12-252
Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-253
Component Tests and System-Level Tests . . . . . . . . . . . . . . . . . . 12-256

Use find_system with Built-In MatchFilter Options for Variant Blocks


................................................... 12-258

Convert Variant Subsystem to Variant Assembly Subsystem . . . . 12-262


Convert Variant Subsystem Block with Expressions to Variant
Assembly Subsystem Block Interactively . . . . . . . . . . . . . . . . . 12-262
Convert Variant Subsystem Block with Expressions to Variant
Assembly Subsystem Block Programmatically . . . . . . . . . . . . . 12-264
Convert Variant Subsystem Block with Labels to Variant Assembly
Subsystem Block Interactively . . . . . . . . . . . . . . . . . . . . . . . . 12-265
Convert Variant Subsystem Block with Labels to Variant Assembly
Subsystem Block Programmatically . . . . . . . . . . . . . . . . . . . . 12-267

Convert Configurable Subsystem to Variant Subsystem . . . . . . . 12-269


Using Upgrade Advisor interactively . . . . . . . . . . . . . . . . . . . . . . 12-269
Using Upgrade Advisor Programmatically . . . . . . . . . . . . . . . . . 12-270
Using convertToVariantSubsystem Method . . . . . . . . . . . . . . . . . 12-271
Using Context Menu of Configurable Subsystem Block . . . . . . . . 12-271
Changing Active Variant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-273

Managing Model Configurations


13
Set Model Configuration Parameters for a Model . . . . . . . . . . . . . . 13-2
Set Configuration Parameters Programmatically . . . . . . . . . . . . . . . 13-2
Set Configuration Parameters by Using the Dialog Box . . . . . . . . . . 13-2

Manage Configuration Sets for a Model . . . . . . . . . . . . . . . . . . . . . . 13-6


Create a Configuration Set in a Model . . . . . . . . . . . . . . . . . . . . . . 13-6
Change Configuration Parameter Values in a Configuration Set . . . 13-7
Activate a Configuration Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-8
Copy, Delete, and Move a Configuration Set . . . . . . . . . . . . . . . . . . 13-8
Save a Configuration Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-9
Load a Saved Configuration Set . . . . . . . . . . . . . . . . . . . . . . . . . . 13-10

xxviii Contents
Compare Configuration Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-10

Share a Configuration with Multiple Models . . . . . . . . . . . . . . . . . 13-12


Create a Configuration Set in the Data Dictionary . . . . . . . . . . . . . 13-13
Create and Attach a Configuration Reference . . . . . . . . . . . . . . . . 13-13
Resolve a Configuration Reference . . . . . . . . . . . . . . . . . . . . . . . . 13-14
Activate a Configuration Reference . . . . . . . . . . . . . . . . . . . . . . . . 13-15
Create a Configuration Reference in Another Model . . . . . . . . . . . 13-15
Change Parameter Values in a Referenced Configuration Set . . . . 13-16
Change Parameter Value in a Configuration Reference . . . . . . . . . 13-16
Save a Referenced Configuration Set . . . . . . . . . . . . . . . . . . . . . . 13-18
Load a Saved Referenced Configuration Set . . . . . . . . . . . . . . . . . 13-18
Configuration Reference Limitations . . . . . . . . . . . . . . . . . . . . . . . 13-18

Share a Configuration Across Referenced Models . . . . . . . . . . . . . 13-20

Automate Model Configuration by Using a Script . . . . . . . . . . . . . 13-24

Configuration Object Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-27

Configuring Models for Targets with Multicore Processors


14
Concepts in Multicore Programming . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Basics of Multicore Programming . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
Types of Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-2
System Partitioning for Parallelism . . . . . . . . . . . . . . . . . . . . . . . . . 14-5
Challenges in Multicore Programming . . . . . . . . . . . . . . . . . . . . . . 14-6

Multicore Programming with Simulink . . . . . . . . . . . . . . . . . . . . . . . 14-8


Basic Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-8
How Simulink Helps You to Overcome Challenges in Multicore
Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-9

Implement Data Parallelism in Simulink . . . . . . . . . . . . . . . . . . . . 14-11

Implement Task Parallelism in Simulink . . . . . . . . . . . . . . . . . . . . . 14-14

Implement Pipelining in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . 14-17

Configure Your Model for Concurrent Execution . . . . . . . . . . . . . . 14-20

Specify a Target Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-21


Choose from Predefined Architectures . . . . . . . . . . . . . . . . . . . . . 14-21
Define a Custom Architecture File . . . . . . . . . . . . . . . . . . . . . . . . 14-22

Partition Your Model Using Explicit Partitioning . . . . . . . . . . . . . . 14-26


Prerequisites for Explicit Partitioning . . . . . . . . . . . . . . . . . . . . . . 14-26
Add Periodic Triggers and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . 14-26
Add Aperiodic Triggers and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . 14-27
Map Blocks to Tasks, Triggers, and Nodes . . . . . . . . . . . . . . . . . . 14-28

xxix
Implicit and Explicit Partitioning of Models . . . . . . . . . . . . . . . . . . 14-31
Partitioning Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-31

Configure Data Transfer Settings Between Concurrent Tasks . . . 14-33

Optimize and Deploy on a Multicore Target . . . . . . . . . . . . . . . . . . 14-36


Generate Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-36
Build on Desktop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-37
Profile and Evaluate Explicitly Partitioned Models on a Desktop . . 14-38
Customize the Generated C Code . . . . . . . . . . . . . . . . . . . . . . . . . 14-42

Programmatic Interface for Concurrent Execution . . . . . . . . . . . . 14-43


Map Blocks to Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-43

Supported Targets for Multicore Programming . . . . . . . . . . . . . . . 14-44


Supported Multicore Targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-44
Supported Heterogeneous Targets . . . . . . . . . . . . . . . . . . . . . . . . 14-44

Limitations with Multicore Programming in Simulink . . . . . . . . . 14-46

Multithreaded Simulation Using For Each Subsystem . . . . . . . . . . 14-47

Modeling Best Practices


15
General Considerations When Building Simulink Models . . . . . . . . 15-2
Avoiding Invalid Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-2
Shadowed Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-3
Model Building Tips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-5

Model a Continuous System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-6

Best-Form Mathematical Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9


Series RLC Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-9
Solving Series RLC Using Resistor Voltage . . . . . . . . . . . . . . . . . . . 15-9
Solving Series RLC Using Inductor Voltage . . . . . . . . . . . . . . . . . . 15-10

Model a Simple Equation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-12

Model Differential Algebraic Equations . . . . . . . . . . . . . . . . . . . . . 15-14


Overview of Robertson Reaction Example . . . . . . . . . . . . . . . . . . . 15-14
Simulink Models from ODE and DAE Equations . . . . . . . . . . . . . . 15-14
Simulink Model from ODE Equations . . . . . . . . . . . . . . . . . . . . . . 15-14
Simulink Model from DAE Equations . . . . . . . . . . . . . . . . . . . . . . 15-17
Simulink Model from DAE Equations Using Algebraic Constraint Block
................................................ 15-19

Basic Modeling Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-23

Model a System Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-25

Create Model Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-27

xxx Contents
Manage Signal Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-30

Manage Model Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-36

Reuse Model Components from Files . . . . . . . . . . . . . . . . . . . . . . . 15-38

Create Interchangeable Variations of Model Components . . . . . . 15-41

Set Up a File Management System . . . . . . . . . . . . . . . . . . . . . . . . . 15-43

Project Setup
16
Organize Large Modeling Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2

What Are Projects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-3

Explore Project Tools with the Airframe Project . . . . . . . . . . . . . . . . 16-5


Explore the Airframe Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-5
Set Up Project Files and Open the Project . . . . . . . . . . . . . . . . . . . 16-5
View, Search, and Sort Project Files . . . . . . . . . . . . . . . . . . . . . . . . 16-6
Open and Run Frequently Used Files . . . . . . . . . . . . . . . . . . . . . . . 16-6
Review Changes in Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . 16-7
Run Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-8
Run Project Integrity Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-10
Commit Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-10
View Project and Source Control Information . . . . . . . . . . . . . . . . 16-10

Create a Project from a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-12

Set MATLAB Projects Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . 16-14

Create a New Project from a Folder . . . . . . . . . . . . . . . . . . . . . . . . . 16-18

Add Files to the Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-22

Create a New Project from an Archived Project . . . . . . . . . . . . . . . 16-24

Create a New Project Using Templates . . . . . . . . . . . . . . . . . . . . . . 16-25


Use Project Templates from R2014a or Before . . . . . . . . . . . . . . . 16-25

Open Recent Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-26

Specify Project Details, Startup Folder, and Derived Files Folders


.................................................... 16-27

Specify Project Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-28

What Can You Do with Project Shortcuts? . . . . . . . . . . . . . . . . . . . 16-29

Automate Startup Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-30

xxxi
Automate Shutdown Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-32

Create Shortcuts to Frequent Tasks . . . . . . . . . . . . . . . . . . . . . . . . 16-33


Create Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-33
Group Shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-33
Annotate Shortcuts to Use Meaningful Names . . . . . . . . . . . . . . . 16-34
Customize Shortcut Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-34

Use Shortcuts to Find and Run Frequent Tasks . . . . . . . . . . . . . . . 16-35

Create Templates for Standard Project Settings . . . . . . . . . . . . . . . 16-36


Using Templates to Create Standard Project Settings . . . . . . . . . . 16-36
Create a Template from the Current Project . . . . . . . . . . . . . . . . . 16-36
Create a Template from a Project Under Version Control . . . . . . . 16-37
Edit a Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-37
Remove a Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-37
Explore the Example Templates . . . . . . . . . . . . . . . . . . . . . . . . . . 16-37

Project File Management


17
Group and Sort File Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-2

Search Inside Project Files and Filter File Views . . . . . . . . . . . . . . . 17-3


Project-Wide Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-3
Filter Project File Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-5
More Ways to Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-6

Work with Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-7

Manage Shadowed and Dirty Models and Other Project Files . . . . . 17-8
Identify Shadowed Project Files When Opening a Project . . . . . . . . 17-8
Find Models and Other Project Files With Unsaved Changes . . . . . . 17-8
Manage Open Models and Data Dictionaries When Closing a Project
................................................. 17-9

Move, Rename, Copy, or Delete Project Files . . . . . . . . . . . . . . . . . 17-10


Move or Add Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-10
Automatic Updates When Renaming, Deleting, or Removing Files
................................................ 17-10

Back Out Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-15

Create Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-16

Add Labels to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-17

View and Edit Label Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-18

Automate Project Tasks Using Scripts . . . . . . . . . . . . . . . . . . . . . . . 17-19

Create a Custom Task Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-28

xxxii Contents
Run a Project Custom Task and Publish Report . . . . . . . . . . . . . . . 17-29

Sharing Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-31

Share Project by Email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-32

Share Project as a MATLAB Toolbox . . . . . . . . . . . . . . . . . . . . . . . . 17-33

Share Project on GitHub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-34

Archive Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-35

Analyze Model Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-37


Open and Explore Dependency Graph . . . . . . . . . . . . . . . . . . . . . . 17-37
Model Dependency Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-38
Find Required Products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-40
Export Dependency Analysis Results . . . . . . . . . . . . . . . . . . . . . . 17-40
Create Project from the Dependency Graph . . . . . . . . . . . . . . . . . 17-41

View Requirements Toolbox Links Associated with Model Elements


.................................................... 17-43
Highlight, Filter, and View Information for Links in a Model . . . . . 17-43
Navigate to Externally Stored Requirements from a Model . . . . . . 17-46

Identify and Run Tests in MATLAB Projects . . . . . . . . . . . . . . . . . . 17-49


Label Test Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17-49
Identify and Run All Tests in Project . . . . . . . . . . . . . . . . . . . . . . . 17-50
Create Test Suite from Project Test Files . . . . . . . . . . . . . . . . . . . 17-51

Project Dependency Analysis


18
Dependency Analyzer Scope and Limitations . . . . . . . . . . . . . . . . . . 18-2
Analysis Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2
Analysis Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-2

Run a Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-5

Explore the Dependency Graph, Views, and Filters . . . . . . . . . . . . . 18-7


Select, Pan, and Zoom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-7
Investigate Dependency Between Two Files . . . . . . . . . . . . . . . . . . 18-7
Color Files by Type, Status, or Label . . . . . . . . . . . . . . . . . . . . . . . . 18-8
Apply and Clear Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-13

Perform an Impact Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-15


About Impact Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-15
Run a Dependency Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-15
Find Required Products and Add-Ons . . . . . . . . . . . . . . . . . . . . . . 18-17
Find Dependencies of Selected Files . . . . . . . . . . . . . . . . . . . . . . . 18-18

Check Dependency Results and Resolve Problems . . . . . . . . . . . . . 18-21


Investigate Problem Files in Dependency Graph . . . . . . . . . . . . . . 18-24

xxxiii
Investigate Problem Files in File List . . . . . . . . . . . . . . . . . . . . . . 18-25

Find Requirements Documents in a Project . . . . . . . . . . . . . . . . . . 18-27

Export Dependency Analysis Results . . . . . . . . . . . . . . . . . . . . . . . . 18-28


Send Files to Project Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18-29

Project Source Control


19
About Source Control with Projects . . . . . . . . . . . . . . . . . . . . . . . . . . 19-2
Classic and Distributed Source Control . . . . . . . . . . . . . . . . . . . . . . 19-2

Add a Project to Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-5


Add a Project to Git Source Control . . . . . . . . . . . . . . . . . . . . . . . . 19-5
Add a Project to SVN Source Control . . . . . . . . . . . . . . . . . . . . . . . 19-5

Set Source Control Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-7


Source Control Preferences in MATLAB Online . . . . . . . . . . . . . . . . 19-7

Register Model Files with Source Control Tools . . . . . . . . . . . . . . . . 19-9

Set Up SVN Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-10


Set Up SVN Provided with Projects . . . . . . . . . . . . . . . . . . . . . . . . 19-10
Set Up Project SVN for SVN Version Already Installed . . . . . . . . . 19-11
Set Up Project SVN for SVN Version Not Yet Provided with Projects
................................................ 19-11
Register Model Files with Subversion . . . . . . . . . . . . . . . . . . . . . . 19-12
Enforce SVN Locking Model Files Before Editing . . . . . . . . . . . . . 19-14
Share a Subversion Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-15
Manage SVN Externals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-15

Set Up Git Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-17


Register Binary Files with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-17
Enable Support for Long Paths . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-18
Enable Signing Commits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-18
Configure MATLAB to Use Git SSH Authentication . . . . . . . . . . . . 19-18
Install Git Credential Helper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-22
Disable Compression for Simulink Models (Before R2023b) . . . . . 19-22
Configure Git to Use Git LFS . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-22
Configure External Git Tools to use MATLAB for Diff and Merge . . 19-22
Additional Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-23

Add Git Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-25


Update Submodules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-25
Use Fetch and Merge with Submodules . . . . . . . . . . . . . . . . . . . . 19-25
Use Push to Send Changes to the Submodule Repository . . . . . . . 19-25

Automatically Merge Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-27

Create New GitHub Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-29

xxxiv Contents
Disable Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-30

Change Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-31

Write a Source Control Integration with the SDK . . . . . . . . . . . . . 19-32

Clone Git Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-33

Check Out SVN Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-35

Tag and Retrieve Versions of Project Files . . . . . . . . . . . . . . . . . . . 19-37

Refresh Status of Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-38

Check for Modifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-39

Update Revisions of Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-40


Update Revisions with SVN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-40
Update Revisions with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-40
Update Selected Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-41

Get SVN File Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-42


Manage SVN Repository Locks . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-42

View Modified Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-44


Project Definition Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-44

Compare Revisions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-47

Run Project Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-49

Commit Modified Files to Source Control . . . . . . . . . . . . . . . . . . . . 19-50

Revert Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-52


Discard Local Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-52
Revert a File to a Specified Revision . . . . . . . . . . . . . . . . . . . . . . . 19-52
Revert the Project to a Specified Revision . . . . . . . . . . . . . . . . . . . 19-53

Pull, Push, and Fetch Files with Git . . . . . . . . . . . . . . . . . . . . . . . . . 19-54


Pull and Push . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-54
Pull, Fetch, and Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-55
Push Empty Folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-57
Use Git Stashes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-57

Branch and Merge Files with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-58


Create a Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-58
Switch Branch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-59
Compare Branches and Save Copies . . . . . . . . . . . . . . . . . . . . . . . 19-60
Merge Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-60
Revert to Head . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-61
Delete Branches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-61

Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-62


Resolve Conflicts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-62

xxxv
Merge Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-63
Merge Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-64
Extract Conflict Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-64

Work with Derived Files in Projects . . . . . . . . . . . . . . . . . . . . . . . . . 19-66

Customize External Source Control to Use MATLAB for Diff and


Merge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-67
Finding the Full Paths for MATLAB Diff, Merge, and AutoMerge . . 19-67
Integration with Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-68
Integration with SVN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-69
Integration with Other Source Control Tools . . . . . . . . . . . . . . . . . 19-70

Continuous Integration Using MATLAB Projects and Jenkins . . . 19-72


Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-72
Set Up MATLAB Project for Continuous Integration in Jenkins . . . 19-72
Reduce Test Runtime Using Dependency Cache and Impact Analysis
................................................ 19-73
Enhance Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-74

Determine Order for Resolving Conflicts Using Dependency Analyzer


.................................................... 19-76

Project Reference
20
Componentization Using Referenced Projects . . . . . . . . . . . . . . . . . 20-2

Add or Remove a Reference to Another Project . . . . . . . . . . . . . . . . 20-5

View, Edit, or Run Referenced Project Files . . . . . . . . . . . . . . . . . . . 20-6

Extract a Folder to Create a Referenced Project . . . . . . . . . . . . . . . . 20-7

Manage Referenced Project Changes Using Checkpoints . . . . . . . . 20-9

Compare Simulink Models


21
Review Changes in Simulink Models . . . . . . . . . . . . . . . . . . . . . . . . . 21-2
Comparison Tool Usage Tips and Limitations . . . . . . . . . . . . . . . . . 21-2

Select Models to Compare . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4


Compare Two Models on Disk . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-4
Compare Model to Revision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-5

Understand Simulink Model Comparison Changes . . . . . . . . . . . . . 21-7


Open Child Comparison Reports for Selected Nodes . . . . . . . . . . . . 21-9
Open and Highlight Changes in Simulink Editor . . . . . . . . . . . . . . . 21-9

xxxvi Contents
Simplify Comparison Report Using Filters . . . . . . . . . . . . . . . . . . 21-10

Port or Restore Model Changes in Comparison Report . . . . . . . . . 21-14


Recommended Merge Order in Models . . . . . . . . . . . . . . . . . . . . . 21-16

Resolve Conflicts in Models Under Source Control . . . . . . . . . . . . 21-17

Make Changes and Merge Git Local Branch . . . . . . . . . . . . . . . . . . 21-18

Identify Order of Resolving Conflicts in Changeset . . . . . . . . . . . . 21-22

Resolve Conflicts in Models Using Three-Way Merge . . . . . . . . . . . 21-24


Open Three-Way Merge Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-24
Resolve Conflicts in Changeset . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-25

Export, Print, and Save Model Comparison Results . . . . . . . . . . . . 21-33

Compare Model or Project Templates . . . . . . . . . . . . . . . . . . . . . . . 21-35

Set Up Simulink Diff and Merge in CI/CD Pipeline . . . . . . . . . . . . 21-36

Attach Model Comparison Report to GitHub Pull Requests . . . . . 21-38


Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-38
Attach Diff Reports Using GitHub Actions . . . . . . . . . . . . . . . . . . . 21-38
Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21-39

Design Evolution Management


22
Get Started with Design Evolution Manager . . . . . . . . . . . . . . . . . . . 22-2
Key Terms and Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2
Example Evolution Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-2

About Design Evolutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4


Evolutions and Evolution Trees . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-4

Manage Evolutions and Evolution Trees . . . . . . . . . . . . . . . . . . . . . . 22-6


Create Evolution Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-6
Create Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-8
Lock Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-8
Get Evolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-8
Delete Evolutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-9
Make Tree Active . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22-9
Managing Changes Made Outside the App . . . . . . . . . . . . . . . . . . . 22-9

Inspect Properties, Compare, and Merge Evolutions . . . . . . . . . . . 22-11


Inspect Properties of Evolution Tree, Evolutions, and Connectors
................................................ 22-11
Compare and Merge Evolutions . . . . . . . . . . . . . . . . . . . . . . . . . . 22-12

Use Design Evolution Manager with the Fixed-Point Tool . . . . . . . 22-13


Use Design Evolution Manager with Fixed-Point Tool . . . . . . . . . . 22-13

xxxvii
Large-Scale Modeling
23
Component-Based Modeling Guidelines . . . . . . . . . . . . . . . . . . . . . . 23-2
Should You Create Model Components? . . . . . . . . . . . . . . . . . . . . . 23-2
Define Model Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-3

Explore Types of Model Components . . . . . . . . . . . . . . . . . . . . . . . . . 23-4


Simulink Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-4
High-Level Component Selection Guidelines . . . . . . . . . . . . . . . . . . 23-5
Modeling Requirement Considerations . . . . . . . . . . . . . . . . . . . . . . 23-7

Compare Capabilities of Model Components . . . . . . . . . . . . . . . . . . 23-8


Collaboration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-8
Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-12
Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-14
Testing and Certification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-18
Interface Design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-20
Custom Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-21

Define Interfaces of Model Components . . . . . . . . . . . . . . . . . . . . . 23-24


Identify Component Boundaries . . . . . . . . . . . . . . . . . . . . . . . . . . 23-24
Simplify Interfaces with Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-24
Partition Interface Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-25
Configure Data Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-26

Configuration Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-28


Manage Designs Using Source Control . . . . . . . . . . . . . . . . . . . . . 23-28
Determine the Files Used by a Component . . . . . . . . . . . . . . . . . . 23-28
Manage Model Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-29
Create Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-29

Power Window Example


24
Power Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-2
Power Window Control Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-3
Quantitative Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-8
Implement Activity Diagram: Power Window Control . . . . . . . . . . 24-15
Interactive Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-17
Case 1: Window Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-19
Case 2: Window Auto-Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-22
Case 3: Driver-Side Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . 24-23
Model Coverage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-27
Create Model Using Model-Based Design . . . . . . . . . . . . . . . . . . . 24-31
Automatic Code Generation for Control Subsystem . . . . . . . . . . . . 24-45
References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24-46

xxxviii Contents
Schedule Editor
25
What are Partitions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2

Create Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-4


Partitioning a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-4
Create Partitions from a Rate-Based Model . . . . . . . . . . . . . . . . . . . 25-5
Export-Function Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-8

Using the Schedule Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-11


Using the Schedule Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-11

Schedule the Partitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-15


Schedule an Export-Function Model Using the Schedule Editor . . 25-15
Schedule a Rate-Based Model Using the Schedule Editor . . . . . . . 25-18

Generate Code from a Partitioned Model . . . . . . . . . . . . . . . . . . . . 25-22

Export-Function Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-26

Create and Analyze Random Schedules for a Model Using the


Schedule Editor API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-27

Events in Schedule Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-33


Event Management in the Schedule Editor . . . . . . . . . . . . . . . . . . 25-33
Schedule Partitions with Events . . . . . . . . . . . . . . . . . . . . . . . . . . 25-37
Test Harness Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-44
Limitations and Error Conditions . . . . . . . . . . . . . . . . . . . . . . . . . 25-45

Software Modeling
26
Software Component Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-2
Create Models of Software Components . . . . . . . . . . . . . . . . . . . . . 26-2
Create Model of Target Environment . . . . . . . . . . . . . . . . . . . . . . . 26-6
Test System by Simulating Composition Model . . . . . . . . . . . . . . . . 26-7
Integrate Components into Software Architectures . . . . . . . . . . . . . 26-7
Design Software Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26-7
Generate Code for Software Components . . . . . . . . . . . . . . . . . . . . 26-8

xxxix
Simulating Dynamic Systems

Running Simulations
27
Simulate a Model Interactively . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-2
Simulation Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-2
Run, Pause, and Stop a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 27-3
Use Blocks to Stop or Pause a Simulation . . . . . . . . . . . . . . . . . . . . 27-3

Use Local Solvers in Referenced Models . . . . . . . . . . . . . . . . . . . . . . 27-5


How Local Solvers Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-5
How to Configure Local Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-6
Additional Considerations for Local Solvers . . . . . . . . . . . . . . . . . . 27-6

Choose a Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8


Automatic Solver Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-8
Solver Selection Criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-10

Choose a Jacobian Method for an Implicit Solver . . . . . . . . . . . . . 27-13


Sparsity of Jacobian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-13
Solver Jacobian Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-13
Heuristic 'auto' Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-14
Full and Sparse Perturbation Methods . . . . . . . . . . . . . . . . . . . . . 27-15
Full and Sparse Analytical Methods . . . . . . . . . . . . . . . . . . . . . . . 27-16
Code Generation Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-17

Variable Step Solvers in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . 27-18


Variable-Step Discrete Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-18
Variable-Step Continuous Solvers . . . . . . . . . . . . . . . . . . . . . . . . . 27-19
Variable-Step Continuous Explicit Solvers . . . . . . . . . . . . . . . . . . . 27-20
Variable-Step Continuous Implicit Solvers . . . . . . . . . . . . . . . . . . . 27-21
Error Tolerances for Variable-Step Solvers . . . . . . . . . . . . . . . . . . 27-23

Fixed Step Solvers in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25


Fixed-Step Discrete Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25
Fixed-Step Continuous Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-25

Choose a Fixed-Step Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-29


When to Use a Fixed-Step Solver . . . . . . . . . . . . . . . . . . . . . . . . . 27-29
Establish Baseline Results Using a Variable-Step Solver . . . . . . . . 27-30
Run Fixed-Step Simulations of the Model . . . . . . . . . . . . . . . . . . . 27-32
Compare Fixed-Step Simulations with the Variable-Step Baseline
................................................ 27-33

Use Model Operating Point for Faster Simulation Workflow . . . . . 27-42


Save Model Operating Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-43
Restore Model Operating Points . . . . . . . . . . . . . . . . . . . . . . . . . . 27-44
Additional Considerations for Saving and Restoring Model Operating
Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-45

Specify Initial State for Simulation . . . . . . . . . . . . . . . . . . . . . . . . . 27-50

xl Contents
Systematic Diagnosis of Errors and Warnings . . . . . . . . . . . . . . . . 27-56

Suppress Diagnostic Messages Programmatically . . . . . . . . . . . . . 27-59


Suppress Diagnostic Messages Programmatically . . . . . . . . . . . . . 27-59
Suppress Diagnostic Messages of a Referenced Model . . . . . . . . . 27-61

Customize Diagnostic Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-65


Display Custom Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-65
Create Hyperlinks to Files, Folders, or Blocks . . . . . . . . . . . . . . . . 27-65
Create Programmatic Hyperlinks . . . . . . . . . . . . . . . . . . . . . . . . . 27-66

Report Diagnostic Messages Programmatically . . . . . . . . . . . . . . . 27-67


Create Diagnostic Stages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-67
Report Diagnostic Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-67
Log Diagnostic Messages in a File . . . . . . . . . . . . . . . . . . . . . . . . 27-68

View and Trace Callbacks in Models . . . . . . . . . . . . . . . . . . . . . . . . 27-70


Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-72
Stage-Specific Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-73
Search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-73
Export . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27-73
Trace Callbacks Programmatically . . . . . . . . . . . . . . . . . . . . . . . . 27-73

Running a Simulation Programmatically


28
Run Simulations Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . 28-2
Decide How to Run or Script Programmatic Simulations . . . . . . . . . 28-2
Run and Script Simulations Using sim Function . . . . . . . . . . . . . . . 28-4
Run and Script Simulations Using Simulation Objects . . . . . . . . . . . 28-5
Interact with Simulations by Issuing Simulation Commands . . . . . . 28-8

Run Parallel Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-11


How parsim Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-11

Using sim Function Within parfor . . . . . . . . . . . . . . . . . . . . . . . . . . 28-14


Overview of Calling sim from Within parfor . . . . . . . . . . . . . . . . . 28-14

Error Handling in Simulink Using MSLException Objects . . . . . . 28-23


Error Reporting in Simulink Applications . . . . . . . . . . . . . . . . . . . 28-23
MSLException Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23
MSLException Object Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 28-23
Capturing Information About the Error . . . . . . . . . . . . . . . . . . . . . 28-23

Multiple Simulations
29
Running Multiple Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-2
Multiple Simulations with Simulink Editor . . . . . . . . . . . . . . . . . . . 29-2

xli
Multiple Simulations with Parallel Computing Toolbox . . . . . . . . . . 29-2
Multiple Simulations with the sim Function . . . . . . . . . . . . . . . . . . 29-3
Multiple Simulations with Simulink.SimulationInput Object . . . . . . 29-3
Simulation Manager to Monitor Simulations . . . . . . . . . . . . . . . . . . 29-3
The parsim/batchsim Function Capabilities . . . . . . . . . . . . . . . . . . . 29-3
Data Logging for Multiple Simulations . . . . . . . . . . . . . . . . . . . . . . 29-4

Run Parallel Simulations for a Thermal Model of a House Using


parsim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-5
Run Multiple Parallel Simulations with Different Set Points . . . . . . . 29-5
View the Runs in the Simulation Manager . . . . . . . . . . . . . . . . . . . . 29-6

Comparison Between Multiple Simulation Workflows . . . . . . . . . . 29-10


parsim Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-11
batchsim Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-12

Analyze Results Using Simulation Manager . . . . . . . . . . . . . . . . . . 29-14


Open Simulation Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-14
Add and Configure Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-16
Save and Load Simulation Manager . . . . . . . . . . . . . . . . . . . . . . . 29-17

Configure and Run Simulations with Multiple Simulations Panel


.................................................... 29-19
Workflow for Multiple Simulations Panel . . . . . . . . . . . . . . . . . . . . 29-19
Video Walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-24

Multiple Simulations Panel: Simulate for Different Values of


Stiffness for a Vehicle Dynamics System . . . . . . . . . . . . . . . . . . . 29-26

Control a Simulink Simulation with App Designer . . . . . . . . . . . . 29-31

Load and Save External Inputs for a Simulink Model with App
Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-35

Visualizing and Comparing Simulation Results


30
Prototype and Debug Models with Scopes . . . . . . . . . . . . . . . . . . . . 30-2

Scope Blocks and Scope Viewer Overview . . . . . . . . . . . . . . . . . . . . . 30-6


Overview of Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-6
Simulink Scope Versus Floating Scope . . . . . . . . . . . . . . . . . . . . . . 30-6
Simulink Scope Versus DSP System Toolbox Time Scope . . . . . . . . . 30-8

Scope Trace Selection Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-11

Scope Triggers Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12


What Is the Trigger Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12
Main Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-12
Source/Type and Levels/Timing Panes . . . . . . . . . . . . . . . . . . . . . 30-13
Hysteresis of Trigger Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-21
Delay/Holdoff Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-22

xlii Contents
Cursor Measurements Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-23

Scope Signal Statistics Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-25

Scope Bilevel Measurements Panel . . . . . . . . . . . . . . . . . . . . . . . . . 30-27


Bilevel Measurements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-27
Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-27
Transitions Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-30
Overshoots / Undershoots Pane . . . . . . . . . . . . . . . . . . . . . . . . . . 30-32
Cycles Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-34

Peak Finder Measurements Panel . . . . . . . . . . . . . . . . . . . . . . . . . . 30-36

Spectrum Analyzer Cursor Measurements Panel . . . . . . . . . . . . . . 30-39

Spectrum Analyzer Channel Measurements Panel . . . . . . . . . . . . . 30-41

Spectrum Analyzer Distortion Measurements Panel . . . . . . . . . . . 30-43

Spectral Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-47


Set Up Spectral Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-47
Check Spectral Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-48

Spectrum Analyzer CCDF Measurements Panel . . . . . . . . . . . . . . . 30-49

Common Scope Block Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-51


Connect Multiple Signals to a Scope . . . . . . . . . . . . . . . . . . . . . . . 30-51
Save Simulation Data Using Scope Block . . . . . . . . . . . . . . . . . . . 30-53
Pause Display While Running . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-55
Copy Scope Image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-55
Plot an Array of Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-57
Scopes in Referenced Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-58
Scopes Within an Enabled Subsystem . . . . . . . . . . . . . . . . . . . . . . 30-62
Modify x-axis of Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-63
Show Signal Units on a Scope Display . . . . . . . . . . . . . . . . . . . . . 30-66
Select Number of Displays and Layout . . . . . . . . . . . . . . . . . . . . . 30-68
Dock and Undock Scope Window to MATLAB Desktop . . . . . . . . . 30-69

View Values of Parameters Set as Variables . . . . . . . . . . . . . . . . . . 30-70


In-Place Parameter Value Display for Different Data Types . . . . . . 30-70
In-Place Parameter Value Display for Variables Defined in Multiple
Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-71
Turn Off In-Place Parameter Value Display . . . . . . . . . . . . . . . . . . 30-71

Floating Scope and Scope Viewer Tasks . . . . . . . . . . . . . . . . . . . . . 30-73


Add Floating Scope Block to Model and Connect Signals . . . . . . . 30-73
Add Scope Viewer to a Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-74
Add Signals to an Existing Floating Scope or Scope Viewer . . . . . 30-74
Save Simulation Data from Floating Scope . . . . . . . . . . . . . . . . . . 30-75
Add and Manage Viewers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-78
Quickly Switch Visualization of Different Signals on a Floating Scope
................................................ 30-79

Generate Signals Without Source Blocks . . . . . . . . . . . . . . . . . . . . 30-81


Attach Signal Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-81

xliii
Modify Signal Generator Parameters . . . . . . . . . . . . . . . . . . . . . . 30-81
Remove Signal Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-82

Viewers and Generators Manager . . . . . . . . . . . . . . . . . . . . . . . . . . 30-83


Open the Viewers and Generators Manager . . . . . . . . . . . . . . . . . 30-83
Change Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-83
Connect Viewers and Generators . . . . . . . . . . . . . . . . . . . . . . . . . 30-83
View Test Point Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-84
Customize Viewers and Generators Manager . . . . . . . . . . . . . . . . 30-84
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-85

Control Scope Blocks Programmatically . . . . . . . . . . . . . . . . . . . . . 30-86

Plot a Circle Using the XY Graph Block . . . . . . . . . . . . . . . . . . . . . . 30-88

Sample Time with Scope Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-92

Inspecting and Comparing Simulation Data


31
View Simulation Data in Simulation Data Inspector . . . . . . . . . . . . 31-2
View Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-2
View Complex Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-3
View String Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-6
View Multidimensional Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-9
View Frame-Based Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-12
View Event-Based Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-13

Import Data from Workspace or File into Simulation Data Inspector


.................................................... 31-15
Import Data From Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-15
Import Data From File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-18

Import Workspace Variables Using a Custom Data Reader . . . . . . 31-21

Import Data Using Custom File Reader . . . . . . . . . . . . . . . . . . . . . . 31-27

View and Replay Map Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-32

Visualize Simulation Data on XY Plot . . . . . . . . . . . . . . . . . . . . . . . 31-41

Analyze Data Using XY Plot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-52

View Many Signals Together Using Sparklines . . . . . . . . . . . . . . . . 31-60

View Multidimensional Signals Using the Array Plot . . . . . . . . . . . 31-68

Microsoft Excel Import, Export, and Logging Format . . . . . . . . . . 31-77


Basic File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-77
Multiple Time Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-77
Signal Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-78
User-Defined Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-80

xliv Contents
Complex, Multidimensional, and Bus Signals . . . . . . . . . . . . . . . . 31-82
Function-Call Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-83
Simulation Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-83
Multiple Runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-83

Import Data from a CSV File into the Simulation Data Inspector
.................................................... 31-85
Basic File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-85
Multiple Time Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-85
Signal Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-86
Import Data from a CSV File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-87

Configure the Simulation Data Inspector . . . . . . . . . . . . . . . . . . . . 31-90


Logged Data Size and Location . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-90
Archive Behavior and Run Limit . . . . . . . . . . . . . . . . . . . . . . . . . . 31-91
Incoming Run Names and Location . . . . . . . . . . . . . . . . . . . . . . . . 31-92
Signal Metadata to Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-93
Signal Selection on the Inspect Pane . . . . . . . . . . . . . . . . . . . . . . 31-94
How Signals Are Aligned for Comparison . . . . . . . . . . . . . . . . . . . 31-94
Colors Used to Display Comparison Results . . . . . . . . . . . . . . . . . 31-95
Signal Grouping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-95
Data to Stream from Parallel Simulations . . . . . . . . . . . . . . . . . . . 31-96
Options for Saving and Loading Session Files . . . . . . . . . . . . . . . . 31-96
Signal Display Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-96

View Streaming Data in the Simulation Data Inspector . . . . . . . . 31-98


Open and Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-98
Change Time Span . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-99
Control Plot Update Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-101
Hold Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-102
Control Display Scaling and Display Offset . . . . . . . . . . . . . . . . . 31-103

Control Display of Streaming Data Using Triggers . . . . . . . . . . . 31-106


Examine the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-106
Interactively Generate Trigger Events . . . . . . . . . . . . . . . . . . . . 31-107
Capture Signal Transient Response . . . . . . . . . . . . . . . . . . . . . . 31-109
Stabilize a Steady-State Periodic Signal . . . . . . . . . . . . . . . . . . . 31-110

Synchronize Cursors in the Simulation Data Inspector with an App


Designer App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-113
Open and Run the Cursors App . . . . . . . . . . . . . . . . . . . . . . . . . . 31-113
Examine the App Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-115

Iterate Model Design Using the Simulation Data Inspector . . . . 31-119


View and Inspect Signals During Simulation . . . . . . . . . . . . . . . . 31-119
Automatically Transfer View to Current Simulation . . . . . . . . . . 31-121
Control Data Retention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-123
Visualize Many Logged Signals . . . . . . . . . . . . . . . . . . . . . . . . . . 31-124

Access Data in MATLAB Function During Simulation . . . . . . . . . 31-128


Write Callback Function for Data Access . . . . . . . . . . . . . . . . . . 31-128
Configure Signals for Data Access . . . . . . . . . . . . . . . . . . . . . . . 31-129

Analyze Multidimensional Signal Data . . . . . . . . . . . . . . . . . . . . . 31-131


Convert Representation of Multidimensional Data . . . . . . . . . . . 31-131

xlv
Plot Multidimensional Signal Data . . . . . . . . . . . . . . . . . . . . . . . 31-133
Compare Multidimensional Signals . . . . . . . . . . . . . . . . . . . . . . . 31-134
Convert Representation of Frame-Based Data . . . . . . . . . . . . . . . 31-134

Analyze Data from Multiple Simulations . . . . . . . . . . . . . . . . . . . . 31-136


Open and Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-136
Create and Save Views to Analyze Simulation Results . . . . . . . . . 31-136
Load a View and Plot Signals Side by Side . . . . . . . . . . . . . . . . . 31-139
Swap Source Run for Plotted Signals . . . . . . . . . . . . . . . . . . . . . 31-143

Save and Share Simulation Data Inspector Data and Views . . . . 31-148
Save and Load Simulation Data Inspector Sessions . . . . . . . . . . . 31-148
Share Simulation Data Inspector Views . . . . . . . . . . . . . . . . . . . 31-149
Share Simulation Data Inspector Plots . . . . . . . . . . . . . . . . . . . . 31-150
Create Simulation Data Inspector Report . . . . . . . . . . . . . . . . . . 31-150
Export Data to Workspace or File . . . . . . . . . . . . . . . . . . . . . . . . 31-152
Export Video Signal to MP4 File . . . . . . . . . . . . . . . . . . . . . . . . . 31-153

Create Interactive Comparison Reports . . . . . . . . . . . . . . . . . . . . 31-154

Create Plots Using the Simulation Data Inspector . . . . . . . . . . . . 31-161


Add Visualizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-161
Select Plot Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-164
View Simulation Data Using Time Plot . . . . . . . . . . . . . . . . . . . . 31-165
Add Text to Plot Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-168
Add Subplots to Visualize Data . . . . . . . . . . . . . . . . . . . . . . . . . . 31-170
Customize Time Plot Appearance . . . . . . . . . . . . . . . . . . . . . . . . 31-170
Customize Signal Appearance . . . . . . . . . . . . . . . . . . . . . . . . . . 31-172
Shade Signal Regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-174
Rename Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-177

Inspect Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-179


Configure Signals for Logging . . . . . . . . . . . . . . . . . . . . . . . . . . 31-179
View Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-179
View Signals on Multiple Plots . . . . . . . . . . . . . . . . . . . . . . . . . . 31-180
Zoom, Pan, and Resize Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-182
Inspect Simulation Data Using Cursors . . . . . . . . . . . . . . . . . . . . 31-184
Replay Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-187
Inspect Metadata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-188

Modify Signal Properties in the Simulation Data Inspector . . . . 31-193


Modify Signal Units . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-193
Modify Signal Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-195
Modify Signal Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-196

Replay Data in the Simulation Data Inspector . . . . . . . . . . . . . . . 31-198

Compare Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-203


Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-203
Compare Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-204
Compare Runs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-207
Configure Comparison Constraints . . . . . . . . . . . . . . . . . . . . . . . 31-211
Cancel Comparisons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-213

xlvi Contents
How the Simulation Data Inspector Compares Data . . . . . . . . . . 31-214
Signal Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-214
Synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-215
Interpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-216
Tolerance Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-216
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-218

Inspect and Compare Data Programmatically . . . . . . . . . . . . . . . 31-219


Create Run and View Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-219
Compare Two Signals in the Same Run . . . . . . . . . . . . . . . . . . . . 31-221
Compare Runs with Global Tolerance . . . . . . . . . . . . . . . . . . . . . 31-221
Analyze Simulation Data Using Signal Tolerances . . . . . . . . . . . . 31-222

Keyboard Shortcuts for the Simulation Data Inspector . . . . . . . . 31-225


General Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-225
Plot Zooming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-225
Data Cursors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-225
Signal Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-226
Import Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31-226

Control Simulations with Interactive Displays


32
Tune and Visualize Your Model with Dashboard Blocks . . . . . . . . . . 32-2
Explore Connections Within the Model . . . . . . . . . . . . . . . . . . . . . . 32-2
Simulate Changing Model States . . . . . . . . . . . . . . . . . . . . . . . . . . 32-3
View Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-4
Tune Parameters During Simulation . . . . . . . . . . . . . . . . . . . . . . . . 32-5

Connect Dashboard Blocks to Simulink Model . . . . . . . . . . . . . . . . . 32-7


Connect Interactive Controls and Displays . . . . . . . . . . . . . . . . . . . 32-7
Connect Dashboard Blocks to Matrices and Structures . . . . . . . . . 32-12

Getting Started with Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-19


Open Example Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-20
Create Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-20
Populate and Edit Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-22
Manage Panel Visibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-29

Use Panels to Monitor Signals and Control Parameters . . . . . . . . 32-37


Open Example Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-37
Create Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-38
Simulate Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-41

Create Tabbed Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-43


Open Example Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-44
Create Panels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-45
Add Empty Tab to Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-48
Detach Tab from Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-49
Attach Tab or Freestanding Panel to Another Panel . . . . . . . . . . . . 32-50
Reorder Panel Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-52

xlvii
Deploy Dashboard Panel as App . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-54
Check Deployment Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-54
Plan Ahead to Avoid Simulation Errors . . . . . . . . . . . . . . . . . . . . . 32-54
Deploy Panel as Standalone App . . . . . . . . . . . . . . . . . . . . . . . . . . 32-55
Deploy Panel as Web App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-56
Run Simulation from Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-57

Create Dashboard Panel for Climate Control System . . . . . . . . . . . 32-58

Design Custom Gauges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-68

Design Custom Knobs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-77

Design Custom Lamps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-88

Design Custom Rocker, Slider, and Toggle Switches . . . . . . . . . . 32-107

Design Custom Buttons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-121

Design Custom Rotary Switches . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-141

Design Custom Sliders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32-156

Connect Interactive Controls and Displays . . . . . . . . . . . . . . . . . . 32-180

Connect Dashboard Blocks to Matrices and Structures . . . . . . . 32-185

Analyzing Simulation Results


33
Decide How to Visualize Simulation Data . . . . . . . . . . . . . . . . . . . . . 33-2
Simulation Data Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-2
Scope Blocks and the Scope Viewer . . . . . . . . . . . . . . . . . . . . . . . . 33-3
Record Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-5
Dashboard Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-6
Port Value Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-7
Custom MATLAB Visualizations . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-8

Linearizing Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33-9

Improving Simulation Performance and Accuracy


34
How Optimization Techniques Improve Performance and Accuracy
..................................................... 34-2

Speed Up Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-3

xlviii Contents
How Simulink Profiler Captures Performance Data . . . . . . . . . . . . . 34-5
How Simulink Profiler Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-5
Start Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-6
Save Profiler Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-10

Check and Improve Simulation Accuracy . . . . . . . . . . . . . . . . . . . . 34-12


Check Simulation Accuracy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-12
Unstable Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-12
Inaccurate Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-12

Modeling Techniques That Improve Performance . . . . . . . . . . . . . 34-14


Accelerate the Initialization Phase . . . . . . . . . . . . . . . . . . . . . . . . 34-14
Reduce Model Interactivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-14
Reduce Model Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-15
Choose and Configure a Solver . . . . . . . . . . . . . . . . . . . . . . . . . . . 34-16
Save the Model Operating Point . . . . . . . . . . . . . . . . . . . . . . . . . . 34-17

Use Performance Advisor to Improve Simulation Efficiency . . . . . 34-19

Understanding Total Time and Self Time in Profiler Reports . . . . 34-20

Performance Advisor
35
Improve Simulation Performance Using Performance Advisor . . . . 35-2
Performance Advisor Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-2
Prepare Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-3
Create a Performance Advisor Baseline Measurement . . . . . . . . . . 35-4
Run Performance Advisor Checks . . . . . . . . . . . . . . . . . . . . . . . . . . 35-5
View and Respond to Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-6
View and Save Performance Advisor Reports . . . . . . . . . . . . . . . . . 35-8

Perform a Quick Scan Diagnosis . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-11


Run Quick Scan on a Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-11
Checks in Quick Scan Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-11

Improve vdp Model Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-12


Enable Data Logging for the Model . . . . . . . . . . . . . . . . . . . . . . . 35-12
Create Baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-12
Select Checks and Run . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-13
Review Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-13
Apply Advice and Validate Manually . . . . . . . . . . . . . . . . . . . . . . . 35-15

Use Hardware Acceleration to Speed Up Simulation for Object


Detection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35-16

xlix
Solver Profiler
36
Examine Model Dynamics Using Solver Profiler . . . . . . . . . . . . . . . . 36-2

Zero-Crossing Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-5

Solver Exception Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-7


Tolerance-Exceeding Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-7
Newton Iteration Failures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-8
Infinite State and Infinite Derivative Exceptions . . . . . . . . . . . . . . 36-10
Differential Algebraic Equation Failures . . . . . . . . . . . . . . . . . . . . 36-11

Solver Resets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-14


Zero-Crossing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-14
Discrete Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-15
ZOH Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-16
Block Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-18
Initial Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-20
Internal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-20

Jacobian Logging and Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-21

Modify Solver Profiler Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-23


Change Thresholds of Profiler Rules . . . . . . . . . . . . . . . . . . . . . . . 36-23
Develop Profiler Rule Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-23

Customize State Ranking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-25

Solver Profiler Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-27


Toolstrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-27
Statistics Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-27
Suggestions Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36-28

Debug Simulations
37
Simulink Debugging Programmatic Interface . . . . . . . . . . . . . . . . . 37-2
Use Simulink Debugging Functions . . . . . . . . . . . . . . . . . . . . . . . . 37-2
Use MATLAB Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-2
Understand Block and Method IDs . . . . . . . . . . . . . . . . . . . . . . . . . 37-2
Set and Manage Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-3
Display Information About the Simulation . . . . . . . . . . . . . . . . . . . . 37-3
Display Information About the Model . . . . . . . . . . . . . . . . . . . . . . . 37-4
Use Simulation Debugging Commands While Debugging from Simulink
Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-4

Debug Simulation of Iterator Subsystem . . . . . . . . . . . . . . . . . . . . . 37-7


Open Example Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-7
Add Port Value Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-8
Set Breakpoint to Pause Within Time Step . . . . . . . . . . . . . . . . . . . 37-9

l Contents
Step Through Block Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-9
Step into While-Iterator Subsystem . . . . . . . . . . . . . . . . . . . . . . . 37-10
Pause on Specific Iteration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-12
View Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37-15
End Simulation Debugging Session . . . . . . . . . . . . . . . . . . . . . . . . 37-17

Accelerating Models
38
What Is Acceleration? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-2

How Acceleration Modes Work . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-3


Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-3
Normal Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-3
Accelerator Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-4
Rapid Accelerator Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-5

Code Regeneration in Accelerated Models . . . . . . . . . . . . . . . . . . . . 38-7


Determine If the Simulation Will Rebuild . . . . . . . . . . . . . . . . . . . . 38-7
Parameter Tuning in Rapid Accelerator Mode . . . . . . . . . . . . . . . . . 38-7

Choosing a Simulation Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-10


Simulation Mode Tradeoffs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-10
Comparing Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-11
Decision Tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-12

Design Your Model for Effective Acceleration . . . . . . . . . . . . . . . . . 38-14


Select Blocks for Accelerator Mode . . . . . . . . . . . . . . . . . . . . . . . 38-14
Select Blocks for Rapid Accelerator Mode . . . . . . . . . . . . . . . . . . 38-14
Control S-Function Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-15
Accelerator and Rapid Accelerator Mode Data Type Considerations
................................................ 38-15
Behavior of Scopes and Viewers with Rapid Accelerator Mode . . . 38-16
Factors Inhibiting Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-16

Perform Acceleration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-19


Customize the Build Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-19
Run Acceleration Mode from the User Interface . . . . . . . . . . . . . . 38-19
Making Run-Time Changes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-20
Switching Solvers between Runs . . . . . . . . . . . . . . . . . . . . . . . . . 38-21

Interact with the Acceleration Modes Programmatically . . . . . . . 38-22


Why Interact Programmatically? . . . . . . . . . . . . . . . . . . . . . . . . . . 38-22
Build JIT Accelerated Execution Engine . . . . . . . . . . . . . . . . . . . . 38-22
Control Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-22
Simulate Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-22
Customize the Acceleration Build Process . . . . . . . . . . . . . . . . . . . 38-23

Comparing Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-25


Performance When Target Must Be Rebuilt . . . . . . . . . . . . . . . . . . 38-25
Performance When Targets Are Up to Date . . . . . . . . . . . . . . . . . . 38-26
Analyze Performance of Simulation Modes . . . . . . . . . . . . . . . . . . 38-26

li
How to Improve Performance in Acceleration Modes . . . . . . . . . . 38-30
Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-30
C Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-30

Create Apps to Control Simulations Using App Designer


39
Create App for Simulink Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39-2

Connect UI Components to Simulink Model Elements . . . . . . . . . . 39-8


Connect UI Components to Model Variables . . . . . . . . . . . . . . . . . . 39-8
Connect UI Components to Signals . . . . . . . . . . . . . . . . . . . . . . . . . 39-9
Modify Bindings in App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39-9

Managing Blocks

Working with Blocks


40
Nonvirtual and Virtual Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-2

Specify Block Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-4


Set Block Annotation Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-4
Specify Block Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-4
Specify Block Execution Order, Execution Priority and Tag . . . . . . . 40-5
Use Block Description to Identify a Block . . . . . . . . . . . . . . . . . . . . 40-6
Create Block Annotations Programmatically . . . . . . . . . . . . . . . . . . 40-7

View Signal Values Using Port Value Labels . . . . . . . . . . . . . . . . . . . 40-8


Add and Remove Port Value Labels . . . . . . . . . . . . . . . . . . . . . . . . . 40-8
Configure Port Value Label Settings . . . . . . . . . . . . . . . . . . . . . . . . 40-9
Configure Port Value Labels for Buses . . . . . . . . . . . . . . . . . . . . . 40-10
Understand Text Displayed in Port Value Labels . . . . . . . . . . . . . . 40-12
Additional Considerations for Using Port Value Labels . . . . . . . . . 40-14

Control and Display Execution Order . . . . . . . . . . . . . . . . . . . . . . . 40-16


Execution Order viewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-16
Navigation from Blocks to Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . 40-18
Execution Order Notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-19
Determining Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-22
Check for Execution Order Changes Involving Data Store Memory
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-28

Access Block Data During Simulation . . . . . . . . . . . . . . . . . . . . . . . 40-31


About Block Run-Time Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-31
Access a Run-Time Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40-31

lii Contents
Listen for Method Execution Events . . . . . . . . . . . . . . . . . . . . . . . 40-31
Synchronizing Run-Time Objects and Simulink Execution . . . . . . . 40-32

Working with Block Parameters


41
Set Block Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-2
Programmatically Access Parameter Values . . . . . . . . . . . . . . . . . . 41-2
Specify Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-3
Considerations for Other Modeling Goals . . . . . . . . . . . . . . . . . . . . 41-7

Share and Reuse Block Parameter Values by Creating Variables . . 41-9


Reuse Parameter Values in Multiple Blocks and Models . . . . . . . . . 41-9
Define a System Constant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-10
Set Variable Value by Using a Mathematical Expression . . . . . . . . 41-10
Control Scope of Parameter Values . . . . . . . . . . . . . . . . . . . . . . . . 41-12
Permanently Store Workspace Variables . . . . . . . . . . . . . . . . . . . . 41-13
Manage and Edit Workspace Variables . . . . . . . . . . . . . . . . . . . . . 41-14
Package Shared Breakpoint and Table Data for Lookup Tables . . . 41-14

Parameter Interfaces for Reusable Components . . . . . . . . . . . . . . 41-17


Referenced Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-17
Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-17

Organize Related Block Parameter Definitions in Structures . . . . 41-19


Create and Use Parameter Structure . . . . . . . . . . . . . . . . . . . . . . 41-19
Store Data Type Information in Field Values . . . . . . . . . . . . . . . . . 41-20
Control Field Data Types and Characteristics by Creating Parameter
Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-21
Manage Structure Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-23
Define Parameter Hierarchy by Creating Nested Structures . . . . . 41-23
Group Multiple Parameter Structures into an Array . . . . . . . . . . . 41-24
Create a Structure of Constant-Valued Signals . . . . . . . . . . . . . . . 41-26
Considerations Before Migrating to Parameter Structures . . . . . . 41-27
Combine Existing Parameter Objects into a Structure . . . . . . . . . . 41-27
Parameter Structures in the Generated Code . . . . . . . . . . . . . . . . 41-28
Parameter Structure Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 41-29
Package Shared Breakpoint and Table Data for Lookup Tables . . . 41-29
Create Parameter Structure According to Structure Type from Existing
C Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-29

Tune and Experiment with Block Parameter Values . . . . . . . . . . . . 41-31


Iteratively Adjust Block Parameter Value Between Simulation Runs
................................................ 41-31
Tune Block Parameter Value During Simulation . . . . . . . . . . . . . . 41-32
Prepare for Parameter Tuning and Experimentation . . . . . . . . . . . 41-33
Interactively Tune Using Dashboard Blocks . . . . . . . . . . . . . . . . . 41-34
Which Block Parameters Are Tunable During Simulation? . . . . . . . 41-34
Why Did the Simulation Output Stay the Same? . . . . . . . . . . . . . . 41-35
Tunability Considerations and Limitations for Other Modeling Goals
................................................ 41-36

liii
Optimize, Estimate, and Sweep Block Parameter Values . . . . . . . . 41-38
Sweep Parameter Value and Inspect Simulation Results . . . . . . . . 41-38
Store Sweep Values in Simulink.SimulationInput Objects . . . . . . . 41-41
Capture and Visualize Simulation Results . . . . . . . . . . . . . . . . . . . 41-42
Improve Simulation Speed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-42
Sweep Parameter Values to Test and Verify System . . . . . . . . . . . . 41-42
Estimate and Calibrate Model Parameters . . . . . . . . . . . . . . . . . . 41-43
Tune and Optimize PID and Controller Parameters . . . . . . . . . . . . 41-43

Control Block Parameter Data Types . . . . . . . . . . . . . . . . . . . . . . . . 41-44


Reduce Maintenance Effort with Data Type Inheritance . . . . . . . . 41-44
Techniques to Explicitly Specify Parameter Data Types . . . . . . . . . 41-45
Use the Model Data Editor for Batch Editing . . . . . . . . . . . . . . . . 41-45
Calculate Best-Precision Fixed-Point Scaling for Tunable Block
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-46
Detect Numerical Accuracy Issues Due to Quantization and Overflow
................................................ 41-49
Reuse Custom C Data Types for Parameter Data . . . . . . . . . . . . . . 41-49
Data Types of Mathematical Expressions . . . . . . . . . . . . . . . . . . . 41-49
Block Parameter Data Types in the Generated Code . . . . . . . . . . . 41-50

Specify Minimum and Maximum Values for Block Parameters . . . 41-52


Specify Parameter Value Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . 41-52
Restrict Allowed Values for Block Parameters . . . . . . . . . . . . . . . . 41-53
Specify Range Information for Tunable Fixed-Point Parameters . . 41-54
Unexpected Errors or Warnings for Data with Greater Precision or
Range than double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-54
Optimize Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-55

Switch Between Sets of Parameter Values During Simulation and


Code Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41-56

Working with Lookup Tables


42
About Lookup Table Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-2

Anatomy of a Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-4

Guidelines for Choosing a Lookup Table . . . . . . . . . . . . . . . . . . . . . . 42-5


Data Set Dimensionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-5
Data Set Numeric and Data Types . . . . . . . . . . . . . . . . . . . . . . . . . 42-5
Data Accuracy and Smoothness . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-5
Dynamics of Table Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-5
Efficiency of Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-6
Summary of Lookup Table Block Features . . . . . . . . . . . . . . . . . . . . 42-6

Breakpoint and Table Size Features in Lookup Tables . . . . . . . . . . . 42-8


Tunable Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-8
Symbolic Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-8
Reusable Struct Data Types for Different Breakpoint and Table Array
Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-9

liv Contents
Characteristics of Lookup Table Data . . . . . . . . . . . . . . . . . . . . . . . 42-12
Sizes of Breakpoint Vectors and Table Data . . . . . . . . . . . . . . . . . . 42-12
Monotonicity of Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-13
Formulation of Evenly Spaced Breakpoints . . . . . . . . . . . . . . . . . . 42-13

Methods for Approximating Function Values . . . . . . . . . . . . . . . . . 42-15


About Approximating Function Values . . . . . . . . . . . . . . . . . . . . . 42-15
Interpolation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-15
Extrapolation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-16
Rounding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-17
Example Output for Lookup Methods . . . . . . . . . . . . . . . . . . . . . . 42-17

Use the Lookup Table Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-19


Start the Lookup Table Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-20
Edit Lookup Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-21
Lookup Table Editor Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 42-22

Edit Lookup Table Data with Lookup Table Spreadsheet . . . . . . . . 42-23


Lookup Table Spreadsheet Data Type Support . . . . . . . . . . . . . . . 42-25
Create Simulink.LookupTable Objects . . . . . . . . . . . . . . . . . . . . . . 42-26
How to Open the Simulink.LookupTable Object Property Dialog Box
................................................ 42-26
Create Table and Breakpoint Data . . . . . . . . . . . . . . . . . . . . . . . . 42-26
View Multidimensional Slices of Data . . . . . . . . . . . . . . . . . . . . . . 42-28
Edit Table and Breakpoint Data with MATLAB Expressions . . . . . . 42-28
Edit Table and Breakpoint Data . . . . . . . . . . . . . . . . . . . . . . . . . . 42-29
Enable Heatmap for Table Data . . . . . . . . . . . . . . . . . . . . . . . . . . 42-31
Overflow Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-32
Data Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-32
Lookup Table Spreadsheet Tabular Interface Shortcuts . . . . . . . . . 42-33

Enter Breakpoints and Table Data . . . . . . . . . . . . . . . . . . . . . . . . . . 42-35


Enter Data in Block Parameter Dialog Box . . . . . . . . . . . . . . . . . . 42-35
Enter Data in Lookup Table Editor . . . . . . . . . . . . . . . . . . . . . . . . 42-35
Enter Data for Multiple Lookup Tables in Lookup Table Editor . . . 42-37
Enter Data Using Inports of Lookup Table Dynamic Block . . . . . . . 42-37

Import Lookup Table Data from MATLAB . . . . . . . . . . . . . . . . . . . . 42-39


Import Standard Format Lookup Table Data . . . . . . . . . . . . . . . . . 42-39
Propagate Standard Format Lookup Table Data . . . . . . . . . . . . . . 42-40
Import Nonstandard Format Lookup Table Data . . . . . . . . . . . . . . 42-40
Propagate Nonstandard Format Lookup Table Data . . . . . . . . . . . 42-42

Copy and Paste Lookup Table Data from Excel . . . . . . . . . . . . . . . . 42-45

Import Lookup Table Data from Excel Using readtable . . . . . . . . . 42-47

Visualize Data Through Plots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-48

Generate Report of Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . 42-51

Register Custom Lookup Table Blocks . . . . . . . . . . . . . . . . . . . . . . 42-52

Visualize Lookup Tables Visualized Through Lookup Table Control


.................................................... 42-54

lv
Create a Logarithm Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . 42-56

Prelookup and Interpolation Blocks . . . . . . . . . . . . . . . . . . . . . . . . 42-58

Optimize Generated Code for Lookup Table Blocks . . . . . . . . . . . . 42-59


Remove Code That Checks for Out-of-Range Inputs . . . . . . . . . . . 42-59
Optimize Breakpoint Spacing in Lookup Tables . . . . . . . . . . . . . . . 42-60
Reduce Data Copies for Lookup Table Blocks . . . . . . . . . . . . . . . . 42-60
Efficient Code for Row-Major Array Layout . . . . . . . . . . . . . . . . . . 42-61

Row-Major Algorithm in Existing Models Containing Lookup Table


Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-62

Update Lookup Table Blocks to New Versions . . . . . . . . . . . . . . . . 42-63


Comparison of Blocks with Current Versions . . . . . . . . . . . . . . . . . 42-63
Compatibility of Models with Older Versions of Lookup Table Blocks
................................................ 42-64
How to Update Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42-64
What to Expect from the Model Advisor Check . . . . . . . . . . . . . . . 42-65

Working with Block Masks


43
Masking Fundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-3
Masking Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-5

Create a Simple Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-7

Manage Existing Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-10


Change a Block Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-10
View Mask Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-10
Look Under Block Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-10
Remove Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-10

Mask Callback Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-12


Execute Callback Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-12

Mask Display and Initialization Commands . . . . . . . . . . . . . . . . . . 43-13

Get Started with Mask Initialization and Callback Code . . . . . . . . 43-17


When to Author Mask Initialization Code? . . . . . . . . . . . . . . . . . . 43-17
Mask Callback Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-19

Author Mask Initialization and Callbacks . . . . . . . . . . . . . . . . . . . . 43-21


How to Author Mask Initialization Code? . . . . . . . . . . . . . . . . . . . 43-22
How to Author Mask Parameter Callback Code? . . . . . . . . . . . . . . 43-23
Write Mask Dialog Control Callback . . . . . . . . . . . . . . . . . . . . . . . 43-24
Migrate Existing Callback Code to MATLAB File . . . . . . . . . . . . . . 43-24
Create or Update Mask Workspace Variables . . . . . . . . . . . . . . . . 43-25
Save Callback File with the Model . . . . . . . . . . . . . . . . . . . . . . . . 43-26

Promote Block Parameters on a Mask . . . . . . . . . . . . . . . . . . . . . . . 43-27

lvi Contents
Control Masks Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-32

Pass Values to Blocks Under the Mask . . . . . . . . . . . . . . . . . . . . . . 43-36


Parameter Promotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-36
Mask Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-36
Referencing Block Parameters Using Variable Names . . . . . . . . . . 43-36

Mask Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-38


Guidelines for Mask Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 43-39
Mask Behavior for Masked, Linked Blocks . . . . . . . . . . . . . . . . . . 43-39
Mask a Linked Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-40

Dynamic Mask Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-41

Dynamic Masked Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-45

Debug Masks That Use MATLAB Code . . . . . . . . . . . . . . . . . . . . . . 43-49


Code Written in Mask Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-49
Code Written Using MATLAB Editor/Debugger . . . . . . . . . . . . . . . 43-49

Introduction to System Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-50


Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-50

Create and Reference a Masked Model . . . . . . . . . . . . . . . . . . . . . . 43-52


Step 1: Define Mask Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . 43-52
Step 2: Create Model Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-52
Step 3: View System Mask Parameters . . . . . . . . . . . . . . . . . . . . . 43-54
Step 4: Reference Masked Model . . . . . . . . . . . . . . . . . . . . . . . . . 43-54

Create and Display System Mask Programmatically . . . . . . . . . . . 43-56

Handling Large Number of Mask Parameters . . . . . . . . . . . . . . . . 43-58

Customize Tables for Masked Blocks . . . . . . . . . . . . . . . . . . . . . . . . 43-59


Adding a Custom Table Parameter . . . . . . . . . . . . . . . . . . . . . . . . 43-59

Control Custom Table Programmatically . . . . . . . . . . . . . . . . . . . . 43-61

Add Images in Masks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-64


Store Mask Images Programmatically . . . . . . . . . . . . . . . . . . . . . . 43-64

Create Hierarchical List in Mask Dialog . . . . . . . . . . . . . . . . . . . . . 43-65

Validating Mask Parameters Using Constraints . . . . . . . . . . . . . . . 43-66


Create and Associate a Constraint . . . . . . . . . . . . . . . . . . . . . . . . 43-66
Create a Cross-Parameter Constraint . . . . . . . . . . . . . . . . . . . . . . 43-68
Rule Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-69
Support Constraints on Literal Edit Parameters . . . . . . . . . . . . . . 43-70

Custom Constraint for Mask Parameter . . . . . . . . . . . . . . . . . . . . . 43-71

Share Parameter Constraints Across Multiple Block Masks . . . . . 43-76

Control Constraints Programmatically . . . . . . . . . . . . . . . . . . . . . . 43-82

lvii
Define Measurement Units for Masked Blocks . . . . . . . . . . . . . . . . 43-83

Masking Example Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-84

Create a Custom Table in the Mask Dialog . . . . . . . . . . . . . . . . . . . 43-86

Create a Block Mask Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-89

Mask a Variant Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-91

Tune Mask Enumeration Parameters - Popup and Radio Button . 43-93

Visualize and Plot N-Dimensional Data Using Mask Lookup Table


Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-103

Validate Input and Output Port Signals Using Port Constraints 43-114

Graphical Icon Editor Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-117


Edit Properties of Block Mask Icon and Its Elements . . . . . . . . . 43-117

Create and Edit Block Mask Icon . . . . . . . . . . . . . . . . . . . . . . . . . . 43-128

Add Dynamic Behavior to Masked Icons . . . . . . . . . . . . . . . . . . . . 43-134


Render Multiple Variations of Same Block Icon Using Parts . . . . 43-134
Hide or Unhide Elements in the Icon Based on Block Parameters or
Mask Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-140
Position Elements Relative to Other Elements Using Layout
Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-143
Text Parameterization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-144
Display Elements That Fit Size of Icon . . . . . . . . . . . . . . . . . . . . 43-147
Repeat Icon Elements on Multiple Ports . . . . . . . . . . . . . . . . . . . 43-148

Validate Port Signals Among Ports of the Same Masked Block . 43-150

Draw Mask Icon Using Drawing Commands . . . . . . . . . . . . . . . . . 43-154

Unsafe Mask Callback Error . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-155

Organize Mask Initialization and Callbacks in a MATLAB File . . 43-156

Simulink Masking Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-162

Manage Interface Connector with Mask Initialization and Block


Callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-163

Unsafe Nested Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-166

Preserve Tunability of Parameters That Are Modified or Created in


Mask Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-167

Share Port Constraints Across Multiple Masked Blocks . . . . . . . 43-174

lviii Contents
Creating Custom Blocks
44
Types of Custom Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-2
MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-2
MATLAB System Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-2
Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-3
C Caller Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-3
C Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-3
S-Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-3
Masked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-4

Comparison of Custom Block Functionality . . . . . . . . . . . . . . . . . . . 44-5


Model State Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-6
Simulation Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-6
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-8
Multiple Input and Output Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-9
Speed of Updating the Simulink Diagram . . . . . . . . . . . . . . . . . . . . 44-9
Callback Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-10
Comparing MATLAB S-Functions to MATLAB Functions for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-11
Expanding Custom Block Functionality . . . . . . . . . . . . . . . . . . . . . 44-11

Design and Create a Custom Block . . . . . . . . . . . . . . . . . . . . . . . . . 44-12


Setup Working Environment to Design and Create a Custom Block
................................................ 44-12
How to Design a Custom Block . . . . . . . . . . . . . . . . . . . . . . . . . . . 44-12
Defining Custom Block Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 44-14
Deciding on a Custom Block Type . . . . . . . . . . . . . . . . . . . . . . . . . 44-14
Placing Custom Blocks in a Library . . . . . . . . . . . . . . . . . . . . . . . . 44-18
Adding a User Interface to a Custom Block . . . . . . . . . . . . . . . . . . 44-19
Adding Block Functionality Using Block Callbacks . . . . . . . . . . . . 44-25

Integrate Python GPS Text Message Parsing Algorithms in Simulink


.................................................... 44-29

Working with Block Libraries


45
Create Custom Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-2
Data Dictionary for Custom Libraries . . . . . . . . . . . . . . . . . . . . . . . 45-3
Blocks for Custom Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-3
Annotations in Custom Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-5
Lock and Unlock Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-6
Prevent Disabling of Library Links . . . . . . . . . . . . . . . . . . . . . . . . . 45-6

Add Libraries to Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-8


Add Library to Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-8
Add Sublibrary to Library Browser . . . . . . . . . . . . . . . . . . . . . . . . . 45-9
Specify Library Order in Library List . . . . . . . . . . . . . . . . . . . . . . 45-11

lix
Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-12
Rules for Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-13
Linked Block Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-13

Parameterized Links and Self-Modifiable Linked Subsystems . . . 45-15


Parameterized Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-15
Self-Modifiable Linked Subsystems . . . . . . . . . . . . . . . . . . . . . . . . 45-18

Create a Self-Modifiable Library Block . . . . . . . . . . . . . . . . . . . . . . 45-20

Display Library Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-21

Disable or Break Links to Library Blocks . . . . . . . . . . . . . . . . . . . . 45-23


Break Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-23

Lock Links to Blocks in a Library . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-25


Rules for Locked Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-25

Restore Disabled Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-27


Restore Disabled Links Individually . . . . . . . . . . . . . . . . . . . . . . . 45-27
Restore Disabled Links Hierarchically . . . . . . . . . . . . . . . . . . . . . 45-27

Restore Parameterized Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-30

Fix Unresolved Library Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-32


Install Missing Product . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-32
Resolve Path to Source Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-32
Specify Unresolved Block Details for Custom Libraries . . . . . . . . . 45-33

Control Linked Block Programmatically . . . . . . . . . . . . . . . . . . . . . 45-34


Linked Block Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-34
Lock Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-34
Link Status . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-34

Maintain Compatibility of Library Blocks Using Forwarding Tables


.................................................... 45-37
Forwarding Table Entry for a Renamed Block . . . . . . . . . . . . . . . . 45-37
Move Block from One Library to Another . . . . . . . . . . . . . . . . . . . 45-38
Add or Remove Parameters from the Block . . . . . . . . . . . . . . . . . . 45-39
Split Block Functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-42
Create Mask Parameter Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . 45-42

Integrating Custom C/C++ Code


46
Specify and Configure Custom C/C++ Code . . . . . . . . . . . . . . . . . . . 46-2
Configure Custom Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46-2
Specify Relative Paths to Custom Code . . . . . . . . . . . . . . . . . . . . . . 46-5

Debug Custom C/C++ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46-8


In-Process and Out-of-Process Simulation . . . . . . . . . . . . . . . . . . . 46-10

lx Contents
Integrate C Code in Simulink Models
47
Integrate C Code Using C Caller Blocks . . . . . . . . . . . . . . . . . . . . . . 47-2
Specify Source Code and Dependencies . . . . . . . . . . . . . . . . . . . . . 47-2
N-D Array Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-4
Call C Caller Block and Specify Ports . . . . . . . . . . . . . . . . . . . . . . . 47-5
Map C Function Arguments to Simulink Ports . . . . . . . . . . . . . . . . . 47-5
Create a FunctionPortSpecification Object and Edit C Caller Block
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-10
Create a Custom C Caller Library . . . . . . . . . . . . . . . . . . . . . . . . . 47-10
Debug Custom Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11
Generate Code from Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47-11

Use C Caller Block with Conditional Execution . . . . . . . . . . . . . . . 47-13

Integrate Algorithms Using C Function Blocks


48
Integrate External C/C++ Code into Simulink Using C Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-2
Write External Source Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-2
Enter the External Code Into Simulink . . . . . . . . . . . . . . . . . . . . . . 48-3
Specify Simulation or Code Generation Code . . . . . . . . . . . . . . . . . 48-5
Specify Declaration for Target-Specific Function for Code Generation
................................................. 48-6

Interface with C++ Classes Using C Function Block . . . . . . . . . . . . 48-7


Create Source Code Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-7
Configure the C Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-8
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-10

Modify States of a C Function Block Using Persistent Symbols . . 48-12

Change Values of Signals Using C Function Block and Buses . . . . 48-14

Access Elements of a Matrix Using Output Code in a C Function


Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-16

Use External Functions with Matrix Input in a C Function Block


.................................................... 48-18

Define an Alias Type in a C Function Block . . . . . . . . . . . . . . . . . . . 48-21

Use Enumerated Data in a C Function Block . . . . . . . . . . . . . . . . . 48-23

Use Inherited Sizes in a C Function Block . . . . . . . . . . . . . . . . . . . 48-25

Call Legacy Lookup Table Function Using C Caller Block . . . . . . . 48-27

lxi
Start and Terminate Actions Within a C Function Block . . . . . . . . 48-29

Call C++ Class Methods Using C-Style Wrapper Function from C


Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48-31

Call C++ Class Methods Directly from a C Function Block . . . . . . 48-33

Call Legacy Lookup Table Functions Using C Function Block . . . . 48-34

Use C Function Block Within For Each Subsystem . . . . . . . . . . . . . 48-36

Simulink Code Importer


49
Import Custom Code Using the Simulink Code Importer Wizard
..................................................... 49-2

Import Custom C++ Class Using the Simulink Code Importer Wizard
.................................................... 49-13

Using the MATLAB Function Block


50
Implement MATLAB Functions in Simulink with MATLAB Function
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-2
Calculate Mean and Standard Deviation with a MATLAB Function
Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-2
Program the MATLAB Function Block . . . . . . . . . . . . . . . . . . . . . . . 50-3
Check Properties for MATLAB Function Block Variables . . . . . . . . . 50-6
Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-7

Configure MATLAB Function Blocks Programmatically . . . . . . . . . . 50-9


Call MATLAB Function Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-9
Programmatically Configure Block Properties . . . . . . . . . . . . . . . . . 50-9
Access Block Inputs, Outputs, and Properties . . . . . . . . . . . . . . . . . 50-9
Programmatically Access MATLAB Function Reports . . . . . . . . . . 50-10

Code Generation Readiness Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-12


Issues Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-12
Files Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-13

Check Code Using the Code Generation Readiness Tool . . . . . . . . 50-15


Run Code Generation Readiness Tool at the Command Line . . . . . 50-15
Run the Code Generation Readiness Tool From the Current Folder
Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-15

Debug MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-16


Debug an Example Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-16
Set Conditions on Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-18

lxii Contents
Watch Function Variables During Simulation . . . . . . . . . . . . . . . . 50-19
Check for Data Range Violations . . . . . . . . . . . . . . . . . . . . . . . . . . 50-21
Debug MATLAB Function Blocks in Initialize Function and Terminate
Function Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-21

Prevent Algebraic Loop Errors in MATLAB Function, Chart, and


Truth Table Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-23

Manage Function Call Outputs of a MATLAB Function Block . . . . 50-25


Create Function Call Outputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-25
Enable a Function-Call Subsystem with a MATLAB Function Block
................................................ 50-25
Considerations When Triggering Function-Call Subsystems . . . . . 50-27
Set Function Call Output Properties . . . . . . . . . . . . . . . . . . . . . . . 50-27

Manage the Input Trigger of a MATLAB Function Block . . . . . . . . 50-29


Create an Input Trigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-29
Enable a MATLAB Function Block with an Input Trigger . . . . . . . . 50-29
Set Input Trigger Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-30

Create and Define MATLAB Function Block Variables . . . . . . . . . . 50-33


Create and Delete MATLAB Function Block Variables . . . . . . . . . . 50-33
Set General Variable Properties . . . . . . . . . . . . . . . . . . . . . . . . . . 50-34
Set Limit Range Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-37
Set Description Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-37
Programmatically Create Variables . . . . . . . . . . . . . . . . . . . . . . . . 50-38

Specify MATLAB Function Block Properties . . . . . . . . . . . . . . . . . . 50-39


MATLAB Function Block Properties . . . . . . . . . . . . . . . . . . . . . . . 50-39
Fixed-Point Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-41
Description and Document Link Properties . . . . . . . . . . . . . . . . . . 50-42
Programmatically Specify Block Properties . . . . . . . . . . . . . . . . . . 50-42

MATLAB Function Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-43


Open a MATLAB Function Report . . . . . . . . . . . . . . . . . . . . . . . . . 50-43
Analyze MATLAB Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-43
View Error and Warning Messages . . . . . . . . . . . . . . . . . . . . . . . . 50-44
View MATLAB Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-44
Report Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-46

Define and Modify Variable Data Types . . . . . . . . . . . . . . . . . . . . . . 50-47


Specify Variable Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-47
Inheriting Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-49
Built-In Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-49
Fixed-Point Designer Data Type Properties . . . . . . . . . . . . . . . . . . 50-50
Specify Data Types with Expressions . . . . . . . . . . . . . . . . . . . . . . 50-54
Programmatically Change Variable Data Types . . . . . . . . . . . . . . . 50-55

Specify Size of MATLAB Function Block Variables . . . . . . . . . . . . . 50-56


Inherit Size from Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-56
Customize Variable Sizes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-56
Custom Size Property Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-57
Simulation and Size Matching . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-58

lxiii
Configure MATLAB Function Block Parameter Variables . . . . . . . 50-59
Assign Parameter Variables to Workspace Data . . . . . . . . . . . . . . . 50-59
Assign Parameter Variables to Mask Parameters . . . . . . . . . . . . . . 50-62
Parameter Variable Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-65

Resolve Signal Objects for Output Variables . . . . . . . . . . . . . . . . . . 50-66


Implicit Signal Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-66
Eliminating Warnings for Implicit Signal Resolution in the Model
................................................ 50-66
Disabling Implicit Signal Resolution for a MATLAB Function Block
................................................ 50-66
Forcing Explicit Signal Resolution for an Output Signal . . . . . . . . 50-66

Attach Buses to MATLAB Function Blocks . . . . . . . . . . . . . . . . . . . 50-68


Read and Write Buses with a MATLAB Function Block . . . . . . . . . 50-68
Write Buses From Data Store Memory to a MATLAB Function Block
................................................ 50-70

Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-74

Create Structures in MATLAB Function Blocks . . . . . . . . . . . . . . . 50-75


Input Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-75
Output Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-75
Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-75
Persistent Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-76
Parameter Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-76
Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-76
Assign Values to Structures and Fields . . . . . . . . . . . . . . . . . . . . . 50-76
Limitations for Structures in MATLAB Function Blocks . . . . . . . . . 50-77

Initialize Matrix Using a Nontunable Structure Parameter . . . . . 50-78

Declare Variable-Size MATLAB Function Block Variables . . . . . . . 50-81


Output Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-81
Other Scope Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-82
Use a Variable-Size Signal in a Filtering Algorithm . . . . . . . . . . . . 50-82

Control Memory Allocation for Variable-Size Arrays in a MATLAB


Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-87
Provide Upper Bounds for Variable-Size Arrays . . . . . . . . . . . . . . . 50-87
Disable Dynamic Memory Allocation for MATLAB Function Blocks
................................................ 50-87
Modify the Dynamic Memory Allocation Threshold . . . . . . . . . . . . 50-87

Use Dynamic Memory Allocation for Variable-Size Arrays in a


MATLAB Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-89
Configure Model for Dynamic Memory Allocation . . . . . . . . . . . . . 50-89
Create Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-89
Simulate Model Using Dynamic Memory Allocation . . . . . . . . . . . 50-90
Use Dynamic Memory Allocation for Bounded Arrays . . . . . . . . . . 50-90
Generate C Code That Uses Dynamic Memory Allocation . . . . . . . 50-90

Code Generation for Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . 50-92


Define Enumerations for MATLAB Function Blocks . . . . . . . . . . . . 50-92
Allowed Operations on Enumerations . . . . . . . . . . . . . . . . . . . . . . 50-93

lxiv Contents
MATLAB Toolbox Functions That Support Enumerations . . . . . . . . 50-94

Add Enumerated Inputs, Outputs, and Parameters to a MATLAB


Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-96
Enumerations in a MATLAB Function Block . . . . . . . . . . . . . . . . . 50-96

Use Global Data in MATLAB Function Blocks . . . . . . . . . . . . . . . . . 50-99


Use Global Data from Data Store Memory Blocks . . . . . . . . . . . . . 50-99
Use Global Data from Simulink.Signal Objects . . . . . . . . . . . . . . . 50-99
Choose How to Store Global Data . . . . . . . . . . . . . . . . . . . . . . . . 50-100
Retrieve Data From Data Store Memory Blocks . . . . . . . . . . . . . 50-100
Retrieve Data From Simulink.Signal Objects Example . . . . . . . . 50-102
Using Data Store Diagnostics to Detect Memory Access Issues . . 50-104

Initialize Persistent Variables in MATLAB Functions . . . . . . . . . . 50-105


MATLAB Function Block with No Direct Feedthrough . . . . . . . . . 50-106
State Control Block in Synchronous Mode . . . . . . . . . . . . . . . . . 50-107
Stateflow Chart Implementing Moore Semantics . . . . . . . . . . . . 50-109

Run Simulations and Generate Code with Masked Library


Subsystems Containing MATLAB Function Blocks . . . . . . . . . . 50-112

Include MATLAB Code as Comments in Generated Code . . . . . . 50-115


How to Include MATLAB Code as Comments in the Generated Code
............................................... 50-115
Location of Comments in Generated Code . . . . . . . . . . . . . . . . . 50-115
Including MATLAB user comments in Generated Code . . . . . . . . 50-117
Limitations of MATLAB Source Code as Comments . . . . . . . . . . . 50-118

Integrate C Code by Using the MATLAB Function Block . . . . . . . 50-119


Call C Code from a Simulink Model . . . . . . . . . . . . . . . . . . . . . . 50-119
Use coder.ceval in an Example MATLAB Function Block . . . . . . . 50-119
Control Imported Bus and Enumeration Type Definitions . . . . . . 50-122

Control Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-123


Types of Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-123
When to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . 50-123
How to Disable Run-Time Checks . . . . . . . . . . . . . . . . . . . . . . . . 50-123

Call MATLAB Function Files in MATLAB Function Blocks . . . . . 50-125

Interface with Row-Major Data in MATLAB Function Block . . . . 50-129


Row-Major Layout in Simulation and Code Generation . . . . . . . . 50-129
Array Layout Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-129
Array Layout and Algorithmic Efficiency . . . . . . . . . . . . . . . . . . . 50-129
Row-Major Layout for N-Dimensional Arrays . . . . . . . . . . . . . . . 50-130
Specify Array Layout in External Function Calls . . . . . . . . . . . . . 50-132

Code and Integration Limitations for MATLAB Function Blocks 50-134


Use Supported Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50-134
Prepare Variables for Code Generation . . . . . . . . . . . . . . . . . . . . 50-134
Use Nondirect Feedthrough in a MATLAB Function Block . . . . . . 50-135

lxv
System Objects in Simulink
51
MATLAB System Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-3
Why Use the MATLAB System Block? . . . . . . . . . . . . . . . . . . . . . . . 51-3
Choosing the Right Block Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-3
System Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-3
Interpreted Execution or Code Generation . . . . . . . . . . . . . . . . . . . 51-4
Default Input Signal Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-4
MATLAB System Block Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 51-4
MATLAB System and System Objects Examples . . . . . . . . . . . . . . . 51-5

Implement a MATLAB System Block . . . . . . . . . . . . . . . . . . . . . . . . . 51-7


Understanding the MATLAB System Block . . . . . . . . . . . . . . . . . . . 51-7

Change Blocks Implemented with System Objects . . . . . . . . . . . . . . 51-9

Call Simulink Functions from MATLAB System Block . . . . . . . . . . 51-10


Create a Simulink Function Block . . . . . . . . . . . . . . . . . . . . . . . . . 51-10
Create a MATLAB System Block and Define System Object . . . . . . 51-10
Call a Simulink Function in a Subsystem from a MATLAB System Block
................................................ 51-11
Call Simulink Functions from a MATLAB System Block . . . . . . . . . 51-12

Specify Sample Time for MATLAB System Block . . . . . . . . . . . . . . 51-13


Types of Sample Time for MATLAB System Block . . . . . . . . . . . . . 51-13

Change Block Icon and Port Labels . . . . . . . . . . . . . . . . . . . . . . . . . 51-14


Modify MATLAB System Block Dialog . . . . . . . . . . . . . . . . . . . . . . 51-14
Change the MATLAB System Block Icon to an Image . . . . . . . . . . 51-14

Nonvirtual Buses and MATLAB System Block . . . . . . . . . . . . . . . . 51-16

Use System Objects in Feedback Loops . . . . . . . . . . . . . . . . . . . . . . 51-17

Simulation Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-18


Interpreted Execution vs. Code Generation . . . . . . . . . . . . . . . . . . 51-18
Simulation Using Code Generation . . . . . . . . . . . . . . . . . . . . . . . . 51-19

Mapping System Object Code to MATLAB System Block Dialog Box


.................................................... 51-20
System Object to Block Dialog Box Default Mapping . . . . . . . . . . . 51-20
System Object to Block Dialog Box Custom Mapping . . . . . . . . . . 51-21

Considerations for Using System Objects in Simulink . . . . . . . . . . 51-24


Variable-Size Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-24
Tunable Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-24
System Objects as Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-24
Default Property Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-25
System Objects in For Each Subsystems . . . . . . . . . . . . . . . . . . . . 51-25
Input Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-25

Simulink Engine Interaction with System Object Methods . . . . . . 51-26


Simulink Engine Phases Mapped to System Object Methods . . . . . 51-26

lxvi Contents
Add and Implement Propagation Methods . . . . . . . . . . . . . . . . . . . 51-29
When to Use Propagation Methods . . . . . . . . . . . . . . . . . . . . . . . . 51-29
Implement Propagation Methods . . . . . . . . . . . . . . . . . . . . . . . . . 51-29

Share Data with Other Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-31


Setup Working Environment to Share System Object Data with Other
Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-31
Data Sharing with the MATLAB System Block . . . . . . . . . . . . . . . . 51-31
Choose How to Store Shared Data . . . . . . . . . . . . . . . . . . . . . . . . 51-32
How to Use Data Store Memory Blocks for the MATLAB System Block
................................................ 51-33
How to Set Up Simulink.Signal Objects . . . . . . . . . . . . . . . . . . . . 51-34
Using Data Store Diagnostics to Detect Memory Access Issues . . . 51-36
Limitations of Using Shared Data in MATLAB System Blocks . . . . 51-36
Use Shared Data with P-Coded System Objects . . . . . . . . . . . . . . . 51-36

Troubleshoot System Objects in Simulink . . . . . . . . . . . . . . . . . . . . 51-38


Class Not Found . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-38
Error Invoking Object Method . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-38
Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-38

Customize MATLAB System Block Dialog . . . . . . . . . . . . . . . . . . . . 51-40

Break Algebraic Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-44

Customize MATLAB System Block Appearance . . . . . . . . . . . . . . . 51-47

Implement a Simple Algorithm . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-50

Specify Output Characteristics of MATLAB System Block . . . . . . . 51-53

Customize System Block Appearance Programmatically . . . . . . . . 51-56


Specify Input and Output Names . . . . . . . . . . . . . . . . . . . . . . . . . 51-56
Add Text to Block Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-57
Add Image to Block Icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-58

Customize MATLAB System Icon and Dialog Box Using Mask Editor
.................................................... 51-60
Create and Customize MATLAB System Icon and Dialog Box Using
Mask Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-60

Customize System Block Dialog Box Programmatically . . . . . . . . 51-72


Define Block Dialog Tabs, Sections, and Order of Properties . . . . . 51-72
Define Property Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-75
Add Header Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-77
Control Simulation Type in MATLAB System Block . . . . . . . . . . . . 51-78
Add Custom Button to MATLAB System Block . . . . . . . . . . . . . . . . 51-79

Specify Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-82


Set Output Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-82
Set Fixed- or Variable-Size Output . . . . . . . . . . . . . . . . . . . . . . . . 51-83
Set Output Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-85
Set Output Complexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-88
Set Discrete State Output Specification . . . . . . . . . . . . . . . . . . . . 51-89

lxvii
Set Model Reference Discrete Sample Time Inheritance . . . . . . . 51-92

Use Update and Output for Nondirect Feedthrough . . . . . . . . . . . 51-94

Enable For Each Subsystem Support . . . . . . . . . . . . . . . . . . . . . . . . 51-96

Define System Object for Use in Simulink . . . . . . . . . . . . . . . . . . . . 51-98


Develop System Object for Use in MATLAB System Block . . . . . . . 51-98
Define Block Dialog Box for Plot Ramp . . . . . . . . . . . . . . . . . . . . . 51-98

Use Global Variables in System Objects . . . . . . . . . . . . . . . . . . . . 51-101


System Object Global Variables in MATLAB . . . . . . . . . . . . . . . . 51-101
System Object Global Variables in Simulink . . . . . . . . . . . . . . . . 51-101

System Design in Simulink Using System Objects . . . . . . . . . . . . 51-105


System Design and Simulation in Simulink . . . . . . . . . . . . . . . . . 51-105
Define New System Objects for Use in Simulink . . . . . . . . . . . . . 51-105
Test New System Objects in MATLAB . . . . . . . . . . . . . . . . . . . . . 51-109
Add System Objects to Your Simulink Model . . . . . . . . . . . . . . . . 51-109

Specify Sample Time for MATLAB System Block System Objects


................................................... 51-111

Create Moving Average Filter Block with System Object . . . . . . . 51-116

Process Message Payload Using MATLAB System Block . . . . . . . 51-120

Call Python Function Using MATLAB Function and MATLAB System


Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-122

Convert Moving Target MATLAB Code to a Simulink Model . . . . 51-124

Integrate Python Packages to Parse NMEA GPS Messages Using


Python Importer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-127

Integrate Python Functions Specified Within Classes Using Python


Importer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51-131

Manage and Create a Blockset Using Blockset Designer


52
Create a Blockset Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-2
Create a New Blockset Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-2
Create a Project from an Existing Blockset . . . . . . . . . . . . . . . . . . . 52-7
Blockset Project File Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-10

Create and Organize Block Artifacts . . . . . . . . . . . . . . . . . . . . . . . . 52-12


Add Tests to Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-12
Document the Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-13
S-Function Related Artifacts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-14

lxviii Contents
Publish the Created Blockset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-16

FMUs and Co-Simulation in Simulink


53
Import FMUs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-2
FMU XML File Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-2
Additional Support and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 53-3
FMU Import Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-5

Implement an FMU Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-6


Explore the FMU Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-6
Change Block Input, Output, Parameter and Internal Variable
Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-10
Timing Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-12
Troubleshooting FMUs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-12

Export a Model as a Tool-Coupling FMU . . . . . . . . . . . . . . . . . . . . . 53-14


Include Tunable Parameters for Tool-Coupling FMU . . . . . . . . . . . 53-15
Use Protected Model to Conceal Content . . . . . . . . . . . . . . . . . . . 53-15
Use the Exported Tool-Coupling FMU . . . . . . . . . . . . . . . . . . . . . . 53-15

Co-Simulation Execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-18


Execution Timing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-18

Numerical Compensation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-20


Numerical Compensation Prerequisites . . . . . . . . . . . . . . . . . . . . 53-20
Manage Numerical Compensation Options Using the Dialog . . . . . 53-21
Manage Numerical Compensation Options from the Command Line
................................................ 53-26
Numerical Compensation Limitations . . . . . . . . . . . . . . . . . . . . . . 53-28

Perform Cosimulation of Multiversion Components . . . . . . . . . . . 53-29


Set up MATLAB Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-29
Set up Parent Simulink model . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-30
Log Signals in Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-31
Debug Submodel from Parent Model . . . . . . . . . . . . . . . . . . . . . . 53-31

Run Co-Simulation Components on Multiple Cores . . . . . . . . . . . . 53-32


Singlethreaded Versus Multithreaded Simulations . . . . . . . . . . . . 53-32
Using Multithreaded Simulation to Speed up Simulation on Multiple
Cores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-33
Using the MultithreadedSim Parameter . . . . . . . . . . . . . . . . . . . . 53-34
Configuring S-Function Blocks to Run Single or Multithreaded . . . 53-35
Co-Simulation on Multiple Threads Limitations and Guidelines . . . 53-35

Simulink Community and Connection Partner Program . . . . . . . . 53-38

FMU Block Calling Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53-39


Co-Simulation Call Sequence for FMI Version 1.0 . . . . . . . . . . . . . 53-39
Model Exchange Call Sequence for FMI Version 1.0 . . . . . . . . . . . 53-40
Co-Simulation Call Sequence for FMI Version 2.0 . . . . . . . . . . . . . 53-41

lxix
Model Exchange Call Sequence for FMI Version 2.0 . . . . . . . . . . . 53-42
Co-Simulation Call Sequence for FMI Version 3.0 . . . . . . . . . . . . . 53-44
Model Exchange Call Sequence for FMI Version 3.0 . . . . . . . . . . . 53-45

Debug FMU with Source Code Using External Debugger . . . . . . . 53-47

Design Considerations for C/C++ Code Generation


54
When to Generate Code from MATLAB Algorithms . . . . . . . . . . . . . 54-2
When Not to Generate Code from MATLAB Algorithms . . . . . . . . . . 54-2

Which Code Generation Feature to Use . . . . . . . . . . . . . . . . . . . . . . . 54-3

Prerequisites for C/C++ Code Generation from MATLAB . . . . . . . . 54-4

MATLAB Code Design Considerations for Code Generation . . . . . . 54-5


See Also . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-5

Differences Between Generated Code and MATLAB Code . . . . . . . . 54-6


Functions that have Multiple Possible Outputs . . . . . . . . . . . . . . . . 54-7
Passing Input Argument Name at Run Time . . . . . . . . . . . . . . . . . . 54-7
Empty Repeating Input Argument . . . . . . . . . . . . . . . . . . . . . . . . . . 54-9
Output Argument Validation of Conditionally-Assigned Outputs . . . 54-9
Writing to ans Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-10
Logical Short-Circuiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-11
Loop Index Overflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-11
Indexing for Loops by Using Single Precision Operands . . . . . . . . 54-12
Index of an Unentered for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 54-13
Character Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-14
Order of Evaluation in Expressions . . . . . . . . . . . . . . . . . . . . . . . . 54-14
Name Resolution While Constructing Function Handles . . . . . . . . 54-15
Termination Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-16
Size of Variable-Size N-D Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . 54-16
Size of Empty Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-17
Size of Empty Array That Results from Deleting Elements of an Array
................................................ 54-17
Growing Variable-Size Column Cell Array That is Initialized as Scalar
at Run Time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-17
Binary Element-Wise Operations with Single and Double Operands
................................................ 54-18
Floating-Point Numerical Results . . . . . . . . . . . . . . . . . . . . . . . . . 54-19
NaN and Infinity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-19
Negative Zero . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-19
Code Generation Target . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-20
MATLAB Class Property Initialization . . . . . . . . . . . . . . . . . . . . . . 54-20
MATLAB Classes in Nested Property Assignments That Have Set
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-20
MATLAB Handle Class Destructors . . . . . . . . . . . . . . . . . . . . . . . . 54-20
Variable-Size Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-21
Complex Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-21
Converting Strings with Consecutive Unary Operators to double . 54-21

lxx Contents
Display Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-21

MATLAB Language Features Supported for C/C++ Code Generation


.................................................... 54-23
MATLAB Features That Code Generation Supports . . . . . . . . . . . . 54-23
MATLAB Language Features That Code Generation Does Not Support
................................................ 54-24

Functions, Classes, and System Objects Supported for


Code Generation
55
Functions and Objects Supported for C/C++ Code Generation . . . . 55-2

System Objects Supported for Code Generation


56
Code Generation for System Objects . . . . . . . . . . . . . . . . . . . . . . . . . 56-2

Defining MATLAB Variables for C/C++ Code Generation


57
Variables Definition for Code Generation . . . . . . . . . . . . . . . . . . . . . 57-2

Best Practices for Defining Variables for C/C++ Code Generation


..................................................... 57-3
Explicitly Define Variables Before Using Them . . . . . . . . . . . . . . . . 57-3
Use Caution When Reassigning Variable Properties . . . . . . . . . . . . 57-4
Define Variable Numeric Data Types . . . . . . . . . . . . . . . . . . . . . . . . 57-4
Define Matrices Before Assigning Indexed Variables . . . . . . . . . . . . 57-5
Aim to Index Arrays by Using Fixed-Size Vectors . . . . . . . . . . . . . . 57-5

Eliminate Redundant Copies of Variables in Generated Code . . . . . 57-7


When Redundant Copies Occur . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-7
How to Eliminate Redundant Copies by Defining Uninitialized
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-7
Defining Uninitialized Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-7

Reassignment of Variable Properties . . . . . . . . . . . . . . . . . . . . . . . . . 57-9

Reuse the Same Variable with Different Properties . . . . . . . . . . . . 57-10


When You Can Reuse the Same Variable with Different Properties
................................................ 57-10
When You Cannot Reuse Variables . . . . . . . . . . . . . . . . . . . . . . . . 57-10
Limitations of Variable Reuse . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-11

lxxi
Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-13

Edit and Represent Coder Type Objects and Properties . . . . . . . . . 57-14


Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-14
Legacy Representation of Coder Type Objects . . . . . . . . . . . . . . . 57-15

Defining Data for Code Generation


58
Data Definition Considerations for Code Generation . . . . . . . . . . . . 58-2

Code Generation for Complex Data . . . . . . . . . . . . . . . . . . . . . . . . . . 58-8


Restrictions When Defining Complex Variables . . . . . . . . . . . . . . . . 58-8
Code Generation for Complex Data with Zero-Valued Imaginary Parts
................................................. 58-8
Results of Expressions That Have Complex Operands . . . . . . . . . . 58-11
Results of Complex Multiplication with Nonfinite Values . . . . . . . . 58-11

Encoding of Characters in Code Generation . . . . . . . . . . . . . . . . . . 58-12

Array Size Restrictions for Code Generation . . . . . . . . . . . . . . . . . 58-13

Code Generation for Constants in Structures and Arrays . . . . . . . 58-14

Code Generation for Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58-16


Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58-16
Differences Between Generated Code and MATLAB Code . . . . . . . 58-16

Code Generation for Sparse Matrices . . . . . . . . . . . . . . . . . . . . . . . 58-17


Code Generation Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58-17
Code Generation Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58-17

Specify Array Layout in Functions and Classes . . . . . . . . . . . . . . . . 58-19


Specify Array Layout in a Function . . . . . . . . . . . . . . . . . . . . . . . . 58-19
Query Array Layout of a Function . . . . . . . . . . . . . . . . . . . . . . . . . 58-20
Specify Array Layout in a Class . . . . . . . . . . . . . . . . . . . . . . . . . . 58-20

Code Design for Row-Major Array Layout . . . . . . . . . . . . . . . . . . . . 58-23


Linear Indexing Uses Column-Major Array Layout . . . . . . . . . . . . 58-23

Generate Code for Growing Arrays and Cell Arrays with end + 1
Indexing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58-25
Grow Array with (end + 1) Indexing . . . . . . . . . . . . . . . . . . . . . . . 58-25
Grow Cell Array with {end + 1} Indexing . . . . . . . . . . . . . . . . . . . 58-26

lxxii Contents
Code Generation for Variable-Size Data
59
Code Generation for Variable-Size Arrays . . . . . . . . . . . . . . . . . . . . . 59-2
Memory Allocation for Variable-Size Arrays . . . . . . . . . . . . . . . . . . 59-2
Enabling and Disabling Support for Variable-Size Arrays . . . . . . . . 59-3
Variable-Size Arrays in a MATLAB Function Report . . . . . . . . . . . . . 59-3

Control Dynamic Memory Allocation for Fixed-Size Arrays . . . . . . . 59-5


Enable Dynamic Memory Allocation for Fixed-Size Arrays . . . . . . . . 59-5
Set Dynamic Memory Allocation Threshold for Fixed-Size Arrays . . 59-5
Generate Code for Fixed-Size Arrays . . . . . . . . . . . . . . . . . . . . . . . 59-5
Usage Notes and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-6

Specify Upper Bounds for Variable-Size Arrays . . . . . . . . . . . . . . . . 59-7


Specify Upper Bounds for MATLAB Function Block Inputs and Outputs
................................................. 59-7
Specify Upper Bounds for Local Variables . . . . . . . . . . . . . . . . . . . . 59-7

Define Variable-Size Data for Code Generation . . . . . . . . . . . . . . . . 59-9


Use a Matrix Constructor with Nonconstant Dimensions . . . . . . . . . 59-9
Assign Multiple Sizes to the Same Variable . . . . . . . . . . . . . . . . . . . 59-9
Grow an Array Using (end + 1) Indexing . . . . . . . . . . . . . . . . . . . 59-10
Define Variable-Size Data Explicitly by Using coder.varsize . . . . . . 59-11

Diagnose and Fix Variable-Size Data Errors . . . . . . . . . . . . . . . . . . 59-15


Diagnosing and Fixing Size Mismatch Errors . . . . . . . . . . . . . . . . 59-15
Diagnosing and Fixing Errors in Detecting Upper Bounds . . . . . . . 59-17

Incompatibilities with MATLAB in Variable-Size Support for Code


Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-18
Incompatibility with MATLAB for Scalar Expansion . . . . . . . . . . . . 59-18
Incompatibility with MATLAB in Determining Size of Variable-Size N-D
Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-19
Incompatibility with MATLAB in Determining Size of Empty Arrays
................................................ 59-19
Incompatibility with MATLAB in Determining Class of Empty Arrays
................................................ 59-21
Incompatibility with MATLAB in Matrix-Matrix Indexing . . . . . . . . 59-21
Incompatibility with MATLAB in Vector-Vector Indexing . . . . . . . . 59-22
Incompatibility with MATLAB in Logical Indexing . . . . . . . . . . . . . 59-22
Incompatibility with MATLAB in Matrix Indexing Operations for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-23
Incompatibility with MATLAB in Concatenating Variable-Size Matrices
................................................ 59-24
Differences When Curly-Brace Indexing of Variable-Size Cell Array
Inside Concatenation Returns No Elements . . . . . . . . . . . . . . . 59-24

Variable-Sizing Restrictions for Code Generation of Toolbox


Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-26
Common Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-26
Toolbox Functions with Restrictions for Variable-Size Data . . . . . . 59-26

lxxiii
Generate Code With Implicit Expansion Enabled . . . . . . . . . . . . . . 59-31
Output Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-31
Additional Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-31
Performance Variation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-33

Optimize Implicit Expansion in Generated Code . . . . . . . . . . . . . . 59-35


Disable Implicit Expansion in Specified Function by Using
coder.noImplicitExpansionInFunction . . . . . . . . . . . . . . . . . . . . 59-37
Disable Implicit Expansion for Specific Binary Operation by Using
coder.sameSizeBinaryOp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-38
Disable Implicit Expansion in your Project . . . . . . . . . . . . . . . . . . 59-39

Representation of Arrays in Generated Code . . . . . . . . . . . . . . . . . 59-40


Customize Interface Generation . . . . . . . . . . . . . . . . . . . . . . . . . . 59-42

Control Memory Allocation for Fixed-Size Arrays . . . . . . . . . . . . . . 59-44


Enable Dynamic Memory Allocation for All Fixed-Size Arrays . . . . 59-44
Enable Dynamic Memory Allocation for Arrays Bigger Than a
Threshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-44

Resolve Error: Size Mismatches . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-45


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-45
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-45

Code Generation for MATLAB Structures


60
Structure Definition for Code Generation . . . . . . . . . . . . . . . . . . . . . 60-2

Structure Operations Allowed for Code Generation . . . . . . . . . . . . . 60-3

Define Scalar Structures for Code Generation . . . . . . . . . . . . . . . . . 60-4


Restrictions When Defining Scalar Structures by Assignment . . . . . 60-4
Adding Fields in Consistent Order on Each Control Flow Path . . . . . 60-4
Restriction on Adding New Fields After First Use . . . . . . . . . . . . . . 60-4

Define Arrays of Structures for Code Generation . . . . . . . . . . . . . . . 60-6


Ensuring Consistency of Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60-6
Using repmat to Define an Array of Structures with Consistent Field
Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60-6
Defining an Array of Structures by Using struct . . . . . . . . . . . . . . . 60-6
Defining an Array of Structures Using Concatenation . . . . . . . . . . . 60-7

Index Substructures and Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60-8

Assign Values to Structures and Fields . . . . . . . . . . . . . . . . . . . . . . 60-10

Pass Large Structures as Input Parameters . . . . . . . . . . . . . . . . . . 60-11

lxxiv Contents
Code Generation for Cell Arrays
61
Code Generation for Cell Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61-2
Homogeneous vs. Heterogeneous Cell Arrays . . . . . . . . . . . . . . . . . 61-2
Controlling Whether a Cell Array Is Homogeneous or Heterogeneous
................................................. 61-2
Cell Arrays in Reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61-3

Control Whether a Cell Array Is Variable-Size . . . . . . . . . . . . . . . . . 61-4

Cell Array Limitations for Code Generation . . . . . . . . . . . . . . . . . . . 61-6


Assign Consistent Element Types . . . . . . . . . . . . . . . . . . . . . . . . . . 61-6
Variable-Size Cell Arrays Must Be Homogenous . . . . . . . . . . . . . . . 61-6
Assign Values to All Cell Array Elements . . . . . . . . . . . . . . . . . . . . . 61-6
Assign Initial Values on the Same Execution Path as the cell Function
................................................. 61-7
To Assign Initial Values to Variable-Size Cell Arrays in Object
Properties or Structure Fields, Use Temporary Variables . . . . . . 61-8
To Index into Heterogeneous Arrays, Use Constant Indices or for-loops
with Constant Bounds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61-8
To Grow Cell Arrays by Using {end + 1}, Use Certain Coding Patterns
................................................. 61-9
To Iterate Over a Cell Array Directly, the First Dimension of the Cell
Array Must Be 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61-10
Do Not Use Smooth Parentheses () to Index into Cell Arrays . . . . . 61-11
Do Not Call the cell Function Inside the Cell Array Constructor {}
................................................ 61-11
Do Not Store mxArray Data in a Cell Array . . . . . . . . . . . . . . . . . . 61-11
Do Not Pass a Cell Array to an External C/C++ Function by Using
coder.ceval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61-12
Do Not Pass Cell Arrays into or out of MATLAB Function Blocks . . 61-12

Code Generation for Categorical Arrays


62
Code Generation for Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . 62-2
Define Categorical Arrays for Code Generation . . . . . . . . . . . . . . . . 62-2
Allowed Operations on Categorical Arrays . . . . . . . . . . . . . . . . . . . 62-2
MATLAB Toolbox Functions That Support Categorical Arrays . . . . . 62-3

Define Categorical Array Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62-6


Define Categorical Array Inputs at the Command Line . . . . . . . . . . 62-6
Representation of Categorical Arrays . . . . . . . . . . . . . . . . . . . . . . . 62-6

Categorical Array Limitations for Code Generation . . . . . . . . . . . . . 62-8

lxxv
Code Generation for Datetime Arrays
63
Code Generation for Datetime Arrays . . . . . . . . . . . . . . . . . . . . . . . . 63-2
Define Datetime Arrays for Code Generation . . . . . . . . . . . . . . . . . 63-2
Allowed Operations on Datetime Arrays . . . . . . . . . . . . . . . . . . . . . 63-2
MATLAB Toolbox Functions That Support Datetime Arrays . . . . . . . 63-2

Define Datetime Array Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63-5


Define Datetime Array Inputs at the Command Line . . . . . . . . . . . . 63-5
Representation of Datetime Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 63-5

Datetime Array Limitations for Code Generation . . . . . . . . . . . . . . . 63-7

Code Generation for Duration Arrays


64
Code Generation for Duration Arrays . . . . . . . . . . . . . . . . . . . . . . . . 64-2
Define Duration Arrays for Code Generation . . . . . . . . . . . . . . . . . . 64-2
Allowed Operations on Duration Arrays . . . . . . . . . . . . . . . . . . . . . 64-2
MATLAB Toolbox Functions That Support Duration Arrays . . . . . . . 64-3

Define Duration Array Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64-6


Define Duration Array Inputs at the Command Line . . . . . . . . . . . . 64-6
Representation of Duration Arrays . . . . . . . . . . . . . . . . . . . . . . . . . 64-6

Duration Array Limitations for Code Generation . . . . . . . . . . . . . . . 64-8

Code Generation for Tables


65
Code Generation for Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-2
Define Tables for Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . 65-2
Allowed Operations on Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-2
MATLAB Toolbox Functions That Support Tables . . . . . . . . . . . . . . 65-3

Define Table Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-5


Define Table Inputs at the Command Line . . . . . . . . . . . . . . . . . . . . 65-5
Representation of Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-5

Table Limitations for Code Generation . . . . . . . . . . . . . . . . . . . . . . . 65-7


Creating Tables Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-7
Modifying Tables Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65-7
Using Table Functions Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 65-9

lxxvi Contents
Code Generation for Timetables
66
Code Generation for Timetables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66-2
Define Timetables for Code Generation . . . . . . . . . . . . . . . . . . . . . . 66-2
Allowed Operations on Timetables . . . . . . . . . . . . . . . . . . . . . . . . . 66-2
MATLAB Toolbox Functions That Support Timetables . . . . . . . . . . . 66-3

Define Timetable Inputs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66-5


Define Timetable Inputs at the Command Line . . . . . . . . . . . . . . . . 66-5
Representation of Timetables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66-5

Timetable Limitations for Code Generation . . . . . . . . . . . . . . . . . . . 66-8


Creating Timetables Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . 66-8
Modifying Timetables Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 66-9
Using Timetable Functions Limitations . . . . . . . . . . . . . . . . . . . . . 66-11

Code Generation for MATLAB Classes


67
MATLAB Classes Definition for Code Generation . . . . . . . . . . . . . . . 67-2
Language Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-2
Code Generation Features Not Compatible with Classes . . . . . . . . . 67-2
Defining Class Properties for Code Generation . . . . . . . . . . . . . . . . 67-3
Inheritance from Built-In MATLAB Classes Not Supported . . . . . . . 67-5

Classes That Support Code Generation . . . . . . . . . . . . . . . . . . . . . . . 67-7

Generate Code for MATLAB Value Classes . . . . . . . . . . . . . . . . . . . . 67-8

Generate Code for MATLAB Handle Classes and System Objects


.................................................... 67-12

Code Generation for Handle Class Destructors . . . . . . . . . . . . . . . 67-15


Guidelines and Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-15
Behavioral Differences of Objects in Generated Code and in MATLAB
................................................ 67-16

Class Does Not Have Property . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-18


Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-18

Passing By Reference Not Supported for Some Properties . . . . . . 67-20

Handle Object Limitations for Code Generation . . . . . . . . . . . . . . . 67-21


A Variable Outside a Loop Cannot Refer to a Handle Object Allocated
Inside a Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-21
A Handle Object That a Persistent Variable Refers To Must Be a
Singleton Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-22
References to Handle Objects Can Appear Undefined . . . . . . . . . . 67-23

lxxvii
System Objects in MATLAB Code Generation . . . . . . . . . . . . . . . . . 67-24
Usage Rules and Limitations for System Objects for Generating Code
................................................ 67-24
System Objects in codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-26
System Objects in the MATLAB Function Block . . . . . . . . . . . . . . . 67-26
System Objects in the MATLAB System Block . . . . . . . . . . . . . . . . 67-26
System Objects and MATLAB Compiler Software . . . . . . . . . . . . . 67-26

Work Around Language Limitation: Code Generation Does Not


Support Object Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-27
Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-27
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67-27

Code Generation for Function Handles


68
Function Handle Limitations for Code Generation . . . . . . . . . . . . . . 68-2

Defining Functions for Code Generation


69
Code Generation for Variable Length Argument Lists . . . . . . . . . . . 69-2

Generate Code for arguments Block That Validates Input and Output
Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69-3
Supported Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69-3
Names Must Be Compile-Time Constants . . . . . . . . . . . . . . . . . . . . 69-3
Using the Structure That Holds Name-Value Arguments . . . . . . . . . 69-4
Differences Between Generated Code and MATLAB Code . . . . . . . . 69-5

Code Generation for Anonymous Functions . . . . . . . . . . . . . . . . . . . 69-6


Anonymous Function Limitations for Code Generation . . . . . . . . . . 69-6

Code Generation for Nested Functions . . . . . . . . . . . . . . . . . . . . . . . 69-7


Nested Function Limitations for Code Generation . . . . . . . . . . . . . . 69-7

Calling Functions for Code Generation


70
Resolution of Function Calls for Code Generation . . . . . . . . . . . . . . 70-2
Key Points About Resolving Function Calls . . . . . . . . . . . . . . . . . . . 70-2
Compile Path Search Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-2
When to Use the Code Generation Path . . . . . . . . . . . . . . . . . . . . . 70-2

Resolution of File Types on Code Generation Path . . . . . . . . . . . . . . 70-4

lxxviii Contents
Compilation Directive %#codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-5

Use MATLAB Engine to Execute a Function Call in MATLAB Function


Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-6
When To Declare a Function as Extrinsic . . . . . . . . . . . . . . . . . . . . 70-6
Use the coder.extrinsic Construct . . . . . . . . . . . . . . . . . . . . . . . . . . 70-7
Call MATLAB Functions Using feval . . . . . . . . . . . . . . . . . . . . . . . . 70-9
Working with mxArrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-9
Restrictions on Using Extrinsic Functions . . . . . . . . . . . . . . . . . . . 70-11

Code Generation for Recursive Functions . . . . . . . . . . . . . . . . . . . . 70-12


Compile-Time Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-12
Run-Time Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-12
Disallow Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-13
Disable Run-Time Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-13
Recursive Function Limitations for Code Generation . . . . . . . . . . . 70-13

Force Code Generator to Use Run-Time Recursion . . . . . . . . . . . . . 70-14


Treat the Input to the Recursive Function as a Nonconstant . . . . . 70-14
Make the Input to the Recursive Function Variable-Size . . . . . . . . 70-15
Assign Output Variable Before the Recursive Call . . . . . . . . . . . . . 70-16

Avoid Duplicate Functions in Generated Code . . . . . . . . . . . . . . . . 70-17


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-17
Cause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-17
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-17

Improve Run-Time Performance of MATLAB Function


Block
71
Avoid Data Copies of Function Inputs in Generated Code . . . . . . . . 71-2

Inline Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71-4

Unroll for-Loops and parfor-Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 71-5


Force for-Loop Unrolling by Using coder.unroll . . . . . . . . . . . . . . . . 71-5

Generate Reusable Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71-7

LAPACK Calls for Linear Algebra in a MATLAB Function Block . . . 71-8

BLAS Calls for Matrix Operations in a MATLAB Function Block . . 71-9

FFTW calls for fast Fourier transform functions in a MATLAB


Function Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71-10

lxxix
Troubleshooting MATLAB Code in MATLAB Function Blocks
72
Compile-Time Recursion Limit Reached . . . . . . . . . . . . . . . . . . . . . . . . . . 72-2
Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-2
Cause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-2
Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-2
Force Run-Time Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-2
Increase the Compile-Time Recursion Limit . . . . . . . . . . . . . . . . . . . . . . 72-4

Output Variable Must Be Assigned Before Run-Time Recursive Call . . . 72-5


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-5
Cause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-5
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-5

Resolve Issue: Cell Array Elements Must Be Fully Defined Before Use
......................................................... 72-8
Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-8
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-9

Nonconstant Index into varargin or varargout in a for-Loop . . . . . . . . 72-12


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-12
Cause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-12
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-12

Unknown Output Type for coder.ceval . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-14


Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-14
Cause . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-14
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-14

Managing Data

Working with Data


73
About Data Types in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-2
Data Typing Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-2
Data Type Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-3

Data Types Supported by Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . 73-4


Block Support for Data and Signal Types . . . . . . . . . . . . . . . . . . . . 73-4

Control Data Types of Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-6


Entering Valid Data Type Values . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-6
Use the Model Data Editor for Batch Editing . . . . . . . . . . . . . . . . . 73-8
Share a Data Type Between Separate Algorithms, Data Paths, Models,
and Bus Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-9
Reuse Custom C Data Types for Signal Data . . . . . . . . . . . . . . . . . 73-10
Determine Data Type of Signal That Uses Inherited Setting . . . . . 73-11

lxxx Contents
Data Types Remain double Despite Changing Settings . . . . . . . . . 73-11

Data Type Inheritance Rules in Simulink . . . . . . . . . . . . . . . . . . . . 73-12


Data Type Rules for Product with Binary-Point Scaling . . . . . . . . . 73-14
Data Type Inheritance Rules for Product with Slope Scaling . . . . . 73-16
Data Type Inheritance Parameter Settings for Add . . . . . . . . . . . . 73-18
Data Type Inheritance Rules for Add with Binary-Point Scaling When
Ideal Type Is Single Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-18
Data Type Inheritance Rules for Add with Binary-Point Scaling When
Ideal Type is Multi-Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-20
Data Type Inheritance Rules for Add with Slope Scaling When Ideal
Result Is Single Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-23
Data Type Inheritance Rules for Add with Slope Scaling when Ideal
Result Type is Multi-Word . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-25
Data Type Inheritance Rules for Multiword Inputs . . . . . . . . . . . . 73-26

Validate a Floating-Point Embedded Model . . . . . . . . . . . . . . . . . . 73-28


Explore the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-28
Validate a Single-Precision Model . . . . . . . . . . . . . . . . . . . . . . . . . 73-29
Blocks That Support Single Precision . . . . . . . . . . . . . . . . . . . . . . 73-30

Fixed-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-32


Binary Point Interpretation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-32
Signed Fixed-Point Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-33

Benefits of Using Fixed-Point Hardware . . . . . . . . . . . . . . . . . . . . . 73-35

Scaling, Precision, and Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-36


Scaling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-36
Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-36
Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-37

Fixed-Point Data in MATLAB and Simulink . . . . . . . . . . . . . . . . . . 73-38


Fixed-Point Data in Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-38
Fixed-Point Data in MATLAB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-39
Scaled Doubles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-40

Share Fixed-Point Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-41

Control Fixed-Point Instrumentation and Data Type Override . . . 73-42


Control Instrumentation Settings . . . . . . . . . . . . . . . . . . . . . . . . . 73-42
Control Data Type Override . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-42
Instrumentation Settings and Data Type Override for a Model
Reference Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-42

Specify Fixed-Point Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-44


Overriding Fixed-Point Specifications . . . . . . . . . . . . . . . . . . . . . . 73-44

Specify Data Types Using Data Type Assistant . . . . . . . . . . . . . . . . 73-46


Specifying a Fixed-Point Data Type . . . . . . . . . . . . . . . . . . . . . . . . 73-48
Specify an Enumerated Data Type . . . . . . . . . . . . . . . . . . . . . . . . 73-53
Specify a Bus Object Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . 73-54
Specify an Image Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-54
Specify a Value Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-56

lxxxi
Simulink Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-58
String Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-60
Simulink Strings and Null Characters . . . . . . . . . . . . . . . . . . . . . . 73-60
String Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-61
Strings in Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-61
Strings and Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-61
String Data Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-62
Display and Extract Coordinate Data . . . . . . . . . . . . . . . . . . . . . . 73-64
Find Patterns in Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-66
Extract a String . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-67
Get Text Following a Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-67
Change Existing Models to Use Strings . . . . . . . . . . . . . . . . . . . . 73-68
Parse NMEA GPS Text Message . . . . . . . . . . . . . . . . . . . . . . . . . . 73-70
Simulink String Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-74

Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-76


Data Class Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . 73-76
Use Data Objects in Simulink Models . . . . . . . . . . . . . . . . . . . . . . 73-77
Data Object Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-79
Create Data Objects from Built-In Data Class Package Simulink . . 73-80
Create Data Objects from Another Data Class Package . . . . . . . . . 73-81
Create Data Objects Directly from Dialog Boxes . . . . . . . . . . . . . . 73-82
Create Data Objects for a Model Using Data Object Wizard . . . . . 73-83
Create Data Objects from External Data Source Programmatically
................................................ 73-86
Data Object Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-87
Handle Versus Value Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-88
Compare Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-89
Resolve Conflicts in Configuration of Signal Objects for Code
Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-89
Create Persistent Data Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-90

Simulink.DualScaledParameter Property Dialog Box . . . . . . . . . . 73-91


Main Attributes Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-91
Calibration Attributes Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-92

Simulink.NumericType Property Dialog Box . . . . . . . . . . . . . . . . . . 73-95

Use Simulink.Signal Objects to Specify and Control Signal Attributes


................................................... 73-100
Using Signal Objects to Assign or Validate Signal Attributes . . . . 73-100
Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-100
Multiple Signal Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-101
Signal Specification Block: An Alternative to Simulink.Signal . . . 73-101
Bus Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-102

Define Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-104


Use an example to define data classes . . . . . . . . . . . . . . . . . . . . 73-104
Manually define data class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-104
Optional: Add properties to data class . . . . . . . . . . . . . . . . . . . . 73-105
Optional: Add initialization code to data class . . . . . . . . . . . . . . . 73-106
Optional: Define storage classes . . . . . . . . . . . . . . . . . . . . . . . . . 73-106
Optional: Define custom attributes for storage classes . . . . . . . . 73-106

lxxxii Contents
Determine Where to Store Variables and Objects for Simulink
Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-109
Types of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-109
Types of Data Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-110
Managing Data Storage for Your Project . . . . . . . . . . . . . . . . . . . 73-113
Data Consistency in Model Hierarchy . . . . . . . . . . . . . . . . . . . . . 73-115

Manage Design Data for Simulink Models Programmatically . . . 73-118


Connect to a Data Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-118
Manage Variables in a Data Source . . . . . . . . . . . . . . . . . . . . . . 73-118
Manage Changes to a Data Source . . . . . . . . . . . . . . . . . . . . . . . 73-120
Manage Data Consistency in a Data Source . . . . . . . . . . . . . . . . 73-120
Manage Source-Specific Data Tasks . . . . . . . . . . . . . . . . . . . . . . 73-122

Create, Edit, and Manage Workspace Variables . . . . . . . . . . . . . . 73-124


Tools for Managing Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-124
Edit Variable Value or Property from Block Parameter . . . . . . . . 73-125
Modify Structure and Array Variables Interactively . . . . . . . . . . . 73-125
Ramifications of Modifying or Deleting a Variable . . . . . . . . . . . . 73-125
Analyze Variable Usage in a Model . . . . . . . . . . . . . . . . . . . . . . . 73-126
Rename a Variable Throughout a Model . . . . . . . . . . . . . . . . . . . 73-126
Interact with Variables Programmatically . . . . . . . . . . . . . . . . . . 73-127

Edit and Manage Workspace Variables by Using Model Explorer


................................................... 73-129
Finding Variables That Are Used by a Model or Block . . . . . . . . . 73-129
Finding Blocks That Use a Specific Variable . . . . . . . . . . . . . . . . 73-130
Finding Unused Workspace Variables . . . . . . . . . . . . . . . . . . . . . 73-131
Editing Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-132
Rename Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-133
Compare Duplicate Workspace Variables . . . . . . . . . . . . . . . . . . 73-134
Export Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-135
Importing Workspace Variables . . . . . . . . . . . . . . . . . . . . . . . . . 73-137

Model Workspaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-138


Model Workspace Differences from MATLAB Workspace . . . . . . . 73-138
Troubleshooting Memory Issues . . . . . . . . . . . . . . . . . . . . . . . . . 73-138
Manipulate Model Workspace Programmatically . . . . . . . . . . . . . 73-139

Specify Source for Data in Model Workspace . . . . . . . . . . . . . . . . 73-140


Data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-141
MAT-File and MATLAB File Source Controls . . . . . . . . . . . . . . . . 73-141
MATLAB Code Source Controls . . . . . . . . . . . . . . . . . . . . . . . . . 73-142

Change Model Workspace Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-143


Change Workspace Data Whose Source Is the Model File . . . . . . 73-143
Change Workspace Data Whose Source Is a MAT-File or MATLAB File
............................................... 73-144
Changing Workspace Data Whose Source Is MATLAB Code . . . . 73-144
Use MATLAB Commands to Change Workspace Data . . . . . . . . . 73-144
Create Model Mask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-145

Create External File Adapter for Loading Variables into


Simulink.SimulationInput Object . . . . . . . . . . . . . . . . . . . . . . . 73-146
Write Class Definition for Custom File Adapter . . . . . . . . . . . . . . 73-146

lxxxiii
Test Custom File Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-148
Register Custom File Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-150
Use Custom File Adapter to Load Variables for Simulation . . . . . 73-150

Symbol Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-151


Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-151
Symbol Resolution Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-151
Numeric Values with Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-152
Other Values with Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-153
Limit Signal Resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-153
Explicit and Implicit Symbol Resolution . . . . . . . . . . . . . . . . . . . 73-153

Upgrade Level-1 Data Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-155

Associating User Data with Blocks . . . . . . . . . . . . . . . . . . . . . . . . 73-157

Support Limitations for Simulink Software Features . . . . . . . . . . 73-158

Supported and Unsupported Simulink Blocks . . . . . . . . . . . . . . . 73-162

Support Limitations for Stateflow Software Features . . . . . . . . . 73-171


ml Namespace Operator, ml Function, ml Expressions . . . . . . . . 73-171
C or C++ Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-171
C Math Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-171
Atomic Subcharts That Call Exported Graphical Functions Outside a
Subchart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-172
Atomic Subchart Input and Output Mapping . . . . . . . . . . . . . . . . 73-172
Recursion and Cyclic Behavior . . . . . . . . . . . . . . . . . . . . . . . . . . 73-172
Custom C/C++ Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-173
Textual Functions with Literal String Arguments . . . . . . . . . . . . 73-174
Stateflow Charts Containing Ports . . . . . . . . . . . . . . . . . . . . . . . 73-174

Custom State Attributes in Discrete FIR Filter block . . . . . . . . . 73-175


Open Model Data Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-176
Build the Model and Inspect the Generated Code . . . . . . . . . . . . 73-177

Enumerations and Modeling


74
Simulink Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74-2
Simulink Constructs that Support Enumerations . . . . . . . . . . . . . . . 74-2
Simulink Enumeration Limitations . . . . . . . . . . . . . . . . . . . . . . . . . 74-3

Use Enumerated Data in Simulink Models . . . . . . . . . . . . . . . . . . . . 74-5


Define Simulink Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74-5
Simulate with Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74-10
Specify Enumerations as Data Types . . . . . . . . . . . . . . . . . . . . . . 74-12
Get Information About Enumerated Data Types . . . . . . . . . . . . . . 74-12
Enumeration Value Display . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74-13
Instantiate Enumerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74-14
Enumerated Values in Computation . . . . . . . . . . . . . . . . . . . . . . . 74-16

lxxxiv Contents
Create Data to Use as Simulation Input
75
Create and Edit Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-2
Differences Between the Root Inport Mapper Signal Editor and Other
Signal Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-3
Table Editing Data Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-3
Add and Edit Multidimensional Signals . . . . . . . . . . . . . . . . . . . . . . 75-3
Change x- and y-axes limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-6
Draw a Ramp Using Snap to Grid for Accuracy . . . . . . . . . . . . . . . . 75-7
Save and Send Changes to the Root Inport Mapper Tool . . . . . . . . . 75-8

Change Signal Editor Default Layout . . . . . . . . . . . . . . . . . . . . . . . . 75-9


Hide Toolstrip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-9
Minimize Signal Editor Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-10
Move Signal Editor Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-10

Use Scenarios and Insert Signals in Signal Editor . . . . . . . . . . . . . 75-11


Use Scenarios to Group and Organize Inputs . . . . . . . . . . . . . . . . 75-11
Link in Signal Data from Signal Builder Block and Simulink Design
Verifier Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-11
Insert Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-12
Add Signals to Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-13

Work with Basic Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-17


Create Signals and Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-17
Work with Basic Signal Data in Tabular Editor . . . . . . . . . . . . . . . 75-17

Create Signals with MATLAB Expressions and Variables . . . . . . . . 75-21


Replace Signal Data with MATLAB Expressions . . . . . . . . . . . . . . 75-24

Create Freehand Signal Data Using Mouse or Multi-Touch Gestures


.................................................... 75-26

Import Custom File Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-28

Create Custom File Type for Import to Signal Editor . . . . . . . . . . . 75-30


Define New FileType Object for Use in Simulink . . . . . . . . . . . . . . 75-31
Define FileType Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75-31

Create sldvData Custom File Type Reader to Import to Signal Editor


.................................................... 75-33

Export Signals to Custom Registered File Types . . . . . . . . . . . . . . 75-34

Load Simulation Input Data


76
Provide Signal Data for Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . 76-2
Identify Model Signal Data Requirements . . . . . . . . . . . . . . . . . . . . 76-2
Signal Data Storage for Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-2

lxxxv
Load Input Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-5
Log Output Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-6

Load Big Data for Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-7


Stream Individual Signals Using SimulationDatastore Objects . . . . 76-7
Stream Entire Dataset Using DatasetRef Object . . . . . . . . . . . . . . . 76-8
Load Individual Signals from a DatasetRef Object . . . . . . . . . . . . . . 76-9

Stream Data from a MAT-File as Input for a Parallel Simulation . 76-11

Overview of Signal Loading Techniques . . . . . . . . . . . . . . . . . . . . . 76-15


Source Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-15
Root-Level Input Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-16
From File Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-17
From Spreadsheet Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-18
From Workspace Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-19
Signal Editor Block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-19

Comparison of Signal Loading Techniques . . . . . . . . . . . . . . . . . . . 76-21


Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-21
Impact of Loading Techniques on Block Diagrams . . . . . . . . . . . . . 76-21
Comparison of Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-22

Control How Models Load Input Data . . . . . . . . . . . . . . . . . . . . . . . 76-27


Configure Input Data Interpolation . . . . . . . . . . . . . . . . . . . . . . . . 76-27
Capture Dynamics of Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . 76-28
Load Data as Continuous Signal . . . . . . . . . . . . . . . . . . . . . . . . . . 76-28
Load Data as Discrete Signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-30
Load Message Data into Model Using Playback Block . . . . . . . . . . 76-33

Load Data Logged in Another Simulation . . . . . . . . . . . . . . . . . . . . 76-39


Load Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-39
Configure Logging to Meet Loading Requirements . . . . . . . . . . . . 76-40

Load Data to Represent Variable-Step Input from Model Hierarchy


.................................................... 76-41

Load Input Data for Basic Test Cases . . . . . . . . . . . . . . . . . . . . . . . 76-47

Load Data to Root-Level Input Ports . . . . . . . . . . . . . . . . . . . . . . . . 76-51


Specify Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-51
Forms of Input Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-52
Time Values for the Input Parameter . . . . . . . . . . . . . . . . . . . . . . . 76-53
Data Loading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-53
Loading Dataset Data to Root-Level Inputs . . . . . . . . . . . . . . . . . . 76-53
Loading MATLAB Timeseries Data to Root-Level Inputs . . . . . . . . 76-54
Loading MATLAB Timetable Data to Root-Level Inputs . . . . . . . . . 76-55
Loading Data Structures to Root-Level Inputs . . . . . . . . . . . . . . . . 76-55
Loading Data Arrays to Root-Level Inputs . . . . . . . . . . . . . . . . . . . 76-58
Loading MATLAB Time Expressions to Root Inports . . . . . . . . . . . 76-60

Load Bus Data to Root-Level Input Ports . . . . . . . . . . . . . . . . . . . . 76-62


Imported Bus Data Requirements . . . . . . . . . . . . . . . . . . . . . . . . . 76-62
Open Example Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-63
Import Bus Data to a Top-Level Inport . . . . . . . . . . . . . . . . . . . . . 76-64

lxxxvi Contents
Get Information About Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . 76-65
Create Structures of Timeseries Objects from Buses . . . . . . . . . . . 76-66
Import Array of Buses Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-66

Load Input Data for Bus Using In Bus Element Blocks . . . . . . . . . 76-71

Load Signal Data That Uses Units . . . . . . . . . . . . . . . . . . . . . . . . . . 76-76


Loading Bus Signals That Have Units . . . . . . . . . . . . . . . . . . . . . . 76-76

Load Data Using the From File Block . . . . . . . . . . . . . . . . . . . . . . . 76-77

Load Data Using the From Workspace Block . . . . . . . . . . . . . . . . . 76-82

Load Data Using Playback Block . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-88

Load Timetable Data Using Playback Block . . . . . . . . . . . . . . . . . . 76-94

Load Simulation Inputs Using the Root Inport Mapper


77
Map Data Using Root Inport Mapper Tool . . . . . . . . . . . . . . . . . . . . . 77-2
The Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-2
Create Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-3
Import and Visualize Workspace Signal Data . . . . . . . . . . . . . . . . . 77-3
Map the Data to Inports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-5
Save the Mapping and Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-6
Simulate the Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-6

Map Root Inport Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-7


Command-Line Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-7
Import and Mapping Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-7
View and Inspect Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-8

Create Signal Data for Root Inport Mapping . . . . . . . . . . . . . . . . . . 77-9


Choose a Source for Data to Import and Map . . . . . . . . . . . . . . . . . 77-9
Choose a Naming Convention for Signals and Buses . . . . . . . . . . . . 77-9
Choose a Base Workspace and MAT-File Format . . . . . . . . . . . . . . . 77-9
Bus Signal Data for Root Inport Mapping . . . . . . . . . . . . . . . . . . . 77-10
Create Signal Data in a MAT-File for Root Inport Mapping . . . . . . 77-11

Import Signal Data for Root Inport Mapping . . . . . . . . . . . . . . . . . 77-13


Import Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-13
Import Bus Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-14
Import Signal Data from Other Sources . . . . . . . . . . . . . . . . . . . . 77-14
Import Data from Signal Editor . . . . . . . . . . . . . . . . . . . . . . . . . . 77-15
Import Test Vectors from Simulink Design Verifier Environment . . 77-15

Map Signal Data to Root Input Ports . . . . . . . . . . . . . . . . . . . . . . . . 77-16


Select Map Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-16
Set Options for Mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-16
Select Data to Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-16
Map Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-16

lxxxvii
Understand Mapping Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-18
Alternative Workflows to Load Mapping Data . . . . . . . . . . . . . . . . 77-20

Preview Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-22

Generate MATLAB Scripts for Simulation with Scenarios . . . . . . . 77-24

Create and Use Custom Map Modes . . . . . . . . . . . . . . . . . . . . . . . . 77-25


Create Custom Mapping File Function . . . . . . . . . . . . . . . . . . . . . 77-25

Root Inport Mapping Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-28


Open Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-28
Save Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-28
Open Existing Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-29
Work with Multiple Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-29

Load Data with Interchangeable Scenarios . . . . . . . . . . . . . . . . . . . 77-31


Load Data with Interchangeable Scenarios Using Signal Editor Block
................................................ 77-31
Explore the Signal Editor Block . . . . . . . . . . . . . . . . . . . . . . . . . . 77-32
Get Number of Scenarios and Signals . . . . . . . . . . . . . . . . . . . . . . 77-33

Migrate from Signal Builder Block to Signal Editor Block . . . . . . 77-35


Replace Signal Builder Block with Signal Editor Block . . . . . . . . . 77-35
Replace Programmatic Use of signalbuilder . . . . . . . . . . . . . . . . . 77-36

Importing and Exporting Simulation Data


78
Save Simulation Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-2
Choose Type of Simulation Data to Log . . . . . . . . . . . . . . . . . . . . . . 78-2
Choose Technique to Log Simulation Data . . . . . . . . . . . . . . . . . . . 78-3
Log Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-8

View and Access Logged Simulation Data . . . . . . . . . . . . . . . . . . . . 78-10


View Logged Data Using Simulation Data Inspector . . . . . . . . . . . 78-10
Access Logged Data Programmatically . . . . . . . . . . . . . . . . . . . . . 78-10

Data Format for Logged Simulation Data . . . . . . . . . . . . . . . . . . . . 78-12


Data Format for Block-Based Logged Data . . . . . . . . . . . . . . . . . . 78-12
Data Format for Model-Based Logged Data . . . . . . . . . . . . . . . . . . 78-12
Signal Logging Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-12
Logged Data Store Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-12
Time, State, and Output Data Format . . . . . . . . . . . . . . . . . . . . . . 78-12

Convert Data to Dataset Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-17


Why Convert to Dataset Format? . . . . . . . . . . . . . . . . . . . . . . . . . 78-17
Results of Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-18
Convert timeseries object to Dataset object . . . . . . . . . . . . . . . . . 78-19
Convert Structure to Dataset Object . . . . . . . . . . . . . . . . . . . . . . . 78-20
Migrate Legacy Code That Uses ModelDataLogs . . . . . . . . . . . . . 78-22
Dataset Conversion Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . 78-24

lxxxviii Contents
Limit the Size of Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-25
Limit the Number of Runs Retained in the Simulation Data Inspector
Archive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-25
Specify a Minimum Disk Space Requirement or Maximum Size for
Logged Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-25
View Data Only During Simulation . . . . . . . . . . . . . . . . . . . . . . . . 78-26
Reduce the Number of Data Points Logged from Simulation . . . . . 78-26

Specify Signal Values to Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-27


Decimation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-27
Log Last n Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-28
Specify Logging Intervals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-28

Work with Big Data for Simulations . . . . . . . . . . . . . . . . . . . . . . . . 78-30


Big Data Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-30

Log Data to Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-32


When to Log to Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . 78-32
Log to Persistent Storage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-33
Enable Logging to Persistent Storage Programmatically . . . . . . . . 78-33
How Simulation Data Is Stored . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-34
Save Logged Data from Successive Simulations . . . . . . . . . . . . . . 78-34

Analyze Big Data from a Simulation . . . . . . . . . . . . . . . . . . . . . . . . 78-36


Create DatasetRef Objects to Access Logged Datasets . . . . . . . . . 78-36
Use SimulationDatastore Objects to Access Signal Data . . . . . . . . 78-36
Create Timetables for MATLAB Analysis . . . . . . . . . . . . . . . . . . . . 78-36
Create Tall Timetables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-37
Access Persistent Storage Metadata . . . . . . . . . . . . . . . . . . . . . . . 78-37
Access Error Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-37

Samples to Export for Variable-Step Solvers . . . . . . . . . . . . . . . . . . 78-39


Output Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-39
Refine Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-39
Produce Additional Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-39
Produce Specified Output Only . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-40

Save Signal Data Using Signal Logging . . . . . . . . . . . . . . . . . . . . . . 78-42


Open Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-42
Enable Signal Logging for Model . . . . . . . . . . . . . . . . . . . . . . . . . 78-43
Mark Signals for Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-43
Specify Signal Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-44
Simulate Model and View Data . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-44
Access Signal Logging Data Programmatically . . . . . . . . . . . . . . . 78-45

View the Signal Logging Configuration . . . . . . . . . . . . . . . . . . . . . . 78-47


Approaches for Viewing the Signal Logging Configuration . . . . . . 78-47
View Signal Logging Configuration Using the Simulink Editor . . . 78-48
View Logging Configuration Using the Signal Logging Selector . . 78-49
View Signal Logging Configuration Using the Model Explorer . . . . 78-50
Programmatically Find Signals Configured for Logging . . . . . . . . 78-51

Override Signal Logging Settings . . . . . . . . . . . . . . . . . . . . . . . . . . 78-52


Benefits of Overriding Signal Logging Settings . . . . . . . . . . . . . . . 78-52
Scope of Signal Logging Setting Overrides . . . . . . . . . . . . . . . . . . 78-52

lxxxix
Override Signal Logging Settings with Signal Logging Selector . . 78-53
Override Signal Logging Settings Programmatically . . . . . . . . . . . 78-54

Visualize and Access Signal Logging Data . . . . . . . . . . . . . . . . . . . 78-58


View Signal Logging Data Using Simulation Data Inspector . . . . . 78-58
Access Workspace Data Programmatically . . . . . . . . . . . . . . . . . . 78-58

Access Logged Signals with Spaces and Newlines in Logged Names


.................................................... 78-63

Log Signals in For-Each Subsystems . . . . . . . . . . . . . . . . . . . . . . . . 78-66


Log Signal in Nested For-Each Subsystem . . . . . . . . . . . . . . . . . . 78-66
Log Buses in For-Each Subsystem . . . . . . . . . . . . . . . . . . . . . . . . . 78-68

Save Block States and Simulation Operating Points . . . . . . . . . . . 78-72


Choose Which State Information to Log . . . . . . . . . . . . . . . . . . . . 78-72
Choose Format for Logged State Information . . . . . . . . . . . . . . . . 78-77

Save State Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78-79

Log Data to the Workspace and a File Using the Record Block . . 78-83

Working with Data Stores


79
Data Store Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-2
When to Use a Data Store . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-2
Local and Global Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-2
Data Store Diagnostics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-3
Specify Initial Value for Data Store . . . . . . . . . . . . . . . . . . . . . . . . . 79-9

Model Global Data by Creating Data Stores . . . . . . . . . . . . . . . . . . 79-10


Data Store Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-10
Create and Apply Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-12
Data Stores with Data Store Memory Blocks . . . . . . . . . . . . . . . . . 79-13
Data Stores with Signal Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 79-16
Access Data Stores with Simulink Blocks . . . . . . . . . . . . . . . . . . . 79-17
Order Data Store Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-19
Data Stores with Buses and Arrays of Buses . . . . . . . . . . . . . . . . . 79-23
Accessing Specific Bus and Matrix Elements . . . . . . . . . . . . . . . . 79-24
Rename Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-27
Customized Data Store Access Functions in Generated Code . . . . 79-28

Log Data Stores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79-30


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

xc Contents
Simulink Data Dictionary
80
What Is a Data Dictionary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-2
Dictionary Capabilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-2
Sections of a Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-3
Dictionary Usage for Models Created with Different Versions of
Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-4
Manage and Edit Entries in a Dictionary . . . . . . . . . . . . . . . . . . . . . 80-5
Dictionary Referencing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-5
Import and Export File Formats . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-5
Allow Access to Base Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-5

Migrate Models to Use Simulink Data Dictionary . . . . . . . . . . . . . . 80-7


Migrate Single Model to Use Dictionary . . . . . . . . . . . . . . . . . . . . . 80-7
Migrate Model Reference Hierarchy to Use Dictionary . . . . . . . . . . 80-7
Considerations Before Migrating to Data Dictionary . . . . . . . . . . . . 80-8
Continue to Use Shared Data in the Base Workspace . . . . . . . . . . 80-11
Migrate Complicated Model Hierarchy with Shared Data . . . . . . . 80-12

Enumerations in Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-13


Migrate Enumerated Types into Data Dictionary . . . . . . . . . . . . . . 80-13
Manipulate Enumerations in Data Dictionary . . . . . . . . . . . . . . . . 80-15
Remove Enumerated Types from Data Dictionary . . . . . . . . . . . . . 80-16

Import and Export Dictionary Data . . . . . . . . . . . . . . . . . . . . . . . . . 80-18


Import Data to Dictionary from File . . . . . . . . . . . . . . . . . . . . . . . 80-18
Export Design Data from Dictionary . . . . . . . . . . . . . . . . . . . . . . . 80-21

View and Revert Changes to Dictionary Data . . . . . . . . . . . . . . . . . 80-23


View and Revert Changes to Dictionary Entries . . . . . . . . . . . . . . 80-23
View and Revert Changes to Entire Dictionary . . . . . . . . . . . . . . . 80-25

Partition Dictionary Data Using Referenced Dictionaries . . . . . . . 80-27

Partition Data for Model Reference Hierarchy Using Data


Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-29
Open the Example Model and Load Design Data . . . . . . . . . . . . . . 80-29
Create a Dictionary for Each Component . . . . . . . . . . . . . . . . . . . 80-29
Strategies to Discover Shared Data . . . . . . . . . . . . . . . . . . . . . . . 80-34

Attach Data Dictionary to Custom Libraries . . . . . . . . . . . . . . . . . . 80-35


Author Library Blocks with Data Types Defined in Attached Data
Dictionary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-35
Use Blocks From a Library with Attached Data Dictionary . . . . . . 80-36
Considerations When Using a Library Dictionary . . . . . . . . . . . . . 80-37

Store Data in Dictionary Programmatically . . . . . . . . . . . . . . . . . . 80-39


Add Entry to Design Data Section of Data Dictionary . . . . . . . . . . 80-39
Rename Data Dictionary Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-40
Increment Value of Data Dictionary Entry . . . . . . . . . . . . . . . . . . . 80-40
Data Dictionary Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-40
Dictionary Section Management . . . . . . . . . . . . . . . . . . . . . . . . . . 80-41
Dictionary Entry Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-42

xci
Transition to Using Data Dictionary . . . . . . . . . . . . . . . . . . . . . . . 80-42
Programmatically Migrate Single Model to Use Dictionary . . . . . . 80-43
Import Directly From External File to Dictionary . . . . . . . . . . . . . 80-43
Programmatically Partition Data Dictionary . . . . . . . . . . . . . . . . . 80-45
Make Changes to Configuration Set Stored in Dictionary . . . . . . . 80-45

Attach Data Dictionary to Subsystem Reference . . . . . . . . . . . . . . 80-47


Attach Data Dictionary to a Subsystem File . . . . . . . . . . . . . . . . . 80-47
Symbol Resolution Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-49
Considerations and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-50

Graphically Manage Shared Interfaces, Data Types, and Constants


.................................................... 80-52
Create Simulink Data Dictionary and Open Architectural Data Section
for Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-52
Design Data Types, Interfaces, and Constants Using Architectural Data
Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-54
Link Data Dictionary to Model . . . . . . . . . . . . . . . . . . . . . . . . . . . 80-56

Managing Signals

Working with Signals


81
Signal Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-2
Signal Line Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-2
Signal Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-3
Signal Names and Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-4
Signal Display Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-5
Store Design Attributes of Signals and States . . . . . . . . . . . . . . . . . 81-5
Test Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-6

Signal Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-7


Control Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-7
Composite Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-8
Virtual and Nonvirtual Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-8

Investigate Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-9


Initialize Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-9
View Signal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-9
Display Signal Values in Model Diagrams . . . . . . . . . . . . . . . . . . . 81-10
Signal Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-10
Complex Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-10
Exporting Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-11

Signal Label Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-12


Blocks That Support Signal Label Propagation . . . . . . . . . . . . . . . 81-12
How Simulink Propagates Signal Labels . . . . . . . . . . . . . . . . . . . . 81-13
Display Propagated Signal Labels . . . . . . . . . . . . . . . . . . . . . . . . . 81-15
Special Cases of Signal Propagation . . . . . . . . . . . . . . . . . . . . . . . 81-16

xcii Contents
How Simulink Propagates Signal Properties in a Model . . . . . . . . 81-18
Algorithm for Propagation of Signal Properties . . . . . . . . . . . . . . . 81-18
Use Configuration Parameter to Report and Resolve Propagation
Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-18
Display and Visualize the Signal Properties During Propagation . . 81-19

Determine Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-20


Simulink Blocks that Support Multidimensional Signals . . . . . . . . 81-21
Determine the Output Dimensions of Source Blocks . . . . . . . . . . . 81-21
Determine the Output Dimensions of Nonsource Blocks . . . . . . . . 81-22
Signal and Parameter Dimension Rules . . . . . . . . . . . . . . . . . . . . . 81-22
Scalar Expansion of Inputs and Parameters . . . . . . . . . . . . . . . . . 81-22
Get Compiled Port Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-24

Highlight Signal Sources and Destinations . . . . . . . . . . . . . . . . . . 81-29


Highlight Signal Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-29
Highlight Signal Destination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-30
Choose the Path of a Trace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-30
Trace a Signal to and from Subsystems . . . . . . . . . . . . . . . . . . . . . 81-31
Show All Possible Paths of a Trace . . . . . . . . . . . . . . . . . . . . . . . . 81-32
Display Port Values Along a Trace . . . . . . . . . . . . . . . . . . . . . . . . . 81-32
Remove Highlighting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-33
Resolve Incomplete Highlighting to Library Blocks . . . . . . . . . . . . 81-34
Signal Highlighting in Variant Systems . . . . . . . . . . . . . . . . . . . . . 81-34
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-35
Bus Element Tracing and Highlighting . . . . . . . . . . . . . . . . . . . . . 81-35

Specify Signal Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-37


Blocks That Allow Signal Range Specification . . . . . . . . . . . . . . . . 81-37
Work with Signal Ranges in Blocks . . . . . . . . . . . . . . . . . . . . . . . . 81-38
Troubleshoot Signal Range Errors . . . . . . . . . . . . . . . . . . . . . . . . 81-39
Unexpected Errors or Warnings for Data with Greater Precision or
Range than double . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-41

Initialize Signals and Discrete States . . . . . . . . . . . . . . . . . . . . . . . 81-43


Using Block Parameters to Initialize Signals and Discrete States . 81-43
Use Signal Objects to Initialize Signals and Discrete States . . . . . 81-44
Using Signal Objects to Tune Initial Values . . . . . . . . . . . . . . . . . . 81-46
Initialization Behavior Summary for Signal Objects . . . . . . . . . . . . 81-47

Configure Signals as Test Points . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-50


What Is a Test Point? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-50
Displaying Test Point Indicators . . . . . . . . . . . . . . . . . . . . . . . . . . 81-51

Specify Common Set of Signal Properties as Value Type . . . . . . . . 81-52


Determine Whether To Use Value Types . . . . . . . . . . . . . . . . . . . . 81-52
Create Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-54
Specify Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-55
Save Value Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-56
Map Value Types to Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-57

Value Types at Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-58

Display Signal Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-64


Ports & Signals Menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-64

xciii
Port Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-65
Design Ranges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-66
Signal Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-66
Signal to Object Resolution Indicator . . . . . . . . . . . . . . . . . . . . . . 81-67
Wide Nonscalar Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-68

Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-69


About Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-69
Using the Signal Builder Block with Fast Restart . . . . . . . . . . . . . 81-70
Editing Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-70
Editing Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-71
Creating Signal Group Sets Manually . . . . . . . . . . . . . . . . . . . . . . 81-79
Signal Data Files and Data Reformatting Function for Following
Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-80
Importing Signal Group Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-80
Importing Data with Custom Formats . . . . . . . . . . . . . . . . . . . . . . 81-93
Editing Waveforms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-94
Signal Builder Time Range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-98
Exporting Signal Group Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81-98
Simulating with Signal Groups . . . . . . . . . . . . . . . . . . . . . . . . . . 81-100
Simulation from Signal Builder Block . . . . . . . . . . . . . . . . . . . . . 81-101

Using Composite Interfaces


82
Composite Interface Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-2
Visualize Composite Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-2
Define Composite Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-4

Explore Composite Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-5


Composite Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-5
High-Level Composite Interface Selection Guidelines . . . . . . . . . . . 82-6
Modeling Requirement Considerations . . . . . . . . . . . . . . . . . . . . . . 82-8

Compare Capabilities of Composite Interfaces . . . . . . . . . . . . . . . . . 82-9


Composite Interface Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-9
Composite Interface Modeling . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-10
Composite Interface Code Generation . . . . . . . . . . . . . . . . . . . . . . 82-12

Group Signals or Messages into Virtual Buses . . . . . . . . . . . . . . . . 82-14


Group Signal Lines Within Component . . . . . . . . . . . . . . . . . . . . . 82-14
Connect Multiple Output Signals to a Port . . . . . . . . . . . . . . . . . . 82-17
Specify Multiple Elements of a Port . . . . . . . . . . . . . . . . . . . . . . . 82-19
Access Elements of Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-23

Simplify Subsystem and Model Interfaces with Bus Element Ports


.................................................... 82-24
Combine Multiple Subsystem Ports into One Port . . . . . . . . . . . . . 82-25
Simplify Bus Interfaces in Subsystems and Models . . . . . . . . . . . . 82-28

Modify Bus Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-33


Resolve Circular Dependencies in Buses . . . . . . . . . . . . . . . . . . . . 82-33

xciv Contents
Create Nonvirtual Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-35
Create Nonvirtual Buses Within Component . . . . . . . . . . . . . . . . . 82-35
Create Nonvirtual Buses at Interfaces . . . . . . . . . . . . . . . . . . . . . 82-37
Convert Virtual Bus to Nonvirtual Bus . . . . . . . . . . . . . . . . . . . . . 82-40
Create Nonvirtual Bus from MATLAB Structure . . . . . . . . . . . . . . 82-42

Display Bus Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-44


Display Bus Line Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-44
View Bus Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-44
Trace Bus Element to Source and Destination Blocks . . . . . . . . . . 82-45
Find Buses at Block Diagram Interfaces . . . . . . . . . . . . . . . . . . . . 82-46
Display Bus Element Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-47
View Simulation Data for Buses . . . . . . . . . . . . . . . . . . . . . . . . . . 82-47
Get Bus Hierarchy and Virtuality Programmatically . . . . . . . . . . . 82-49
Get Bus Attributes at Interfaces Programmatically . . . . . . . . . . . . 82-50

Bus-Capable Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-53

Assign Signal Values to Bus Elements . . . . . . . . . . . . . . . . . . . . . . . 82-59

Identify Automatic Bus Conversions . . . . . . . . . . . . . . . . . . . . . . . . 82-61


Bus-to-Vector Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-61
Virtual and Nonvirtual Bus Conversions . . . . . . . . . . . . . . . . . . . . 82-61

Modify Sample Times for Nonvirtual Buses . . . . . . . . . . . . . . . . . . 82-63

Specify Bus Properties with Bus Objects . . . . . . . . . . . . . . . . . . . . . 82-65


Determine Whether to Use Bus Objects . . . . . . . . . . . . . . . . . . . . 82-65
Create Simulink Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-66
Specify Simulink Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-66
Save Simulink Bus Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-67
Map Simulink Bus Objects to Models . . . . . . . . . . . . . . . . . . . . . . 82-68

Programmatically Create Simulink Bus Objects . . . . . . . . . . . . . . . 82-70


Create Bus Objects from Bus Element Objects . . . . . . . . . . . . . . . 82-70
Create Bus Objects from Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . 82-71
Create Bus Objects from MATLAB Data . . . . . . . . . . . . . . . . . . . . 82-71
Create Bus Objects from External C Code . . . . . . . . . . . . . . . . . . . 82-71

Specify Initial Conditions for Bus Elements . . . . . . . . . . . . . . . . . . 82-72


Blocks That Support Bus Initialization . . . . . . . . . . . . . . . . . . . . . 82-72
Set Diagnostics to Support Bus Initialization . . . . . . . . . . . . . . . . 82-72
Create Initial Condition Structures . . . . . . . . . . . . . . . . . . . . . . . . 82-73
Control Data Types of Structure Fields . . . . . . . . . . . . . . . . . . . . . 82-73
Create Full Structures for Initialization . . . . . . . . . . . . . . . . . . . . 82-73
Create Partial Structures for Initialization . . . . . . . . . . . . . . . . . . 82-74
Initialize Buses Using Block Parameters . . . . . . . . . . . . . . . . . . . . 82-76

Group Nonvirtual Buses in Arrays of Buses . . . . . . . . . . . . . . . . . . 82-79


Requirements of Arrays of Buses . . . . . . . . . . . . . . . . . . . . . . . . . 82-79
Create Array of Buses from Nonvirtual Buses . . . . . . . . . . . . . . . . 82-79
Create Array of Buses from MATLAB Structures . . . . . . . . . . . . . . 82-81

Work with Arrays of Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-83


Perform Iterative Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-83

xcv
Assign Values into Arrays of Buses . . . . . . . . . . . . . . . . . . . . . . . . 82-83
Select Bus Elements from Array of Buses . . . . . . . . . . . . . . . . . . . 82-84
Import Array of Buses Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-84
Log Arrays of Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-84
Initialize Arrays of Buses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-85
Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82-85

Programmatically Initialize Arrays of Buses . . . . . . . . . . . . . . . . . . 82-86

Assign into Elements of Array of Buses . . . . . . . . . . . . . . . . . . . . . . 82-88

Iteratively Process Nonvirtual Buses with Arrays of Buses . . . . . . 82-90

Share and Reuse Bus-Routing Blocks . . . . . . . . . . . . . . . . . . . . . . . 82-92

Generate Code for Nonvirtual Buses . . . . . . . . . . . . . . . . . . . . . . . . 82-93


Control Data Types of Initial Condition Structure Fields . . . . . . . . 82-94
Code Generation for Arrays of Buses . . . . . . . . . . . . . . . . . . . . . 82-100

Inspect Generated Code for Nonvirtual Buses . . . . . . . . . . . . . . . 82-101

Trace Connections Using Interface Display . . . . . . . . . . . . . . . . . 82-103


Trace Connections in a Subsystem . . . . . . . . . . . . . . . . . . . . . . . 82-103

Working with Variable-Size Signals


83
Variable-Size Signal Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83-2
How Variable-Size Signals Propagate . . . . . . . . . . . . . . . . . . . . . . . 83-2
Determine Whether Signal Line Has Variable Size . . . . . . . . . . . . . 83-3
Empty Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83-4
Simulink Block Support for Variable-Size Signals . . . . . . . . . . . . . . 83-4
Variable-Size Signal Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . 83-6

Unbounded Variable-Size Signals . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83-9


Using Unbounded Variable-Size Signals . . . . . . . . . . . . . . . . . . . . 83-10
Unbounded Variable-Size Signals in C++ Code Generation . . . . . . 83-12
Unbounded Variable-Size Arrays in MATLAB Function Block . . . . . 83-12
Supported Blocks and Features for Simulation . . . . . . . . . . . . . . . 83-13
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83-14

Inspect Variable-Size Signals on Simulink Models . . . . . . . . . . . . . 83-15


Variable-Size Signal Generation and Operations . . . . . . . . . . . . . . 83-15
Variable-Size Signal Length Adaptation . . . . . . . . . . . . . . . . . . . . 83-17
Mode-Dependent Variable-Size Signals . . . . . . . . . . . . . . . . . . . . . 83-20
S-Functions Using Variable-Size Signals . . . . . . . . . . . . . . . . . . . . 83-24

xcvi Contents
Customizing Simulink Environment and Printed Models

Customizing the Simulink User Interface


84
Access Frequently Used Features and Commands in Simulink . . . . 84-2
Search for Simulink Toolstrip Actions . . . . . . . . . . . . . . . . . . . . . . . 84-2
Rerun Favorite Commands for Simulink . . . . . . . . . . . . . . . . . . . . . 84-2
Share Favorite Commands for Simulink . . . . . . . . . . . . . . . . . . . . . 84-4

Create Custom Simulink Toolstrip Tabs . . . . . . . . . . . . . . . . . . . . . . 84-5


Start Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-5
Create Simulink Toolstrip Component . . . . . . . . . . . . . . . . . . . . . . . 84-6
Add Blank Tab to Simulink Toolstrip . . . . . . . . . . . . . . . . . . . . . . . . 84-6
Open JSON File to Develop Custom Tab . . . . . . . . . . . . . . . . . . . . . 84-7
Define Custom Tab Layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-8
Choose Among Types of Controls . . . . . . . . . . . . . . . . . . . . . . . . . 84-10
Get Built-In Simulink Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-11
Specify Built-In Simulink Actions . . . . . . . . . . . . . . . . . . . . . . . . . 84-12
Define Custom Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-13
Choose Among Pop-Up List Elements . . . . . . . . . . . . . . . . . . . . . . 84-17
Define Pop-Up Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-18
Share Custom Tabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-27

Add Prepopulated Custom Tab to Simulink Toolstrip . . . . . . . . . . . 84-28

Add Items to Model Editor Menus . . . . . . . . . . . . . . . . . . . . . . . . . . 84-36


Code for Adding Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-36
Define Menu Items . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-37
Register Menu Customizations . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-41
Callback Info Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-41
Debugging Custom Menu Callbacks . . . . . . . . . . . . . . . . . . . . . . . 84-42
Menu Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-42

Disable Simulink Toolstrip and Context Menu Actions . . . . . . . . . 84-44


Get Action Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-44
Create Customization File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-45
Create Filter Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-46
Register Filter Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-46
Read and Refresh Customization Files . . . . . . . . . . . . . . . . . . . . . 84-47

Disable and Hide Dialog Box Controls . . . . . . . . . . . . . . . . . . . . . . . 84-48


About Disabling and Hiding Controls . . . . . . . . . . . . . . . . . . . . . . 84-48
Disable a Button on a Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . 84-48
Write Control Customization Callback Functions . . . . . . . . . . . . . . 84-49
Dialog Box Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-49
Widget IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-49
Register Control Customization Callback Functions . . . . . . . . . . . 84-50

Customize Library Browser Appearance . . . . . . . . . . . . . . . . . . . . . 84-52


Reorder Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-52
Disable and Hide Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-52

xcvii
Expand or Collapse Library in Browser Tree . . . . . . . . . . . . . . . . . 84-53

Improve Quick Block Insert Results . . . . . . . . . . . . . . . . . . . . . . . . 84-55

Register Customizations with Simulink . . . . . . . . . . . . . . . . . . . . . 84-56


Create Customization File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-56
Edit the Customization File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84-56
Read and Refresh Customization Files . . . . . . . . . . . . . . . . . . . . . 84-56

Frames for Printed Models


85
Create Print Frames for Printed Pages . . . . . . . . . . . . . . . . . . . . . . . 85-2
PrintFrame Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85-3
Create a Print Frame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85-4
Add Rows and Cells to Print Frames . . . . . . . . . . . . . . . . . . . . . . . . 85-5
Add Content to Print Frame Cells . . . . . . . . . . . . . . . . . . . . . . . . . . 85-5
Format Content in Cells . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85-7

Running Models on Target Hardware

About Run on Target Hardware Feature


86
Simulink Supported Hardware . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86-2

Block Produces Zeros or Does Nothing in Simulation . . . . . . . . . . . 86-3

Running Simulations in Fast Restart


87
How Fast Restart Improves Iterative Simulations . . . . . . . . . . . . . . . . . . 87-2
Script Fast Restart Simulations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87-2
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87-4

Get Started with Fast Restart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87-7


Prepare a Model to Use Fast Restart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87-8
Fast Restart Methodology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87-10

xcviii Contents
Model Component Testing

Component Verification
88
Component Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-2
Use Foundational Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-2
Perform Rigorous Component Verification . . . . . . . . . . . . . . . . . . . . 88-2

Run Polyspace Analysis on Generated Code by Using Packaged


Options Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-5
Generate and Package Polyspace Options Files . . . . . . . . . . . . . . . . 88-5
Run Polyspace Analysis by Using the Packaged Options Files . . . . . 88-7

Analyze Code Generated as Standalone Code in a Distributed


Workflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-8
Open Model for Distributed Analysis . . . . . . . . . . . . . . . . . . . . . . . . 88-8
Configure Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-9
Generate Code Archive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-10
Generate and Package Polyspace Options File . . . . . . . . . . . . . . . 88-10
Run Polyspace Analysis by Using the Packaged Options Files . . . . 88-10

Manage a Variant Model Using Variant Manager


89
Variant Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-2
What is a Variant Configuration? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-2
Types of Variant Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-3
Constraints on Variant Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-3
Variant Configuration Data Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-3
Activate a Variant Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-5
Differences Between Variant Manager Activation and Update Diagram
Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-6
Referenced Component Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . 89-7
Preferred Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-7
Variant Manager View of Variant Configurations . . . . . . . . . . . . . . . . . . . 89-7
Use Variant Configurations in Simulation and Testing Workflows . . . . . . 89-9
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-9

Create and Activate Variant Configurations . . . . . . . . . . . . . . . . . . . . . . 89-10


Steps to Create Variant Configurations . . . . . . . . . . . . . . . . . . . . . . . . . 89-10
Open Variant Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-10
Configurations Tab in Variant Manager . . . . . . . . . . . . . . . . . . . . . . . . . 89-10
Add New Variant Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-12
Add, Import, or Export Control Variables in Variant Configuration . . . . 89-12
Edit Control Variables in Variant Configuration . . . . . . . . . . . . . . . . . . . 89-13
Set Up Variant Configurations for Referenced Components . . . . . . . . . . 89-15
Define Constraints for Variant Configurations . . . . . . . . . . . . . . . . . . . . 89-15
Save Variant Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-18

xcix
Validate and Activate Variant Configuration . . . . . . . . . . . . . . . . . . . . . 89-18
Apply Variant Configuration on Model . . . . . . . . . . . . . . . . . . . . . . . . . 89-19

Generate Variant Configurations Automatically . . . . . . . . . . . . . . . . . . . 89-20


Generate Variant Configurations Using Variant Manager . . . . . . . . . . . 89-20
Steps to Generate Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-21
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-26

Compose Variant Configurations for Top Model Using Referenced Model


Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-29
Open Component Configurations View . . . . . . . . . . . . . . . . . . . . . . . . . 89-29
Select Variant Configuration for Referenced Component . . . . . . . . . . . . 89-30
Clear Selected Variant Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . 89-31
Component Configurations View Example . . . . . . . . . . . . . . . . . . . . . . . 89-31
Validate That Top-Level Model Uses Referenced Component Configuration
.................................................... 89-32

Save and Reuse Variant Configurations Using Variant Configuration Data


Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-34

Variant Manager Workflow to Set Up Variant Configurations for Models


........................................................ 89-38

Variant Manager Workflow to Manage Existing Variant Configurations in


Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-41

Reduce Variant Models Using Variant Reducer . . . . . . . . . . . . . . . . . . . 89-44


Variant Reducer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-44
Video Walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-46
Steps to Reduce Variant Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-46
Explore Variant Reducer Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-52
Considerations for Variant Reduction . . . . . . . . . . . . . . . . . . . . . . . . . . 89-53
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-55

Reduce Models Containing Referenced Subsystems . . . . . . . . . . . . . . . 89-57

Reduce Model Containing Variant Blocks . . . . . . . . . . . . . . . . . . . . . . . . 89-61

Reduce Model Containing Variant Parameters . . . . . . . . . . . . . . . . . . . . 89-68

Analyze Variant Configurations in Models Containing Variant Blocks


........................................................ 89-77
Analyze Variant Configurations Using Variant Analyzer . . . . . . . . . . . . . 89-77
Run Variant Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-78
Explore Variant Analysis Report . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-80
Analyze Variant Configurations Programmatically . . . . . . . . . . . . . . . . . 89-84

Compatibility Considerations When Using Variant Manager for Simulink


Support Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-85
Changes to the Simulink.VariantConfigurationData class . . . . . . . . . . . 89-85
Changes to the Simulink.VariantManager class . . . . . . . . . . . . . . . . . . . 89-87
Variant Reducer and Variant Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . 89-87

Validate and Activate Variant Configurations . . . . . . . . . . . . . . . . . . . . . 89-89

c Contents
Analyze Variant Configurations Programmatically . . . . . . . . . . . . . . . . . 89-90

Generate Variant Configurations Programmatically . . . . . . . . . . . . . . . 89-92

Find Variant Control Variables for Model . . . . . . . . . . . . . . . . . . . . . . . . 89-94

Manage, Configure, Reduce, and Analyze System Variants with Variant


Manager for Simulink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89-95

Run Simulations for Variant Models Using Variant Configurations . . 89-104

Run Tests for Variant Models Using Variant Configurations . . . . . . . 89-106

Vary Block Parameter Values Conditionally Using Variant


Parameters
90
Use Variant Parameters to Reuse Block Parameters with Different Values
......................................................... 90-2
When to Create Variant Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-2
Advantages of Using Variant Parameters . . . . . . . . . . . . . . . . . . . . . . . . . 90-3
Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-3

Create a Simple Variant Parameter Model . . . . . . . . . . . . . . . . . . . . . . . . 90-5

Change Active Values and Activation Time of Variant Parameters . . . . 90-10

Variant Control Mode in Variant Parameters . . . . . . . . . . . . . . . . . . . . . 90-13


Switch Between Choices Using Condition Expressions in Variant Parameters
.................................................... 90-13
Variant Activation Times for Different Variant Control Modes in Variant
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-16

Use Variant Control Variables in Variant Parameters . . . . . . . . . . . . . . . 90-18


Numeric Variant Control Values for Rapid Prototyping of Variant Parameters
.................................................... 90-18
Simulink.Parameter Type of Variant Control Variables for Code Generation
of Variant Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-20
Enumerated Types to Improve Code Readability of Variant Control Variables
of Variant Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-23
Simulink.VariantExpression Objects for Variant Condition Reuse of Variant
Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-26

Compile Code Conditionally for All Values of Variant Parameters with


Same and Different Dimensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-29

Run Executable for Different Variant Parameter Values Without


Recompiling Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-35

Improve Code Readability of Variant Parameters Using Enumerated Types


........................................................ 90-42

ci
Reuse Variant Parameter Values from Handwritten Code Using
Simulink.Parameter Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-46

Group Variant Parameter Values in Code Using Variant Parameter Bank


........................................................ 90-49

Group Variant Parameter Values and Conditionally Switch Active Value


Sets in Generated Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-50

Integrate Python Code with Simulink


91
Overview of Integrating Python Code with Simulink . . . . . . . . . . . . . . . . 91-2
Configure System to Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91-2
Integrate Python Code with Simulink Using MATLAB Function Block . . . 91-2
Integrate Python Code with Simulink Using MATLAB System Block . . . . 91-3

Import Python Code to Simulink Using Python Importer Wizard . . . . . . 91-6


Configure System to Use Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91-6
Use Python Importer with Blockset Designer . . . . . . . . . . . . . . . . . . . . . 91-6
Use Python Importer as a Standalone Application . . . . . . . . . . . . . . . . . 91-12
Specify Simulation Mode for the Generated Blocks . . . . . . . . . . . . . . . . 91-16

cii Contents
Introduction to Simulink

103
1

Simulink Basics

The following sections explain how to perform basic tasks when using the Simulink product.

• “Programmatic Modeling Basics” on page 1-2


• “Keyboard Shortcuts and Mouse Actions for Simulink Modeling” on page 1-8
• “Open Models” on page 1-19
• “Save Models” on page 1-26
• “Add Blocks to Models” on page 1-32
• “Connect Blocks” on page 1-36
• “Edit Block Parameters” on page 1-48
• “Configure Model Layout” on page 1-56
• “Configure Model Element Names and Labels” on page 1-64
• “Configure Model Style Elements” on page 1-67
• “Customize Block Icons” on page 1-70
• “Visually Organize Models Using Areas” on page 1-72
• “Annotate Models” on page 1-76
• “Bookmark Your Place in Models” on page 1-85
• “Search Model Contents” on page 1-88
• “Keyword Search for Simulink Editor Actions” on page 1-92
• “Preview Content of Model Components” on page 1-93
• “Exchange Messages with Block Comments” on page 1-95
• “Print Model Diagrams” on page 1-98
• “Print Model Reports” on page 1-105
• “Programmatically Print Models from MATLAB Command Window” on page 1-107
• “Index and Search Models with Model Finder” on page 1-112
1 Simulink Basics

Programmatic Modeling Basics


In this section...
“Load a Model” on page 1-2
“Create a Model and Specify Parameter Settings” on page 1-2
“Programmatically Load Variables When Opening a Model” on page 1-3
“Programmatically Add and Connect Blocks” on page 1-3
“Programmatically Comment Out or Comment Through Blocks” on page 1-5
“Name a Signal Programmatically” on page 1-5
“Arrange Model Layouts Automatically” on page 1-6
“Open the Same Model in Multiple Windows” on page 1-6
“Use Model Finder to Index and Search Models and Improve Their Discoverability” on page 1-6
“Locate Diagram Elements Using Highlighting” on page 1-6
“Specify Colors Programmatically” on page 1-6

You can perform most Simulink modeling basics programmatically at the MATLAB® Command
Window, such as creating models, adding blocks to models, and setting parameters. These examples
show some of these commands and how you can use them.

Load a Model
Loading a model brings it into memory but does not open it in the Simulink Editor for editing. After
you load a model, you can work with it programmatically. You can use the Simulink Editor to edit the
model only if you open the model.

To load a system, use the load_system command.

For example, suppose you have a model named myModel on the MATLAB path. To load the model,
enter this command in the MATLAB Command Window:

load_system('myModel')

Create a Model and Specify Parameter Settings


You can write a function that creates a model and uses the settings that you prefer. For example, this
function creates a model that has a green background 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));

1-2
Programmatic Modeling Basics

% set default screen color


set_param(modelname,'ScreenColor','green');

% set default solver


set_param(modelname,'Solver','ode3');

% save the model


save_system(modelname);

Programmatically Load Variables When Opening a Model


If you assign a variable as a block parameter value, you must define the value of the variable in the
model. You can define the variable programmatically using the PreloadFcn callback with the
set_param function. Use the function in this form:

set_param('mymodel','PreloadFcn','expression')

expression is a MATLAB command or a MATLAB script on your MATLAB search path. This
command sets the model PreloadFcn callback to the value that you specify. Save the model to save
the setting.

For example, when you define the variables in a MATLAB script loadvar.m for the model
modelname.slx, use this command:

set_param('modelname','PreloadFcn','loadvar')

To assign the variable K the value 15, use this command:

set_param('modelname','PreloadFcn','K=15')

After you save the model, the PreloadFcn callback executes when you next open the model.

Programmatically Add and Connect Blocks


This example shows how to use functions to add blocks and connect the blocks programmatically.
Once you have added blocks to the model, you use three different approaches to connect them:
routed lines, port handles, and port IDs. Routed lines allow you to specify the exact (x,y) coordinates
of all connecting line segment endpoints. Port handles and port IDs allow connecting lines to block
ports without having to know the port location coordinates.

Create and open a blank model named ‘mymodel’.

Add blocks, including a subsystem block. Use the position array in the set_param function to set
the size and position of the blocks. Set the upper left and lower right block corners using (x,y)
coordinates.

add_block('simulink/Sources/Sine Wave','mymodel/Sine1');
set_param('mymodel/Sine1','position',[140,80,180,120]);
add_block('simulink/Sources/Pulse Generator','mymodel/Pulse1');
set_param('mymodel/Pulse1','position',[140,200,180,240]);
add_block('simulink/Ports & Subsystems/Subsystem','mymodel/Subsystem1');
set_param('mymodel/Subsystem1','position',[315,120,395,200]);
add_block('simulink/Sinks/Scope','mymodel/Scope1');
set_param('mymodel/Scope1','position',[535,140,575,180]);

1-3
1 Simulink Basics

Inside Subsystem1, delete the default connection between In1 and Out1. Also, add a second input
port by copying and renaming In1 from the block library.
delete_line('mymodel/Subsystem1','In1/1','Out1/1');
add_block('simulink/Sources/In1','mymodel/Subsystem1/In2');

Reposition the internal input and output port blocks inside Subsystem1.
set_param('mymodel/Subsystem1/In1','position',[50,50,90,70]);
set_param('mymodel/Subsystem1/In2','position',[50,130,90,150]);
set_param('mymodel/Subsystem1/Out1','position',[500,80,540,100]);

Insert and position an Add block inside Subsystem1.


add_block('simulink/Math Operations/Add','mymodel/Subsystem1/Add1');
set_param('mymodel/Subsystem1/Add1','position',[250,80,290,120]);

Next, add lines to connect all the blocks in the model. Start by connecting the Sine1 and Pulse1
blocks using routed lines.

Find the (x,y) coordinates of the Sine1 output port.

Sine1_Port = get_param('mymodel/Sine1','PortConnectivity')
Sine1_Port =

struct with fields:

Type: '1'
Position: [185 100]
SrcBlock: []
SrcPort: []
DstBlock: [1×0 double]
DstPort: [1×0 double]

get_param shows that the port Position is [185 100].

Find the (x,y) coordinates of the Pulse1 output port.

Pulse1_Port = get_param('mymodel/Pulse1','PortConnectivity')
Pulse1_Port =

struct with fields:

Type: '1'
Position: [185 220]
SrcBlock: []
SrcPort: []
DstBlock: [1×0 double]
DstPort: [1×0 double]

get_param shows that the port position is [185 220].

Connect the output of Sine1 to the first input of Subsystem1 using three segments of routed line.
add_line('mymodel', [185 100; 275 100]);
add_line('mymodel', [275 100; 275 140]);
add_line('mymodel', [275 140; 310 140]);

1-4
Programmatic Modeling Basics

Connect the output of Pulse1 to the second input of Subsystem1 using three segments of routed
line.

add_line('mymodel', [185 220; 275 220]);


add_line('mymodel', [275 220; 275 180]);
add_line('mymodel', [275 180; 310 180]);

Use get_param to get the port handles of the blocks being connected. Then use the block port
handles to connect the output of Subsystem1 to the input of Scope1.

SubsysPortHandles = get_param('mymodel/Subsystem1','PortHandles');
ScopePortHandles = get_param('mymodel/Scope1','PortHandles');
add_line('mymodel',SubsysPortHandles.Outport(1),...
ScopePortHandles.Inport(1));

Use port names and IDs to connect the Add1 block inside Subsystem1 to the subsystem inputs and
outputs. Simulink uses the most direct path to connect the ports.

add_line('mymodel/Subsystem1','In1/1','Add1/1');
add_line('mymodel/Subsystem1','In2/1','Add1/2');
add_line('mymodel/Subsystem1','Add1/1','Out1/1');

Programmatically Comment Out or Comment Through Blocks


To view or change the commented state of a block programmatically, use the get_param and
set_param commands.

• To view the commented state of a block:

get_param(gcb,'commented');
• To comment out a block:

set_param(gcb,'commented','on');
• To comment through a block:

set_param(gcb,'commented','through');
• To uncomment a block:

set_param(gcb,'commented','off');

Name a Signal Programmatically


1 Select the block that is the source for the signal line.
2 Use get_param to assign the port handle of the currently selected block to the variable p. Use
get_param to assign the handle of the line connected to that port to the variable l. Then set the
name of the signal line to 's9'.

p = get_param(gcb,'PortHandles')
l = get_param(p.Outport,'Line')
set_param(l,'Name','s9')

1-5
1 Simulink Basics

Arrange Model Layouts Automatically


You can use the Simulink.BlockDiagram.arrangeSystem command to lay out your model. This
command aligns input blocks on the left, output blocks on the right, and model elements in columns
between the inputs and outputs. The command affects only one layer at a time.

You can use the Simulink.BlockDiagram.routeLine command to route existing lines of your
model. Routing existing lines improves line route quality and avoids overlaps of a line with other lines
and obstacles in the model.

While you can use these commands with any open model, they are particularly useful with models you
build programmatically. For an example, see “Arrange Programmatically Populated Model”.

Open the Same Model in Multiple Windows


When you open a model, the model appears in a Simulink Editor window. For example, if you have
one model open and then you open a second model, the second model appears in a second window.

To open the same model in two Simulink Editor windows, at the MATLAB command prompt, enter the
open_system command and use the window argument. For example, if you have a model called
modelName open, to open another instance of modelName, enter:

open_system('modelName','window')

Use Model Finder to Index and Search Models and Improve Their
Discoverability
You can use the modelfinder function to search examples, models, and projects in multiple
databases. By default, modelfinder searches the MathWorks® Examples database. You can also
configure your databases with Model Finder. For more information on Model Finder, see “Configure
and Search Databases” on page 1-112.

Locate Diagram Elements Using Highlighting


To highlight a block, line, port, or annotation in an open model, use hilite_system.

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
model colors.

Parameter Determines
ScreenColor Model background
BackgroundColor Block and annotation background
ForegroundColor Block and annotation foreground

Set the color parameter to either a named color or an RGB value.

1-6
Programmatic Modeling Basics

• Named color: 'automatic', 'black', 'white', 'red', 'green', 'blue', 'cyan',


'magenta', 'yellow', 'gray', 'lightBlue', 'orange', 'darkGreen'
• RGB 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]')

See Also
load_system | open_system | new_system | save_system | add_line | delete_line |
add_block | delete_block | set_param | get_param | gcb |
Simulink.BlockDiagram.routeLine | hilite_system

More About
• “Common Block Properties”
• “Customize Model Colors” on page 1-67

1-7
1 Simulink Basics

Keyboard Shortcuts and Mouse Actions for Simulink Modeling

You can use keyboard shortcuts and mouse actions to model systems in Simulink. To open this page

from a model, press Shift+? or click Keyboard Shortcuts on the navigation bar.

Note When you use the keyboard shortcuts on macOS:

• Press command (⌘) instead of Ctrl.


• Press option instead of Alt.

View Keyboard Shortcuts in Editor


When you are in any of these modes, you can view a hints panel that displays keyboard shortcuts
specific to the active mode.

Mode Definition How to Enter Mode How to View Hints Panel


Keyboard Use the arrow keys to Select a block in your model. The hints panel appears when
Selection select a different block. Press M to switch from you enter selection mode.
movement mode (the default)
to selection mode.
Movemen Move a block by Drag a block with the pointer. The hints panel appears when
t dragging it with the you enter movement mode.
pointer.
Keyboard Use the arrow keys to When you open Simulink, you The hints panel appears when
Movemen move the selected block. are in movement mode by you use the arrow keys to move
t default. a selected block.

To switch from selection mode


to movement mode, press M.
Signal Trace the signal line to Click a signal in your model. The hints panel appears when
tracing the signal source or Pause on the ellipsis that you enter signal tracing mode.
destination. See appears. In the action bar that
“Highlight Signal expands, click either
Sources and Highlight Signal to Source
Destinations” on page
81-29 for details. or Highlight Signal to

Destination .

1-8
Keyboard Shortcuts and Mouse Actions for Simulink Modeling

Mode Definition How to Enter Mode How to View Hints Panel


Pan and Pan to move the view When you open Simulink, you Press the space bar until the
zoom over the model. Zoom to are in pan and zoom mode by hints panel expands. If the
change how close the default. hints panel is minimized, press
model appears. the space bar until the ? button

appears.

To hide the hints panel, click


the canvas.
Resize Change the size of a Pause on a block resize handle. The hints panel appears when
block. you enter resize mode.

To minimize the hints panel, press ? on your keyboard. When the hints panel is minimized, only the ?

button is visible.

To restore the hints panel, press ? on your keyboard.

Minimizing or restoring a hints panel in one mode does not affect the hints panels of other modes.
Expanded hints panels remain expanded and minimized hints panels remain minimized across
MATLAB sessions.

For example, to see the Keyboard Selection hints panel for selection mode:

1 Select a block in your model.


2 Press M. The minimized hints panel appears in the lower right of the model window.
3 To restore the hints panel, press ? on your keyboard.

1-9
1 Simulink Basics

Perform File and Clipboard Actions


Task Shortcuts
Open model Ctrl+O
Create model Ctrl+N
Print model Ctrl+P
Save all modified models in current model Ctrl+S
hierarchy
Save current referenced model Ctrl+Shift+S
Close model Ctrl+W
Cut Ctrl+X
Copy Ctrl+C
Paste Ctrl+V
Undo Ctrl+Z
Redo Ctrl+Y, Ctrl+Shift+Z (Simulink Online™)
Find search string Ctrl+F

1-10
Keyboard Shortcuts and Mouse Actions for Simulink Modeling

Zoom and Pan


Task Shortcuts and Actions
Fit diagram to window Space bar
Fit selection to window Space bar + F
Zoom in Ctrl+Plus (+) or space bar + Plus (+)
Zoom out Ctrl+Minus (-) or space bar + Minus (-)
Zoom to 100% Ctrl+0, Alt+1, or space bar + 0
Zoom with scroll wheel Scroll wheel

Ctrl + scroll wheel when Scroll wheel controls


zooming is cleared
Zoom in on model element
Drag the Zoom button from the palette to the
element.
View portion of block diagram visible in model Zoom or pan to part of the model.
window relative to full block diagram with
miniature map When only part of the model is visible, press the
space bar until the miniature map appears.
View different portion of model Click the destination in the miniature map.
Pan Drag the highlighted area in the miniature map.

Drag with middle button.

Space bar + drag.

When a scroll bar is shown, to move the scroll bar


with your keyboard, press Space bar + left, right,
up, or down arrow.
Pan vertically Ctrl + scroll wheel
Pan horizontally Shift + scroll wheel
Pan by page Shift + space bar + left, right, up, or down arrow

Navigate Model
Task Shortcuts and Actions
Open model Double-click.

Enter
Change tabs Ctrl+Shift+Tab
Enter selected subsystem, referenced model, or Enter
Stateflow® chart
Go to parent of selected subsystem, referenced Esc
model, or Stateflow chart

1-11
1 Simulink Basics

Task Shortcuts and Actions


Go to last viewed component in model hierarchy Ctrl+[
navigation history
Go to next viewed component in model hierarchy Ctrl+]
navigation history
Look under block mask Ctrl+U
For linked blocks, go to library of parent block Ctrl+L
Open the Model Explorer Ctrl+H

Select and Move Model Elements


Selected elements have a solid blue outline. The most recently selected element has blue corner
brackets in addition to the outline. To represent the cursor when you use the keyboard for selection, a
blue box with dashed lines surrounds the element.

By default, the model is in movement mode. To switch to selection mode, press M.

Task Shortcuts and Actions


Toggle between movement and selection mode M
Select all blocks, lines, and annotations Ctrl+A
Clear selection Ctrl+Alt+A
Select one or more model elements Draw a selection box around the model elements
you want to select. Start the selection box on an
empty spot on the canvas.
Move any model element, including signal labels Drag element.
Move selected elements Drag one of the selected elements.

Drag selection box.

After selecting elements with the keyboard, in


selection mode, press the left, right, up, or down
arrow.
By default, when you move or resize a block with Hold the space bar while you move or resize a
three or more ports, the shape of signal lines block.
connecting to blocks with one or two ports does
not change. Instead, the connected blocks move. When you release the space bar, the functionality
turns back on.
Turn the functionality off.
Change selection to closest similar element in a In selection mode, press the left, right, up, or
direction down arrow.

1-12
Keyboard Shortcuts and Mouse Actions for Simulink Modeling

Task Shortcuts and Actions


Move cursor to closest element in a direction, In selection mode, press Ctrl+Shift + left, right,
regardless of similarity up, or down arrow.
Change selection to element at top-left of canvas Ctrl+Home

On macOS, press home.


Change selection to element at bottom-right of Ctrl+End
canvas
On macOS, press end.
Change selection to leftmost element relative to Home
cursor
On macOS, press control+left.
Change selection to rightmost element relative to End
cursor
On macOS, press control+right.
Select additional adjacent elements To select additional adjacent elements with the
keyboard, in selection mode, press Shift + left,
right, up, or down arrow.

To select additional adjacent elements with the


pointer, press Shift while dragging a selection
box around the additional elements.
Select additional elements that are not adjacent To select additional elements with the keyboard,
in selection mode, press Ctrl + left, right, up, or
down arrow and navigate to the element you
want to select. Then, add the element to the
selection by pressing Ctrl + space bar.

On macOS, to add the current element to the


selection, press command+shift + space bar or
shift + space bar.

To select additional elements with the pointer,


press Shift and click.
Constrain movement of model elements to Start dragging the element, then press Shift.
vertical and horizontal directions

Add and Edit Model Elements


Task Shortcuts and Actions
Open or hide the Property Inspector Ctrl+Shift+I

On macOS, press command+option+O.

Before R2023b, on macOS, press command


+shift+I.
Set main parameter for selected block Alt+Enter

1-13
1 Simulink Basics

Task Shortcuts and Actions


Add block to model at current location with the Double-click the Simulink Editor canvas and start
quick insert menu typing the block name, then select the block from
the menu.

Ctrl+Period (.) twice and start typing the block


name, then press the down arrow to select the
block from the list and press Enter to insert the
block.

On AZERTY keyboards, press Ctrl+Shift+Period


(.) instead of Ctrl+Period (.).
Choose block to connect to signal line Move your pointer over the unconnected end of a
signal line. When your pointer is over the end of
the signal line, it becomes a circle. Double-click
the end of the signal line. Using the quick insert
menu that appears, add a block. The new block is
connected to the end of the signal line that you
double-clicked.

For information about how to use the quick insert


menu, see “Add Blocks to Models Using Quick
Insert Menu” on page 1-32.
Open the Library Browser Ctrl+Shift+L
Add annotation to model at current location with Double-click the Simulink Editor canvas and type
the quick insert menu the annotation content, then select the annotation
option.

Ctrl+Period (.) twice and type the annotation


content, then press the down arrow to select the
annotation option and press Enter to insert the
annotation.

On AZERTY keyboards, press Ctrl+Shift+Period


(.) instead of Ctrl+Period (.).
Copy selected model elements Drag elements with the right mouse button.

Ctrl + drag.
Copy selected model elements between Simulink Drag elements between windows.
Editor windows
Delete selected model elements Delete or Backspace

1-14
Keyboard Shortcuts and Mouse Actions for Simulink Modeling

Connect Model Elements


Task Shortcuts and Actions
Connect blocks with signal lines Click a port. Click the blue chevron symbol
that appears near a compatible port you want to
connect to.

Select the first block, then Ctrl + click a second


block.

Drag from port to port.

Click a port and press Shift as you connect to the


next port. Press Shift to make multiple,
consecutive connections.
Branch signal line Click a port, move the cursor near the line you
want to branch, and then click after you see the
preview.

Select a line, move the cursor toward the element


you want to connect with, and then click the blue
chevron symbol that appears near the port.

Ctrl + drag line.

Right mouse button + drag.


Add ports to blocks that take multiple inputs Drag toward the port from a compatible block or
signal line.

Drag from the edge of the block that you want to


add the port to.

Click the edge of the port, and then drag.

Click the edge of the port, move the cursor over


the signal type — signal, bus, or connector —
from the menu, and drag.
Disconnect selected blocks Press Shift, then drag block.

After selecting blocks with the keyboard, press M


then Shift + left, right, up, or down arrow.
Comment through selected blocks Ctrl+Shift+Y
Comment out or uncomment selected blocks Ctrl+Shift+X

1-15
1 Simulink Basics

Name Model Elements


Task Shortcuts and Actions
Rename selected model element Click or double-click the label.

Select the element and press F2.

On macOS, press command+return instead of


F2.
Name signal line Double-click the signal and type its name.
Display name on branch of a named signal line Double-click the branch.
Name every branch of a signal line Right-click the signal, select Properties, and use
the Signal Properties dialog box.
Delete signal label and name Delete characters in the label, or delete the name
in Signal Properties dialog box.
Delete signal label only Right-click the label and select Delete Label.
Copy signal label Ctrl + drag the signal label.
Edit port labels on subsystem blocks Point to the port label and click the interactive
cue (blue box surrounding the label).

Select the port. Click the port label cue or press


F2.

To switch between block name and signal name


when editing labels on signal ports, press Ctrl
+1,2.

To make successive port label edits on a


subsystem block:

• Select a port on the block, edit the label, and


press Enter. This action enables keyboard
selection of ports.
• Use up or down arrow keys to select adjacent
ports and press F2 for quick editing.

Format Block Diagram


Task Shortcuts and Actions
Automatically arrange model Ctrl+Shift+A
Resize block, maintaining ratio of width and Shift + drag handle
height
Resize block about the center Ctrl + drag handle
Route lines around blocks Shift + drag while drawing
Rotate blocks clockwise Ctrl+R
Rotate blocks counterclockwise Ctrl+Shift+R

1-16
Keyboard Shortcuts and Mouse Actions for Simulink Modeling

Task Shortcuts and Actions


Flip blocks Ctrl+I
Create subsystem from selection Ctrl+G
Create subsystem or area from empty selection To create the highlighted option, which you can
change by using the arrow keys or mouse:

• Click inside the selection box.


• Press Enter.

Press the number key associated with an option.


Change signal label font Select the signal line (not the label), then on the
Format tab, click the Font Properties button
arrow, then click Fonts for Model.
Mask block Ctrl+M
Refresh Model blocks Ctrl+K

Perform Generic Actions


Task Shortcuts and Actions
Perform generic action with the quick action Double-click the Simulink Editor canvas, select
search menu the Actions tab, and start typing the action name
or description, then select the action from the
list.

Ctrl+Period (.) and start typing the action name


or description, then press the down arrow to
select the action and press Enter to perform it.

On AZERTY keyboards, press Ctrl+Shift+Period


(.) instead of Ctrl+Period (.).
Perform context-sensitive action Before opening the quick action search menu,
select a model element.

Simulate, Update, and Generate Code for Models


Task Shortcuts
Start simulation Ctrl+T or F5
Stop simulation Ctrl+Shift+T
Update model Ctrl+D
Open Configuration Parameters dialog box Ctrl+E
Build model (for code generation) Ctrl+B

Debug Simulations
The keyboard shortcuts in the table are the same in the Simulink Editor, the Stateflow Editor, and the
MATLAB Function Block Editor.

1-17
1 Simulink Basics

Task Shortcuts
Step over F10

On macOS, press shift+command+O.


Step in F11

On macOS, press shift+command+I.


Step out Shift+F11

On macOS, press shift+command+U.

See Also

Related Examples
• “Library Browser Keyboard Shortcuts”

1-18
Open Models

Open Models
You can open a blank Simulink model from the MATLAB Editor or from the Simulink Editor.

You can open a saved Simulink model, template, or library. You can open the saved file from your file
browser, from the MATLAB Editor, from the Simulink Editor, or from the Library Browser in
standalone mode.

Tip If you want to open the model using a file browser and the file browser does not display the
model, try changing the file type to All Files.

To open a referenced model from a Model block, double-click the Model block. For more information,
see “Navigate Model Hierarchy” on page 4-34.

Open Simulink
To open Simulink, on the MATLAB Toolstrip, click Simulink.

To open Simulink programmatically, enter this command in the MATLAB Command Window:

simulink

Open Blank Models


When no Simulink models are open, you can open a blank model from the MATLAB Editor:

1 Open Simulink.
2 On the Simulink Start Page, in the Simulink menu, click Blank Model.

When there is already an open Simulink model, you can open a blank model from the Simulink Editor
by taking one of these actions:

• In the Simulink Toolstrip, click New.


• Select the open model window and press Ctrl+N.

Open Saved Models


Opening a saved model loads the model into memory and displays it in the Simulink Editor.

Note

1-19
1 Simulink Basics

• To open a model created in a later version of Simulink in a previous version, first export the model
to the previous version. See “Export Model to Previous Version of Simulink” on page 1-30.
• .slxp and .mdlp extensions denote protected models that you cannot open or edit. See
“Reference Protected Models from Third Parties” on page 8-18.

When MATLAB is not open, you can open a saved model from your operating file system browser.

When MATLAB is open but no Simulink models are open, you can open a saved model by taking one
of these actions:


In the MATLAB Editor, click Browse for folder . In the file browser that appears, navigate to
the folder that contains the model and click Select Folder. Then, in the Current Folder Browser,
double-click the model name.
• Open Simulink. On the Simulink Start Page, in the side bar on the left, select a recent model or
project from the list, or click Open.

When there is already an open Simulink model, you can open a saved model from the Simulink Editor:

1 In the Simulink Toolstrip, on the Simulation tab, click Open.


2 Click Recent Files to open recent files or Open to search for a model.

When the Simulink Library Browser is open in standalone mode, you can open a saved model from

the Library Browser window by clicking Open .

To open a saved model programmatically, in the MATLAB Command Window, enter the name of the
model without a file extension, for example, modelName. The model must be in the current folder or
on the MATLAB search path.

Load Model Variables and Data from MAT-File


If the data for your model is stored in a MAT-file, to load the data into your MATLAB workspace, first
change directory to the file location:


In the MATLAB Editor, click Browse for folder .
• In the file browser that appears, navigate to the folder that contains the MAT-file and click Select
Folder.

Then enter this command, where modelName is the name of the MAT-file:

load(modelName);

For more information on how to load variables from a file into the workspace, see load.

Automatically Initialize Variables and Load Data


If you define parameters in your model using variables, you must initialize those variables before the
model can run. For example, suppose that you have a model that contains a Gain block. You can

1-20
Open Models

specify the variable K as the gain rather than setting the value on the block. When you use this
approach, you must initialize the variable K before you can run the model.

Also, if your model imports data from the workspace, for example using a From Workspace block, you
must load the data into the workspace before you can run the model.

You can use model callbacks to automatically initialize variables and load data. A callback is code that
runs at a specified action point, for example after you load or save a model. You can use the callback
code to initialize the variables and load the data for your Simulink model at a specified action point.
You can specify the action point by choosing the corresponding type of callback.

For example, suppose you have a model that contains:

• A Gain block with the gain value specified as the variable K.


• A From Workspace block that is supposed to import data from the file modelData.mat.

If you want K to automatically initialize to a value of 5 and the data from data.mat to automatically
load every time your Simulink model finishes loading:

1 If the Property Inspector is already open and is minimized, restore it by clicking Property
Inspector at the right edge of the model window.

If the Property Inspector is not open, in the Simulink Toolstrip, on the Modeling tab, in the
Design section, click Property Inspector.
2 On the Properties tab, in the Callbacks section, select PostLoadFcn. A PostLoadFcn function
is a callback that runs after your model loads.
3 In the text box, enter this code.

K=5;
load(modelData);

Tip Alternatively, you can save the code as a MATLAB script and then enter the name of the
script in the text box.
4 Save the model.

1-21
1 Simulink Basics

Now, every time you load the model, when the model finishes loading, the variable K automatically
initializes and data.mat automatically loads.

To learn more about callbacks, see “Customize Model Behavior with Callbacks” on page 4-68. To
define a callback for loading variables programmatically, see “Programmatically Load Variables When
Opening a Model” on page 1-3.

Set Default Template for New Models

You can specify a model template to use as the default template. A new model is created using the
default template when you:

• In the Simulink Toolstrip, click New.


• Press Ctrl+N.
• Use the new_system function.

You can create a new template to use as the default template. To create the new template:

1-22
Open Models

1 Create a model with the configuration settings and blocks you want.
2 Export the model to a template. See “Create Template from Model” on page 4-2.

To set the default template:

1 To open the Simulink Start Page, in the MATLAB Toolstrip, click Simulink.
2 On the Start Page, click the title of a template to expand the description.
3 Click the down arrow next to Create Model and select Set As Default.

The default template has a check mark on the Simulink Start Page.

When you click the arrow under New in the Simulink Toolstrip, the default template appears at the
top of the list.

You can also make the new template the default template programmatically using the
Simulink.defaultModelTemplate.

Set Favorite Files


To easily find your favorite models and projects on the Simulink Start Page, add them to the
Favorites list on the left tab of the Start Page.

To add a model or project to the Favorites list, in the Recent list, click the star next to the name of
your favorite models and projects.

1-23
1 Simulink Basics

Clear Recent Files


The Recent list on the Simulink Start Page is a list of the files you most recently opened.

To edit or clear the Recent list, right-click a recent file and click Remove from List or Clear List.

You can also clear the Simulink history programmatically using the Simulink.history.clear
function.

Open Model with Different Character Encoding


If you open a MDL file created in a release prior to R2021b in a MATLAB session that uses different
encoding, you receive a warning.

For example, suppose you create a MDL file in a MATLAB session configured for Shift_JIS and
open it in a session configured for windows-1252. The warning message displays the encoding of the
current session and the encoding used to create the model.

Starting in R2021b, MDL files can store characters from any encoding.

To open a MDL file created in a release prior to R2021b in a MATLAB session that uses different
encoding, in the environment with the encoding that the MDL file is configured for, resave the file in
the R2021b release or later, or resave the MDL file as an SLX file.

See Also
simulink | open_system | Simulink.defaultModelTemplate | Simulink.history.clear

See Also

Related Examples
• “Export Model to Previous Version of Simulink” on page 1-30
• “Reference Protected Models from Third Parties” on page 8-18
• “Customize Model Behavior with Callbacks” on page 4-68
• “Programmatically Load Variables When Opening a Model” on page 1-3

1-24
Open Models

• “Create Template from Model” on page 4-2

1-25
1 Simulink Basics

Save Models
You can save a model, template, or library. For information about how to create templates and
libraries, see “Create Template from Model” on page 4-2 and “Create Custom Library” on page 45-
2.

You can save Simulink models in the SLX format or the MDL format.

By default, Simulink saves new models and libraries in the SLX format with the file extension .slx.
The SLX format is a compressed package that conforms to the Open Packaging Conventions (OPC)
interoperability standard. The SLX format 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 files. The file
size reduction varies depending on the model.

Saving models in the SLX format also enables incremental loading and saving. Simulink optimizes
performance and memory usage by loading only required parts of the model and saving only modified
parts of the model.

You can specify the file format for saving new models and libraries with the Simulink preference “File
format for new models and libraries”.

In addition to the model itself, you can also store and save data that your model needs to run. While
the model is open, you can use variables to store data in the model workspace and the base
workspace. For more information about the difference between these workspaces, see “Model
Workspaces” on page 73-138. When you close the model, the data is deleted unless you save it.

You can save the data as a MAT-File, or using a data dictionary. A data dictionary is a persistent
repository of data that are relevant to your model. For more information about data dictionaries, see
“What Is a Data Dictionary?” on page 80-2

Determine Whether a Model Has Unsaved Changes


If a model has unsaved changes, an asterisk (also known as the dirty flag) appears next to the model
name in the title bar of the Simulink Editor.

To determine programmatically whether a model has unsaved changes, query the value of the model
parameter Dirty with the get_param function. For example, this command saves the current
system (gcs) if the system is dirty.
if strcmp(get_param(gcs,'Dirty'),'on')
save_system;
end

1-26
Save Models

Save Models
To save a model for the first time, in the Simulink Editor, on the Simulation tab, click Save. For file
naming requirements, see “Choose Valid Model File Names” on page 1-27.

To resave a previously saved model, do one of the following:

• To save the model using the current file name, in the Simulink Editor, on the Simulation tab, click
Save.
• To save the contents of the model to a new name or location, or to change the model format, in the
Simulink Editor, on the Simulation tab, select Save > Save As. For information about the SLX
format, see “Convert Model File Format to SLX” on page 1-29.
• To save the model in a format compatible with a previous Simulink version, on the Simulation
tab, select Save > Previous Version. For more information, see “Export Model to Previous
Version of Simulink” on page 1-30.
• To save the contents of a referenced model to a new name, location, or format, open the file of the
referenced model. Then, on the Simulation tab, select Save > Save As.

Choose Valid Model File Names


Model file names must start with a letter and can contain letters, numbers, and underscores. The
total number of characters in the model name must not be greater than the maximum value that your
system supports, which is usually 63 characters. To find the maximum file name length for your
system, use the namelengthmax function.

You can open a model even when the file does not have a valid name, for example, mymodel
(1).slx. Simulink opens the model and assigns a valid name. To rename or save changes to the
newly named model, click Save.

When you name your model, do not use:

• A language keyword (for example, if, for, or end)


• A reserved name (for example, simulink)
• A MATLAB built-in function (for example, plot)

For information about how MATLAB determines which function to call when multiple files in the
current scope have the same name, see “Function Precedence Order”.

Save Model Variables and Data


If your MATLAB workspace contains variables and data that your Simulink model needs to run, you
can save those contents and reuse them the next time you open the model.

If you want to save all the contents of your workspace, in the MATLAB Editor, in the MATLAB
Toolstrip, on the Home tab, in the Variable section, click Save Workspace. Save the data in a MAT-
file.

If you want to save a specific item in your workspace, in the MATLAB Editor, in the Workspace
Browser, right-click the item and select Save As. Save the item in a MAT-file.

The next time you open the model, before you run the simulation, load the MAT-file into the
workspace. See “Load Model Variables and Data from MAT-File” on page 1-20.

1-27
1 Simulink Basics

Specify Code That Runs Before or After Saving Model


A callback is code that runs at a specified action point,such as right before or after you save a model.

You can specify the action point by choosing the corresponding type of callback.

• A PreSaveFcn function runs right before you save a model.


• A PostSaveFcn function runs right after you save a model.

For example, if you want to automatically clear the values of all workspace variables right after you
save a model:

1 If the Property Inspector is already open and is minimized, restore it by clicking Property
Inspector at the right edge of the model window.

If the Property Inspector is not open, in the Simulink Toolstrip, on the Modeling tab, in the
Design section, click Property Inspector.
2 On the Properties tab, in the Callbacks section, select PostSaveFcn.
3 In the text box, enter this code.

clearvars;

Tip Alternatively, you can save the code as a MATLAB script and then enter the name of the
script in the text box.
4 Save the model.

1-28
Save Models

Now, every time you save the model, when the model finishes saving, the workspace is cleared.

To learn more about callbacks, see “Customize Model Behavior with Callbacks” on page 4-68. To
define a callback for loading variables programmatically, see “Programmatically Load Variables When
Opening a Model” on page 1-3.

Convert Model File Format to SLX


To convert an existing MDL file to the SLX file format:

1 On the Simulation tab, select Save > Save As.


2 Leave the default Save as type as SLX and click Save.

When you convert a MDL file to the SLX file format, the file contains the same information as the
MDL file.

Functions that works with MDL files, such as get_param and set_param, also work with the SLX
file format.

1-29
1 Simulink Basics

When you convert a MDL file to the SLX file format without changing the model name or location, the
software creates a backup file by renaming the MDL file (if the file is writable) to
mymodel.mdl.releasename, for example, mymodel.mdl.R2010b.

Note You can also convert the MDL file to the SLX file format programmatically using the
save_system function.

save_system mymodel mymodel.slx

This command creates the file mymodel.slx. 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.

Caution If you use third-party source control tools, register the model file extension .slx as a
binary file format. Otherwise, the third-party tools might corrupt SLX files when you submit them.

This table describes operations with possible compatibility considerations when using SLX files.

Operations with Possible What Happens Action


Compatibility Considerations
when Using SLX
Hard-coded references to file Scripts cannot find or process Make your code work with both
names with the extension .mdl models saved with the new file the .mdl and .slx extension.
extension, .slx.
Use functions like which and
what instead of file names.
Third-party source control tools The binary format of SLX files Register the .slx and .mdl
that assume a text format by can cause third-party tools to extensions as binary file formats
default corrupt the files when you with third-party source control
submit them. tools. See “Register Model Files
with Source Control Tools” on
page 19-9.

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

Export Model to Previous Version of Simulink


You can export a model to a previous version of Simulink. For example, you can share a model with
colleagues who only have access to a previous version of Simulink.

To export a model to a previous version of Simulink:

1 Ensure that all changes you made to the model are saved before proceeding. If a model has
unsaved changes, in the Simulink Editor, on the Simulation tab, click Save.
2 In the Simulink Editor, on the Simulation tab, select Save > Previous Version.

1-30
Save Models

3 In the Export to Previous Version dialog box, from the Save as type list, select the previous
version to which to export the model. The list supports seven years of previous releases.
4 Click Save.

When you export a model to a previous version, the model is saved in the previous version regardless
of whether the model contains blocks and features that were introduced after that version. If the
model contains blocks or uses features that were developed after the previous version, the model
might not give correct results when you run it in the previous version of Simulink.

Simulink converts blocks that were introduced in a previous version into yellow, empty, masked
Subsystem blocks.

Simulink also removes any unsupported functionality from the model. See save_system.

See Also
save_system

Related Examples
• “File format for new models and libraries”
• “Convert Model File Format to SLX” on page 1-29
• “Customize Model Behavior with Callbacks” on page 4-68
• “Register Model Files with Source Control Tools” on page 19-9
• “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-31
1 Simulink Basics

Add Blocks to Models


A basic model takes an input signal, operates on the signal, and visualizes or logs the output. You can
use blocks to generate or import an input signal, modify the signal, and plot the output signal or pass
it to a workspace.

If you are unsure of which blocks to add to create your model, see “Explore Available Blocks Using
Library Browser” on page 1-34.

Add Blocks to Models Using Quick Insert Menu

To add a block using the quick insert menu:

1 At the location where you want to add the block, double-click the Simulink canvas.
2 Enter the name of the block that you want to add, or search for it by entering keywords.
3 In the list of search results, select the block you want to add using the arrow keys, then press
Enter.

Note There can be multiple blocks with the same name that belong to different libraries. In each
search result, the library appears below the block name. Check the library to make sure you
choose the block you want to add.

To add a block to the unconnected end of a signal line:

1 Move your pointer over the end of the signal line. When your pointer is over the end of the signal
line, it becomes a circle.

1-32
Add Blocks to Models

2 Double-click the end of the signal line.


3 Using the quick insert menu that appears, add the block. The new block is connected to the end
of the signal line that you double-clicked.

Add Blocks to Models Using Library Browser


To add a block using the Library Browser:

1 To open the Library Browser, in the Simulink Toolstrip, on the Simulation tab, in the Library
section, click Library Browser.
2 You can either do a keyword search for the block that you want to add or look for the block by
navigating the Library Browser tree.

To do a keyword search, in the Library Browser, in the search box, enter a keyword or key
phrase, then press Enter. The search results appear in the Search Results tab. For more
information, see “Search for Library Items by Keyword”.

Tip To return to the Library Browser tree after a keyword search, click the Library tab.
3 When you have found the block that you want to add, click and drag it from the Library tab or
the Search Results tab to the Simulink canvas.

Tip To add the block to the model, you can also do one of these actions:

• Right-click the block in the Library Browser and select Add block to model.
• Select the block and press Ctrl+I.

For more information about the Library Browser, see Library Browser.

1-33
1 Simulink Basics

Explore Available Blocks Using Library Browser


If you are unsure of which block you want to add, you can explore the available blocks using the
Library Browser.

To open the Library Browser, in the Simulink Toolstrip, on the Simulation tab, in the Library
section, click Library Browser.

To explore the available blocks, expand the libraries in the tree. If you are looking for a block that:

• Generates an input signal, try expanding the Simulink Library and then the Sources sublibrary.

You can use a From Workspace block to import data from the workspace. You can use a From File
block to import data from a file.
• Operates on one or more signals, try expanding the Simulink Library, and then the Commonly
Used Blocks or the Math Operations sublibrary.

For example, if you want to add two signals together, you can use the Add block from the Math
Operations sublibrary.
• Outputs the simulation results, try expanding the Simulink Library, and then the Sinks sublibrary.

You can use a Scope block to plot the simulation results. You can use a To Workspace block to pass
simulation results to the workspace. You can use a To File block to save simulation results to a file.

For more information about the Library Browser, see Library Browser.

1-34
Add Blocks to Models

See Also
Library Browser | Library Browser in Standalone Mode

Related Examples
• “Create a Simple Model”
• “Programmatically Add and Connect Blocks” on page 1-3

1-35
1 Simulink Basics

Connect Blocks
Establish relationships between the blocks in your model by connecting them.

You can connect most blocks using signal lines.

Signal lines connect to ports on blocks. During simulation, signals travel from output ports to
connected input ports.

• You can send the signal from the output port of one block to the input ports of multiple blocks by
branching the signal line.
• For some blocks you can change the number of input ports on the block. For example, to plot
multiple signals on the same graph, you can increase the number of input ports on the Scope
block.

For information about changing signal line layout, see “Configure Model Layout” on page 1-56.

You can simplify your block diagrams by bundling signals. For information about bundling signals, see
“Group Signals or Messages into Virtual Buses” on page 82-14.

Related blocks connect without signal lines. For information about how to connect related blocks, see
“Connect Blocks Without Signal Lines” on page 1-43.

Connect Blocks with Signal Lines


To connect two blocks with a signal line, click and drag the port symbol at the output port of one
block to the input port of the other block.

You can use these shortcuts to connect blocks:

• To connect the blocks without dragging the signal line:

1 Vertically line up the output port and input port you want to connect with no other
components between them. If the ports are already lined up, move one of the blocks to break
the alignment, then line them up again. When you release the block that you moved to align
the ports, a preview of the connection appears.

2 To make the connection, click the preview.

1-36
Connect Blocks

• To connect the blocks without dragging the signal line or lining up the ports:

1 Click the port symbol of the output port you want to connect. The port hint symbol appears
on the input ports of other components that you can connect to.

2 To see a preview of the connection, pause on the port hint symbol of the input port that you
want to connect to.

3 To make the connection, click the preview.

To connect multiple blocks to a single block without dragging the signal line or lining up the ports:

1 Left-click and drag a selection box around the blocks whose output ports you want to connect.

1-37
1 Simulink Basics

2 Press Ctrl and right-click the block whose input ports you want to connect.

• To connect both the input port and output port of a block to an existing signal line, click and drag
the block onto the signal line. Position the block such that the port symbols are on the signal
line. When the output port symbol disappears and the input port symbol turns into a solid
arrowhead, release your pointer.

To make a signal line segment diagonal, press Shift and drag a vertex that connects to another signal
line segment.

Connect Single Output Port to Multiple Input Ports


To connect an output port to multiple input ports, connect one input port to the output port, then
branch the signal line to connect to the other input ports.

To branch the signal line, press Ctrl, then click and drag the existing signal line to the input port of
the block to which you want to connect.

1-38
Connect Blocks

Tip To branch the line, you can also click and drag the port symbol of the unconnected input port
onto the existing signal line.

Connect Output Ports of Multiple Blocks to Single Block


Some blocks can connect multiple signal lines on their input port side. For example, to plot multiple
signals on one graph, you can connect the output ports of multiple blocks to a single Scope block.

To connect the output ports of multiple blocks to a single block, from each output port you want to
connect, drag a signal line over the input port side (left edge) of the single block. When the block icon
turns blue and the port number appears, release your pointer. An input port is created automatically
to connect the signal line.

1-39
1 Simulink Basics

If the blocks whose output ports you want to connect are not in the model yet, to increase the number
of input ports on the single block:

1 Pause on the input port side (the left edge) of the block until a plus sign appears next to the
pointer.

2 Then, click and drag your pointer away from the block. A dashed signal line appears that you can
connect to the output port of another block.

To delete an input port, click its port symbol and press Delete.

To specify the number of input ports a block has, use the Block Parameters dialog box or the
Parameters tab of the Property Inspector.

1-40
Connect Blocks

Tip For some blocks, you can enter the number of input ports when you add the block to the model.

Connect Subsystems
To send signals into a subsystem, the subsystem must contain as many input ports as signals that you
want to send into the subsystem.

To receive signals from a subsystem, the subsystem must contain as many output ports as signals that
you want to receive from the subsystem.

When you add a blank subsystem to the model, the subsystem contains an input port and an output
port by default.

To connect a subsystem:

1 To enter the subsystem, double-click the Subsystem block.

1-41
1 Simulink Basics

2 Inside the subsystem, add the required number of input ports and output ports.

3 Inside the subsystem, connect the input ports and output ports to the subsystem.

4 To navigate up a level in the model hierarchy, in the Explorer Bar at the top of the Simulink
canvas, click the name of the level to the left of the name of the Subsystem block.

5 Connect the signal lines of the signals that you want to send into the subsystem to the input ports
of the Subsystem block.

1-42
Connect Blocks

Each input port on the Subsystem block corresponds to an Inport block inside the subsystem. You
can tell which input port on the Subsystem block corresponds to which Inport block inside the
subsystem by the port number.
6 Connect the signal lines of the signals that you want to receive from the subsystem to the output
ports of the Subsystem block.

Each output port on the Subsystem block corresponds to an Outport block inside the subsystem.

Tip To avoid manually connecting subsystems, build the contents of the subsystem in the level of the
model hierarchy where you want to add the Subsystem block. Then, convert the contents into a
subsystem:
1 Select the subsystem components by clicking and dragging your pointer across the canvas to
draw a rectangle that encompasses the components.
2 Pause on the ellipsis that appears.
3 In the action bar that expands, click Create Subsystem.

The conversion to a subsystem automatically adds and connects the subsystem input ports and output
ports.

Connect Blocks Without Signal Lines


Related blocks connect to each other without signal lines.

For example, the Goto and From blocks are related blocks that you can use to send a signal without a
signal line. The signal that enters the Goto block exits the From block without passing through a
signal line.

To connect related blocks, use the Block Parameters dialog box or the Parameters tab of the
Property Inspector.

Tip To check whether two or more related blocks are connected, select one. All related blocks that
connect to the selected block highlight in purple.

1-43
1 Simulink Basics

Some related blocks connect using tags. For example, all Goto and From blocks with the same tag are
connected.

You can set the tag for these blocks in the Block Parameters dialog box or in the Property Inspector,
on the Parameters tab.

Blocks from the Dashboard and Customizable Blocks libraries are also related blocks. You can
connect display blocks from these libraries to signals. You can connect control blocks to block
parameters or variables. For information about how to connect dashboard blocks, see “Connect
Dashboard Blocks to Simulink Model” on page 32-7.

1-44
Connect Blocks

Convert Signal Lines to Goto and From Block Sets


You can simplify your model diagrams by replacing lengthy signal lines with Goto and From blocks.
However, when you want to trace a signal path, seeing the signal lines can be useful.

You can convert signal lines and virtual buses to Goto and From block sets, and you can convert Goto
and From block sets to signal lines. A Goto and From block set is a connected group of Goto and
From blocks that have the same tag.

To perform the conversion, the signal lines, buses, or Goto and From blocks you want to convert must
meet these conditions:

• The lines, buses, or blocks are fully connected.


• The lines, buses, or blocks are all in the same location in the model hierarchy, meaning on the
same level and inside the same component .
• If you want to convert lines or buses to blocks, the lines or buses are not connected to any Goto or
From blocks.

You can perform the conversion regardless of whether the block tags are visible.

To convert a Goto block and all From blocks to which it connects or a From block and the Goto block
to which it connects to a signal line, select the block. Pause on the ellipsis that appears above the
selected block. In the action menu that expands, select Convert to signal.

To convert a signal line or bus to a Goto and From block set, select the signal line or bus. Pause on
the ellipsis that appears. In the action menu that expands, select Convert to Goto and From
blocks.

Tip Alternatively, perform one of these actions.

• Select the block, and in the Simulink Toolstrip, on the Goto or From tab, click Convert to Signal.
• Select the signal line or bus, and in the toolstrip, on the Signal tab, click Convert to Goto/From.

To convert multiple Goto and From block sets to signal lines simultaneously, press Shift and select
the Goto blocks of all the sets you want to convert. In the Simulink Toolstrip, on the Signal tab, click
Convert to Signal.

If a Goto block has multiple From blocks with the same tag, to convert a subset of the From blocks to
signal lines, press Shift and select the From blocks you want to convert. In the toolstrip, on the
Signal tab, click Convert to Signal. The selected From blocks convert to signal lines connected to
the signal line coming out of the corresponding Goto block. The Goto block does not convert to a
signal line.

1-45
1 Simulink Basics

To convert multiple signal lines or buses to Goto and From block sets simultaneously, press Shift and
select the signal lines or buses. In the toolstrip, on the Signal tab, click Convert to Goto/From.

Comment Out and Comment Through Blocks


You can exclude blocks from simulation without physically removing the blocks from the model by
commenting out or commenting through the blocks.

• Comment Out: Excludes the selected block from simulation. The signals are terminated and
grounded.
• Comment Through: Excludes the selected block from simulation. The signals are passed
through. To comment through, a block must have the same number of input and output ports and
no control or connection ports.

Note These Simulink blocks do not support the Comment Out and Comment Through commands:

• Inport
• Outport
• Connection ports
• Argument Inport
• Argument Outport
• Data Store Memory
• Goto Tag Visibility

1-46
Connect Blocks

The Signal Generator block does not support the Comment Through command.

To comment out a block, select the block. In the action bar that appears, click Comment Out.

To comment through a block, right-click the block and select Comment Through.

Tip Alternatively, select the block and press:

• Ctrl+Shift+X to comment out


• Ctrl+Shift+Y to comment through

See Also

Related Examples
• “Create a Simple Model”
• “Programmatically Add and Connect Blocks” on page 1-3

1-47
1 Simulink Basics

Edit Block Parameters


Parameters specify how a block behaves in the model.

You can use the default parameter values or set your own values using the block icon, the Block
Parameters dialog box, or the Property Inspector. You can also set parameters programmatically and
specify block parameters as variables.

Edit Parameters on Block Icon


For blocks that display a parameter value on the block icon, you can edit the value directly on the
icon:

1 Select the block.


2 Click on the parameter value on the block icon.
3 Enter a new value.
4 Press Enter.

Note The block icon only displays the new value if the value fits on the icon.

You can also edit enumerated block parameter values on the block icon:

• For the block parameters that have a fixed set of values, you can select the value from a list on the
block icon using the cursor or arrow keys.

These blocks have this feature:

• Logical Operator
• Rounding Function
• MinMax
• Sqrt
• Relational Operator
• Math Function
• Complex to Real-Imag

For example, for the Rounding Function block, you can select the Function parameter from a list
of values:

1 Select the Rounding Function block.


2 Point to the block icon. The editable parameter value appears underlined.
3 Click the underlined text to edit the value. A list with Function parameter values appears.
4 Select a new value from the list using the cursor or the arrow keys.

1-48
Edit Block Parameters

• The Goto and From blocks are a special case. While they pair with each other as related blocks,
for the Goto block, you can only type a new Goto tag parameter value on the block icon. For the
From block, you can only select the Goto tag parameter value from a list on the block icon.

Note Typing a new value for the Goto block removes unmatched values from the list.

For example, consider a From block with the Goto Tag parameter value sensor_A and three Goto
blocks with the Goto Tag parameter values sensor_A, sensor_B, and sensor_C.

To change the Goto Tag parameter value of the highlighted Goto and From block pair to a new
value:
1 Select a Goto block, then click on the text on the block icon.
2 Type in a new name for the tag.

3 Press Enter.
4 Select the From block.
5 Click the text on the block icon. A list with Goto tag parameter values appears.

6 Select the new tag name that you assigned to the Goto block.

Alternatively, to connect the From block to one of the other two Goto blocks, expand the list on the
From block icon and select the tag of the Goto block to which you want to connect.

1-49
1 Simulink Basics

Edit Parameters Using the Property Inspector


To edit parameters that you cannot edit on the block icon, use the Property Inspector.

To edit a parameter using the Property Inspector:

1 Select the block.


2 Check if the Property Inspector is open.

If the Property Inspector window is not visible, check whether the right edge of the Simulink
window displays a Property Inspector tab.

• If a tab is displayed, the Property Inspector is open and minimized. To expand the Property
Inspector window, click the tab.
• If no tab is displayed, the Property Inspector is closed. To open the Property Inspector, in the
Simulink Toolstrip, on the Modeling tab, in the Design section, select Property Inspector.
3 In the Property Inspector, click the Parameters tab.
4 On the Parameters tab, find the name of the parameter whose value you want to edit.
5 Edit the parameter value in the corresponding text box.

Tip To hide the Property Inspector, click the canvas. If the Property Inspector does not hide when
you click the canvas, in the upper right-corner of the Property Inspector window, click the down
arrow and select Minimize.

To show the Property Inspector again, click the Property Inspector tab.

1-50
Edit Block Parameters

Edit Parameters Using the Block Parameters Dialog Box


To edit parameters that you cannot edit on the block icon, you can also use the Block Parameters
dialog box.

To edit a parameter using the Block Parameters dialog box:

1 Double-click the block. The Block Parameters dialog box appears.


2 In the Block Parameters dialog box, find the name of the parameter whose value you want to edit.
3 Edit the parameter value in the corresponding text box. When you edit a parameter value, the
text box turns yellow.
4 Click OK.

1-51
1 Simulink Basics

Edit Parameters Programmatically


To edit the value of a parameter programmatically, use the set_param function.

To obtain the value of a parameter programmatically, use the get_param function.

Specify Block Parameters as Variables


If you want to be able to edit the value of a parameter from the MATLAB Command Window, a script,
or the Workspace Browser, specify the value of the parameter as a variable or as an expression that
contains variables. When you change the value of the variable, the value of the parameter also
changes.

You can also use the set_param function to edit the value from the command window or a script.
However, specifying the parameter as a variable makes your code more compact. You also do not
need to update your code when model or block names change.

To specify the value of a parameter as a variable:

1 Initialize the variable in the MATLAB workspace (base, model, or mask) in which the parameter
value is specified.
2 Change the parameter value to the name of the variable or to the variable expression.

Tip When you set a block parameter value to a variable or function in the Block Parameters dialog
box or the Property Inspector, Simulink provides a list based on the text you type. Instead of
completely typing a variable name, you can type part of it and then select the full name from the list.

1-52
Edit Block Parameters

The list includes:

• Variables and objects from every workspace (base, model, and mask)
• Data dictionary
• Referenced dictionary visible to the block parameter

Autocomplete is available for variables, fields of structures and objects, and for functions on the
MATLAB path.

When you specify the value of a parameter as a variable or variable expression, the Block Parameters
dialog box and the Property Inspector display the value of the variable or the expression.

The text box where you enter the parameter value displays the variable or expression on the left and
the value on the right.

To see the value the variable or expression has during simulation, run the simulation and open the
Block Parameters dialog box or the Property Inspector. The displayed value is the value of the
variable or expression in the simulation at the time step when you open the Block Parameters dialog
box or the Property Inspector.

For more information, see “View Values of Parameters Set as Variables” on page 30-70.

Consider this example for how to specify the parameter values as variables:

A model contains a Constant block with a Constant value of 1 that connects to a Display block.

To specify the Constant value parameter value as the variable expression 2*x+8 with x initialized to
a value of 3:

1 To initialize x, enter this command in the MATLAB Command Window.

1-53
1 Simulink Basics

x=3;
2 To open the Block Parameters dialog box, in the Simulink model window, double-click the
Constant block.
3 In the Block Parameters dialog box, set the Constant value to 2*x+8. On the right side of the
text box, the value of the variable expression 2*x+8 is displayed.

4 In the Block Parameters dialog box, click OK.


5 Run the model. The Display block shows a value of 14.

To change the value of x to -1:

1 Enter this command in the MATLAB Command Window.

x=-1;
2 Run the model. The Display block now shows a value of 6.

1-54
Edit Block Parameters

See Also
Property Inspector | get_param | set_param

Related Examples
• “View Values of Parameters Set as Variables” on page 30-70
• “Create a Simple Model”
• “Programmatic Modeling Basics” on page 1-2

1-55
1 Simulink Basics

Configure Model Layout


You can organize block diagrams by changing the position and orientation of model elements.

• You can move signal lines by dragging them.


• You can move, rotate, and flip blocks.
• For some blocks, such as the Subsystem block, you can change the port order.

You can change the block diagram layout manually, or you can have the software can arrange it for
you.

For information about how to organize blocks into subsystems, see “Group Blocks into Subsystems”
on page 4-20. For information about how to bundle signal lines, see “Group Signals or Messages into
Virtual Buses” on page 82-14.

You can further configure the appearance of your diagram by resizing blocks. You can also change the
width, height, or size of multiple blocks to match the dimensions of a block you select.

Improve Model Layout with Auto Arrange


To improve your diagram layout and appearance, on the Format tab, click Auto Arrange.
Alternatively, press Ctrl+Shift+A.

This option:

• Aligns blocks in your block diagram from left to right, starting with inputs and ending with
outputs
• Resizes blocks, such as the Constant block, to display long parameter values
• Standardizes block size among similar blocks
• Straightens signal lines by moving blocks

You can also auto arrange the block diagram in a model programmatically.

1 Load the model using the load_system function.


2 Auto arrange the block diagram using the Simulink.BlockDiagram.arrangeSystem
function.

Alternatively, you can try improving the shapes of individual signal lines. Select the signal line and,
from the action bar, select Auto-route Line. The line redraws if a better route between model
elements is possible.

You can try to improve multiple lines by using Auto-route Lines. To access Auto-route Lines from
the action bar, select a block or select multiple model elements by dragging a box around the
elements.

To change the alignment or distribution of blocks, draw a selection box around the blocks. Then, in
the Simulink Toolstrip, on the Format tab, use the buttons in the Distribute and Match sections to
arrange the blocks.

1-56
Configure Model Layout

Move Multiple Model Elements Simultaneously


To move multiple model elements while maintaining their spatial relationships, drag a selection box
around the elements. Then, drag an edge of the selection box to a new position.

The contents of the selection box move as a unit. The relationship among lines, blocks, and other
elements in the selection box remains the same as you move them. Line segments outside of the
selection box reroute.

For example, consider this model.

When you drag a selection box that includes line bends, the included line bends remain the same
when you move the selection.

When you drag a selection box that excludes line bends, the excluded line bends may change when
you move the selection.

To move multiple lines together, drag the selection box around the line segments you want to move.

1-57
1 Simulink Basics

Resize Blocks
To resize a block, pause your pointer on the block. The resize handles appear at the four corners of
the block. Drag one of the resize handles outward to make the block larger, or drag inward to make
the block smaller.

To resize one or more blocks to match the size of another block, follow these steps.

1 Select the block whose size you want the other blocks to match.
2 Press Shift and drag a selection box around the blocks you want to resize.
3
In the Simulink Toolstrip, on the Format tab, in the Match section, click the Match size
button.

To resize one or more blocks to match either the width or height of another block, click the Match

width or Match Height button instead.

Preserve Signal Line Shape When Moving and Resizing Blocks


By default, when you move or resize a block with three or more ports, any signal lines connecting the
block to nearby blocks with one or two ports do not change shape. Instead, the connected blocks
move. You can use this functionality, for example, to move a subsystem block without bending the
signal lines to nearby ports.

If the block connects to a chain of consecutive blocks with one or two ports that are close to each
other, the signal lines in the chain do not change their shape. Instead, the blocks move.

The affected signal lines and blocks highlight in green. The new functionality does not affect signal
lines with branches or Simscape™ connections.

To temporarily turn the functionality off, hold the space bar while you move or resize a block. When
you release the space bar, the functionality turns back on.

To turn the functionality off such that the functionality stays off across MATLAB sessions, in the
Simulink Editor, on the Modeling tab, from Environment, unselect Preserve Alignment. To turn
the functionality back on, from Environment, select Preserve Alignment again.

1-58
Configure Model Layout

Flip or Rotate Blocks


You can change the orientation of a block or a group of blocks by rotating blocks in 90-degree
increments or by flipping the blocks. Rotating or flipping blocks can help them fit better in the block
diagram, such as in feedback loops, where the blocks are connected to each other in a loop. You
might also need to rotate a block so that the block input ports align with output ports or to make
better use of the model canvas.

The figure shows a Gain block flipped to simplify a feedback loop diagram.

To rotate a block, select the block. On the Format tab, click Rotate 90 clockwise or Rotate 90

counterclockwise .

Tip Alternatively:

• To rotate a block clockwise, press Ctrl+R.


• To rotate a block counterclockwise, press Ctrl+Shift+R

1-59
1 Simulink Basics

Blocks automatically rotate when you place them on a signal line that has an orientation other than
left to right. For example, if the signal goes from bottom to top and you place a block on it, the block
rotates to align with the signal.

To flip a block, select the block and, on the Format tab, click Flip left-right or Flip up-down .
You can flip a block horizontally or vertically based on the orientation of the block ports. For example,
if the ports are on the sides, the block flips left to right.

Tip Alternatively, to flip a block horizontally, press Ctrl+I.

To rotate or flip a group of blocks, select multiple blocks before rotating or flipping them. You can
only flip groups of blocks to the left or right.

After you rotate or flip a group of blocks, you can improve the readability of the block diagram by
editing the signal lines. The Auto Arrange option might improve the appearance of signals. (For
information on rotation with multiple ports, see “Identify Port Location on Rotated or Flipped Block”
on page 1-61.)

For example, suppose you rotate these selected blocks clockwise.

After you rotate the blocks, some model elements might overlap.

1-60
Configure Model Layout

With the blocks and signals selected, on the Format tab, click Auto Arrange.

Identify Port Location on Rotated or Flipped Block

Rotating moves block ports from the sides to top and bottom or the reverse, depending on the
placement of the ports. The resulting positions of the block ports depend on the block port rotation
type.

Rotating can reposition the ports on some blocks to maintain left-to-right or top-to-bottom port
numbering order. A block whose ports are reordered after a rotation has the 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. The figure shows the effect of clockwise rotation on a
block with the default port rotation policy.

1-61
1 Simulink Basics

A masked block can specify that ports keep their order after rotation (see “Icon drawing commands”).
These blocks have a physical port rotation type. This policy helps when designing blocks to use when
modeling physical systems and other applications where diagrams do not have a preferred
orientation. The figure shows the effect of clockwise rotation on a block with a physical port rotation
type.

Flipping a block moves the ports to the opposite side of the block, creating a mirror image, regardless
of port rotation type.

Move Ports
You can put ports in any order on any side of these blocks:

• Subsystem block
• Subsystem Reference block
• Model block
• Chart block
• Truth Table block
• State Transition Table block

You can move ports by clicking and dragging the port.

For Subsystem blocks, the port index will automatically be renumbered after each move. For port
label editing on Subsystem blocks, see “Edit Port Labels on Subsystem Blocks” on page 4-26.

You can drag a port to any side of a Subsystem block.

You cannot drag ports on masked or linked Subsystem blocks.

1-62
Configure Model Layout

See Also

Related Examples
• “Edit Port Labels on Subsystem Blocks” on page 4-26
• “Create a Simple Model”
• “Arrange Programmatically Populated Model”

1-63
1 Simulink Basics

Configure Model Element Names and Labels


You can change model element names, hide them, and change their location on a signal line or block.

In addition to block names, In Bus Element and Out Bus Element blocks have also have labels.
Depending on what type of element the block is handling, the label describes a bus, signal, or
message.

Label Signal Lines


To label a signal line, double-click the signal line, then type the label. For the label naming
requirements, see “Signal Names and Labels” on page 81-4.

To change an existing signal line label, double-click the label, then type the new label.

Move Signal Line Labels


By default, signal line labels appear below horizontal signal lines and to the left of vertical signal
lines. To change the location of a block name, drag the signal line label to either side of the signal
line.

Change Block Names


The Simulink Editor names blocks when you add them to a model. The first occurrence of the block is
the library block name, for example, Gain. The next occurrence is the block name with a number
appended. Each new block increments the number, for example, Gain1, Gain2, and so on. These
names are called automatic names.

Note Copying and pasting blocks whose names follow numeric order (Gain1, Gain2, and so on)
creates names that follow standard sorting order conventions for ASCII characters.

To change the block name:


1 Select the block.
2 Double-click the block name.
3 Type the new name.

Hide or Display Block Names


You can edit block names when they are displayed.

By default, the automatic names that the Simulink Editor assigns to new blocks you add to the model
are hidden. Non-automatic names are displayed. For example, if you add your second gain block to a

1-64
Configure Model Element Names and Labels

model, the automatic name, Gain2, is hidden by default. If you rename the block, the new name is
displayed by default.

To temporarily display a block name, pause on the block.

Note Pausing on a block temporarily displays the block name irrespective of all other settings.

To persistently display or hide a block name, click the block. Pause on the ellipsis (…) that appears. In

the action bar that expands, click Show Block Name or Hide Block Name .

To persistently set the visibility of all blocks with automatic names, select one or multiple blocks. In
the Simulink Toolstrip, on the Format tab, in the Block Layout section, click the button labeled
Auto Name, Name On, or Name Off depending on its current setting.

• To display block names of all blocks with automatic names, in the Model Settings section, clear
Hide Automatic Block Names.
• To hide display block names of all blocks with automatic names, in the Model Settings section,
select Hide Automatic Block Names.

To persistently set the visibility of a selected set of blocks, select one of the options above the Model
Settings section instead.

• Name On displays automatic and non-automatic names irrespective of the Hide Automatic
Block Names setting.
• Name Off hides automatic and non-automatic names irrespective of the Hide Automatic Block
Names setting.
• Auto Name returns automatic names to the default state.

To display and hide block names programmatically, use the set_param command with the
'HideAutomaticNames' option for models and the 'HideAutomaticName' and 'ShowName'
options for blocks. For more information on these parameters, see “Common Block Properties”. The
table shows how these parameters interact.

'ShowName' (block 'HideAutomaticName 'HideAutomaticName Result


setting) ' (block setting) s' (model setting)
'off' Any Any Name is hidden
'on' 'on' 'on' Name is hidden
'on' 'off' Any Name is shown
'on' 'on' 'off' Name is shown

Move Block Names


By default, block names appear below blocks whose ports are on the sides and to the left on blocks
whose ports are on the top and bottom. To change the location of a block name, do one of these:

• Drag the block name to any side of the block.


• Select the block and, on the Format tab, click Flip Name.

1-65
1 Simulink Basics

See Also

Related Examples
• “Signal Names and Labels” on page 81-4
• “Signal Label Propagation” on page 81-12

1-66
Configure Model Style Elements

Configure Model Style Elements


You can configure the colors and fonts of your block diagrams, and the depth of the block drop
shadow. You can also copy the formatting of one model element and apply it to another.

For information about how to customize block icons, see “Customize Block Icons” on page 1-70.

Customize Model Colors


You can specify these colors in a block diagram:

• Background color of any system


• Outline and interior colors of any block
• Text and background color of annotations
• Background color of areas

For example, this image shows the Fault-Tolerant Fuel Control System with a black background and
different block outline and interior colors.

To change a background color in a system, open the system. On the Format tab, select a color from
the Background menu.

You can select a color from the menu or click Custom Color to define your own color.

1-67
1 Simulink Basics

Note To add background images to your model, use image annotations. For more information about
image annotations, see “Create Image Annotations” on page 1-80.

To change the outline color of a block, text color in an annotation, or interior color for an area, select
the element. Then, on the Format tab, select a color from the Foreground menu. Changing the
foreground color of a block also changes the color of its output signals.

To change the color of the port labels on a Subsystem block, change the foreground color of the
corresponding Inport and Outport blocks inside the subsystem.

To change the interior color of a block or background color in an annotation, select the element, and
then, on the Format tab, select a color from the Background menu.

You can also use the Property Inspector to change color for an area or an annotation. To specify
colors programmatically, see “Specify Colors Programmatically” on page 1-6.

Customize Model Fonts


Change the font family, style, and size for any model element to make your block diagrams easier to
read or to comply with company standards. You can modify the font for selected blocks, signal labels,
areas, and annotations. Some blocks display text according to the font style settings. Some blocks
have fixed fonts and styles. To increase the font size of those blocks, zoom in.

You can also change the default font for the model. The default font affects any elements whose font
you have not changed and any new elements you create. If you want to use the same default font in
all new models, change the default model font in your default template. See “Set Default Template for
New Models” on page 1-22.

• To change the font of a block, signal label, area, or annotation, select the element. Specify font
information on the Format tab in the Font & Paragraph section.
• To change the default fonts for the model, on the Format tab, click the Configure font for selected
object(s) arrow , then click Fonts for Model. Use the Font Styles dialog box to specify the
font information.

You can also use the Property Inspector to change font for an area or an annotation.

Select Font Dialog Box on Linux Machines

On Linux® machines configured for English, the Font style list in the Select Font dialog box can
appear out of order or in another language in some fonts. If the characters in your Font style list
appear in another language, set the LANG environment variable to en_US.utf-8 before you start
MATLAB. For example, at a Linux terminal, enter this command.

setenv LANG en_US.utf-8


matlab

Copy Formatting Between Model Elements


If you have applied formatting to a block, signal line, or area in a model, you can copy the formatting
and apply it to another model element. Examples of formatting include font changes, foreground and
background color selections, and drop shadow effects.

1-68
Configure Model Style Elements

1 Select the block, line, or area whose formatting you want to copy.
2 From the action bar, select Copy Formatting. The cursor becomes a paintbrush.

3 Using the paintbrush, click each element that you want to copy the formatting to.
4 To cancel the paintbrush cursor, click a blank spot on the canvas or press Esc.

Increase Drop Shadow Depth


By default, blocks have a drop shadow. To make the block stand out more against the background,
you can increase the depth of the drop shadow.

Select the blocks whose drop shadow depth you want to increase. Then, on the Format tab, click
Shadow.

Tip To remove the default drop shadow for all blocks, in the Simulink Toolstrip, on the Modeling tab,
select Environment > Simulink Preferences. In the Editor pane of the Simulink Preferences
dialog box, select Use classic diagram theme.

See Also

Related Examples
• “Specify Colors Programmatically” on page 1-6
• “Create a Simple Mask” on page 43-7
• “Author Block Masks”

1-69
1 Simulink Basics

Customize Block Icons


A mask is a custom interface for a block that hides the block content, making it appear as an atomic
block with its own icon and parameter dialog box. The mask encapsulates the block logic, provides
controlled access to the block data, and simplifies the graphical appearance of a block diagram.

A mask changes only the block interface, not the underlying block characteristics. You can provide
access to one or more underlying block parameters by defining corresponding mask parameters on
the mask.

Mask a Simulink block to:

• Display an icon on a block.


• Provide a customized dialog box for the block.
• Provide a dialog box that enables you to access only select parameters of the underlying blocks.
• Provide users customized description that is specific to the masked block.
• Initialize parameters using MATLAB code.

To create a mask that displays an icon on the block:

1 Right-click the block and select Mask > Create Mask.


2 In the Mask Editor dialog box, click the Icon tab.

3 In the Mask Editor toolstrip, on the Icon tab, click Add Image.
4 In the file browser that appears, navigate to the image you want to use and click Open.
5 In the Mask Editor toolstrip, on the Icon tab, click Save Mask.
6 Close the Mask Editor dialog box.

To look under the mask, click the arrow in the lower left corner of the block.

1-70
Customize Block Icons

For an example on how to create a mask on which you can modify the values of block parameters, see
“Create a Simple Mask” on page 43-7.

For more information about masks, see “Author Block Masks”.

1-71
1 Simulink Basics

Visually Organize Models Using Areas


You can add areas to your model to visually group related model elements.

Areas have these properties:

• You can label an area.


• All model elements inside an area, including the label, move with the area and maintain their
spatial relationship as they move.
• Areas have a solid background color.

Tip If you want to want to use an image as a background for a set of model elements, use an
image annotation. For more information about image annotations, see “Create Image Annotations”
on page 1-80.

Unlike model elements inside an area, model elements on top of an image annotation do not move
with the annotation. If you want a background image and the ability to move the model elements
together with the image, consider adding both the elements and an image annotation to an area.

You can convert part of an existing block diagram to an area, or you can add a blank area to your
model and insert model elements.

To convert part of an existing block diagram to an area:

1 Drag a box around the area of interest in the canvas.


2 From the action bar, click Create Area.

3 Type the name of the area. The name appears in the upper-left corner of the area.

1-72
Visually Organize Models Using Areas

To add a blank area:

1 In the canvas, click and drag over a blank area to draw the area shape.
2 From the action bar, click Area.

3 Type the name of the area.

To add a model element to an area, either drag the element into the bounds of the area. Alternatively,
expand the area to encompass the element by clicking and dragging the corners of the area outward.

To move an area, pause on one of the edges of the area. When the gray bar appears, click and drag
the area to the new position.

To move an area without moving its contents, press Alt while you click and drag the area. On macOS,
press Option instead.

1-73
1 Simulink Basics

To change the label text of an area, select the area, click the ? in the upper left corner, and type the
new label text.

To create a copy of an area, press Ctrl while you click and drag the area. The contents of the area
will also copy.

To change to color of an area, in the Simulink Toolstrip, on the Format tab, in the Style section, click

Foreground. You can select a color from the menu or click Custom Color to define your own
color.

Tip To specify colors programmatically, see “Specify Colors Programmatically” on page 1-6.

1-74
Visually Organize Models Using Areas

See Also

Related Examples
• “Create Image Annotations” on page 1-80
• “Create Area” on page 4-14

1-75
1 Simulink Basics

Annotate Models
You can use annotations to label your block diagram and provide information about its contents in the
canvas. You can also add annotations that perform an action when you click them.

You can create a text annotation or an image annotation.

Text annotations can contain any combination of these elements:

• Text
• Images
• Equations generated using LaTeX and MathML commands
• Hyperlinks that open a website or run MATLAB functions

Image annotations can only contain images.

Use image annotations when you want to resize or move an image independently from text.

Create Text Annotations


To create a text annotation:

1 Double-click the canvas where you want the annotation. The quick insert menu opens. The
default option in the quick insert menu is Create Annotation.

2 Press Enter.
3 Type the annotation text.

• Use the formatting toolbar to edit the text font, font size, font color, or highlight color.
• To create a bulleted or ordered list, right-click the annotation and select Paragraph >
Bullets or Paragraph > Numbering.
• To align the annotation text, right-click the text and select Paragraph > Alignment.

To add an image, table, or equation to the annotation, in the formatting toolbar, click Insert

Image , Insert Table , or Insert Equation . For more information about adding
equations, see “Add Equations to Text Annotations” on page 1-77.

1-76
Annotate Models

To add a hyperlink, in the annotation, select the content that you want to make interactive. Right-
click the selected content and select Hyperlink or press Ctrl+K. For more information about
adding hyperlinks, see “Add Hyperlinks to Annotations” on page 1-82.

Tip Alternatively, to create a text annotation, in the Simulink Editor palette at the left edge of the
model window, click Annotation . Then, click the canvas and type the annotation text.

To create an annotation using text from another application, drag the text from the application to the
canvas.

To paste text from the clipboard into an annotation, right-click the canvas and select Paste.

To create a copy of the annotation, press Ctrl while you click and drag the annotation.

Add Equations to Text Annotations

To add an equation to a text annotation:

1 In the formatting toolbar, click Insert Equation.

2 In the Edit Equation dialog box, enter LaTeX or MathML code to generate equations. For
supported LaTeX commands, see “Insert LaTeX Equation”.

1-77
1 Simulink Basics

3 To format the equation, use the formatting toolbar. You can change the text font, font size, font
color, or highlight color.

To edit equation code, double-click the equation in the annotation.

Add Symbols to Text Annotations


To add symbols or Greek letters into the annotation text, type the TeX formatting command that
generates these symbols into the annotation text.

1 Add supported TeX commands to your annotation. For example, add this text:

\sigma \kappa \mu


2 With the annotation selected, or with the text cursor in the annotation, in the Property Inspector,
under Appearance, select Enable TeX commands.

When you click outside the annotation, the TeX commands appear as symbols in the annotation.

The table shows the TeX characters that you can type directly into the text of a Simulink annotation.

1-78
Annotate Models

Supported TeX Characters


alpha forall supseteq

beta exists supset

gamma ast subseteq

delta cong subset

epsilon sim int

zeta leq in

eta infty o

theta clubsuit copyright

vartheta diamondsuit 0

iota heartsuit ldots

kappa spadesuit varpi

lambda leftarrow times

mu uparrow cdot

nu rightarrow vee

xi downarrow wedge

pi circ perp

rho pm mid

sigma geq Leftarrow

varsigma propto Rightarrow

tau partial Uparrow

upsilon bullet Downarrow

phi div prime

chi neq nabla

psi equiv surd

omega approx angle

Gamma aleph neg

Delta Im lceil

Theta Re rceil

1-79
1 Simulink Basics

Supported TeX Characters


Lambda otimes lfloor

Xi oplus rfloor

Pi oslash langle

Sigma cap rangle

Upsilon cup

Phi

Psi

Omega

Create Image Annotations

You can use image annotations to add images to the Simulink canvas that convey information about
the model or function as background images for the entire block diagram or for groups of model
elements.

To add an image to your model:

1 In the Simulink Editor palette at the left edge of the model window, click Image.

2 Click the canvas at the location where you want the image.

1-80
Annotate Models

3 Double-click the image icon in the canvas.


4 In the file locator that opens, find and open the image you want to add.
5 If the image that appears in the canvas is too large or too small, to resize it, click and drag one of
its corners.

Tip

• To resize proportionally, press Shift as you drag.


• If you resize an image, you can reset it to its original size. Right-click the image and select
Format > Restore Size.

To create an annotation using an image from another application, drag the image from the
application to the canvas.

To create an annotation using an image file, drag the image file to the canvas.

To paste an image from the clipboard into an annotation, right-click the canvas and select Paste.

To include an image, such as your company logo, in every new model, add the image to your default
template. See “Create Template from Model” on page 4-2.

To create a copy of the annotation, press Ctrl while you click and drag the annotation.

To change the image to a different image, double-click the image. In the file locator that opens, find
and open the new image you want to use.

Associate Annotations with Blocks and Areas


You can add a line between an annotation and a block or area in a model. These annotation
connectors attach dynamically at both ends, so that they move and resize as necessary to maintain
the connection.

To add a connector:

1 Pause the cursor over the annotation outline where you want the line to start.

1-81
1 Simulink Basics

2 When the cursor is a crosshair, drag the line to the block or area where you want the line to end.

To specify the color or width of an annotation connector, right-click the connector and use the
Format menu.

Hide Annotations
You cannot hide an annotation, but you can convert an annotation to markup and then hide the
markup.

To convert the annotation to markup:

1 Right-click the annotation.


2 From the context menu, select Convert to Markup.

Note Markup has a light blue background, regardless of the background color you set. If you change
markup to an annotation, the annotation returns to the background color you set.

To change markup back to an annotation, right-click the markup and select Convert to Annotation.

To hide the markup in your model, in the Format tab, click Show Markup.

To display hidden markup annotations, in the Format tab, click Show Markup.

In a model reference hierarchy, Show Markup and Hide Markup apply only to the current model
reference level.

Add Hyperlinks to Annotations


You can add hyperlinks to annotations that open web pages or run MATLAB functions.

1-82
Annotate Models

To add a hyperlink to an annotation:

1 In the annotation, select the content that you want to make interactive.
2 Right-click and select Hyperlink from the context menu.
3 In the Hyperlink dialog box, do one of these actions:

• Select URL Address and enter the web address in the Code box.
• Select MATLAB Code and enter MATLAB functions in the Code box.
4 Click OK.

When you click the annotation, the web page you specified opens or the code you specified runs.

You can also associate text or image annotations with callback functions that run:

• When you load the model containing the annotation (load function)
• When you programmatically delete an annotation or when you interactively or programmatically
close the model (delete function).

• To associate a load function with an annotation, programmatically set the LoadFcn property of the
Simulink.Annotation object to the desired function.
• To associate a delete function with an annotation, programmatically set the DeleteFcn property
of the Simulink.Annotation object to the desired function.

For example, add an annotation to your that modifies the value of the variable x when you load or
close the model:

1 Add an annotation to your model with the text increment x.


2 To initialize x, enter this command in the MATLAB Command Window.

x=3;
3 To get the annotation programmatically, in your model, select the annotation. Then, enter this
command.

an=getCurrentAnnotation;
4 To specify the load function for the annotation, enter this command.

an.LoadFcn="x=x+1;";
5 To specify the delete function for the annotation, enter this command.

an.DeleteFcn="x=x-1;";
6 Save the model.
7 Close the model and check the value of x in the Workspace Browser. The value of x is 2 because
the delete function has decreased the value by 1.
8 Reopen the model and check the value of x in the Workspace Browser. The value of x is 3
because the load function has increased the value by 1.

See Also
Simulink.Annotation

1-83
1 Simulink Basics

Related Examples
• “Create and Edit Annotations Programmatically” on page 4-9
• “Write In-Model Documentation Using Notes” on page 4-4

1-84
Bookmark Your Place in Models

Bookmark Your Place in Models

You can use viewmarks to bookmark parts of a model or to capture graphical views of a model so you
can navigate directly to that view. You can capture viewmarks for specific levels in a model hierarchy.
You can also pan and zoom to capture a point of interest.

Some examples of ways to use viewmarks include:

• Navigate to specific locations in complex models without opening multiple Simulink Editor tabs or
windows.
• Review model designs.
• Visually compare versions of a model.
• Share views of a model by storing viewmarks within the model.

You manage viewmarks in the viewmarks gallery. By default, viewmarks are stored locally on your
computer. If you want to include a viewmark to share with a model, see “Save a Viewmark to the
Model” on page 1-86. The figure shows the viewmark gallery.

1-85
1 Simulink Basics

Create a Viewmark
1 Navigate to the part of the model that you want to capture in a viewmark.
2 Pan and zoom to the part of the system that you want to capture.
3 Resize the Simulink Editor window to frame the part of the model you want to capture.
4
In the palette, click the Viewmark This View button .

The viewmark displays briefly and becomes part of the viewmarks gallery.

Open and Navigate Viewmarks


1
In the Simulink Editor palette, click the Viewmarks button .

The viewmarks gallery has two tabs. The Personal tab has viewmarks that you created in a
model and are stored locally on your computer. The Model tab has viewmarks that are saved in
the Simulink model file.
2 Select the tab (Personal or Model) that contains your viewmark, then click the viewmark.

The Simulink Editor opens the model, if necessary, and displays the part of the model captured in
the viewmark.

Manage Viewmarks
In the viewmarks gallery, you can rename viewmarks, add or edit a description for viewmark, and
delete viewmarks. You also use the viewmarks gallery to save viewmarks with the model. You can
manage viewmarks only in models saved in SLX format. In models saved in MDL format, the Manage
button appears dimmed.

• To rename a viewmark, click the name and edit it.



To add a description, pause on the viewmark, click the Description button , and enter a
description.

To delete a viewmark, pause on the viewmark and click the Delete button on the viewmark. To
delete all the viewmarks for a model, pause on the model name and click Delete.

Save a Viewmark to the Model


1
In the Simulink Editor palette, click the Viewmarks button .
2 In the viewmarks gallery, click Manage.
3 Select the check box in the viewmarks you want to copy to the model.
4
Click the Add viewmarks to model button .

These viewmarks become part of the model.

1-86
Bookmark Your Place in Models

Refresh a Viewmark
A viewmark is a static view of a part of a model. For currently loaded models, you can refresh a
viewmark so that it reflects the current model. Open the viewmark gallery and click the Refresh

button on the viewmark.

If the viewmark shows a subsystem that has been removed, then the viewmark appears dimmed.

See Also

Related Examples
• “Print Models to PDFs” on page 1-103

1-87
1 Simulink Basics

Search Model Contents


You can use the Finder to search a Simulink model, subsystem, or library or a Stateflow chart for
model elements such as blocks and signal lines. For example, you can search for a specific block, or
you can search for all the Constant blocks in the model. You can also search for parameters,
functions, annotations, events, or messages.

You can narrow your search by filtering the search results.

Tip If you want to filter the model content inventory for items of a certain type or with certain
properties, you can also use the Model Data Editor.

To search for the source or destination of a signal and trace signal paths, see “Highlight Signal
Sources and Destinations” on page 81-29.

If your model contains blocks that connect without signal lines, given one such block, you can
highlight or jump to the blocks it connects to. For more information, see “Search for Blocks
Connected Without Signal Lines” on page 1-90.

To search for Simulink Editor actions, see “Keyword Search for Simulink Editor Actions” on page 1-
92.

Keyword Search for Model Elements and Parameters


You can use the Finder to perform a keyword search for model elements and parameters.

To open the Finder, select the Simulink Editor and press Ctrl+F.

In the search box, type a keyword or key phrase, then press Enter. The keyword or key phrase can be
any in this table.

Keyword or Key Phrase Example


Name of an item A block name or a signal line label
Type of item signal or subsystem
Property value Name of a variable used to set the Constant value of a Constant
block
Label string Condition of a Stateflow transition
Words or phrases in a script Line of code in a MATLAB Function block
Words or phrases in a Phrase from a block description
description
Name of a source For a signal line, the block to whose input port the signal line
connects
Name of a destination For a signal line, the block to whose output port the signal line
connects

The search results highlight matches for the keyword or key phrase in the Names column.

To navigate to a search result in the model, in the Finder, in the Name column, double-click the item.

1-88
Search Model Contents

To change the scope of the search, click Change the search scope and select one of these
options:

• Search from top model


• Search this level and below

1-89
1 Simulink Basics

• Search this level only

When a search returns too many results, narrow your search using advanced settings . For more
information, see “Perform Advanced Search”.

You can also use the Finder to replace text in the model. For more information, see “Find and Replace
Text”.

Search for Blocks Connected Without Signal Lines


Related blocks connect without signal lines. To search for related blocks, select a block. All blocks
related to the selected block highlight in purple. Blocks that contain related blocks also highlight in
purple.

To both find and switch selection to a related block, you can use the Related Blocks button.

Note The Related Blocks button is not available for blocks from the Dashboard, Customizable
Blocks, or Aerospace Blockset™ libraries.

Select a block, then pause on the ellipsis (…) that appears. In the action bar that expands, click

Related Blocks . If more than one related block is present, a list of related blocks appears.
Navigate to the name of the block you want to select by clicking or using the arrow keys on your
keyboard, then press Enter.

Tip Instead of the Related Blocks button in the action bar, you can also click the Related Blocks
button in the Simulink Toolstrip, on the block-specific tab (for example, the Goto tab of a Goto block).

When you switch the selection, you automatically navigate to the related block that you are switching
the selection to. If the block you switch the selection to is located inside a component (for example, a
subsystem or model reference), and the selected block is not inside a component or is inside a
different component, the component you automatically navigate to opens in a new tab or a new
window.

1-90
Search Model Contents

See Also
Finder | Model Data Editor

Related Examples
• “Highlight Signal Sources and Destinations” on page 81-29
• “Keyword Search for Simulink Editor Actions” on page 1-92

1-91
1 Simulink Basics

Keyword Search for Simulink Editor Actions


You can use the quick insert menu to perform a keyword search for actions that you want to take or
for keyboard shortcuts. When you find the action you are looking for in the search results, you can
implement it by selecting it and pressing Enter.

For example, you can search for updating a model.

1 To open the quick insert menu, double-click the canvas.


2 To search for actions instead of blocks, switch to action search by pressing Ctrl+..

3 To search for the action, type the keyword update. A list of actions containing the keyword
appears. The keyboard shortcut for each action is displayed in parentheses.
4 To update the model, select the first search result using your arrow keys and press Enter.
Alternatively, click the search result or use the keyboard shortcut to implement the action.

Tip If the quick insert menu is open to action search and you want to search for a block instead,
press Ctrl+..

See Also

Related Examples
• “Add Blocks to Models Using Quick Insert Menu” on page 1-32
• “Keyboard Shortcuts and Mouse Actions for Simulink Modeling” on page 1-8

1-92
Preview Content of Model Components

Preview Content of Model Components


To display a representation of the contents of a hierarchical model element, such as a subsystem, on
the block, you can use content preview. Content preview helps you see the contents of a hierarchical
element without navigating the hierarchy. Content preview shows blocks, signals, signal and block
labels, sample time color coding, signal highlighting, and Stateflow animations.

By default, content preview is on for new hierarchical elements. You can change this setting by using
Simulink Preferences. To open the Simulink Preferences dialog box, on the Modeling tab, select
Environment > Simulink Preferences. On the Editor pane, you can clear the Content preview
displays for new hierarchical elements option.

To toggle content preview for a hierarchical element, select the block that you want to enable or
disable content preview for, and then on the Format tab, click Content Preview. Content preview
settings for blocks apply across Simulink sessions.

In this figure, the Throttle & Manifold subsystem has content preview enabled.

Simulink scales the content preview to fit the size of the block. To improve the readability of the
content preview, you can zoom in on or resize the block.

You can enable content preview on:

• Subsystem blocks
• Model blocks
• Variant Subsystem blocks
• Stateflow charts, subcharts, and graphical functions

In some cases, content preview does not appear when it is enabled. Content preview does not appear
for:

• Hierarchical block icons when they are smaller than their default size in the Library Browser
• Masked blocks whose Icon transparency property is set to Opaque or Opaque with ports
• Masked blocks that have a mask icon image
• Subsystem blocks when they have the Read/Write permissions block parameter set to
NoReadOrWrite
• Model blocks whose referenced models are protected models
• Model blocks whose referenced models are not loaded
• Models that have the classic diagram theme enabled in Simulink Editor preferences

Note A slight delay can occur when drawing models with many hierarchical elements that contain
many blocks and have content preview enabled.

1-93
1 Simulink Basics

Programmatic Use
Parameter: ContentPreviewEnabled
Type: character vector
Value: 'on' | 'off'
Default: 'on'

See Also
Model | Subsystem | Variant Subsystem, Variant Model

1-94
Exchange Messages with Block Comments

Exchange Messages with Block Comments


Comments provide an interface for teams to review, iterate, and develop block diagrams. With
comments, you can collaborate directly in the Simulink Editor. Team members can add comments to
provide feedback, ask questions, and suggest alternative designs.

You can also use comments to record action items as you develop a block diagram. For example, you
can add comments to remind yourself of design ideas and to indicate where you may need to change
a parameter value.

To add descriptive notes and annotations that are not actionable, see “Annotate Models” on page 1-
76.

To mark up a printed copy of the block diagram, see “Print Model Diagrams” on page 1-98.

Determine Whether Model Has Open Comments


When you close a model, subsystem, or library file that has comments, the comments are saved in an
MLDATX file with a _comments suffix. For example, for a model named mymodel.slx, the comments
file is named mymodel_comments.mldatx. To access the comments, the corresponding comments
file must be on the MATLAB path. When the comments file is accessible and the model has open

comments, a badge ( ) appears in the lower-left corner of the Simulink Editor canvas.

1-95
1 Simulink Basics

View Comments
To view comments, open the Review Manager perspective by performing one of these actions:

• In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, select Review Manager.
• In the lower-right corner of the Simulink Editor canvas, click the perspectives control and select
the Review Manager perspective.


If the model has open comments, click the Model has open review comments badge in the
lower-left corner of the Simulink Editor canvas.

These actions open the Review tab and the Comments pane.

When a block has comments associated with it, a comment icon appears on the block. Click the
comment icon to highlight the related comments in the Comments pane. To see the most recent
comment for the block as a tooltip, pause on the comment icon.

Add Comments
To add a comment:

1 Open the Review Manager perspective by performing one of these actions:

• In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, select Review
Manager.
• In the lower-right corner of the Simulink Editor canvas, click the perspectives control and
select the Review Manager perspective.


If the model has open comments, click the Model has open review comments badge in
the lower-left corner of the Simulink Editor canvas.
2 Select a block in the Simulink Editor canvas, then perform one of these actions:


Pause on the ellipsis, then click the Add Comment button in the action bar.
• On the Review tab, click Add Comment.
3 Enter the comment in the text box that appears in the Comments pane.

To enter multiline comments in the Comments pane, press Shift+Enter while editing a
comment.

1-96
Exchange Messages with Block Comments

When you rename a block that has comments, the Comments pane updates to display the new block
name. Blocks are sorted alphabetically by name in the Comments pane. Renaming a block can
change the position of the comments in the pane.

When you close the parent model, subsystem, or library file, the comments are saved in an MLDATX
file in the same location as the parent. Suppose you add comments to a model named mymodel.slx,
which previously had no comments associated with it. Closing the model creates a comments file
named mymodel_comments.mldatx.

To add comments to blocks in other files, open the files separately. For example, open a referenced
model as a top model by clicking the Open As Top Model icon on a Model block that references it.

Edit, Reply to, and Resolve Comments


In the Comments pane, pause on a committed comment to receive options to edit it, reply to it,
resolve it, and show the block that corresponds to it. Clicking Show in Model highlights the block to
facilitate finding the block in the block diagram.

When you pause on a resolved comment, you receive options to reopen the comment and to show the
block that corresponds to the comment.

Hide and Delete Comments


To display fewer comments in the Comments pane, on the Review tab, clear Comment List > Show
resolved comments. Alternatively, permanently delete all resolved comments by selecting
Comment List > Delete all resolved comments.

When the comments file is on the MATLAB path, deleting a block that has comments also deletes the
corresponding comments. If you undo the deletion of a block, the block and its comments are
restored.

See Also
Finder

Related Examples
• “Bookmark Your Place in Models” on page 1-85
• “Annotate Models” on page 1-76
• “Create a Project from a Model” on page 16-12
• “Print Model Diagrams” on page 1-98
• “Print Model Reports” on page 1-105

1-97
1 Simulink Basics

Print Model Diagrams


To print a model diagram, in the Simulink Editor, on the Simulation tab, click Print.

Print Models Using Default Settings


The default print settings produce good quality printed output for quickly capturing a model in
printed form.
1 Open your model.
2 In the Simulink Editor, on the Simulation tab, click Print.
3 In the Print Model dialog box, use the default settings. Click Print.

The model as it appears in the Simulink Editor prints on a single page using portrait orientation and
without a print frame.

Specify Paper Size and Orientation


Use the Print Model dialog box to specify the page orientation (portrait or landscape) for the current
printing session.

To specify paper size and orientation without printing, use the Page Setup dialog box. To open the
dialog box, on the Simulation tab, select Print > Page Setup. Only the paper size and orientation
are used.

Specify Background Color


By default, the canvas (background) of the printed model is white. To match the color of the model,
set the Simulink Preferences > General > Print.

1-98
Print Model Diagrams

Specify Print Frames


Print frames are borders of a printed page that contain information about a block diagram, such as
the model name or the date of printing.

To print using a print frame, specify an existing print frame. If you want to build a print frame, see
“Create Print Frames for Printed Pages” on page 85-2.

Note If you enable the print frame option, then Simulink does not use tiled printing.

1 In the Simulink Editor or Stateflow Editor, on the Simulation tab, click Print.
2 In the Print Model dialog box, select the Frame check box.

3 Supply the file name for the print frame you want to use. Either type the path and file name
directly in the edit box, or click the ... button and select a print frame file you saved using the
PrintFrame Editor. The default print frame file name, sldefaultframe.fig, appears in the file
name edit box until you specify a different file name.
4 Specify other printing options in the Print Model dialog box.

Note The paper orientation you specify with the PrintFrame Editor does not control the paper
orientation used for printing. For example, assume you specify a landscape-oriented print frame
in the PrintFrame Editor. If you want the printed page to have a landscape orientation, you must
specify that using the Print Model dialog box.
5 Click OK.

The block diagram prints with the print frame that you specify.

Select the Systems to Print


To print the system in the currently open Simulink Editor tab, on the Simulation tab, click Print.

1-99
1 Simulink Basics

For models with subsystems, use the Simulink Editor and the Print Model dialog box to specify the
subsystems to print.

Note To print a model reference hierarchy, you must print each referenced model separately. You
cannot print the contents of protected models.

By default, Simulink does not print masked subsystems or subsystems linked to libraries.

• To print the contents of masked subsystems, in the Print Model dialog box, click Look under
mask dialog.
• To print the contents of library links, in the Print Model dialog box, click Expand unique library
links. Simulink prints one copy, regardless of how many copies of the block the model contains.
• If a subsystem is a masked subsystem linked to a library, Simulink uses the Look under mask
dialog setting and ignores the Expand unique library links setting.

To print all of the subsystems in a model:

1 Display the top-level of a model in the currently open Simulink Editor tab.
2 In the Simulink Editor, on the Simulation tab, click Print.
3 In the Print Model dialog box, select All systems.
4 Click Print.

To print a subset of the subsystems in a model:

1 In the current tab of the Simulink Editor, display the subsystem level that you want to use as the
starting point for printing the subsystem hierarchy.
2 In the Print Model dialog box, select one of the following:

• Current system and below


• Current system and above
3 Click Print.

Print Large Diagrams over Multiple Pages


By default, each block diagram is scaled during the printing process so that it fits on a single page. In
the case of a large diagram, this automatic scaling can make the printed image difficult to read.

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. For example, you
can use tiling to divide a model as shown in the figure, with each white box and each gray box
representing a separate printed page.

1-100
Print Model Diagrams

You can control the number of pages over which Simulink prints the block diagram.

You can also set different tiled-print settings for each of the systems in your model.

Note If you enable the print frame option, then Simulink does not use tiled printing.

To print multiple pages for large model:

1 In the Simulink Editor, open the model in the current tab.


2 On the Simulation tab, click Print.
3 In the Print Model dialog box, select Enable tiled printing.

Note The default Enable tiled printing setting in the Print Model dialog box is the same as the
Print > Enable Tiled Printing setting. If you change the Print Model dialog box Enable tiled
printing setting, the Print Model dialog box setting takes precedence.
4 Confirm that tiling divides the model into separate pages the way you want it to appear in the
printed pages. In the Simulink Editor, on the Simulation tab, select Print > Show Page
Boundaries. The gray and white squares indicate the page boundaries.
5 Optionally, from the MATLAB Command Window, specify the model scaling, tile margins, or both.
See “Set Tiled Page Margins” on page 1-110.
6 Optionally, specify a subset of pages to print. In the Print Model dialog box, specify the Page
Range.
7 Click Print.

1-101
1 Simulink Basics

Add Log of Printed Models


A print log lists the blocks and systems you have printed. To print the print log when you print a
model:
1 In the Simulink Editor, open the model whose print job you want to log.
2 On the Simulation tab, click Print.
3 In the Print Model dialog box, select Include print log.
4 Click Print.

The print log appears on the last page.

For example, here is the print log for the sldemo_enginewc model, with All systems enabled and
Enable tiled printing cleared.

Add 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:
1 In the Simulink Editor, on the Modeling tab, click Update Model.
2 On the Simulation tab, click Print.
3 In the Print Model dialog box, select Print sample time legend.
4 Click Print.

A sample time legend appears on the last page. For example, here is the sample time legend for the
sldemo_enginewc model, with All systems enabled.

1-102
Print Model Diagrams

For more information on sample times, see “View Sample Time Information” on page 7-15.

Configure Print Job


To open the print dialog box for your operating system, in the Print Model dialog box, click Print
using system dialog. The operating system print dialog box provides additional printing options for
models, such as page range, copies, double-sided printing, printing in color (if your print driver
supports color printing), and nonstandard paper sizes.

Print Models to PDFs


You can print a model to a .pdf file. Simulink creates one file for all of the systems in the model.

1 In the Simulink Editor, on the Simulation tab, click Print.


2 Select Print to File.
3 Specify a location and file name to save the new .pdf file. Include the extension .pdf in the file
name.
4 Click Print.

Copy Diagrams as Images


On Microsoft® Windows® platforms, you can copy the current view of your model in either a bitmap
or metafile format. You can then paste the clipboard image to a third-party application, such as word
processing software.

On Macintosh platforms, when you copy a model view to the clipboard, Simulink saves the model in a
scalable format in addition to a bitmap format. When you paste from the clipboard to a third-party
application, the application selects the format that best meets its requirements.

1 To copy a Simulink model to the operating system clipboard, in the Simulink Editor, on the
Format tab, select Screenshot, then select the desired format.
2 Navigate out of Simulink and into a third-party application with image capabilities. Paste the
model from the clipboard to the third-party application. Export the model image using the correct
procedure for the application.

Note The quality of the exported image will depend on the third-party application. Results may vary
based on individual cases.

By default, the canvas (background) of the copied model matches the color of the model. To use a
white or transparent canvas for copied model files, set the Simulink Preferences > General >
Clipboard preference. For more information, see Simulink Preferences.

See Also
print

More About
• “Create Print Frames for Printed Pages” on page 85-2

1-103
1 Simulink Basics

• “Print Model Reports” on page 1-105


• “Programmatically Print Models from MATLAB Command Window” on page 1-107

1-104
Print Model Reports

Print Model Reports

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 Simulink Report Generator™ installed, you can generate a detailed report about a
system. In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, select System Design
Report. For more information, see “System Design Description” (Simulink Report Generator).

To generate a model report for the current model:

1 In the Simulink Editor, on the Simulation tab, select Print > Print Details.
2 In the Print Details dialog box, select report options.

Report Option Description


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.
Increment filename to prevent Creates a unique report file name each time
overwriting old files 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.
3 Click Print.

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

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

1-105
1 Simulink Basics

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 stop the report generation,
click 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.

See Also

More About
• “Print Model Diagrams” on page 1-98
• “Masking Fundamentals” on page 43-3

1-106
Programmatically Print Models from MATLAB Command Window

Programmatically Print Models from MATLAB Command


Window
In this section...
“Printing Commands” on page 1-107
“Print Systems with Multiline Names or Names with Spaces” on page 1-108
“Set Paper Orientation and Type” on page 1-109
“Print Diagrams over Multiple Pages” on page 1-109
“Print Models to Image File Formats” on page 1-110

You can print Simulink model diagrams and export them to image file formats programmatically. To
print and export model diagrams interactively, see “Print Model Diagrams” on page 1-98.

Printing Commands
The MATLAB print command provides several printing options. For example, to print the
Compression subsystem in the sldemo_enginewc model to your default printer, enter these
commands in the MATLAB Command Window.

openExample('sldemo_enginewc');
print -sCompression

When you use the print command, you can print only one diagram. To print multiple levels in a
model hierarchy, use multiple print commands, one for each diagram that you want to print.

Tip Alternatively, consider printing interactively. In the Simulink Toolbar, on the Simulation tab, in
the File section, click Print. Then, use the Print Model dialog box in the Simulink Editor to specify
the diagrams to print. For details, see “Select the Systems to Print” on page 1-99.

You can use the set_param function with these parameters to specify printing options for models.

1-107
1 Simulink Basics

Model Parameters for Printing

Parameter Description Values


PaperOrientation Printing paper orientation. 'portrait' | {'landscape'}
PaperPositionMode Paper position mode. {'auto'} | 'tiled'

• auto – When printing, Simulink


software sizes the diagram to fit the
printed page. When exporting a
diagram as a graphic image, Simulink
software sizes the exported image to
be the same size as the diagram's
normal size on screen.
• tiled – Print or export diagram over
multiple pages. See “Print Diagrams
over Multiple Pages” on page 1-109 for
more information.
PaperType Printing paper type. 'usletter' | 'uslegal' | 'a0' |
'a1' | 'a2' | 'a3' | 'a4' | 'a5'
| 'b0' | 'b1' | 'b2' | 'b3' |
'b4' | 'b5' | 'arch-A' | 'arch-
B' | 'arch-C' | 'arch-D' |
'arch-E' | 'A' | 'B' | 'C' | 'D'
| 'E' | 'tabloid'
PaperUnits Printing paper size units. 'normalized' | {'inches'} |
'centimeters' | 'points'
TiledPaperMargins Size of the margins associated with each vector — [left, top, right,
tiled page. Each element in the vector bottom]
represents a margin at the particular
edge.

Print Systems with Multiline Names or Names with Spaces


To print a system whose name appears on multiple lines, assign the name to a variable and use that
variable in the print command. This example shows how to print the subsystem named Aircraft
Dynamics Model.

openExample('simulink_aerospace/AircraftLongitudinalFlightControlExample')
open_system('slexAircraftExample/Aircraft Dynamics Model');
sys = sprintf('slexAircraftExample/Aircraft\nDynamics\nModel');
print (['-s' sys])

To print a system whose name includes one or more spaces, specify the name as a character vector.
For example, to print the Throttle & Manifold subsystem, enter these commands.

openExample('sldemo_enginewc');
open_system('sldemo_enginewc/Throttle & Manifold');
print (['-sThrottle & Manifold'])

1-108
Programmatically Print Models from MATLAB Command Window

Set Paper Orientation and Type


To set just the paper orientation, use the orient function. Alternatively, set the paper orientation by
using set_param function with the PaperOrientation model parameter.

To set the paper type, use the set_param function with the PaperType model parameter. For
example, to print to US letter-sized paper, set the paper type to 'usletter'.

Print Diagrams over Multiple Pages


By default, each block diagram is scaled during the printing process so that the diagram fits on a
single page. In the case of a large diagram, this automatic scaling can compromise the printed image.

Tiled printing allows 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. For example, you
can use tiling to divide a model as shown in the figure, with each white box and each gray box
representing a separate printed page.

Enable Tiled Printing

1 Use the set_param function to set the PaperPositionMode parameter to tiled.


2 Use the print command with the -tileall argument.

For example, to enable tiled printing for the Compression subsystem in the sldemo_enginewc
model, use these commands.

openExample('sldemo_enginewc');
set_param('sldemo_enginewc/Compression', 'PaperPositionMode', ...
'tiled');
print('-ssldemo_enginewc/Compression', '-tileall')

1-109
1 Simulink Basics

Display Tiled Page Boundaries

To display the page boundaries programmatically, use the set_param function with the model
parameter ShowPageBoundaries set to on.

openExample('sldemo_enginewc');
set_param('sldemo_enginewc', 'ShowPageBoundaries', 'on')

Set Tiled Page Margins

By decreasing the margin sizes, you can increase the printable area of the tiled pages. To specify the
margin sizes associated with tiled pages, use the set_param function with the TiledPaperMargins
parameter. Each margin is 0.5 inches by default. The value of TiledPaperMargins is a vector that
specifies margins in this order: [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
units of measurement for the margins.

Specify Range of Tiled Pages to Print

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 specifies
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, use these commands.

openExample('simulink_general/VanDerPolOscillatorExample');
print('-svdp','-tileall','-pages[2 4]')

Print Models to Image File Formats


To print your model to an image file format such as .png or .jpeg, use the -device argument with
the MATLAB print command. For example, to print the vdp model to a .png format, use these
commands.

openExample('simulink_general/VanDerPolOscillatorExample');
print -dpng -svdp vdp_model.png

To programmatically export a model into an image format:

• Call your model in the MATLAB command line.

model %model is your model name


• Use the print command to save your model in a .jpeg format.

print('-smodel', '-djepg', 'new_name')

By default, the canvas (background) of the exported model matches the color of the model. To use a
white or transparent canvas for model files that you export to another file format, set the Simulink
Preferences > General > Export preference. For more information, see Simulink Preferences.

1-110
Programmatically Print Models from MATLAB Command Window

See Also
print | orient

Related Examples
• “Engine Timing Model with Closed Loop Control”

More About
• “Print Model Diagrams” on page 1-98

1-111
1 Simulink Basics

Index and Search Models with Model Finder


Use the Model Finder to search and browse examples, models, and projects across various databases.
Model Finder supports multiple databases, including the default MathWorks Examples database.
You can also create new databases or import any existing databases to Model Finder. Using multiple
databases enables you to group similar models, making it simpler to share, search, maintain, and
control access to these databases. You can use Model Finder to index models in your databases and to
store textual information of models, such as model names, paths, blocks, and descriptions to make
the models easily searchable using Model Finder.

You can use Model Finder to support a collaborative development of models in your teams:

• Create or Import — Create a new database or use an existing database for your project.
• Index — Save model-related textual data in the database to make models easily findable.
• Search — Search the database to find relevant models.

To enable your team to access the database containing information of models, share the database
path with the developers. This allows them to import the shared database to Model Finder for
indexing or searching models.

Configure and Search Databases


Model Finder uses the default MathWorks Examples database consisting of MathWorks examples,
models, and projects. You can also configure your databases with the Model Finder.

To use Model Finder to manage your team's collection of Simulink models for a project related to
Wireless Communication Systems:

1 Create a project database — Create a dedicated database using Model Finder to store
information of the Simulink models related to the project. To create a new database, use the
modelfinder.createDatabase function.

For example, create a database wireless_systems.db and assign alias Wireless


Communication.

1-112
Index and Search Models with Model Finder

modelfinder.createDatabase("/home/users/modelfinderdatabases/wireless_systems.db",...
"Wireless Communication")

Model Finder uses the aliases to display the databases. If you do not specify an alias, Model
Finder uses the database filename as the alias.

To view the list of databases available with Model Finder, open the Model Finder UI by using the
modelfinderui function and view the list of databases in the Database pane.
2 Index models in project database — Store textual information of the models, such as model
names, example names, model paths, descriptions, annotations, block names, block types, and
referenced files, in the database. To index models in a database, use the
modelfinder.registerFolder function.

To index models from the folder named 5G in wireless_systems.db, set the database as the
default database and then index the models.
modelfinder.setDefaultDatabase("/home/users/modelfinderdatabases/wireless_systems.db")
modelfinder.registerFolder("/home/users/data/5G")
3 Import project database — Team members can import the project database to Model Finder. This
enables them to search for models or index their models in the project database. To import
databases to Model Finder, use the modelfinder.importDatabase function. You must share
the database path within your team to allow access and use the database as a central repository
of models.

Import wireless_systems.db and assign alias Wireless Communication.


modelfinder.importDatabase("/home/users/modelfinderdatabases/wireless_systems.db",...
"Wireless Communication")

Note Model Finder supports only databases created in the same release version. To use
databases from previous releases with the latest Model Finder, you must recreate them. This
allows for optimal performance and access to the latest features of Model Finder.
4 Set project database as search scope — By default, Model Finder uses the MathWorks
Examples database as its search scope. To set other databases as search databases, use the
modelfinder.setSearchDatabase function.

Set wireless_systems.db as the search database.


modelfinder.setSearchDatabase("/home/users/modelfinderdatabases/wireless_systems.db")

Alternatively, you can change the search scope from the Model Finder UI. Open the Model Finder
UI by using the modelfinderui function and select the databases from the list of available
databases in the Databases pane.
5 Search the database — Enter search terms in the Model Finder UI or use the modelfinder
function to initiate a search. Model Finder supports keyword-based searches and natural
language queries. When you enter a search query, Model Finder returns a set of examples,
models, and projects that match your search terms in the databases set as search databases. For
more information, see “Search, Filter, and Browse Models”.

Search for models in the search databases using the search term mobile communication.
modelfinder("mobile communication")
6 Remove models from databases — If you do not want some models to appear in the search results
of Model Finder, remove the folder that contains those models using the
modelfinder.unregisterFolder function.

1-113
1 Simulink Basics

Remove indexed folder 5G from the databases selected as search databases.

modelfinder.unregisterFolder("/home/users/data/5G")
7 Remove databases from Model Finder — If you do not want to index or search models in certain
databases, you can remove those databases from Model Finder. For more information on
removing databases from Model Finder, see modelfinder.deleteDatabase. Removing a
database from Model Finder will not delete models or the database.

Remove wireless_systems.db from Model Finder.


modelfinder.deleteDatabase("/home/users/modelfinderdatabases/wireless_systems.db")

Note To view the changes in the Model Finder UI made using Model Finder functions, close and
reopen the Model Finder UI.

See Also
Functions
modelfinder.createDatabase | modelfinder.importDatabase |
modelfinder.setDefaultDatabase | modelfinder.registerFolder |
modelfinder.setSearchDatabase | modelfinder | modelfinder.deleteDatabase |
modelfinder.unregisterFolder

Tools
Model Finder

Related Examples
• “Search, Filter, and Browse Models”
• “Create New Database and Store Model Information”

1-114
2

Step Through Simulations

• “Step Through Simulation” on page 2-2


• “How Stepping Through Simulation Works” on page 2-7
• “Debug Simulation Using Signal Breakpoints” on page 2-12
2 Step Through Simulations

Step Through Simulation


In this section...
“Open and Configure Model” on page 2-2
“Step Forward One Step at a Time” on page 2-3
“Step Forward Multiple Time Steps at a Time” on page 2-4
“Step Back in Simulation” on page 2-4
“Finish or Stop Simulation” on page 2-5

This example shows how to step through major time steps of a simulation while viewing signal values
in the block diagram. In this example, you start the simulation by clicking Step Forward so the
simulation pauses after the first major time step. You can also start stepping through a simulation
after you pause by clicking Pause or after the simulation pauses on a breakpoint. When the
simulation pauses on a breakpoint, additional stepping options are available that allow you to step
through a time step block by block. For more information, see “Debug Simulation Using Signal
Breakpoints” on page 2-12.

Open and Configure Model


Open the model vdp, which implements the Van der Pol equation. For more information about the
model, see “Van der Pol Oscillator”.

openExample("simulink_general/VanDerPolOscillatorExample",...
supportingFile="vdp")

You might run several simulations while analyzing and debugging your model. To save time by
compiling the model only before the first simulation, enable fast restart. In the Simulink Toolstrip, on
the Simulation tab, click Fast Restart.

Add port value labels so you can see the signal values as you step through the simulation. Click an
empty area in the upper left of the canvas and drag to select everything in the block diagram. Then,
on the Debug tab, in the Tools section, in the Port Values button group, click Show port value label

2-2
Step Through Simulation

on selected signal . The port value labels show no data yet until the first forward step in
simulation after you add the port value labels.

Step Forward One Step at a Time


When you want to run a simulation one step at a time from the beginning, you can start the
simulation by clicking Step Forward. In the Simulink Toolstrip, on the Simulation tab, click Step
Forward to start a simulation of the model vdp. The simulation starts and pauses just after
calculating the output values for the first simulation time and before stepping to the next simulation
time.

To monitor the simulation status and simulation time, use the status bar at the bottom of the Simulink
Editor. In the middle of the status bar, the software displays the time that corresponds to the most
recent output values and a progress bar that indicates the simulation status. Some solvers perform
calculations to determine the time of the next major time hit before the point in the simulation loop
where the simulation pauses when you click Step Forward. In this case, the solver is ahead in

2-3
2 Step Through Simulations

simulation time relative to the block diagram. The asterisk on the simulation time indicates that the
solver has moved ahead in simulation time.

Each time you click Step Forward, the simulation advances one major time step. The time in the
status bar updates, and the port value labels update to display the new signal values.

Step Forward Multiple Time Steps at a Time


To advance the simulation by multiple time steps each time you click Step Forward, configure the
simulation stepping options. To open the Simulation Stepping Options dialog box, click the Step
Back button arrow then select Configure Simulation Stepping. In the Simulation Stepping Options
dialog box, specify Move back/forward by as 5. Then, click OK.

Now, when you click Step Forward again, the simulation advances through five major time steps.
The time changes by a larger increment, and you can see the overall simulation progress indicated in
the status bar.

Double-click the Scope block. The plot updates to display the data for the signals x1 and x2 as the
simulation advances. Click Step Forward to see the Scope block update to display data from five
more time steps.

Step Back in Simulation


Before you can step back in simulation, you have to enable stepping back. To support stepping back
in simulation, the software captures snapshots of the model operating point while advancing forward
in simulation. Capturing these snapshots requires memory and can affect simulation performance.
For more information, see “How Stepping Through Simulation Works” on page 2-7.

2-4
Step Through Simulation

Open the Simulation Stepping Options dialog box. Click the Step Back button arrow then select
Configure Simulation Stepping. In the Simulation Stepping Options dialog box, select Enable
stepping back then click OK.

Because stepping back was not enabled at the start of simulation, the software does not have a
snapshot from a prior time in the simulation. Before you can step back, you must step forward. You
cannot step back to a simulation time before the time you enabled stepping back.

Click Step Forward twice. Then, click Step Back. In the status bar, the simulation time updates to
reflect the step back. The port value labels also update to display the value from the time to which
you stepped back.

When you click Step Back a second time, the software disables the Step Back button because you
cannot step back farther in this simulation.

Finish or Stop Simulation


When you are done stepping through the simulation, you can continue the simulation until the end or
stop the simulation at the current time step.

To run the simulation through the simulation stop time, in the Simulation tab, click Continue.

To stop the simulation at the current time step, in the Simulation tab, click Stop.

See Also
Simulation Stepping Options | Breakpoints List

2-5
2 Step Through Simulations

Related Examples
• “Debug Simulation Using Signal Breakpoints” on page 2-12
• “How Stepping Through Simulation Works” on page 2-7
• “Debug Simulation of Iterator Subsystem” on page 37-7

2-6
How Stepping Through Simulation Works

How Stepping Through Simulation Works

In this section...
“Stepping Forward” on page 2-7
“Capturing Simulation Snapshots” on page 2-8
“Stepping Back” on page 2-9
“Pausing on Breakpoints” on page 2-9
“Additional Considerations for Stepping Through Simulation” on page 2-10

The parameter values you specify in the Simulation Stepping Options dialog box affect how the
software:

• Advances the simulation when you click Step Forward or Step Back
• Captures snapshots of the model operating point to support stepping back

When you step forward in simulation, the software continues the simulation. However, when you step
backward, the software does not simulate the model in reverse. To support stepping backward in a
simulation, the software captures snapshots of the model operating point as the simulation runs.
When you click Step Back, the software restores the model operating point from one of the
snapshots.

Note The software collects simulation snapshots for stepping back only when stepping back is
enabled. When you enable stepping back for a simulation that is in progress, you must step forward
before you can step back. You cannot step back to a point in the simulation before you enabled
stepping back.

The simulation snapshots contain the same model operating point information that is logged when
you select Save final operating point on the Data Import/Export pane of the Configuration
Parameters dialog box. The software captures the model operating point information in the simulation
snapshots only to support stepping back. The simulation snapshots the software captures for stepping
back are not accessible during or after simulation. For more information about saving the model
operating point, see “Save Block States and Simulation Operating Points” on page 78-72.

Stepping Forward
The Move back/forward by parameter specifies the number of major time steps to advance the
simulation each time you click Step Forward. The image illustrates how the simulation advances
based on whether the Move back/forward by option is specified as 1 or 2:

• At the start of the simulation, State 0, the parameter value is 2. When you click Step Forward,
the simulation advances through State 1 and pauses on State 2.
• While paused after the second major time step, suppose you change the parameter value to 1.
Now, when you click Step Forward, the simulation advances to State 3, which corresponds to the
next time step.
• Suppose you change the parameter value back to 2 while paused after the fourth major time step.
Now, when you click Step Forward, the simulation advances to State 6.

2-7
2 Step Through Simulations

Capturing Simulation Snapshots


The simulation snapshots that the software collects for stepping backward contain all the information
required to continue the simulation from the point at which the snapshot was taken. Collecting the
snapshots requires memory and can affect simulation performance. When you configure the
simulation stepping options, you can specify:

• Maximum number of saved back steps — Total number of snapshots to save


• Interval between stored back steps — Number of simulation time steps to skip between saving
snapshots

Saving a smaller number of total time steps and skipping steps between snapshots can mitigate the
effect that enabling stepping back has on simulation performance.

The simulation stepping options for saving snapshots are independent of the Move back/forward by
option, which controls how the simulation advances when you click Step Forward or Step Back.

The image illustrates how snapshots are captured when the Interval between stored back steps
parameter value is 3. The software captures a snapshot at the start of the simulation, after the third
major time step, and after the sixth major time step.

You can change the interval between snapshots during simulation when you need to advance the
simulation by smaller increments to analyze a point of interest. For example, the image illustrates
how the simulation in the previous image would capture snapshots if you changed the interval
between snapshots from 3 to 1.

• The software captures a snapshot of State 0 at the start of the simulation.


• After three major time steps, the software captures a snapshot of State 3.
• While paused on State 3, you change the value of the Interval between stored back steps
parameter from 3 to 1.
• The software captures a snapshot of the simulation state for each major time step through State
6.

2-8
How Stepping Through Simulation Works

Stepping Back
The way the software steps back in simulation depends on whether a snapshot exists for the time to
which you step back.

• When a snapshot exists for the time step, the software restores the model operating point
contained in the snapshot.
• When a snapshot does not exist for the time step, the software restores the model operating point
from the last snapshot before the time step then simulates forward

For example, suppose you are paused after the sixth time step in a simulation that:

• Captures a snapshot of the model operating point every three time steps
• Steps backward by one time step each time you click Step Back

When you click Step Back, the software restores the snapshot captured after the third time step and
simulates forward two time steps to pause after the fifth time step.

You can modify the values of tunable parameters while paused during simulation. The software
applies the new parameter value for the next forward step in simulation. Depending on how you
configure the simulation stepping options, the next forward step in simulation might happen when
you click Step Back.

Pausing on Breakpoints
When your model contains enabled breakpoints, the simulation pauses on the breakpoint if the
condition for the breakpoint is met in the process of stepping forward. The software ignores
breakpoints when stepping backward.

By default, the software is configured to pause within a time step as soon as the condition for a
breakpoint is met. When you click Step Forward while paused on a breakpoint, the simulation
advances through the current time step. When you click Step Back, the software steps back to the
start of the current time step. For more information, see Breakpoints List.

2-9
2 Step Through Simulations

Additional Considerations for Stepping Through Simulation


Not all blocks, features, and model configurations support stepping back in simulation. Lack of
support for stepping back does not interrupt a simulation. The software issues a warning when a
model with stepping back enabled does not support stepping back.

Because stepping back relies on the functionality for saving the model operating point, stepping back
is supported only for models that support saving the model operating point. For more information,
see “Additional Considerations for Saving and Restoring Model Operating Points” on page 27-45.

The table summarizes other considerations related to stepping back in simulation for several blocks
and modeling constructs.

Feature or Modeling Pattern Considerations for Stepping Back


Model references If you modify the simulation stepping options for
a referenced model during simulation, the same
options change in the top model. When the
simulation completes, the simulation stepping
options for referenced models revert to their
values before the simulation. The simulation
stepping options for the top model stay the same
as they were at the end of the simulation.
Visualization blocks The visualizations in these blocks do not update
to reflect the result of stepping back:

• Auto Correlator and Cross Correlator


• Spectrum Analyzer and Averaging Spectrum
Analyzer
• Power Spectral Density and Averaging Power
Spectral Density
• Floating Bar Plot
• 3DoF Animation
• MATLAB Animation
• VR Sink
• Blocks that implement a custom visualization
in their output method
MATLAB Function blocks The simulation state after stepping back might be
incorrect for models that contain MATLAB
Function blocks that call C code that contains
static variables or has side effects, such as
writing to a file.

2-10
How Stepping Through Simulation Works

Feature or Modeling Pattern Considerations for Stepping Back


S-functions • S-functions that have Pwork vectors do not
support stepping back if the operating point
compliance is not specified or is specified as
unknown or disallowed. For more information,
see ssSetOperatingPointCompliance.
• Custom visualizations implemented in the
output method of an S-function do not update
to reflect stepping back.

Block output methods might not execute when


you step backward in simulation. While the
block states remain consistent with the
simulation time if the S-function complies with
model operating point, the visualization does
not update until the next forward step in the
simulation.

See Also
Simulation Stepping Options | Breakpoints List

Related Examples
• “Step Through Simulation” on page 2-2
• “Debug Simulation Using Signal Breakpoints” on page 2-12
• “Debug Simulation of Iterator Subsystem” on page 37-7

2-11
2 Step Through Simulations

Debug Simulation Using Signal Breakpoints

This example shows how to:

• Pause simulation at a specified time.


• View signal values in the block diagram using port value labels.
• Pause simulation at points of interest using signal breakpoints.
• Step through a time step block by block.
• View the execution order in the block diagram.

You can also step through a simulation from the beginning. For an example that shows how to step a
simulation from the start and configure options for stepping through time steps and stepping back,
see “Step Through Simulation” on page 2-2.

Open and Configure Model


Open the model vdp, which implements the Van der Pol equation. For more information about the
model, see “Van der Pol Oscillator”.

openExample("simulink_general/VanDerPolOscillatorExample",...
supportingFile="vdp")

You might run several simulations while analyzing and debugging your model. To save time by
compiling the model only before the first simulation, enable fast restart. In the Simulink Toolstrip, on
the Simulation tab, click Fast Restart.

Specify Time to Pause Simulation


Suppose you know you need to analyze the behavior of your model around a certain time in the
simulation. You can run the simulation without interruption up to the time you specify as the Pause
Time. For this example, specify a pause time of 2 seconds.

2-12
Debug Simulation Using Signal Breakpoints

In the Simulink Toolstrip, on the Debug tab, in the Breakpoints section, specify the Pause Time as
2. Then, to start the simulation, click Run.

Because this is the first simulation, the model compiles before starting the simulation. Then, the
simulation pauses after the major time hit that happens at a simulation time of 2.079 seconds. The
status bar at the bottom of the Simulink Editor displays the current simulation time. Some solvers
perform calculations to determine the time of the next major time hit before the point in the
simulation loop where the simulation pauses when you click Step Forward. In this case, the solver is
ahead in simulation time relative to the block diagram. The asterisk on the simulation time indicates
that the solver has moved ahead in simulation time.

When you specify a pause time, the simulation does not necessarily pause at that exact time. The
solver determines the time steps the simulation takes, and the simulation might not have a major time
hit at the exact time you specify. Instead, the simulation pauses at the end the first major time hit that
occurs at or after the time that you specify.

View Signal Values in Block Diagram


Both before and during simulation, you can add and remove port value labels to view signal values for
each time step in the block diagram. You can add and remove port value labels for individual signals
and for a selection of multiple signals.

For this example, add port value labels for all signals. Click an empty area in the upper left of the
canvas and drag to select everything in the block diagram. Then, on the Debug tab, in the Tools

section, in the Port Values button group, click Show port value label on selected signal . The port
value labels show no data yet until the first forward step in simulation after you add the port value
labels.

Step Through Time Steps


While paused in simulation due to the pause time, you can use the Step Forward and Step Back
buttons to step the simulation through major time steps. Before you can step back, you must enable

2-13
2 Step Through Simulations

stepping back. You can also configure the number of major time steps to advance the simulation each
time you click Step Forward or Step Back. For more information, see “Step Through Simulation” on
page 2-2.

Click Step Forward. The simulation advances forward by one major time step. The port value labels
update to display the signal values from the time step.

You can continue advancing the simulation by clicking Step Forward. As the simulation progresses,
you can observe the signal values using the port value labels and the Scope block in the model.

Set Breakpoint to Pause Simulation


You can use a signal breakpoint to pause the simulation each time a signal value satisfies the
specified condition. When you use signal breakpoints, by default, the simulation pauses within the
time step as soon as the condition is met, just after the block that produces the signal runs its output
method to update the signal value.

You can control whether the simulation pauses within the time step when the condition is met or at
the end of the time step in which the condition is met in the Breakpoints List. When you clear Pause
within time step in the Breakpoints List, the simulation pauses at the end of the time step in which
the condition is met. For more information, see Breakpoints List.

Suppose you want to investigate the behavior of the model when the value of the signal x1 is close to
zero. Specify the condition for the breakpoint as > 0. You could also configure the condition using the
equal (=) relational operator. However, in that case, the breakpoint pauses the simulation only when
the signal has exactly that value. The solver might choose time steps where the signal value is close
to zero but not exactly zero. The signal breakpoint with the condition > 0 pauses the simulation in
the time step just after the signal value passes through zero.

2-14
Debug Simulation Using Signal Breakpoints

To set the signal breakpoint:

1 Select the signal x1.


2 On the Debug tab, in the Breakpoints section, click Add Breakpoint.
3 In the Add Breakpoint menu, select a relational operator to define the condition for the signal
breakpoint. For this example, select greater than >.
4 Specify the value for the breakpoint condition as 0 so that the simulation pauses when the value
of the signal x1 becomes greater than zero.
5 Click OK.

A red circle on the line for the signal x1 indicates that the signal has an enabled breakpoint.

By default, during simulation, clicking a signal line adds or removes the port value label for the line.
To add the port value label for the signal x1, click the signal line again. The port value label displays
no data yet because when you remove a port value label, the software does not retain a history of
signal values. The port value label updates to display the signal value the next time the simulation
advances forward.

To advance the simulation until the breakpoint is hit, click Continue. The simulation pauses when the
signal value becomes greater than zero. The port value label for the signal x1 shows the signal value
that satisfied the breakpoint condition. The breakpoint icon has a red arrow on it that indicates that
the breakpoint caused the simulation to pause. The block that produces the signal is highlighted
green to indicate where the simulation is paused within the time step.

The left side of the status bar provides a detailed simulation status that indicates where the
simulation is paused.

2-15
2 Step Through Simulations

When the simulation is paused on a breakpoint, you can open the Breakpoints List by clicking Open
Breakpoints List near the middle of the status bar.

The green highlight in the Breakpoints List indicates that the simulation is paused on the breakpoint.

Step Block by Block


When the simulation is paused within a time step, the Step Over, Step In, and Step Out buttons
become active, allowing you to step through the time step block by block. To step the simulation to
the next block, click Step Over.

The simulation pauses just before executing the output method for the Outport block. The breakpoint
no longer has the green arrow on it.

The next time you click Step Over, the simulation pauses just before executing the output method for
the Integrator block named x2. When you click Step Over once more, the Integrator block named x2
executes its output method, the port value label updates to display the new signal value, and the
simulation pauses just before executing the output method for the second Outport block.

2-16
Debug Simulation Using Signal Breakpoints

While paused within a time step, you can use some functions from the Simulink debugging
programmatic interface to get additional information about the simulation. For example, you could
use the probe function to view information about a specified block. Port value labels display only
signal values that result from blocks running their output methods in a major time step. When you
use functions from the Simulink debugging programmatic interface, the values displayed might be
different because the functions show results from minor time steps as well.

As you continue to click Step Over to step through the time step, after the Scope block executes its
output method, the simulation pauses with no blocks in the block diagram highlighted green. The
status string on the left side of the status bar indicates that the simulation is paused on a hidden
block. Because the block is hidden, no green highlight appears in the model. In this case, the hidden
block is part of the logging implementation for the Outport blocks.

You can continue stepping the simulation one block at a time through multiple time steps. If you click
Step Forward or Step Back, only the Step Over button remains enabled to allow you to resume
stepping within a time step, block by block.

If you click Step Forward or Step Back, the simulation pauses between time steps, and the Step
Over, Step In, and Step Out buttons are disabled. The Step Over, Step In, and Step Out buttons
are enabled again when the simulation pauses on a breakpoint.

View Execution Order


When you step the simulation block by block, the blocks do not execute based on the layout of the
block diagram. At the start of the simulation, the software determines the execution order for all
tasks and blocks in the model. In each time step, the tasks and blocks execute according to the
execution order.

To understand the order in which the blocks execute as you step, you can view the execution order in
the block diagram. To display the execution order, on the Debug tab, in the Diagnostics section,
click Information Overlays. Then, under Blocks, click Execution Order. The Execution Order
viewer opens on the right of the Simulink Editor with the current task selected. The Execution Order
viewer highlights and annotates the model to indicate the blocks involved in the current task and
their order of execution.

2-17
2 Step Through Simulations

When you first open the Execution Order viewer, the execution order highlighting obscures the green
debugging highlight that indicates where the simulation is paused within the time step. After you
advance the simulation, the green debugging highlight overlays the execution order highlighting. For
example, click Step Over. The simulation pauses on the Integrator block named x1, and the green
highlight around the block overlays the highlighting from the Execution Order viewer. The Execution
Order viewer also highlights the row for the Integrator block named x1 in the Execution Order
Block List.

You can continue to step through the simulation with the execution order highlighting visible in the
block diagram, or you can clear the execution order highlighting to focus on other aspects of
debugging. To clear the execution order highlighting, in the Execution Order viewer, click Clear

Highlighting . To view the execution order again in the block diagram, in the Execution Order
viewer, select the task for which you want to view the execution order.

The execution order highlighting overlays the green debugging highlight that indicates where the
simulation is paused, even after you advance the simulation.

2-18
Debug Simulation Using Signal Breakpoints

End Simulation Debugging Session


When you are done analyzing and debugging your model, you can end the simulation debugging
session in one of several ways, depending on what you plan to do next.

To continue the simulation from the current time point and retain the set of breakpoints configured in
the model, disable all breakpoints.

1 To open the Breakpoints List, on the Debug tab, click Breakpoints List.
2 In the Breakpoints List, use the check boxes in the Enable column or the Enable or disable all
breakpoints button to disable all the breakpoints.
3 To resume the simulation, click Continue.

To continue the simulation from the current time point without retaining breakpoints, remove all
breakpoints from the model.

1 To clear all breakpoints in the model, on the Debug tab, click the Add Breakpoint button arrow
and select Clear All Breakpoints.
2 To resume simulation, click Continue.

To stop the simulation at the current time point, in the Simulink Toolstrip, on the Debug tab, click
Stop.

See Also
Simulation Stepping Options | Breakpoints List

Related Examples
• “Debug Simulation of Iterator Subsystem” on page 37-7
• “Step Through Simulation” on page 2-2
• “How Stepping Through Simulation Works” on page 2-7
• “Control and Display Execution Order” on page 40-16

2-19
3

How Simulink Works

• “Simulation Phases in Dynamic Systems” on page 3-2


• “Compare Solvers” on page 3-6
• “Zero-Crossing Detection” on page 3-10
• “Zero-Crossing Detection with Fixed-Step Simulation” on page 3-25
• “Zero-Crossing Algorithms” on page 3-37
• “Algebraic Loop Concepts” on page 3-39
• “Identify Algebraic Loops in Your Model” on page 3-45
• “Remove Algebraic Loops” on page 3-48
• “Modeling Considerations with Algebraic Loops” on page 3-63
• “Use Model Name as Programmatic Interface” on page 3-65
3 How Simulink Works

Simulation Phases in Dynamic Systems


In this section...
“Model Compilation” on page 3-2
“Link Phase” on page 3-2
“Simulation Loop Phase” on page 3-3

Model Compilation
The first phase of simulation occurs when the system’s model is open and you simulate the model. In
the Simulink Editor, click 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.
• Propagates the attributes of a source signal to the inputs of the blocks that it drives in order to
compute previously unspecified attributes in the blocks.
• Performs block reduction optimizations.
• Flattens the model hierarchy by replacing virtual subsystems with the blocks that they contain
(see “Compare Solvers” on page 3-6).
• Determines the block execution order by task-based sorting.
• 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 7-37).

These events are essentially the same as what occurs when you update a diagram. The difference is
that the Simulink software starts model compilation as part of model simulation, where compilation
leads directly into the linking phase, as described in “Link Phase” on page 3-2. In contrast, you
start an explicit model update as a standalone operation on a model.

When you compile a model or model hierarchy, you can cancel model compilation by clicking the
Cancel button next to the progress bar.

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
execution order lists generated during the model compilation phase are used to construct the method
execution lists.

3-2
Simulation Phases in Dynamic Systems

Block Priorities

You can assign update priorities to blocks. The output methods of higher priority blocks are executed
before those of lower priority blocks. These priorities are honored only if they are consistent with its
block execution order.

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 “Compare
Solvers” on page 3-6) used to compute the system's continuous states, the system's fundamental
sample time (see “Sample Times in Systems and Subsystems” on page 7-29), and whether the
system's continuous states have discontinuities (see “Zero-Crossing Detection” on page 3-10).

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.

3-3
3 How Simulink Works

The following flowchart explains how the simulation loop works where k denotes the major step

counter:

Loop Iteration

At each time step, the Simulink engine:

1 Computes the model 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

3-4
Simulation Phases in Dynamic Systems

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 “Compare Solvers” on
page 3-6).

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

See Also

More About
• “Compare Solvers” on page 3-6
• “Simulate a Model Interactively” on page 27-2

3-5
3 How Simulink Works

Compare 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, Simulink provides a set of programs, known as solvers, each of which
embodies a particular approach to solving a model. The Configuration Parameters dialog box allows
you to choose the solver best suited to your model.

Fixed-Step Versus Variable-Step Solvers


You can choose the solvers provided by Simulink based on the way they calculate step size: 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. They reduce the step size to increase
accuracy when a model's states are changing rapidly and increase 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 the
simulation time required to maintain a specified level of accuracy for models with rapidly changing or
piecewise continuous states.

Fixed-step and variable-step solvers compute the next simulation time as the sum of the current
simulation time and the step size. The Type control on the Solver configuration pane allows you to
select the type of solver. With a fixed-step solver, the step size remains constant throughout the
simulation. 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 tolerances that you specify.

The choice between these 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. 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 saving because, for a
given level of accuracy, the solver can dynamically adjust the step size as necessary. This approach
reduces the number of steps required. The fixed-step solver must use a single step size throughout
the simulation, based on the accuracy requirements. To satisfy these requirements throughout the
simulation, the fixed-step solver typically requires a small step.

For example, consider a model that has two sample times, 0.5 and 0.75. To cover execution of both
rates, a fixed-step solver must use a step size of 0.25, the least common denominator for the two
sample times. The time steps for a fixed-step simulation include:

[0.0 0.25 0.5 0.75 1.0 1.25 1.5 ...]

3-6
Compare Solvers

A variable-step solver can take a different step size for each time step. For this model, the variable-
step solver takes a step only when blocks with each sample time execute. The time steps for the
variable-step simulation include:

[0.0 0.5 0.75 1.0 1.5 ...]

To get to a simulation time of 1.5, the fixed-step simulation required seven steps, while the variable-
step simulation used only five. As model complexity and simulation durations increase, a variable-step
solver can significantly reduce the number of time steps required to simulate a model.

Continuous Versus Discrete Solvers


Simulink provides both continuous and discrete solvers.

When you select a solver type, you can also select a specific solver. Both sets of solvers include
discrete and continuous solvers. 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. When choosing a
solver, determine first whether 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 your model has only continuous states or a mix of continuous
and discrete states, choose a continuous solver from the remaining solver choices based on the
dynamics of your model. Otherwise, an error occurs.

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.

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.

The solver library contains two discrete solvers: a fixed-step discrete solver and a variable-step
discrete solver. The fixed-step solver by default chooses the step size and 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
adjustment can avoid unnecessary steps and shorten simulation time for multirate models. See
“Sample Times in Systems and Subsystems” on page 7-29 for more information.

Note You must use a continuous solver to solve a model that contains both continuous and discrete
states 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.

Explicit Versus Implicit Continuous Solvers


You represent an explicit system by an equation

ẋ = f (x)

3-7
3 How Simulink Works

For any given value of x, you can compute ẋ by substituting x in f(x) and evaluating the equation.

Equations of the form

F(ẋ, x) = 0

are considered to be implicit. For any given value of x, you must solve this equation to calculate ẋ .

A linearly implicit system can be represented by the equation

M(x) . ẋ = f (x)

M(x) is called the mass matrix and f (x) is the forcing function. A system becomes linearly implicit
when you use physical modeling blocks in the model.

While you can apply an implicit or explicit continuous solver to solve all these systems, implicit
solvers are generally better for solving stiff systems. Explicit solvers solve nonstiff systems. An
ordinary differential equation problem is said to be stiff if the desired solution varies slowly, but there
are closer solutions that vary rapidly. The numerical method must then take small time steps to solve
the system. Stiffness is an efficiency issue. The more stiff a system, the longer it takes to for the
explicit solver to perform a computation. A stiff system has both slowly and quickly varying
continuous dynamics.

When compared to explicit solvers, implicit solvers provide greater stability for oscillatory behavior.
However, implicit solvers 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 “Choose a Jacobian Method for an
Implicit Solver” on page 27-13 for more information. Implicit solvers are more efficient than explicit
solvers for solving a linearly implicit system.

One-Step Versus Multistep Continuous Solvers


The Simulink solver library provides both one-step and multistep solvers. The one-step solvers
estimate using the solution at the immediately preceding time point, , and the values of
the derivative at multiple points between tn and tn-1. These points are minor steps.

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.

Single-Order Versus Variable-Order Continuous Solvers


This distinction is based on the number of orders that the solver uses to solve the system of equation.
Two variable-order solvers, ode15s and ode113, are part of the solver library. They 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 equations. For ode15s, you can limit the highest order applied via the
Maximum Order parameter. For more information, see “Maximum Order” on page 27-22.

3-8
Compare Solvers

See Also
“Zero-Crossing Detection” on page 3-10 | “Simulink Models” | “Simulation Phases in Dynamic
Systems” on page 3-2

3-9
3 How Simulink Works

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.

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

Simulink uses two algorithms for this purpose: nonadaptive and adaptive. For information about
these techniques, see “Zero-Crossing Algorithms” on page 3-37.

Demonstrating Effects of Excessive Zero-Crossing Detection

This example provides three models that illustrate zero-crossing behavior:


example_bounce_two_integrators, example_doublebounce, and example_bounce.

The example_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 example_bounce model uses a better model design, implementing the dynamics of the ball
using a double integrator, than example_bounce_two_integrators.

The example_doublebounce model demonstrates how the adaptive algorithm successfully solves a
complex system with two distinct zero-crossing requirements.

Consider the example_bounce_two_integrators model. It uses two single integrators to compute


the vertical velocity and position of the ball over the time of the simulation.

1 Open the model by running open_system('example_bounce_two_integrators') at the


command line.
2 Once the block diagram appears, set the Solver details > Zero-crossing options > Algorithm
parameter in the Solver pane of the Model configuration parameters to Nonadaptive. Set the
stop time of the model to 20 s. You can change this setting in the Simulink toolstrip or the Solver
pane of the model configuration parameters.
3 Simulate the model.

3-10
Zero-Crossing Detection

You can now view and analyze the simulation results.

3-11
3 How Simulink Works

Upon closer examination of the last portion of the simulation, you will see that velocity hovers just
above zero.

3-12
Zero-Crossing Detection

Change the simulation Stop time to 25 s and simulate the model. The simulation stops with an error
due to excessive consecutive zero-crossing events at the Compare To Zero and Position blocks.

Simulink will stop the simulation of model 'example_bounce_two_integrators' because the 2 zero cr
--------------------------------------------------------------------------------
Number of consecutive zero-crossings : 1000
Zero-crossing signal name : RelopInput
Block type : RelationalOperator
Block path : 'example_bounce_two_integrators/Compare To Zero/Compare'
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Number of consecutive zero-crossings : 500
Zero-crossing signal name : x Lower Saturation
Block type : Integrator
Block path : 'example_bounce_two_integrators/Position'
--------------------------------------------------------------------------------

Although you can increase this limit by adjusting the Model Configuration Parameters > Solver >
Number of consecutive zero crossings parameter, making that change still does not allow the
simulation to go on for 25 s.

Change the Solver details > Zero-crossing options > Algorithm parameter in the Solver pane of
the Model configuration parameters to Adaptive and simulate the model again for 25 s.

3-13
3 How Simulink Works

Zooming in on the last 5 seconds of the simulation, you can see that the results are more complete
and closer to the expected analytical solution of the dynamics of a bouncing ball. The amount of
chatter you see is a consequence of the system's states approaching zero and is expected in
numerical simulations.

3-14
Zero-Crossing Detection

The example_bounce model uses a Second-Order Integrator block to model the dynamics of the
bouncing ball. This is the preferred method to model the double integration of the ball's dynamics for
solver performance. To compare the solver performance for example_bounce_two_integrators
and example_bounce, try running the Solver Profiler on both models. For a detailed comparison of
both models, see “Simulation of Bouncing Ball”.

3-15
3 How Simulink Works

For a side-by-side comparison of adaptive and nonadaptive zero-crossing detection algorithms, see
“Double Bouncing Ball: Use of Adaptive Zero-Crossing Location”.

3-16
Zero-Crossing Detection

3-17
3 How Simulink Works

Preventing Excessive Zero Crossings

Use the following table to prevent excessive zero-crossing errors in your model.

Change Type Change Procedure Benefits


Increase the number of Increase the value of the Number of This may give your model enough
allowed zero crossings consecutive zero crossings. option time to resolve the zero crossing.
on the Solver pane in the
Configuration Parameters dialog box.
Relax the Signal Select Adaptive from the Algorithm The solver requires less time to
threshold pull down and increase the value of precisely locate the zero crossing.
the Signal threshold option on the This can reduce simulation time and
Solver pane in the Configuration eliminate an excessive number of
Parameters dialog box. consecutive zero-crossing errors.
However, relaxing the Signal
threshold may reduce accuracy.

3-18
Zero-Crossing Detection

Change Type Change Procedure Benefits


Use the Adaptive Select Adaptive from the Algorithm This algorithm dynamically adjusts
algorithm drop-down on the Solver pane in the the zero-crossing threshold, which
Configuration Parameters dialog box. 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.
Disable zero-crossing 1 Clear the Enable zero-crossing Locally disabling zero-crossing
detection for a specific detection check box on the detection prevents a specific block
block block's parameter dialog box. from stopping the simulation because
2 Select Use local settings of excessive consecutive zero
from the Zero-crossing control crossings. All other blocks continue
pull down on the Solver pane of to benefit from the increased
the Configuration Parameters accuracy that zero-crossing detection
dialog box. provides.

Disable zero-crossing Select Disable all from the Zero- This prevents zero crossings from
detection for the entire crossing control pull down on the being detected anywhere in your
model Solver pane of the Configuration model. A consequence is that your
Parameters dialog box. model no longer benefits from the
increased accuracy that zero-
crossing detection provides.
If using the ode15s Select a value from the Maximum For more information, see Maximum
solver, consider order pull down on the Solver pane order.
adjusting the order of of the Configuration Parameters
the numerical dialog box.
differentiation
formulas
Reduce the maximum Enter a value for the Max step The solver takes steps small enough
step size size option on the Solver pane of to resolve the zero crossing.
the Configuration Parameters dialog However, reducing the step size can
box. increase simulation time, and is
seldom necessary when using the
adaptive algorithm.

How the Simulator Can Miss Zero-Crossing Events


The bounce and double-bounce models, in “Simulation of Bouncing Ball” and “Double Bouncing Ball:
Use of Adaptive Zero-Crossing Location” 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 searches 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.

3-19
3 How Simulink Works

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
sign change and therefore detects the zero-crossing event.

Consider the two-integrator implementation of the bounce model.

Profiling of the last 0.5 s of the simulation using the Solver Profiler shows that the simulation detects
44 zero-crossing events at the Compare To Zero block and 22 events at the output of the Position
block.

3-20
Zero-Crossing Detection

Increase the value of the Relative tolerance parameter to 1e-2 instead of the default 1e-3. You can
change this parameter in the Solver Details section of the Solver pane in the Configuration
Parameters dialog or using set_param to specify RelTol as '1e-2'.

Profiling the last 0.5 s of the simulation with the new relative tolerance of the solver shows that it
detects only 24 zero-crossing events at the Compare To Zero block and 12 events at the output of the
Position block.

3-21
3 How Simulink Works

Zero-Crossing Detection in Blocks


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.

Note The Zero-Crossing detection algorithm can bracket zero-crossing events only for signals of data
type double.

Blocks That Register Zero Crossings

The following table lists blocks that register zero crossings and explains how the blocks use the zero
crossings.

Block Number of Zero Crossing Detections


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

3-22
Zero-Crossing Detection

Block Number of Zero Crossing Detections


Enable One, If an Enable port is inside of a Subsystem block, it provides the
capability to detect zero crossings. For details, “Using Enabled
Subsystems” on page 10-12.
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
Hit Crossing One or two. If there is no output port, there is only one zero crossing to
detect when the input signal hit the threshold value. If there is an output
port, the second zero crossing is used to bring the output back to 0 from 1
to create an impulse-like output.
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.
MinMax One, for each element of the output vector, to detect when an input signal
is the new minimum or maximum.
Rate Limiter Dynamic Two, one to detect upper limit and the other to detect lower limit
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.
Saturation Dynamic Two, one to detect upper limit and the other to detect lower limit
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 Editor 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.
Trigger One, If a Triggered port is inside of a Subsystem block, it provides the
capability to detect zero crossings. For details, see “Using Triggered
Subsystems” on page 10-18.
Enabled and Triggered Two, one for the enable port and one for the trigger port. For details, see:
Subsystem “Using Enabled and Triggered Subsystems” on page 10-21
From Spreadsheet One, to detect when the input signal has a discontinuity in either the
rising or falling direction.

3-23
3 How Simulink Works

Note Zero-crossing detection is also available for a Stateflow chart that uses continuous-time mode.
See “Configure a Stateflow Chart for Continuous-Time Simulation” (Stateflow) 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-22 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:

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

See Also

More About
• “Algebraic Loop Concepts” on page 3-39
• “Compare Solvers” on page 3-6

3-24
Zero-Crossing Detection with Fixed-Step Simulation

Zero-Crossing Detection with Fixed-Step Simulation


Models with both continuous states and discontinuous signals may require a small fixed-step size to
obtain accurate simulation results near discontinuities. With fixed-step zero crossing enabled,
Simulink can automatically detect and locate discontinuities and correct the continuous states in the
model. This functionality allows you to use a larger step size and enables faster simulation times
without affecting simulation accuracy.

You may find fixed-step zero-crossing detection useful if your model contains:

• Continuous states
• Blocks with zero-crossings driven by signals with continuous sample time
• Frequent switching or other events that limit solver step-size

Effects of Zero-Crossing Detection in Fixed-Step


Consider a self-resetting integrator that can be used to generate a sawtooth wave where the state is
reset to 1/3 each time it reaches a value of 1. Simulating in variable-step with zero-crossing detection
shows the expected results, or baseline, for this model.

model = 'mSelfResetIntegrator';
open_system(model);

set_param(model, 'Solver', 'ode23');


simoutVS = sim(model);
figure();
plot(simoutVS.tout, simoutVS.xout);
legend('Variable-Step (baseline)',...
'Location', 'southeast');

The sawtooth wave generated using variable-step simulation is used as a baseline.

3-25
3 How Simulink Works

Simulate in Fixed-Step Without Zero-Crossing Detection


You can use a fixed-step solver like ode3 to simulate this model with default fixed-step size equal to
0.2. However, the simulation results are not very accurate for this step size. The fixed-step size must
be decreased to about 0.001 for the simulation results that align with the expected result.
set_param(model, 'Solver', 'ode3', ...
'FixedStep', '0.2');
simoutFS = sim(model);

plot(simoutVS.tout, simoutVS.xout, ...


simoutFS.tout, simoutFS.xout, '-x');
title('Fixed-step size = 0.2');
legend('Variable-Step (baseline)', 'Fixed-step (Zero-Crossing Disabled)',...
'Location', 'southeast');

3-26
Zero-Crossing Detection with Fixed-Step Simulation

set_param(model, 'FixedStep', '.001');


simoutFS2 = sim(model);

plot(simoutVS.tout, simoutVS.xout, ...


simoutFS2.tout, simoutFS2.xout, '-x');
title('Fixed-step size = 0.001');
legend('Variable-Step (baseline)', 'Fixed-step (Zero-Crossing Disabled)',...
'Location', 'southeast');

3-27
3 How Simulink Works

Enable Fixed-Step Zero-Crossing Detection


Zero-crossing detection can be enabled for this model by selecting Enable zero-crossing detection for
fixed-step simulation. You can also set the step size back to 0.2 and simulate. Note that despite this
substantial increase in step size, each state value in this simulation coincides with the expected
result. Thus, zero-crossing detection for fixed-step simulation results in faster simulation times for
this model.
set_param(model, 'FixedStep', '0.2', ...
'EnableFixedStepZeroCrossing', 'on');

simoutFSZC = sim(model);
plot(simoutVS.tout, simoutVS.xout, ...
simoutFSZC.tout, simoutFSZC.xout, '-x');
title('Fixed-step size = 0.2');
legend('Variable-Step (baseline)', 'Fixed-step (Zero-Crossing Enabled)',...
'Location', 'southeast');

3-28
Zero-Crossing Detection with Fixed-Step Simulation

Set Parameters for Zero-Crossing Detection


You use two main parameters to control zero crossing for fixed-step simulation. These parameters
help ensure that the detection and location of zero-crossing events is fixed-cost. Go to the Solver
Details > Zero-crossing options section of the configuration parameters to access the parameters.

Maximum Number of Bracketing Iterations

The Maximum number of bracketing iterations parameter limits the number of search iterations
used by Simulink for locating a zero-crossing event once the event has been detected. In general, a
higher number of bracketing iterations will provide a more accurate event location, but this option is
computationally costly.

Consider this model with a sine wave driving a Hit Crossing block. Zero-crossings are detected when
the Hit Crossing block detects that its input signal has crossed zero, which should occur at multiples
of pi. The scope displays this result.

3-29
3 How Simulink Works

model = 'mFixedStepZcParameters';
open_system(model);
set_param(model, 'Solver', 'VariableStepAuto');
sim(model);

Too few bracketing iterations results in locating zero crossings with less accuracy. To see the number
of bracketing iterations simulation results, enable fixed-step zero-crossing, change to a fixed-step
solver, and set the Maximum number of zero-crossings per step parameter to 2. Use a fixed-step
size of 0.5.

3-30
Zero-Crossing Detection with Fixed-Step Simulation

set_param(model, 'EnableFixedStepZeroCrossing', 'on',...


'MaxZcBracketingIterations', '2',...
'SolverName', 'ode3',...
'FixedStep', '0.5');

Increasing the number of bracketing iterations to 4 results in more accurate location of the events in
this model. The zero crossing is located closer to the expected value of pi.

set_param(model, 'MaxZcBracketingIterations', '4');

Maximum Number of Zero-Crossings per Step

Use Maximum number of zero-crossings per step parameter to limit the maximum number of
zero crossings that Simulink will locate in one simulation time step. Once this maximum number is
reached in a step, any additional zero-crossings that occur within that step are ignored. To see how
this can affect simulation results, consider the following example. Set the Sine Wave block to output
two sine waves that are slightly offset by using scalar expansion on the 'Bias' parameter of the sine
wave block. Two zero crossing events should be located near pi.
sineWaveBlock = [model '/Sine Wave'];
set_param(sineWaveBlock, 'Bias', '[0.0 0.1]');
set_param(model, 'Solver', 'ode45');
simoutVS = sim(model);

3-31
3 How Simulink Works

Setting the maximum number of zero-crossings to locate per step to 1 will restrict Simulink to only
locating the first zero crossing that occurs within a single time step. In this example, Simulink only
locates the first zero-crossing in the step at pi in the step from t = 3 to t = 3.5. As a result, the second
state of the Integrator block is less accurate due to the missed zero crossing.
set_param(model, 'Solver', 'ode3',...
'EnableFixedStepZeroCrossing', 'on',...
'MaxZcPerStep', '1');
simoutFS_1ZC = sim(model);
f = figure();
tiledlayout(f,'flow','TileSpacing','compact','Padding','compact');
nexttile;
plot(simoutVS.tout, simoutVS.xout.signals(1).values(:, 1),...
simoutFS_1ZC.tout,simoutFS_1ZC.xout.signals(1).values(:,1), '-x');
title('State 1')
nexttile;
plot(simoutVS.tout, simoutVS.xout.signals(1).values(:,2),...
simoutFS_1ZC.tout,simoutFS_1ZC.xout.signals(1).values(:,2), '-x');
title('State 2')
legend('Variable-Step (Expected Result)', 'Fixed-Step with One Zc Per Step',...
'Location', 'northwest');

3-32
Zero-Crossing Detection with Fixed-Step Simulation

3-33
3 How Simulink Works

Since you know to expect a maximum of two zero crossings to be located within the fixed-step size of
0.5, setting the Maximum number of zero-crossings per step parameter to 2 should yield more
accurate simulation results. This plot shows that both continuous states of the Integrator block match
the expected result.
set_param(model, 'MaxZcPerStep', '2')
simoutFS_2ZC = sim(model);
f = figure();
tiledlayout(f,'flow','TileSpacing','compact','Padding','compact');
nexttile;
plot(simoutVS.tout, simoutVS.xout.signals(1).values(:, 1),...
simoutFS_2ZC.tout,simoutFS_2ZC.xout.signals(1).values(:,1), '-x');
title('State 1')
nexttile;
plot(simoutVS.tout, simoutVS.xout.signals(1).values(:,2),...
simoutFS_2ZC.tout,simoutFS_2ZC.xout.signals(1).values(:,2), '-x');
title('State 2')
legend('Variable-Step (Expected Result)', 'Fixed-Step with Two Zc Per Step',...
'Location', 'northwest');

3-34
Zero-Crossing Detection with Fixed-Step Simulation

3-35
3 How Simulink Works

See Also
Maximum number of bracketing iterations | Enable zero-crossing detection for fixed-step simulation |
Maximum number of zero-crossings per step | “Zero-Crossing Detection” on page 3-10 | “Zero-
Crossing Algorithms” on page 3-37

3-36
Zero-Crossing Algorithms

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

Signal Threshold for Adaptive Zero-Crossing Detection


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.

3-37
3 How Simulink Works

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-38
Algebraic Loop Concepts

Algebraic Loop Concepts


In this section...
“Mathematical Interpretation” on page 3-40
“Physical Interpretation” on page 3-41
“Artificial Algebraic Loops” on page 3-41
“How the Algebraic Loop Solver Works” on page 3-42
“Implications of Algebraic Loops in a Model” on page 3-44

An algebraic loop occurs when a signal loop in a model contains only blocks that have direct
feedthrough. Direct feedthrough refers to blocks that use the input value for the current time step to
calculate the output value for the current time step. A signal loop that contains only blocks with
direct feedthrough creates a circular dependency of block output and input values in the same time
step. The resulting equation is an algebraic equation that requires a solution at each time step and
adds computational cost.

Some blocks always have direct feedthrough, while others have direct feedthrough only for certain
block configurations. Examples of blocks with direct feedthrough include:

• Math Function
• Gain
• Product
• State-Space block with a nonzero D matrix
• Sum
• Transfer Fcn block with a numerator order that is the same as the denominator order
• Zero-Pole block with the same number of zeros and poles

Blocks that do not have direct feedthrough maintain one or more state variables that store input
values from prior time steps. Examples of blocks that do not have direct feedthrough include the
Integrator block and the Unit Delay block.

Tip To determine whether a block has direct feedthrough, refer to the Block Characteristics table on
the block reference page. To view the block characteristics for all blocks, use the Block Support Table
block or the showblockdatatypetable function.

Consider a model that contains a Sum block that subtracts the block output value xa from the input
value u.

The model implements this equation

3-39
3 How Simulink Works

xa = u – xa.

For this simple loop, the solution is xa = u/2.

Mathematical Interpretation
The software has several numerical solvers for simulating ordinary differential equations (ODEs).
ODEs are systems of equations that you can write as

ẋ = f (x, t),

where x is the state vector and t is the independent time variable.

Some systems of equations include additional constraints that involve the independent variable and
the state vector, but not the derivative of the state vector. Such systems are called differential
algebraic equations (DAEs).

The term algebraic refers to equations that do not involve derivatives. You can express DAEs that
arise in engineering in the semi-explicit form

ẋ = f(x, xa, t)
0 = g(x, xa, t),

where:

• 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 a model, an algebraic loop represents an algebraic constraint. Models with algebraic loops define a
system of differential algebraic equations. The software solves the algebraic loop numerically for xa at
each step of a simulation that uses an ODE solver.

Consider this model that implements a simple system of DAEs. The inner loop represents an algebraic
constraint, while the outer loop represents a differential equation.

The model implements this system of DAEs.


x' = xa
0 = u - x - 2xa

For each step the ODE solver takes, the algebraic loop solver must solve the algebraic constraint for
xa before calculating the derivative x'.

3-40
Algebraic Loop Concepts

Physical Interpretation
Algebraic constraints:

• Occur when modeling physical systems, often due to conservation laws, such as conservation of
mass and energy
• Occur when you choose a particular coordinate system for a model
• Help impose design constraints on system responses in a dynamic system

Use Simscape to model systems that span mechanical, electrical, hydraulic, and other physical
domains as physical networks. Simscape constructs the DAEs that characterize the behavior of a
model. The software integrates these equations with the rest of the model and then solves the DAEs
directly. Simulink solves the variables for the components in the different physical domains
simultaneously, avoiding problems with algebraic loops.

Artificial Algebraic Loops

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 a direct
feedthrough from the input to the output. When you create an atomic subsystem, all Inport blocks are
direct feedthrough, resulting in an algebraic loop.

Start with the included model, which represents a simple proportional control of the plant described
by

which can be rewritten in state-space form as

The system has neither algebraic variables nor direct feedthrough and does not contain an algebraic
loop.

Modify the model as described in the following steps:

1 Enclose the Controller and Plant blocks in a subsystem.


2 In the subsystem dialog box, select Treat as atomic unit to make the subsystem atomic.

3-41
3 How Simulink Works

3 In the Diagnostics pane of the Model Configuration Parameters, set the Algebraic Loop
parameter to error.

When simulating this model, an algebraic loop occurs because the subsystem is direct feedthrough,
even though the path within the atomic subsystem is not direct feedthrough. Simulation stops with an
algebraic loop error.

How the Algebraic Loop Solver Works


When a model contains an algebraic loop, Simulink 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 there is one. As a result, models with algebraic loops can run more slowly than models
without algebraic loops.

Simulink uses a dogleg trust region algorithm to solve algebraic loops. The tolerance used is smaller
than the ODE solver Reltol and Abstol. This is because Simulink uses the “explicit ODE method”
to solve Index-1 differential algebraic equations (DAEs).

For the algebraic loop solver to work,

• There must be one block where the loop solver can break the loop and attempt to solve the loop.
• The model should have 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 this way:

xa(t) = u(t) / 2. (3-1)

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 can fail.

3-42
Algebraic Loop Concepts

For more information, see Solving Index-1 DAEs in MATLAB and Simulink 1

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
• Line-Search

By default, Simulink chooses the best algebraic loop solver and may switch between the two methods
during simulation. To explicitly enable automatic algebraic loop solver selection for your model, at the
MATLAB command line, enter:

set_param(model_name, 'AlgebraicLoopSolver','Auto');

To switch to the trust-region algorithm, at the MATLAB command line, enter:

set_param(model_name, 'AlgebraicLoopSolver', 'TrustRegion');

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');

For more information, see:

• Shampine and Reichelt’s nleqn.m code


• The Fortran program HYBRD1 in the User Guide for MINPACK-1 2
• Powell’s “A Fortran subroutine for solving systems in nonlinear equations,” in Numerical Methods
for Nonlinear Algebraic Equations3
• “Trust-Region Methods for Nonlinear Minimization” (Optimization Toolbox).
• “Line Search” (Optimization Toolbox).

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
• Stateflow charts

1 Shampine, Lawrence F., M.W.Reichelt, and J.A.Kierzenka. ”Solving Index-1 DAEs in MATLAB and Simulink.”Siam
Review.Vol.18,No.3,1999,pp.538–552.
2 More,J.J.,B.S.Garbow, and K.E.Hillstrom. User guide for MINPACK-1. Argonne, IL:Argonne National Laboratory,1980.
3 Rabinowitz, Philip, ed. Numerical Methods for Nonlinear Algebraic Equations, New York: Gordon and Breach Science
Publishers, 1970.

3-43
3 How Simulink Works

Implications of Algebraic Loops in a Model


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

See Also
Algebraic Constraint | Descriptor State-Space

More About
• “Identify Algebraic Loops in Your Model” on page 3-45
• “Remove Algebraic Loops” on page 3-48
• “Modeling Considerations with Algebraic Loops” on page 3-63

3-44
Identify Algebraic Loops in Your Model

Identify Algebraic Loops in Your Model

If Simulink reports an algebraic loop in your model, the algebraic loop solver may be able to solve the
loop. If Simulink cannot solve the loop, there are several techniques to eliminate the loop.

Use this workflow to decide how you want to eliminate an algebraic loop.

3-45
3 How Simulink Works

Highlight Algebraic Loops in the Model


Use getAlgebraicLoops to identify algebraic loops in a model and highlight them in the Simulink
Editor. With this approach:

• You can traverse multiple layers of model hierarchy to locate algebraic loops.
• You can identify real and artificial algebraic loops.
• You can visualize all loops in your model simultaneously.
• You do not need to drill in and out of the model, across boundaries.
• You do not need to detect loops in serial order. Also, you do not need to compile the model every
time you detect and solve a loop. Therefore you can solve loops quickly.

You perform algebraic loop highlighting on an entire model, not on specific subsystems.

1 Open the model.


2 In the Diagnostics pane of Model Configuration Parameters, set Algebraic loop to none or
warning. Setting this parameter to error prevents the model from compiling.
3 Compile the model without any errors. The model must compile before you can highlight any
algebraic loops.
4 At the MATLAB command prompt, enter:
Simulink.BlockDiagram.getAlgebraicLoops(bdroot)

The getAlgebraicLoops function highlights algebraic loops in the model, including algebraic loops
in subsystems. It also creates a report with information about each loop:

• Solid lines represent real algebraic loops.


• Dotted lines represent artificial algebraic loops.
• A red highlight appears around a block assigned with an algebraic variable.
• The Loop ID helps you identify the system that contains a particular loop.

Customize the report by selecting or clearing the Visible check box for a loop.

Once you have identified algebraic loops in a model, you can remove them by editing the model. Close
the highlight report and make changes to the model. You can edit the model only after you close the
report.

Simulink does not save loop highlighting. Closing the model or exiting the display removes the loop
highlighting.

Use the 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.

In the Diagnostics pane of the Model Configuration Parameters, set the Algebraic loop parameter:

• none -- Simulink tries to solve the algebraic loop; reports an error only if the algebraic loop
cannot be solved.

3-46
Identify Algebraic Loops in Your Model

• 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. Review the loop manually before Simulink tries to
solve the loop.

This example shows how to use the algebraic loop diagnostic to highlight algebraic loops in the
sldemo_hydcyl model.

1 Open the sldemo_hydcyl model


2 In the Diagnostics pane of the Model Configuration Parameters, set the Algebraic loop
parameter to error.
3 Try to simulate the model

When Simulink detects an algebraic loop during initialization, the simulation stops. The Diagnostic
Viewer displays an error message and lists all the blocks in the model that are part of that algebraic
loop. In the model, red highlights show the blocks and signals that make up the loop.

To remove the highlights, close the Diagnostic Viewer.

See Also

More About
• “Algebraic Loop Concepts” on page 3-39
• “Remove Algebraic Loops” on page 3-48
• “Modeling Considerations with Algebraic Loops” on page 3-63

3-47
3 How Simulink Works

Remove Algebraic Loops


Use these techniques to remove algebraic loops in a model.

Remove Algebraic Loops by Introducing Delay

Feedback loops can create algebraic loops in a model. You can remove these algebraic loops by
introducing a delay in the loop using the Unit Delay block.

Open the model AlgebraicLoopUnitDelay. The model contains three atomic subsystems, A, B, and
C. The output from subsystem A is an input for subsystem B, and the output from subsystem B is an
input for subsystem C. The output from subsystem C feeds back into subsystem A and subsystem B,
creating two feedback loops.

mdl = "AlgebraicLoop";
open_system(mdl)

To determine whether the model contains algebraic loops, use the


Simulink.BlockDiagram.getAlgebraicLoops function. The function opens the Algebraic Loops
viewer, which shows that the model contains one real algebraic loop.

Simulink.BlockDiagram.getAlgebraicLoops(mdl);

3-48
Remove Algebraic Loops

The Simulink.BlockDiagram.getAlgebraicLoops function highlights the path of the algebraic


loop in the model in yellow and highlights blocks with algebraic variables in red. In the model
AlgebraicLoop, the Gain blocks in the feedback loops are both highlighted as algebraic variables.

In general, to remove algebraic loops from your model, add a delay before or after each algebraic
variable. To see this solution, open the model AlgebraicLoopTwoUnitDelays which is the same as
the model AlgebraicLoop but with a Unit Delay block added after the Gain block in each feedback
loop.

mdl2 = "AlgebraicLoopTwoUnitDelays";
open_system(mdl2)

3-49
3 How Simulink Works

To confirm that the Unit Delay blocks removed the algebraic loops, use the
Simulink.BlockDiagram.getAlgebraicLoops function.

Simulink.BlockDiagram.getAlgebraicLoops(mdl2);

No algebraic loops were found.

With this placement of Unit Delay blocks, subsystem A and subsystem B use the output from
subsystem C from the previous time step.

In this model, you can also remove the algebraic loop by adding a single Unit Delay block between
subsystem B and subsystem C. This signal path is part of both feedback loops, so the delay affects the
path of both algebraic variables. To see this solution, open the model
AlgebraicLoopOneUnitDelay.

mdl3 = "AlgebraicLoopOneUnitDelay";
open_system(mdl3)

To confirm that the model does not contain an algebraic loop, use the
Simulink.BlockDiagram.getAlgebraicLoops function.

Simulink.BlockDiagram.getAlgebraicLoops(mdl3);

3-50
Remove Algebraic Loops

No algebraic loops were found.

With this placement of the Unit Delay block, subsystem C uses the value from the previous time step
for the output from subsystem B to produce the feedback value for the current time step.

Solve Algebraic Loops Manually


If the solver is unable to solve the algebraic loop, the software issues an error. Use one of these
techniques to solve the loop manually:

• 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.
• Only for a legitimate algebraic loop, specify an initial guess for the algebraic states in the loop to
help the algebraic loop solver converge. You can specify the initial guess one of these ways:

• Place an IC block in the algebraic loop.


• Specify an initial guess for a signal in an algebraic loop using an Algebraic Constraint block.

How the Software Eliminates Artificial Algebraic Loops


When you enable the Minimize algebraic loop occurrences parameter, the software tries to
eliminate artificial algebraic loops. In this example, the model contains an atomic subsystem that
causes an artificial algebraic loop.

The contents of the atomic subsystem do not have direct feedthrough, but the software identifies the
atomic subsystem as having direct feedthrough.

3-51
3 How Simulink Works

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 eliminate this algebraic loop,

1 Create the model from the preceding graphics, with the atomic subsystem that causes the
artificial algebraic loop.
2 In the Diagnostics pane of Model Configuration Parameters, set the Algebraic loop parameter
to warning or none.
3 To display the block execution order for this model and the atomic subsystem, in the Debug tab,
select Information Overlays > Execution Order.

Reviewing the execution order can 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-52
Remove Algebraic Loops

Note For more information about block execution order, see “Control and Display Execution
Order” on page 40-16.
4 In the top-level model’s Subsystem Parameters dialog box, select Minimize algebraic loop
occurrences. This parameter directs the software to try to eliminate the algebraic loop that
contains the atomic subsystem when you simulate the model.
5 Save the changes.
6 In the Modeling tab, click Update Model to recalculate the execution order.

Now there are two levels of execution order inside the subsystem: 1 and 2.

3-53
3 How Simulink Works

To eliminate the artificial algebraic loop, the software tries to adjust the execution order so that the
subsystem or model reference does not have direct feedthrough.

When you simulate a model, all blocks execute methods in this order:

1 mdlOutputs
2 mdlDerivatives
3 mdlUpdate

In the original version of this model, the execution of the mdlOutputs method starts with the Plant
block because the Plant block does not have direct feedthrough. The execution finishes with the
Controller block.

3-54
Remove Algebraic Loops

For more information about these methods, see “Simulink Models”.

If you enable the Minimize algebraic loop occurrences parameter for the atomic subsystem, the
software divides the subsystem into two atomic units.

3-55
3 How Simulink Works

These conditions are true:

• Atomic unit 2 does not have direct feedthrough.


• Atomic unit 1 has only a mdlOutputs method.

Only the mdlDerivatives or mdlUpdate methods of Atomic unit 2 need the output of Atomic unit 1.
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:

1 mdlOutputs method of model

a mdlOutputs method of Atomic unit 2


b mdlOutputs methods of other blocks
2 mdlDerivatives method of model

a mdlOutputs method of Atomic unit 1


b mdlDerivatives method of Atomic unit 2
c 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 and must
not contain any signals designated as test points. The software can then set the
DirectFeedthrough property of the block Inport to false to indicate that the input port does not
have direct feedthrough.

Eliminate Artificial Algebraic Loops Caused by Atomic Subsystems


If an atomic subsystem causes an artificial algebraic loop, convert the atomic subsystem to a virtual
subsystem. When the subsystem is atomic and you simulate the model, Simulink invokes the algebraic
loop solver. The solver terminates after one iteration. The algebraic loop is automatically solved
because there is no algebraic constant. After you make the subsystem virtual, Simulink does not
invoke the algebraic loop solver during simulation.

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 Save the changes.

If you replace the atomic subsystem with a virtual subsystem and the simulation still fails with an
algebraic loop error, examine the model for one of these:

• An algebraic constraint
• An artificial algebraic loop that was not caused by this atomic subsystem

3-56
Remove Algebraic Loops

Bundled Signals That Create Artificial Algebraic Loops


Some models bundle signals together. This bundling can cause Simulink to detect an algebraic loop,
even when an algebraic constraint does not exist. If you redirect one or more signals, you may be
able to remove the artificial algebraic loop.

In this example, a linearized model simulates the dynamics of a two-tank system fed by a single
pump. In this model:

• 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-57
3 How Simulink Works

If you simulate this model with the Algebraic loop parameter set to warn or error, Simulink
identifies the algebraic loop.

To eliminate this algebraic loop:

1 Change the C and D matrices as follows:

3-58
Remove Algebraic Loops

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-59
3 How Simulink Works

Model and Block Parameters to Diagnose and Eliminate 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 Model Referencing pane of Configuration
Parameters, select Minimize algebraic loop occurrences.
• Minimize algebraic loop parameter — Specifies what diagnostic action Simulink takes if the
Minimize algebraic loop occurrences parameter has no effect.

The Minimize algebraic loop parameter is in the Diagnostics pane of Configuration


Parameters. 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 Model Configuration Parameters, 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 generating code.

Enabling block reduction can also help Simulink solve artificial algebraic loops.

Consider the following model.

3-60
Remove Algebraic Loops

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.

If you enable block reduction and execution order, and simulate the model again, Simulink does not
display the execution order for blocks that have been reduced. You can now quickly see which blocks
have been reduced.

3-61
3 How Simulink Works

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.

Tip Use Bus Selector blocks to pass only the required signals into atomic subsystems.

See Also
Unit Delay

More About
• “Algebraic Loop Concepts” on page 3-39
• “Identify Algebraic Loops in Your Model” on page 3-45
• “Modeling Considerations with Algebraic Loops” on page 3-63

3-62
Modeling Considerations with Algebraic Loops

Modeling Considerations with Algebraic Loops

Managing Large Models with Artificial Algebraic Loops


Adopt these design techniques for large models with algebraic loops:

• Avoid creating loops that contain discontinuities or nondouble data types. The 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 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. The software 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.

Model Blocks and Direct Feedthrough

When a Model block is part of a cycle, and the block has direct feedthrough, an algebraic loop can
result. An algebraic loop in a model is not necessarily an error, but it can give unexpected results.
See:

• “Highlight Algebraic Loops in the Model” on page 3-46 for information about seeing algebraic
loops graphically.
• The “Model Configuration Parameters: Diagnostics” pane Algebraic loop option for information on
detecting algebraic loops automatically.

Direct Model Block Feedthrough Caused by Referenced Model Structure

A Model block can be a direct feed through block due to the structure of the referenced model.
Where direct feed through results from sub model structure, and causes an unwanted algebraic loop,
you can:

• Automatically eliminate the algebraic loop using techniques described in:

• Minimize algebraic loop


• Minimize algebraic loop occurrences
• “Remove Algebraic Loops” on page 3-48
• Manually insert the number of Unit Delay blocks needed to break the algebraic loop.

Direct Model Block Feedthrough Caused by Model Configuration

Generic Real Time (grt) and Embedded Real Time (ert) based targets provide the Single output/
update function option on the Configuration Parameters dialog. This option controls whether

3-63
3 How Simulink Works

generated code has separate output and update functions, or a combined output/update function.
See:

• “Configure Generated C Function Interface for Model Entry-Point Functions” (Simulink Coder) for
information about separate and combined output and update functions.
• Single output/update function (Simulink Coder) for information about specifying whether code has
separate or combined functions.

When Single output/update function is enabled (default), a Model block has a combined output/
update function. The function makes the block a direct feed through block for all input ports,
regardless of the structure of the referenced model. Where an unwanted algebraic loop results, you
can:

• Disable Single output/update function. The code for the Model block then has separate output
and update functions, eliminating the direct feed through and hence the algebraic loop.
• Manually insert one or more Unit Delay blocks as needed to break the algebraic loop.

Changing Block Priorities When Using Algebraic Loop Solver


During the updating phase of simulation, Simulink determines the simulation execution order of block
methods. This block invocation ordering is the execution 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.

See Also

More About
• “Algebraic Loop Concepts” on page 3-39
• “Identify Algebraic Loops in Your Model” on page 3-45
• “Remove Algebraic Loops” on page 3-48

3-64
Use Model Name as Programmatic Interface

Use Model Name as Programmatic Interface


You can use the name of a model as a programmatic interface for executing a specified simulation
phase and computing values for individual states and times that you specify.

This functionality is not intended for running a model step by step, simulating a model
programmatically, or for debugging. For those purposes, consider these alternatives:

• To step through a simulation, use the Step Forward and Step Back buttons.

For more information, see “Step Through Simulation” on page 2-2.


• To simulate a model programmatically, use the sim, parsim, and batchsim functions.
• For low-level debugging, use the Simulink debugger.

Model Requirements
When you use the model name as a programmatic interface to compute simulation values, the
software ignores the effects of state transitions and conditional execution. Use this functionality only
for models that implement simple dynamic systems. Such systems must meet these requirements:

• All states in the model must have built-in nonbus data types.

For more information about built-in data types, see “About Data Types in Simulink” on page 73-
2.
• The model must contain a minimal amount of state logic, such as Stateflow charts and
conditionally executed subsystems.
• The model must contain only blocks from Simulink libraries. The model cannot contain S-functions
or Simscape blocks.
• When you specify the state values as a vector, states in the model must have real double values.

Using this functionality for models that do not meet these requirements and models that use
multitasking execution can produce unexpected results. For more information about multitasking and
single task execution, see “Time-Based Scheduling and Code Generation” (Simulink Coder).

Input Arguments
To use a model name as a programmatic interface, you use the name of your model as though it were
the name of a function. You always provide four inputs:

• t — Simulation time, specified as a real, double scalar.


• x — State values, specified as a vector of real double values or as a structure.

Specifying the states as a Simulink.op.ModelOperatingPoint object is not supported.


• u — Input data, specified as a vector of real, double values.
• phase — Simulation phase to execute, specified as one of these options:

• 'sizes' — Size computation phase, in which the software determines the sizes for the model
input, output, and state vectors
• 'compile' — Compilation phase, in which the software propagates signal and sample time
attributes

3-65
3 How Simulink Works

• 'update' — Update phase, in which the model computes the values of discrete states
• 'outputs' — Output phase, in which the model computes block and model output values
• 'derivs' — Derivatives phase, in which the model computes the derivatives for continuous
states
• 'term' — Termination phase

The number, type, and dimensions of the output arguments depend on which simulation phase you
execute.

When you use this functionality, you must manually execute each simulation phase in the appropriate
order. For more information about how simulations run, see “Simulation Phases in Dynamic Systems”
on page 3-2. This functionality is not meant to run a simulation step by step or as a replacement for
the typical simulation workflow.

Execute Size Computation Phase


To run the sizes phase, use this syntax, specifying [] for the first three input arguments.

[sys,x0,blks,st] = modelName([],[],[],"sizes");

You can also execute the sizes phase without specifying any input arguments.

The syntax with no input arguments is no longer supported.

The sizes phase returns four output arguments:

• sys — System information, returned as a vector with seven elements:

• sys(1) — Number of continuous states in the system.


• sys(2) — Number of discrete states in the system.
• sys(3) — Number of model outputs.
• sys(4) — Number of model inputs.
• sys(5) — Reserved.
• sys(6) — Direct feedthrough flag for system. A value of 1 indicates that the system has direct
feedthrough. A value of 0 indicates that the system does not have direct feedthrough.
• sys(7) — Number of continuous, discrete, fixed-in-minor-step, and controllable sample times
in the system. The value at this index indicates the number of rows in the ts output.
• x0 — Vector that contains the initial conditions for system states.
• blks — Vector that contains the names of blocks associated with the system states. The order of
elements in blks matches the order of elements in x0.
• st — m-by-2 array of sample time information for the system, where m is equal to the value of
sys(7). The first column of the array indicates the sample time and the second column indicates
the offset. For more information about sample time, see “Types of Sample Time” on page 7-18.

Execute Compilation Phase


To run the compilation phase, use this syntax, specifying [] for the first three input arguments.

[sys,x0,blks,st] = modelName([],[],[],"compile");

3-66
Use Model Name as Programmatic Interface

The compilation phase returns the same four output arguments as the sizes phase:

• sys — System information, returned as a vector with seven elements:

• sys(1) — Number of continuous states in the system.


• sys(2) — Number of discrete states in the system.
• sys(3) — Number of model outputs.
• sys(4) — Number of model inputs.
• sys(5) — Reserved.
• sys(6) — Direct feedthrough flag for system. A value of 1 indicates that the system has direct
feedthrough. A value of 0 indicates that the system does not have direct feedthrough.
• sys(7) — Number of continuous, discrete, fixed-in-minor-step, and controllable sample times
in the system. The value at this index indicates the number of rows in the ts output.
• x0 — Vector that contains the initial conditions for system states.
• blks — Vector that contains the names of blocks associated with the system states. The order of
elements in blks matches the order of elements in x0.
• st — m-by-2 array of sample time information for the system, where m is equal to the value of
sys(7). The first column of the array indicates the sample time and the second column indicates
the offset. For more information about sample time, see “Types of Sample Time” on page 7-18.

After running the compilation phase, you must run the termination phase before you can close the
model. If you execute the compilation phase multiple times before executing the termination phase,
you must execute the termination phase an equal number of times.

Compute Discrete State Values


To execute the update phase and compute the discrete state values, use this syntax. You specify the
time at which you want to calculate the discrete states and the current state and input values to use
in the computation.

dStates = modelName(t,x,u,"update");

The update phase returns the discrete state values dStates as a structure or an array, depending on
how you specify the current state values, x.

• When you specify x as empty ([]) or as a structure, the update phase returns dStates as a
structure that contains both discrete and continuous state values for all states with built-in data
types.
• When you specify x as a vector or an array, the update phase returns dStates as a vector or an
array that contains only the discrete state values for states that have real, double values.

Compute Output Values


To compute the model outputs, use this syntax. You specify the time at which you want to calculate
the discrete states and the current state and input values to use in the computation.

out = modelName(t,x,u,"outputs");

3-67
3 How Simulink Works

Compute Continuous State Derivatives


To compute the derivatives for continuous states, use this syntax. You specify the time at which you
want to calculate the discrete states and the current state and input values to use in the computation.

derivs = modelName(t,x,u,"derivs");

Execute Termination Phase


When you are done analyzing the model behavior, use this syntax to execute the termination phase so
you can close the model. Specify [] for the first three input arguments.

modelName([],[],[],"term");

See Also
sim | parsim | batchsim

Related Examples
• “Simulation Phases in Dynamic Systems” on page 3-2
• “Types of Sample Time” on page 7-18
• “Step Through Simulation” on page 2-2
• “About Data Types in Simulink” on page 73-2
• “Time-Based Scheduling and Code Generation” (Simulink Coder)

3-68
Modeling Dynamic Systems

69
4

Creating a Model

• “Create Template from Model” on page 4-2


• “Write In-Model Documentation Using Notes” on page 4-4
• “Create and Edit Annotations Programmatically” on page 4-9
• “Explore Types of Subsystems” on page 4-17
• “Group Blocks into Subsystems” on page 4-20
• “Connect Subsystems” on page 4-25
• “Expand Subsystem Contents” on page 4-30
• “Navigate Model Hierarchy” on page 4-34
• “Create and Use Referenced Subsystems in Models” on page 4-38
• “Convert Subsystem to a Referenced Subsystem” on page 4-46
• “Mask a Subsystem File” on page 4-49
• “Control Subsystem Reference Programmatically” on page 4-52
• “Change Subsystem Reference Component Dynamically Using InitFcn” on page 4-54
• “Define Subsystem Reference Interfaces Using Test Harnesses and Generate Reusable Code”
on page 4-57
• “Subsystem Reference Demos” on page 4-61
• “Use Control Flow Logic” on page 4-62
• “Customize Model Behavior with Callbacks” on page 4-68
• “Model Callbacks” on page 4-70
• “Block Callbacks” on page 4-75
• “Port Callbacks” on page 4-81
• “Initialization Function” on page 4-82
• “Manage Model Versions and Specify Model Properties” on page 4-86
• “Model Discretizer” on page 4-91
• “Create Model That Performs Neighborhood Processing” on page 4-107
• “Specify Region of Interest for Neighborhood Processing” on page 4-111
• “Use Neighborhood Processing Subsystem Block Padding Options with Region of Interest”
on page 4-114
4 Creating a Model

Create Template from Model

Create a Simulink template from a model to reuse or share the settings and contents of the model
without copying the model each time. Create templates only from models that do not have external
file dependencies, for example, model references, data dictionary, scripts, S-functions, or other file
dependencies. If you want to include other dependent files, use a project template instead. See
“Using Templates to Create Standard Project Settings” on page 16-36.

1 In the model, on the Simulation tab, select Save > Template.


2 In the Export modelname to Model Template dialog box, edit the template title, select or create a
group, and enter a description of the template.

The Simulink Start Page displays the title and description you specify and stores the template
under the group you select, for example, My Templates.
3 In the File location box, specify a file name and location for the template SLTX file.

Tip Save the template on the MATLAB path to make it visible on the Simulink Start Page. If you
save the template to a location that is not on the path, the new template is visible on the Start
Page only in the current MATLAB session. Saving the template does not add the destination
folder to the path.
4 Optionally, specify a thumbnail image for the template, click Change, then select an image file.
5 Click Export.

Edit a Template
To edit a model file template, open the template from the Current Folder or from the Simulink Start
Page. Make the desired changes.

1 Open the template for editing.

• From the Current Folder, navigate to the template (*.sltx). Right-click the template and
select Open Template for Editing.
• From the Simulink Start Page, point to the template and click the arrow to see the template
information. On the Create button, click the arrow and select Edit Template.
2 Make the changes you want.
3 You can also edit the template properties.

• For a model template, on the Simulation tab, click Template Properties.


• For a subsystem template, on the Subsystem tab, click Template Properties.
• For a library template, on the Library tab, click Template Properties.
4 Save the template for your changes to take effect.

See Also
Simulink.exportToTemplate

4-2
Create Template from Model

Related Examples
• “Using Templates to Create Standard Project Settings” on page 16-36

4-3
4 Creating a Model

Write In-Model Documentation Using Notes

To provide background information or instructions within a model file, you can write notes in the
Notes pane of the Simulink Editor. The notes can include text, images, hyperlinks, equations, and
website content. To add labels, short descriptions, images, equations, and hyperlinks to the canvas,
use annotations instead. For more information about annotations, see “Annotate Models” on page 1-
76.

To show the Notes pane, in the Simulink Toolstrip, on the Modeling tab, click the arrow on the far
right of the Design section. In the Design gallery, under Review, click Model Notes. Alternatively,
press Ctrl+Shift+N.

To write notes, you must create a file to store the notes, or load an existing notes file. Notes are
stored in a file with the extension .mldatx. To create a notes file, in the Notes pane, click the Create

a notes file button . To use an existing notes file, click the Use an existing notes file button .
The notes file is saved separately from the model. If you move your model to a different folder,
the .mldatx file does not also move, but the association remains if the file is on the MATLAB path.

If a model has an associated notes file, the name of the notes file the software is reading from and
writing to is displayed at the top of the Notes pane. If a model does not have an associated notes file,
this message appears at the top of the Notes pane: This model does not have notes
associated with it. The software can only read from and write to one notes file at a time.
However, you can create multiple notes files for use with the same model, for example, for users with
different roles. The person using the model can load the file pertaining to their role. Notes files
contain the model name and version information to ensure the notes file and model match.

The notes you can view and edit in the Notes pane are specific to the component in the model
hierarchy you are in, for example, a chart or subsystem. If you navigate to a different component, you
see the notes for that component. For each component in your model, you can set what the Notes

pane displays. To do so, click the Edit Notes button . Then, from the drop-down list at the top of
the Notes pane, select one of these options.

• Write Notes – Display the notes associated with the component.


• Use URL for Notes – Enter the URL of a website you want to display.
• Show Parent Notes – If the component has a parent component, display the notes associated
with the parent component.
• No Notes – Hide the notes.

4-4
Write In-Model Documentation Using Notes

View Notes and Load Notes Files


You can view notes in the Notes pane.

• To view the notes associated with a model component, navigate to the component. For example, to
view the notes for a subsystem, enter the subsystem.
• To find out which notes file you are viewing the contents of, check the filename at the top of the
Notes pane.

To load and view the contents of different notes file, click the Show Options button. Click the

Use an existing notes file button . Select an MLDATX file and click Open.

Add and Edit Notes


1 Navigate to the component you want to add notes to or whose note you want to edit. For
example, to add notes to or edit the notes of a subsystem, enter the subsystem.
2 Open the Notes pane.

4-5
4 Creating a Model

3 Check whether the model has an associated notes file. If the model has an associated notes file,
the name of the notes file the software is reading from and writing to is displayed at the top of
the Notes pane. If the model does not have an associated notes file, this message appears at the
top of the Notes pane:

This model does not have notes associated with it.


4
If the model has an associated notes file and the Create a notes file and Use an existing

notes file buttons are not visible in the Notes pane, click the Show Options button.
5 If the model does not have an associated notes file, or if you want to change the associated notes
file, create a new notes file or open an existing notes file.


To create a new file, in the Notes pane, click the Create a notes file button . Enter a
name for the notes file or use the default name, then click Save.

To open an existing file, in the Notes pane, click the Use an existing notes file button .
Select a MLDATX file and click Open.
6 Enter edit mode. When you create a new notes file, you automatically enter edit mode. If you
open an existing notes file, or if the model already has an associated notes file and you skipped

the previous step, click the Edit Notes button to enter edit mode.
7 Add or edit the contents of the note.

• To add text, enter the text in the text box.


• To inherit the notes from the parent component, in the drop-down list at the top of the Notes
pane, select Show Parent Notes.


To add images, include hyperlinks, or add equations, use the Image , Link , and

Equation Editor buttons, respectively. You can mix text, images, hyperlinks, and equations
in the same note. You can include multiple images, hyperlinks, and equations in the same
note.
• To use web content as the note, in the drop-down list at the top of the Notes pane, select Use
URL for Notes. In the text box in the Notes pane title bar, enter the web content URL.
Then, press Enter. You can only display the contents of one URL in the note.

4-6
Write In-Model Documentation Using Notes

8
To toggle the notes to read-only mode, click the Read Notes button .

Note The notes you add are saved automatically.

Hide and Show Notes


1 Navigate to the component whose notes you want to hide. For example, to hide the notes of a
subsystem, enter the subsystem.
2 Open the Notes pane.
3
To enter edit mode, click the Edit Notes button .
4 To hide the notes of the component you are in, in the drop-down list at the top of the Notes pane,
select No Notes.

If the notes of the component you are in are hidden, to show the notes, select Write Notes.

4-7
4 Creating a Model

5
To toggle the notes to read-only mode, click the Read Notes button .

See Also

Related Examples
• “Annotate Models” on page 1-76

4-8
Create and Edit Annotations Programmatically

Create and Edit Annotations Programmatically


Annotations are visual elements that you can use to add descriptive notes and callouts to your model.
In addition to text-only annotations, you can create annotations that:

• Open websites
• Perform MATLAB commands
• Display images
• Visually differentiate areas of block diagrams

These examples show how to programmatically create, edit, and delete annotations.

Create Annotation

This example shows how to create, modify, and view an annotation programmatically.

Open a new model.

open_system(new_system)

Create an annotation with default properties using the Simulink.Annotation function.

a = Simulink.Annotation(gcs,'This is an annotation.');

After creating the annotation, use dot notation to set property values. For example, apply an 18-point
font and yellow background to the annotation.

a.FontSize = 18;
a.BackgroundColor = 'yellow';

To view and briefly highlight the new annotation, use the view function.

view(a)

Find and Modify Annotations

This example shows how to find the annotations in the vdp model and modify the properties of one of
the annotations programmatically.

Open the example. Then, open the vdp model.

4-9
4 Creating a Model

open_system('vdp')

To find the annotations in the model, use the find_system function.

h = find_system(gcs,'FindAll','on','Type','annotation');

To identify the annotations, query the text inside the annotations by using the get_param function.

get_param(h,'PlainText')

ans = 3x1 cell


{'Copyright 2004-2022 The MathWorks, Inc.'}
{'Van der Pol Equation' }
{'x'' - µ(1-x^2) x' + x = 0' }

Suppose you want to apply a green background color to the 'Van der Pol Equation' annotation.

Get the Simulink.Annotation object by specifying the corresponding index of the array.

an = get_param(h(2),'Object');

Use dot notation to set the value of the BackgroundColor property.

an.BackgroundColor = 'Green';

4-10
Create and Edit Annotations Programmatically

Delete Annotation

This example shows how to delete an annotation in the vdp model programmatically.

Open the example. Then, open the vdp model.

open_system('vdp')

To get the handles for the annotations in the model, use the find_system function.

h = find_system(gcs,'FindAll','on','Type','annotation');

4-11
4 Creating a Model

To identify the annotations, query the text inside the annotations.

get_param(h,'PlainText')

ans = 3x1 cell


{'Copyright 2004-2022 The MathWorks, Inc.'}
{'Van der Pol Equation' }
{'x'' - µ(1-x^2) x' + x = 0' }

To delete the title of the model, 'Van der Pol Equation', get the Simulink.Annotation object
that corresponds to the second handle.

an = get_param(h(2),'Object');

Delete the annotation from the model.

delete(an)

Get the handles for the annotations in the model. Then, query the text inside the annotations.

h1 = find_system(gcs,'FindAll','on','Type','annotation');
get_param(h1,'PlainText')

ans = 2x1 cell


{'Copyright 2004-2022 The MathWorks, Inc.'}
{'x'' - µ(1-x^2) x' + x = 0' }

The model no longer has an annotation with 'Van der Pol Equation' as text.

Create Annotations That Contain Hyperlinks

4-12
Create and Edit Annotations Programmatically

This example shows how to use HTML formatting to add hyperlinks to text within rich-text
annotations.

Open a new model.

open_system(new_system)

Create two annotations, moving one of the annotations so that it does not overlap the other.

a1 = Simulink.Annotation(gcs,'This is an annotation.');
a2 = Simulink.Annotation(gcs,'This is another annotation.');
a2.Position = [0 20 28 34];

To create a hyperlink in the annotation, set Interpreter to 'rich' and define the hyperlink in the
Text property.

a1.Interpreter = 'rich';
a1.Text = 'Go to <a href="www.mathworks.com">www.mathworks.com</a>.';

You can also embed MATLAB functions in the hyperlink.

a2.Interpreter = 'rich';
a2.Text = '<a href="matlab:magic(4)">Generate magic square</a>.';

For more information, see “Create Hyperlinks that Run Functions”.

Add Image to Model

This example shows how to add an image to your model, such as a logo, by creating an image-only
annotation programmatically.

Open the example. Then, open a new model and create an annotation in it.

open_system(new_system)
a = Simulink.Annotation(gcs,'This is an annotation.');

4-13
4 Creating a Model

Change the annotation to display only the specified image.

img = fullfile(pwd,'drivingCar_24.png');
setImage(a,img)

Create Area

This examples shows how to create an area annotation in a model programmatically.

Open the example. Then, open the vdp model.

open_system('vdp')

To create an area that includes some of the blocks in the model, use the get_param function to get
the position of those blocks. For example, get the position of the blocks named x1 and x2.

x1_pos = get_param('vdp/x1','Position');
x2_pos = get_param('vdp/x2','Position');

The function returns the position as a vector of coordinates, in pixels: [left top right bottom].
The origin is the upper-left corner of the Simulink Editor canvas before any canvas resizing. Positive
values are to the right of and down from the origin. Negative values are to the left of and up from the
origin.

4-14
Create and Edit Annotations Programmatically

To create an area around the blocks named x1 and x2, use the add_block function with the built-
in/Area option. Specify a relative position for the edges of the area based on the block positions.

add_block('built-in/Area','vdp/This is an area',...
'Position',[x2_pos(1)-20,x2_pos(2)-20,x1_pos(3)+20,x1_pos(4)+20])

The area contains the blocks named x1 and x2. Each side of the area is offset 20 pixels from the
closest block edge.

Create and Hide Markup Annotation

This example shows how to create markup annotations, which can be easily hidden.

Open a new model.

open_system(new_system)

Create two annotations, and move the second annotation so that it does not overlap the first
annotation.

a1 = Simulink.Annotation(gcs,'This is a model annotation.');


a2 = Simulink.Annotation(gcs,'This is another model annotation.');
a2.Position = [0 20 28 34];

By default, you create model annotations, which appear in the model.

Change the second annotation to a markup annotation.

4-15
4 Creating a Model

a2.MarkupType = 'markup';
a2.Text = 'This is a markup annotation.';

Configure the current model to hide markup annotations.

set_param(gcs,'ShowMarkup','off');

ah = find_system(gcs,'FindAll','on','Type','annotation');
at = get_param(ah,'Text')

at = 2x1 cell
{'This is a markup annotation.'}
{'This is a model annotation.' }

Both annotations remain, despite the markup annotation being hidden.

Find Annotation Executing Callback Function


If an annotation invoked a currently executing callback function, use the getCallbackAnnotation
to determine which annotation invoked it. The function returns the corresponding Annotation
object. This function is also useful if you write a callback function in a separate MATLAB file that
contains multiple callback calls.

See Also
add_block | delete (Annotation) | setImage (Annotation) | view (Annotation) |
Simulink.Annotation

Related Examples
• “Annotate Models” on page 1-76

4-16
Explore Types of Subsystems

Explore Types of Subsystems


Subsystems can be virtual or nonvirtual.

• Virtual subsystems help visually organize a block diagram. When you group blocks in a virtual
subsystem or expand a virtual subsystem, you can affect the execution order of blocks because of
the changes to the block paths.
• Nonvirtual subsystems, also known as atomic subsystems, help functionally organize a block
diagram. When you group blocks in a nonvirtual subsystem or expand a nonvirtual subsystem, you
change the model behavior. Each nonvirtual subsystem executes as a single block, or atomic unit,
when the parent model executes. The blocks in a nonvirtual subsystem execute consecutively.

Tip For controllers and other standalone components, define a hard boundary around the related
blocks by using a nonvirtual subsystem or referenced model. Defining a hard boundary upfront avoids
costly refactoring when you want to generate code for the component.

To determine whether a subsystem is virtual or nonvirtual, use either of these strategies:

• Check the border of the block. A virtual subsystem has a thin border. A nonvirtual subsystem has a
thick border.

• Use the get_param function to query the Boolean block parameter IsSubsystemVirtual. For
an example, see “Determine Whether Subsystem Is Virtual”.

This table classifies some of the types of nonvirtual subsystems.

Basis of Subsystem Subsystem Subsystem Block More Information


Execution Description Name
Control signal value Subsystem whose Enabled Subsystem “Using Enabled
execution is enabled by Subsystems” on page
external input. 10-12
Subsystem whose Triggered Subsystem “Using Triggered
execution is triggered Subsystems” on page
by external input. 10-18
Subsystem whose Enabled and Triggered “Using Enabled and
execution is enabled Subsystem Triggered Subsystems”
and triggered by on page 10-21
external inputs.
Subsystem whose block Resettable Subsystem “Using Resettable
states reset with an Subsystems” on page
external trigger. 10-137

4-17
4 Creating a Model

Basis of Subsystem Subsystem Subsystem Block More Information


Execution Description Name
If-else logic Subsystem whose If Action Subsystem “Select Subsystem
execution is enabled by Execution” on page 10-
an If block. 25
Switch logic Subsystem whose Switch Case Action “Select Subsystem
execution is controlled Subsystem Execution” on page 10-
by a Switch Case block. 25
Function-call event Subsystem whose Function-Call “Using Function-Call
execution is controlled Subsystem Subsystems” on page
by an external function- 10-53
call input.
Number of iterations Subsystem that repeats For Iterator Subsystem “Iterate Subsystem
execution during a Execution with While
simulation time step for Iterator and For Iterator
a specified number of Subsystems” on page
iterations. 10-29
Subsystem that repeats While Iterator “Iterate Subsystem
execution during a Subsystem Execution with While
simulation time step Iterator and For Iterator
while a logical condition Subsystems” on page
is true. 10-29
Number of elements Subsystem that repeats For Each Subsystem “Repeat an Algorithm
execution on each Using a For-Each
element or subarray of Subsystem” on page 10-
input signal and 34
concatenates results.
Message Subsystem that Message Polling “Using Message Polling
executes conditionally Subsystem and Message Triggered
at each time step based Subsystems” on page
on whether a message 11-87
is available at the
control port.
Subsystem that Message Triggered “Using Message Polling
executes whenever a Subsystem and Message Triggered
message is available at Subsystems” on page
the control port, 11-87
independent of sample
time.
Execution order only Subsystem that Atomic Subsystem “Specify Whether
executes as a single Subsystem Is Atomic”
block, or atomic unit, on page 4-22
when the parent model
executes.

See Also
Subsystem

4-18
Explore Types of Subsystems

Related Examples
• “Group Blocks into Subsystems” on page 4-20
• “Connect Subsystems” on page 4-25
• “Navigate Model Hierarchy” on page 4-34
• “Expand Subsystem Contents” on page 4-30
• “Conditionally Executed Subsystems and Models”
• “Reference a Subsystem File in a Model” on page 4-39

4-19
4 Creating a Model

Group Blocks into Subsystems


As a model increases in size and complexity, you can simplify it by grouping blocks into subsystems. A
Subsystem block is a block that contains a subset of a model. You can have multiple subsystems in a
model, and you can have subsystems inside of other subsystems.

Using subsystems:

• Establishes a hierarchy where a Subsystem block is on one layer and the blocks that make up the
subsystem are on another. Each subsystem you enter takes you one level deeper in the hierarchy.
• Keeps functionally related blocks together.
• Helps reduce the number of blocks displayed in your model window.
• Establishes an interface with inputs and outputs.

When you make a copy of a subsystem, that copy is independent of the source subsystem. To reuse
the contents of a subsystem across a model or across models, consider referenced subsystems,
referenced models, or subsystems linked to a block in a custom library. For more information, see
“Explore Types of Model Components” on page 23-4.

To create subsystems whose execution depends on other components, use conditionally executed
subsystems. For more information, see “Explore Types of Subsystems” on page 4-17.

Create Subsystems
You can create a subsystem by converting part of an existing model into a subsystem, or by adding a
Subsystem block to your model and populating it.

To convert part of a block diagram into a subsystem:

1 In the Simulink canvas, drag a selection box over the model elements that you want to include in
the subsystem. An ellipsis appears next to the selection box.

2 Pause on the ellipsis. An action bar expands.

4-20
Group Blocks into Subsystems

3 In the action bar, click Create Subsystem or another subsystem option.

When the selection contains blocks that correspond to input and output ports, the new subsystem
includes copies of those blocks. The new subsystem does not contain copies of blocks that correspond
to control ports.

To create a subsystem from the bottom up:

1 Decide what type of subsystem you want to create. For information on the types of subsystems,
see “Explore Types of Subsystems” on page 4-17.

Tip For controllers and other standalone components, define a hard boundary around the related
blocks by using a nonvirtual subsystem or referenced model. Defining a hard boundary upfront
avoids costly refactoring when you want to generate code for the component.
2 Open the quick-insert menu by double-clicking the Simulink canvas.
3 In the search box, start typing the name of the block that corresponds to the type of subsystem
you want to implement in your model.
4 In the list that appears, select the block name. Use the arrow keys and press Enter, or click the
block.

To view or edit the contents of a subsystem, double-click the corresponding block. To exit the

subsystem, below the left end of the Simulink Toolbar, click . For more information on how to
navigate the hierarchy of a model with subsystems, see “Navigate Model Hierarchy” on page 4-34.

4-21
4 Creating a Model

Tip The contents of a Subsystem block are saved with the model. If you want to save the contents in
a separate file, convert the Subsystem block to a Subsystem Reference block. For more information,
see “Create and Use Referenced Subsystems in Models” on page 4-38.

Replace Subsystem with Its Contents


To replace a Subsystem block with its contents, select the Subsystem block. Then, in the Simulink
Toolstrip, on the Subsystem Block tab, click Expand.

The contents of the subsystem appear in an area labeled with the name of the replaced block.

For more information, see “Expand Subsystem Contents” on page 4-30.

Specify Whether Subsystem Is Atomic


When you add a Subsystem block to your model, the block creates a virtual subsystem. Virtual
subsystems help visually organize a block diagram. When you group blocks in a virtual subsystem or
expand a virtual subsystem, you can affect the execution order of blocks because of the changes to
the block paths.

By contrast, an atomic subsystem helps functionally organize a block diagram. When you group
blocks in an atomic subsystem or expand an atomic subsystem, you change the model behavior. Each
atomic subsystem executes as a single block, or atomic unit, when the parent model executes. The
blocks in an atomic subsystem execute consecutively. Atomic subsystems are also known as
nonvirtual subsystems.

Note Conditionally executed subsystems are inherently atomic and nonvirtual. For information on
the types of subsystems, see “Explore Types of Subsystems” on page 4-17.

If you expect a subsystem to grow, make the subsystem atomic so that the subsystem functionally
groups the blocks. Specifying that a subsystem is atomic upfront avoids costly refactoring when you

4-22
Group Blocks into Subsystems

want to generate code for the component later. Atomic behavior is necessary for you to convert a
subsystem to a model reference.

To make a subsystem atomic, select the Subsystem block in the canvas. Then, in the Simulink
Toolstrip, on the Subsystem Block tab, click Make Atomic.

To demonstrate the result of making a subsystem atomic, this block diagram displays the execution
order of its blocks, including two Subsystem blocks.

For the Subsystem block named Discrete Cruise Controller, the block diagram displays an
execution order of 4. This subsystem is nonvirtual and has atomic behavior. The blocks in the
subsystem are not part of the execution order of the current block diagram. Instead, the blocks in the
subsystem have execution orders relative to each other.

For the Subsystem block named Car Dynamics, the block diagram displays an execution order of
{1,5,6,...}. This subsystem is virtual and does not have atomic behavior. The displayed execution
order is for the blocks in the subsystem, which have execution orders relative to the parent block
diagram.

For more information, see “Control and Display Execution Order” on page 40-16.

Specify Subsystem Read/Write Permissions


You can specify these read/write permissions for a subsystem:

• ReadWrite — Enable opening and modification of subsystem contents.


• ReadOnly — Enable opening but not modification of the subsystem.
• NotReadorWrite — Disable opening and modification of subsystem.

To control the level of access allowed for the subsystem, set the Read/Write permissions parameter
of the Subsystem block.

4-23
4 Creating a Model

Note Restricting read or write access does not prevent the access restrictions from being changed.
To hide proprietary information, consider using a protected model. For more information, see
“Explore Protected Model Capabilities”.

When a subsystem is stored in a custom library, you can use the Read/Write permissions parameter
on the parent library block to control access for the linked instances of the block. As long as the
library link remains intact, the restricted access can prevent people from viewing or modifying the
contents of the subsystem while still allowing them to use the subsystem in a model. For more
information, see “Linked Blocks” on page 45-12.

Customize Subsystem
You can change the name of the Subsystem block and modify the block the way that you do with any
other block.

For example:

• Apply block masks to hide the subsystem content, giving the appearance of an atomic block with
its own icon and parameter dialog box. For more information, see “Masking Fundamentals” on
page 43-3.
• Use block callbacks to perform actions in response to subsystem modeling actions such as
handling an error, deleting a block or line in a subsystem, or closing a subsystem. For more
information on block properties, such as callbacks, see “Specify Block Properties” on page 40-4.

See Also
Blocks
Subsystem

Functions
Simulink.BlockDiagram.copyContentsToSubsystem

More About
• “Explore Types of Subsystems” on page 4-17
• “Connect Subsystems” on page 4-25
• “Navigate Model Hierarchy” on page 4-34
• “Expand Subsystem Contents” on page 4-30
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Reference a Subsystem File in a Model” on page 4-39

4-24
Connect Subsystems

Connect Subsystems
To connect subsystems, use ports on a Subsystem block. The ports on a Subsystem block correspond
with blocks inside the subsystem.

For example, this Subsystem block has two input ports and one output port.

The subsystem contains Inport blocks named In1 and In2 and an Outport block named Out1. These
blocks correspond to input ports 1 and 2 and output port 1, respectively.

When you add a blank subsystem to a model, the subsystem contains an input port and an output port
by default.

Add Ports to Subsystems


To add ports to a Subsystem block directly, perform one of these actions:

• Click the edge of a Subsystem block. Then, select whether to create an input or output signal port,
an input or output bus element port, or a connection port.

• Drag a line to the edge of a Subsystem block. This action creates an input signal port.

• Drag a line from the edge of a Subsystem block. This action creates an output signal port.

4-25
4 Creating a Model

These actions add corresponding port blocks inside the subsystem.

Tip After port creation, the port label on the Subsystem block is enabled for quick editing. See “Edit
Port Labels on Subsystem Blocks” on page 4-26.

Alternatively, open the subsystem by double-clicking the Subsystem block. Then, add the
corresponding blocks to the subsystem.

Type of Port Corresponding Block


Signal port, input Inport block
Signal port, output Outport block
Bus element port, input In Bus Element block
Bus element port, output Out Bus Element block
Control port, enabled Enable block
Control port, triggered Trigger block
Control port, function-call Trigger block with Trigger type set to
function-call
Control port, reset Reset block
Control port, action Action Port block
Connection port Connection Port block

These blocks add corresponding ports to the Subsystem block.

Change Port Locations on Subsystem Blocks


To change the location of a port on a Subsystem block, drag the port to a new location on any side of
the block.

Edit Port Labels on Subsystem Blocks


By default, the software labels the ports on a Subsystem block. To specify how the software labels the
ports:

4-26
Connect Subsystems

1 Select the Subsystem block.


2 On the Format tab of the Simulink Toolstrip, select one of the labeling options from the Port
Labels menu. For more information, see Show port labels.

You can directly edit the port labels on these types of Subsystem blocks:

• Regular subsystem
• Subsystem with mask
• Variant subsystem
• Chart subsystem

To edit the port label on a Subsystem block in the current model:


1 Point to the port label. An interactive port label cue (blue box surrounding the port label)
appears. Click the cue.

Alternatively, select the port and press F2. The cue enters edit mode.

Creating a new port on a Subsystem block using automatic port creation also enables the port
label cue for quick editing.

2 A port selector cue appears above the port label cue to indicate the port label information that is
being edited: the port block name, signal name, bus port, or connection port. For signal ports,
you can edit both the port block name and the port signal name from the port label. To switch
between the values, click the respective icon in the selector cue or use the keyboard shortcuts
Ctrl+1,2.
3 Enter a value in the port label cue and press Enter or Esc, or click away.

4-27
4 Creating a Model

4 After the port label is edited, the software automatically updates the name of the related port or
signal within the subsystem.

Tip To make successive port label edits on a Subsystem block:

1 Select a port on the block.


2 Edit the port label and press Enter. This action enables keyboard selection of ports.
3 Select adjacent ports using the up arrow or down arrow key and pressing F2 for quick editing.

This table lists the update action depending on the type of port label defined on the Subsystem block.

Type of Port Label Action


None Editing not supported.
Port icon Updates the names of elements in the subsystem depending on the
Icon display parameter of the port.

For example, if the value of the Icon display parameter of the port
is Signal name, then both the icon on the port block and the
name of the linked signal are updated.

For this type of port label, the information shown on the port label
after an edit depends on the final edit performed on the label using
the selector cue:

• If the initial port label shows the port block name, and the final
edit is on the signal name, then the Icon display parameter for
the underlying port block automatically updates to Signal
name. So, after the edit, the port label shows the signal name
by default.
• If the initial port label shows the port signal name, and the final
edit is on the port block name, then the Icon display
parameter for the underlying port block automatically updates
to Port number. So, after the edit, the port label shows the
block name by default.
Port block name Updates the block name of the port in the subsystem. For this type
of port label, you can edit only the port block name using the port
selector cue.

4-28
Connect Subsystems

Type of Port Label Action


Signal name Updates the name of the signal linked to the port.

Subsystem port labels show the name of propagated signals when


all these conditions are true:

• The value of the Icon display parameter for the underlying


port block is Signal name.
• The internal signal within the subsystem is connected but does
not have a name.
• The propagated signal has a name.

Port Editing Limitations


• The software does not show the port selector cue for Chart blocks.
• Editing port labels on Subsystem blocks with a mask icon is not supported.
• Editing port numbers from the port label is not supported. You can still edit the port block name
and signal name using the port label cue.
• Editing name of propagated signals from the port label is not supported. You can still edit the port
block name and internal signal name using the port label cue. When you click the cue, the port
signal name field is empty because the internal signal does not have a name.

See Also
Subsystem

Related Examples
• “Group Blocks into Subsystems” on page 4-20
• “Navigate Model Hierarchy” on page 4-34
• “Expand Subsystem Contents” on page 4-30
• “Conditionally Executed Subsystems and Models”
• “Reference a Subsystem File in a Model” on page 4-39

4-29
4 Creating a Model

Expand Subsystem Contents


To move the contents of a subsystem into the containing system, you can expand the subsystem.

For example, the sldemo_enginewc model includes the Combustion subsystem.

After you expand the Combustion subsystem, the top level of the sldemo_enginewc model includes
the blocks and signals of the Combustion subsystem. The expansion removes the Subsystem block
and the Inport and Outport blocks.

4-30
Expand Subsystem Contents

Why Expand a Subsystem?


Expand a subsystem if you want to flatten a model hierarchy by bringing the contents of a subsystem
up one level.

Expanding a subsystem is useful when refactoring a model. Flattening a model hierarchy can be the
end result, or just one step in refactoring. For example, you could pull a set of blocks up to the parent
system by expanding the subsystem, deselect the blocks that you want to leave in the parent, and
then create a subsystem from the remaining selected blocks.

What Subsystems Can You Expand?


You can expand virtual subsystems that are not masked, linked, or commented. If you try to expand a
masked, linked, or commented subsystem using the Simulink Editor, a message gives you the option
of having Simulink modify the subsystem so that you can then expand it.

Kind of Subsystem Modification


Masked subsystem Removes all masking information
Library links Breaks the link
Commented-out subsystem Uncomments the subsystem

You cannot expand these subsystems:

• Atomic subsystems
• Conditional subsystems
• Configurable subsystems
• Variant subsystems
• Subsystems with the Read/Write permissions parameter set to ReadOnly or NoReadOrWrite
• Subsystems with an InitFcn, StartFcn, PauseFcn, ContinueFcn, or StopFcn callback
• Subsystems with linked requirements (using Requirements Toolbox™ software)

4-31
4 Creating a Model

Expand a Subsystem
To expand a subsystem interactively, right-click a Subsystem block and, from the context menu, select
Subsystem & Model Reference > Expand Subsystem.

To expand a subsystem programmatically, use the Simulink.BlockDiagram.expandSubsystem


function.

Tip Subsystem expansion applies to the currently selected subsystem level. The software does not
expand other subsystems in a nested subsystem hierarchy.

To improve readability when you expand nested subsystems, start by expanding the highest-level
subsystem that you want to expand, and then work your way down the hierarchy as far as you want to
expand.

Results of Expanding a Subsystem


When you expand a subsystem, Simulink:

• Removes the Subsystem block


• Removes the root Inport, root Outport, and Simscape Connection Port blocks that were in the
subsystem
• Connects the signal lines that went to the input and output ports of the subsystem directly to the
ports of the blocks in the model that connected to the subsystem
• Distributes blocks and routes signals for readability.

Block Paths

The paths for blocks that were in the subsystem that you expanded change. After expansion, update
scripts and test harnesses that rely on the hierarchical paths to blocks that were in the subsystem
that you expanded.

Signal Names and Properties

If you expand a subsystem with a missing connection on the outside or inside of the subsystem,
Simulink keeps the line labels, but uses the signal name and properties from just one of the lines. For
lines corresponding to:

• A subsystem input port, Simulink uses the signal name and properties from the signal in the
system in which the subsystem exists
• A subsystem output port, Simulink uses the signal name and properties from the subsystem

Display Layers

The display layers of blocks (in other words, which blocks appear in front or in back for overlapping
blocks) does not change after expansion. Blocks in front of the Subsystem block remain above the
expanded contents, and blocks below the Subsystem block remain under the expanded contents.

4-32
Expand Subsystem Contents

Execution Order and Block Priorities

When you compile a model, Simulink sorts the blocks in terms of the order of block execution.
Expanding a subsystem can change block path names, which, in rare cases, can impact the block
execution order.

If you explicitly set block execution order by setting block priorities within a subsystem, Simulink
removes those block priority settings when you expand that subsystem.

Data Stores

Expanding a subsystem that contains a Data Store Memory block that other subsystems read from or
write to can change the required data store write and read sequence. You may need to restructure
your model. For details, see “Order Data Store Access” on page 79-19.

See Also

More About
• “Explore Types of Subsystems” on page 4-17
• “Group Blocks into Subsystems” on page 4-20
• “Navigate Model Hierarchy” on page 4-34

4-33
4 Creating a Model

Navigate Model Hierarchy


You can use these model components to create a hierarchical model composed of many layers. For
more information about model components, see “Explore Types of Model Components” on page 23-
4.

Component Definition Example More Information


Subsystem block Block that contains a subset of a “Group Blocks into
model. Subsystems” on
page 4-20

Subsystem Block that references a subsystem “Create and Use


Reference block saved in a file. By referencing a Referenced
subsystem, you can reuse it in any Subsystems in
model without copying over the Models” on page 4-
block diagram. 38
Linked block Instance of a masked library block “Linked Blocks” on
or of a Subsystem block from a page 45-12
library.

Model block Block that references a model file. • Model


By referencing a model, you can • “Model
reuse its contents in other models Reference
without copying over the block Basics” on page
diagram. 8-2
Chart block Flow charts that contain Stateflow Chart
model elements such as states and
transitions.

The hierarchy can have multiple levels. For example, a Subsystem block can contain any of the listed
model elements, including other Subsystem blocks.

Entering a component takes you one level deeper in the hierarchy. You can move through the
hierarchy one level at a time, or you can skip around. You can open levels of the hierarchy in the
current tab, in new tabs, or in new windows.

To navigate simple model hierarchies or small ranges of levels in complex hierarchies, navigate down
in the canvas and up using the Explorer Bar.

Use the Model Browser to perform these actions:

• Skip levels when navigating down the hierarchy.


• Navigate large ranges of levels in complex model hierarchies.
• View the contents of a higher level in a new tab or a new window.
• Open a referenced model that does not have a visible Model block.

When you simulate a model, the whole hierarchy simulates, regardless of which level you are viewing.

4-34
Navigate Model Hierarchy

Navigate Down in Canvas


To navigate down one level in the hierarchy in the canvas, perform these actions:

How to View the Level You Action


Navigate To
In the current tab Double-click the component you want to enter.
In a new tab Press Ctrl (Command on a Mac) and double-click the component
you want to enter.
In a new window Press Shift and double-click the component you want to enter.

For example, to view the contents of a subsystem in the current tab, double-click the Subsystem
block.

If the subsystem you want to enter is masked, click the down arrow in the lower left corner of the
block icon instead.

Navigate Up Using Explorer Bar


To navigate up in the hierarchy, in the Explorer Bar that appears above the Simulink canvas, click the
name of the model component whose top level you want to see.

For example, suppose the sldemo_fuelsys model is open. You are in the top level of the Throttle
subsystem, and you want to navigate directly up to the top level of the Engine Gas Dynamics
subsystem. In the Explorer Bar, click Engine Gas Dynamics.

When you use the Explorer Bar, the higher level you navigate to opens in the current tab.

To open a higher level in a new tab or a new window, use the Model Browser.

Navigate by Selecting Destination in Model Hierarchy Tree


In the Model Browser, you can navigate directly to any level by selecting your destination in the
model hierarchy tree. To view the Model Browser, at the bottom left corner of the Simulink Editor,
click the Hide/Show Model Browser button . To view the hierarchy, expand the nodes of the tree.

To navigate to a level of the hierarchy, perform these actions.

4-35
4 Creating a Model

How to View the Level You Action


Navigate To
In the current tab Click your destination in the tree.
In a new tab Press Ctrl (Command on a Mac) and click your destination in the
tree.
In a new window Press Shift and click your destination in the tree.

Tip Alternatively, right-click your destination in the tree and select Open (in the current tab), Open
in New Tab, or Open in New Window.

To hide or restore the Model Browser, click the Hide/Show Model Browser button .

To specify whether to display referenced models, library links, or systems with mask parameters in

the tree, click .

Navigate to Previously Viewed Level

To navigate to the level you last viewed, click the Back button located above the Explorer Bar.

To navigate forward to the next level you viewed, click the Forward button .

4-36
Navigate Model Hierarchy

Navigate Up to Level of Parent Component

To navigate up to the level of the parent of a model component, click the Up to Parent button
located above the Explorer Bar.

The model component from which you navigated highlights in the canvas.

Navigate to Library
To navigate from a linked block to its library, select the linked block and press Ctrl+L. Alternatively,
select the block, then in the Simulink Toolstrip, on the block-specific tab (for example, the
Subsystem Block tab), click the Go to Library button.

The library opens in a new window.

Open Referenced Model Outside Model Hierarchy


When you double-click a Model block, you open the referenced model in the context of the current
model hierarchy.

To open a referenced model outside of the current model hierarchy, perform one of these actions:

• On the Model block icon, click the Open As Top Model badge.
• When the referenced model does not have a visible Model block, in the Model Browser, right-click
the block name. Then, select Open As Top Model.

The referenced model opens in the top model in a new window instead of as a referenced model. To
use a referenced model as a standalone model, the referenced model must not depend on data in a
higher-level model.

For more information, see “Model Reference Hierarchy” on page 8-4.

See Also

Related Examples
• “Explore Model Hierarchy”
• “Preview Content of Model Components” on page 1-93
• “Search Model Contents” on page 1-88

4-37
4 Creating a Model

Create and Use Referenced Subsystems in Models


What is a Subsystem Reference?
In component-based modeling, you can divide a Simulink model into smaller components, such as
subsystems, subsystem references, and model references. Each component has a well-defined scope
and performs a certain functionality. For more information on different Simulink components, see
“High-Level Component Selection Guidelines” on page 23-5.

A subsystem reference enables you to store a subsystem in a separate file and reference it in a model.
This is particularly useful when you have to reuse a subsystem multiple times in a model. This helps
in maintaining consistency and reducing redundancy in the model, as any changes you make to the
original subsystem automatically propagate to all its referenced instances. These instances exhibit
identical execution behavior as the original subsystem.

For example, consider the front and rear windshield wipers of a car. The front and rear wipers have
the same behavior but use different rain sensor inputs to control their speeds. Instead of designing
multiple subsystems that contain the same logic to control the speeds of the windshield wipers, you
can save a single subsystem to control the wiper speed in a separate file and reuse this subsystem in
your model by passing different inputs to it. This approach promotes component reuse, simplifies
model maintenance, and enhances modularity in your design.

To use a subsystem reference, save the subsystem in a separate file, known as the subsystem file, in
either .slx or .mdl format. Then, reference this subsystem file in a model using a Subsystem
Reference block. When you reference a subsystem file in a model, it forms a referenced subsystem. A
Subsystem Reference block has triangles in opposite corners of the block icon with the subsystem
filename in the center.

Advantages of Using Subsystem Reference


Using subsystem references in component-based modeling provides several advantages:

• Modular development — You can develop and test a subsystem reference as an individual
component, separate from the models that use it.
• Inclusion by reference — You can reference a subsystem file multiple times without making
redundant copies.
• Automatic synchronization — When you edit and save a subsystem reference instance, the
changes are saved in the subsystem file and all the referenced instances of that file are
synchronized.
• Dynamic interface — Subsystem reference adapts to the context of the parent model and does not
require a defined input-output interface.
• Incremental loading — Simulink loads a subsystem reference only when it is needed, which speeds
up model loading.
• Reduced file conflict — Subsystem reference isolates the subsystem components in separate files
and reduces conflict during parallel access.

4-38
Create and Use Referenced Subsystems in Models

• Instance-specific customization — You can customize and debug subsystem reference instances
individually and maintain the same execution behavior as the original subsystem.

Reference a Subsystem File in a Model

This example shows you how to create and reference a subsystem file in a model. The example also
demonstrates these capabilities of subsystem references:

• Instance-specific customization using a system mask.


• Behavior adaptation based on the properties of the input data.
• Instance-specific debugging.
• Automatic synchronization in multiple subsystem reference instances while editing and saving.
• Individual testing of subsystem files.

Create a Subsystem File

1. Open an empty subsystem window using any of these methods:

• Start Simulink®. On the Simulink Start Page, in the Simulink product group, click Blank
Subsystem.
• In the Simulink toolstrip, on the Simulation tab, select New and click Blank Subsystem.
• Use the new_system command:
sub = new_system("slexTimesK","Subsystem");
open_system(sub);

2. Add content to the subsystem. Inside the subsystem, add Inport, Gain, and Outport blocks and
connect them as shown.

3. Save the subsystem file as slexTimesK.

You also have the option to convert an existing Subsystem block within a model or library into a
Subsystem Reference block. When you convert a Subsystem block, it creates a subsystem file for the
Subsystem Reference block. For more information, see “Convert Subsystem to a Referenced
Subsystem” on page 4-46.

Reference a Subsystem File in a Model

Subsystem references allow you to reference the same subsystem file multiple times in a model
without creating redundant copies.

1. Create a new model called slexSubsystemReferenceContextAdapting. Alternatively, you can


open a model in which you want to reference the subsystem file.

2. Add a Subsystem Reference block using the Simulink Library Browser or the Quick Block Insert
menu.

4-39
4 Creating a Model

3. In the Simulink toolstrip, on the Subsystem Block tab, enter the name of the subsystem file
slexTimesK in the File Name field, or click Browse and navigate to the subsystem file.

Alternatively, you can double-click the Subsystem Reference block and enter the subsystem file name.

This creates a subsystem reference instance in the model that references the subsystem file
slexTimesK. Name this instance SSREF1.

4. To reference the same subsystem file in another subsystem reference instance SSREF2, make a
copy of the Subsystem Reference block SSREF1.

Customize Subsystem Reference Instances

You can set a different behavior for each subsystem reference instance and simultaneously use the
shared characteristics and functionality of the subsystem file. To enable instance-specific
customization, create a system mask for the subsystem file. When you create a system mask for the
subsystem file, all its referenced instances share the same mask parameters. You can assign different
values to these mask parameters using the Mask dialog box of each referenced instance.

1. Add a System Mask to the subsystem file. In the Simulink toolstrip of slexTimesK, on the
Subsystem tab, click Create System Mask. The Mask Editor window opens. Add a new mask
parameter and set it to k, the Gain value. Set the Prompt to Input for Gain. Save the mask.

For more information on masking a subsystem file, see “Mask a Subsystem File” on page 4-49.

2. Save the subsystem file slexTimesK.

3. Edit the mask parameter values of the subsystem reference instances in the model
slexSubsystemReferenceContextAdapting. Double-click the Subsystem Reference block
SSREF1 and enter the value 5 in the Input for Gain box of the mask dialog box. Similarly, set the
mask parameter value of SSREF2 to 10.

Dynamic Behavior of Subsystem Reference Based on Input Data

A subsystem reference adapts its behavior according to the properties of its input data. You do not
need to define the signal attributes and you can directly use input signals of different dimensions and
data types for each subsystem reference instance.

1. In the model slexSubsystemReferenceContextAdapting, set different input signals for both


subsystem reference instances:

4-40
Create and Use Referenced Subsystems in Models

• Use a Constant block with scalar value 1 as an input to SSREF1 .


• Use a Constant block with vector value [1,2,3,4] as an input to SSREF2.

2. To view the output, add Display blocks to both subsystem reference instances.

3. Simulate the model.

Observe that the subsystem reference instances SSREF1 and SSREF2:

• Use mask parameter values of 5 and 10, respectively, which are set using their mask dialog boxes.
• Adapt to have one dimension and four dimensions, respectively, in the output.

Instance Specific Debugging

As each subsystem reference instance is driven by its own set of inputs in the model, you must debug
and analyze each instance individually.

To debug the subsystem reference instance SSREF1:

1. In the model, select the subsystem reference SSREF1 and on the Subsystem tab, click Look
Under Mask.

2. Inside SSREF1, select the output signal of the Gain block and set a breakpoint. Set the breakpoint
condition to pause the simulation if the signal value is greater than 2. For more information to set
breakpoints, see “Debug Simulation Using Signal Breakpoints” on page 2-12.

3. Save SSREF1.

4. Simulate SSREF1 to debug and analyze the behavior of the subsystem reference instance.

When you set a breakpoint in the subsystem reference instance SSREF1, the other subsystem
reference instance SSREF2 in unaffected. This enables you to debug SSREF2 independently.

4-41
4 Creating a Model

Edit and Save Subsystem Reference

In a model containing multiple instances of the same subsystem file, you can edit any instance. When
you actively edit a subsystem reference instance, all the other instances are locked and unavailable
for editing. After you edit and save a subsystem reference instance, the changes are automatically
saved in the subsystem file. These changes are also reflected in any other open windows that
currently display instances of the same subsystem file. The remaining subsystem reference instances
are updated when you:

• Open, simulate, or update a model containing the subsystem reference instances.


• Use the find_system , get_param , or set_param commands. For more information on using
these commands, see “Control Subsystem Reference Programmatically” on page 4-52.

Follow these steps to edit an instance of the subsystem file slexTimesK:

1. In the model, navigate inside the subsystem reference instance SSREF1 and make any change. A
badge appears at the bottom left corner that indicates whether the instance is available for editing.

2. Right-click the badge and select Go to instance to view a list of all the active instances of the
same subsystem file. Select the option to open the instance SSREF2.

3. The subsystem reference instance SSREF2 is grayed out and cannot be edited because another
instance is actively being edited. To go to the instance being edited SSREF1, use the badge at the
bottom left corner.

Once you have edited a subsystem reference instance, you can save or discard your changes.

4-42
Create and Use Referenced Subsystems in Models

To save the changes, save the subsystem file or use these options from the drop-down menu of the
Save All button on the Simulation tab of the model window.

• Save All — To save all the updates in the current model


• Save Referenced Files > Save Specific File — To save a specific subsystem file when you have
made changes to multiple subsystem files

To discard the changes in a specific subsystem file made while editing its instance, close your
subsystem file. A dialog box appears asking whether to save the subsystem file before closing. Click
No. This action reverts changes in all the instances of the subsystem file.

Simulate a Subsystem File with a Test Harness

A subsystem file cannot simulate like a model or a subsystem. Instead, you must associate a test
harness with the subsystem file and then simulate the subsystem file using the test harness. Using a
test harness enables you to:

• Check for any errors or discrepancies while editing a subsystem file.


• Enable use of subsystem reference instances in only tested environments in a model. For
information on unit testing, see “Define Subsystem Reference Interfaces Using Test Harnesses
and Generate Reusable Code” on page 4-57.

You can associate more than one test harness with a subsystem file and set a default test harness
from a set of available test harnesses.

Follow these steps to develop and test a subsystem file as an individual component, separate from the
models that use it:

1. In the Simulink toolstrip of the subsystem file slexTimesK, on the Subsystem tab, click Add Test
Harness. The Create Test Harness dialog box opens.

2. To create the test harness, specify its name and click OK. Save the test harness. For more
information on test harness, see “Create a Test Harness” (Simulink Test).

4-43
4 Creating a Model

3. Edit the subsystem file slexTimesK and introduce an error by deleting the signal line between the
Gain block and the Outport block.

4. Click Run with Test Harness on the Simulink toolstrip to simulate the subsystem file using the
test harness. You can also select the Open harness on run check box, to automatically open the test
harness while running.

4-44
Create and Use Referenced Subsystems in Models

Observe the warnings displayed in the Diagnostic Viewer.

Subsystem Reference Requirements

Do not reference a parent subsystem from a subsystem file because it creates reference loop.

Subsystem Reference Compatibility with Previous Versions of


Simulink
When you export a model containing subsystem reference components to a version of Simulink prior
to R2019b, all the Subsystem Reference blocks are converted to independent Subsystem blocks. This
conversion is done because the subsystem reference components were not available before R2019b.
Also, subsystem files created in R2019b cannot be exported to a prior version. For information on
how to export a Simulink model to a previous version of Simulink, see “Export Model to Previous
Version of Simulink” on page 1-30.

See Also
Blocks
Subsystem | Subsystem Reference

Functions
convertSubsystemToSubsystemReference |
convertSubsystemReferenceBlockToSubsystem

Related Examples
• “Convert Subsystem to a Referenced Subsystem” on page 4-46
• “Subsystem Reference Demos” on page 4-61

More About
• “Component-Based Modeling Guidelines” on page 23-2
• “Explore Types of Model Components” on page 23-4

4-45
4 Creating a Model

Convert Subsystem to a Referenced Subsystem

This example shows how you can convert a Subsystem block in a model or library to a Subsystem
Reference block.

Convert Subsystem Block in a Model to a Subsystem Reference Block

Consider a model sldemo_mdlref_conversion with a Subsystem block Bus Counter that models
a counter algorithm.

To convert the Bus Counter Subsystem block to a Subsystem Reference block:

1. Select the Bus Counter block. On the Subsystem Block tab, select Convert > Convert to
Referenced Subsystem. A dialog box opens.

2. Enter a valid MATLAB® name such as Bus_Counter in the Subsystem file name field. If a test
harness is associated with the subsystem, you can select the Transfer test harnesses check box to
save the test harnesses of the subsystem with the subsystem file.

3. Click Convert. The Subsystem block changes into a Subsystem Reference block with the name of
the subsystem file Bus_Counter displayed at the top of the block icon. The subsystem file contains
the Bus Counter subsystem and is saved in the current directory.

4-46
Convert Subsystem to a Referenced Subsystem

When you convert a subsystem to a referenced subsystem, the Subsystem Reference block
automatically inherits the properties of its input and output signals. You do not need to explicitly
define the interface for the Subsystem Reference block.

Alternatively, to convert the block programmatically, enter this command in the MATLAB Command
Window.

Simulink.SubsystemReference.convertSubsystemToSubsystemReference(...
'sldemo_mdlref_conversion/Bus Counter','Bus_Counter');

For more information, see convertSubsystemToSubsystemReference.

4. Save the model.

Convert Library Subsystem Block to Subsystem Reference Block

You can also convert “Library Subsystems” (Simulink Coder) to referenced subsystems using the
same steps as converting a Subsystem block to a Subsystem Reference block in a model. However,
you must unlock the library before conversion and then save the library to preserve the changes
made during the conversion process.

When you convert a library subsystem block to a Subsystem Reference block, all the linked instances
of the library Subsystem block are converted to subsystem reference. Alternatively, you can also
convert only a specific instance of a linked subsystem. First break the link of the instance to the
parent library and then perform the conversion. For more information on breaking links to libraries,
see “Disable or Break Links to Library Blocks” on page 45-23.

Conditions to Convert to Referenced Subsystems

A block cannot be converted to a referenced subsystem when:

• The block is read-only.


• The block is a Configurable Subsystem, Variant Subsystem, Stateflow, Component under test, or
Simulink Function.
• The block is a linked subsystem or injector subsystem.
• The block is masked with its contents hidden using 'MaskHideContents'.
• The block is being tested by a test harness.
• The block is inside a subsystem and has a test harness.
• The block is inside models that have AUTOSAR or Software architectures
• The state owner and accessor blocks are not inside the same subsystem.

See Also
Blocks
Subsystem | Subsystem Reference

Functions
convertSubsystemToSubsystemReference

4-47
4 Creating a Model

More About
• “Create and Use Referenced Subsystems in Models” on page 4-38

4-48
Mask a Subsystem File

Mask a Subsystem File

Add a System Mask to a Subsystem File


You can mask a subsystem file using a system mask. When you create a system mask for a subsystem
file, all the referenced instances share the same system mask.

To mask a subsystem file:

1 Open the subsystem file to be masked.


2 In the Simulink toolstrip, on the Subsystem tab, click Create System Mask. Alternatively, right-
click anywhere on the canvas and select Mask and click Create System Mask. The Mask Editor
dialog opens.
3 Add mask parameters and click OK.

Note

• You cannot directly mask a Subsystem Reference block. To mask a Subsystem Reference block,
select the block. On the Referenced Subsystem tab, click Create System Mask. This action
opens the subsystem file being referenced and creates a mask on it.
• You cannot set parameters using set_param in a call back code of a masked subsystem. However
if the subsystem is self-modifiable or referenced from a library you can set the parameters.

For more information on creating and editing system masks, see “Introduction to System Mask” on
page 43-50.

Create Self-Modifiable Subsystem Reference Using System Mask


You can make instance-specific changes in the contents of a masked subsystem file using the system
mask. To allow dynamic changes, set the masked subsystem file as self-modifiable. In a self-modifiable
subsystem file, you can use the initialization callback of the system mask to add or delete blocks and
set the parameters of the blocks within the file.

To set a masked subsystem file as self-modifiable, in the subsystem file, go to the Code tab of the
System Mask Editor and select Allow mask initialization code to modify the subsystem's
content.

4-49
4 Creating a Model

You can also set the masked subsystem file ssref as self-modifiable programmatically. First, get the
subsystem file mask as a mask object. Then set the masked subsystem file as self-modifiable.

maskObj = Simulink.Mask.get("ssref");
maskObj.SelfModifiable = 'on';

In a self-modifiable masked subsystem file, you can modify the blocks of a masked subsystem
reference instance or allow the masked subsystems inside a masked subsystem reference instance to
self-modify.

Modify Blocks of a Masked Subsystem Reference

Consider a self-modifiable masked subsystem file ssref1 that includes a Gain block. The system
mask of the subsystem reference instance SR1 uses Gain as the mask parameter to set the value of
the Gain block. To dynamically set the block's value from the system mask, the mask initialization
callback of ssref1 first gets the Gain parameter value from the system mask and then sets the value
of the Gain block inside the subsystem reference instance.

Allow Masked Subsystems Inside a Masked Subsystem Reference to Self-Modify

Consider a self-modifiable masked subsystem file ssref2 that includes a masked subsystem
Subsystem-1. Further, Subsystem-1 includes a Gain block. Subsystem reference instance SR3 and

4-50
Mask a Subsystem File

masked subsystem Subsystem-1 use Gain as the mask parameter to set the value of the Gain block.
To dynamically set the block's value from the system mask, the mask initialization callback of
Subsystem-1 gets the Gain parameter value from the system mask. The mask initialization callback
of ssref2 gets the Gain parameter value from the parent subsystem Subsystem-1 mask and then
sets the value of the Gain block.

Considerations

There are certain cases where you cannot use a callback to modify the contents of a subsystem
reference instance even with a self-modifiable mask.

• If you want to modify a block located inside a Subsystem Reference, you cannot use callback of a
top model or block that is higher in the model hierarchy than the Subsystem Reference.
• If the block you want to modify is inside a masked subsystem of a Subsystem Reference, you must
use the mask callback of the parent masked subsystem. Using the callback of any other block to
modify a block within a masked subsystem of a Subsystem Reference is not feasible.

See Also
Blocks
Subsystem | Subsystem Reference

Functions
convertSubsystemToSubsystemReference

More About
• “Introduction to System Mask” on page 43-50
• “Get Started with Mask Initialization and Callback Code” on page 43-17
• “Create and Use Referenced Subsystems in Models” on page 4-38

4-51
4 Creating a Model

Control Subsystem Reference Programmatically


You can create a referenced subsystem, find available referenced subsystems in a model, change the
referenced subsystem file in a block, and check the block diagram type of the file using a command-
line interface.

Create a Referenced Subsystem


You can create a referenced subsystem using the new_system command:

new_system(subsystemfilename,'SubSystem')

Find Subsystem Reference in a Model


You can find if a model contains a referenced subsystem using the Simulink.findBlocksOfType
function:

Simulink.findBlocksOfType(bdroot, 'SubSystem',...
'ReferencedSubsystem','.',Simulink.FindOptions('RegExp',1))

You can also use the find_system command:


find_system(bdroot, 'RegExp','on','BlockType','SubSystem','ReferencedSubsystem', '.')

Both return the number of Subsystem Reference blocks in the model. By default, find_system lists
all the child blocks inside a subsystem reference instance.

If you do not want find_system to look inside a referenced subsystem, use find_system with
LookInsideSubsystemReference set to off. By default, LookInsideSubsystemReference is
set to on.

Change the Referenced File for a Subsystem


You can change the subsystem file being referenced in a Subsystem Reference block through
command-line interface using the set_param command:

set_param(gcb, 'ReferencedSubsystem', '<subsystemfilename>')

This command changes the file being currently referenced by the Subsystem Reference block and
replaces it with the new subsystem file you specify.

Check if the SLX or MDL File is a Subsystem Block Diagram Type


You can check if an SLX or MDL file is a subsystem block diagram type that can be placed in a
Subsystem Reference block using any of these commands:

bdIsSubsystem(bdname)

This command returns logical 1 if bdname.slx is a Subsystem block diagram type and logical
0 if it is not. When using this command, make sure that bdname.slx is loaded.

get_param(bdname,'BlockDiagramType')

4-52
Control Subsystem Reference Programmatically

This command returns Subsystem if bdname.slx is a Subsystem block diagram type. When using
this command, make sure that bdname.slx is loaded.

Simulink.MDLInfo(bdname)

This command gives the entire model information where the BlockDiagramType property is shown
as Subsystem if bdname.slx is a Subsystem block diagram type.

See Also
Blocks
Subsystem | Subsystem Reference

More About
• “Create and Use Referenced Subsystems in Models” on page 4-38

4-53
4 Creating a Model

Change Subsystem Reference Component Dynamically Using


InitFcn

This example shows how to dynamically change the subsystem reference component using the
“Initialization Function” on page 4-82. InitFcn is used to change the implementation of the model
without having to change the contents. This example model simulates the front and rear wipers of a
vehicle. The front wiper is sensor-based and it senses rain and fog. The rear wiper is controlled by the
driver.

Explore the Model

Inputs: The wipers are turned on during rain or fog. Double-click Turn on Fog Sensor or Turn on
Rain Sensor component on the top left corner of the model to select the type of input. Based on the
selection, the sensor input variable SensorInput is created in the model workspace.

Wiper speed controller: During simulation the InitFcn is executed and calls the switchSensor
function. This function reads the variable SensorInput from the model workspace and changes the
subsystem to slexRainSensor or slexFogSensor according to your input selection. The
subsystem reference component (Rain or Fog) converts the input voltage into speed levels low,
medium, and high. The wiper speed controller converts the front and rear wiper speed levels into the
appropriate speed in cycles per second.

Use this code in the InitFcn call back

4-54
Change Subsystem Reference Component Dynamically Using InitFcn

function wiperController(bd, option)


switch option
case 'PostLoad'
createWiperConstants(bd);
case 'Init'
switchSensor(bd);
otherwise
end
end

function switchSensor(bd)
mws = get_param(bdroot, 'modelworkspace');
si = mws.getVariable('SensorInput');
blockpath = [bd '/SensorBasedSpeedController'];
if strcmp(si,'Fog')
set_param(blockpath,'ReferencedSubsystem','slexFogSensor');
elseif strcmp(si,'Rain')
set_param(blockpath,'ReferencedSubsystem','slexRainSensor');
end
end

4-55
4 Creating a Model

See Also

“Initialization Function” on page 4-82

4-56
Define Subsystem Reference Interfaces Using Test Harnesses and Generate Reusable Code

Define Subsystem Reference Interfaces Using Test Harnesses


and Generate Reusable Code
This example shows you how to define interfaces for a subsystem reference component using test
harnesses and verify that the model reuses the component in defined interfaces only. It also shows
how you can generate code for the subsystem reference component and reuse it in a model.

Subsystem Reference components adapt to the environment in which they are used. As a result, you
might get undesired results when you use a subsystem reference component in an untested
environment. To ensure pertinent results, you can mark the test harnesses of a subsystem file that
produce the intended results as unit tests.

Use the Unit Test features available in the Simulink toolstrip to:

• Specify valid testing environments of a subsystem file.


• Capture signatures to diagnose and resolve invalid use of components.
• Generate code for components to reuse in the top model.

Video Walkthrough
For a walkthrough of the example, play the video.

Validate Subsystem Reference Use in Model and Generate Reusable


Code

4-57
4 Creating a Model

Explore the Model

1. Open the subsystem file slexReusableSS.

The subsystem slexReusableSS limits the input between (-10,10) and then amplifies the result
by a factor of 50. slexReusableSS has two test harnesses, ssref1_double and ssref1_int32. To
accommodate data between (-500,500), ssref1_double and ssref1_int32 use double and int32
data types, respectively.

2. Open the model slexModelUsingReusableSS.

The model slexModelUsingReusableSS uses three instances of the subsystem file


slexReusableSS named Double Input, Int32 Input2, and Int8 Input. The inputs to Double
Input, Int32 Input, and Int8 Input are constants of type double, int32, and int8,
respectively.

Define Interfaces and Verify Component Use

This section explains how to validate the use of Subsystem Reference blocks Double Input, Int32
Input2, and Int8 Input in the model slexModelUsingReusableSS using unit test features.

1. In the subsystem file slexReusableSS, select the test harnesses ssref1_double and
ssref1_int32 from the drop-down menu of the Select unit tests button on the Simulink® toolstrip.

If you create new test harnesses for the subsystem file, set the Subsystem Reference block in the test
harness as Atomic with Reusable function packaging.

4-58
Define Subsystem Reference Interfaces Using Test Harnesses and Generate Reusable Code

2. To generate signatures, select Generate Signature option from the Generate Signature menu
on the Simulink® toolstrip. This action generates signatures for the Subsystem Reference block in
the unit tests ssref1_double and ssref1_int32 of the subsystem file.

Alternatively, in complex subsystems, you can generate signatures for the selected unit tests in
parallel using multiple instances of MATLAB®. This approach enables you to speed up signature
generation. For more information, see “Parallel Computing Toolbox Product Description” (Parallel
Computing Toolbox). To generate signatures in parallel, run the MATLAB® script
generateSignatureInParallel.m. The script performs the following steps:

• Load subsystem file and unit tests.


• Set up parallel computing.
• Generate signatures in parallel using multiple MATLAB® sessions.
• Save signatures in subsystem file.

3. Save the subsystem file slexReusableSS.

4. To verify use of subsystem reference instances in the model, simulate the model
slexModelUsingReusableSS. Simulink® compares the signatures of the Subsystem Reference
blocks Double Input, Int32 Input2, and Int8 Input in the model with the signatures of the
Subsystem Reference block in the unit tests ssref1_double and ssref1_int32. Use of a subsystem
reference is valid when its signature matches at least one unit test signature.

5. Diagnostic Viewer displays an error message to highlight the invalid use of the subsystem
reference Int8 Input in the model as Int8 Input does not have matching signature with any of
the unit tests.

To disable the error message, set the diagnostic parameter Behavior when a matching unit test for
subsystem reference is missing to none or warning in the Configuration Parameters dialog box.

Alternatively, use the Signature Difference Viewer to identify the reason for the signature
mismatch and resolve these differences. The Signature Difference Viewer box provides parsed
differences between the attributes of the Subsystem Reference block Int8 Input in the model and
the attributes of the Subsystem Reference block in the test harnesses ssref1_double and
ssref1_int32 of slexReusableSS.

6. Resolve the diagnostic messages and run the model slexModelUsingReusableSS again.

Generate Code

This section explains how to generate code for the Subsystem Reference block in the test harnesses
ssref1_double and ssref1_int32.

1. In the subsystem file slexReusableSS, open test harness ssref1_double and go to Model
Settings > Code Generation > Interface and set Shared code placement to Shared location.
This action sets a common location to save generated codes. For more information, see Shared code
placement (Simulink Coder). Save test harness ssref1_double and apply the same setting to the
other test harness ssref1_int32.

2. To generate code, select the Generate Code option from the Generate Signature menu on the
Simulink® toolstrip. This action generates code for the Subsystem Reference block in the selected
test harnesses ssref1_double and ssref1_int32.

3. Save slexReusableSS.

4-59
4 Creating a Model

Reuse Code

This section explains how you can reuse the generated code of the Subsystem Reference block to
build the model.

1. Set the code generation folder structure using Simulink.fileGenControl (Simulink Coder).

Simulink.fileGenControl('set','CodeGenFolderStructure',...
Simulink.filegen.CodeGenFolderStructure.TargetEnvironmentSubfolder);

2. Press Command + B on Mac or Ctrl + B on all other operating systems to build the model
slexModelUsingReusableSS.

In the build, the model slexModelUsingReusableSS uses the code generated for subsystem
reference slexReusableSS. To check the reused codes, open the code generation report for the
model.

See Also
Blocks
Subsystem Reference

Functions
Simulink.SubsystemReference.generateSignatures |
Simulink.SubsystemReference.getUnitTestNames |
Simulink.SubsystemReference.removeSignatures |
Simulink.SubsystemReference.showSignatureDiffDialogForSS |
Simulink.SubsystemReference.showSignatureDiffDialogForUnitTests

More About
• “Create and Use Referenced Subsystems in Models” on page 4-38

4-60
Subsystem Reference Demos

Subsystem Reference Demos

The slexSubsystemReferenceExamples model contains a set of conceptual examples that


demonstrate the capabilities of Subsystem Reference.

4-61
4 Creating a Model

Use Control Flow Logic

In this section...
“What is a Control Flow Subsystem” on page 4-62
“Equivalent C Language Statements” on page 4-62
“Conditional Control Flow Logic” on page 4-62
“While and For Loops” on page 4-64

What is a Control Flow Subsystem


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, switch, and for).

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-62
Use 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.

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.

4-63
4 Creating a Model

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

In this example, Simulink repeatedly executes the contents of the While Iterator 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

4-64
Use Control Flow Logic

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

Modeling For Loops

The following diagram represents a for loop:

In this example, Simulink executes the contents of the For Iterator 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.

4-65
4 Creating a Model

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

Use For loop with Assignment block

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-66
Use Control Flow Logic

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

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.

See Also
Assignment | For Iterator | While Iterator | While Iterator Subsystem | For Iterator Subsystem | While
Iterator Subsystem

4-67
4 Creating a Model

Customize Model Behavior with Callbacks


Callbacks are commands you can define that execute in response to a specific modeling action, such
as opening a model or stopping a simulation. Callbacks define MATLAB expressions that execute
when the block diagram or a block is acted upon in a particular way.

Simulink provides model, block, and port callback parameters that identify specific kinds of model
actions. You provide the code for a callback parameter. Simulink executes the callback code when the
associated modeling action occurs.

For example, the code that you specify for the PreLoadFcn model callback parameter executes
before the model loads. You can provide code for PreLoadFcn that loads the variables that model
uses into the MATLAB workspace.

What You Can Do with Callbacks


Callbacks are a powerful way to customize your Simulink model. A callback executes when you
perform actions on your model, such as double-clicking a block or starting a simulation. You can use
callbacks to execute MATLAB code. You can use model, block, or port callbacks to perform common
tasks, for example “Automatically Initialize Variables and Load Data” on page 1-20.

Types of Callbacks
Simulink provides many types of callbacks, including:

• Model callbacks — Model callbacks execute at specified action points, for example, after you load
or save the model. See “Model Callbacks” on page 4-70.
• Block callbacks — Block callbacks execute for block events, such as when a block is loaded,
opened, or edited. See “Block Callbacks” on page 4-75.
• Block mask callbacks — Block mask callbacks execute when the value of a mask parameter
changes. See “Initialization and Parameter Callbacks”.
• Port callbacks — A port callback executes every time the connectivity of the corresponding port
changes. See “Port Callbacks” on page 4-81.
• Annotation callbacks — An annotation can execute a callback when you click the annotation. See
Simulink.Annotation.
• Callback Button block callbacks — The Callback Button block executes a callback when you click
the block.

Callback Limitations
Do not call the run command from within model or block callback code. Doing so can result in
unexpected behavior such as errors or incorrect results if you load, compile, or simulate a Simulink
model.

For limitations of specific callbacks, see their documentation.

4-68
Customize Model Behavior with Callbacks

See Also

Related Examples
• “View and Trace Callbacks in Models” on page 27-70
• “Fast Restart Methodology” on page 87-10

4-69
4 Creating a Model

Model Callbacks
Model callbacks execute at specified action points, for example, after you load or save the model.

You can use model callbacks to perform common tasks, such as “Automatically Initialize Variables and
Load Data” on page 1-20.

Libraries and subsystem references support most of the model callbacks. However, for these
components, you can set only those callbacks that can execute for a library or subsystem reference.
For example, you cannot set the InitFcn callback for a library, which is called as a part of
simulation, because you cannot simulate a library. This same behavior applies to subsystem
references.

Create Model Callbacks

1 In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, click Property Inspector.
2 With no selection at the top level of your model or referenced model, on the Properties tab, in
the Callbacks section, select the callback you want to set.

Note Block callbacks differ from model callbacks. Do not select a Model block to set model
callbacks for a referenced model.
3 In the box, enter the functions you want the callback to perform.

To programmatically create a model callback, use the set_param function to assign MATLAB code to
a model callback parameter.

4-70
Model Callbacks

Model Callback Parameters


Model Callback When Executed
Parameter
PreLoadFcn Before the model is loaded.

Do not use model parameters in a PreLoadFcn model callback because


parameters are loaded after the model is loaded. Instead, use a
PostLoadFcn callback to work with model parameters when the model is
loaded.

Defining a callback code for this parameter is useful for loading variables
that the model uses.

If you want to call your model from a MATLAB file without opening your
model, use the load_system function so that the PreLoadFcn executes.

For an example, see “Automatically Initialize Variables and Load Data” on


page 1-20.

Limitations include:

• For the PreLoadFcn callback, get_param does not return the model
parameter values because the model is not yet loaded. Instead,
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
• Programmatic access to Scopes is not supported.
PostLoadFcn After the model is loaded.

Defining callback code for this parameter may be useful for generating an
interface requiring a loaded model.

Limitations include:

• If you make structural changes with PostLoadFcn, the function does


not set the model Dirty flag to indicate unsaved changes. When you
close the model, Simulink does not prompt you to save.
• Programmatic access to Scopes is not supported.

Because the Simulink Editor opens after this callback executes, the
PostLoadFcn callback is not suitable for setting up the model view, for
example, setting a zoom factor. Save zoom information with the model to
open it with a particular zoom factor.

4-71
4 Creating a Model

Model Callback When Executed


Parameter
InitFcn During the update phase before block parameters are evaluated. This
callback is called during model update and simulation.

Avoid InitFcn model callbacks that edit the structure of the model.
Simulink may execute or ignore these callbacks based on the model load
status.

Avoid InitFcn model callbacks that edit the contents of a referenced


model. Doing so can result in unexpected behavior such as errors or
incorrect results when you simulate a Simulink model.

For more information on the InitFcn callback, see “Initialization


Function” on page 4-82.

For an example, see “Call MATLAB Function Files in MATLAB Function


Blocks” on page 50-125.
StartFcn Before the simulation phase. This callback is not called during model
update.

This callback is called for every simulation in fast restart.


PauseFcn After the simulation pauses.
ContinueFcn Before the simulation continues.
StopFcn After the simulation stops.

Output is written to workspace variables and files before the StopFcn is


executed.

Simulation outputs are not available in the StopFcn callbacks for


command-line simulations.

This callback is called for every simulation in fast restart.


PreSaveFcn Before the model is saved.
PostSaveFcn After the model is saved.

If you make structural changes with PostSaveFcn, the function does not
set the model Dirty flag to indicate unsaved changes. When you close the
model, Simulink does not prompt you to save.
CloseFcn Before the block diagram is closed.

Any ModelCloseFcn and DeleteFcn callbacks set on blocks in the model


are called prior to the model CloseFcn callback. The DestroyFcn
callback of any blocks in the model is called after the model CloseFcn
callback.

Referenced Model Callbacks


In a model hierarchy, the execution of callbacks reflects the order in which the top model and the
models it references execute their callbacks. For example, suppose:

4-72
Model Callbacks

• Model A:

• References model B in accelerator mode.


• Has a PostLoadFcn callback that creates variables in the MATLAB workspace.
• Has the Rebuild configuration parameter set to Always, If changes detected, or If
changes in known dependencies detected.
• Model B:

• Has a CloseFcn callback that clears the MATLAB workspace.


• Has not been built or is out of date.

Simulating model A triggers a rebuild of referenced model B. When Simulink rebuilds model B, it
opens and closes model B, which invokes the model B CloseFcn callback. CloseFcn clears the
MATLAB workspace, including the variables created by the model A OpenFcn callback.

Instead of using a CloseFcn callback for model B, you can use a StopFcn callback in model A to
clear the variables used by the model from the MATLAB workspace. Alternatively, you can use a data
dictionary for the data to avoid the need to have variables in the base workspace.

The simulation mode of a Model block affects when the model callbacks of the referenced model
execute.

Simulation Mode of Behavior


Model Block
Normal During model compilation, Simulink loads each referenced model that is
configured to simulate in normal mode and is not already loaded.

In most cases, Simulink compiles each normal-mode referenced model


once, regardless of the number of Model blocks that reference it.

The InitFcn, StartFcn, PauseFcn, ContinueFcn, and StopFcn model


callbacks execute for each executable form of the model created by the
model compiler.

The referenced models remain loaded after model compilation.


Accelerator During model compilation, Simulink may open and close referenced models
that are configured to simulate in accelerator mode based on their
Rebuild settings and simulation targets. Models that are open before
model compilation remain open.

Simulink does not execute some callbacks.

• If everything is up to date and the Rebuild configuration parameter is


set to If changes in known dependencies detected, then the
referenced model does not compile and its InitFcn callbacks do not
execute.
• Callbacks such as StartFcn and StopFcn do not execute because
referenced models in accelerator mode use an S-function, which starts
and stops instead of the referenced model.

For more information about model reference simulation modes, see “Choose Simulation Modes for
Model Hierarchies” on page 8-45.

4-73
4 Creating a Model

See Also

Related Examples
• “Customize Model Behavior with Callbacks” on page 4-68
• “Block Callbacks” on page 4-75
• “Port Callbacks” on page 4-81
• “View and Trace Callbacks in Models” on page 27-70
• “Fast Restart Methodology” on page 87-10

4-74
Block Callbacks

Block Callbacks
You can specify block callbacks that execute MATLAB code for block events, such as when a block is
loaded, opened, or edited.

1 On the Modeling tab, under Design, click Property Inspector.


2 Select the block whose callback you want to specify.
3 On the Properties tab of the Property Inspector, in the Callbacks section, select the callback
you want to define.
4 In the box, enter the functions you want the callback to perform.

To specify a block callback programmatically, use set_param to assign MATLAB code to the block
callback parameter.

If a block callback executes before or after a modeling action takes place, that callback occurs
immediately before or after the action.

Block Opening Callback Parameters


Block Callback Parameter When Executed
OpenFcn When the block is opened.

Generally, use this parameter with Subsystem blocks.

The callback executes when you double-click the block or when you
use open_system with the block as an argument. The OpenFcn
parameter overrides the normal behavior associated with opening a
block, which is to display the block dialog box or to open the
subsystem. Examples of tasks that you can use OpenFcn for include
defining variables for a block, making a call to MATLAB to produce a
plot of simulated data, or generating a graphical user interface.

After you add an OpenFcn callback to a block, double-clicking the


block does not open the block dialog box. Also, the block parameters
do not appear in the Property Inspector when the block is selected. To
set the block parameters, select Block Parameters from the block
context menu.
LoadFcn After the block diagram is loaded.

For Subsystem blocks, the LoadFcn callback is performed for any


blocks in the subsystem (including other Subsystem blocks) that have
a LoadFcn callback defined.

Block Editing Callback Parameters


Block Callback Parameter When Executed
MoveFcn When the block is moved or resized.

4-75
4 Creating a Model

Block Callback Parameter When Executed


NameChangeFcn After a block name or path changes.

When a Subsystem block path changes, the Subsystem block calls the
NameChangeFcn callback of its descendant blocks and then calls the
NameChangeFcn callback on itself.
PreCopyFcn Before a block is copied. The PreCopyFcn is also executed if
add_block is used to copy the block.

If you copy a Subsystem block that contains a block for which the
PreCopyFcn callback is defined, that callback executes also.

The block CopyFcn callback is called after all PreCopyFcn callbacks


are executed.
CopyFcn After a block is copied. The callback is also executed if add_block is
used to copy the block.

If you copy a Subsystem block that contains a block for which the
CopyFcn parameter is defined, the callback is also executed.
ClipboardFcn When the block is copied or cut to the system clipboard.
PreDeleteFcn Before a block is graphically deleted (for example, when you
graphically delete the block or invoke 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.
DeleteFcn After a block is graphically deleted (for example, 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. 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.

For Subsystem blocks, the DeleteFcn callback is performed for any


blocks in the subsystem (including other Subsystem blocks) that have a
DeleteFcn callback defined.
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


blockDeleteFcn callback is called prior to the DestroyFcn. When the
DestroyFcn is called, the block handle is no longer valid.
UndoDeleteFcn When a block deletion is undone.

4-76
Block Callbacks

Block Compilation and Simulation Callback Parameters


Block Callback Parameter When Executed
InitFcn Before the block diagram is compiled and before block parameters are
evaluated. For more information on InitFcn callback, see
“Initialization Function” on page 4-82.
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”.
ContinueFcn Before the simulation continues.
PauseFcn After the simulation pauses.
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”.

Block Saving and Closing Callback Parameters


Block Callback Parameter When Executed
PreSaveFcn Before the block diagram is saved.

For Subsystem blocks, the PreSaveFcn callback is performed for any


blocks in the subsystem (including other Subsystem blocks) that have a
PreSaveFcn callback defined.
PostSaveFcn After the block diagram is saved.

For Subsystem blocks, the PostSaveFcn callback is performed for any


blocks in the subsystem (including other Subsystem blocks) that have a
PostSaveFcn callback defined.
CloseFcn When the block is closed using close_system.

The CloseFcn is not called when you interactively close the block
parameters dialog box, when you interactively close the subsystem or
model containing the block, or when you close the subsystem or model
containing a block using close_system.

For example, to close all open MATLAB windows, use a command such
as:

set_param('my_model','CloseFcn','close all')

4-77
4 Creating a Model

Block Callback Parameter When Executed


ModelCloseFcn Before the block diagram is closed.

When the model is closed, the block's ModelCloseFcn is called prior


to its DeleteFcn.

For Subsystem blocks, the ModelCloseFcn callback is performed for


any blocks in the subsystem (including other Subsystem blocks) that
have a ModelCloseFcn callback defined.

Subsystem Block Callback Parameters


You can use the other block callback parameters with Subsystem blocks, but the callback parameters
in this table are specific to Subsystem blocks.

Note A callback for a masked subsystem cannot directly reference the parameters of the masked
subsystem (see “Author Block Masks”). 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,
here gain is the name of a mask parameter of the current block:

get_param(gcb, 'gain')

Block Callback Parameter When Executed


DeleteChildFcn After a block or line is deleted in a subsystem.

If the block has a DeleteFcn or DestroyFcn callback, those callbacks


execute prior to the DeleteChildFcn callback.

4-78
Block Callbacks

Block Callback Parameter When Executed


ErrorFcn When an error has occurred in a subsystem.

Use the following form for the callback code for the ErrorFcn
parameter:

newException = errorHandler(subsys, ...


errorType, originalException)

where

• errorHandler is the name of the function.


• subsys is a handle to the subsystem in which the error occurred.
• errorType is a character vector indicating the type of error that
occurred.
• originalException is an MSLException (see “Error Handling in
Simulink Using MSLException Objects” on page 28-23).
• 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:

set_param(subsys,'ErrorFcn','errorHandler')

In such calls to set_param, do not include the input arguments of the


callback code. Simulink displays the error message returned by the
callback.
ParentCloseFcn Before closing a subsystem containing the block or when the block is
made part of a new subsystem using either:

• The new_system function


• The Create Subsystem icon on the Multiple tab, in the Simulink
Editor.

When you close the model, Simulink does not call the
ParentCloseFcn callbacks of blocks at the root model level.

See Also

Related Examples
• “Customize Model Behavior with Callbacks” on page 4-68
• “Model Callbacks” on page 4-70
• “Port Callbacks” on page 4-81
• “View and Trace Callbacks in Models” on page 27-70

4-79
4 Creating a Model

• “Fast Restart Methodology” on page 87-10

4-80
Port Callbacks

Port Callbacks

Block input and output ports have a single callback 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.

Use get_param to get the port handle of a port and set_param to set the callback on the port. The
callback code must have one input argument that represents the port handle. 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 sets
foo as the connection callback on the input port.

phs = get_param(gcb, 'PortHandles');


set_param(phs.Inport, 'ConnectionCallback', 'foo');

foo is defined as:

function foo(portHandle)

See Also

Related Examples
• “Customize Model Behavior with Callbacks” on page 4-68
• “Model Callbacks” on page 4-70
• “Block Callbacks” on page 4-75
• “View and Trace Callbacks in Models” on page 27-70
• “Fast Restart Methodology” on page 87-10

4-81
4 Creating a Model

Initialization Function
An initialization function (InitFcn) is a type of callback that is executed or evaluated at the
beginning of model compilation. You can specify the InitFcn callback as a model or block callback.

Note Variant controls can be defined only in a model InitFcn callback.

Model InitFcn Callback


Use the model InitFcn callback to initialize parameters and environment settings that are specific
to the model, for example:

• Variables used in model parameters


• License checks for the required software

In the Simulink Toolstrip, on the Modeling tab, click the Model Settings arrow, then click Model
Properties. In the Model Properties dialog box, the model InitFcn callback is on the Callbacks tab.

Do not use the model InitFcn callback to:

• Get the simulation status. If you simulate a model with the slbuild function or use software-in-
the-loop (SIL) or rapid accelerator mode, the model InitFcn callback status may show as
'stopped'.
• Run simulation commands. For example, do not use commands such as
set_param(ModelName,'SimulationCommand','start') or
set_param(ModelName,'SimulationCommand','update') in the model InitFcn callback.
• Modify other models. Similarly, the block InitFcn callback of a Model block must not modify the
parameters or structure of the referenced model.
• Overwrite any variables used in a referenced model. For example, if the top model and a
referenced model use the variable k, the model InitFcn callback of the top model must not

4-82
Initialization Function

modify k for the referenced model. In such modeling patterns, use different variable names or a
data dictionary.
• Edit the structure of the model, except to define variant controls. For example, do not use
functions such as add_line or delete_line in the model InitFcn callback.

If you use the InitFcn callback for a model, edit-time checking for missing variables in block
parameters is disabled for the entire model.

For examples of the model InitFcn callback with variants, open the sldemo_variant_initFcn
model. Then, double-click the green block to open a model that uses the recommended workflow. The
model that opens contains Variant Subsystem and Variant Source blocks.

In this model, the model InitFcn callback is used to initialize parameters for the model.

4-83
4 Creating a Model

While you can define these parameters in the model PreLoadFcn or PostLoadFcn callbacks, these
callbacks execute before or after the model loads. Suppose you clear the parameters from the
MATLAB workspace and simulate the model. The model PreLoadFcn and PostLoadFcn callbacks do
not re-create the parameters. When you define the parameters in the model InitFcn callback, model
update and simulation re-create the parameters.

Block InitFcn Callback


Use the block InitFcn callback to initialize parameters and settings of the block.

Right-click the block. Then, click Properties. In the Block Properties dialog box, the block InitFcn
callback is on the Callbacks tab.

4-84
Initialization Function

Do not use the block InitFcn callback to:

• Modify the parameters (or variables) of other blocks, except in the case where you use the
InitFcn callback of a Subsystem block to modify the parameters of its direct child blocks.
• Make structural changes. For example, do not use functions such as add_block or
delete_block in the block InitFcn callback.
• Modify any global variables or variables in the model workspace that another block uses.
• Modify the parameters, structure, or settings of a model referenced by a Model block.

If you use an InitFcn callback for a block, edit-time checking for missing variables in block
parameters is disabled for that block.

See Also

Related Examples
• “Customize Model Behavior with Callbacks” on page 4-68
• “Model Callbacks” on page 4-70
• “Block Callbacks” on page 4-75
• “Manage Model Versions and Specify Model Properties” on page 4-86

4-85
4 Creating a Model

Manage Model Versions and Specify Model Properties


In Simulink, you can manage multiple versions of a model using these techniques:

• Use projects to manage your project files, connect to source control, review modified files, and
compare revisions. See “Project Management”.
• Use model file change notifications to manage work with source control operations and multiple
users. See “Model File Change Notification” on page 4-86.
• Use Simulink.MDLInfo to extract information from a model file without loading the block
diagram into memory. You can use MDLInfo to query 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 a Simulink preference to specify whether to notify you if the model has changed on disk.
You can receive this notification when updating or simulating the model, first editing the model, or
saving the model. The model can change on disk, for example, with source control operations and
multiple users.

In the Simulink Editor, on the Modeling tab, select Environment > Simulink Preferences. In the
Model File pane, under Change Notification, you can select these options:

• If you select First editing the model, the file has changed on disk, and the block diagram is
unmodified in Simulink:

• Any interactive operation that modifies the block diagram (for example, adding a block) causes
a warning to appear.
• Any command-line operation that modifies the block diagram (such as a call to set_param)
causes a warning to appear.
• If you select Saving the model, and the file has changed on disk:

• Saving the model in the Simulink Editor causes a message to appear.


• The save_system function reports an error, unless you use the
OverwriteIfChangedOnDisk option.

To programmatically check whether the model has changed on disk since it was loaded, use the
function slIsFileChangedOnDisk.

For more options that help you work with source control and multiple users, see “Project
Management”.

Manage Model Properties

You can use the Property Inspector to view and edit model version properties, description, and
callback functions. To open the Property Inspector, in the Modeling tab, under Design, click
Property Inspector. Model properties or, if you are in a library model, library properties, appear in
the Property Inspector when nothing is selected at the top level of a model.

4-86
Manage Model Versions and Specify Model Properties

Specify the Current User

When you create or update a model, your name is logged in the model. Simulink assumes that your
name is specified by at least one of the USER, USERNAME, LOGIN, or LOGNAME environment variables.
If your system does not define any of these variables, Simulink 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 in
to your system. Thus, if you are using a UNIX system, you do not have to take further action for
Simulink to identify you as the current user.

Windows systems can define environment variables for user name that Simulink expects, depending
on the version of Windows installed on your system and whether it is connected to a network. Use the
MATLAB function getenv to determine which of the environment variables is defined. For example,
at MATLAB Command Window, enter:

getenv('user')

This function determines whether the USER environment variable exists on your Windows system. If it
does not, set it.

Model Information

The Info tab summarizes information about the current version of the model, such as modifications,
version, and the last saved date. You can view and edit model information and enable, view, and edit
the model change history.

Use the Description section to enter a description of the model. You can then view the model
description by entering help followed by the model name at the MATLAB Command Window.

• Model version

Version number for this model. The major model version is incremented by the number of releases
passed since the model was last saved. The minor model version is reset to zero for every new
release of Simulink and is incremented by one each time you save the model within the same
release.
• Created by

Name of the person who created this model based on the value of the USER environment variable
when the model is created.
• Created on

Date and time this model was created. Do not change this value.
• Last saved by

Name of the person who last saved this model based on the value of the USER environment
variable when the model is saved.
• Last saved on

Date that this model was last saved, based on the system date and time.

4-87
4 Creating a Model

Properties

You can view the source file location, set the model compression level, specify where to save model
design data, and define callbacks in the Properties tab of the model properties.

Note Library properties also enable you to specify the mapping from old library blocks to new library
blocks. For information on using forwarding tables for this purpose, see “Maintain Compatibility of
Library Blocks Using Forwarding Tables” on page 45-37.

Set SLX Compression Level

In the Properties tab of the Property Inspector, you can select one of three SLX Compression
options:

• None applies no compression during the save operation. Turning off compression results in larger
SLX files on disk, but reduces repository size.
• Normal creates the smallest file size.
• Fastest creates a smaller file size than you would get by selecting None, but provides a faster
save time than Normal.

To set the compression level programmatically, use SLXCompressionType.

Starting in R2023b, by default, Simulink applies no compression during the save operation.

Before R2023b, to reduce your Git™ repository size, save Simulink models without compression. This
allows Git to effectively compress the repository history. To use this setting with new SLX files, create
your models using a model template with SLX Compression set to None. See “Create Template from
Model” on page 4-2. For existing SLX files, set the compression and then save the model.
Define Location of Design Data

Use the External Data section to specify the location of the design data that your model uses. You
can define design data in the base workspace or in a data dictionary. See “Migrate Single Model to
Use Dictionary” on page 80-7.
Callbacks

Use the Callbacks section to specify functions to invoke at specific points during the simulation of
the model. Select the callback from the list. In the box, enter the function you want to invoke for the
selected callback. For information on these callbacks, see “Create Model Callbacks” on page 4-70.

Access Model Information Programmatically


Some version information is stored as model parameters in a model. You can access this information
programmatically using the Simulink get_param function.

The table describes the model parameters used by Simulink to store version information.

Property Description
BlockDiagramType Returns model if it is in an open Simulink block
diagram. Returns library if it is a Simulink library.

4-88
Manage Model Versions and Specify Model Properties

Property Description
Created Date created.
Creator Name of the person who created this model.
Description User-entered description of this model. In the Property
Inspector, on the Info tab, enter or edit a description for
the model in the Description box. To view the model
description at the MATLAB Command Window, enter:

help 'mymodelname'
Dirty If the value of this parameter is on, the model has
unsaved changes.
FileName Absolute path where the model is saved.
LastModifiedBy Name of the user who last saved the model.
LastModifiedDate Date when the model was last saved.
MetaData Names and attributes of arbitrary data associated with
the model. For more details, see
Simulink.MDLInfo.getMetadata.
ModifiedByFormat Format of the ModifiedBy parameter. The value can
include the tag %<Auto>. The Simulink software
replaces the tag with the current value of the USER
environment variable.
ModifiedDateFormat Format used to generate the value of the
LastModifiedDate parameter. The value can include
the tag %<Auto>. Simulink replaces the tag with the
current date and time when saving the model.
ModelVersion The major model version is incremented by the number
of releases passed since the model was last saved. The
minor model version is reset to zero for every new
release of Simulink and is incremented by one each time
you save the model within the same release.
ModelVersionFormat The value contains the model format version as
%<AutoIncrement:#.#> where # is an integer.
Simulink increments the model version by # when saving
the model.
PreviousFileName When a PreSaveFcn or PostSaveFcn callback is
running, PreviousFileName indicates the absolute
path of the model before the save operation started.

To find the current absolute path of the model, use


FileName instead.
SavedSinceLoaded Indicates whether the model has been saved since it was
loaded. 'on' indicates the model has been saved.
VersionLoaded Simulink version that last saved the model, e.g., '7.6'.
EnableAccessToBaseWorkspace Whether the model has access to design data and
configuration sets in the base workspace, specified as
'true' or 'false'.

4-89
4 Creating a 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 “Project Management”.

See Also
Model Info

Related Examples
• “Project Management”
• “Model File Change Notification” on page 4-86
• Simulink.MDLInfo

4-90
Model Discretizer

Model Discretizer

In this section...
“What Is the Model Discretizer?” on page 4-91
“Requirements” on page 4-91
“Discretize a Model with the Model Discretizer” on page 4-91
“Model Discretizer Workflow” on page 4-92
“View the Discretized Model” on page 4-96
“Discretize Blocks from the Simulink Model” on page 4-99
“Discretize a Model with the sldiscmdl Function” on page 4-106

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

The Model Discretizer does not support masked subsystems.

Requirements
To use Model Discretizer

• You must have a Control System Toolbox™ license, Version 5.2 or later.
• Make sure your model does not contain any obsolete blocks and is upgraded to the current
Simulink version. For more information, see “Model Upgrades”
• You must convert configurable subsystem blocks in existing models to Variant Subsystem. For
more information, see “Convert Configurable Subsystem to Variant Subsystem” on page 12-269.

Discretize a Model with the Model Discretizer

This example shows how to discretize the f14 model using the Model Discretizer.

model='f14';
open_system(model)

4-91
4 Creating a Model

Model Discretizer Workflow


To discretize a model:

1 “Start Model Discretizer” on page 4-92.


2 “Specify the Transform Method” on page 4-93.
3 “Specify the Sample Time” on page 4-93.
4 “Specify the Discretization Method” on page 4-93.
5 “Discretize the Blocks” on page 4-95.

Start Model Discretizer

To open the tool, in the Simulink Editor, on the Apps tab, under Apps, under Control Systems, click
Model Discretizer.

The Simulink Model Discretizer opens.

Alternatively, you can open Model Discretizer from the MATLAB Command Window using the
slmdldiscui function.

This command sequence opens the Simulink Model Discretizer window with the f14 model:

openExample('f14');
slmdldiscui('f14')

To open a new model or library from Model Discretizer, select File > Load model.

4-92
Model Discretizer

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.

The Transform method list contains the following options:

Transform Method Description


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. For the Model Discretizer, this value must be
numeric.

You can specify an offset time by entering a two-element vector for discrete blocks or variant
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-93.

Specify the Discretization Method

Specify the discretization method in the Replace current selection with field. The options are

Discretization Method Description


“Discrete blocks (Enter parameters in s-domain)” Creates a discrete block whose parameters are
on page 4-93 retained from the corresponding continuous
block.
“Discrete blocks (Enter parameters in z-domain)” Creates a discrete block whose parameters are
on page 4-94 “hard-coded“ values placed directly into the
block's dialog.
“Variant subsystem (Enter parameters in s- Create multiple discretization candidates using s-
domain)” on page 4-95 domain values for the current selection.
“Variant subsystem (Enter parameters in z- Create multiple discretization candidates in z-
domain)” on page 4-95 domain for the current selection.

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.

4-93
4 Creating a Model

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

Note If you generated code from a model, parameters are not tunable when Default parameter
behavior is set to Inlined in the model's Configuration Parameters dialog box.

The following figure shows a continuous Transfer Function block next to a Transfer Function block
that has been discretized in the s-domain with the Tustin transform method. 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

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.

4-94
Model Discretizer

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.

Variant subsystem (Enter parameters in s-domain)

Create multiple discretization candidates using s-domain values for the current selection. Creates a
discrete block whose parameters are retained from the corresponding continuous block.

The Location for block in Variant Subsystem field becomes active when this option is selected.
This option allows you to either create a new variant subsystem.
Variant subsystem (Enter parameters in z-domain)

Create multiple discretization candidates in z-domain for the current selection. Creates a discrete
block whose parameters are “hard-coded“ values placed directly into the block's dialog.

The Location for block in Variant Subsystem field becomes active when this option is selected.
This option allows you to either create a new variant subsystem.

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 Library Link > Disable
Link from the context menu.

4-95
4 Creating a Model

There are two methods for discretizing blocks:

• “Select Blocks and Discretize” on page 4-96


• “Store the Discretization Settings and Apply Them to Selected Blocks in the Model” on page 4-96

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.

Deleting a Discretization Candidate from a Variant Subsystem

You can delete a discretization candidate from a variant subsystem by selecting it in the Location for
block in Variant Subsystem field and clicking the Delete button.

Undoing a Discretization

To undo a discretization, click the Undo discretization button.

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-96
Model Discretizer

The following figure shows that the Aircraft Dynamics Model subsystem has been discretized into a
variant subsystem with two discretization candidates.

The other blocks in this f14 model have not been discretized.

The following figure shows the Aircraft Dynamics Model subsystem of the f14 example model after
discretization into a variant subsystem containing the original continuous model and two
discretization candidates.

The following figure shows the Aircraft Dynamics Model variant subsystem with the two
discretization candidates.

4-97
4 Creating a Model

Refreshing Model Discretizer View of the Model

To refresh the Model Discretizer tree view of the model when the model has been changed, click the
Refresh button.

Alternatively, you can select View > Refresh.

4-98
Model Discretizer

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

The Library: discretizing window opens.

4-99
4 Creating a Model

This library contains s-domain discretized blocks.


4 Add the Discretized Transfer Fcn (with initial states) block to the f14/Aircraft Dynamics Model
window.

a Click the Discretized Transfer Fcn block in the Library: discretizing window.
b Drag it into the f14/Aircraft Dynamics Model window.

4-100
Model Discretizer

5 Open the parameter dialog box for the Transfer Fcn.1 block.

Double-click the Transfer Fcn.1 block in the f14/Aircraft Dynamics Model window.

The Block Parameters: Transfer Fcn.1 dialog box opens.

4-101
4 Creating a Model

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.

The Block Parameters: Discretized Transfer Fcn dialog box opens.

4-102
Model Discretizer

Copy the parameter information from the Transfer Fcn.1 block 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 dropdown list.

The parameter dialog box for the Discretized Transfer Fcn now looks like this.

9 Click OK.

4-103
4 Creating a Model

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.

The f14/Aircraft Dynamics Model window now looks like this.

4-104
Model Discretizer

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.

The f14/Aircraft Dynamics Model window now looks like this.

4-105
4 Creating a Model

Discretize a Model with the sldiscmdl Function


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

See Also
sldiscmdl | slmdldiscui

Related Examples
• Variant Subsystem, Variant Model, Variant Assembly Subsystem
• “Convert Configurable Subsystem to Variant Subsystem” on page 12-269
• “Discrete blocks (Enter parameters in s-domain)” on page 4-93
• “Discrete blocks (Enter parameters in z-domain)” on page 4-94
• “Variant subsystem (Enter parameters in s-domain)” on page 4-95
• “Variant subsystem (Enter parameters in z-domain)” on page 4-95

4-106
Create Model That Performs Neighborhood Processing

Create Model That Performs Neighborhood Processing


In this section...
“Import Image and Output Results” on page 4-107
“Configure Neighborhood Processing Subsystem” on page 4-107
“Simulate and View Results” on page 4-108

This example shows how to create a model that performs neighborhood processing by using the
Neighborhood Processing Subsystem block to blur an image. Neighborhood processing algorithms
operate on images by iteratively processing windows of pixels, called neighborhoods, within the
image.

Import Image and Output Results


The Neighborhood Processing Subsystem block operates on image data. You can use Computer Vision
Toolbox™ blocks to import image data and render images.

1 Create a model that contains a Neighborhood Processing Subsystem block.


2 To import an image, add the Image From File (Computer Vision Toolbox) block to your model.
Double-click the block to open the block dialog. To prevent precision loss, in the Data Types tab,
set the Output data type block parameter to double.
3 Connect the output port of the Image From File block to the input port of the Neighborhood
Processing Subsystem block.
4 To display images, use the Video Viewer (Computer Vision Toolbox) block. Use two Video Viewer
blocks to display the image before and after the Neighborhood Processing Subsystem block.

Configure Neighborhood Processing Subsystem


The Neighborhood Processing Subsystem block accepts a matrix as input and produces a matrix as
output. Inside the subsystem, build an algorithm that accepts a neighborhood of the input matrix as
input and produces a scalar as output. The block handles the processes of iteratively passing each
neighborhood and assembling the output scalars into an output matrix.

4-107
4 Creating a Model

1 Open the Neighborhood Processing Subsystem block.


2 The Neighborhood control block in the subsystem configures the behavior of the subsystem.
Open the Neighborhood block parameters.
3 Set the Neighborhood size parameter to [5 5 1]. The Neighborhood Processing Subsystem
block iterates over 5-by-5 windows for each color channel in the input image. A larger window
size produces more blur.
4 Set the Stride parameter to [1 1 1] and the Processing offset parameter to [0 0 0]. The
input matrix has three dimensions, so the Stride and Processing offset parameters must each
have three elements.
5 Place a Gain block between the Inport and Outport blocks. Set the Gain value to 1/25.
6 Place a Sum of Elements block between the Gain and Outport blocks. The Sum of Elements block
converts a matrix to a scalar. By multiplying the 25 elements of the neighborhood by 1/25 and
summing the values, the subsystem computes the average value of the neighborhood. This
creates a blur effect by blending nearby pixels together.

Simulate and View Results


Simulate the model. The processed image is blurry compared to the original image.

4-108
Create Model That Performs Neighborhood Processing

4-109
4 Creating a Model

See Also
Neighborhood Processing Subsystem

Related Examples
• “Convert RGB Image to Grayscale by Using a Pixel Processing Subsystem Block”
• “Perform Fog Rectification by Using Neighborhood Processing Subsystem Blocks”
• “Perform Edge Detection by Using a Neighborhood Processing Subsystem Block”
• “Perform Corner Detection by Using Neighborhood Processing Subsystem Blocks”
• “Calculate Optical Flow by Using Neighborhood Processing Subsystem Blocks”
• “Generate HDL Code from Frame-Based Models by Using Neighborhood Modeling Methods”
(HDL Coder)
• “Use Neighborhood, Reduction, and Iterator Patterns with a Frame-Based Model or Function for
HDL Code Generation” (HDL Coder)

4-110
Specify Region of Interest for Neighborhood Processing

Specify Region of Interest for Neighborhood Processing

In this section...
“Import Image and Output Results” on page 4-111
“Configure Neighborhood Processing Subsystem” on page 4-111
“Simulate and View Results” on page 4-112

This example shows how to configure a Neighborhood Processing Subsystem block to operate over
only a subsection of an input matrix. This subsection is called a region of interest (ROI).

Import Image and Output Results


The Neighborhood Processing Subsystem block operates on numerical matrices such as image data.
You can use Computer Vision Toolbox blocks to import image data and render images.

1 Create a model that contains a Neighborhood Processing Subsystem block.


2 To import an image, add the Image From File (Computer Vision Toolbox) block to your model.
Double-click the block to open the block dialog. To prevent precision loss, in the Data Types tab,
set the Output data type block parameter to double.
3 Connect the output port of the Image From File block to the input port of the Neighborhood
Processing Subsystem block.
4 To display images, use the Video Viewer (Computer Vision Toolbox) block. Use two Video Viewer
blocks to display the image before and after the Neighborhood Processing Subsystem block.

Configure Neighborhood Processing Subsystem


The input image peppers.png is 384 pixels tall and 512 pixels wide, with three color channels.
Configure the Neighborhood Processing Subsystem block to operate over a 100-by-100 pixel ROI
from inside the input image and return that ROI as it appears in the input image.

1 Open the Neighborhood Processing Subsystem block.

4-111
4 Creating a Model

2 The Neighborhood control block in the subsystem configures the behavior of the subsystem.
Open the Neighborhood block parameters.
3 Set the Neighborhood size and Stride parameters to [1 1 1]. The Neighborhood Processing
Subsystem block iterates over 1-by-1 windows for each of the three color channels in the input
image. Because the Inport block connects directly to the Outport block, the Neighborhood
Processing Subsystem block returns the input pixels as they appear in the input image.
4 Set the Processing offset parameter to [50 40 0]. Instead of beginning by processing the top
left pixel of the input image, the Neighborhood Processing Subsystem block begins iterating from
50 pixels down and 40 pixels to the right.
5 Set the Processing width parameter to [100 100 3]. Instead of iterating over the input image
until reaching the lower and rightmost boundaries of the image, the Neighborhood Processing
Subsystem block processes only a 100-by-100 pixel region of the image beginning from the pixel
you specified in the Processing offset parameter.

Simulate and View Results


Simulate the model. The processed image represents only a section of the original image.

4-112
Specify Region of Interest for Neighborhood Processing

See Also
Neighborhood Processing Subsystem | Neighborhood

Related Examples
• “Create Model That Performs Neighborhood Processing” on page 4-107
• “Use Neighborhood Processing Subsystem Block Padding Options with Region of Interest” on
page 4-114

4-113
4 Creating a Model

Use Neighborhood Processing Subsystem Block Padding


Options with Region of Interest
You can configure the Neighborhood Processing Subsystem block to pad values outside the input
matrix using different padding methods. Use the parameters of the Neighborhood control block to
configure the Neighborhood Processing Subsystem block behavior. This topic explains how the
Padding option parameter interacts with other Neighborhood block parameters.

Overview of Parameters
The Neighborhood Processing Subsystem block iterates over elements of a matrix. For each element,
it processes a neighborhood of values surrounding that element. The Processing width and
Processing offset parameters optionally configure a region of interest (ROI) within the image; the
Neighborhood Processing Subsystem block iterates over only this subsection.

Some neighborhoods contain elements that extend beyond the ROI or input matrix. Because the
Processing width and Processing offset parameters do not allow an ROI to extend beyond the
input matrix, any value outside the input matrix is also outside the ROI. However, neighborhood
elements can extend beyond the ROI while remaining inside the input matrix. The Padding option
parameter specifies how the Neighborhood Processing Subsystem block populates values outside the
input matrix. This parameter does not affect values inside the input matrix, even if those values are
outside the ROI.

For more information about each block parameter, see Neighborhood. For an example of using the
Processing width and Processing offset parameters to specify an ROI, see “Specify Region of
Interest for Neighborhood Processing” on page 4-111.

Example
Consider this matrix.

The blue region represents a 3-by-5 ROI specified by the Processing width parameter value [3 5]
and Processing offset parameter value [0 0]. The orange region represents a 3-by-5 neighborhood,
specified by the Neighborhood size parameter value [3 5], around the value 11 in the input
matrix. a, b, and c denote values outside the ROI. The Neighborhood Processing Subsystem block
determines the values of a, b, and c depending on the padding option you select.

4-114
Use Neighborhood Processing Subsystem Block Padding Options with Region of Interest

Padding option Value at a Value at b Value at c


Constant (with 0 0 16
Padding constant set
to 0)
Replicate 11 16 16
Symmetric 12 16 16
Circular 14 20 16

c is always 16 because it corresponds to the value 16 in the input matrix. The Neighborhood
Processing Subsystem block uses values from the input matrix when possible, even if those values are
outside the ROI. a and b apply the rules of the padding option. If you select a padding option that
reuses values from the input matrix, the Neighborhood Processing Subsystem block extrapolates the
values of a and b from the full input matrix, even when the source of a reused value lies outside the
ROI.

See Also
Neighborhood Processing Subsystem | Neighborhood

Related Examples
• “Create Model That Performs Neighborhood Processing” on page 4-107
• “Specify Region of Interest for Neighborhood Processing” on page 4-111

4-115
5

Model Advisor
5 Model Advisor

Check Your Model Using the Model Advisor

Model Advisor Overview


The Model Advisor checks your model or subsystem for modeling conditions and configuration
settings that cause inaccurate or inefficient simulation of the system that the model represents. The
Model Advisor checks can help you verify compliance with industry standards and guidelines. By
using the Model Advisor, you can implement consistent modeling guidelines across projects and
development teams.

Upon completing the analysis of your model, the Model Advisor produces a report that lists the
suboptimal conditions, settings, and modeling techniques and proposes solutions, when applicable.

You can use the Model Advisor to check your model in these ways:

• Interactively run Model Advisor checks


• Configure the Model Advisor to automatically run edit-time checks (requires Simulink Check™)

These limitations apply when you use the Model Advisor to check your model. For limitations that
apply to specific checks, see the Capabilities and Limitations section in the check documentation.

• 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 the active subsystem. To
check both the active and inactive subsystems, set the Advisor.Application (Simulink Check)
property, AnalyzeVariants, to true.
• Model Advisor does not analyze commented blocks.
• 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.
• Unless specified otherwise in the documentation for a check, the Model Advisor does not analyze
the contents of a Model block. To run checks on referenced models, use instances of the
Advisor.Application class (Simulink Check license required).
• Model Advisor parallel run is not supported in Simulink Online.

Note Software is inherently complex and may not be free of errors. Model Advisor checks might
contain bugs. MathWorks reports known bugs brought to its attention on its Bug Report system at
https://www.mathworks.com/support/bugreports/. The bug reports are an integral part of the
documentation for each release. Examine 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 increases 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
unintended functionality.

5-2
Check Your Model Using the Model Advisor

Model Advisor Checks Documentation

The Model Advisor only displays the checks for your installed products. This table provides links to
the product-specific check documentation. A product license may be required to review some of the
documentation.

Product Model Advisor Check Documentation


Simulink “Simulink Checks”
Embedded Coder® “Embedded Coder Checks” (Embedded Coder)
AUTOSAR Blockset “AUTOSAR Blockset Checks” (AUTOSAR
Blockset)
Simulink Coder™ “Model Advisor Checks” (Simulink Coder)
HDL Coder™ “HDL Code Advisor Checks” (HDL Coder)
Simulink Code Inspector™ “Simulink Code Inspector Checks” (Simulink
Code Inspector)
Simulink Check “Using Model Advisor Checks for High Integrity
System Modeling Guidelines” (Simulink Check)

“Model Advisor Checks for MAB Modeling


Guidelines” (Simulink Check)

“Model Advisor Checks for JMAAB Modeling


Guidelines” (Simulink Check)

“Using Model Advisor Checks for IEC 61508, IEC


62304, ISO 26262, ISO 25119, and EN 50128/EN
50657 Industry Standards” (Simulink Check)

“Model Advisor Checks for DO-178C/DO-331


Industry Standards” (Simulink Check)

“Model Advisor Checks for DO-254 Standard


Compliance” (Simulink Check)

“Using Model Advisor Checks for MISRA C:2012


Coding Standards” (Simulink Check)

“Model Advisor Checks for CERT C, SWE, and


ISO/IEC TS 17961 Coding Standards” (Simulink
Check)

“Model Metrics” (Simulink Check)


Simulink Design Verifier™ “Simulink Design Verifier Checks” (Simulink
Design Verifier)
Simulink PLC Coder™ “PLC Model Advisor Checks” (Simulink PLC
Coder)
Requirements Toolbox “Requirements Consistency Checks”
(Requirements Toolbox)

5-3
5 Model Advisor

Product Model Advisor Check Documentation


Simscape Documentation is available only in the Model
Advisor. To review the documentation for the
check, in the Model Advisor, right-click on the
check title and select What's This?
Simulink Control Design™ “Simulink Control Design Checks” (Simulink
Control Design)
IEC Certification Kit “Model Advisor Checks for ISO 26262, ISO
25119, IEC 61508, IEC 62304, and EN 50128/EN
50657 Industry Standards” (Simulink Check)
DO Qualification Kit “Model Advisor Checks for DO-178C/DO-331
Industry Standards” (Simulink Check)

Run Model Advisor Checks and Review Results


You can use the Model Advisor to check your model interactively against modeling standards and
guidelines. The following example uses the sldemo_mdladv model to demonstrate the execution of
the Model Advisor checks using the Model Advisor.

1 To open the Model Advisor example model, at the MATLAB command line:

openExample('sldemo_mdladv')
2 To open the Model Advisor, in the Simulink editor, click the Modeling tab and select Model
Advisor. A System Selector dialog opens. Select the model or system that you want to review
and click OK.
3 In the left pane of the Model Advisor, select the checks you want to run on your model:

a You can select the checks by using the By Product or By Task folders.

• Show By Product Folder ― Displays checks available for each product


• Show By Task Folder ― Displays checks related to specific tasks

Checks with the icon trigger an update of the model diagram.

Checks with the icon trigger an extensive analysis of the model. Checks that trigger extensive
analysis of the model use additional analysis techniques, such as analysis with Simulink Design
Verifier.
4 Click on the folder that contains the checks and, on the toolstrip, select Run Checks to execute
the analysis. To run a single check, right-click the check in the folder and select Run This
Check.
5 View the results on the Model Advisor User Interface. This table shows the common check status
results; notice that different icons are used depending on the parameter set for Check result
when issues are flagged in the Model Advisor Configuration Editor (requires a Simulink Check
license). For more information about this parameter, see “Specify Parameters for Check
Customization” (Simulink Check).

Check Result Status Icon Description


Passed Model does not have any violations for the
given check(s).

5-4
Check Your Model Using the Model Advisor

Check Result Status Icon Description


Failed Check has identified severe violations.

Warning Check has identified violations.

Justified Check violations are justified.

Not Run Check not selected for Model Advisor


analysis.
Incomplete Check analysis is incomplete or check
execution has resulted in exceptions.
6 Fix the warnings or failures as desired. For more information, see “Address Model Check Results”
on page 5-7.
7 Use the Exclusions tab to review checks that were marked for exclusion from the analysis.
8 View and save the report. For additional information, see “Save and View Model Advisor Check
Reports” on page 5-8 and “Generate Model Advisor Reports” (Simulink Check).

Run Model Checks Programmatically


If you have Simulink Check, you can create MATLAB scripts and functions so that you can run the
Model Advisor programmatically. For example, you can create a ModelAdvisor.run function to
check whether your model passes a specified set of the Model Advisor checks every time that you
open the model and start a simulation.

See Also

Related Examples
• “Run Model Advisor Checks and Review Results” (Simulink Check)
• “Address Model Check Results” on page 5-7
• “Save and View Model Advisor Check Reports” on page 5-8

More About
• “Design Techniques to Optimize Models for Efficient Code Generation” (Simulink Coder)

5-5
5 Model Advisor

Find Model Advisor Check IDs


An ID is a unique identifier for a Model Advisor check. You find check IDs in the Model Advisor, using
check context menus.

To Find Do This
Check Title, ID, or location of 1 On the model window toolbar, in the Modeling tab, select Model Advisor
the MATLAB source code to open the Model Advisor.
2 Select a check from the Check Selector window.
3 In the right pane of the Model Advisor window, the Model Advisor window
displays the check Title, TitleID, and location of the MATLAB source code
for the check.
Check ID 1 In the left pane of the Model Advisor, select the check.
2 Right-click the check name and select Send Check ID to Workspace.
The ID is displayed in the Command Window and sent to the base
workspace.
Check IDs for selected checks 1 In the left pane of the Model Advisor, select the checks for which you want
in a folder IDs. Clear the other checks in the folder.
2 Right-click the folder and select Send Check ID to Workspace. An array
of the selected check IDs are sent to the base workspace.

If you know a check ID from a previous release, you can find the current check ID using the
ModelAdvisor.lookupCheckID function. For example, the check ID for Check for root Outports
with missing range definitions prior to Release 2018b was mathworks.iec61508.OutportRange.
Using the ModelAdvisor.lookupCheckID function returns:

>> NewID = ModelAdvisor.lookupCheckID('mathworks.iec61508.OutportRange')

NewID =
'mathworks.hism.hisl_0026'

See Also
ModelAdvisor.lookupCheckID

Related Examples
• “Run Model Advisor Checks and Review Results” on page 5-4
• “Address Model Check Results” on page 5-7
• “Save and View Model Advisor Check Reports” on page 5-8

More About
• “Check Your Model Using the Model Advisor” on page 5-2

5-6
Address Model Check Results

Address Model Check Results


After you run the Model Advisor checks on page 5-4 to find warnings or failures in your model, you
can use the Model Advisor to fix check warnings or failures manually or by using the Model Advisor.

Fix a Model Advisor Check Warning or Failure


The Model Advisor check results identify model elements that are being flagged by the Model Advisor
check. You can either manually fix the issues or use the Model Advisor to automatically apply a fix.

For more information on why a specific check does not pass, see the documentation for that check.

1 In the Model Advisor results, review the results of the analysis.


2 Fix the warning of failure by using one of these methods:

a To manually fix an issue, use the hyperlinks from the Result Details > Failing Element to
open model elements that are being flagged by the Model Advisor check. You can also apply
batch changes to model parameters from the command line.
b To use the Model Advisor to automatically fix an issue, from the toolstrip, click Fix. The
Action Report box displays a table of changes.
3 To verify that the check passes, rerun the check.

Note After you finish addressing all warnings or failures, it is important that you rerun all
checks to verify that there are no additional issues.

See Also

Related Examples
• “Run Model Advisor Checks and Review Results” (Simulink Check)
• “Save and View Model Advisor Check Reports” on page 5-8
• “Find Model Advisor Check IDs” on page 5-6

More About
• “Check Your Model Using the Model Advisor” on page 5-2

5-7
5 Model Advisor

Save and View Model Advisor Check Reports

When the Model Advisor runs checks, it generates an HTML report of check results. By default, the
HTML report is in the slprj/modeladvisor/model_name folder.

If you have Simulink Check, you can generate reports in Adobe® PDF and Microsoft Word Word
formats.

Save Model Advisor Check Reports


The Model Advisor uses the slprj folder in the Simulink cache folder to store reports and other
information. If the slprj folder does not exist in the Simulink cache folder, the Model Advisor
creates it.

You can save a Model Advisor report to a new location.

1 In the Model Advisor window, navigate to the folder with the checks that you ran.
2 Select the folder. The right pane of the Model Advisor window displays information about that
folder.
3 From the toolstrip, click Report.

Save Report dialog box appears.


4 In the Save Report dialog box, enter the path to the folder where you want to generate the
report. Provide a file name.
5 Click Save. The Model Advisor saves the report in HTML format to the location that you
specified.

Note To change the Report format PDF or WORD, from the toolstrip, use the Report drop-down
options. Simulink Online does support report generation in PDF or WORD format for Model Advisor.

If you rerun the Model Advisor, the report is updated in the working folder, not in the location where
you archived the original report.

The full path to the report is in the title bar of the report window.

The Model Advisor report includes all checks including those that were not run. If you have a
Simulink Check license, you can create a configuration of checks, so that the report includes just
those check results. For more information, see “Use Model Advisor Configuration Editor to Customize
Model Advisor” (Simulink Check).

View Model Advisor Check Reports


Access a report by selecting a folder and clicking the link in the Report box.

Tip Use the options in the Model Advisor window to interactively fix warnings and failures. Model
Advisor reports are best for viewing a summary of checks.

5-8
Save and View Model Advisor Check Reports

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, an informational message appears in the
report. Timestamps 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 timestamp following the
check name.

Goal Action
Display results for checks that Use the Filter checks check boxes. For example, to display results
pass, warn, or fail. for only checks that warn, in the left pane of the report, select the
Warning check box. Clear the Passed, Failed, and Not Run check
boxes.
Display results for checks with Use the Keywords field. Results for checks without the keyword in
keywords or phrases in the the check title are not displayed in the report. For example, to
check title. display results for checks with only “setting” in the check title, in
the Keywords field, enter “setting”.
Quickly navigate to sections of Select the links in the table-of-contents navigation pane.
the report.
Expand and collapse content in Click Show/Hide check details.
the check results.
Scroll to the top of the report. Click Scroll to top.
Minimize folder results in the Click the minus sign next to the folder name.
report.

Printed versions of the report do not contain:

• Filtering checks, Navigation, or View panes.


• Content hidden due to filtering or keyword searching.

Some checks have input parameters specified in the right pane of the Model Advisor. For example,
Check 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.

See Also
Simulink.ModelAdvisor

Related Examples
• “Run Model Advisor Checks and Review Results” (Simulink Check)
• “Address Model Check Results” on page 5-7

5-9
6

Upgrade Advisor
6 Upgrade Advisor

Upgrade Models Using Upgrade Advisor


This example shows you how to fix your Simulink models and upgrade them to the current release by
using Upgrade Advisor. The Upgrade Advisor tool runs checks, fixes errors, and incorporates new
Simulink functionality.

Open Upgrade Advisor


Open the model you want to upgrade.

openExample("vdp")

To open the Upgrade Advisor, on the Modeling tab, select Model Advisor > Upgrade Advisor.

Select and Run Upgrade Checks


Use the Upgrade Advisor to run all selected checks.

1 Select the Upgrade Advisor node.


2 Click Run Selected Checks.

Tip For models with no hierarchy, by default, the Upgrade Advisor selects and runs all checks except
the Analyze model hierarchy and continue upgrade sequence check.

For model hierarchies, use the Analyze model hierarchy and continue upgrade sequence check
to guide you through upgrade checks. You must run upgrade checks in this order: first the checks

6-2
Upgrade Models Using Upgrade Advisor

that do not require compile time information and do not trigger an Update Diagram, then the compile
checks. For more information, see “Analyze model hierarchy and continue upgrade sequence”.

The Upgrade Advisor runs the selected checks and shows a summary in the Report section.

To run one individual check, select the check, then click Run This Check.

Save Results in Report

You can save the results of all checks you run in a report.

1 Select the Upgrade Advisor node.


2 In the Report section, click Save As...
3 Specify the name of the report.

Tip When you fix a check with warnings or failures, rerun the check before you create an Upgrade
Advisor report.

6-3
6 Upgrade Advisor

Investigate and Fix Check Warnings and Failures


Inspect the summary of the checks you run. In this example, two checks show a warning.

To investigate and fix a warning or a failure in a check, follow these steps:

1 Select a check that did not pass.


2 Inspect the Results section to view the analysis and the recommended fixes.
3 Fix the warning or failure manually by following the recommended steps. In some cases, you can
fix issues automatically by clicking the button in the Action section.

Tip For more information on individual upgrade advisor checks, see “Model Upgrades”.

See Also
Upgrade Advisor

Related Examples
• “Model Upgrades”
• “Check Your Model Using the Model Advisor” on page 5-2
• “Address Model Check Results” on page 5-7

6-4
7

Working with Sample Times

• “What Is Sample Time?” on page 7-2


• “Union Rate” on page 7-3
• “Specify Sample Time” on page 7-10
• “View Sample Time Information” on page 7-15
• “Types of Sample Time” on page 7-18
• “Blocks for Which Sample Time Is Not Recommended” on page 7-23
• “Block Compiled Sample Time” on page 7-25
• “Sample Times in Subsystems” on page 7-28
• “Sample Times in Systems and Subsystems” on page 7-29
• “Resolve Rate Transitions” on page 7-34
• “How Propagation Affects Inherited Sample Times” on page 7-37
• “Backpropagation in Sample Times” on page 7-40
• “Modeling for Multitasking Execution” on page 7-41
• “Rate Transitions and Asynchronous Blocks” on page 7-49
• “Handle Rate Transitions” on page 7-53
• “Specify Execution Domain” on page 7-64
7 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. To learn more about rates of execution, see “Types of Sample Time” on
page 7-18.

See Also

More About
• “Specify Sample Time” on page 7-10
• “Types of Sample Time” on page 7-18

7-2
Union Rate

Union Rate
The union sample time of a system is one sample time that unites two or more event sample times.

In the figure, E1 and E2 are independent events that do not preempt each other. The sample time of C
is E3 which is computed using E3 = union(E1,E2). . For example, if an Outport block receives a union
sample time of 2 and 3, then the block runs twice at 0 sample time, once for sample time 2, once for
sample time 3, then at 2, 3, 4, twice again at 6, and so on. For more details on sample time, see
“What Is Sample Time?” on page 7-2.

You can expect union sample time in these scenarios:

• Root-level Inport block – When Allow multiple tasks to access inputs and outputs is enabled for
non-export function models, or when a root-level Inport block has multiple destinations in at least
two different tasks. Union sample time may occur these situations.

• Two destinations have different discrete rates and the model setting Treat each discrete rate
as a separate task is enabled.

• Two destinations have different explicit partitions.

7-3
7 Working with Sample Times

• Two destinations have exported function-call subsystems in an export-function model.

• Root-level Outport block and Merge block – When a Merge block receives input from sources
in at least two different tasks and is connected to the root Outport block. Union sample times may
occur in these situations:

• Two blocks with discrete rates have the model setting Treat each discrete rate as a separate
task enabled, such that the blocks in different tasks, and write to a Merge block connected to a
root Outport block.

7-4
Union Rate

• Two explicit partitions write to a Merge block that is connected to the root output.

• Two exported function-call systems write to the root output via a Merge block.

7-5
7 Working with Sample Times

• Model block – When Allow multiple tasks to access inputs and outputs is enabled for non-export
function models, or when ports of the Model block are accessed in multiple tasks inside the
referenced model. Union sample time may occur in these situations:

• Two discrete rates read or write from the root input or output ports of the referenced model,
and Allow multiple tasks to access inputs and outputs is enabled in the referenced model. In
this case, the Model block will get a union rate on its ports if Treat each discrete rate as a
separate task is enabled in both the referenced and the top models.

• Two explicit partitions access the input or output ports in a referenced model. In this case, the
Model block inputs or outputs will get a union rate.

7-6
Union Rate

• Two exported functions access the input or output ports in a referenced export-function model.
In this case, the Model block will have a union rate if Allow multiple tasks to access inputs and
outputs is enabled in the top model.

• Function-call subsystem and Model block with function-call ports – When the function-call
ports are fed by a muxed signal containing functions calls with different sample times. Union
sample time may occur in these situations:

• A function-call subsystem is called by two callers.

7-7
7 Working with Sample Times

• A function-call port on a Model block is called by two callers.

• A Simulink function has two callers that have different rates in different tasks.

7-8
Union Rate

See Also

More About
• “Specify Sample Time” on page 7-10
• “Types of Sample Time” on page 7-18
• “Sample Times in Systems and Subsystems” on page 7-29
• “Sample Times in Subsystems” on page 7-28

7-9
7 Working with Sample Times

Specify Sample Time


In this section...
“Designate Sample Times” on page 7-10
“Specify Block-Based Sample Times Interactively” on page 7-11
“Specify Port-Based Sample Times Interactively” on page 7-12
“Specify Block-Based Sample Times Programmatically” on page 7-13
“Specify Port-Based Sample Times Programmatically” on page 7-13
“Access Sample Time Information Programmatically” on page 7-13
“Specify Sample Times for a Custom Block” on page 7-13
“Determining Sample Time Units” on page 7-13
“Change the Sample Time After Simulation Start Time” on page 7-13

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. Sample time value must be a double or a two-element array of
double that contains the sample time period and offset. 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 7-18. 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 7-15.)

Designations of Sample Time Information

Sample Time Type Sample Time Annotation Explicit


Discrete [Ts, To] D1, D2, D3, D4, D5, D6, D7,... Yes
Di
Continuous [0, 0] Cont Yes
Fixed in minor step [0, 1] FiM Yes
Inherited [–1, 0] N/A Yes
Constant [Inf, 0] Inf Yes
Variable [–2,Tvo] V1, V2,... Vi No
Multirate N/A N/A No
Asynchronous [–1, –n] A1, A2,... Ai No
Dataflow N/A N/A No

7-10
Specify Sample Time

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

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 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, serves as a reference for this section.

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

ex_specify_sample_time after Setting 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.

7-11
7 Working with Sample Times

To specify and inspect block-based sample times throughout a model, consider using the Model Data
Editor (on the Modeling tab, click Model Data Editor). On the Inports/Outports, Signals, and
Data Stores tabs, set the Change view drop-down list to Design and use the Sample Time column.
For more information, see Model Data Editor.

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:

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.

7-12
Specify Sample Time

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

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
“Specify S-Function Sample Times” in Writing S-Functions of the Simulink documentation.

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.

7-13
7 Working with Sample Times

See Also

More About
• “What Is Sample Time?” on page 7-2
• “Types of Sample Time” on page 7-18

7-14
View Sample Time Information

View Sample Time Information


In this section...
“Inspect Sample Time Using Timing Legend” on page 7-15
“Inspect Sample Times Throughout a Model” on page 7-17

Simulink models can display color coding and annotations that represent specific sample times. You
can display the blocks and signal lines in color. The annotations are badges on the output ports on the
blocks and are colored in black:
1 To enable colors, in the Simulink model window, on the Debug tab, select Information Overlays
> Colors.
2 To enable annotations, on the Debug tab, select Information Overlays > Text.

Selecting both Colors and Text displays both the colors and the annotations. Regardless of your
choice, Simulink performs an Update Model automatically.

To turn off the colors and annotations:


1 On the Debug tab, select Information Overlays > Colors to disable colors.
2 On the Debug tab, select Information Overlays > Text to disable annotations.

When you change these settings, the software automatically performs Update Diagram.

Your sample time display choices directly control the information that the Timing Legend displays.

Note The discrete sample times in the table Designations of Sample Time Information represent a
special case. Five colors indicate the speed 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.

Inspect Sample Time Using Timing Legend

You can view the Timing 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.

To assist you with interpreting a block diagram, the Timing Legend contains the sample time color,
annotation, and value for each sample time in the model. To view the legend:
1 In the Simulink model window, on the Modeling tab, click Update Model.
2 On the Debug tab, select Information Overlays > Legend, or press Ctrl+J.

You can also use the shortcut on the Explorer Bar on the left side of the Simulink Editor.

In addition, when you select Colors or Text, the software updates the model diagram and opens the
legend by default. The legend contents reflect your choices. If you turn colors on, the legend displays
the color and the value of the sample time. If you turn annotations on, the annotations appear in the
legend.

7-15
7 Working with Sample Times

The legend displays sample times present in the model, classified by the type of the sample time. To
avoid clutter, the timing information is displayed in rows that expand to show more information about
each specific sample time. You can expand each row to learn how that specific sample time is
introduced in the model. Check boxes for sample times also allow you to choose specific sample times
to display. The Timing Legend also displays the base rate and scalar multipliers for analysis of the
discrete time-lines.

For discrete sample time, the Time/Freq toggle button allows you to choose the format of the
multiplier information. All discrete sample times are combined into the same row, for example,
periodic partitions, discrete export function etc. Triggered sample time rates are now visualized as
their source sample times, illustrating the sample rate that drives the trigger. Annotations for
aperiodic partition, reset, initialize, reinitialize, and terminate sample times do not use their event
names as annotations but instead have their own concise annotations.

The Timing Legend allows you to highlight the blocks and signals in the model that the sample time
originates from. Expand a sample time row, and then click the hyperlink of the block, to see where
the block is present in the model.

7-16
View Sample Time Information

Note The Timing 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 (0.1 and 0.2) appear in the legend.

Starting in R2023b, you do not need to update the diagram for your model when changing the sample
time visualization options or when launching the Timing Legend after model compilation.

If you do not want to view the legend upon selecting Sample Time Display:

1 In the Simulink Editor, on the Modeling tab, select Environment > Simulink Preferences
2 In the General pane, clear Open the timing legend when the sample time display is
changed and click Apply.

Inspect Sample Times Throughout a Model


The Model Data Editor shows information about model data such as signals, parameters, and states,
in a sortable, searchable table. To open the Model Data Editor, on the Modeling tab, click Model
Data Editor.The Sample Time column shows the sample time specified for each signal in a model.
After you update the block diagram, the column also shows the specific sample that each signal uses.
For example, for signals for which you specify inherited sample time, the column shows -1. You can
also use this column to specify sample times.

For more information, see Model Data Editor.

See Also

More About
• “What Is Sample Time?” on page 7-2
• “Specify the Sample Time” on page 4-93
• “Types of Sample Time” on page 7-18

7-17
7 Working with Sample Times

Types of Sample Time

In this section...
“Discrete Sample Times” on page 7-18
“Continuous Sample Times” on page 7-19
“Events and Asynchronous Sample Times” on page 7-19
“Other Sample Times” on page 7-20
“Multirate Sample Times” on page 7-21
“Dataflow Sample Time” on page 7-21
“Initialize, Reinitialize, Terminate Sample Times” on page 7-22

Discrete Sample Times

Given a block with a discrete sample time, Simulink software 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

Tsim
0≤n≤ .
Ts

As simulation progresses, the software computes block outputs only once at each of these fixed time
intervals of tn. These simulation times at which the software executes the output method of a block
for a given sample time are called 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.

Controllable Sample Time

You can configure a block to use a controllable sample time with a resolution Tbase. Tbase is the
smallest allowable time interval between block executions. To set Tbase in your own C S-Function
block, use the ssSetControllableSampleTime function.

When a block uses controllable sample time, you can dynamically configure the block to execute at n
multiples of Tbase. The time of the next block execution is

Tnext = n Tbase + T (7-1)

You can set n in your C S-Function block using the


ssSetNumTicksToNextHitForControllableSampleTime function.

7-18
Types of Sample Time

Continuous Sample Times


Continuous Sample Time

Continuous sample time hits are divided into major time steps and minor time steps. Minor time steps
are subdivisions of the major time steps. The solver produces a result at each major time step. The
solver uses results at the minor time steps to improve the accuracy of the result at the major time
step.

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. You see the block
output only at the major time steps.

To specify continuous sample time for a block, such as the Derivative block, for the Sample time
parameter, enter [0, 0] or 0.

Fixed-in-Minor-Step Sample Time

If the sample time of a block is [0 1], the block has fixed-in-minor-step sample time. For this sample
time, the block does not execute at the minor time steps. The block executes only at major time steps.
Fixed-in-minor-step sample time eliminates unnecessary computations of blocks with outputs that
cannot change between major steps.

While you can explicitly set a block to fixed-in-minor-step sample time, more often the software sets
this condition as either an inherited sample time or as an alteration to a specification of continuous
sample time. Fixed-in-minor-step sample time is equivalent to the fastest discrete rate in a system
that uses a fixed-step solver. When you use a fixed-step solver, fixed-in-minor-step sample time is
converted to the fastest discrete sample time.

Variable Sample Time

Blocks that use a variable sample time have an implicit sample time parameter that the block
specifies. The block tells the software when it executes. The compiled sample time is [–2 Tvo], where
Tvo is a unique variable offset.

The Hit Scheduler block and the Pulse Generator block both have variable sample time. Variable
sample time is supported only for variable-step solvers. The Hit Scheduler block is not supported for
fixed-step solvers. When you use a fixed-step solver to simulate a model that contains a Pulse
Generator block, the block specifies a discrete sample time.

To learn how to write your own block that uses a variable sample time, see “C MEX S-Function
Examples”.

Events and Asynchronous Sample Times


Asynchronous Sample Time

An asynchronous sample time is similar to a triggered sample time. In both cases, you need to specify
an inherited sample time because the Simulink engine does not regularly execute the block. Instead,

7-19
7 Working with Sample Times

a runtime condition determines when the block executes. For 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 “Using Function-Call
Subsystems” on page 10-53.
• The source of the function-call signal is an S-function that has 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
“Asynchronous Events” (Simulink Coder) in the Simulink Coder User's Guide.
• The sample time is [-1,-n].

For an explanation of how to use blocks to model and generate code for asynchronous event handling,
see “Rate Transitions and Asynchronous Blocks” (Simulink Coder) in the Simulink Coder User's
Guide.

Aperiodic Partitions

Aperiodic partitions in the model introduce this type of sample time. Aperiodic partitions have no
constraints and can be made to execute at any time. You can specify hit times in the Schedule Editor
to drive the timeline of aperiodic partitions. Events can determine the execution timing of the blocks
that have this sample time specified. Subsystem blocks can have an aperiodic as a specified sample
time parameter.

Other Sample Times


Inherited Sample Time

If a block sample time is set to [–1 0] or –1, the sample time is inherited, and software determines
the best sample time for the block based on the context of the block within the model. The software
determines the sample time for blocks with inherited sample time during compilation. Because the
inherited setting is overwritten in compilation, the Sample Time Legend never shows inherited
sample time [-1 0] in a compiled model. For more information, see “View Sample Time Information”
on page 7-15.

Some blocks inherit sample time by default. For these blocks, the parameter is not visible unless you
specify a non-inherited value. For example, the Gain and Rounding Function blocks do not have a
visible sample time parameter and have inherited sample time by default. As a best practice, do not
change the Sample time parameter for these blocks. For more information, see “Blocks for Which
Sample Time Is Not Recommended” on page 7-23.

All inherited blocks are subject to the process of sample time propagation. For more information, see
“How Propagation Affects Inherited Sample Times” on page 7-37.

Constant Sample Time

7-20
Types of Sample Time

In Simulink software, a constant is a symbolic name or expression whose value you can change only
outside the algorithm or through supervisory control. Blocks whose outputs do not change during
normal execution of the model, such as the Constant block, are always considered to be constant.

The software assigns constant sample time to these blocks. They run the block output method:

• At the start of a simulation


• In response to runtime changes in the environment, such as tuning a parameter

For constant sample time, the block sample time assignment is [inf 0] or inf.

For a block to allow constant sample time, the block must not have continuous or discrete states and
must not drive an output port of a conditionally executed subsystem. For more information, see
“Using Enabled Subsystems” on page 10-12.

The Simulink block library includes several blocks whose ports can produce outputs at different
sample rates, such as the MATLAB S-Function block, the Level-2 MATLAB S-Function block, and the
C S-Function block. Some ports of these blocks can have a constant sample time.

Triggered Sample Time

If a block is inside a triggered subsystem, such as a function-call subsystems or enabled subsystem,


the block may be constant or have a triggered sample time, except in the case of an asynchronous
function call. You cannot specify the triggered sample time type explicitly. To achieve a triggered
sample time during compilation, set the block sample time to inherited (–1). The software then
determines the specific times at which the block executes during simulation.

Multirate Sample Times


Union Rate

Union sample times are container sample times that are a union of the component sample times. The
execution for these sample times, is the union of the time-lines of the component sample times.

Multirate Sample Time

Multirate sample time is introduced in the model by the Simulink engine. An Update Diagram turns
the subsystem or any multi-rate block (for example, Rate Transition block) yellow because the blocks
contain more than one sample time.

While assessing a system for multiple sample times, the software does not consider either constant
[inf, 0] or model-wide events. Thus, a subsystem that contains one block with a constant value
output, and one block with a discrete sample time is not be designated as multirate. If blocks have a
continuous and fixed-in-minor-step sample times, these blocks are also not designated as multirate
because the timeline for these sample times is the same. Such blocks are designated as having a
continuous sample time.

Dataflow Sample Time

7-21
7 Working with Sample Times

Blocks that have data flow as their sample time is data driven. For example, Dataflow Subsystem
block. This block uses synchronous dataflow as a model of computation, which is data-driven and
statically scheduled. For more information, see Dataflow Subsystem (DSP System Toolbox).

Initialize, Reinitialize, Terminate Sample Times

You can add custom routines to the default routines using Initialize Function, Reinitialize Function,
and Terminate Function blocks to change or read block states. You can also implement custom
routines using Reset Function blocks. Initialize, reset, terminate sample times are specified when the
Initialize Function, Reinitialize Function, and Terminate blocks are present in a model. These blocks
contain an algorithm or semantics that introduces this sample time in the model.

See Also

More About
• “View Sample Time Information” on page 7-15
• “Specify Sample Time” on page 7-10

7-22
Blocks for Which Sample Time Is Not Recommended

Blocks for Which Sample Time Is Not Recommended

In this section...
“Best Practice to Model Sample Times” on page 7-23
“Appropriate Blocks for the Sample Time Parameter” on page 7-23
“Specify Sample Time in Blocks Where Hidden” on page 7-24

Some blocks do not enable you to set the Sample time parameter by default. However, you can see
and set the Sample time parameter for these blocks in an existing model if the sample time is set to
a value other than the default of -1 (inherited sample time). The Sample time parameter is not
available on certain blocks because specifying a sample time that is not -1 on blocks such as the
Gain, Sum, n-D Lookup Table, Discrete Filter, Discrete FIR Filter, and Discrete Transfer Fcn causes
sample rate transition to be implicitly mixed with block algorithms. This mixing can often lead to
ambiguity and confusion in Simulink models.

In most modeling applications, you specify rates for a model on the boundary of your system instead
of on a block within the subsystem. You specify the system rate from incoming signals or the rate of
sampling the output. You can also decide rates for events you are modeling that enter the subsystem
as trigger, function-call, or enable/disable signals. Some global variables (such as Data Store Memory
blocks) might need additional sample time specification. If you want to change rate within a system,
use a Rate Transition block, which is designed specifically to model rate transitions.

In a future release, you might not be able see or set this parameter on blocks where it is not
appropriate.

Best Practice to Model Sample Times


Use these approaches instead of setting the Sample time parameter in the blocks where it is not
appropriate:

• Adjust your model by specifying Sample time only in the blocks listed in “Appropriate Blocks for
the Sample Time Parameter” on page 7-23, and set Sample time to -1 for all other blocks. To
change the sample time for multiple blocks simultaneously, use Model Explorer. For more
information, see Model Explorer.
• Use the Rate Transition block to model rate transitions in your model.
• Use the Signal Specification block to specify sample time in models that don’t have source blocks,
such as algebraic loops.
• Specify the simulation rate independently from the block sample times, using the Model
Parameter dialog box.

Once you have completed these changes, verify whether your model gives the same outputs as
before.

Appropriate Blocks for the Sample Time Parameter


Specify sample time on the boundary of a model or subsystem, or in blocks designed to model rate
transitions. Examples include:

7-23
7 Working with Sample Times

• Blocks in the Sources library


• Blocks in the Sinks library
• Trigger ports (if Trigger type is set to function-call) and Enable ports
• Data Store Read and Data Store Write blocks, as the Data Store Memory block they link to might
be outside the boundary of the subsystem
• Rate Transition block
• Signal Specification block
• Blocks in the Discrete library other than the Discrete Filter, Discrete FIR Filter, and Discrete
Transfer Fcn blocks
• Message Receive block
• Function Caller block

Specify Sample Time in Blocks Where Hidden


You can specify sample time in the blocks that do not display the parameter on the block dialog box. If
you specify value other than -1 in these blocks, no error occurs when you simulate the model.
However, a message appears on the block dialog box advising to set this parameter to -1 (inherited
sample time). If you promote the sample time block parameter to a mask, this parameter is always
visible on the mask dialog box.

To change the sample time in this case, use the set_param command. For example, select a block in
the Simulink Editor and, at the command prompt, enter:

set_param(gcb,'SampleTime','2');

See Also

More About
• “Resolve Rate Transitions” on page 7-34
• “What Is Sample Time?” on page 7-2
• “Sample Times in Subsystems” on page 7-28
• “Sample Times in Systems and Subsystems” on page 7-29

7-24
Block Compiled Sample Time

Block Compiled Sample Time


During the compilation phase of a simulation, Simulink determines the sample time of a block from
the SampleTime parameter (if the block has an explicit sample time), the block type (if it has an
implicit sample time), or by the model content. 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.

For example, consider the following model.

Use get_param to obtain the block CompiledSampleTime parameter for each of the blocks in this
example.

get_param('model_name/block_name','CompiledSampleTime');

For the Sine Wave3 block,

get_param('ex_compiled_sample_new/Sine Wave3','CompiledSampleTime');

displays

0.5000 0

The atomic subsystem contains sine wave blocks with sample times of 3 and 4.

7-25
7 Working with Sample Times

When calculating the block CompiledSampleTime for this subsystem, Simulink returns a cell array
of the sample times present in the subsystem.

3 0
4 0

The greatest common divisor (GCD) of the two rates is 1. However, this is not necessarily one of the
rates in the model.

The Rate Transition block in this model serves as a Zero-Order Hold. Since the Sample Time
Multiple parameter is set to 3, the input to the rate transition block has a sample rate of 0.5 while
the output has a rate of 1.5.

rt=get_param('ex_compiled_sample_new/Rate Transition',...
'CompiledSampleTime');
rt{:}

0.5000 0
1.5000 0

The Sample Time Legend shows all of the sample rates present in the model.

7-26
Block Compiled Sample Time

To inspect compiled sample times throughout a model, you can use the Model Data Editor (on the
Modeling tab, click Model Data Editor). After you update the block diagram, the right side of the
Sample Time column shows compiled sample times for signals and data stores. For more
information, see Model Data Editor.

See Also

Related Examples
• “Sample Times in Subsystems” on page 7-28
• “View Sample Time Information” on page 7-15

7-27
7 Working with Sample Times

Sample Times in Subsystems


Subsystems fall into two categories: triggered and non-triggered. 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.

There are four non-triggered subsystems:

• Virtual
• Enabled
• Atomic
• 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 SystemSampleTime
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. To obtain the sample time
set on an atomic subsystem, use this command at the command prompt:

get_param(AtomicSubsystemBlock,‘SystemSampleTime’);

Finally, the sample time of the action subsystem is set by the If block or the Switch Case block.

For non-triggered subsystems where blocks have different sample rates, Simulink returns the
Compiled Sample Time for the subsystem as a cell array of all the sample rates present in the
subsystem. To see this, use the get_param command at MATLAB prompt.

get_param(subsystemBlock,'CompiledSampleTime')

See Also

More About
• “Block Compiled Sample Time” on page 7-25
• “Sample Times in Systems and Subsystems” on page 7-29
• “Specify Execution Domain” on page 7-64

7-28
Sample Times in Systems and Subsystems

Sample Times in Systems and Subsystems


In this section...
“Purely Discrete Systems” on page 7-29
“Hybrid Systems” on page 7-31
“Sample Time in Subsystems” on page 7-32

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.

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

7-29
7 Working with Sample Times

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

Running the simulation and plotting the outputs using the stairs function

set_param(bdroot,'SolverType','Variable-Step','SolverName','VariableStepDiscrete','SaveFormat','A
simOut = sim(bdroot,'Stoptime','3');
stairs(simOut.tout,simOut.yout,'-*','LineWidth',1.2);
xlabel('Time (t)');
ylabel('Outputs (out1,out2)');
legend('t_s = [1, 0.1]','t_s = 0.7','location','best')

produces the following plot.

(For information on the sim command. see “Run Simulations Programmatically” on page 28-2. )

7-30
Sample Times in Systems and Subsystems

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.

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

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

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

Car Dynamics Subsystem after an Update Diagram

7-31
7 Working with Sample Times

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

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 that outputs constant
value 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.

Sample Time in Subsystems


Subsystems fall into two categories: triggered and non-triggered. 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.

There are four non-triggered subsystems:

• Virtual
• Enabled

7-32
Sample Times in Systems and Subsystems

• Atomic
• 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 SystemSampleTime
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. To obtain the sample time
set on an atomic subsystem, use this command at the command prompt:

get_param(AtomicSubsystemBlock,‘SystemSampleTime’);

Finally, the sample time of the action subsystem is set by the If block or the Switch Case block.

For non-triggered subsystems where blocks have different sample rates, Simulink returns the
Compiled Sample Time for the subsystem as a cell array of all the sample rates present in the
subsystem. To see this, use the get_param command at MATLAB prompt.

get_param(subsystemBlock,'CompiledSampleTime')

See Also

More About
• “View Sample Time Information” on page 7-15
• “Specify Execution Domain” on page 7-64

7-33
7 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:

• Blocks that output constant value never have 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 manually by inserting rate transition blocks and by using two
diagnostic tools. For the single-tasking execution mode, the Single task data transfer diagnostic
allows you to set the level of Simulink rate transition messages. The Multitask data transfer
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.

Automatic Rate Transition


Simulink can detect mismatched rate transitions in a multitasking model during an update diagram
and automatically insert Rate Transition blocks to handle them. To enable this, in the Solver pane of
model configuration parameters, select Automatically handle rate transition for data transfer.
The default setting for this option is off. When you select this option:

• Simulink handles transitions between periodic sample times and asynchronous tasks.
• Simulink inserts hidden Rate Transition blocks in the block diagram.
• Automatically inserted Rate Transition blocks operate in protected mode for periodic tasks and
asynchronous tasks. You cannot alter this behavior. For periodic tasks, automatically inserted Rate
Transition blocks operate with the level of determinism specified by the Deterministic data
transfer parameter in the Solver pane. The default setting is Whenever possible, which
enables determinism for data transfers between periodic sample-times that are related by an
integer multiple. For more information, see Deterministic data transfer. To use other modes, you
must insert Rate Transition blocks and set their modes manually.

Visualize Inserted Rate Transition Blocks

When you select the Automatically handle rate transition for data transfer option, Simulink
inserts Rate Transition blocks in the paths that have mismatched transition rates. These blocks are
hidden by default. To visualize the inserted blocks, update the diagram. Badge labels appear in the
model and indicate where Simulink inserted Rate Transition blocks during the compilation phase. For
example, in this model, three Rate Transition blocks were inserted between the two Sine Wave blocks
and the Multiplexer and Integrator when the model compiled. The ZOH and DbBuf badge labels
indicate these blocks.

7-34
Resolve Rate Transitions

You can show or hide badge labels. On the Debug tab, select Information Overlays > Automatic
Rate Transitions.

To configure the hidden Rate Transition blocks, right click on a badge label and click on Insert rate
transition block to make the block visible.

When you make hidden Rate Transition blocks visible:

• You can see the type of Rate Transition block inserted as well as the location in the model.
• You can set the Initial Conditions of these blocks.
• You can change data transfer and sample time block parameters.

Validate the changes to your model by updating your diagram.

7-35
7 Working with Sample Times

Displaying inserted Rate Transition blocks is not compatible with export-function models.

To learn more about the types of Rate Transition blocks, see Rate Transition.

Note Suppose you automatically insert rate transition blocks and there is a virtual block specifying
sample time upstream of the block you insert. You cannot click the badge of the inserted block to
configure the block and make it visible because the sample time on the virtual block causes a rate
transition as well. In this case, manually insert a rate transition block before the virtual block. To
learn more about virtual blocks, see “Nonvirtual and Virtual Blocks” on page 40-2.

See Also

Related Examples
• “Handle Rate Transitions” (Simulink Coder)

7-36
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:

Rule Action
All of the inputs have the same sample time and Simulink assigns the sample time to the block
the block can accept that sample time
The inputs have different discrete sample times Simulink assigns the sample time of the fastest
and all of the input sample times are integer input to the block . (This assignment assumes
multiples of the fastest input sample time that the block can accept the fastest sample
time.)
The inputs have different discrete sample times, Simulink assigns a fixed-in-minor-step sample
some of the input sample times are not integer time to the block.
multiples of the fastest sample time, and the
model uses a variable-step solver

7-37
7 Working with Sample Times

Rule Action
The inputs have different discrete sample times, Simulink assigns the GCD sample time to the
some of the input sample times are not integer block. Otherwise, Simulink assigns the fixed step
multiples of the fastest sample time, the model size of the model to the block.
uses a fixed-step solver, and Simulink can
compute the greatest common integer divisor
(GCD) of the sample times coming into the block
The sample times of some of the inputs are Simulink determines a sample time for the block
unknown, or if the block cannot accept the based on a set of heuristics.
sample time

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 Information Overlays > Colors from the Debug
tab of the Simulink toolstrip 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, on the Modeling tab, selecting Update Model to update the colors. Both blocks now
appear black.

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.

7-38
How Propagation Affects Inherited Sample Times

See Also

More About
• “Blocks for Which Sample Time Is Not Recommended” on page 7-23
• “Backpropagation in Sample Times” on page 7-40

7-39
7 Working with Sample Times

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 Information Overlays > Colors from the Debug
tab of the Simulink toolstrip 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, on the Modeling tab, selecting Update Model to update the colors. Both blocks now
appear black.

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.

See Also

More About
• “View Sample Time Information” on page 7-15
• “How Propagation Affects Inherited Sample Times” on page 7-37

7-40
Modeling for Multitasking Execution

Modeling for Multitasking Execution

Multitasking and Pseudomultitasking Modes


When periodic tasks execute in a multitasking mode, by default the blocks with the fastest sample
rates are executed by the task with the highest priority, the next fastest blocks are executed by a task
with the next higher priority, and so on. Time available in between the processing of high-priority
tasks is used for processing lower priority tasks. This results in efficient program execution.

Where tasks are asynchronous rather than periodic, there may not necessarily be a relationship
between sample rates and task priorities; the task with the highest priority need not have the fastest
sample rate. You specify asynchronous task priorities using Async Interrupt and Task Sync blocks.
You can switch the sense of what priority numbers mean by selecting or clearing model configuration
parameter Higher priority value indicates higher task priority.

In multitasking environments (that is, under a real-time operating system), you can define separate
tasks and assign them priorities. For bare-metal target hardware (that is, no real-time operating
system present), you cannot create separate tasks. However, generated application modules
implement what is effectively a multitasking execution scheme using overlapped interrupts,
accompanied by programmatic context switching.

This means an interrupt can occur while another interrupt is currently in progress. When this
happens, the current interrupt is preempted, the floating-point unit (FPU) context is saved, and the
higher priority interrupt executes its higher priority (that is, faster sample rate) code. Once complete,
control is returned to the preempted ISR.

The next figures illustrate how timing of tasks in multirate systems are handled by the code generator
in multitasking, pseudomultitasking, and single-tasking environments.

7-41
7 Working with Sample Times

The next figure shows how overlapped interrupts are used to implement pseudomultitasking. In this
case, Interrupt 0 does not return until after Interrupts 1, 2, and 3.

7-42
Modeling for Multitasking Execution

Build a Program for Multitasking Execution


To use multitasking execution, select model configuration parameter Treat each discrete rate as a
separate task. This parameter is active only if you set Solver type to Fixed-step. Auto mode
results in a multitasking environment if your model has two or more different sample times. A model
with a continuous and a discrete sample time runs in single-tasking mode if the fixed-step size is
equal to the discrete sample time.

Execute Multitasking Models


In cases where the continuous part of a model executes at a rate that is different from the discrete
part, or a model has blocks with different sample rates, the Simulink engine assigns each block a task
identifier (tid) to associate the block with the task that executes at the block's sample rate.

You set sample rates and their constraints on the Solver pane of the Model Configuration Parameters
dialog box. To generate code, select Fixed-step for the solver type. Certain restrictions apply to the
sample rates that you can use:

• The sample rate of a block must be an integer multiple of the base (that is, the fastest) sample
period.
• When you set model configuration parameter Periodic sample time constraint to
unconstrained, the base sample period is determined by the setting of parameter Fixed step
size.
• When you set parameter Periodic sample time constraint to Specified, the base rate fixed-
step size is the first element of the sample time matrix that you specify for parameter Sample
time properties. The Solver pane from the example model
MultirateMultitaskingBareBoard shows an example.

7-43
7 Working with Sample Times

• Continuous blocks execute by using an integration algorithm that runs at the base sample rate.
The base sample period is the greatest common denominator of rates in the model only when you
set model configuration parameter Periodic sample time constraint to Unconstrained and
parameter Fixed step size to Auto.
• The continuous and discrete parts of the model can execute at different rates only if the discrete
part is executed at the same or a slower rate than the continuous part and is an integer multiple of
the base sample rate.

Multitasking Execution
You can simulate and execute code generated from this simple multirate model, which is configured
to use a fixed-step solver, in single-tasking or multitasking mode.

7-44
Modeling for Multitasking Execution

The tasking mode that gets applied depends on the setting of model configuration parameter Treat
each discrete rate as a separate task. When cleared, the parameter specifies single-tasking mode.
When selected, the parameter specifies multitasking mode.

The example description refers to the six blocks in the model as A through F.

The execution order of the blocks (indicated in the upper right of each block) is forced into the order
shown by assigning higher priorities to blocks F, E, and D. The ordering shown is one possible valid
execution ordering for this model. For more information, see “Simulation Phases in Dynamic
Systems” on page 3-2.

The execution order is determined by data dependencies between blocks. In a real-time system, the
execution order determines the order in which blocks execute within a given time interval or task.
This discussion treats the model execution order as a given, because it is concerned with the
allocation of block computations to tasks, and the scheduling of task execution.

Note The discussion and timing diagrams in this section are based on the assumption that the Rate
Transition blocks are used in the default (protected) mode, with block parameters Ensure data
integrity during data transfer and Ensure deterministic data transfer (maximum delay)
selected.

When this model is configured for multitasking, block computations are executed under two tasks,
prioritized by rate:

• The slower task, which gets the lower priority, is scheduled to run every second. This is called the
1 second task.
• The faster task, which gets higher priority, is scheduled to run 10 times per second. This is called
the 0.1 second task. The 0.1 second task can preempt the 1 second task.

For each block in the model, this table shows the execution order, the task under which the block
runs, and whether the block has an output or update computation. Blocks A and B do not have
discrete states, and accordingly do not have an update computation.

Blocks Task Output Update


(in Execution Order)
E 0.1 second task Y Y
F 0.1 second task Y Y

7-45
7 Working with Sample Times

Blocks Task Output Update


(in Execution Order)
D The Rate Transition Y Y
block uses port-based
sample times.
Output runs at the
output port sample time
under 0.1 second task.
Update runs at input
port sample time under
1 second task.
For more information on
port-based sample
times, see “Referenced
Model Sample Times”
on page 8-41.
A 0.1 second task Y N
B The Rate Transition Y N
block uses port-based
sample times.
Output runs at the
output port sample time
under 0.1 second task.
For more information on
port-based sample
times, see “Referenced
Model Sample Times”
on page 8-41.
C 1 second task Y Y

Real-Time Multitasking Execution

This figure shows the scheduling of computations when the generated code is deployed in a real-time
system in multitasking mode. The generated program is shown running in real time as two tasks
under control of interrupts from a 10 Hz timer.

7-46
Modeling for Multitasking Execution

Simulated Multitasking Execution

This figure shows the execution of the model during a Simulink simulation loop.

This figure shows a simulation of the model in multitasking mode. The Simulink engine runs the
blocks in one thread of execution, simulating multitasking. Preemption does not occur.

7-47
7 Working with Sample Times

See Also

More About
• “Time-Based Scheduling and Code Generation” (Simulink Coder)
• “Configure Time-Based Scheduling” (Simulink Coder)
• “Resolve Rate Transitions” on page 7-34
• “Handle Rate Transitions” (Simulink Coder)
• “Time-Based Scheduling Example Models” (Simulink Coder)

7-48
Rate Transitions and Asynchronous Blocks

Rate Transitions and Asynchronous Blocks


Because an asynchronous function call subsystem can preempt or be preempted by other model code,
an inconsistency arises when more than one signal element is connected to an asynchronous block.
The issue is that signals passed to and from the function call subsystem can be in the process of being
written to or read from when the preemption occurs. Thus, some old and some new data is used. This
situation can also occur with scalar signals in some cases. For example, if a signal is a double (8
bytes), the read or write operation might require two machine instructions.

About Rate Transitions and Asynchronous Blocks


The Simulink Rate Transition block is designed to deal with preemption problems that occur in data
transfer between blocks running at different rates. These issues are discussed in “Time-Based
Scheduling and Code Generation” (Simulink Coder).

You can handle rate transition issues automatically by selecting model configuration parameter
Automatically handle rate transition for data transfer. This saves you from having to manually
insert Rate Transition blocks to avoid invalid rate transitions, including invalid asynchronous-to-
periodic and asynchronous-to-asynchronous rate transitions, in multirate models. For asynchronous
tasks, the Simulink engine configures inserted blocks for data integrity but not determinism during
data transfers.

For asynchronous rate transitions, the Rate Transition block provides data integrity, but cannot
provide determinism. Therefore, when you insert Rate Transition blocks explicitly, you must clear the
block parameter Ensure deterministic data transfer (maximum delay).

When you insert a Rate Transition block between two blocks to maintain data integrity and priorities
are assigned to the tasks associated with the blocks, the code generator assumes that the higher
priority task can preempt the lower priority task and the lower priority task cannot preempt the
higher priority task. If the priority associated with task for either block is not assigned or the
priorities of the tasks for both blocks are the same, the code generator assumes that either task can
preempt the other task.

Priorities of periodic tasks are assigned by the Simulink engine, in accordance with the parameters
specified in the Solver selection section of the Solver pane of the Configuration Parameters dialog
box. When the Periodic sample time constraint parameter is set to Unconstrained, the model
base rate priority is set to 40. Priorities for subrates then increment or decrement by 1 from the base
rate priority, depending on the setting of parameter Higher priority value indicates higher task
priority.

You can assign priorities manually by using parameter Periodic sample time properties. The
Simulink engine does not assign a priority to asynchronous blocks. For example, the priority of a
function call subsystem that connects back to an Async Interrupt block is assigned by the Async
Interrupt block.

Block parameter Simulink task priority of the Async Interrupt block specifies a priority level
(required) for every interrupt number entered for parameter VME interrupt number(s). The
priority array sets the priorities of the subsystems connected to each interrupt.

For the Task Sync block, if the example RTOS (VxWorks®) is the target, clear block parameter Higher
priority value indicates higher task priority. Parameter Simulink task priority specifies the
block priority relative to connected blocks (in addition to assigning an RTOS priority to the generated
task code).

7-49
7 Working with Sample Times

The vxlib1 library provides two types of rate transition blocks as a convenience. These are simply
preconfigured instances of the Rate Transition block:

• Protected Rate Transition block: Rate Transition block that is configured with block parameter
Ensure data integrity during data transfers selected and Ensure deterministic data
transfer cleared.
• Unprotected Rate Transition block: Rate Transition block that is configured with the Ensure data
integrity during data transfers cleared.

Handle Rate Transitions for Asynchronous Tasks


For rate transitions that involve asynchronous tasks, you can maintain data integrity. However, you
cannot achieve determinism. You have the option of using the Rate Transition block or target-specific
rate transition blocks.

Consider the following model, which includes a Rate Transition block.

You can use the Rate Transition block in either of the following modes:

• Maintain data integrity, no determinism


• Unprotected

Alternatively, you can use target-specific rate transition blocks. The following blocks are available for
the example RTOS (VxWorks):

• Protected Rate Transition block (reader)


• Protected Rate Transition block (writer)
• Unprotected Rate Transition block

Handle Multiple Asynchronous Interrupts


Consider the following model, in which two functions trigger the same subsystem.

7-50
Rate Transitions and Asynchronous Blocks

The two tasks must have equal priorities. When priorities are the same, the outcome depends on
whether they are firing periodically or asynchronously, and also on a diagnostic setting. The following
table and notes describe these outcomes:

Supported Sample Time and Priority for Function Call Subsystem with Multiple Triggers

Async Priority = Async Priority = Async Priority Periodic Priority Periodic Priority
1 2 Unspecified =1 =2
Async Priority = Supported (1)
1
Async Priority = Supported (1)
2
Async Priority Supported (2)
Unspecified
Periodic Priority Supported
=1
Periodic Priority Supported
=2

1 Control these outcomes by using model configuration parameter Tasks with equal priority ; set
this diagnostic to none if tasks of equal priority cannot preempt each other in the target system.
2 For this case, the following warning message is issued unconditionally:

The function call subsystem <name> has multiple asynchronous


triggers that do not specify priority. Data integrity will
not be maintained if these triggers can preempt one another.

Empty cells in the above table represent multiple triggers with differing priorities, which are
unsupported.

The code generator provides absolute time management for a function call subsystem connected to
multiple interrupts in the case where timer settings for TriggerA and TriggerB (time source,
resolution) are the same.

Assume that all of the following conditions are true for the model shown above:

• A function call subsystem is triggered by two asynchronous triggers (TriggerA and TriggerB)
having identical priority settings.
• Each trigger sets the source of time and timer attributes by calling the functions
ssSetTimeSource and ssSetAsyncTimerAttributes.

7-51
7 Working with Sample Times

• The triggered subsystem contains a block that needs elapsed or absolute time (for example, a
Discrete Time Integrator).

The asynchronous function call subsystem has one global variable, clockTick# (where # is the task
ID associated with the subsystem). This variable stores absolute time for the asynchronous task.
There are two ways timing can be handled:

• If the time source is set to SS_TIMESOURCE_BASERATE, the code generator produces timer code
in the function call subsystem, updating the clock tick variable from the base rate clock tick. Data
integrity is maintained if the same priority is assigned to TriggerA and TriggerB.
• If the time source is SS_TIMESOURCE_SELF, generated code for both TriggerA and TriggerB
updates the same clock tick variable from the hardware clock.

The word size of the clock tick variable can be set directly or be established according to setting of
model configuration parameter Application lifespan (days) and the timer resolution set by the
TriggerA and TriggerB S-functions (which must be the same). See “Timers in Asynchronous Tasks”
(Simulink Coder) and “Optimize Memory Usage and Prevent Overflows for Time Counters” (Simulink
Coder) for more information.

Protect Data Integrity with volatile Keyword


When you select block parameter Ensure data integrity during data transfer, the code generated
for a Rate Transition block defines volatile global buffers and semaphores and uses them to
protect the integrity of the transferred data. For additional protection, or for protection without a
Rate Transition block, you can explicitly apply volatile to the transferred data. For more
information, see “Protect Global Data with const and volatile Type Qualifiers” (Embedded Coder).

See Also

More About
• “Handle Rate Transitions” (Simulink Coder)

7-52
Handle Rate Transitions

Handle Rate Transitions


Rate Transitions
Two periodic sample rate transitions can exist within a model:

• A faster block driving a slower block


• A slower block driving a faster block

The following sections concern models with periodic sample times with zero offset only. Other
considerations apply to multirate models that involve asynchronous tasks. For details on how to
generate code for asynchronous multitasking, see “Asynchronous Support” (Simulink Coder).

In multitasking and pseudomultitasking systems, differing sample rates can cause blocks to be
executed in the wrong order. To prevent possible errors in calculated data, you must control model
execution at these transitions. When connecting faster and slower blocks, you or the Simulink engine
must add Rate Transition blocks between them. Fast-to-slow transitions are illustrated in the next
figure.

Slow-to-fast transitions are illustrated in the next figure.

7-53
7 Working with Sample Times

Note Although the Rate Transition block offers a superset of the capabilities of the Unit Delay block
(for slow-to-fast transitions) and the Zero-Order Hold block (for fast-to-slow transitions), you should
use the Rate Transition block instead of these blocks.

Data Transfer Problems


Rate Transition blocks deal with issues of data integrity and determinism associated with data
transfer between blocks running at different rates.

• Data integrity: A problem of data integrity exists when the input to a block changes during the
execution of that block. Data integrity problems can be caused by preemption.

Consider the following scenario:

• A faster block supplies the input to a slower block.


• The slower block reads an input value V1 from the faster block and begins computations using
that value.
• The computations are preempted by another execution of the faster block, which computes a
new output value V2.
• A data integrity problem now arises: when the slower block resumes execution, it continues its
computations, now using the “new” input value V2.

Such a data transfer is called unprotected. “Faster to Slower Transitions in Real Time” (Simulink
Coder) shows an unprotected data transfer.

In a protected data transfer, the output V1 of the faster block is held until the slower block finishes
executing.
• Deterministic versus nondeterministic data transfer: In a deterministic data transfer, the timing of
the data transfer is completely predictable, as determined by the sample rates of the blocks.

The timing of a nondeterministic data transfer depends on the availability of data, the sample
rates of the blocks, and the time at which the receiving block begins to execute relative to the
driving block.

You can use the Rate Transition block to protect data transfers in your application and make them
deterministic. These characteristics are considered desirable in most applications. However, the Rate
Transition block supports flexible options that allow you to compromise data integrity and
determinism in favor of lower latency. The next section summarizes these options.

Data Transfer Assumptions


When processing data transfers between tasks, the code generator makes these assumptions:

• Data transitions occur between a single reading task and a single writing task.
• A read or write of a byte-sized variable is atomic.
• When two tasks interact through a data transition, only one of them can preempt the other.
• For periodic tasks, the faster rate task has higher priority than the slower rate task; the faster rate
task preempts the slower rate task.
• All tasks run on a single processor. Time slicing is not allowed.

7-54
Handle Rate Transitions

• Processes do not crash or restart (especially while data is transferred between tasks).

Rate Transition Block Options


Several parameters of the Rate Transition block are relevant to its use in code generation for real-
time execution, as discussed below. For a complete block description, see Rate Transition.

The Rate Transition block handles periodic (fast to slow and slow to fast) and asynchronous
transitions. When inserted between two blocks of differing sample rates, the Rate Transition block
automatically configures its input and output sample rates for the type of transition; you do not need
to specify whether a transition is slow-to-fast or fast-to-slow (low-to-high or high-to-low priorities for
asynchronous tasks).

The critical decision you must make in configuring a Rate Transition block is the choice of data
transfer mechanism to be used between the two rates. Your choice is dictated by considerations of
safety, memory usage, and performance. As the Rate Transition block parameter dialog box in the
next figure shows, the data transfer mechanism is controlled by two options.

• Ensure data integrity during data transfer: When you select this parameter, data transferred
between rates maintains its integrity (the data transfer is protected). When you clear this
parameter, data might not maintain its integrity (the data transfer is unprotected). By default,
parameter Ensure data integrity during data transfer is selected.
• Ensure deterministic data transfer (maximum delay): This parameter is supported for
periodic tasks with an offset of zero and fast and slow rates that are multiples of each other. When
this parameter is selected, the Rate Transition block behaves like a Zero-Order Hold block (for
fast to slow transitions) or a Unit Delay block (for slow to fast transitions). The Rate Transition

7-55
7 Working with Sample Times

block controls the timing of data transfer in a completely predictable way. When this parameter is
cleared, the data transfer is nondeterministic. By default, Ensure deterministic data transfer
(maximum delay) is selected for transitions between periodic rates with an offset of zero; for
asynchronous transitions, it cannot be selected.

The Rate Transition block offers three modes of operation with respect to data transfer. In order of
level of safety:

• Protected/Deterministic (default): This is the safest mode. The drawback of this mode is that it
introduces deterministic latency into the system for the case of slow-to-fast periodic rate
transitions. For that case, the latency introduced by the Rate Transition block is one sample
period of the slower task. For the case of fast-to-slow periodic rate transitions, the Rate Transition
block does not introduce additional latency.
• Protected/NonDeterministic: In this mode, for slow-to-fast periodic rate transitions, data
integrity is protected by double-buffering data transferred between rates. For fast-to-slow periodic
rate transitions, a semaphore flag is used. The blocks downstream from the Rate Transition block
use the latest available data from the block that drives the Rate Transition block. Maximum
latency is less than or equal to one sample period of the faster task.

The drawbacks of this mode are its nondeterministic timing. The advantage of this mode is its low
latency.
• Unprotected/NonDeterministic: This mode is not recommended for mission-critical
applications. The latency of this mode is the same as for Protected/NonDeterministic mode, but
memory requirements are reduced since neither double-buffering nor semaphores are required.
That is, the Rate Transition block does nothing in this mode other than to pass signals through; it
simply exists to notify you that a rate transition exists (and can cause generated code to compute
incorrect answers). Selecting this mode, however, generates the least amount of code.

Note In unprotected mode (Ensure data integrity during data transfer is selected), the Rate
Transition block does nothing other than allow the rate transition to exist in the model.

Rate Transition Blocks and Continuous Time

The sample time at the output port of a Rate Transition block can only be discrete or fixed in minor
time step. This means that when a Rate Transition block inherits continuous sample time from its
destination block, it treats the inherited sample time as Fixed in Minor Time Step. Therefore, the
output function of the Rate Transition block runs only at major time steps. If the destination block
sample time is continuous, Rate Transition block output sample time is the base rate sample time (if
solver is fixed-step), or zero-order-hold-continuous sample time (if solver is variable-step).

Automatic Rate Transition


The Simulink engine can detect mismatched rate transitions in a multitasking model during an
update diagram and automatically insert Rate Transition blocks to handle them. To enable this, select
model configuration parameter Automatically handle rate transition for data transfer. By
default, this parameter is cleared. When you select this parameter:

• Simulink handles transitions between periodic sample times and asynchronous tasks.
• Simulink inserts hidden Rate Transition blocks in the block diagram.

7-56
Handle Rate Transitions

• The code generator produces code for the Rate Transition blocks that were automatically inserted.
This code is identical to the code generated for Rate Transition blocks that were inserted
manually.
• Automatically inserted Rate Transition blocks operate in protected mode for periodic tasks and
asynchronous tasks. You cannot alter this behavior. For periodic tasks, automatically inserted Rate
Transition blocks operate with the level of determinism specified by model configuration
parameter Deterministic data transfer. The default setting is Whenever possible, which
enables determinism for data transfers between periodic sample-times that are related by an
integer multiple. For more information, see Deterministic data transfer. To use other modes, you
must insert Rate Transition blocks and set their modes manually.

For example, in this model, SineWave2 has a sample time of 2, and SineWave3 has a sample time of 3.

When you select model configuration parameter Automatically handle rate transition for data
transfer, Simulink inserts a Rate Transition block between each Sine Wave block and the Product
block. The inserted blocks have the parameter values to reconcile the Sine Wave block sample times.

If the input port and output port data sample rates in a model are not multiples of each other,
Simulink inserts a Rate Transition block whose sample rate is the greatest common divisor (GCD) of
the two rates. If no other block in the model contains this new rate, an error occurs during
simulation. In this case, you must insert a Rate Transition block manually.

Visualize Inserted Rate Transition Blocks


When you select model configuration parameter Automatically handle rate transition for data
transfer, Simulink inserts Rate Transition blocks in the paths that have mismatched transition rates.
These blocks are hidden by default. To visualize the inserted blocks, update the diagram. Badge
labels appear in the model and indicate where Simulink inserted Rate Transition blocks during the
compilation phase. For example, in this model, three Rate Transition blocks were inserted between
the two Sine Wave blocks and the Multiplexer and Integrator when the model compiled. The ZOH and
DbBuf badge labels indicate these blocks.

7-57
7 Working with Sample Times

You can show or hide badge labels. Open the Debug tab. In the Diagnostics section of the
Information Overlays/Sample Time gallery select or clear Automatic Rate Transitions.

To configure the hidden Rate Transition blocks so that the blocks are visible, right-click a badge label
and click Insert rate transition block.

When you make hidden Rate Transition blocks visible:

• You can see the type of Rate Transition block inserted and the location of the block in the model.
• You can set the block parameter Initial Conditions.
• You can change block parameter settings for rate transfer.

Validate the changes to your model by updating your diagram.

7-58
Handle Rate Transitions

Displaying inserted Rate Transition blocks is not compatible with export-function models.
To learn more about the types of Rate Transition blocks, see Rate Transition.

Periodic Sample Rate Transitions


These sections describe cases in which Rate Transition blocks are required for periodic sample rate
transitions. The discussion and timing diagrams in these sections are based on the assumption that
the Rate Transition block is used in its default (protected/deterministic) mode. Model configuration
parameters Ensure data integrity during data transfer and Ensure deterministic data transfer
(maximum delay) are selected. These are the settings used for automatically inserted Rate
Transition blocks.

Faster to Slower Transitions in a Simulink Model

In a model where a faster block drives a slower block having direct feedthrough, the outputs of the
faster block are computed first. In simulation intervals where the slower block does not execute, the
simulation progresses more rapidly because there are fewer blocks to execute. The next figure
illustrates this situation.

A Simulink simulation does not execute in real time, which means that it is not bound by real-time
constraints. The simulation waits for, or moves ahead to, whatever tasks are required to complete
simulation flow. The actual time interval between sample time steps can vary.

Faster to Slower Transitions in Real Time

In models where a faster block drives a slower block, you must compensate for the fact that execution
of the slower block might span more than one execution period of the faster block. This means that
the outputs of the faster block can change before the slower block has finished computing its outputs.
The next figure shows a situation in which this problem arises (T = sample time). Note that lower
priority tasks are preempted by higher priority tasks before completion.

7-59
7 Working with Sample Times

In the above figure, the faster block executes a second time before the slower block has completed
execution. This can cause unpredictable results because the input data to the slow task is changing.
Data might not maintain its integrity in this situation.

To avoid this situation, the Simulink engine must hold the outputs of the 1 second (faster) block until
the 2 second (slower) block finishes executing. The way to accomplish this is by inserting a Rate
Transition block between the 1 second and 2 second blocks. The input to the slower block does not
change during its execution, maintaining data integrity.

It is assumed that the Rate Transition block is used in its default (protected/deterministic) mode.

The Rate Transition block executes at the sample rate of the slower block, but with the priority of the
faster block.

When you add a Rate Transition block, the block executes before the 2 second block (its priority is
higher) and its output value is held constant while the 2 second block executes (it executes at the
slower sample rate).

7-60
Handle Rate Transitions

Slower to Faster Transitions in a Simulink Model

In a model where a slower block drives a faster block, the Simulink engine again computes the output
of the driving block first. During sample intervals where only the faster block executes, the simulation
progresses more rapidly.

The next figure shows the execution sequence.

As you can see from the preceding figures, the Simulink engine can simulate models with multiple
sample rates in an efficient manner. However, a Simulink simulation does not operate in real time.

Slower to Faster Transitions in Real Time

In models where a slower block drives a faster block, the generated code assigns the faster block a
higher priority than the slower block. This means the faster block is executed before the slower block,
which requires special care to avoid incorrect results.

This timing diagram illustrates two problems:

• Execution of the slower block is split over more than one faster block interval. In this case the
faster task executes a second time before the slower task has completed execution. This means
the inputs to the faster task can have incorrect values some of the time.
• The faster block executes before the slower block (which is backward from the way a Simulink
simulation operates). In this case, the 1 second block executes first; but the inputs to the faster
task have not been computed. This can cause unpredictable results.

To eliminate these problems, you must insert a Rate Transition block between the slower and faster
blocks.

7-61
7 Working with Sample Times

It is assumed that the Rate Transition block is used in its default (protected/deterministic) mode.

The next figure shows the timing sequence that results with the added Rate Transition block.

Three key points about transitions in this diagram (refer to circled numbers):

1 The Rate Transition block output runs in the 1 second task, but at a slower rate (2 seconds). The
output of the Rate Transition block feeds the 1 second task blocks.
2 The Rate Transition update uses the output of the 2 second task to update its internal state.
3 The Rate Transition output in the 1 second task uses the state of the Rate Transition that was
updated in the 2 second task.

The first problem is addressed because the Rate Transition block is updating at a slower rate and at
the priority of the slower block. The input to the Rate Transition block (which is the output of the
slower block) is read after the slower block completes executing.

The second problem is addressed because the Rate Transition block executes at a slower rate and its
output does not change during the computation of the faster block it is driving. The output portion of
a Rate Transition block is executed at the sample rate of the slower block, but with the priority of the
faster block. Since the Rate Transition block drives the faster block and has effectively the same
priority, it is executed before the faster block.

Note This use of the Rate Transition block changes the model. The output of the slower block is now
delayed by one time step compared to the output without a Rate Transition block.

7-62
Handle Rate Transitions

Protect Data Integrity with volatile Keyword


When you select model configuration parameter Ensure data integrity during data transfer, the
code generated for a Rate Transition block defines global buffers and semaphores and uses them to
protect the integrity of the transferred data.

Particularly for a multitasking application, the tasks (rates) involved in a data transfer can write to
the transferred data, buffers, and semaphores at times that your compiler cannot anticipate. To
prevent your compiler from optimizing the assembly code in a manner that compromises the integrity
of the transferred data, the code generator applies the keyword volatile to the buffers and
semaphores. The code generator does not apply volatile to the global variable that represents the
transferred data because the volatile buffers and semaphores typically offer enough protection.

With Embedded Coder, you can explicitly apply volatile to the transferred data by applying the
built-in custom storage class Volatile to the input of the Rate Transition block. For example, you
can use this technique to help protect the integrity of data that your external code shares with the
generated code.

Alternatively, to protect data that your external code shares with the generated code, you can write
your own C functions that read and write the data in a protected manner. Then, you can apply the
custom storage class GetSet to the data in the model, which causes the generated code to call your
functions instead of directly accessing the data.

For more information about applying volatile, see “Protect Global Data with const and volatile
Type Qualifiers” (Embedded Coder). For more information about GetSet, see “Access Data Through
Functions with Storage Class GetSet” (Embedded Coder).

7-63
7 Working with Sample Times

Specify Execution Domain


Execution domain specification allows you to set a model and its subsystems and referenced models
to simulate as discrete-time or data-driven systems. Use this setting to separate the discrete
dynamics from the rest of its dynamics, for example, in the design of a deployable controller for a
plant that is modeled with continuous-time dynamics.

To simulate a computationally intensive signal processing or multirate signal processing system, you
can also assign a dataflow domain. Dataflow domains simulate using a model of computation
synchronous dataflow, which is data-driven and statically scheduled. For more information, see
“Dataflow Domain” (DSP System Toolbox).

You can create subsystems that maintain their discrete execution domain irrespective of their
environment. By constraining a subsystem to be discrete, you can increase reusability of your
subsystem as a component. To improve code generation, this specification reduces unnecessary
update methods, reduces major time step checks, and increases reusability of generated code.

Domain Specification Badge


The domain specification badge indicates the execution domain computed to a model or subsystem
when you update the model diagram. You can toggle the visibility of the domain specification badge
by turning on the Sample Time Display. For more information on visualizing sample time, see “View
Sample Time Information” on page 7-15. The badge is visible at the bottom left corner of the Simulink
Editor.

The model below shows a discrete Sine Wave block whose rate is reduced by the Rate Transition
block before driving the Gain block.

Observe that the model receives the Discrete execution domain because its contents are all discrete.

You can also toggle the visibility of the badge by enabling or disabling the Set Domain Specification
parameter in the Execution tab of the Property Inspector.

Types of Execution Domains


You can instruct Simulink to assign the execution domain, along with the allowed sample times, via
the Property Inspector.

Specification Discrete Other Dataflow


Deduce from X X -
contents
Discrete X - -
Dataflow - - X
Export function X - -

7-64
Specify Execution Domain


Deduce from contents Let Simulink assign the execution domain based on the contents of
the subsystem.

Discrete Constrain all blocks in a subsystem to be discrete.

Dataflow Simulate a computationally-intensive signal processing or multi-rate signal
processing system. This setting requires the DSP System Toolbox™.

Export function Specify that the model is to be treated as an export-function model.
When you specify a model as an export-function model, Simulink automatically sets the Solver
selection in the Model Configuration Parameters to Fixed-step and auto. See “Export-
Function Models Overview” on page 10-125 for more information.

When you update the model diagram or simulate the model, the badge displays the computed
execution domain for the model component. There are three execution domains in Simulink:


Discrete Blocks have discrete states and sample times. Allowed samples times include
“Discrete Sample Times” on page 7-18, “Controllable Sample Time” on page 7-18, and
“Asynchronous Sample Time” on page 7-19.

Dataflow Dataflow domains simulate using computation synchronous dataflow, which is data-
driven and statically scheduled. This execution domain requires the DSP System Toolbox. For
more information, see “Specifying Dataflow Domains” (DSP System Toolbox).

Other Blocks are not strictly discrete.

Subsystems that receive the Other execution domain include:

• Subsystems whose blocks have continuous states and sample times, including “Continuous
Sample Time” on page 7-19, “Fixed-in-Minor-Step Sample Time” on page 7-19, and “Variable
Sample Time” on page 7-19
• Subsystems with a mixture of continuous and discrete sample times.
• Subsystems with “Asynchronous Sample Time” on page 7-19.
• Triggered Subsystem
• Function-Call Subsystem
• Enabled and Triggered Subsystem
• Initialize Function
• Reset Function
• Terminate Function
• If Action Subsystem

If a subsystem has continuous, variable, fixed-in-minor step, “Constant Sample Time” on page 7-20, or
a mixture of sample times, you can use the badge to enable or disable domain specification. The
subsystem still receives the Other time domain.

The domain specification badge is not actionable when the currently selected subsystem or model is a
linked block, inside a library block, or a conditionally executed subsystem that receives the Other
domain. To change the execution domain of a linked library block, break the link to the parent library
block. See “Disable or Break Links to Library Blocks” on page 45-23.

7-65
7 Working with Sample Times

Set Execution Domain

You can set the domain specification per subsystem and at the root level of the model using the
Execution tab of the Property Inspector. To enable the Property Inspector for the model, on the
Modeling tab, under Design, click Property Inspector, or press Ctrl+Shift+I on your keyboard.
On macOS, press command+option+O instead. If the domain specification badge is displayed, you
can also open the Execution settings in the Property Inspector by clicking the badge. See “Domain
Specification Badge” on page 7-64.

Select the Set Execution Domain check box. You can now specify the Domain.

Note Changing the domain specification at the root level of the model does not change the setting
for its child subsystems.

You can also enable this setting from the command line using set_param to set the
SetExecutionDomain parameter 'on' or 'off'.

Once enabled, the default setting for the Domain parameter is Deduce from contents. When you
update the diagram, the execution domain is deduced from the characteristics of the blocks in the
currently open subsystem. For example, a system that has only discrete blocks is in the Discrete
execution domain. See “Types of Execution Domains” on page 7-64.

The badge shows the current specification setting. If you set the subsystem domain to Deduce from
contents, the badge text displays Deduce until you update the diagram. Once you update the model
diagram, the badge shows the computed execution domain, as described in “Types of Execution
Domains” on page 7-64. When you enable Set domain specification and Domain is set to Deduce
from Contents, Simulink computes the execution domain of the currently focused subsystem based
on the blocks and sample times inside the subsystem.

To set the Domain parameter from the command line, use set_param to change
ExecutionDomainType to either 'Deduce' or 'Discrete'. You can also get the computed

7-66
Specify Execution Domain

execution domain after you update the diagram using the CompiledExecutionDomain parameter of
the subsystem.

Enforce Discrete Execution Domain for a Subsystem

This example shows how to specify execution domains for the constituent subsystems of a model.

The SubsystemExecution model has a discrete cruise controller subsystem that tracks the
reference speed set in the Constant block named Desired Speed. A car dynamics subsystem models
the continuous-time dynamics of the car.

To visualize the sample times and domains of the subsystems, turn on the sample time colors and
annotations.

The discrete cruise controller of the model has a hybrid sample time due to the presence of a
continuous-time signal from the output of the car dynamics subsystem at the input port of the
controller.

To enforce discrete-time execution of the controller:

1 Select the Subsystem block named discrete cruise controller.


2 Open the Property Inspector and go to the Execution tab.
3 Select Set execution domain.
4 Set Domain to Discrete.

To update the sample time colors and annotations, update or simulate the model.

7-67
7 Working with Sample Times

The discrete cruise controller subsystem is now discrete.

The car dynamics subsystem receives the hybrid sample time and the Other execution domain. To set
the execution domain of the car dynamics subsystem to Deduce from Contents:

1 Select the Subsystem block named car dynamics.


2 Open the Property Inspector and go to the Execution tab.
3 Select Set execution domain.
4 Set Domain to Deduce from contents.

Optionally, set the Sample Time parameter of the Inport block in this subsystem to 0.

To update the sample time colors and annotations, update or simulate the model.

See Also
“What Is Sample Time?” on page 7-2 | “Sample Times in Subsystems” on page 7-28 | “How
Propagation Affects Inherited Sample Times” on page 7-37 | “Dataflow Domain” (DSP System
Toolbox)

7-68
8

Referencing a Model

• “Model Reference Basics” on page 8-2


• “Model Reference Requirements and Limitations” on page 8-11
• “Reference Existing Models” on page 8-16
• “Reference Protected Models from Third Parties” on page 8-18
• “Convert Subsystems to Referenced Models” on page 8-23
• “Conditionally Execute Referenced Models” on page 8-28
• “Inspect Model Hierarchies” on page 8-32
• “Define Model Reference Interfaces” on page 8-35
• “Referenced Model Sample Times” on page 8-41
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Override Model Reference Simulation Modes” on page 8-50
• “Simulate Conditionally Executed Referenced Models” on page 8-58
• “Simulate Multiple Referenced Model Instances in Normal Mode” on page 8-59
• “Manage Simulation Targets for Referenced Models” on page 8-66
• “Reduce Update Time for Referenced Models by Using Parallel Builds” on page 8-69
• “Share Simulink Cache Files for Faster Simulation” on page 8-70
• “Set Configuration Parameters for Model Hierarchies” on page 8-75
• “Parameterize Instances of a Reusable Referenced Model” on page 8-80
• “Parameterize a Referenced Model Programmatically” on page 8-93
• “Group Multiple Model Arguments into a Single Structure” on page 8-95
• “Configure Instance-Specific Data for Lookup Tables Programmatically” on page 8-98
8 Referencing a Model

Model Reference Basics


You can include one model in another by using a Model block. Each Model block is a model reference,
or a reference to another model. You can reference a model multiple times without making redundant
copies, and multiple models can reference the same model. These references create a model
hierarchy.

A model can function as both a referenced model and a standalone model, without changing the
model or any entities derived from it. To use a referenced model as a standalone model, the
referenced model must not depend on data that is available only from a higher-level model.

Each referenced model compiles independently. This standalone behavior can improve the
performance of your model hierarchy and help you achieve your modeling goals.

Model Reference Advantages


Like subsystems, model references allow you to organize large models hierarchically. Like libraries,
model references allow you to define a set of blocks once and use it repeatedly. Unlike subsystems
and libraries, model references provide advantages that result from the referenced models compiling
independently. The ideal way to implement a model component depends on your requirements.

When your component is reused multiple times in a model hierarchy and contains many blocks,
implementing the component as a model reference can speed up simulation and code generation. For
example, when you use model references, you can benefit from:

• Incremental loading

The software loads a referenced model when the model is needed, which speeds up model loading.
• Accelerated simulation

When a referenced model simulates in accelerator mode, the software converts the referenced
model to code. Then, the software simulates the model by running the code, which is faster than
running a normal mode simulation.
• Incremental builds

The software generates code for a referenced model only if the model has changed since the code
was previously generated. When your team members or a continuous integration system generate
code for referenced models, Simulink cache files package this code for reuse. Local copies of
these files can speed up simulation and code generation for you.
• Local solvers

When you use a local solver in a referenced model, the software solves a model reference as a
separate set of differential equations. The local solver can use a different, smaller or larger step
size. The choice of solver and solver settings involves a trade off between speed and accuracy in
simulation. For more information, see “Use Local Solvers in Referenced Models” on page 27-5.
• Parallel computing (with a Parallel Computing Toolbox™ license)

For large model reference hierarchies, you can increase the speed of diagram updates by building
model reference targets in parallel. For a referenced model to build in parallel, you must configure
it to run in accelerator mode. For more information, see “Reduce Update Time for Referenced
Models by Using Parallel Builds” on page 8-69.

8-2
Model Reference Basics

Model references support collaboration with team members and third parties. For example, model
references can help you satisfy these requirements:

• Modular development

You can develop a referenced model independent from the models that use it. For example, you
can open a referenced model without the context of a model hierarchy. Then, you can simulate and
generate code for the referenced model. A referenced model is a standalone component that you
can use in an assembly and integrate with other components.
• Intellectual property protection (with a Simulink Coder or HDL Coder license)

You can obscure the contents of a referenced model, allowing you to distribute the model as a
protected model without revealing its intellectual property. You can grant the protected model
recipient permission to view, simulate, and generate code for the protected model. For more
information, see “Protect Models to Conceal Contents” (Simulink Coder) or “Create Protected
Models to Conceal Contents and Generate HDL Code” (HDL Coder).

Model references help you verify the behavior of your component by offering an isolated
environment. For example, model references support your testing and certification requirements
with:

• Unit testing

You can test a referenced model independently by simulating the referenced model as a top model,
isolating its behavior. You can also create a test harness that exercises the referenced model in a
test environment with various test scenarios. Unit testing can eliminate retesting for unchanged
components and reduce the cost of verification. For more information, see “Component
Verification” on page 88-2. For help verifying compliance with industry standards and
guidelines, see “Check Your Model Using the Model Advisor” on page 5-2.
• SIL/PIL testing (with an Embedded Coder license)

To verify referenced models in an environment that mimics the target environment, you can
simulate the referenced models in software-in-the-loop (SIL) or processor-in-the-loop (PIL) mode.
These simulations let you generate and test production code that is compiled for and executed on
the host platform for SIL simulations and the target platform for PIL simulations. For more
information, see “SIL and PIL Simulations” (Embedded Coder).
• Single-sourced generated code

Each referenced model has one set of source code, regardless of how many times a model
hierarchy includes the referenced model. Single-sourced code can reduce the cost of verification.
• Independent traceability for generated code

You can trace the generated code for a referenced model independently of other models. Suppose
you confirm that the generated code traces back to the referenced model with baseline
equivalence tests and additional test vectors that target 100% code coverage. Changes to the
parent model do not affect this verification testing, which reduces the cost of verification.

With a Simulink Code Inspector license, you can create a traceability matrix for each referenced
model. The traceability matrix provides the traceability among model objects, generated code, and
model requirements. For more information, see “Generate Traceability Matrices” (Simulink Code
Inspector).

8-3
8 Referencing a Model

To compare model references, subsystem references, subsystems, and libraries, see “Explore Types of
Model Components” on page 23-4.

Model Reference Hierarchy


A model hierarchy can use multiple componentization techniques. For example, a model can use a
combination of subsystems, referenced models, and Stateflow charts to create hierarchy.

When a model hierarchy contains referenced models, the top model is the top-level model in the
Simulink window. For example, suppose you open the sldemo_mdlref_basic model. Then, you
navigate into a referenced model via the Model block named CounterA.

The window title includes two elements.

• sldemo_mdlref_basic — Name of the top model


• CounterA — Name of the Model block

The Explorer Bar includes three elements.

• sldemo_mdlref_basic — Name of the top model


• CounterA — Name of the Model block
• sldemo_mdlref_counter — Name of the referenced model

The Model Browser displays the hierarchy of the top model, referenced models, and other model
components.

Each referenced model can reference other models. To prevent cyclic inheritance, a Model block
cannot reference a model that is above it in the model hierarchy. For example, a model cannot
reference its parent model, which is the model that references it.

8-4
Model Reference Basics

A model can contain multiple Model blocks that reference the same model as long as the referenced
model does not define global data. For example, the sldemo_mdlref_basic model contains three
Model blocks that reference the sldemo_mdlref_counter model.

The referenced model can also appear in other models at any level.

To open a referenced model as a top model, on the Model block icon, click . The referenced model
opens outside of the context of the current model hierarchy.

When you edit a model, the changes affect the same model file regardless of whether the model is
open as a referenced model or top model.

Model Reference Interface


The ports on a Model block correspond to blocks at the top level of the referenced model. The ports
can be input, output, or control ports.

For example, in the sldemo_mdlref_basic model, each Model block references the
sldemo_mdlref_counter model and has:

• Three input ports, named upper, input, and lower


• One output port, named output

8-5
8 Referencing a Model

The sldemo_mdlref_counter referenced model has:

• Three Inport blocks, named upper, lower, and input


• One Outport block, named output

When you connect a signal to a Model block port, you connect the signal to the corresponding port of
the referenced model. The output of a Model block can differ despite the referenced model being the
same.

For example, in sldemo_mdlref_basic, each Model block port named input receives a signal from
a unique Pulse Generator block. Because the input signal from each Pulse Generator block uses a
different sample time, the output signal from each Model block differs despite the referenced model
being the same.

To view how the output signal for each Model block differs, you can use the Simulation Data
Inspector.

8-6
Model Reference Basics

Signal attributes in the referenced model are independent from the context of the Model block. For
example, signal dimensions and data types do not propagate across the Model block boundary. To
define signal attributes in the referenced model, use the block parameters of the root-level Inport and
In Bus Element blocks.

Model Workspaces and Data Dictionaries


Each model has its own workspace for storing variable values. In a model hierarchy, each model
workspace acts as a unique namespace. Therefore, you can use the same variable name in multiple
model workspaces.

To share data among models, use a data dictionary.

Duplicate data definitions can exist in a model reference hierarchy under these conditions:

• Each model in the hierarchy can see only one definition.


• Definitions must be the same across models in the hierarchy.

For more information on where you can store variables and objects, see “Determine Where to Store
Variables and Objects for Simulink Models” on page 73-109.

Model Reference Behavior and Execution


During simulation and code generation, a Model block behaves like a single block, or atomic unit.
When the Model block executes, the blocks within the referenced model execute the current task
without interruption from blocks in the parent system.

8-7
8 Referencing a Model

To modify how a referenced model behaves and when it executes, consider these features:

• 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 more information, see “Set Configuration Parameters for
Model Hierarchies” on page 8-75.
• Instance parameters

By default, a block parameter has the same value in each Model block instance of a reusable
referenced model. To specify a different block parameter value for each instance of a reusable
referenced model, create model arguments. For example, if you add a Gain block to model
sldemo_mdlref_counter, model arguments allow each of the three instances of this model to
use different gain values. See “Parameterize Instances of a Reusable Referenced Model” on page
8-80.
• Model masks

With a model mask, you can control the appearance of Model blocks and customize the way the
blocks display model arguments. For model mask requirements, see “Model Masks” on page 8-
11.
• Conditional execution

An external signal can control whether a Model block executes during simulation. For more
information, see “Conditionally Execute Referenced Models” on page 8-28.
• Dynamic startup and shutdown behavior

To model dynamic startup and shutdown behavior for a Model block, add custom routines to the
default initialization and termination routines of the Model block. For more information, see
“Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208.
• Variants

You can use multiple Model blocks to represent multiple design variations of a system component.
A conditional expression determines the active variant. For more information, see “What Are
Variants and When to Use Them” on page 12-3.

Model Reference Simulation and Code Generation


When you simulate a model hierarchy, the top model simulates. For example, suppose you open the
sldemo_mdlref_basic model. Then, you navigate into a referenced model via the Model block
named CounterA.

8-8
Model Reference Basics

The sldemo_mdlref_basic model is the top model. When you click Run, the
sldemo_mdlref_basic model simulates.

For another example, suppose you open the sldemo_mdlref_counter model as a top model in a
new window.

In the new window, the sldemo_mdlref_counter model is the top model. When you click Run, the
sldemo_mdlref_counter model simulates.

For a referenced model to simulate as a standalone top model, the referenced model must have the
data required to execute in a standalone context. For example, the referenced model must have the
variables and data types that define parameters and signals.

You can simulate a referenced model either interpretively (in normal mode) or by compiling the
referenced model to code and executing the code (in accelerator mode). For details, see “Choose
Simulation Modes for Model Hierarchies” on page 8-45.

For information about generating code for a model reference hierarchy, see “Generate Code for
Model Reference Hierarchy” (Simulink Coder).

Tip For faster simulation and incremental code generation, consider using Simulink cache files.
Simulink cache files contain build artifacts that can speed up simulation and code generation. For

8-9
8 Referencing a Model

more information, see “Share Simulink Cache Files for Faster Simulation” on page 8-70 and
“Simulink Cache Files for Incremental Code Generation” (Simulink Coder).

See Also
Model

Related Examples
• “Component-Based Modeling Guidelines” on page 23-2
• “Model Reference Requirements and Limitations” on page 8-11
• “Reference Existing Models” on page 8-16
• “Reference Protected Models from Third Parties” on page 8-18
• “Convert Subsystems to Referenced Models” on page 8-23

8-10
Model Reference Requirements and Limitations

Model Reference Requirements and Limitations


Before referencing models, consider model reference requirements and limitations. By understanding
the requirements and limitations upfront, you are better prepared to reference models successfully.

Model Reuse
You can reference a model more than once in a model hierarchy unless the referenced model has any
of these properties:

• The model references another model that is set to single instance.


• The model contains To File blocks.
• The model contains an internal signal or state with a storage class that is not supported for multi-
instance models. Internal signals and states must have the storage class set to Auto or Model
default and the default storage class for internal data must be a multi-instance storage class.
• The model uses exported Stateflow graphical functions.
• The referenced model executes in accelerator mode and contains an S-function that is either not
inlined or is inlined but does not set the option SS_OPTION_WORKS_WITH_CODE_REUSE.
• The model contains a function-call subsystem that:

• Simulink software forces to be a function


• Is called by a wide signal

If the referenced model has any of these properties, only one instance of the model can appear in the
model hierarchy. The model must have Total number of instances allowed per top model set to
One.

Model Masks
You can use masked blocks in a referenced model. Also, you can mask a referenced model (see
“Create and Reference a Masked Model” on page 43-52).

To successfully use masks, consider these requirements and limitations:

• If a mask specifies the name of a referenced model, 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 referenced model. 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
• Mask callbacks cannot add Model blocks, change the Model block name, or change the Model
block simulation mode.

S-Functions in Referenced Models


Different types of S-functions provide different levels of support for model references.

8-11
8 Referencing a Model

S-Function Type Models Referenced in Normal Models Referenced in


Mode Accelerator Mode and
Protected Models
Level-1 MATLAB S-function Not supported Not supported
Level-2 MATLAB S-function Supported Supported — requires a TLC file
Handwritten C MEX S-function Supported — can be inlined with Supported — can be inlined with
a TLC file a TLC file
S-Function Builder Supported Supported
Legacy Code Tool Supported Supported

When you use S-functions in referenced models, consider these requirements and limitations.

S-Function Consideration Requirements and Limitations


Sample Time Inheritance If an S-function depends on an inherited sample time, the S-
function must explicitly declare a dependence on the inherited
sample time. To control sample-time inheritance, use
ssSetModelReferenceSampleTimeInheritanceRule
differently based on whether an S-function permits or precludes
inheritance. For details, see “S-Functions That Specify Sample
Time Inheritance Rules” (Simulink Coder).
Models Referenced in Accelerator For accelerator mode referenced models that contain an S-
Mode function that requires inlining using a Target Language Compiler
(TLC) 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 these


cases:

• The model is referenced more than once in the model


hierarchy. To work around this limitation, use normal mode or:

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.
• The S-function uses character vector parameters.

A referenced model in accelerator mode cannot use S-functions


generated by Simulink Coder software.

8-12
Model Reference Requirements and Limitations

S-Function Consideration Requirements and Limitations


Models Referenced in Normal Under certain conditions, when a C S-function appears in a
Mode referenced model that executes in normal mode, successful
execution is impossible. For details, see “S-Functions in Normal
Mode Referenced Models”.

To specify whether an S-function can be used in a normal mode


referenced model, use the
ssSetModelReferenceNormalModeSupport SimStruct
function.

For an S-function to work with multiple instances of referenced


models in normal mode, the S-function must indicate explicitly
that it supports multiple exec instances. For details, see
“Supporting the Use of Multiple Instances of Referenced Models
That Are in Normal Mode”.
Protected Models For protected models that contain an S-function that requires
inlining using a Target Language Compiler (TLC) file, the S-
function must use the ssSetOptions macro to set the
SS_OPTION_USE_TLC_WITH_ACCELERATOR option in its
mdlInitializeSizes method.

Model Architecture Requirements and Limitations


Element Requirements and Limitations
Goto and From blocks Goto and From blocks cannot cross model reference boundaries.
Iterator subsystems If the referenced model contains Assignment blocks, you can
place the Model block in an iterator subsystem only if the
Assignment blocks are also in an iterator subsystem.
Configurable subsystems In a configurable subsystem with a Model block, during model
update, do not change the subsystem that the configurable
subsystem selects.
InitFcn callback An InitFcn callback in a top model cannot change parameters
used by referenced models.
Printing referenced models You cannot print a referenced model from a top model.

8-13
8 Referencing a Model

Signal Requirements and Limitations


Signal Requirements and Limitations
0-based or 1-based indexing In two cases, Simulink does not propagate 0-based or 1-based
information propagation 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.
• 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.
Asynchronous rates 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.
User-defined data type input or A referenced model can input or output only the user-defined data
output types that are fixed point or that Simulink.DataType or
Simulink.Bus objects define.
Buses If you use a virtual bus as an input or an output for a referenced
model, the bus cannot contain a variable-sized signal element.
See “Use Buses at Model Interfaces” on page 8-39.
Signal objects 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.

8-14
Model Reference Requirements and Limitations

Simulation Requirements and Limitations


Simulation Property Requirements and Limitations
Continuous sample time A continuous sample time cannot be propagated to a Model block
propagation that is sample-time independent.
Sample times and solvers The solver of the top model controls all continuous sample times
in a model hierarchy. For example, for a fixed-step solver, all
continuous rates in referenced models run at the fixed-step size of
the top model. For information about how sample times impact
solvers, see “Types of Sample Time” on page 7-18.
State initialization To initialize the states of a model that references other models
with states, specify the initial states in structure or structure with
time format.
Parameter tunability When you simulate a model that references other models, under
some circumstances, you lose some tunability of block parameters
(for example, the Gain parameter of a Gain block). For more
information, see “Tunability Considerations and Limitations for
Other Modeling Goals” on page 41-36.

Code Generation Requirements and Limitations


By understanding code generation requirements and limitations upfront, you are better prepared to
properly set up the model hierarchy for code generation. See “Set Configuration Parameters for Code
Generation of Model Hierarchies” (Simulink Coder) and “Code Generation Limitations for Model
Reference” (Simulink Coder).

See Also

Related Examples
• “Compare Capabilities of Model Components” on page 23-8
• “Set Configuration Parameters for Model Hierarchies” on page 8-75
• “Code Generation Limitations for Model Reference” (Simulink Coder)

8-15
8 Referencing a Model

Reference Existing Models


A model becomes a referenced model when a Model block in another model references it. Any model
can function as a referenced model and can continue to function as a separate model.

To reference an existing model in another model:

1 If the folder that contains the model you want to reference is not on the MATLAB path, add the
folder to the MATLAB path. For more information, see “What Is the MATLAB Search Path?”
2 If you plan to reference the model once at most in a model hierarchy, in the configuration set of
the referenced model, set Total number of instances allowed per top model to One.
Otherwise, use the default value Multiple, which lets you reference the model more than once
in a model hierarchy.
3 To reference another model, add a Model block. The new block is initially unresolved because it
does not specify a model to reference.

4 To open the Block Parameters dialog box, double-click the unresolved Model block.

5 In the Model name text box, enter the name of the model you want to reference. The name must
contain fewer than 60 characters, exclusive of the file extension.
6 Click OK.

8-16
Reference Existing Models

Connect Model Block Ports


The Model block displays a port for each root-level input and output port of the referenced model.
When you connect a signal to a Model block port, you connect the signal to the corresponding port of
the referenced model.

The port of the referenced model determines what connections the Model block supports. For
example, a port might require a bus or a signal with a data type of uint8.

For more information about model reference interfaces, see “Define Model Reference Interfaces” on
page 8-35.

Configure Model Block Parameters


You can use Model block parameters to specify:

• Simulation mode
• Code interface
• Model events, such as initialize, reinitialize, reset, and terminate events
• Scheduling via periodic event ports or the Schedule Editor
• Instance-specific parameter values for model arguments
• Local solver

For information about the block parameters and the values they support, see Model.

When a Model block references another model, double-clicking the Model block opens the referenced
model, not the Block Parameters dialog box.

To access block parameters, select the Model block. Then, open the Property Inspector or Block
Parameters dialog box.

• Property Inspector — In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, select
Property Inspector.
• Block Parameters dialog box — In the Simulink Toolstrip, on the Model Block tab, click Block
Parameters.

See Also

More About
• “Inspect Model Hierarchies” on page 8-32
• “Model Reference Requirements and Limitations” on page 8-11
• “Reference Protected Models from Third Parties” on page 8-18
• “Convert Subsystems to Referenced Models” on page 8-23
• “Conditionally Execute Referenced Models” on page 8-28

8-17
8 Referencing a Model

Reference Protected Models from Third Parties

To deliver a model without revealing its intellectual property, third parties can protect the model
before delivery. A protected model is a referenced model that does not support editing. The protected
model author chooses whether to enable read-only view, simulation, code generation, and password
protection. When an operation is password-protected, the AES-256 encryption technology protects
the supporting file contents.

Note Creating a protected model requires a Simulink Coder license.

To identify protected models, look for:


Files in the MATLAB Current Folder browser with a badge icon and an .slxp extension.
Protected models do not appear in the model hierarchy in the Model Explorer.
• Model blocks in the Simulink Editor with a badge icon in the lower left corner:

If available, a protected model report describes the supported functionality. To open the report, use
one of these options:

• In the MATLAB Current Folder browser, right-click the protected model and click Open Report.
• In the Simulink Editor, right-click the protected-model badge icon on the Model block and click
Display Report.

Load Supporting Files for Protected Model


You may receive the protected model on its own, in a project archive, or in a package.

• If you receive a project archive (.mlproj), extract the protected model and any supporting files.
Double-click the project archive (.mlproj) in the Current Folder browser and specify the
destination folder. Alternatively, right-click on the project archive and click Extract Here. The
project opens, and the extracted files are in a new folder named after the project archive.
• If you receive a protected model or supporting files by another method, follow any provided
instructions. For example, you might need to load a MAT-file that contains workspace definitions.
You can configure a callback function, such as LoadFcn, to load the MAT-file automatically. See
“Customize Model Behavior with Callbacks” on page 4-68.

Verify Digital Signature of Protected Model


If the author signed the protected model, verify the digital signature. In the Current Folder browser,
double-click the protected model. In the Details pane, the Signed by field indicates the publisher
that signed the model and whether the signature is verified by a trusted certificate authority.
Verification fails in the following cases:

8-18
Reference Protected Models from Third Parties

• The protected model was changed after it was signed.


• The protected model was not signed.
• The protected model was signed with an expired certificate.
• The protected model was self-signed with a certificate issued by the author.
• The protected model was signed with a missing or invalid certificate.
• The certificate of the CA is missing in your system or is invalid.

To verify the signature on protected models by default, in the Simulink Preferences dialog box, select
Verify digital signature of protected model before opening.

View Protected Model Contents

Web view allows you to view this protected model information:

• System contents
• Block parameters
• Signal properties

To open the read-only view, you can double-click the Model block referencing the protected model or
the .slxp file in the Current Folder browser. If the read-only view is password protected, right-click
the protected-model badge icon and select Authorize. In the Model view box, enter the password,
then click OK.

You can navigate the model hierarchy by double-clicking Model or Subsystem blocks. Alternatively,
you can navigate to the View All tab and select the system that you want to view. You cannot view the
content of protected referenced models in the protected model.

To view block parameters and signal properties, select a block or a signal line, respectively.

To search in Web view, click the search button, then enter the name or value that you want to search
in the box that appears. The elements of the model that the search returns appear highlighted. The
search results include the name and parent of each returned element.

Test Protected Model in Isolated Environment

With the protected model, you may receive a harness model, which typically has the suffix _harness.
A harness model provides an isolated environment for you to test the protected model. If any
supporting files are missing, simulating or generating code for the harness model can help identify
them.

To create a harness model, right-click the protected model file in the Current Folder browser, then
click Create Harness Model. The created harness model is set up for simulation of the protected
model.

Reference Protected Model


To reference a protected model:

8-19
8 Referencing a Model

1 Ensure that the protected model is on the MATLAB path.


2 If you have a harness model, copy the Model block from the harness model into your model.
Otherwise, reference the protected model in a new Model block. Open the Block Parameters
dialog box and enter the name of the protected model in the Model name field.

When a Model block references a protected model, the Simulation mode of the block becomes
Accelerator. You cannot change this mode.
3 If the protected model is password protected, right-click the protected-model badge icon on the
Model block and click Authorize. In the Model view box, enter the password, then click OK.
4 Connect signal lines to the Model block that match its input and output port requirements. See
“Define Model Reference Interfaces” on page 8-35.

Note that the protected model cannot use noninlined S-functions directly or indirectly.
5 Provide any needed model argument values. See “Parameterize a Referenced Model” on page 8-
81.

If you plan to simulate the protected model, use the same platform used to create the protected
model. The software stores the protected model as a compiled MEX binary.

Use Models Protected in Previous Releases

Check that the Simulink release you are using supports the protected model.

If available, the protected model report shows the release versions used to create the protected
model. Use the same Simulink release that was used to create the protected model unless the
protected model also supports later releases, as described by this table.

Modeling Requirement Cross-Release Protected Model Support


Read-only view Supported with limitations — R2019a and later releases

• Protected model must have been created in R2018b or a later


release.
Simulation in normal mode Supported with limitations — R2019a and later releases

• Protected model must have been created in R2018b or a later


release.

8-20
Reference Protected Models from Third Parties

Modeling Requirement Cross-Release Protected Model Support


Simulation in accelerator mode Supported with limitations — R2020a and later releases

• Protected model must have been created in R2018b or a later


release.
• You must directly simulate the parent of the protected model.
Simulating a model hierarchy that contains the parent model as
a referenced model is not supported. To interactively simulate
the parent model, you must open it as the top model in its own
window. For more information, see “Navigate Model Hierarchy”
on page 4-34.
• The protected model must use Just-in-Time acceleration and
must not require C code generation. For more information on
acceleration modes, see “How Acceleration Modes Work” on
page 38-3.
Simulation in SIL or PIL mode Supported with limitations — R2020b and later releases

• Protected model contains ERT, ERT-based, AUTOSAR, GRT, or


GRT-based code generated in R2018b or a later release. You
can run Model block SIL and PIL simulations that reference the
protected model. For more information, see “Use Protected
Models from Previous Releases to Perform SIL Testing and
Generate Code” (Embedded Coder).

If ERT or AUTOSAR code in the protected model requires


shared utility code, use sharedCodeUpdate to copy the
required code to an existing shared utility code folder. For more
information, see “Cross-Release Shared Utility Code Reuse”
(Embedded Coder).
• You cannot use
Simulink.ModelReference.ProtectedModel.addTarget
or
Simulink.ModelReference.ProtectedModel.removeTar
get to add or remove generated code from a protected model
created in a different release.
Simulation in rapid accelerator Not supported
mode

8-21
8 Referencing a Model

Modeling Requirement Cross-Release Protected Model Support


Code generation Supported with limitations — R2020b and later releases

• Protected model contains ERT, ERT-based, AUTOSAR, GRT, or


GRT-based code generated in R2018b or a later release, with a
Model reference code interface. For more information, see
“Use Protected Models from Previous Releases to Perform SIL
Testing and Generate Code” (Embedded Coder).

If ERT or AUTOSAR code in the protected model requires


shared utility code, use sharedCodeUpdate to copy the
required code to an existing shared utility code folder. For more
information, see “Cross-Release Shared Utility Code Reuse”
(Embedded Coder).
• You cannot use
Simulink.ModelReference.ProtectedModel.addTarget
or
Simulink.ModelReference.ProtectedModel.removeTar
get to add or remove generated code from a protected model
created in a different release.

See Also
Simulink.ProtectedModel.getPublisher | Simulink.ProtectedModel.verifySignature

More About
• “Reference Existing Models” on page 8-16
• “Inspect Model Hierarchies” on page 8-32
• “Protect Models to Conceal Contents” (Simulink Coder)

8-22
Convert Subsystems to Referenced Models

Convert Subsystems to Referenced Models

Model reference offers benefits for modeling large, complex systems and for team-based
development. Many large models use a combination of subsystems and referenced models. To decide
whether to convert a subsystem to a referenced model, see “Explore Types of Model Components” on
page 23-4.

A subsystem you convert must have atomic behavior that functionally groups the blocks. The blocks
in the subsystem must execute consecutively and behave like a single block, or atomic unit, when the
parent model executes. For more information, see “Specify Whether Subsystem Is Atomic” on page 4-
22. The atomic behavior can cause artificial algebraic loops. For more information, see “Algebraic
Loop Concepts” on page 3-39.

Prepare Subsystem for Conversion


Preparing a subsystem for conversion can eliminate or reduce the number of issues identified during
conversion. Addressing these issues before conversion can be more efficient than switching
repeatedly between the diagnostic messages and the Simulink Editor.

The software can automatically fix some issues during conversion. To respect the original design
intent, the automatic fixes might apply less clean solutions than you can apply manually. For example,
the software might place the Model block in a subsystem, use extra blocks, or append a parenthetical
to signal names.

To prepare the subsystem for conversion:

1 To ensure the subsystem has atomic behavior, select the Subsystem block. In the Simulink
Toolstrip, on the Subsystem Block tab, select Make Atomic.
2 To minimize artificial algebraic loops that the atomic behavior might create, select the Subsystem
block. In the Property Inspector, select Minimize algebraic loop occurrences.

Note To open the Property Inspector, in the Simulink Toolstrip, on the Modeling tab, in the
Design gallery, select Property Inspector. Alternatively, press Ctrl+Shift+I
3 To avoid implicit signal resolution to Simulink.Signal objects, configure a parent model
setting. Set the Signal resolution configuration parameter to Explicit only (default) or
None.

Note To open the Configuration Parameters dialog box, in the Simulink Editor, on the Modeling
tab, perform one of these actions:

• If the parent model is a top model, click Model Settings.


• If the parent model is a referenced model, click the Model Settings button arrow. Then, in
the Referenced Model section, click Model Settings.

4 Fix the conversion issues in this table, if applicable.

8-23
8 Referencing a Model

Conversion Issue Manual Fix


A Function-Call Generator block provides Move the Function-Call Generator block into
input to a subsystem that is not an export- the subsystem.
function subsystem.
A wide (nonscalar) function-call signal is Trigger the subsystem with a scalar function-
input to the function-call input port of a call signal instead.
subsystem.
A function-call signal is an output of the Change the function-call output to a data
subsystem. trigger.
A Merge block combines the signals from the Configure the subsystem to avoid the Merge
subsystem input ports. block.
Bus elements have duplicate names. Assign unique names to the elements.
A Goto block passes input to a From block Replace each problematic Goto block with an
that is outside the subsystem. Outport block. Then, connect the new
subsystem output ports to blocks in the
parent system.
A From block receives input from a Goto Replace each problematic From block with
block that is outside the subsystem. an Inport block. When the From blocks have
the same tag, duplicate the Inport block that
replaces the first of the From blocks instead
of adding unique Inport blocks for each From
block. For more information, see “Create
Duplicate Inport Blocks”. Then, connect the
new subsystem input ports to blocks in the
parent system.
The subsystem uses global tunable To create a Simulink.Parameter object for
parameters specified in the dialog box that each tunable parameter, use
opens when you click the Configure button tunablevars2parameterobjects. Each
next to the Default parameter behavior Simulink.Parameter object must have a
configuration parameter. storage class other than Auto. For more
information, see “Parameterize Instances of a
Reusable Referenced Model” on page 8-80
and “Tunable Parameters” on page 10-95.
The sample time differs between a block that Change one of the two sample times to match
represents an input port and the block that the other or insert a Rate Transition block.
drives the input port.
The sample time at an input port is constant. Move each source block with a constant
sample time into the subsystem. For
example, move Constant blocks into the
subsystem.
5 Compile the model and resolve any errors.

For the conversion to succeed, the model that contains the subsystem must compile successfully.

Convert Subsystems to Referenced Models


To convert a subsystem to a referenced model:

8-24
Convert Subsystems to Referenced Models

1 To make the conversion process faster, close Scope block windows.


2 Select the Subsystem block you want to convert.
3 In the Simulink Toolstrip, on the Subsystem Block tab, click Convert > Model Block.
4 To automatically fix some conversion issues, in the Model Reference Conversion Advisor, select
Fix errors automatically (if possible). You do not control the automatic fixes.
5 To leave the Subsystem block in place and create a separate model from the contents of the
Subsystem block, clear Replace the content of a subsystem with a Model block.
6 To compare top-model simulation results before and after conversion:

• Enable signal logging for output signals of interest.


• Select Check simulation results after conversion and Replace the content of a
subsystem with a Model block.
• Set the Stop time, Absolute tolerance, and Relative tolerance.
• Set the Model block simulation mode option in the advisor to the same simulation mode as
the original model.
7 Optionally, configure additional conversion parameters. For more information, see Model
Reference Conversion Advisor.
8 Click Convert.
9 Address any identified issues.

Alternatively, in the MATLAB Command Window, use the


Simulink.SubSystem.convertToModelReference function. You can convert multiple Subsystem
blocks using one Simulink.SubSystem.convertToModelReference command. However, you
cannot convert a parent subsystem and a child of that subsystem at the same time.

Conversion Results
After all conversion checks pass, the software:

• Creates a referenced model from the subsystem.


• Creates the Simulink.Bus objects, Simulink.Signal objects, and tunable parameters that the
referenced model requires.
• By default, replaces the Subsystem block with a Model block that references the new model.
• Inserts the Model block in a Subsystem block if the automatic fixes added ports to the Model block
interface.
• Creates an HTML conversion summary report in the slprj folder. This report summarizes the
results of the conversion process, including the results of the fixes that the advisor performed.
This report also describes the elements that it copies.
• Optionally checks the consistency of simulation results before and after conversion.

The software copies the following elements from the original model to the new referenced model.

• Configuration set — If the parent model uses a referenced configuration set, then both the
parent and referenced models use the same referenced configuration set. Otherwise, the advisor
copies the entire configuration set to the referenced model.
• Variables — The advisor copies only the model workspace variables that the subsystem used in
the original model to the model workspace of the referenced model. If the model that contained
the subsystem uses a data dictionary, then the referenced model uses the same data dictionary.

8-25
8 Referencing a Model

• Requirements links — The advisor copies requirements links created with Requirements Toolbox
software to the Model block from the original Subsystem block.

Compare Simulation Results Before and After Conversion


After you successfully complete conversion, use the Click here to view the comparison results
link. The results display in the Simulation Data Inspector. A green check mark indicates that
simulation results are within tolerance between the baseline model and the model with the new
referenced model.

For more information, see “Compare Simulation Data” on page 31-203.

Revert Conversion
If you are not satisfied with the conversion results, you can restore the model to its initial state. Use
one of these approaches:

• At any point during the conversion, select File > Load Restore Point.
• After you successfully run the Complete conversion check, use the Click here to restore the
original model link.

8-26
Convert Subsystems to Referenced Models

Integrate Referenced Model into Parent Model


After you complete the conversion, update the model as necessary to meet your modeling
requirements. For example, you can manually replace a Subsystem block with a Model block that
references the new model.

If you want to simulate the model with external data, check that the root Inport blocks in the new
model have the appropriate Interpolate data parameter setting. For more information, see
Interpolate data.

See Also
Model | Subsystem

More About
• “Reference Existing Models” on page 8-16
• “Explore Types of Model Components” on page 23-4
• “Model Reference Requirements and Limitations” on page 8-11
• “Inspect Model Hierarchies” on page 8-32

8-27
8 Referencing a Model

Conditionally Execute Referenced Models


A conditionally executed referenced model, or conditional model, allows you to control its execution
with an external signal. The external signal, called the control signal, is attached to the control input
port. Conditional models are useful when you create complex model hierarchies that contain
components whose execution depends on other components.

Conditional Models
You can set up referenced models to execute conditionally, similar to conditional subsystems. For
information about conditional subsystems, see “Conditionally Executed Subsystems Overview” on
page 10-3.

Simulink software supports these conditional model types:

Conditional Model Description


Enabled An enable port executes a referenced model at each simulation step for
which the control signal has a positive value. To add an enable port to a
Model block, insert an Enable block in the referenced model.

For an example of an enabled subsystem, see “Enabled Subsystems”. A


corresponding enabled referenced model uses the same blocks as are in the
enabled subsystem.
Triggered A trigger port executes a referenced model each time a trigger event
occurs. To add a trigger port to a Model block, insert a Trigger block in the
referenced model.

8-28
Conditionally Execute Referenced Models

Conditional Model Description


Triggered and Enabled A Model block can have both trigger and enable ports. If the enable control
signal has a positive value at the time step for which a trigger event occurs,
a triggered and enabled model executes once.
Function-Call A function-call port executes a referenced model each time a function-call
event occurs. To add a function-call port to a Model block, insert a Trigger
block in the referenced model. Then, open the Block Parameters dialog box
and set the Trigger type to function-call.

A Stateflow chart, a Function-Call Generator block, a Hit Crossing block, or


an appropriately configured custom S-function can provide function-call
events. See “Using Function-Call Subsystems” on page 10-53.

For an example of a function-call model, see “Model Reference Function-


Call”.

Requirements for Conditional Models


Conditional models must meet the requirements for:

• Conditional subsystems (see “Conditionally Executed Subsystems and Models”)


• Referenced models (see “Reference Existing Models” on page 8-16)

Conditional models must also meet the requirements specific to each type of conditional model.

Conditional Model Requirements


Enabled • Multi-rate enabled models cannot use multi-tasking solvers. 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.
• 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 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.
Triggered and Enabled See requirements for triggered models and enabled models.

8-29
8 Referencing a Model

Conditional Model Requirements


Function-Call • A function-call model cannot have an output port 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


output port.
2 Enable the Exclude this block from 'Block reduction'
optimization option of the inserted block.
• The parent 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 parent 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.
• 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.

Modify a Referenced Model for Conditional Execution


1 At the root level of the referenced model, insert one of the following blocks:

Type 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:

Type of Model Trigger Type Parameter Setting


Triggered One of the following:

Triggered and enabled • rising


• falling
• either
Function-Call function-call
3 Use the Model block ports to connect the referenced model to other ports in the parent model.

8-30
Conditionally Execute Referenced Models

• The top of the Model block displays an icon that corresponds to the control signal type
expected by the referenced model. For a triggered model, the top of the Model block displays
this icon.

See Also
Enable | Trigger | Function-Call Subsystem

More About
• “Simulate Conditionally Executed Referenced Models” on page 8-58
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Export-Function Models Overview” on page 10-125

8-31
8 Referencing a Model

Inspect Model Hierarchies


To better understand a model hierarchy, you can use Simulink tools, functions, parameters, or
preferences to:

• Preview model contents


• Visualize the model hierarchy
• List referenced models and Model blocks
• Display model version numbers

Content Preview
Content preview displays a representation of the contents of a referenced model on the Model block.
This preview helps you to understand at a glance the kind of processing performed by the referenced
model without opening the referenced model. See “Preview Content of Model Components” on page
1-93.

Model Dependency Graph


The Dependency Analyzer shows the structure of the model hierarchy and lets you open constituent
models. The Model Instances view displays Model blocks differently to indicate Normal, Accelerator,
SIL, and PIL modes. See “Analyze Model Dependencies” on page 17-37.

The depview function opens the model dependency graph.

8-32
Inspect Model Hierarchies

List of Model References


The find_mdlrefs function lists all models that are directly or indirectly referenced by a given
model. This function also provides the paths to the related Model blocks.

Find Referenced Models in Model Hierarchy

Find referenced models and Model blocks for all models referenced by the specified model.

load_system('sldemo_mdlref_basic');
[myModels,myModelBlks] = find_mdlrefs('sldemo_mdlref_basic')

myModels = 2x1 cell


{'sldemo_mdlref_counter'}
{'sldemo_mdlref_basic' }

myModelBlks = 3x1 cell


{'sldemo_mdlref_basic/CounterA'}
{'sldemo_mdlref_basic/CounterB'}
{'sldemo_mdlref_basic/CounterC'}

Model Version Numbers

To display the version numbers of referenced models, in the parent model, on the Debug tab, click
Information Overlays, then under Blocks, select Ref. Model Version. The version of each Model
block instance appears on each Model block.

For information on model versions, see “Manage Model Versions and Specify Model Properties” on
page 4-86.

See Also
find_mdlrefs | depview

More About
• “Preview Content of Model Components” on page 1-93

8-33
8 Referencing a Model

• “Analyze Model Dependencies” on page 17-37


• “Manage Model Versions and Specify Model Properties” on page 4-86
• “Save Signal Data Using Signal Logging” on page 78-42

8-34
Define Model Reference Interfaces

Define Model Reference Interfaces


The ports on a Model block correspond to blocks at the top level, or root level, of the referenced
model. The ports can be input, output, or control ports.

For example, in the sldemo_mdlref_basic model, each Model block references the
sldemo_mdlref_counter model and has:

• Three input ports, named upper, input, and lower


• One output port, named output

The sldemo_mdlref_counter referenced model has:

• Three Inport blocks, named upper, lower, and input


• One Outport block, named output

8-35
8 Referencing a Model

When you connect a signal to a Model block port, you connect the signal to the corresponding port of
the referenced model. The output of a Model block can differ despite the referenced model being the
same.

For example, in sldemo_mdlref_basic, each Model block input port receives a signal from a
unique Pulse Generator block. Because the input signal from each Pulse Generator block uses a
different sample time, the output signal from each Model block differs despite the referenced model
being the same.

To view how the output signal for each Model block differs, you can use the Simulation Data
Inspector.

Add Ports to Model Reference Interface


A model reference interface supports multiple types of ports and port blocks.

This table describes the type of ports and corresponding port blocks that a model reference interface
supports.

Type of Port Corresponding Port Block


Signal port, input Inport block
Signal port, output Outport block
Bus element port, input In Bus Element block
Bus element port, output Out Bus Element block
Control port, enabled Enable block

8-36
Define Model Reference Interfaces

Type of Port Corresponding Port Block


Control port, triggered Trigger block
Control port, function-call Trigger block with Trigger type set to function-call
Function port, client Function Element Call block
Function port, server Function Element block

To add ports to a model reference interface, perform either of these actions:

• In the top level of the referenced model, add blocks that correspond with ports.
• In the parent model, add ports to a Model block that references the model.

Note If the maximum port number in the model exceeds the number of ports in the model, you
cannot add ports to the model reference interface. For example, if there are five port blocks in the
model, and you change the port number parameter of one of them to 10, you cannot add ports to the
model reference interface.

To open a referenced model, open the model file or double-click the Model block. Then, add the port
blocks to the referenced model.

To add ports to a Model block, pause on any of the four edges of the block. When your pointer turns
into a cross, click. A new port, highlighted in blue, appears on the edge you click.

Pause your pointer on the new port. In the action menu that expands, select the type of port you want
to create. For example, you can create signal and bus element ports.

You can also add ports to a Model block by dragging a signal line from the model element you want to
connect to an edge of the Model block.

8-37
8 Referencing a Model

Dragging from a port block creates a new port of the same type. Dragging from a Subsystem or
Model block port that represents a port block also creates a new port of the same type as the port
block.

The input signals for the Model block must be valid for the corresponding input blocks of the
referenced model. The output signals for the Model block are the signals that connect to the
corresponding output blocks.

To delete an existing port, select the port and press Delete. To delete multiple ports, press Shift,
select the ports, and then press Delete.

For more information about referenced models with control ports, see “Conditionally Execute
Referenced Models” on page 8-28.

Tip You can use the same approach to add ports to and delete ports from Reference Component
blocks and Component (AUTOSAR Blockset) blocks that are linked to models.

Refresh Model Blocks

Refreshing a Model block updates it to reflect changes to the interface of the referenced model. For
example, when the referenced model gains or loses a port, refreshing the Model block updates its
ports.

By default, when a referenced model is loaded, the Model blocks that reference it automatically
refresh. When a referenced model is not loaded, the corresponding Model blocks refresh when you
perform actions such as:

• Opening the parent model


• Selecting a Model block
• Simulating the model hierarchy
• Generating code for the model hierarchy

To be notified when Simulink detects Model blocks that might not match their referenced models,
change the default setting for these diagnostic configuration parameters:

• Model block version mismatch


• Port and parameter mismatch

When these configuration parameters are set to error for a model, the Model blocks in that model
do not automatically refresh. To refresh a Model block when these configuration parameters are set
to error, perform either of these actions:

• Select the Model block. On the Model Block tab, click Refresh .
• Use the Simulink.ModelReference.refresh function.

When these configuration parameters are set to warning or none for a model, you can manually
refresh all Model blocks in the model hierarchy. To do so, perform either of these actions:

• On the Model Block tab, click the Update Model button arrow. Then, select Refresh Blocks.

8-38
Define Model Reference Interfaces

• Use the Simulink.BlockDiagram.refreshBlocks function.

Define Signal Attributes


Signal attributes in a referenced model are independent from the context of the Model block. For
example, signal dimensions and data types do not propagate across the Model block boundary.

To define the attributes of input to a referenced model, use the parameters of the root-level Inport
and In Bus Element blocks. An In Bus Element block can fully specify the hierarchy and attributes of
an input bus without a Simulink.Bus object.

In Bus Element and Out Bus Element blocks support multirate virtual buses and do not require
Simulink.Bus objects at model interfaces, unlike Inport and Outport blocks.

For signals that connect to Outport blocks to propagate out of a referenced model to the parent
model, the signal names must explicitly appear on the signal lines.

A referenced model can only provide input or get output for user-defined data types that are fixed
point or that Simulink.DataType or Simulink.Bus objects define.

Use Buses at Model Interfaces


Bus input for a Model block must be consistent with the bus expected by the referenced model.

If you use a bus as an input to or an output from a referenced model:

• Only a nonvirtual bus can contain variable-size signal elements.


• For code generation, you can configure the I/O arguments step method style of the C++
class interface for the referenced model only when using a nonvirtual bus or when using the
Default style of the C++ class interface.
• For code generation, you can configure function prototype control for the referenced model only
when using a nonvirtual bus.

For cleaner bus interfaces, use:

• In Bus Element blocks instead of Inport blocks connected to Bus Selector blocks
• Out Bus Element blocks instead of Bus Creator blocks connected to Outport blocks

For more information, see “Simplify Subsystem and Model Interfaces with Bus Element Ports” on
page 82-24.

For an example of a model hierarchy that uses buses with Inport blocks, see “Interface Specification
Using Bus Objects”.

Log Signals 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 the signals configured for signal logging in a model hierarchy. For
details, see “Override Signal Logging Settings” on page 78-52.

You can use the Simulation Data Inspector to view and analyze signals logged in referenced models.
You can view signals on multiple plots, zoom, and use data cursors to understand and evaluate the

8-39
8 Referencing a Model

data. Also, you can compare signal data from multiple simulations. For an example of viewing signals
with referenced models, see “Viewing Signals in Model Reference Instances”.

Configure Sample Times


The first nonvirtual block that connects to a root-level input or output block of a referenced model
must have the same sample time as the related port. If the sample times are different, use Rate
Transition blocks to match input and output sample times, as shown in this block diagram.

Share Data Among Referenced Model Instances


By default, each Model block instance reads from and writes to a separate copy of the signals and
block states in the model. Therefore, the instances do not interact with each other through shared
signal or state data.

To share a piece of data between all of the instances (for example, an accumulator or a fault
indicator), model the data as a data store.

• To restrict access to data so that only the blocks in the referenced model can read from and write
to it, use a Data Store Memory block in the model and select the Share across model instances
parameter. For an example, see “Share Data Among Multiple Instances of a Reusable Algorithm”.
• To allow access to data outside the referenced model, use a global data store, which is a
Simulink.Signal object in the base workspace or a data dictionary. Data outside the referenced
model can be in the parent model or in other referenced models.

For more information about data stores, see “Model Global Data by Creating Data Stores” on page
79-10.

See Also
Model | Inport | Outport | In Bus Element | Out Bus Element

More About
• “Use Buses at Model Interfaces” on page 8-39
• “Model Reference Requirements and Limitations” on page 8-11
• “Conditionally Execute Referenced Models” on page 8-28

8-40
Referenced Model Sample Times

Referenced Model Sample Times

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. Also, allowing a Model block to inherit sample time maximizes its reuse
potential. For example, a model can 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).

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
• 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 8-42
• 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 8-42.

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.

Note A continuous sample time cannot be propagated to a Model block that is sample-time
independent.

For more information, see “Blocks Whose Outputs Depend on Inherited Sample Time” on page 8-42.

Determining Sample Time of a Referenced Model


To determine whether a referenced model can inherit its sample time, set the Periodic sample time
constraint configuration parameter 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.

8-41
8 Referencing a Model

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:

• 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 (when the chart uses absolute-time temporal logic, or 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.

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. When building a referenced model that does

8-42
Referenced Model Sample Times

not need a specified rate, Simulink checks for blocks whose outputs are functions of the inherited
sample time. This checking includes examining S-Function blocks. If Simulink finds any such blocks,
it specifies a default sample time. If you have set the Configuration Parameters > Solver >
Periodic sample time constraint to Ensure sample time independent, Simulink displays an
error. 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
• Rate Limiter Dynamic
• 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 “Specify S-Function Sample Times” for
information on how to create S-functions that declare whether their output depends on their
inherited sample time.

In referenced models that inherit their sample time, avoid S-functions in referenced models that fail
to declare whether output depends on inherited sample time. Excluding those kinds of S-functions
helps to avoid simulation errors. 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.

Sample Time Consistency


Use consistent sample time rates to promote the reliable use of a model referenced by another model.
Make the rates of root Inport and Outport blocks in a referenced model consistent with the rates of
blocks reading from and writing to those blocks. Simulink generates an error when there are sample
time mismatches between:

• The sample times of root Inport blocks and the sample times of blocks to which the Inport block
inputs.
• The sample times of root Outport blocks and the sample times of blocks that input to the Outport
block.

To address an error that flags a sample time inconsistency in a referenced model, you can use one of
these approaches.

Top-Level Inport or Outport Block Sample Possible Solution


Time
Different from all the blocks to which it connects, Set the sample time of the Inport or Outport
and those blocks all have the same sample time block so that it matches the sample time of the
as each other block to which it connects.
Different from one or more blocks and the same For blocks that do not match the Inport or
as one or more blocks Outport block, insert Rate Transition blocks on
the signal that connects to the Inport or Outport
block.

8-43
8 Referencing a Model

Sample Rates and Solvers


The solver of the top model controls all continuous sample times in a model hierarchy. For example,
for a fixed-step solver, all continuous rates in referenced models run at the fixed-step size of the top
model. For information about how sample times impact solvers, see “Types of Sample Time” on page
7-18.

See Also

Related Examples
• “What Is Sample Time?” on page 7-2
• “Types of Sample Time” on page 7-18
• “Specify Sample Time” on page 7-10
• “View Sample Time Information” on page 7-15

8-44
Choose Simulation Modes for Model Hierarchies

Choose Simulation Modes for Model Hierarchies

When you simulate a model hierarchy, you should consider how top models and referenced models
execute.

• Top model — Supports all Simulink simulation modes. To speed up execution of a top model, you
can use Simulink accelerator or rapid accelerator mode.
• Referenced model — Although you can specify any simulation mode for a model, when you
reference that model, the Model block for each instance of the referenced model controls the
simulation mode of the instance. The simulation mode of a parent model can override the
simulation mode of a Model block.

For information on simulation modes, see “Choosing a Simulation Mode” on page 38-10 and “How
Acceleration Modes Work” on page 38-3.

For information on selecting solvers for models in a model hierarchy, see “Set Configuration
Parameters for Model Hierarchies” on page 8-75.

Model Reference Simulation Modes


You can specify any of these simulation modes for a Model block:

• Normal
• Accelerator
• Software-in-the-loop (SIL) — requires Embedded Coder
• Processor-in-the-loop (PIL) — requires Embedded Coder

When you choose between normal and accelerator mode, you must make a tradeoff between
flexibility and speed. Normal mode supports more Simulink and Stateflow features in referenced
models, such as scopes, port value display, and debugging tools. Accelerator mode supports fewer
features in referenced models, but simulates model hierarchies faster.

Modeling Normal Mode Accelerator Mode


Requirement
Simulation speed Models execute slower in normal mode Models execute faster in accelerator
than accelerator mode. However, mode than normal mode. Before
referenced models that execute in simulating the model, Simulink must
normal mode do not delay simulation to build and compile simulation targets,
build and compile simulation targets which can be undesirable for
because normal mode executes prototyping. For more information, see
referenced models interpretively. “Manage Simulation Targets for
Referenced Models” on page 8-66.

8-45
8 Referencing a Model

Modeling Normal Mode Accelerator Mode


Requirement
Debugging With the Simulink Debugger, you can For referenced models that execute in
set a breakpoint inside a referenced accelerator mode, specifications made
model that executes in normal mode. and actions taken by the Simulink
For more information, see “Debug Debugger and Simulink Profiler are
Simulations Programmatically”. ignored.

With the Simulink Profiler, you can


enable profiling for a referenced model
that executes in normal mode. Enabling
profiling on a parent model does not
enable profiling for referenced models.
See “How Simulink Profiler Captures
Performance Data” on page 34-5.
Testing Simulink Coverage™ model coverage Simulink Coverage model coverage
analysis supports referenced models analysis ignores referenced models that
that execute in normal mode. execute in accelerator mode.
Tunability You can tune block parameters during For referenced models that execute in
simulation for referenced models that accelerator mode, if the referenced
execute in normal mode. model uses variables in the base
workspace or a data dictionary to set
parameter values, you can tune the
values of the variables. You cannot tune
block parameters in the referenced
model during simulation. For more
information, see “Tunability
Considerations and Limitations for
Other Modeling Goals” on page 41-36.
Data logging Data logging provides extensive For referenced models that execute in
support for referenced models that accelerator mode, To Workspace blocks
execute in normal mode. log data only if they use the
Timeseries format for saving.

8-46
Choose Simulation Modes for Model Hierarchies

Modeling Normal Mode Accelerator Mode


Requirement
Data visualization You can view simulation results for all You can view simulation results for all
instances of the referenced model with instances of the referenced model with
the Simulation Data Inspector. the Simulation Data Inspector.

You can view instance-specific These visualization methods show no


simulation results for each instance data for referenced models that execute
with Display blocks in the referenced in accelerator mode.
model.
• Scope, Floating Scope, and Scope
Scopes and port value labels display Viewer blocks in the referenced
data for only the instance of the model
referenced model that has normal • Runtime displays, such as port value
mode visibility enabled. For more labels
information, see “Simulate Multiple
Referenced Model Instances in Normal Top model Scope blocks can display data
Mode” on page 8-59. for referenced models that execute in
accelerator mode if you use the Viewers
& Generators Manager to add test
points in the referenced model. Adding
or removing a test point requires
rebuilding the model reference
simulation target for a model.
Diagnostics Configuration parameter settings are For models referenced in accelerator
applied as specified. mode, Simulink can ignore some
configuration parameter settings. For
details, see “Diagnostics That Are
Ignored in Accelerator Mode” on page 8-
78.
Runtime checks Runtime checks are enabled. 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,
MATLAB Function, and MATLAB System
blocks.
Linearization Normal mode allows block-by-block In accelerator mode, discrete states of
analysis and linearization of a referenced model, model references are not exposed to
optimization which achieves an accurate linearization. These discrete states are
linearization. not perturbed during linearization and,
therefore, are not truly free in the
trimming process.

The outputs of random blocks are not


kept constant during trimming. Outputs
that are not kept constant can affect the
optimization process.

8-47
8 Referencing a Model

Modeling Normal Mode Accelerator Mode


Requirement
Extrinsic A MATLAB Function block in a A MATLAB Function block in a
functions referenced model that executes in referenced model that executes in
normal mode can call MATLAB accelerator mode cannot call MATLAB
functions that are declared extrinsic for functions that are declared extrinsic for
code generation. code generation.
S-Functions Referenced models that execute in Referenced models that execute in
normal mode support more S-functions accelerator mode support fewer S-
than referenced models that execute in functions than referenced models that
accelerator mode. For more execute in normal mode. For more
information see, “S-Functions in information see, “S-Functions in
Referenced Models” on page 8-11. Referenced Models” on page 8-11.

SIL and PIL simulation modes execute referenced models by generating production code for
embedded processors. SIL mode provides a convenient alternative to PIL simulation because it can
run on a host platform when the target hardware is not available. For more information, see “SIL and
PIL Simulations” (Embedded Coder).

Overridden Simulation Modes

The simulation mode of the parent model can override the simulation mode of a Model block. This
table shows which simulation mode the software uses for a referenced model instance based on the
simulation mode of the parent model and related Model block.

Simulation Mode Used by Simulation Mode of Model Block


Parent Model Normal Accelerator
Normal Compatible — Referenced Compatible — Referenced
model simulates in normal model simulates in accelerator
mode. mode.
Accelerator Overridden — Referenced model Compatible — Referenced
Rapid accelerator (top model simulates in accelerator mode. model simulates in accelerator
only) mode.

For information on SIL and PIL, see “Simulation Mode Override Behavior in Model Reference
Hierarchy” (Embedded Coder).

To manually override model reference simulation modes without dirtying any models, see “Override
Model Reference Simulation Modes” on page 8-50.

See Also

Related Examples
• “Manage Simulation Targets for Referenced Models” on page 8-66
• “Model Reference Requirements and Limitations” on page 8-11
• “Simulate Multiple Referenced Model Instances in Normal Mode” on page 8-59

8-48
Choose Simulation Modes for Model Hierarchies

• “Choosing a Simulation Mode” on page 38-10


• “Override Model Reference Simulation Modes” on page 8-50

8-49
8 Referencing a Model

Override Model Reference Simulation Modes

To override model reference simulation modes without dirtying any models:

1 Confirm that the top model in the model hierarchy simulates in normal mode.
2 Specify the override type by using the ModelReferenceSimulationModeOverride parameter
of the top model.
3 When the override affects only a subset of model references, specify the scope of the override by
using the ModelReferenceSimulationModeOverrideScope parameter of the top model.
4 Simulate the model hierarchy.

Supported ModelReferenceSimulationModeOverride override types include:

• none (default) — Use the simulation modes specified by the Model blocks.
• all-normal — Use normal mode for all Model blocks.
• all-accelerator — Use accelerator mode for all Model blocks.
• specified-models-to-normal — Use normal mode for the Model blocks that reference the
models specified by the ModelReferenceSimulationModeOverrideScope model parameter.
• specified-blocks-to-normal — Use normal mode for the Model blocks specified by the
ModelReferenceSimulationModeOverrideScope model parameter.

Only one override type is supported at a time. When you set


ModelReferenceSimulationModeOverride to none, all-normal, or all-accelerator, the
simulation ignores the ModelReferenceSimulationModeOverrideScope parameter.

Model blocks that reference protected models do not support simulation mode overrides.

For a comparison of model reference simulation modes, see “Choose Simulation Modes for Model
Hierarchies” on page 8-45.

Open Example

This example uses a model hierarchy that has multiple referenced models. Some referenced models
simulate in normal mode, while others simulate in accelerator mode.

Open the project named ModelReferenceHierarchy.

openProject("ModelReferenceHierarchy");

A project startup task opens the sldemo_mdlref_depgraph model, which is the top model in the
model hierarchy.

8-50
Override Model Reference Simulation Modes

Check Simulation Mode of Top Model

Confirm that the top model simulates in normal mode. When a top model simulates in normal mode,
its children can simulate in normal or accelerator mode. When a top model simulates in accelerator
or rapid accelerator mode, its children simulate in accelerator mode.

The ModelReferenceSimulationModeOverride parameter does not affect the simulation mode of


the top model. When the top model simulates in accelerator or rapid accelerator mode, the
ModelReferenceSimulationModeOverride parameter cannot override the model reference
simulation modes.

Examine Model Reference Simulation Modes

To view the model hierarchy and the simulation mode of each model reference instance, use the
Dependency Analyzer.

1 In the Simulink Toolstrip, on the Modeling tab, in the Design gallery, click Dependency
Analyzer.
2 In the Dependency Analyzer toolstrip, in the Views gallery, select Model Instances.

The Dependency Analyzer displays the model hierarchy and the simulation mode of each model
reference instance. While the model hierarchy references most of the models only once, the model
hierarchy references the sldemo_mdlref_F2C model twice.

8-51
8 Referencing a Model

One instance of sldemo_mdlref_F2C simulates in normal mode. The other instance simulates in
accelerator mode.

Determine How to Override Model Reference Simulation Modes

How you specify the ModelReferenceSimulationModeOverride and


ModelReferenceSimulationModeOverrideScope model parameters depends on your goal. This
example uses two strategies to specify these parameters for the top model in the model hierarchy:

• To temporarily set the parameters during simulation, this example uses a


Simulink.SimulationInput object.
• To set the parameters during edit time and support the debugging programmatic interface, this
example uses the set_param function.

Regardless of how you specify the ModelReferenceSimulationModeOverride and


ModelReferenceSimulationModeOverrideScope parameters, these parameters do not dirty the
model.

The override takes effect only during simulation. During edit time, the Model blocks do not display
the overridden simulation modes.

Override Simulation Mode of Specified Model

Suppose you want all instances of sldemo_mdlref_F2C to simulate in normal mode. To override the
simulation mode of sldemo_mdlref_F2C, you must also override the simulation modes of its parent
models.

To get the models between the sldemo_mdlref_depgraph top model and the sldemo_mdlref_F2C
referenced model, use the pathsToReferencedModel function.
topmodel = "sldemo_mdlref_depgraph";
refmodel = "sldemo_mdlref_F2C";
models = pathsToReferencedModel(topmodel,refmodel)

models = 4x1 cell


{'sldemo_mdlref_depgraph' }
{'sldemo_mdlref_outdoor_temp'}
{'sldemo_mdlref_heater' }
{'sldemo_mdlref_F2C' }

Create a Simulink.SimulationInput object that overrides the simulation mode of


sldemo_mdlref_F2C and its parent models to normal mode.

8-52
Override Model Reference Simulation Modes

simConfigModels = Simulink.SimulationInput(topmodel);
simConfigModels = setModelParameter(simConfigModels,...
ModelReferenceSimulationModeOverride="specified-models-to-normal",...
ModelReferenceSimulationModeOverrideScope=models)

simConfigModels =
SimulationInput with properties:

ModelName: "sldemo_mdlref_depgraph"
InitialState: [0x0 Simulink.op.ModelOperatingPoint]
ExternalInput: []
ModelParameters: [1x2 Simulink.Simulation.ModelParameter]
BlockParameters: [0x0 Simulink.Simulation.BlockParameter]
Variables: [0x0 Simulink.Simulation.Variable]
PreSimFcn: []
PostSimFcn: []
UserString: ''
VariantConfiguration: ''

In the Simulink.SimulationInput object, the ModelParameters property stores the parameter


settings.
simConfigModels.ModelParameters(1)

ans =
ModelParameter with properties:

Name: "ModelReferenceSimulationModeOverride"
Value: "specified-models-to-normal"

simConfigModels.ModelParameters(2)

ans =
ModelParameter with properties:

Name: "ModelReferenceSimulationModeOverrideScope"
Value: {4x1 cell}

Simulate the model hierarchy using the configuration stored in the Simulink.SimulationInput
object.
sim(simConfigModels);

### Searching for referenced models in model 'sldemo_mdlref_depgraph'.


### Found 3 model references to update.
### Starting serial model reference simulation build.
### Successfully updated the model reference simulation target for: sldemo_mdlref_thermostat
### Successfully updated the model reference simulation target for: sldemo_mdlref_heat2cost
### Successfully updated the model reference simulation target for: sldemo_mdlref_house

Build Summary

Simulation targets built:

Model Action Rebuild Reason


=================================================================================================

8-53
8 Referencing a Model

sldemo_mdlref_thermostat Code generated and compiled. sldemo_mdlref_thermostat_msf.mexw64 does


sldemo_mdlref_heat2cost Code generated and compiled. sldemo_mdlref_heat2cost_msf.mexw64 does n
sldemo_mdlref_house Code generated and compiled. sldemo_mdlref_house_msf.mexw64 does not e

3 of 3 models built (0 models already up to date)


Build duration: 0h 0m 58.618s

sldemo_mdlref_F2C and its parent models simulate in normal mode. Simulation does not check,
update, or use the model reference simulation target for the models that simulate in normal mode.

Overriding the model reference simulation modes does not dirty any of the models.

Override Simulation Mode of Specified Block

Suppose all the referenced models in the model hierarchy are configured to simulate in accelerator
mode. You want only the instance of sldemo_mdlref_F2C in sldemo_mdlref_heater to simulate
in normal mode. To override the simulation mode of sldemo_mdlref_F2C in
sldemo_mdlref_heater, you must also override the simulation mode of sldemo_mdlref_heater.

To get the Model blocks between the sldemo_mdlref_depgraph top model and the
sldemo_mdlref_F2C referenced model, use the pathsToReferencedModel function.

topmodel = "sldemo_mdlref_depgraph";
refmodel = "sldemo_mdlref_F2C";
[models,blocks] = pathsToReferencedModel(topmodel,refmodel)

models = 4x1 cell


{'sldemo_mdlref_depgraph' }
{'sldemo_mdlref_outdoor_temp'}
{'sldemo_mdlref_heater' }
{'sldemo_mdlref_F2C' }

blocks =
1x2 BlockPath array with properties:

SubPath
isLoadingModel
isSavingModel

The function returns one Simulink.BlockPath object for each instance of the referenced model in
the model hierarchy.

Get the Simulink.BlockPath object that corresponds to the instance of sldemo_mdlref_F2C in


sldemo_mdlref_heater. Assign the Simulink.BlockPath object to a variable.

block1 = blocks(1)

block1 =
Simulink.BlockPath
Package: Simulink

Block Path:
'sldemo_mdlref_depgraph/outdoor temp'
'sldemo_mdlref_outdoor_temp/Fahrenheit to Celsius'

Use the getBlock method to access block path character vectors from this object.

8-54
Override Model Reference Simulation Modes

block2 = blocks(2)

block2 =
Simulink.BlockPath
Package: Simulink

Block Path:
'sldemo_mdlref_depgraph/thermostat'
'sldemo_mdlref_heater/Fahrenheit to Celsius'

Use the getBlock method to access block path character vectors from this object.

The second Simulink.BlockPath object represents the Model block that references
sldemo_mdlref_F2C in sldemo_mdlref_heater.

Create a Simulink.SimulationInput object that overrides the simulation mode of this Model
block.

simConfigBlock = Simulink.SimulationInput(topmodel);
simConfigBlock = setModelParameter(simConfigBlock,...
ModelReferenceSimulationModeOverride="specified-blocks-to-normal",...
ModelReferenceSimulationModeOverrideScope=block2)

simConfigBlock =
SimulationInput with properties:

ModelName: "sldemo_mdlref_depgraph"
InitialState: [0x0 Simulink.op.ModelOperatingPoint]
ExternalInput: []
ModelParameters: [1x2 Simulink.Simulation.ModelParameter]
BlockParameters: [0x0 Simulink.Simulation.BlockParameter]
Variables: [0x0 Simulink.Simulation.Variable]
PreSimFcn: []
PostSimFcn: []
UserString: ''
VariantConfiguration: ''

In the Simulink.SimulationInput object, the ModelParameters property stores the parameter


settings.

simConfigBlock.ModelParameters(1)

ans =
ModelParameter with properties:

Name: "ModelReferenceSimulationModeOverride"
Value: "specified-blocks-to-normal"

simConfigBlock.ModelParameters(2)

ans =
ModelParameter with properties:

Name: "ModelReferenceSimulationModeOverrideScope"
Value: [1x1 Simulink.BlockPath]

8-55
8 Referencing a Model

Simulate the model hierarchy using the configuration stored in the Simulink.SimulationInput
object.

sim(simConfigBlock);

### Searching for referenced models in model 'sldemo_mdlref_depgraph'.


### Found 5 model references to update.
### Starting serial model reference simulation build.
### Successfully updated the model reference simulation target for: sldemo_mdlref_F2C
### Model reference simulation target for sldemo_mdlref_thermostat is up to date.
### Model reference simulation target for sldemo_mdlref_heat2cost is up to date.
### Model reference simulation target for sldemo_mdlref_house is up to date.
### Successfully updated the model reference simulation target for: sldemo_mdlref_outdoor_temp

Build Summary

Simulation targets built:

Model Action Rebuild Reason


=================================================================================================
sldemo_mdlref_F2C Code generated and compiled. sldemo_mdlref_F2C_msf.mexw64 does not e
sldemo_mdlref_outdoor_temp Code generated and compiled. sldemo_mdlref_outdoor_temp_msf.mexw64 d

2 of 5 models built (3 models already up to date)


Build duration: 0h 0m 26.436s

The specified instance of sldemo_mdlref_F2C simulates in normal mode. Its parent model,
sldemo_mdlref_heater, also simulates in normal mode.

The other instance of sldemo_mdlref_F2C continues to simulate in accelerator mode. The


simulation checks whether to update the model reference simulation target for
sldemo_mdlref_F2C.

Overriding the model reference simulation modes does not dirty any of the models.

Override Simulation Modes of All Model Blocks

Suppose you want to simulate the entire model hierarchy in normal mode for debugging.

The debugging programmatic interface does not support Simulink.SimulationInput objects as


input.

To set the override type, use the set_param function.

topmodel = "sldemo_mdlref_depgraph";
set_param(topmodel,...
ModelReferenceSimulationModeOverride="all-normal");

When you set ModelReferenceSimulationModeOverride to all-normal, you do not specify the


scope of the override.

To start the simulation in debug mode, enter this command.

sim(topmodel,Debug="on");

For information about debugging simulations programmatically, see “Simulink Debugging


Programmatic Interface” on page 37-2.

8-56
Override Model Reference Simulation Modes

All the referenced models simulate in normal mode. Simulation does not check, update, or use the
model reference simulation targets for models that simulate in normal mode.

Overriding the model reference simulation modes does not dirty any of the models.

Optionally, remove the override after you finish debugging.

set_param(topmodel,...
ModelReferenceSimulationModeOverride="none");

The override settings do not persist when you close the model or change MATLAB® sessions.

See Also
Model

Related Examples
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Manage Simulation Targets for Referenced Models” on page 8-66
• “Model Reference Requirements and Limitations” on page 8-11
• “Simulate Multiple Referenced Model Instances in Normal Mode” on page 8-59
• “Choosing a Simulation Mode” on page 38-10

8-57
8 Referencing a Model

Simulate Conditionally Executed Referenced Models


You can run a standalone simulation of a conditionally executed referenced model, or conditional
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. Use normal, accelerator, or rapid
accelerator mode to simulate a conditional model.

Triggered, Enabled, and Triggered and Enabled Models


Triggered, enabled, and triggered and enabled models require an external input to drive the Trigger
or Enable blocks. In the Signal Attributes pane of the Trigger or Enable block dialog box, specify
values for the signal data type, dimension, and sample time.

To run a standalone simulation, specify the inputs using the Input configuration parameter. For
details about how to specify the input, see “Comparison of Signal Loading Techniques” on page 76-
21. The following conditions apply when you use the Input parameter for Trigger and Enable block
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.

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.

Function-Call Models
When you simulate a function-call model, the Model block conditionally executes when it receives a
function-call event. A Stateflow chart, Function-Call Generator block, or S-Function block can provide
function-call events.

You can also configure the model to calculate output at specific times using a variable-step solver. For
more information, see “Samples to Export for Variable-Step Solvers” on page 78-39.

See Also
Enable | Trigger | Function-Call Subsystem

More About
• “Conditionally Execute Referenced Models” on page 8-28
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Export-Function Models Overview” on page 10-125

8-58
Simulate Multiple Referenced Model Instances in Normal Mode

Simulate Multiple Referenced Model Instances in Normal Mode


Multiple Model blocks can reference the same model. Each Model block that references the same
model creates an instance of the referenced model in the model hierarchy.

A referenced model instance simulates in normal mode when both of these conditions apply:

• The corresponding Model block has its Simulation Mode block parameter set to Normal.
• The top model and any intermediate Model blocks are configured to simulate in normal mode.

For additional requirements, see “Model Reference Requirements and Limitations” on page 8-11.

When you simulate multiple referenced model instances in normal mode, only one instance has
normal mode visibility.

Normal Mode Visibility

All instances of a referenced model that simulate in normal mode are part of the simulation. However,
only one normal-mode instance of the referenced model supports all data visualizations. For example,
scopes and port value labels display data for only the instance that has normal mode visibility
enabled. To view simulation results for all instances of the referenced model, use the Simulation Data
Inspector. To view instance-specific data for each instance of the model that simulates in normal
mode, use Display blocks in the referenced model.

To set normal mode visibility, in the Simulink Toolstrip, on the Simulation tab, click the down arrow
on the far right of the Prepare section. In the gallery, under Signal Monitoring, click Normal
Mode Visibility. This setting determines the instance that has normal mode visibility enabled. If you
do not specify normal mode visibility for an instance of a referenced model, the software selects
which instance of the referenced model has normal mode visibility enabled.

Examine Multiple Referenced Model Instances

Open the example model named sldemo_mdlref_basic.

8-59
8 Referencing a Model

The model has Model blocks named CounterA, CounterB, and CounterC that each reference the
model named sldemo_mdlref_counter.

When you update the top model, each Model block icon has different colors at the corners.

• The Model block named CounterA has white corners.


• The Model block named CounterB has gray corners.
• The Model block named CounterC has black corners.

The different corner colors indicate the simulation mode and normal mode visibility setting.

• White corners — Normal mode with normal mode visibility enabled


• Gray corners — Normal mode with normal mode visibility disabled
• Black corners — Accelerator mode

Simulate the model hierarchy.

Double-click the Model block named CounterA or CounterB.

8-60
Simulate Multiple Referenced Model Instances in Normal Mode

Open the Scope block named ScopeA.

8-61
8 Referencing a Model

Regardless of which Model block you open, the scope displays the data for CounterA, because
CounterA has normal mode visibility enabled.

To view the data for the other instances of the referenced model, mark the signal for logging before
simulation. Then, use the Simulation Data Inspector.

Determine Which Instance Has Normal Mode Visibility Enabled

After you compile a model, you can determine whether an instance has normal mode visibility
enabled by inspecting the corners of the Model block icon. When the corners are white, the instance
has normal mode visibility enabled. For a large model hierarchy, finding this instance based on the
Model block icons can be time consuming. Instead, use these programmatic parameters:

• ModelReferenceNormalModeVisibilityBlockPath — For a referenced model, find the Model


block that has normal mode visibility enabled.
• CompiledModelBlockNormalModeVisibility — For all referenced models in a model
hierarchy, find the Model blocks that have normal mode visibility enabled.

For example, open the project named ModelReferenceHierarchy.


openProject("ModelReferenceHierarchy");

The project opens a model hierarchy with sldemo_mdlref_depgraph as the top model.

Suppose you want to find the Model block that references the sldemo_mdlref_F2C model and has
normal mode visibility enabled.

Update the top model.


set_param("sldemo_mdlref_depgraph",SimulationCommand="Update");

Get the Model block path.


get_param('sldemo_mdlref_F2C',...
'ModelReferenceNormalModeVisibilityBlockPath')

ans =
Simulink.BlockPath
Package: Simulink

Block Path:
'sldemo_mdlref_depgraph/thermostat'
'sldemo_mdlref_heater/Fahrenheit to Celsius'

Use the getBlock method to access block path character vectors from this object.

Suppose you want to find all the Model blocks in a model hierarchy that have normal mode visibility
enabled.

Execute the compilation phase of simulation by using the sldemo_mdlref_depgraph model name
as a programmatic interface.
sldemo_mdlref_depgraph([],[],[],'compile');

### Searching for referenced models in model 'sldemo_mdlref_depgraph'.


### Found 5 model references to update.

8-62
Simulate Multiple Referenced Model Instances in Normal Mode

### Starting serial model reference simulation build.


### Model reference simulation target for sldemo_mdlref_F2C is up to date.
### Model reference simulation target for sldemo_mdlref_thermostat is up to date.
### Model reference simulation target for sldemo_mdlref_heat2cost is up to date.
### Model reference simulation target for sldemo_mdlref_house is up to date.
### Model reference simulation target for sldemo_mdlref_outdoor_temp is up to date.

Build Summary

0 of 5 models built (5 models already up to date)


Build duration: 0h 0m 2.5274s

Get the Model block paths.

blocks = get_param('sldemo_mdlref_depgraph',...
'CompiledModelBlockNormalModeVisibility')

blocks = struct with fields:


sldemo_mdlref_F2C: [1x1 Simulink.BlockPath]
sldemo_mdlref_heater: [1x1 Simulink.BlockPath]

Inspect the Model block paths.

blocks.sldemo_mdlref_F2C

ans =
Simulink.BlockPath
Package: Simulink

Block Path:
'sldemo_mdlref_depgraph/thermostat'
'sldemo_mdlref_heater/Fahrenheit to Celsius'

Use the getBlock method to access block path character vectors from this object.

blocks.sldemo_mdlref_heater

ans =
Simulink.BlockPath
Package: Simulink

Block Path:
'sldemo_mdlref_depgraph/thermostat'

Use the getBlock method to access block path character vectors from this object.

Terminate the compilation phase.

sldemo_mdlref_depgraph([],[],[],'term');

Specify Which Instance Has Normal Mode Visibility Enabled

While you edit a model hierarchy, you can specify which instance of a referenced model has normal
mode visibility enabled.

8-63
8 Referencing a Model

1 In the Simulink Toolstrip, on the Simulation tab, click the down arrow on the far right of the
Prepare section. Then, under Signal Monitoring, click Normal Mode Visibility.

The Model Block Normal Mode Visibility dialog box opens. For example, this dialog box for the
sldemo_mdlref_basic model has the hierarchy pane expanded.

The dialog box does not display Model blocks that reference protected models, and each
displayed branch of the model hierarchy stops at the first Model block that is not in normal
mode. The normal mode instances of referenced models have check boxes.

Tip To update the model hierarchy in the dialog box to reflect the current model hierarchy, click
Refresh.
2 Select the instance of the model that you want to have normal mode visibility.

When you select an instance, you also select its parents. When you clear an instance, you also
clear its children.

Tip To open a model from the dialog box, right-click the model name. Then, click Open.

8-64
Simulate Multiple Referenced Model Instances in Normal Mode

3 To apply the normal mode visibility setting, simulate the model hierarchy.

Alternatively, change the instance that has normal mode visibility enabled with the
ModelBlockNormalModeVisibility parameter. Set this parameter to one of these values:

• An array of Simulink.BlockPath objects.

bp1 = Simulink.BlockPath({'TopModel/Model',...
'ReferencedModelA/Model'});
bp2 = Simulink.BlockPath({'TopModel/Model1',...
'ReferencedModelB/Model'});
bps = [bp1, bp2];
set_param('TopModel','ModelBlockNormalModeVisibility',bps);

Note When you create a Simulink.BlockPath object for specifying normal mode visibility:

• The first character vector must represent a block that is in the top model of the model
reference hierarchy.
• Character vectors must represent Model blocks that are in normal mode.
• Character vectors that represent variant models or variant subsystems must refer to an active
variant.

• A cell array of cell arrays of character vectors, with the character vectors being paths to individual
blocks and models.

bp1 = {'TopModel/Model','ReferencedModelA/Model'};
bp2 = {'TopModel/Model1','ReferencedModelB/Model'};
bps = {bp1, bp2};
set_param('TopModel','ModelBlockNormalModeVisibility',bps);
• An empty array, to use the default selection of the instance that has normal mode visibility.

set_param('TopModel','ModelBlockNormalModeVisibility',[]);

Using an empty array is equivalent to clearing all the check boxes in the Model Block Normal
Mode Visibility dialog box.

See Also

Related Examples
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Choosing a Simulation Mode” on page 38-10
• “Reduce Update Time for Referenced Models by Using Parallel Builds” on page 8-69
• “Manage Simulation Targets for Referenced Models” on page 8-66

8-65
8 Referencing a Model

Manage Simulation Targets for Referenced Models


A simulation target, or SIM target, is an automatically generated 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 instances of the referenced model that execute in accelerator
mode. Instances of the referenced model that execute in normal mode do not use the simulation
target.

To create model reference simulation targets, Simulink generates code that imposes some
requirements and limitations on referenced models that execute in accelerator mode. Aside from
these constraints, you can generally ignore simulation targets when you execute a referenced model
in accelerator mode. For information on these constraints, see “Choose Simulation Modes for Model
Hierarchies” on page 8-45.

By default, Simulink generates the simulation target for a referenced model that executes in
accelerator mode if:

• The simulation target does not exist when you update the diagram of a direct or indirect parent of
the referenced model or simulate the model hierarchy.
• The simulation target is out of date with structural changes in the referenced model.

While generating a simulation target, the MATLAB command window displays status messages so
that you can monitor the simulation target generation process.

To programmatically build a model reference simulation target, use the slbuild function.

Note If you have a Simulink Coder license, be careful not to confuse the simulation target of a
referenced model with these other types of targets:

• 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

Reduce Time Spent Checking For Changes


You can reduce the time that Simulink spends checking whether simulation targets require rebuilding
by setting configuration parameter values as follows:

• In all referenced models throughout the hierarchy, set the Signal resolution configuration
parameter to Explicit only or None.
• In the top model of the model hierarchy, set the Rebuild configuration parameter to If changes
in known dependencies detected. Alternatively, you can use this parameter to specify that
Simulink always or never rebuilds simulation targets.

These parameters exist in the configuration set of the model; they are not parameters of the Model
block. Setting these parameters for any instance of a referenced model sets it for all instances of that
model.

8-66
Manage Simulation Targets for Referenced Models

Specify Programming Language of Simulation Targets


To specify the programming language for model reference simulation targets, use the Language
configuration parameter on the Simulation Target tab of the Configuration Parameters dialog box.

Use Custom Code for Simulation Targets


To use custom code with Stateflow or with MATLAB Function blocks when building a model reference
simulation target, use the Include custom code for referenced models configuration parameter.

Caution Using custom code for referenced models in accelerator mode can produce different results
than when you simulate the model without using custom code. If the custom code includes
declarations of structures for buses or enumerations, the simulation target generation fails if the
build results in duplicate declarations of those structures. Also, if custom code uses a structure that
represents a bus or enumeration, you can get unexpected simulation results.

Control Location of Simulation Targets


Simulink creates simulation targets in the slprj build folder of the current folder. If the slprj
folder does not exist, Simulink creates it.

Note Simulink Coder code generation also uses the slprj folder. Subfolders in slprj provide
separate places for simulation code, Simulink Coder code, and other files. For details, see “Manage
Build Process Folders” (Simulink Coder).

You can place generated files in a different root folder than the current working folder. This option
allows you to:

• Store generated files separate from the models and other source materials used to generate them.
• Reuse or share previously built simulation targets without having to set the current working folder
to a previous working folder.
• Separate generated simulation artifacts from generated production code.

The simulation cache folder is the root folder in which to place artifacts used for simulation.

To specify a simulation cache folder to use instead of the current folder (pwd), in the Simulink
Preferences > General dialog box, set the Simulation cache folder by entering or browsing to a
folder path.

8-67
8 Referencing a Model

This preference provides the initial defaults for MATLAB session parameters.

Alternatively, you can set the CacheFolder MATLAB session parameter using the set_param
function.

>> set_param(0, 'CacheFolder', fullfile('C:','Work','MyModelSimCache'))


>> get_param(0, 'CacheFolder')

ans =

C:\Work\MyModelSimCache

To override or restore the Simulation cache folder preference only for the current MATLAB
session, use the Simulink.fileGenControl function. The values you set using
Simulink.fileGenControl expire at the end of the current MATLAB session.

See Also

More About
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Share Simulink Cache Files for Faster Simulation” on page 8-70
• “Reduce Update Time for Referenced Models by Using Parallel Builds” on page 8-69

8-68
Reduce Update Time for Referenced Models by Using Parallel Builds

Reduce Update Time for Referenced Models by Using Parallel


Builds
For models with large model reference hierarchies, you can increase the speed of diagram updates by
building in parallel referenced models that are configured to run in accelerator mode. With Parallel
Computing Toolbox software, you can distribute the code generation and compilation for referenced
models across a parallel pool of MATLAB workers. If you also have MATLAB Parallel Server™
software, you can distribute the code generation and compilation across remote workers in your
MATLAB Parallel Server configuration.

To configure parallel building of referenced models:

1 Open the Configuration Parameters dialog box for the top model of the model hierarchy.
2 Select the Enable parallel model reference builds check box.
3 For each MATLAB worker, you can set up a MATLAB environment that is consistent with the
MATLAB environment of the client. From the MATLAB worker initialization for builds drop-
down list, select one of these values:

• None –– Simulink does not initialize workers.


• Copy base workspace –– Simulink attempts to copy the base workspace to each MATLAB
worker.
• Load top model –– Simulink loads the top model onto each MATLAB worker.

If the Parallel Computing Toolbox parallel preference Automatically create a parallel pool (if one
doesn't already exist) when parallel keywords (e.g., parfor) are executed is selected, a parallel
pool of MATLAB workers is automatically started. For more information, see “Specify Your Parallel
Preferences” (Parallel Computing Toolbox).

If a parallel pool is not running when you update your model, MATLAB automatically opens a parallel
pool of workers by using the default cluster profile. To change the default behaviour of the worker
cluster, you can modify properties of the cluster profile. If you have not touched your parallel
preferences, the default profile is local. Control parallel behavior with the parallel preferences,
including scaling up to a cluster, automatic pool creation, and preferred number of workers. For more
information, see “Discover Clusters and Use Cluster Profiles” (Parallel Computing Toolbox).

For more general information about parallel computing, see “Run MATLAB Functions with Automatic
Parallel Support” (Parallel Computing Toolbox).

See Also

More About
• “Manage Simulation Targets for Referenced Models” on page 8-66
• “Share Simulink Cache Files for Faster Simulation” on page 8-70
• “Run Parallel Simulations” on page 28-11
• “Reduce Build Time for Referenced Models by Using Parallel Builds” (Simulink Coder)

8-69
8 Referencing a Model

Share Simulink Cache Files for Faster Simulation


Simulink cache files contain build artifacts that can speed up simulation and code generation. To
generate these build artifacts and automatically package them in Simulink cache files, perform one of
these actions:

• Update the diagram for a model hierarchy that contains models referenced in accelerator mode
• Simulate a model hierarchy that contains models referenced in accelerator mode
• Simulate a top model in accelerator or rapid accelerator mode
• Generate code for a model or model hierarchy

The second time that you perform any of these actions, Simulink builds only the out-of-date files as
long as the Rebuild configuration parameter is set to If changes detected (default) or If
changes in known dependencies detected. With fewer files to build, the actions complete
faster.

Note While you can avoid all referenced model rebuilds by setting the Rebuild configuration
parameter to Never, using this setting can produce invalid simulation results.

Team members and continuous integration (CI) systems can generate Simulink cache files for models
that you use. To reduce the time it takes when you build those models for the first time, you can copy
the corresponding Simulink cache files to your local folder specified by the Simulation cache folder
preference. Simulink extracts any Simulink cache file contents that differ from the contents on disk. If
Simulink generates or updates the build artifacts on disk, it locally updates the corresponding
Simulink cache files.

You can identify a Simulink cache file by its .slxc extension. Its file name matches the name of the
corresponding model.

Inspect Simulink Cache File Contents


Simulink cache files can contain multiple types of build artifacts, including:

• Accelerator targets
• Rapid accelerator targets
• Model reference simulation targets
• Variable usage information
• Code generation targets (Simulink Coder, Embedded Coder)
• Model representations (Simulink Design Verifier)
• Web views (Simulink Report Generator)

Simulink cache files accumulate build artifacts for multiple platforms and Simulink releases.

To learn what a specific Simulink cache file contains, open the report by double-clicking the file.

8-70
Share Simulink Cache Files for Faster Simulation

8-71
8 Referencing a Model

Alternatively, to get the contents of the Simulink cache file in a MATLAB table, use the slxcinfo
function.

You can reuse build artifacts that support the platform and release that you are using. For example,
suppose that you use a Windows machine and the R2019a Simulink release. In the Simulink cache file
described by this report, you can use the simulation targets under R2019a : win64. A team member
that uses a Linux machine and R2019b can use the simulation and code generation targets under
R2019b : glnxa64 and the model representations under R2019b : all platforms.

A Simulink cache file can accumulate build artifacts for the release in which it was created and later
releases. Suppose you create a Simulink cache file in R2019b. You would not be able to use that
Simulink cache file in R2019a.

Use Simulink Cache Files


While most teams can benefit from using Simulink cache files, a development environment with these
features is best suited for using Simulink cache files.

• A model hierarchy that contains many referenced models.


• A top model that simulates in accelerator or rapid accelerator mode, causing Simulink to generate
a simulation target for the top model and all referenced models.
• A standardized platform, compiler, and Simulink release for the entire development team.
• Relative paths or consistent absolute paths, which you specify with the Include directories
configuration parameter, for the entire development team.
• A source control system, such as Git, that manages design files. See “Set Up Git Source Control”
on page 19-17.

Note Since Simulink cache files are derived files, you should not manage them under source
control. Even if you share Simulink cache files by storing them in a source control system, you
cannot diff or merge different versions of these files.
• A CI system, such as Jenkins®, which periodically builds the latest version of the model hierarchy
using a pool of parallel workers.

Note To avoid unnecessary rebuilds for simulation and coder targets that use custom code, map
the CI system directories to named volumes or symbolic links that are the same in team member
sandboxes. For example, have the CI system and team members store custom code in a mapped
directory such as B:\path\customcode.

In this development environment, you interact with files in the source control system and build
archive.

8-72
Share Simulink Cache Files for Faster Simulation

To reduce the amount of time that you spend updating simulation targets, follow these steps.

1 Pull the latest version of all design files from the source control system.
2 Copy the latest version of all Simulink cache files from the build archive and place them in your
Simulation cache folder.
3 Open the top model and simulate it.

Simulink extracts the required build artifacts from the Simulink cache files. The simulation
completes without rebuilding any models as long as the models have not changed since the most
recent build completed by the CI system.

Note To unpack the simulation and code generation targets from the Simulink cache files
without updating, simulating, or generating code for the model hierarchy, use the slxcunpack
function.
4 Change a model and simulate the model hierarchy again.

Simulink rebuilds the necessary models and updates the local copy of the corresponding
Simulink cache file.
5 Commit the updated model to the source control system. You do not commit the Simulink cache
file, which is a derived file.

Check for Simulink Cache Files in Projects


When you create a project from a top model, the project includes the corresponding Simulink cache
files for the model and its referenced models.

To view Simulink cache file dependencies in a model hierarchy, you can select Dependency Analyzer
in the Views pane of the corresponding project.

8-73
8 Referencing a Model

For more information, see “Perform Impact Analysis with a Project”.

See Also
slxcinfo | slxcunpack

Related Examples
• “Choose Simulation Modes for Model Hierarchies” on page 8-45
• “Manage Simulation Targets for Referenced Models” on page 8-66
• “Simulink Cache Files for Incremental Code Generation” (Simulink Coder)
• “Reduce Update Time for Referenced Models by Using Parallel Builds” on page 8-69
• “Share Simulink Cache File for Faster Analysis” (Simulink Design Verifier)

External Websites
• Simulink Cache (1 min, 27 sec)
• Agile Model-Based Design: Accelerating Simulink Simulations in Continuous Integration
Workflows
• Workflow for Simulink Cache and Jenkins (File Exchange)

8-74
Set Configuration Parameters for Model Hierarchies

Set Configuration Parameters for Model Hierarchies


A referenced model uses a configuration set the same way that it would if the model executed
independently. By default, every model in a hierarchy has its own configuration set. Because each
model can have its own configuration set, configuration parameter values can be different in different
models.

Some parameter values are intrinsically incompatible with model references. The response to an
inconsistent or unusable configuration parameter depends on the parameter.

• Where an inconsistency has no significance, or a trivial resolution without risk exists, the software
ignores or resolves the inconsistency without issuing a warning.
• Where a nontrivial and possibly acceptable solution exists, the software resolves the conflict
silently, resolves it and issues a warning, or issues an error. For details, see “Diagnostics That Are
Ignored in Accelerator Mode” on page 8-78.
• Where no acceptable resolution is possible, the software issues an error.

Manage Configuration Parameters by Using Configuration References


To assign an externally stored configuration set to multiple models, you can use configuration
references. Configuration references help you eliminate configuration parameter incompatibilities.

You can propagate the configuration reference of a top model to an individual referenced model or to
all referenced models in the model hierarchy. For an example, see “Share a Configuration Across
Referenced Models” on page 13-20.

Review Configuration Requirements for Simulation of Model Reference


Hierarchies
Some configuration parameter settings can cause incompatibilities in model hierarchies. Where
possible, the software resolves violations of these requirements automatically, but most cases require
changes to the parameters in some or all models.

This table provides configuration parameter requirements for simulation of model reference
hierarchies. For code generation requirements, see “Set Configuration Parameters for Code
Generation of Model Hierarchies” (Simulink Coder).

8-75
8 Referencing a Model

Dialog Box Pane Configuration Requirement


Parameter
Solver Start time The compiled start time of the top model and all
referenced models must be the same.

The compiled start time is the start time that the


solver uses for the simulation. Often, the
compiled start time value matches the value you
specify using the Start time parameter. When
you use a fixed-step solver and the start time you
specify is not 0 or an integer multiple of the fixed
step size for the simulation, the solver determines
the compiled start time as the nearest integer
multiple of the fixed step size, moving forward in
time.
Stop time The software uses the stop time of the top model
for simulation, overriding any differing stop time
in a referenced model.
Type When no referenced models in the hierarchy use
a local solver, the solver type of the top model
applies throughout the hierarchy. To check
compatibility, see “Specify Compatible Solver
Settings” on page 8-77.

When you configure one or more referenced


models to use a local solver:

• The top solver type can be variable-step or


fixed-step.
• The local solver type must be fixed-step.
Solver When no referenced models in the hierarchy use
a local solver, the solver of the top model applies
throughout the hierarchy.

When you configure one or more referenced


models to use a local solver, the solver you select
for the referenced model solves the model as a
separate set of differential equations. For more
information, see “Configure Local Solver
Settings” on page 8-78.
Treat each discrete When a multirate model treats each discrete rate
rate as a separate as a separate task and references another
task multirate model, the referenced model must also
treat each discrete rate as a separate task.

8-76
Set Configuration Parameters for Model Hierarchies

Dialog Box Pane Configuration Requirement


Parameter
Allow tasks to execute A parent model and referenced model support
concurrently on different concurrent tasking settings only when
target the referenced model does not contain
asynchronous sample times and one of these
conditions is true:

• The referenced model contains only one


periodic sample time.
• The referenced model contains multiple
periodic sample times, and the parent model
enables explicit partitioning. The software
satisfies the rate-transition requirements with
rate monotonic scheduling.
Data Import/Export Initial state When a top model specifies an initial model state
or operating point for simulation, a referenced
model must not also specify an initial model state
or operating point.
Math and Data Types Simulation behavior In a model reference hierarchy, you can simulate
for denormal a top model using gradual underflow with any
numbers simulation mode. Models referenced by the top
model can simulate the flush-to-zero behavior
only if the instance of the referenced model uses
an accelerated simulation mode and has this
parameter set to Flush to zero (FTZ).
Use division for fixed- For simulations in normal or accelerator mode, a
point net slope parent model and referenced model must be
computation configured to perform Fixed-Point Designer™ net
scaling computations in the same way.
Diagnostics > Block behavior When a model is configured to produce an error
Compatibility depends on frame for this parameter, each referenced model must
status of signal also be configured to produce an error.
Model Referencing Total number of A referenced model must specify that it is
instances allowed per available to be referenced, and whether it can be
top model referenced at most once or can have multiple
instances. By default, a referenced model can be
referenced multiple times.

The total number of instances allowed per top


model must not be zero for a referenced model.

Specify Compatible Solver Settings


Model referencing works with both fixed-step and variable-step solvers. When no referenced models
use a local solver, all models in a model hierarchy use the same solver, which is always the solver
specified by the top model. The software issues an error if the solver type specified in the top model
is incompatible with the solver type specified in any referenced model.

8-77
8 Referencing a Model

Top Model Solver Type Referenced Model Solver Compatibility


Type
Fixed-step Fixed-step Compatible.
Variable-step Variable-step Compatible.
Variable-step Fixed-step Compatible unless the
referenced model specifies both
a discrete sample time and a
continuous sample time.
Fixed-step Variable-step Incompatible. The software
issues an error.

If an incompatibility exists between the solver type in the top model and the solver type in any
referenced model, one or both models must change to use compatible solver types. For information
about solvers, see “Compare Solvers” on page 3-6 and “Solver Selection Criteria” on page 27-10.

Configure Local Solver Settings


You can configure one or more referenced models in a model hierarchy to use a local solver. Consider
using a local solver when:

• A referenced model represents a component with much faster or slower dynamics compared to
the rest of the system and continuous states that are decoupled from the rest of the system.
• A different solver from the solver for the top model is better suited to solve the referenced model.

To use a local solver, set these configuration parameters for the referenced model:

1 Select the Use local solver when referencing model parameter.


2 Set the Type parameter to Fixed-step.
3 Set the Solver parameter to a value other than discrete (no continuous states).
4 Specify the Fixed-step size (fundamental sample time) parameter value as a scalar number
or auto.

Local solvers for referenced models operate on continuous states in the referenced model. Because
using a local solver for a referenced model with only discrete states has no effect on simulation
results, local solvers are not supported for models that do not contain continuous states. When a
model contains no continuous states, the software always uses the discrete solver. The fixed-step
discrete solver is not supported as a local solver.

For information about how local solvers work, how to configure instance-specific local solver settings,
and a complete list of limitations and considerations, see “Use Local Solvers in Referenced Models”
on page 27-5.

Diagnostics That Are Ignored in Accelerator Mode

When a referenced model simulates only in accelerator mode, the software does not issue warnings
or errors for these diagnostic configuration parameters of the referenced model.

• Array bounds exceeded

8-78
Set Configuration Parameters for Model Hierarchies

• Inf or NaN block output


• Simulation range checking
• Division by singular matrix
• Wrap on overflow
• Detect read before write
• Detect write after read
• Detect write after write

To identify the referenced models with diagnostics that are ignored during simulation in accelerator
mode, use the Model Advisor.

1 On the Modeling tab, click Model Advisor.


2 Select the top model, then click OK.
3 Select By Task > Model Referencing > Check diagnostic settings ignored during
accelerated model reference simulation.
4 Click Run This Check.

To run the diagnostics for the identified referenced models, configure the corresponding
configuration parameters to produce warnings or errors. Then, simulate the model in normal mode
and check for diagnostic messages.

Note Configuration parameters on the Code Generation pane of the Configuration Parameters
dialog box do not affect simulation in either normal or accelerator mode. Code Generation
parameters affect only Simulink Coder code generation. Accelerator mode simulation requires code
generation to create a simulation target. Simulink software uses default values for all Code
Generation parameters when generating the target and restores the original parameter values after
code generation is complete.

See Also

More About
• “Manage Configuration Sets for a Model” on page 13-6
• “Share a Configuration with Multiple Models” on page 13-12
• “Set Configuration Parameters for Code Generation of Model Hierarchies” (Simulink Coder)

8-79
8 Referencing a Model

Parameterize Instances of a Reusable Referenced Model

When you reference the same model using multiple Model blocks, you can configure a block
parameter to use either the same value or a different value for each instance of the model. For
example, you can configure the Gain parameter of a Gain block. To use different values, create and
use a model argument to set the value of the block parameter. For some applications, you can reuse a
referenced model only if you can configure each instance to use a different value for a block
parameter (such as the setpoint of a controller or a filter coefficient).

Referenced models that use local solvers do not support model arguments. For more information, see
“Use Local Solvers in Referenced Models” on page 27-5.

Specify a Different Value for Each Instance of a Reusable Model


For a block parameter in a reusable referenced model, to specify a different value for each instance of
the model:

1 Create a MATLAB variable or Simulink.Parameter object in the model workspace of the


referenced model.

• Use a MATLAB variable for ease of maintenance.


• Use a Simulink.Parameter object for greater control over the minimum and maximum
value, the data type, and other properties of the model argument.
2 Set the block parameter value by using the variable or parameter object. Optionally, use the
same variable or object to set other block parameter values.
3 Configure the variable or object as a model argument by selecting the Argument property.
4 Specify a default value for the variable or Simulink.Parameter object. When you simulate this
model directly, the block parameters use the value that the variable or object stores in the model
workspace. When this model is simulated as a referenced model, a parameter configured as a
model argument gets its value from its parent model.

Optionally, you can leave the value for a Simulink.Parameter object empty. See “Define Model
Arguments Without Specifying a Default Value” on page 8-80.
5 In each Model block that refers to the reusable model, specify an instance-specific value for the
block parameter. The dimensions and data type of the instance-specific value must match that of
the model argument definition. If you do not specify a value, the argument uses the last value
specified below it in the model hierarchy. In the top model, you can configure the diagnostic
configuration parameter No explicit final value for model arguments to generate an error or
warning when the topmost Model block that can set the value for a model argument uses this
default value instead of providing an explicit value.
6 In intermediate models, in addition to specifying an instance-specific value for the block
parameter, you can specify if the parameter can be overridden at the next level of the hierarchy.

Define Model Arguments Without Specifying a Default Value


If you use a Simulink.Parameter object to set the block parameter value, you can compile and
simulate the model as a referenced model with the value for the object left empty (Value set to '[]')
as long as you provide an explicit value somewhere in the parent model reference hierarchy. In this
case, you cannot simulate the model directly. When the value is empty, you must provide the Data

8-80
Parameterize Instances of a Reusable Referenced Model

Type and Dimensions for the object. You can also specify the Min, Max, and Complexity properties.
Although you have specified an empty value, Simulink still synthesizes a Value using the properties
you have specified (see Simulink.Parameter).

Combine Multiple Arguments into a Structure


When you configure a model to use multiple model arguments, consider using a structure instead of
separate variables in the model workspace. This technique reduces the effort of maintenance when
you want to add, rename, or delete arguments. Instead of manually synchronizing the arguments in
the model workspace with the argument values in Model blocks, you modify structures by using the
Variable Editor or the command prompt.

If you have a Simulink Coder license, this technique can also reduce the ROM consumed by the
formal parameters of the referenced model functions, such as the output (step) function.

To create and use structures to set block parameter values, see “Organize Related Block Parameter
Definitions in Structures” on page 41-19.

Parameterize a Referenced Model


This example shows how to interactively configure multiple instances of a referenced model to use
different values for the same block parameter. For an example that parameterizes a referenced model
using only the command prompt, see “Parameterize a Referenced Model Programmatically” on page
8-93. For an example that involves code generation, see “Specify Instance-Specific Parameter Values
for Reusable Referenced Model” (Simulink Coder).

Configure Referenced Model to Use Model Arguments

To configure model arguments for a referenced model, you must create MATLAB variables or
Simulink.Parameter objects in the model workspace. This example configures
Simulink.Parameter objects as model arguments without storing a default value in the object and
instead relies on the parent model reference hierarchy to provide explicit values. Without a default
value, the model cannot be simulated directly and must be simulated as referenced model.

Create a model ex_model_arg_ref that contains a Gain block and a Discrete Filter block.

To configure the Gain parameter of the Gain block and the Numerator parameter of the Discrete
Filter block as model arguments:

1 In the model, on the Modeling tab, click Model Data Editor.


2 In the Model Data Editor, select the Parameters tab.

8-81
8 Referencing a Model

3 Use the Value column to set the value of the Gain parameter to a variable, for example,
gainArg.
4
Next to gainArg, click the action button and select Create.
5 In the Create New Data dialog box, set Value to Simulink.Parameter and Location to Model
Workspace. Click Create.
6 In the Simulink.Parameter property dialog box, set Data Type to double and Dimensions to
1. Leave the value empty (Value set to '[]'). Specifying the Min, Max, Complexity values for
the object is optional.
7 To configure the object as a model argument, select Argument.
8 Click OK.
9 Repeat steps 4 through 9 for the Numerator parameter of the Discrete Filter block. In this case,
create a Simulink.Parameter object named coeffArg.

Remember that the model by itself does not compile successfully without values set for the parameter
objects.

Set Model Argument Values in Parent Model

When you simulate a parent model, each instance of a reusable referenced model uses the parameter
values that you specify in the parent model. This example shows how you can expose a model
argument as a tunable parameter on the Model block at each level of the model hierarchy.

Create a model ex_model_arg that uses multiple instances of the reusable model
ex_model_arg_ref from the previous example.

To set instance-specific values for your model arguments in the model reference hierarchy:

1 In the model, on the Modeling tab, click Model Data Editor.


2 In the Model Data Editor, select the Parameters tab. The Model Data Editor shows four rows
that correspond to the instance-specific parameters that you can specify for the two Model
blocks.
3 Use the Model Data Editor to set values for the parameters in Model and Model1. By default, a
model argument uses the last value specified below it in the model hierarchy (indicated by the
value <from below>). Replace the default with the values in this figure.

8-82
Parameterize Instances of a Reusable Referenced Model

4 To override the value of these parameters at the next level of the model hierarchy, select the
check box in the Argument column. By default, the check box is not selected.

You can also configure instance-specific parameters at each Model block. In the block dialog box,
select the Instance parameters tab.

5 Create a model ex_model_arg_top that contains a Model block that references


ex_model_arg.

8-83
8 Referencing a Model

6 In the Model Data Editor, click the Show/refresh additional information button. On the
Parameters tab, you can see each instance-specific parameter that is exposed as a tunable
parameter in the referenced models. From here, you can create a parameter value set for all
instances of the coeffArg and gainArg parameters in the model hierarchy.

By default, each instance uses the last value specified below it in the model hierarchy. In this
case, the Model Data Editor displays <from_below>. If you select the Argument check box to
expose a parameter to a parent model, the Value displays as <inherited> to indicate that the
runtime value now comes from that parent.

After you update the model diagram, the editor also displays the compiled value for the instance.
To navigate to this default value, click the button with the three vertical dots next to the compiled
value and select Navigate to default value from below. The referenced model where
the value was last specified opens in a new tab in the model canvas, and the Model Data Editor
highlights the row that contains the block parameter.

Note You can use a Parameter Writer block to change values of model instance parameters or model
workspace variables during simulation. See “Initialize and Reset Parameter Values” on page 10-226.

Group Multiple Model Arguments into Single Structure

You can use structures to reduce the effort of maintenance when you want to add, rename, or delete
arguments. With structures, the mathematical functionality of the models is the same.

To replace the parameter values with structures for ex_model_arg_ref and ex_model_arg, follow
these steps:

8-84
Parameterize Instances of a Reusable Referenced Model

1 At the command prompt, create a structure. Add one field for each of the parameter objects in
the ex_model_arg_ref workspace.

structForInst1.gain = 3.17;
structForInst1.coeff = 1.05;
2 Store the structure in a Simulink.Parameter object.

structForInst1 = Simulink.Parameter(structForInst1);
3 Open the Model Explorer. In the referenced model, ex_model_arg_ref, on the Modeling tab,
click Model Explorer.
4 Use the Model Explorer to copy the parameter object from the base workspace into the
ex_model_arg_ref model workspace.
5 In the model workspace, rename structForInst1 as structArg.
6 In the Contents pane, configure structArg as the only model argument.

7 In the ex_model_arg_ref model, in the Model Data Editor Parameters tab, set the value of the
Gain parameter to structArg.gain and the value of the Numerator parameter to
structArg.coeff.
8 Save the model.
9 At the command prompt, copy the existing structure in the base workspace as structForInst2.

structForInst2 = copy(structForInst1);
10 Set the field values in the two structures by using the same numbers that you used to set the
model argument values in the Model blocks.

structForInst1.Value.gain = 2.98;
structForInst1.Value.coeff = 0.98;

structForInst2.Value.gain = 3.34;
structForInst2.Value.coeff = 1.11;
11 In the top model, ex_model_arg, use the Model Data Editor to set the argument values as
shown in this figure.

8-85
8 Referencing a Model

Use Bus Object as Data Type of Structures

You can use a Simulink.Bus object as the data type of the structures. The object ensures that the
characteristics of the instance-specific structures, such as the names and order of fields, match the
characteristics of the structure in the model workspace.

1 At the command prompt, use the function Simulink.Bus.createObject to create a


Simulink.Bus object. The hierarchy of elements in the object matches the hierarchy of the
structure fields. The default name of the object is slBus1.

Simulink.Bus.createObject(structForInst1.Value);
2 Rename the bus object as myParamStructType by copying it.

myParamStructType = copy(slBus1);
3 In the Model Data Editor for ex_model_arg, click the Show/refresh additional information
button. The Model Data Editor now contains rows that correspond to the parameter objects in
the base workspace, structForInst1 and structForInst2.
4 Use the Data Type column to set the data type of structForInst1 and structForInst2 to
Bus: myParamStructType.
5 In the Model Data Editor for ex_model_arg_ref, use the Model Data Editor to set the data type
of structArg to Bus: myParamStructType.

Change Model Argument Name or Value


To rename a model argument in the context of the referenced model:

• Find all Model blocks that refer to the model and save the instance-specific parameter values that
each block specifies. Use the get_param function to query the InstanceParameters parameter
of each block, which is a structure array. The structure contains four fields: Name, Value, Path,
and Argument.

You must save the instant-specific parameter values because the renaming operation discards the
values in the Model blocks.
• In the Model Data Editor, right-click the variable or object in the model workspace of the
referenced model and select Rename All. The renaming operation changes the name of the

8-86
Parameterize Instances of a Reusable Referenced Model

variable or object and changes references to it throughout the model. For more information, see
“Create, Edit, and Manage Workspace Variables” on page 73-124.
• Reapply the argument values to the Model blocks by using the new name of the argument. To
programmatically set argument values in a Model block, see “Instance parameters”.

Customize User Interface for Reusable Components


When you design a reusable referenced model for use by other members of a team, you can apply a
mask to the entire referenced model. You can then customize the way that your users interact with
Model blocks, including setting instance-specific values.

Using this technique also makes it easier to programmatically specify instance-specific values. If you
create and use a mask parameter named gainMask to programmatically set the value to 0.98 for an
instance of the model named myModelBlock, your users can use this command at the command
prompt:

set_param('myModelBlock','gainMask','0.98')

If you apply a mask to the referenced model, the model mask shows only the instance-specific
parameters from the direct child model. It does not show instance-specific parameters promoted up
from descendant models.

If you do not mask the model, to set the instance-specific value, use the InstanceParameters
parameter of the block. For more information, see “Parameterize a Referenced Model
Programmatically” on page 8-93.

For information about masking models, see “Introduction to System Mask” on page 43-50.

Configure Instance-Specific Data for Simulink.LookupTable and


Simulink.Breakpoint Objects
When you use Simulink.LookupTable objects to store and configure lookup table data for ASAP2
or AUTOSAR code generation, for example, STD_AXIS or CURVE, you can configure the objects as
model arguments. You can also configure a Simulink.Breakpoint object that is referenced by a
Simulink.LookupTable as a model argument. You can then specify unique table data and
breakpoint data for each instance of a component.

You can specify the instance-specific value of a Simulink.LookupTable argument as a new


Simulink.LookupTable object in the parent model or as a simple MATLAB structure or array.

Specify an instance-specific value for a Simulink.LookupTable object based on the value of the
Breakpoints specification property.

• When the Breakpoints specification property is set to Explicit values or Even spacing,
the instance-specific value of the lookup table object can be:

• A Simulink.LookupTable object
• The name of a valid MATLAB structure variable, such as Model1_LUT2
• A literal structure expression, such as struct(‘Table’, …, ‘BP1’, …, ‘BP2’, …)
• Other expressions that return a valid structure, such as Params.Model1.LUT2 or a call to a
MATLAB function

8-87
8 Referencing a Model

• When the Breakpoints specification property is set to Reference, the instance-specific value of
the Simulink.LookupTable object can be:

• A Simulink.LookupTable object. In this case, Simulink passes only the Table property of
the lookup table object to the child model. This allows you to configure model arguments for
Simulink.LookupTable objects and Simulink.Breakpoint objects independently of each
other and reuse these objects as instance parameters for multiple Model blocks.
• A literal numeric array value, such as [1 5 7; 2 8 13].
• The name of a numeric array variable, such as Model1_LUT2.
• Other expressions that return a valid numeric array, such as Params.Model1.LUT2 or a call
to a MATLAB function.

In this case, if you configure the Simulink.Breakpoint object that is referenced by the
Simulink.LookupTable as a model argument, the instance-specific value for the
Simulink.Breakpoint object can be:

• A Simulink.Breakpoint object.
• An array of numeric values that define the breakpoints. The array must match the design
definition for the breakpoint object. Simulink synthesizes a Simulink.Breakpoint object by
using the values in the array.
• The name of a numeric array variable or a field of a structure.

When you specify the instance-specific value of a Simulink.LookupTable argument as a structure,


these rules apply:

• Each field of the model argument definition must be specified in the structure, and the number of
fields and the names of the fields must match. For example, while only the table data from a
Simulink.LookupTable object of type Reference is passed to the child model, you must still
specify the breakpoint data in your structure or Simulink reports and error.
• The dimensions of the table and the breakpoint data in the structure must match that of the model
argument definition.
• If the data type of a structure field is double, the value is cast to the data type of the
corresponding model argument field. Otherwise, the value must match the data type of the
corresponding model argument field.

You can specify the value of a Simulink.LookupTable object as a simple numeric value for any
simulation mode and for code generation. For code generation, if you configure the model argument
with a storage class of Auto, the structure or numeric array variable is not preserved in the
generated code. If you set the storage class to any other value, the value of the structure or numeric
array is used to initialize the tunable argument in the generated code, similar to other model
arguments.

Specify Instance-Specific Value of Simulink.LookupTable Object

This example shows how to specify the instance-specific value of a Simulink.LookupTable


argument as a new Simulink.LookupTable and as a MATLAB structure.

For an example that parameterizes a referenced model by using lookup tables and the command
prompt, see “Configure Instance-Specific Data for Lookup Tables Programmatically” on page 8-98.

First, create a model that represents a reusable algorithm. Configure a Simulink.LookupTable


object as a model argument to be used by your model.

8-88
Parameterize Instances of a Reusable Referenced Model

1 Create a model ex_arg_LUT_ref, which represents a reusable algorithm.

2 Using the Model Explorer, add a Simulink.LookupTable object in the model workspace. You

can use the Add Simulink LookupTable button . Name the object LUTArg.
3 In the Contents pane, for LUTArg, select the check box in the Argument column.
4 Set Number of table dimensions to 2. In the Table and Breakpoints tabular area, specify
values for the Table, BP1, and BP2 data. For example, configure the table and breakpoint data
by entering these values in the MATLAB expression box.

• Table — [3 4;1 2]
• BP1 — [1 2]
• BP2 — [3 4]

When you simulate or generate code directly from ex_arg_LUT_ref, the model uses these
values.
5 Under Struct Type definition, set Name to LUTArg_Type.
6 Click Apply.
7 In the Contents pane, for LUTArg, select the check box in the Argument column.
8 In the referenced model, in the n-D Lookup Table block, set Data specification to Lookup
table object. Set Name to LUTArg.
9 Save the model.

Next, create a model that uses the reusable algorithm and specify instance-specific values for the
Simulink.LookupTable object.

1 Create a model ex_arg_LUT, which uses the reusable algorithm twice.

8-89
8 Referencing a Model

2 At the command prompt, create a Simulink.LookupTable object in the model workspace.


Alternatively, you can create the Simulink.LookupTable object in a data dictionary or in the
base workspace.

LUTForInst1 = Simulink.LookupTable;
3 Specify breakpoint and table data for the object.

LUTForInst1.Table.Value = [8 7; 6 5];
LUTForInst1.Breakpoints(1).Value = [5 6];
LUTForInst1.Breakpoints(2).Value = [3 4];
4 Specify a structure type name. Match this name to the name specified by the object in the
referenced model workspace.

LUTForInst1.StructTypeInfo.Name = 'LUTArg_Type';
5 Use a structure to create the instance-specific argument value for the second Model block.
Specify the breakpoint and table data for the structure.

StructForInst2.Table = [9 8; 7 7];
StructForInst2.BP1 = [3 4];
StructForInst2.BP2 = [5 6];
6 In the ex_arg_LUT model, for model instance Model, on the Instance parameters tab, set the
value of LUTArg to LUTForInst1.
7 For model instance Model1, set LUTArg to StructForInst2.

One instance of ex_arg_LUT_ref uses the table and breakpoint data stored in the
Simulink.LookupTable object in the model workspace. The other instance uses the table and
breakpoint data stored in the structure.

Specify Instance-Specific Values for Simulink.LookupTable and Simulink.Breakpoint Object

This example shows how to specify an instance-specific value of a Simulink.LookupTable object as


a new Simulink.LookupTable object. The example also shows how to specify an instance-specific
value for a Simulink.Breakpoint object that is referenced by the Simulink.LookupTable
object.

First, create a model that represents a reusable algorithm. Configure both a Simulink.Breakpoint
object and the Simulink.LookupTable object that references the Simulink.Breakpoint object
as model arguments.

1 Create a model ex_arg_BP_ref, which represents a reusable algorithm.

8-90
Parameterize Instances of a Reusable Referenced Model

2 Using the Model Explorer, add a Simulink.LookupTable object in the model workspace. You

can use the Add Simulink LookupTable button . Name the object LUTArg.
3 In the Contents pane, for LUTArg, select the check box in the Argument column.
4 Set Number of table dimensions to 1.
5 Specify the value of the table data as [1 2].
6 Set Breakpoints specification to Reference.
7 In the Breakpoints section, set the Names to BP1.
8 Add a Simulink.Breakpoint object in the model workspace. Name the object BP1 and specify
the value as [3 4].
9 In the Contents pane, for BP1, select the check box in the Argument column.

Next, create a model that uses the reusable algorithm and specify instance-specific values for the
Simulink.LookupTable object and the Simulink.Breakpoint object.

1 Create a model ex_arg_BP, which uses the reusable algorithm twice.

2 At the command prompt, for model instance Model, create a Simulink.LookupTable object
and a Simulink.Breakpoint object in the model workspace. Alternatively, you can create
these objects in a data dictionary or the base workspace.

LUTForInst1 = Simulink.LookupTable;
BPForInst1 = Simulink.Breakpoint;
3 Specify breakpoint and table data for the objects. You must specify breakpoint information for
LUTForInst1 so that the specification of the instance-specific value matches the model
argument specifications. However, only the table data is pushed to the child model.

LUTForInst1.Table.Value = [7 8];
LUTForInst1.BreakpointsSpecification = 'Reference';
LUTForInst1.Breakpoints = {'BPForInst1'};
BPForInst1.Breakpoints.Value = [5 6];
4 In the ex_arg_BP model, for model instance Model, on the Instance parameters tab, set the
value of LUTArg to LUTForInst1 and the value of BP1 to BPForInst1.
5 For model instance Model1, create another Simulink.LookupTable object in the model
workspace and specify the table and breakpoint data. Alternatively, you can create the
Simulink.LookupTable object in a data dictionary or in the base workspace.

LUTForInst2 = Simulink.LookupTable;
BPForInst2 = Simulink.Breakpoint;

8-91
8 Referencing a Model

BPForInst2.Breakpoints.Value = [11 12];


LUTForInst2.Table.Value = [9 10];
LUTForInst2.BreakpointsSpecification = 'Reference';
LUTForInst2.Breakpoints = {'BPForInst2'};
6 For this model instance, use an array to specify the instance-specific value for the
Simulink.Breakpoint object.

BPArrayForInst2 = [11 12];


7 In the ex_arg_BP model, for model instance Model1, on the Instance parameters tab, set the
value of LUTArg to LUTForInst2. For this model instance, set the value of BP1 to the array
BPArrayForInst2.

See Also
Objects
Simulink.Parameter | Simulink.LookupTable | Simulink.Breakpoint

Blocks
Parameter Writer | Initialize Function | Reset Function

Related Examples
• “Parameterize a Referenced Model Programmatically” on page 8-93
• “Configure Instance-Specific Data for Lookup Tables Programmatically” on page 8-98
• “Specify Instance-Specific Parameter Values for Reusable Referenced Model” (Simulink Coder)
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Parameter Interfaces for Reusable Components” on page 41-17
• “Tune and Experiment with Block Parameter Values” on page 41-31

8-92
Parameterize a Referenced Model Programmatically

Parameterize a Referenced Model Programmatically

This example shows how to programmatically configure multiple instances of a referenced model to
use different values for the same block parameter.

Configure Referenced Model to Use Model Arguments

When you simulate a model, the parameter objects in the model workspace use the values that you
specify for the Simulink.Parameter objects, Simulink.LookupTable objects, or MATLAB®
variables. The block parameters also use these values.

To configure the Gain parameter of a Gain block and the Numerator parameter of a Discrete Filter
block as model arguments, follow these steps.

Open model ex_model_arg_ref. This model represents a reusable algorithm.

open_system('ex_model_arg_ref')

For the Gain block, set the value of the Gain parameter to a Simulink.Parameter object in the
model workspace with a numeric value. For this example, name the Simulink.Parameter object
gainArg and assign a value of 3.17.

set_param('ex_model_arg_ref/Gain','Gain','gainArg')
modelWorkspace = get_param('ex_model_arg_ref','ModelWorkspace');
assignin(modelWorkspace,'gainArg',Simulink.Parameter(3.17));

For the Discrete Filter block, set the value of the Numerator parameter to a Simulink.Parameter
object in the model workspace with a numeric value. For this example, name the
Simulink.Parameter object coeffArg and assign a value of 1.05.

set_param('ex_model_arg_ref/Discrete Filter','Numerator','coeffArg')
assignin(modelWorkspace,'coeffArg',Simulink.Parameter(1.05));

Specify gainArg and coeffArg as model arguments.

set_param('ex_model_arg_ref','ParameterArgumentNames','coeffArg,gainArg')

8-93
8 Referencing a Model

Set Model Argument Values in Parent Model

When you simulate a parent model, each instance of a reusable referenced model uses the argument
values that you specify in the parent model. In this example, in the upper instance of
ex_model_arg_ref, the parameter object gainArg uses the value 2.98.

Model ex_model_arg contains two Model blocks that reference ex_model_arg_ref. To set
different parameter values for the two instances of the model, follow these steps.

Open model ex_model_arg. This model represents a system model that uses multiple instances of
the reusable algorithm.

open_system('ex_model_arg')

For both instances of model ex_model_arg, set values for the model arguments. If you decide to re-
promote these arguments, set the Argument field to true. By default, the Argument field is false.

instSpecParams = get_param('ex_model_arg/Model','InstanceParameters');
instSpecParams1 = get_param('ex_model_arg/Model1','InstanceParameters');

instSpecParams(1).Value = '.98';
instSpecParams(2).Value = '2.98';
instSpecParams1(1).Value = '1.11';
instSpecParams1(2).Value = '3.34';
instSpecParams(1).Argument = true;
instSpecParams(2).Argument = true;
instSpecParams1(1).Argument = true;
instSpecParams1(2).Argument = true;

set_param('ex_model_arg/Model','InstanceParameters',instSpecParams);
set_param('ex_model_arg/Model1','InstanceParameters',instSpecParams1);

See Also

More About
• “Group Multiple Model Arguments into a Single Structure” on page 8-95

8-94
Group Multiple Model Arguments into a Single Structure

Group Multiple Model Arguments into a Single Structure

This example shows how to programmatically configure multiple instances of a referenced model to
use different values for the same block parameter by using structures.

Configure Referenced Model to Use Model Arguments Grouped into Structure

You can use structures to reduce the effort of maintenance when you want to add, rename, or delete
arguments. With structures, the mathematical functionality of the models is the same.

To replace the parameter values with structures for ex_model_arg_ref and ex_model_arg, follow
these steps.

Open model ex_model_arg_ref. This model represents a reusable algorithm.

open_system('ex_model_arg_ref')

Create a structure that contains one field for each of the parameter objects that exist in the
ex_model_arg_ref workspace. Specify a value for each field.

structForInst1.gain = 3.17;
structForInst1.coeff = 1.05;

Store the structure in a Simulink.Parameter object.

structForInst1Param = Simulink.Parameter(structForInst1);

Copy the Simulink.Parameter object into the ex_model_arg_ref model workspace. For this
example, name the copy of the object structArg.

modelWorkspace = get_param('ex_model_arg_ref','ModelWorkspace');
assignin(modelWorkspace,'structArg',copy(structForInst1Param));

Configure structArg as the only model argument.

set_param('ex_model_arg_ref','ParameterArgumentNames','structArg')

In the ex_model_arg_ref model, set the Gain parameter of the Gain block to structArg.gain
and set the Numerator parameter of the Discrete Filter block to structArg.coeff.

8-95
8 Referencing a Model

set_param('ex_model_arg_ref/Gain','Gain','structArg.gain')
set_param('ex_model_arg_ref/Discrete Filter',...
'Numerator','structArg.coeff')

Copy the existing structure as structForInst2Param.


structForInst2Param = copy(structForInst1Param);

Set the field values in the two structures to the same numbers that you used to set the model
argument values in the Model blocks.
structForInst1Param.Value.coeff = 0.98;
structForInst1Param.Value.gain = 2.98;
structForInst2Param.Value.coeff = 1.11;
structForInst2Param.Value.gain = 3.34;

Open model ex_model_arg. This model represents a system model that uses multiple instances of
the reusable algorithm.
open_system('ex_model_arg')

For model instance Model, set structArg to structForInst1Param. For model instance Model1,
set structArg to structForInst2Param.
instSpecParamsStruct = get_param('ex_model_arg/Model','InstanceParameters');
instSpecParamsStruct1 = get_param('ex_model_arg/Model1','InstanceParameters');

instSpecParamsStruct(1).Value = 'structForInst1Param';
instSpecParamsStruct1(1).Value = 'structForInst2Param';

set_param('ex_model_arg/Model','InstanceParameters',instSpecParamsStruct);
set_param('ex_model_arg/Model1','InstanceParameters',instSpecParamsStruct1);

Use Bus Object as Data Type of Structures

You can use a Simulink.Bus object as the data type of the structures. The bus object makes sure
that the characteristics of the instance-specific structures, such as the names and order of fields,
match the characteristics of the structure in the model workspace.

To set the data type of the structures to bus objects, follow these steps.

8-96
Group Multiple Model Arguments into a Single Structure

Use the Simulink.Bus.createObject function to create the bus object. The hierarchy of elements
in the object matches the hierarchy of the structure fields. The default name of the object is slBus1.

Simulink.Bus.createObject(structForInst1Param.Value);

Rename the bus object by copying it.

myParamStructType = copy(slBus1);

Set the data type of the parameter objects in the base workspace by using the bus object.

structForInst1Param.DataType = 'Bus: myParamStructType';


structForInst2Param.DataType = 'Bus: myParamStructType';

For the structArg object, set DataType to Bus: myParamStructType.

temp = getVariable(modelWorkspace,'structArg');
temp = copy(temp);
temp.DataType = 'Bus: myParamStructType';
assignin(modelWorkspace,'structArg',copy(temp));
close_system('ex_model_arg_ref',0)
close_system('ex_model_arg',0)

See Also

More About
• “Parameterize a Referenced Model Programmatically” on page 8-93

8-97
8 Referencing a Model

Configure Instance-Specific Data for Lookup Tables


Programmatically

When you use Simulink.LookupTable objects to store and configure lookup table data for ASAP2
or AUTOSAR code generation (for example, STD_AXIS or CURVE), you can configure the objects as
model arguments. You can then specify unique table data and breakpoint data for each instance of a
component.

This example shows how to configure multiple instances of a referenced model to use different values
for the same block parameter by using lookup tables and the command prompt.

Configure Model Arguments in Referenced Model

Open model ex_arg_LUT_ref, which represents a reusable algorithm.

open_system('ex_arg_LUT_ref')

Create a Simulink.LookupTable object in the base workspace. For this example, name the object
LUTArg.

temp = Simulink.LookupTable;

Specify values for the table and breakpoint data. When you simulate or generate code directly from
ex_arg_LUT_ref, the model uses these values.

temp.Table.Value = [3 4; 1 2];
temp.Breakpoints(1).Value = [1 2];
temp.Breakpoints(2).Value = [3 4];

Set the structure name to LUTArg_Type.

temp.StructTypeInfo.Name = 'LUTArg_Type';

Copy the structure to the model workspace.

mdlwks = get_param('ex_arg_LUT_ref','ModelWorkspace');
assignin(mdlwks,'LUTArg',copy(temp))

Specify LUTArg as a model argument.

set_param('ex_arg_LUT_ref','ParameterArgumentNames','LUTArg')

For the n-D Lookup Table block, set 'Data specification' to 'Lookup table object' and set
the name to LUTArg.

8-98
Configure Instance-Specific Data for Lookup Tables Programmatically

set_param('ex_arg_LUT_ref/n-D Lookup Table',...


'DataSpecification','Lookup table object','LookupTableObject','LUTArg')

Create Instance-Specific Argument Values

Open model ex_arg_LUT, which uses the reusable algorithm twice.

open_system('ex_arg_LUT')

Create a Simulink.LookupTable object in the base workspace.

LUTForInst1 = Simulink.LookupTable;

Specify table and breakpoint data for the object.

LUTForInst1.Table.Value = [8 7; 6 5];
LUTForInst1.Breakpoints(1).Value = [5 6];
LUTForInst1.Breakpoints(2).Value = [3 4];

Specify the structure name to match the name specified by the object in the referenced model
workspace.

LUTForInst1.StructTypeInfo.Name = 'LUTArg_Type';

Use a structure to create the instance-specific argument value for the second Model block. Specify
the breakpoint and table data for the structure.

StructForInst2.Table = [9 8; 7 7];
StructForInst2.BP1 = [3 4];
StructForInst2.BP2 = [5 6];

In the ex_arg_LUT model, for model instance Model, set the value of LUTArg to LUTForInst1. For
model instance Model1, set the value of LUTArg to StructForInst2.

instSpecParams = get_param('ex_arg_LUT/Model','InstanceParameters');
instSpecParams(1).Value = 'LUTForInst1';
instSpecParams1 = get_param('ex_arg_LUT/Model1','InstanceParameters');
instSpecParams1(1).Value = 'StructForInst2';
set_param('ex_arg_LUT/Model','InstanceParameters',instSpecParams);
set_param('ex_arg_LUT/Model1','InstanceParameters',instSpecParams1);

8-99
8 Referencing a Model

One instance of ex_arg_LUT_ref uses the table and breakpoint data stored in the
Simulink.LookupTable object in the base workspace and the other instance uses the table and
breakpoint data stored in the structure.

8-100
9

Simulink Units
9 Simulink Units

Unit Specification in Simulink Models

Simulink enables you to specify physical units as attributes on signals at the boundaries of model
components. Such components can be:

• Subsystems
• Referenced Simulink models
• Simulink-PS Converter and PS-Simulink Converter blocks that interface between Simulink and
components developed in Simscape and its associated physical modeling products
• Stateflow charts, state transition tables, or truth tables
• MATLAB Function blocks
• Constant blocks
• Data Store Memory, Data Store Read, and Data Store Write blocks
• C MEX S-Function

By specifying, controlling, and visualizing signal units, you can ensure the consistency of calculations
across the various components of your model. For example, this added degree of consistency
checking is useful if you are integrating many separately developed components into a large, overall
system model.

In Simulink models, you specify units from a unit database. The unit database comprises units from
the following unit systems:

• SI — International System of Units


• SI (extended) — International System of Units (extended)
• English — English System of Units
• CGS — Centimetre-gram-second System of Units

Based on the type of system you are modeling, you can use any combination of units from these
supported unit systems. For more information about supported unit systems and the units they
contain, see Allowed Units.

You can assign units to signals through these blocks:

• Inport
• In Bus Element
• Outport
• Out Bus Element
• Signal Specification
• MATLAB Function
• Chart

You can assign units to signals through these objects:

• Simulink.ValueType
• Simulink.Signal

9-2
Unit Specification in Simulink Models

• Simulink.BusElement
• Simulink.Parameter

When you add a supported block to your model, the Unit parameter on the block is set to inherit
by default. This setting means that the block inherits the unit from a connecting signal that has an
explicitly specified unit.

You can explicitly specify units for signals using the Unit parameter of a supported block. For this
parameter, the dialog box provides matching suggestions to help you:

If you do not provide a correctly formed unit expression, you get an error. Correctly formed unit
expressions are a combination of unit names or symbols with properly balanced parentheses and *, /,
and ^ characters. Special characters such as [, ], {, }, <, >, \, ", &, and so forth are not supported.

By default, a block port has an empty (that is, unspecified) unit and the Unit parameter is set to
inherit. When you specify a unit for one port, Simulink checks the unit setting of any port
connected to it. If a port has an empty unit, you can connect it to another port that has any supported
unit. If a port unit parameter is set to inherit, it inherits the unit from a connected port that has a
specified unit.

To display the units on the Simulink lines in the model, on the Debug tab, click Information
Overlays > Units.

Guidelines for Unitless, Dimensionless, and No Unit Quantities


When dealing with unitless, dimensionless, or no unit quantities, consider these guidelines:

• Pure numbers with no units

9-3
9 Simulink Units

Consider using 1, the SI standard dimensionless unit. Simulink checks the unit to make sure other
dimensionless quantities are propagated in. You can add, multiply, and otherwise manipulate these
types of numbers.
• Unspecified units

Consider using an empty unit, where the Unit parameter is blank. When this parameter is blank,
Simulink accepts any unit that propagates to the port without returning a warning.
• Integer counting number unit

Consider using count to denote an integer counting number unit. Use this unit for quantities that
are difficult to describe, but that are considered unitless or dimensionless, such as thermally
accessible states or PWM count. For more information, see count in Allowed Units.
• Dimensionless physical quantities

Dimensionless physical quantities represent a specific physical quantity. Consider using the
physical quantities velocity_factor, refractive_index, relative_permeability,
strain, Reynolds_number, and logical. Some of these physical quantities, strain and
Reynolds_number, have corresponding units. To specify units for the other physical quantities,
use a format such as 1@physical quantity, for example, 1@refractive_index. Simulink
performs a physical quantity check at propagation. For example, if a model tries to add
dimensional physical quantities, Simulink returns a warning.
• Pure scaled numbers

Consider using ppm, ppb, ppt.

Specify Physical Quantities


When you model a physical system, it is possible to use the same unit expression for two or more
signals that represent different physical quantities. For example, a unit expression of N*m can
represent either torque or energy. To prevent mistaken connection of two ports with the same unit
but representing different physical quantities, you can add a physical quantity to the unit expression.
For example, for the same unit of N*m, you can specify different physical quantities of N*m@torque
and N*m@energy. Similar to units, the dialog box provides suggestions as you type the names of
physical quantities.

Physical quantities help you to enforce an extra degree of unit consistency checking between
connected ports. When you attempt to connect ports with different physical quantities, the model
displays a warning.

Specify Units in Objects


By default, Simulink.ValueType, Simulink.Signal, Simulink.BusElement, and
Simulink.Parameter objects have empty units. In the case of a:

• Simulink.ValueType object, the object does not attach a unit to the corresponding signals.
• Simulink.Signal object, the empty unit means that the corresponding signal can inherit a unit
from an upstream or downstream port.
• Simulink.BusElement object, the empty unit means that the corresponding bus element also
has an empty unit. You can connect the element to a port with any unit, but the element does not
inherit a unit from the port.

9-4
Unit Specification in Simulink Models

• Simulink.Parameter object, the object does not attach a unit to the corresponding parameter
value.

If you specify a unit in a Simulink.ValueType, Simulink.Signal, or Simulink.BusElement


object, Simulink applies the attribute to the corresponding signal line when:

• The Simulink.ValueType object specifies the properties for a signal in the model.
• The Simulink.Signal object resolves to a signal in the model.
• The Simulink.BusElement object is associated with a Simulink.Bus object and you use the
corresponding bus element with a Bus Creator, Bus Selector, or Bus Assignment block that applies
the Simulink.Bus object.

For the Simulink.Parameter object, Simulink does not apply any attribute. For all objects, if the
Unit parameter has a value that is not formed correctly, you see an error. If the unit is formed
correctly but is undefined, you see a warning when you compile the model. If the unit expression
contains special characters such as [, ], {, }, <, >, \, ", &, and so forth, Simulink replaces them with
underscores (_).

Custom Unit Properties

Notes on the Unit and DocUnits properties starting in R2016a:

• The DocUnits property is now Unit for Simulink.Parameter and Simulink.Signal objects.
If, in a previous release, you used the DocUnits parameter of a Simulink.Parameter or
Simulink.Signal object to contain text that does not now comply with units specifications,
simulation returns a warning when the model simulates.

To suppress these warnings, set the configuration parameter Units inconsistency messages to
none. This setting suppresses all units inconsistency check warnings.
• If you have a class that derives from Simulink.Parameter, Simulink.Signal, or
Simulink.BusElement with a previously defined Unit property, Simulink returns an error like
the following:

Cannot define property 'Unit' in class 'classname' because


the property has already been defined in the superclass 'superclass'.

If you use this property to represent the physical unit of the signal, delete the Unit property from
the derived class in the R2016a or later release. Existing scripts continue to work, unless you are
assigning incorrectly formed unit expressions to the Unit field. In this case, replace the use of
Unit with DocUnits to continue to be able to assign the unit expression.

Note If you store existing data in a MAT- or .sldd file, in a release prior to R2016a, copy the
contents of the Unit property to the DocUnits first. Then, save the file in the earlier release
before loading the model in R2016a or later release.

Specify Units for Temperature Signals


When modeling absolute temperature quantities, use units such as K, degC, degF, and degR. When
modeling temperature difference quantities, use units such as deltaK, deltadegC, deltadegF, and
deltadegR. If you connect a signal that has a temperature difference unit to a block that specifies an
absolute temperature unit, Simulink detects the mismatch.

9-5
9 Simulink Units

Specify Units in MATLAB Function Blocks


You specify the units for the inputs and outputs of a MATLAB Function block by specifying the units in
the Unit (e.g., m, m/s^2, N*m) parameter in the Property Inspector. Double-click the MATLAB
Function block to open the MATLAB Function Block Editor. In the Modeling tab, in the Design
section, click Symbols Pane. Right-click the variable name and select Inspect. By default, this
property is inherit, which means that the unit equals the signal sent to the port. If you select the
Data must resolve to signal object property for an output, the signal connected to the output port
determines the port unit and the other properties except for the Name and Scope.

MATLAB Function blocks check if the Simulink signal unit matches the unit assigned to the
corresponding input or output of the block. If the units do not match, Simulink displays a warning
when you update the model. Otherwise, unit settings do not affect MATLAB Function block execution.

Specify Units in Constant Blocks


You can specify units for output data of Constant blocks by using the Unit property in the
Simulink.Parameter object.

Specify Units for Logging and Loading Signal Data


You can include units in signal data that you log or load.

You specify units for logging and loading using Simulink.SimulationData.Unit objects. When
you log using Dataset or Timeseries format, Simulink stores the unit information using
Simulink.SimulationData.Unit objects. If you create MATLAB timeseries data to load, you can
specify Simulink.SimulationData.Unit object for the Units property of the timeseries
object.

For details, see “Load Signal Data That Uses Units” on page 76-76.

Restricting Unit Systems


By default, you can specify units from any of the supported unit systems. However, in large modeling
projects, to enforce consistency, you might want to restrict the unit systems that certain components
of your model can use. To specify available unit systems for a model, in the configuration parameter
Allowed unit systems, enter all or a comma-separated list containing one or more of SI, SI
(extended), CGS, and English. Do not use quotation marks. If your model contains referenced
models, you can use the Allowed unit systems to restrict units in each of those referenced models.
If your model contains subsystems, you can use the Unit System Configuration block to restrict units
in the subsystems. You can also optionally use a Unit System Configuration block in a model. In this
case, the settings in the Unit System Configuration block override whatever you specify in Allowed
unit systems.

To restrict unit systems in a model:

1 In the Unit parameter of the Inport, Outport, or Signal Specification block, click the link.

9-6
Unit Specification in Simulink Models

If a Unit System Configuration block exists in your model, this link opens the block dialog box.
Otherwise, the link opens the Allowed unit systems configuration parameter.
2 Specify one or more the desired unit systems, SI, SI (extended), English, or CGS, in a
comma-delimited list, or all, without quotation marks.

In a parent-child relationship (for example, a top model with a referenced model or subsystem), you
can specify different unit systems for each component. However, if a child propagates a unit into a
parent that is not in the unit systems specified for the parent, you get a warning.

To check whether there are unit mismatches caused by restricted unit systems in your model
hierarchy:

• Press Ctrl+D and visually inspect the model for warning badges.
• Use the Model Advisor check Identify disallowed unit systems.

See Also
Blocks
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element |
Signal Specification | MATLAB Function

Objects
Simulink.ValueType | Simulink.Parameter | Simulink.Signal | Simulink.BusElement

More About
• “Update an Existing Model to Use Units” on page 9-16
• “Displaying Units” on page 9-8
• “Unit Consistency Checking and Propagation” on page 9-10
• “Converting Units” on page 9-14
• “Troubleshooting Units” on page 9-26

9-7
9 Simulink Units

Displaying Units
To display signal units in your model, on the Debug tab, select Information Overlays > Units. To
select this option programmatically, use the command-line property ShowPortUnits.

With this option selected, the model dynamically updates port and signal labels to show any changes
that you make to units. You do not need to press Ctrl+D to update the model. When you simulate
your model, the Scope block displays units for connected signals as y-axis labels.

Note When you explicitly specify units on input or output blocks, block port labels and signal lines
display those units. If a port is set to inherit units or has empty units, port labels and signal lines do
not show labels.

Note With the option to display units cleared, you do not see port and signal labels, even when you
press Ctrl+D to update your model. However, you do see warning or error badges for any unit
inconsistency problems that exist in the model.

You can also see units in the interface view of your model. On the Modeling tab, under Design, click
Model Interface.

9-8
Displaying Units

See Also
Blocks
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element |
Signal Specification | MATLAB Function

Objects
Simulink.ValueType | Simulink.Parameter | Simulink.Signal | Simulink.BusElement

More About
• “Update an Existing Model to Use Units” on page 9-16
• “Unit Specification in Simulink Models” on page 9-2
• “Unit Consistency Checking and Propagation” on page 9-10
• “Converting Units” on page 9-14
• “Troubleshooting Units” on page 9-26

9-9
9 Simulink Units

Unit Consistency Checking and Propagation


Simulink performs unit consistency checking between components. Ports that you connect together —
sometimes via intermediate blocks that propagate units — must have the same units. For example,
you cannot connect a port with unit ft/s to a port with unit m/s^2.

By default, Simulink shows the mismatch warning when it detects a mismatch in units between
two connected ports. You can press Ctrl+D to show mismatched units in your model.

To make this connection valid, you can:

9-10
Unit Consistency Checking and Propagation

• Explicitly set both port units to the same unit.


• Set the Unit parameter of one of the connecting ports to inherit.
• Insert a Unit Conversion block between the mismatched units if they are separated by a scaling
factor or offset, or if they are inverse units. These units are convertible. For more information, see
“Converting Units” on page 9-14.
• Select the Allow automatic unit conversions configuration parameter. For more information,
see “Converting Units” on page 9-14.

Note Simulink supports variations on unit expressions. For example, one port can have a unit of
m/s^2 and a connected port can have a unit of m/s/s. In these cases, Simulink does not display a
warning for mismatched units.

When Simulink detects one of these conditions, it displays the inconsistency warning :

• Disallowed unit system


• Undefined unit

Simulink checks the consistency of unit settings and propagates units across component boundaries.
In a model that contains a referenced model, Simulink compiles the referenced model independently
of the top model. This independent compilation means that the referenced model cannot inherit units
from the top model.

If a port in a referenced model has Unit set to inherit, it can inherit a unit from any upstream or
downstream block in the referenced model. If the port does not inherit a unit from an upstream or
downstream block, you can connect it to a port in the top model with any unit.

Simulink passes units through the following blocks that do not change data, known as
noncomputation blocks:

• Bus Creator
• Bus Selector
• Bus to Vector
• Data Type Conversion
• Demux
• From
• Goto
• Inport
• Merge
• Model
• Mux
• Outport
• Rate Transition
• Signal Conversion
• Signal Specification
• Subsystem

9-11
9 Simulink Units

• Variant Sink
• Variant Source

Note If you supply two or more signals with different units to a Mux block, Simulink applies empty
units to the vector signal that the Mux block outputs. Vector signals must have a common unit.

Note If you have a nonvirtual bus in your model (see “Composite Interface Guidelines” on page 82-
2), Simulink sets the unit of the bus to empty. A nonvirtual bus cannot have a unit. However, if the
bus element signals themselves have units, Simulink does not change these.

Simulink does not propagate units through blocks that produce new data as output. When signals
with units pass through these blocks, the units of these signals become empty. Examples of blocks
that do not preserve units because they produce new data as an output include:

• Sum
• Gain
• Filter
• Product

Unit Consistency Checking and Model Arguments


Simulink checks whether any units for a model argument definition and value are equal. At a
component boundary, Simulink detects and reports a warning when these units are mismatched.

To detect and report warnings for mismatched units, you must set the simulation mode of the Model
blocks to normal mode.

For more information, see “Mismatched Units Detected Between Model Argument Definition and
Value” on page 9-27.

Unit Propagation Between Simulink and Simscape


When modeling physical systems, you might want to integrate components developed in Simulink
with components developed in Simscape and its associated physical modeling products. Simscape
components use physical signals instead of regular Simulink signals. Therefore, you need Simulink-PS
Converter and PS-Simulink Converter converter blocks to connect signals between Simulink and
Simscape components.

To specify units for the input and output signals of your Simscape component, you can explicitly
specify the units on the converter blocks. When you specify units on a PS-Simulink Converter block
that converts a signal from Simscape to Simulink, Simulink propagates the unit settings to the
connected Simulink port. However, Simulink cannot propagate a signal unit from Simulink into your
Simscape component. To do that, you must explicitly specify the unit on the Simulink-PS Converter
block. For more information, see “Physical Units” (Simscape).

9-12
Unit Consistency Checking and Propagation

See Also
Blocks
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element |
Signal Specification | MATLAB Function

Objects
Simulink.ValueType | Simulink.Parameter | Simulink.Signal | Simulink.BusElement

More About
• “Update an Existing Model to Use Units” on page 9-16
• “Unit Specification in Simulink Models” on page 9-2
• “Displaying Units” on page 9-8
• “Converting Units” on page 9-14
• “Troubleshooting Units” on page 9-26

9-13
9 Simulink Units

Converting Units
Simulink can convert units between ports when it detects discrepancies that have known
mathematical relationships such as:

• Scaling factors
• Conversion factors and offsets, such as °F (Fahrenheit) to °C (Celsius)
• Scaled, inverse units, such as mpg (miles per gallon) and L/km (liters per kilometer).

For example, if you connect one port with a unit of cm to one with a unit of mm, Simulink can
automatically scale one unit to work with the other.

To enable Simulink to convert unit mismatches in your model automatically, select the Allow
automatic unit conversions configuration parameter.

• When Simulink successfully converts signal units at a block port, it displays .


• When Simulink detects that an automatic conversion is not possible, it displays .

To manually convert units separated by a conversion factor or offset:

1 Clear the Allow automatic unit conversions configuration parameter.


2 Insert a Unit Conversion block between the ports whose units you want to convert.

Tip Automatic conversion of units is a convenience. For better control of units, when Simulink
detects a mismatch, consider modifying the units specified at one or the other of the two connected
ports.

Automatic Unit Conversion Limitations


Simulink does not support automatic conversion:

• At the root level of models configured for concurrent execution or export-function models. For
more information, see “Configure Your Model for Concurrent Execution” on page 14-20 and
“Export-Function Models Overview” on page 10-125.
• For fixed-point and integer signals.
• At an input port of a Merge block.
• At any port of an asynchronous Rate Transition block.
• At an input port of a function-call subsystem.
• For bus signals.

See Also
Blocks
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element |
Signal Specification | MATLAB Function

Objects
Simulink.ValueType | Simulink.Parameter | Simulink.Signal | Simulink.BusElement

9-14
Converting Units

More About
• “Update an Existing Model to Use Units” on page 9-16
• “Unit Specification in Simulink Models” on page 9-2
• “Displaying Units” on page 9-8
• “Unit Consistency Checking and Propagation” on page 9-10
• “Troubleshooting Units” on page 9-26

9-15
9 Simulink Units

Update an Existing Model to Use Units


This example shows how to add units to an existing model. You see how to:

• Use an incremental workflow to add units to components in your model


• Integrate components that use different unit systems
• Specify units for individual elements of a bus object
• Troubleshoot unit mismatch problems

Model for Updating Units

The model in the example is a fuel control system. The controller (Fuel Rate Controller) and plant
(Engine Gas Dynamics) components of the model are nonvirtual subsystems. Nonvirtual subsystems
have the Treat as atomic unit parameter selected. You introduce units to the plant before introducing
units to the controller and connecting signals. You also specify units for the individual elements of a
bus object in the model.

Open the ex_units_fuelsys model.

model=ex_units_fuelsys;
open_system('ex_units_fuelsys')

Incrementally Work Through the Model to Set Units


Incrementally work through the model to set units.

For the top model, the Allowed unit systems configuration parameter determines the unit systems
the model can use. For each of the plant and controller subsystems, a Unit System Configuration
block determines the allowed unit systems.

9-16
Update an Existing Model to Use Units

Component Allowed Unit Systems


Top model SI
Fuel Rate Controller subsystem all
(controller)
Engine Gas Dynamics subsystem (plant) all

In the plant subsystem, on the Signal Attributes tab of each Inport block dialog box, set the Unit
parameter to a value appropriate for the connected physical signal.

Block Physical Signal Unit Parameter Setting


1 engine speed rad/s (radians per second)
2 throttle angle deg (degrees)
3 fuel rate g/s (grams per second)

To display units on ports and signals in the model, on the Debug tab, select Information Overlays >
Port Units.

In the plant subsystem, you see units on the Inport blocks and connected signals.

Navigate back to the top model. To compile the model, press Ctrl+D, which also performs unit
consistency checking.

The model displays a warning to indicate that there is a disallowed unit for the throttle angle
signal. Clicking the warning icon displays a link to a Model Advisor report that gives you more detail.

The model also displays the warning at the bottom of the model editing window.

9-17
9 Simulink Units

In the plant subsystem, you specified a unit of deg (degrees) for the throttle angle signal.
However, the warning message indicates that degrees are not in the SI unit system. As determined by
the Allowed unit systems configuration parameter, SI is the only unit system that the top model
currently allows. To resolve this warning, you have two options:

• In the plant subsystem, specify a unit for the throttle angle signal that the SI unit system
supports. For more information about supported unit systems and the units they contain, see
Allowed Units.
• In the top model, change the Allowed unit systems configuration parameter to expand the set of
allowed unit systems.

In this case, a unit of deg for the throttle angle signal is appropriate. Instead, to resolve the
warning, expand the set of allowed unit systems for the top model. Set the Allowed unit systems
configuration parameter of the top model to all. To recompile the model, press Ctrl+D.

The top model no longer displays warnings.

Now that you have introduced units to the plant and successfully resolved unit inconsistency
problems, you can add units to the controller. In the Fuel Rate Controller subsystem, set the Unit
parameter of the fuel_rate Outport block to kg/s (kilograms per second).

9-18
Update an Existing Model to Use Units

Navigate back to the top model. To recompile it, press Ctrl+D.

The top model now shows a warning for mismatched units between the controller and plant. To
resolve this error, you can:

• Explicitly insert a Unit Conversion block between the two components.


• Select the Allow automatic unit conversions configuration parameter.

Both options convert units in the same way. A situation in which you might disallow automatic
conversions and insert conversion blocks instead is when you are integrating many components in a
large system model. In that case, manually inserting conversion blocks can give you an added degree
of control of unit conversions in the model. Also, with a conversion block, you can control the data
type of the converted signal. This is useful, for instance, when you are modeling for fixed-point
precision.

In this case, to enable Simulink to resolve the unit mismatch automatically, select Allow automatic
unit conversions. To recompile the model, press Ctrl+D.

9-19
9 Simulink Units

Simulink automatically converts units between the controller and the plant. An automatic conversion
icon replaces the warning.

The top model includes a Simulink.Bus object named EngSensors that passes various sensor
signals as a composite signal to the controller. To use the Type Editor to add units to individual
elements of the bus object:

1 On the Modeling tab, under Design, click Type Editor.


2 Set View to Value.
3 In the interactive table, specify the units.

For the EngSensors bus object, set the Unit parameter of each element.

Signal Unit Parameter Setting


throttle deg (degrees)
speed rad/s (radians per second)

9-20
Update an Existing Model to Use Units

Signal Unit Parameter Setting


ego V (volts)
map bar (bars)

To recompile the model, press Ctrl+D.

The model shows units on the individual elements of the bus object.

You can also see the units in the interface view of your model. On the Modeling tab, under Design,
click Model Interface.

The airflow_calc block of the controller subsystem displays units on the individual elements of the bus
object, both at the component interface and within the component.

After you introduce units incrementally and resolve inconsistency and mismatch issues, you can
simulate the model.

9-21
9 Simulink Units

For the fuel signal that is connected to the scope, the plot window displays the associated units of
kg/s as a y-axis label.

See Also
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element

More About
• “Unit Specification in Simulink Models” on page 9-2
• “Nonvirtual and Virtual Blocks” on page 40-2
• “Displaying Units” on page 9-8
• “Unit Consistency Checking and Propagation” on page 9-10
• “Converting Units” on page 9-14
• “Troubleshooting Units” on page 9-26

9-22
Working with Custom Unit Databases

Working with Custom Unit Databases


In Simulink models, you specify units from a unit database. The unit database comprises units from
the following unit systems:

• SI — International System of Units


• SI (extended) — International System of Units (extended)
• English — English System of Units
• CGS — Centimetre-gram-second System of Units

By default, Simulink supports only the units and unit systems listed in Allowed Units. To introduce
additional units from other unit systems at a system-wide level and use those new units as you would
those listed in Allowed Units, create and load a new unit database with these functions:

• createCustomDBFromExcel — Creates a custom unit database file from an Excel spreadsheet


that contains definitions for the custom unit database. On all supported platforms, the
createCustomDBFromExcel function supports: .xls and .xlsx files.
• rehashUnitDBs — Loads custom unit databases by rehashing unit database files on the MATLAB
path.

Custom Units Spreadsheet Format


Spreadsheets must have these columns in any order:

• name — Unit name, using any graphical Unicode characters except @, *, /, ^, (,), +, \, ", ', {, },
[, ], <, >, &, -, ::, and white space.
• symbol — Symbol of unit, using any graphical Unicode characters except @, *, /, ^, (,), +, \, ",
', {, }, [, ], <, >, &, -, ::, and white space.
• asciiSymbol — Symbol of unit, in ASCII.
• displayName — Name of unit displayed in model in LaTeX format.
• definitionExpression — Definition of the unit in terms of predefined units, such as seven base SI
units.
• conversionFactor — Conversion factor between the unit and its definition.
• conversionOffset — Conversion offset between the unit and its definition.
• physicalQuantity — Valid physical quantities. See table 'Physical Quantities' in showunitslist.
• provenance — Optional column. List of unit provenances, separated by commas.

Follow these guidelines when developing spreadsheets:

• If the input spreadsheet contains more then one worksheet, you must name the worksheets with
the prefixes unit, physicalQuantity, or provenance.
• If there are multiple instances of a prefix in a worksheet, the function uses all of the worksheets to
create the database:

• unit — Creates units


• physicalQuantity — Creates physical quantities
• provenance — Creates provenances

9-23
9 Simulink Units

Optionally, you can define physical quantities in another worksheet of the input spreadsheet. A
worksheet defining physical quantities contains these columns in any order:

• name — Physical quantity name, using any graphical Unicode characters except @, *, /, ^, (,), +,
\, ", ', {, }, [, ], <, >, &, -, ::, and white space.
• definitionExpression — Definition of physical quantity in terms of predefined physical quantities.
• provenance — Optional. List of physical quantity provenances, separated by commas.

Optionally, you can also define provenances in another worksheet of the input spreadsheet. A
worksheet defining provenances contains these columns in any order:

• identifier — Identifier of provenance


• title — Title of provenance
• subTitle — Subtitle of provenance
• organization — Organization of provenance
• fullName — Full name of provenance
• urlList — List of URL links of provenance
• edition — Provenance edition
• year — Provenance year

Define Custom Units in Excel Spreadsheet


First, create an Excel spreadsheet following the guidelines in “Custom Units Spreadsheet Format” on
page 9-23. Use unit definitions, one per row, such as:

Save this spreadsheet in a file such as unitsDB.xlsx. You can then create the database and load it.

Create and Load Custom Unit Database

This example shows how to create a custom units database and then load it.

Create the database using the spreadsheet included in this example.

createCustomDBFromExcel('unitsDB.xlsx')

The function creates unitsDB.slunitdb.mldatx in the current folder.

Load the new units database into memory.

rehashUnitDBs

To verify that the new database has been loaded, open the slex_customunits model and apply
custom units on any of the output ports:

9-24
Working with Custom Unit Databases

slex_customunits

See Also
Functions
createCustomDBFromExcel | rehashUnitDBs | showunitslist

Blocks
Unit System Configuration | Unit Conversion

More About
• “Unit Specification in Simulink Models” on page 9-2
• “Nonvirtual and Virtual Blocks” on page 40-2
• “Displaying Units” on page 9-8
• “Unit Consistency Checking and Propagation” on page 9-10
• “Converting Units” on page 9-14
• “Troubleshooting Units” on page 9-26

9-25
9 Simulink Units

Troubleshooting Units
In this section...
“Undefined Units” on page 9-26
“Overflow and Underflow Errors or Warning” on page 9-26
“Mismatched Units Detected” on page 9-26
“Mismatched Units Detected Between Model Argument Definition and Value” on page 9-27
“Mismatched Units Detected While Loading” on page 9-27
“Disallowed Unit Systems” on page 9-27
“Automatic Unit Conversions” on page 9-27
“Unsuccessful Automatic Unit Conversions” on page 9-27
“Simscape Unit Specification Incompatible with Simulink” on page 9-27

To help you troubleshoot issues with unit settings, Simulink uses Model Advisor checks to generate a
report useful for larger models.

By default, Simulink flags unit usage issues, such as mismatched units, with warnings. Warnings
enable you to continue working despite mismatched units. You can reduce the number of warnings
you see by setting the configuration parameter Units inconsistency messages to none.

Undefined Units

Simulink does not support custom unit specifications. For more information about supported unit
systems and the units they contain, see Allowed Units.

The Model Advisor check “Identify undefined units in the model” identifies undefined units.

Overflow and Underflow Errors or Warning


You can get overflow and underflow errors or warnings when using the Unit Conversion block. If you
get:

• Overflow messages, change the data type at the output port to one with a better range
• Underflow messages, change the data type at the output port to one with better precision

Mismatched Units Detected

At the boundary of a component, Simulink detects if the units of two ports do not match. To see the
tooltip, hover over the warning badge. If the unit is convertible, Simulink displays advice on fixing the
issue.

The Model Advisor check “Identify unit mismatches in the model” identifies mismatched units.

9-26
Troubleshooting Units

Mismatched Units Detected Between Model Argument Definition and


Value
At a component boundary, Simulink detects and reports a warning when these units are mismatched.

To detect and report warnings for mismatched units, you must set the simulation mode of the Model
blocks to normal mode.

The Model Advisor check “Identify unit mismatches in the model” identifies mismatched units.

Mismatched Units Detected While Loading

At the boundary of a component, Simulink detects if the units of two ports do not match. To see the
tooltip, hover the warning badge. When possible, Simulink displays advice on fixing the issue.

The Model Advisor check “Identify unit mismatches in the model” identifies mismatched units.

Disallowed Unit Systems

Simulink supports only the unit systems listed in the tables of allowed units.

The Model Advisor check “Identify disallowed unit systems in the model” identifies unit systems that
are not allowed in the configured units systems.

Automatic Unit Conversions

If the Allow automatic unit conversions configuration parameter is set, Simulink supports the
automatic conversion of units. Simulink flags automatically converted units with the badge.

For a list of the automatic unit conversions, use the Model Advisor check “Identify automatic unit
conversions in the model”.

Unsuccessful Automatic Unit Conversions

If the Allow automatic unit conversions configuration parameter is set, Simulink supports the
automatic conversion of units. If Simulink cannot perform the automatic unit conversion, Simulink
returns a warning ( ). In such cases, consider manually specifying the unit.

Tip Automatic unit conversion is a convenience. For better control of units, you can manually set the
units for two connecting ports.

Simscape Unit Specification Incompatible with Simulink

9-27
9 Simulink Units

If these are true:

• You define a new unit to your unit registry by using the pm_addunit function.
• You use the new unit with the Simulink-PS Converter or PS-Simulink Converter block.
• Your new unit conflicts with an existing one in the Simulink database.

Simulink returns a warning about a potential incorrect calculation ( ).

See Also
Blocks
Unit Conversion | Unit System Configuration | Inport | In Bus Element | Outport | Out Bus Element |
Signal Specification | MATLAB Function

Functions
showunitslist | createCustomDBFromExcel | rehashUnitDBs

Objects
Simulink.ValueType | Simulink.Parameter | Simulink.Signal | Simulink.BusElement

More About
• “Unit Specification in Simulink Models” on page 9-2
• “Displaying Units” on page 9-8
• “Unit Consistency Checking and Propagation” on page 9-10
• “Converting Units” on page 9-14

9-28
10

Conditional Subsystems

• “Conditionally Executed Subsystems Overview” on page 10-3


• “Ensure Output Port Is Virtual” on page 10-5
• “Using Enabled Subsystems” on page 10-12
• “Using Triggered Subsystems” on page 10-18
• “Using Enabled and Triggered Subsystems” on page 10-21
• “Select Subsystem Execution” on page 10-25
• “Iterate Subsystem Execution with While Iterator and For Iterator Subsystems” on page 10-29
• “Repeat an Algorithm Using a For-Each Subsystem” on page 10-34
• “Using Function-Call Subsystems” on page 10-53
• “Conditional Subsystem Initial Output Values” on page 10-57
• “Schedule Components to Avoid Data Dependency Issues” on page 10-59
• “Create Rate-Based Model” on page 10-60
• “Test Rate-Based Model Simulation Using Function-Call Generators” on page 10-62
• “Generate Code from Rate-Based Model” on page 10-65
• “Sorting Rules for Explicitly Scheduled Model Components” on page 10-68
• “Conditional Subsystem Output Values When Disabled” on page 10-75
• “Simplified Initialization Mode” on page 10-76
• “Classic Initialization Mode” on page 10-78
• “Convert from Classic to Simplified Initialization Mode” on page 10-97
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114
• “Generate Code for Export-Function Model” on page 10-118
• “Generate Code for Export-Function Model with Rate-Based Model” on page 10-121
• “Export-Function Models Overview” on page 10-125
• “Using Resettable Subsystems” on page 10-137
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151
• “Call a Simulink Function from a Model” on page 10-159
• “Argument Specification for Simulink Function Blocks” on page 10-168
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
10 Conditional Subsystems

• “Scoped Simulink Function Blocks in Models” on page 10-188


• “Model Client-Server Communication Using Function Ports” on page 10-195
• “Define Diagnostic Services Using Simulink Functions” on page 10-200
• “Resolve Error: Block Is Unable to Call The Scoped Simulink Function” on page 10-204
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Initialize and Reset Parameter Values” on page 10-226
• “Initialize, Reinitialize, Reset, and Terminate Function Limitations” on page 10-232
• “Reinitialize States of Blocks in Subsystem” on page 10-235
• “Common Uses of the Initialize Function Block” on page 10-238
• “Model House Heating System” on page 10-251
• “Wireless Tire Pressure Monitoring System with Fault Logging” on page 10-284
• “Prepare Sensor and Controller Models in a Distributed Monitoring System for Code Generation”
on page 10-289
• “Fixed-Point Data Type Support for If Block” on page 10-293

10-2
Conditionally Executed Subsystems Overview

Conditionally Executed Subsystems Overview


A conditionally executed subsystem is a nonvirtual subsystem that allows you to control its execution
with an external signal. The external signal, called the control signal, is attached to the control input
port. Conditional subsystems are useful when you create complex models that contain components
whose execution depends on other components.

Simulink supports these types of conditional subsystems:

• Enabled Subsystem — Executes at each time step while the control signal is positive. Execution
starts at the time step when the control signal crosses zero from the negative to the positive
direction. See “Using Enabled Subsystems” on page 10-12.
• Triggered Subsystem — Executes at each time step when the control signal rises or falls to zero or
crosses zero. See “Using Triggered Subsystems” on page 10-18.
• Enabled and Triggered Subsystem — Executes at the time step when the enable control signal has
a positive value and the trigger control signal rises or falls to zero. See “Using Enabled and
Triggered Subsystems” on page 10-21.
• Message Triggered Subsystem — Uses messages as a control signal, and executes whenever a
message is available at the control port, independent of the block sample time. See “Using
Message Polling and Message Triggered Subsystems” on page 11-87.
• Message Polling Subsystem — Uses messages as a control signal, and executes at each time step
when a message is available at the control port. See “Using Message Polling and Message
Triggered Subsystems” on page 11-87.
• Function-Call Subsystem — Executes when the control signal receives a function-call event.
Events can occur one or more time during a time step. A Stateflow chart, Function-Call Generator
block, S-Function block, or Hit Crossing block can provide function-call events. See “Using
Function-Call Subsystems” on page 10-53.

A conditionally executed subsystem or conditionally executed referenced model runs:

• Once at the current time step when enabled by a control block. A control block implements control
logic similar to that expressed by a programming language statement such as if-then-else or
switch.
• Once at the current time step when enabled or triggered by a control signal or an action signal.
• One or more times during a time step when receiving a function-call event.

10-3
10 Conditional Subsystems

For example models, see “Simulink Subsystem Semantics”.

See Also
Enabled Subsystem | Triggered Subsystem | Enabled and Triggered Subsystem | Message Triggered
Subsystem | Function-Call Subsystem

Related Examples
• “Using Enabled Subsystems” on page 10-12
• “Using Triggered Subsystems” on page 10-18
• “Using Enabled and Triggered Subsystems” on page 10-21
• “Using Message Polling and Message Triggered Subsystems” on page 11-87
• “Using Function-Call Subsystems” on page 10-53
• “Conditional Subsystem Initial Output Values” on page 10-57
• “Conditional Subsystem Output Values When Disabled” on page 10-75

10-4
Ensure Output Port Is Virtual

Ensure Output Port Is Virtual


The software may add a hidden signal buffer before an Outport block in a conditional subsystem or
before an Outport block at the top level of a model. In effect, the buffer is a Signal Copy block that
does not appear on the canvas. This buffer ensures consistent initialization of the Outport block
signal.

When a Merge block receives conditional output signals or partial-write signals as input, the hidden
signal buffer might affect simulation results. To prevent the software from adding the buffer, select
the Ensure outport is virtual block parameter of the related Outport block.

Merged Conditional Output Signals

This example shows the effect of a hidden buffer that might be added between a conditional
subsystem and an Outport block when the Ensure outport is virtual parameter of the Outport block
is cleared.

Open the example model ex_conditional_write.

The Merge block combines its inputs into a signal whose value at any time is equal to the most
recently computed output of its driving blocks.

The conditional subsystem named Enabled Subsystem A contains a conditional subsystem named
Enabled Subsystem C that connects to an Outport block.

10-5
10 Conditional Subsystems

By default, the Ensure outport is virtual parameter of an Outport block is cleared. When the
Ensure outport is virtual parameter of an Outport block is cleared:

• The Outport block follows nonvirtual semantics.


• The software might insert a hidden buffer to provide consistent initialization of the Outport block
signal.

For most Outport blocks that connect to conditional subsystems, keep the Ensure outport is virtual
parameter cleared.

Simulation with Hidden Buffer

In the example model, check that the Ensure outport is virtual parameter is cleared for the Outport
block that connects to Enabled Subsystem C.

The software inserts a hidden buffer in Enabled Subsystem A between Enabled Subsystem C
and the Outport block.

Simulation with a fixed-step solver produces these results.

10-6
Ensure Output Port Is Virtual

• Time 0: Enabled Subsystem A runs, but Enabled Subsystem C does not run. The buffer in
Enabled Subsystem A runs and copies the initial value of zero to the Outport block. Enabled
Subsystem B does not run. The merged signal is zero from the output of Enabled Subsystem
A.
• Time 0.5: Enabled Subsystem A does not run. Enabled Subsystem B runs and outputs a sine
wave. The merged signal is the sine wave from Enabled Subsystem B.
• Time 1: Enabled Subsystem A runs, but Enabled Subsystem C does not run. Again, the
buffer in Enabled Subsystem A runs and copies the initial value of zero to the Outport block.
Enabled Subsystem B does not run. The merged signal is the initial value from Enabled
Subsystem A, not the last value from Enabled Subsystem B.

Simulation Without Hidden Buffer

Select the Ensure outport is virtual parameter of the Outport block that connects to Enabled
Subsystem C.

When you select the Ensure outport is virtual parameter:

• The Outport block follows virtual semantics.


• The software does not insert a hidden buffer. If simulation needs a buffer before the Outport block,
you receive an error.

Simulation with a fixed-step solver produces these results.

10-7
10 Conditional Subsystems

• Time 0: Enabled Subsystem A runs, but Enabled Subsystem C does not run. Enabled
Subsystem B does not run. The merged signal is the initial value of the signal.
• Time 0.5: Enabled Subsystem A does not run. Enabled Subsystem B runs and outputs a sine
wave. The merged signal is the value of the sine wave from Enabled Subsystem B.
• Time 1: Enabled Subsystem A runs, but Enabled Subsystem C does not run. Enabled
Subsystem B does not run. The merged signal is the most recently computed output, which is the
sine wave from Enabled Subsystem B.

Merged Partial-Write Signals

Suppose you want to initialize a vector and periodically update partial elements of the signal based
on certain conditions or inputs. You can use a Merge block whose inputs are from two Function-Call
Subsystem blocks. One subsystem provides the initialize task while the other subsystem provides a
periodic-write task.

Open the example model ex_partial_write_single_merge.

10-8
Ensure Output Port Is Virtual

The function-call subsystem named Initialize_Process_Subsystem is called once at the


beginning of a simulation to initialize a vector.

The function-call subsystem named Run_Process_Subsystem is called to partially write to elements


of the vector.

10-9
10 Conditional Subsystems

In Run_Process_Subsystem, the output from the Assignment block needs a path where a hidden
buffer does not make copies of the vector. To remove a hidden buffer, select the Ensure outport is
virtual parameter of the Outport block. If the software determines the buffer is needed, you receive
an error.

The Initialize_Process_SubSystem:

• Initializes each element of a 2 element vector with a value of 7.


• Outputs the vector [7 7].

The Run_Process_Subsystem:

• Inputs an index value of 1, but because the Index mode parameters of the Selector blocks is set
to Zero-based, the Selector blocks select the second elements from the input vectors.
• Adds the output scalar values from the Selector blocks for a result of 4.
• Requires an output signal that is a vector with length 2 because the Assignment block Index
mode parameter is set to Zero-based and the input index Idx1 is 1. After setting the Output
size parameter to 2, the Assignment block is able to write to the second element.
• Selects the Ensure outport is virtual parameter of the Outport block to remove the hidden
buffer.

The Merge block outputs the vector [7 4].

Code generated from this model includes two functions, Init_Proc and Run_Proc.
/* Model step function */
void Init_Proc(void)
{
int32_T s3_iter;

/* Initialize signal vector elements with 7.0 */


for (s3_iter = 0; s3_iter < 2; s3_iter++) {
PartialWriteSingleMerge_DW.Assignment[s3_iter] = 7.0;
}

for (s3_iter = 0; s3_iter < 2; s3_iter++) {


PartialWriteSingleMerge_Y.Out4[s3_iter] =
PartialWriteSingleMerge_DW.Assignment[s3_iter];
}
}

10-10
Ensure Output Port Is Virtual

/* Model step function */


void Run_Proc(void)
{
/* Write to element 1 of the output signal vector */
PartialWriteSingleMerge_Y.Out4[1] = 4.0;
}

See Also
Merge | Outport

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Conditionally Execute Referenced Models” on page 8-28

10-11
10 Conditional Subsystems

Using Enabled Subsystems


An enabled subsystem is a conditionally executed subsystem that runs once at each major time step
while the control signal has a positive value. If the signal crosses zero during a minor time step, the
subsystem is not enabled or disabled until the next major time step.

The control signal can be either a scalar or a vector.

• If a scalar value is greater than zero, the subsystem executes.


• If any one of the vector element values is greater than zero, the subsystem executes.

Create an Enabled Subsystem


To create an enabled subsystem:

1 Add an Enabled Subsystem block to your model.

• Copy a block from the Simulink Ports & Subsystems library to your model.
• Click the model diagram, start typing enabled, and then select Enabled Subsystem.

2 Set initial and disabled values for the Outport blocks. See “Conditional Subsystem Initial Output
Values” on page 10-57 and “Conditional Subsystem Output Values When Disabled” on page 10-
75.

10-12
Using Enabled Subsystems

3 Specify how subsystem states are handled when the subsystem is enabled.

Open the subsystem block, and then open the parameter dialog box for the Enable port block.
From the States when enabling drop-down list, select:

• held — States maintain their most recent values.


• reset — If the subsystem is disabled for at least one time step, states revert to their initial
conditions.

Note If the subsystem contains a Stateflow chart that contains a Simulink Function block,
blocks inside the Simulink Function block do not revert to their initial conditions. For a more
generic reinitialize functionality, consider using the Reinitialize Function block.

In simplified initialization mode (default), the subsystem elapsed time is always reset during
the first execution after becoming enabled. This reset happens regardless of whether the
subsystem is configured to reset on being enabled. See Underspecified initialization detection.

For nested subsystems whose Enable blocks have different parameter settings, the settings for
the child subsystem override the settings inherited from the parent subsystem.
4 Output the control signal from the Enable block.

In the parameter dialog box for the Enable Block, select the Show output port check box.

Selecting this parameter allows you to pass the control signal into the enabled subsystem. You
can use this signal with an algorithm that depends on the value of the control signal.

Blocks in Enabled Subsystems


Discrete Blocks

Discrete blocks in an enabled subsystem execute only when the subsystem executes, and only when
their sample times are synchronized with the simulation sample time.

Consider this model, which contains four discrete blocks and a control signal. The discrete blocks
are:

• Block A, with the sample time of 0.25 seconds


• Block B, with the sample time of 0.5 seconds

Signal E is the enable control signal generated by a Pulse Generator with a sample time of 0.125. Its
output changes value from 0 to 1 at 0.375 seconds and returns to 0 at 0.875 seconds.

10-13
10 Conditional Subsystems

The discrete blocks in the enabled subsystem are:

• Block C, within the enabled subsystem, with the sample time of 0.125 seconds
• Block D, also within the enabled subsystem, with the sample time of 0.25 seconds

Discrete blocks execute at sample times shown.

10-14
Using Enabled Subsystems

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 becomes positive, blocks C and D execute at their
assigned sample rates until the enable control signal becomes zero again. Block C does not execute at
0.875 seconds when the enable control signal changes to zero.

Goto Blocks

Enabled subsystems can contain Goto blocks. However, only output ports for blocks with state can
connect to Goto blocks. For an example of using Goto blocks in an enabled subsystem, see the
Locked subsystem in the sldemo_clutch model.

Alternately Executing Enabled Subsystem Blocks

You can use conditional subsystems with Merge blocks to create sets of subsystems that execute
alternately, depending on the current state of the model.

Consider a model that uses two Enabled Subsystem blocks and a Merge block to model a full-wave
rectifier, which is a device that converts AC current to pulsating DC current.

Open the example model ex_alternately_executing_model.

10-15
10 Conditional Subsystems

Open the subsystem named pos.

This subsystem is enabled when the AC waveform is positive and passes the waveform unchanged to
its output.

Open the subsystem named neg.

This subsystem is enabled when the waveform is negative and inverts the waveform.

The Merge block passes the output of the currently enabled subsystem along with the original
waveform to the Scope block.

Simulate the model. Then, open the Scope block.

10-16
Using Enabled Subsystems

Model Examples
For model examples, see:

• “Simulink Subsystem Semantics”


• “Building a Clutch Lock-Up Model”
• “Enabled Subsystems”
• “Advanced Enabled Subsystems”

See Also
Enabled Subsystem | Triggered Subsystem | Enabled and Triggered Subsystem | Function-Call
Subsystem

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Using Triggered Subsystems” on page 10-18
• “Using Enabled and Triggered Subsystems” on page 10-21
• “Using Function-Call Subsystems” on page 10-53
• “Conditional Subsystem Initial Output Values” on page 10-57
• “Conditional Subsystem Output Values When Disabled” on page 10-75
• “Comparison of Resettable Subsystems and Enabled Subsystems” on page 10-139

10-17
10 Conditional Subsystems

Using Triggered Subsystems


A triggered subsystem is a conditionally executed atomic subsystem that runs each time the control
signal (trigger signal):

• Either rises from a negative value to a positive value or zero, or rises from a zero value to a
positive value.
• Either falls from a positive value to a negative value or zero, or falls from a zero value to a
negative value.
• Rises or falls through or to a zero value.

Unlike an Enabled Subsystem block, a Triggered Subsystem block always holds its outputs at the last
value between triggers. Also, triggered subsystems cannot reset block states when executed; the
states of any discrete block are held between triggers.

Create a Triggered Subsystem


To create a triggered subsystem:
1 Add a Triggered Subsystem block to your model.

• Copy a block from the Simulink Ports & Subsystems library to your model.
• Click the model diagram, start typing trigger, and then select Triggered Subsystem.

10-18
Using Triggered Subsystems

2 Set initial and disabled values for the Outport blocks. See “Conditional Subsystem Initial Output
Values” on page 10-57 and “Conditional Subsystem Output Values When Disabled” on page 10-
75.
3 Set how the control signal triggers execution.

Open the subsystem block, and then open the parameter dialog box for the Trigger port block.
From the Trigger type drop-down list, select:

• rising — Trigger execution of the subsystem when the control signal rises from a negative
or zero value to a positive value.
• falling — Trigger execution of the subsystem when the control signal falls from a positive
or zero value to a negative value.
• either — Trigger execution of the subsystem with either a rising or falling control signal.

Different symbols appear on the Trigger and Subsystem blocks to indicate rising and falling
triggers.

4 Output the enable control signal from the Trigger port block. Open the Trigger port block. Select
the Show output port check box to pass the control signal into the triggered subsystem.

You can use this signal with an algorithm that depends on the value of the control signal.
5 From the Output data type drop-down list, select 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 block port connected to the signal.

Triggering with Discrete Time Systems


For a discrete time system, the trigger control signal must remain at zero for more than one time
step. This triggering strategy eliminates false triggers caused by control signal sampling.

In the following timing diagram for a discrete system, a rising trigger signal (R) does not occur at
time step 3. The trigger signal remains at zero for only one time step before the signal increases from
zero.

10-19
10 Conditional Subsystems

Triggered Model Versus a Triggered Subsystem


You can place a Trigger port block in a Model block (referenced model) to simplify your model design
instead of using one of these blocks:

• A Triggered Subsystem block in a Model block.


• A Model block in a Triggered Subsystem block.

For information about using Trigger port blocks in referenced models, see “Conditionally Execute
Referenced Models” on page 8-28.

To convert a subsystem to use model referencing, see “Convert Subsystems to Referenced Models” on
page 8-23.

Blocks in a Triggered Subsystem


All blocks in a triggered subsystem must have Sample time set to inherited (-1) or constant (inf).
This requirement allows the blocks in a triggered subsystem to run only when the triggered
subsystem itself runs. This requirement also means that a triggered subsystem cannot contain
continuous blocks, such as an Integrator block.

Model Examples
For model examples, see:

• “Simulink Subsystem Semantics”


• “Triggered Subsystems”
• “Model Engine Timing Using Triggered Subsystems”

See Also
Enabled Subsystem | Triggered Subsystem | Enabled and Triggered Subsystem | Function-Call
Subsystem

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Using Enabled Subsystems” on page 10-12
• “Using Enabled and Triggered Subsystems” on page 10-21
• “Using Function-Call Subsystems” on page 10-53
• “Conditional Subsystem Initial Output Values” on page 10-57
• “Conditional Subsystem Output Values When Disabled” on page 10-75

10-20
Using Enabled and Triggered Subsystems

Using Enabled and Triggered Subsystems


An Enabled and Triggered Subsystem is a conditionally executed subsystem that runs once at each
simulation time step when both these conditions apply:

• Enabled control signal has a positive value.


• Trigger control signal rises or falls through zero.

An Enabled and Triggered Subsystem block contains both an Enable port block and a Trigger port
block. When a trigger signal rises or falls through zero, the enable input port is checked to evaluate
the enable control signal. If its value is greater than zero, the subsystem is executed. When both
inputs are vectors, the subsystem executes if at least one element of each vector is nonzero.

10-21
10 Conditional Subsystems

Creating an Enabled and Triggered Subsystem


To create an enabled and triggered subsystem:

1 Add an Enabled and Triggered Subsystem block to your model.

• Copy a block from the Simulink Ports & Subsystems library to your model.
• Click the model diagram, start typing enabled, and then select Enabled and Triggered
Subsystem.

2 Set initial and disabled values for the Outport blocks. See “Conditional Subsystem Initial Output
Values” on page 10-57 and “Conditional Subsystem Output Values When Disabled” on page 10-
75.
3 Set how the control signal triggers execution.

Open the subsystem block, and then open the block parameters dialog box for the Trigger port
block. From the Trigger type drop-down list, select:

• rising — Trigger execution of the subsystem when the control signal rises from a negative
or zero value to a positive value.
• falling — Trigger execution of the subsystem when the control signal falls from a positive
or zero value to a negative value.
• either — Trigger execution of the subsystem with either a rising or falling control signal.

Different symbols appear on the Trigger and Subsystem blocks to indicate rising and falling
triggers.

10-22
Using Enabled and Triggered Subsystems

4 Specify how subsystem states are handled when enabled.

Open the subsystem, and then open the Enable port block. From the States when enabling
drop-down list, select:

• held — States maintain their most recent values.


• reset — States revert to their initial conditions if the subsystem is disabled for at least one
time step.

In simplified initialization mode, the subsystem elapsed time is always reset during the first
execution after becoming enabled. This reset happens regardless of whether the subsystem is
configured to reset when enabled. See Underspecified initialization detection.

For nested subsystems whose Enable blocks have different parameter settings, the settings for
the child subsystem override the settings inherited from the parent subsystem.

Blocks in an Enabled and Triggered Subsystem


All blocks in an enabled and triggered subsystem must have Sample time set to inherited (-1 or
constant (inf). This requirement allows the blocks in a triggered subsystem to run only when the
triggered subsystem itself runs. This requirement also means that a triggered subsystem cannot
contain continuous blocks, such as an Integrator block.

Model Examples
For model examples, see:

• “Simulink Subsystem Semantics”


• “Enabled Subsystems”

See Also
Enabled Subsystem | Triggered Subsystem | Enabled and Triggered Subsystem | Function-Call
Subsystem

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Using Enabled Subsystems” on page 10-12
• “Using Triggered Subsystems” on page 10-18
• “Using Function-Call Subsystems” on page 10-53
• “Conditional Subsystem Initial Output Values” on page 10-57

10-23
10 Conditional Subsystems

• “Conditional Subsystem Output Values When Disabled” on page 10-75

10-24
Select Subsystem Execution

Select Subsystem Execution


A logically executed subsystem block runs one or more times at the current time step when enabled
by a control block. A control block implements control logic similar to that expressed by a
programming language statement (e.g., if-then, switch, while, for).

Selector subsystems are one type of logically executed subsystem that execute once during a time
step in response to an action signal from a control block located external to the subsystem. Simulink
supports two selector subsystem structures, if-else and switch-case.

Models with If-Else Structures


The If Action Subsystem block is a Subsystem block preconfigured as a starting point for creating a
subsystem whose execution is enabled by an If block.

An external If block controls execution. The If block evaluates a logical expression and then,
depending on the result of the evaluation, outputs an action signal to an If Action Subsystem block.

Merge Signals from If Action Subsystem Blocks

The example model ex_if_block shows how to merge signals controlled by an If block.

The If block selects the execution of an If Action Subsystem block from a set of subsystems.
Regardless of which subsystem the If block selects, you can create one output signal with a Merge
block.

All blocks in an If Action Subsystem block must execute at the same rate as the driving If block. To
satisfy this requirement, set the sample time parameter for each block to either inherited (-1) or the
same value as the If block sample time.

The inputs to the If block provide the operand values for the logical expressions represented as
output ports. Each output port is attached to an If Action Subsystem block. The expressions in the If

10-25
10 Conditional Subsystems

block are evaluated top down starting with the if expression. When an expression evaluates to true,
its corresponding If Action Subsystem is executed, and the remaining expressions are not evaluated.

The if-else structure in the model can be represented with this pseudo code.

IF u1 > 0 THEN
Subsystem 1
ELSEIF u2 > 0
Subsystem 2
ELSE
Subsystem 3
END IF

Create Model with If-Else Structure

To create the example model, use this procedure.

1 Place an If block in the Simulink Editor. Double-click the block to open the block parameters
dialog box.
2 In the Number of inputs box, enter 2.

Two input ports are added to the block. The inputs ports are for signals containing operand
values, not necessary the number of operands. An input signal can be a vector. For example, you
could specify the fifth element of a vector u in an expression as u(5) > 0.
3 In the If expression text box, enter u1 > 0.

An output port is added to the block with the label if(u1 > 0). This port is the only required
output for an If block.
4 In the Elseif expressions text box, enter u2 > 0.

You can enter multiple elseif expressions with a comma separating the expressions. Each
expression adds an output port to the If block with a label of the form elseif(expression).
5 Check the Show else condition check box.

An output port is added to the block with the label else.


6 Add three If Action Subsystem blocks.

These blocks are Subsystem blocks with an Action Port block. When you place an Action Port
block inside a subsystem, an input port named Action is added to the block.
7 Connect each output port from the If block to the action port of an If Action Subsystem block.

When you make the connection, the icon for the If Action Subsystem block is renamed to the type
of expression that attached to it.
8 In each If Action Subsystem block, enter the Simulink blocks to be executed for the condition it
handles.
9 Connect outputs from If Action Subsystem blocks to a Merge block.
10 Run a simulation.

The action signal lines between the If block and the If Action Subsystem blocks change from a
solid to a dashed line.

10-26
Select Subsystem Execution

Note All blocks in an If Action Subsystem block driven by an If block must run at the same rate as
the driving block.

Models with Switch Case Structure


The Switch Case Action Subsystem block is a Subsystem block preconfigured as a starting point for
creating a subsystem whose execution is enabled by a Switch Case block.

An external Switch Case block controls execution. The Switch Case block evaluates a case index and
then, depending on the selected case, outputs an action signal to a Switch Case Action Subsystem
block.

Merge Signals from Switch Case Action Subsystem Blocks

The example model ex_switch_case_block shows how to create one signal from multiple
subsystem output signals.

The Switch Case block selects the execution of one Switch Case Action Subsystem block from a set of
subsystems. Regardless of which subsystem the Switch Case block selects, you can create one
resulting signal with a Merge block.

The input to the Switch Case block provides the index value for selecting a case represented as
output ports. Each output port is attached to a Switch Case Action Subsystem block. When a case is
selected, its corresponding Switch Case Action Subsystem block is executed.

The switch structure in the model can be represented with this pseudo code.
CASE u1
u1 = 1:
subsystem_1
break
u1 = 2 or 3:
subsystem_2_3
break

10-27
10 Conditional Subsystems

u1 = OTHER VALUES:
subsystem_default
break
END CASE

Create Model with Switch Case Structure

To create the example model, use this procedure.

1 Place a Switch Case block in the Simulink Editor. Double-click the block to open the block
parameters dialog box.
2 In the Case conditions box, enter {1, [2,3]}.

Two cases are defined. The first case when the input value is 1, and the second case when the
input value is 2 or 3. Cases can be single or multivalued and appear as output ports on the
Switch Case block. Non-integer input values are truncated to integers.
3 Select the Show default case check box.

An output port labeled default:is added to the block. This port sends an action signal if no
other cases are selected.
4 Add three Switch Case Action Subsystem blocks.

These blocks are Subsystem blocks with an Action Port block. When you place an Action Port
block inside a subsystem, an input port named Action is added to the block.
5 Connect each output port from the Switch Case block to the action port of an Switch Case Action
Subsystem block.

When you make the connection, the icon for the Switch Case Action Subsystem block is renamed
to the type of expression attached to it.
6 In each Switch Case Action Subsystem block, enter the Simulink blocks to be executed for the
case it handles.
7 Run a simulation.

The action signal lines between the Switch Case block and the Switch Case Action Subsystem
blocks change from a solid to a dashed line.

Note After the subsystem for a particular case executes, an implied break terminates the execution
of the Switch Case block. Simulink Switch Case blocks do not exhibit the fall -through behavior of C
switch statements.

See Also
Action Port | If | If Action Subsystem | Subsystem | Switch Case | Switch Case Action Subsystem

Related Examples
• “Simulink Subsystem Semantics”
• “Modeling Clutch Lock-Up Using If Blocks”
• “If-Then-Else Blocks”

10-28
Iterate Subsystem Execution with While Iterator and For Iterator Subsystems

Iterate Subsystem Execution with While Iterator and For


Iterator Subsystems

In this section...
“Models with While Structures” on page 10-29
“Model with For Structures” on page 10-31

Iterator subsystems, such as the While Iterator and For Iterator subsystems, are a type of logically
executed subsystem that executes one or more times during a time step in response to a control block
internal to the subsystem block. The control block implements control logic similar to that expressed
by a programming language construct such as a while loop or a for loop.

For information about the For Each subsystem, which partitions input signals or mask parameters
into individual elements or subarrays and applies an algorithm to each, see For Each Subsystem.

Note The While Iterator Subsystem and For Iterator Subsystem blocks must not contain blocks with
continuous states (for example, blocks from the Continuous block library). The sample times of all
blocks within the subsystem must be either inherited (-1) or constant (inf).

Models with While Structures


The While Iterator Subsystem block is a Subsystem block preconfigured as a starting point for
creating a subsystem that repeats execution during a simulation time step while a logical (Boolean)
expression is true.

Repeat Block Execution While Boolean Expression Is True

This example shows how to execute a subsystem until a maximum value is reached.

Open the model ex_while_iterator_block.

Open the while-iterator subsystem.

10-29
10 Conditional Subsystems

An input of 1 (true) to the While Iterator block activates the subsystem. At each time step, the
current iterative number is added to a running total until a maximum sum is reached.

The while structure in the model can be represented with this pseudo code.

maximum_sum = 10
sum = 0
iteration_number = 1
condition = TRUE

WHILE (condition is TRUE) AND (iteration_number <= maximum_iterations)


sum = sum + iteration_number
IF (sum > maximum_sum) THEN
condition = FALSE
END IF
iteration_number = iteration_number + 1
END WHILE

Create Model with While Structure

To create the example model, use this procedure.

1 Place a While Iterator Subsystem block in the Simulink Editor. Double-click the subsystem block
to display its contents.

2 Double-click the While Iterator block to open its block parameters dialog box. Set the Maximum
number of iterations to 20 and States when starting to reset. Select the Show iteration
number port check box.
3 Add Memory, Relational Operator, and Sum blocks. Connect blocks as shown. For the Memory
block, select the Inherit sample time check box.

10-30
Iterate Subsystem Execution with While Iterator and For Iterator Subsystems

The iteration number from the output of the While Iterator block is added to its previous value
until the sum is greater than or equal to the maximum sum from Inport block 1.
4 Navigate to the top level of the model.
5 Connect a Constant block to input port 2. This block provides the initial logical condition value
for the While Iterator block. Set the Constant value to any non-zero number.

The While Iterator block requires an initial logical condition (input port labeled IC) for its first
iteration. This signal enables the While Iterator Subsystem block and must originate from outside
the subsystem. If this value is nonzero, the first iteration takes place.
6 Connect a second Constant block to input port 1. This block provides a maximum value for the
iterative algorithm. The algorithm adds successive integers until a maximum value is reached.
7 Connect a Display block to output port 1. This block shows the number of iterations from the
While Iterator block output port.
8 Run a simulation.

During a single time step, the first four iteration numbers are added for a total sum (10). With
the fifth iteration, the sum (15) is greater than the maximum sum (10), the iterations stop, and
the block waits for the next time step.

Note Simulation time does not advance during iterative executions of a While Iterator Subsystem
block. Nevertheless, blocks in the subsystem treat each iteration as a time step. As a result, in a
While Iterator Subsystem block, 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 the block input at the previous simulation time step. For example, a
Unit Delay block in a While Iterator subsystem outputs the value of its input at the previous iteration
of the while loop, not the value at the previous simulation time step.

Model with For Structures


The For Iterator Subsystem block is a Subsystem block preconfigured as a starting point for creating
a subsystem that repeats execution during a simulation time step for a specified number of iterations.

Repeat Block Execution for Specified Number of Times

10-31
10 Conditional Subsystems

This example shows a subsystem that repeats execution during a simulation time step for a specified
number of iterations.

Open the model ex_for_iterator_block.

Open the for-iterator subsystem.

The input to the For Iterator block specifies the number of iterations. At each time step, the current
iterative number is added to a running total for 5 iterations.

The for structure in the model can be represented with this pseudo code.

number_of_iterations = 5
sum = 0

FOR iteration_number = 1 TO number_of_iterations


sum = sum + iteration_number
END FOR

Create Model With For Structure

To create the example model, use this procedure.

1 Place a For Iterator Subsystem block in the Simulink Editor. Double-click the subsystem block to
display its contents.

10-32
Iterate Subsystem Execution with While Iterator and For Iterator Subsystems

2 Double-click the For Iterator block to open its block parameters dialog box. Set States when
starting to reset and Iteration limit source to external.
3 Add Memory, Sum, and Outport blocks. Connect blocks as shown. For the Memory block, select
the Inherit sample time check box.

The iteration number from the output of the For Iterator block is added to its previous value for
the specified number of iterations from Inport block 1.
4 Navigate to the top level of the model.
5 Connect a Constant block to input port 1. This block provides the number of iterations for the For
Iterator block. Set the Constant value to 5.
6 Connect Display blocks to output ports 1 and 2. These blocks shows the number of iterations
from the For Iterator block output port and the sum from the Memory block.
7 Run a simulation.

During each time step, the first five iteration numbers are added for a total sum (15).

See Also
While Iterator Subsystem | While Iterator | For Iterator Subsystem | For Iterator | Subsystem

Related Examples
• “Simulink Subsystem Semantics”
• “Iterated Assignment with the Assignment Block”

10-33
10 Conditional Subsystems

Repeat an Algorithm Using a For-Each Subsystem


To repeat an algorithm, you can iterate the algorithm over signals, subsystems, and parameters that
are grouped into arrays and structures. This page gives examples of how to convert an inefficiently
complex repetitive algorithm into a compact form that is easier to manage.

If you repeat algorithms in a diagram by copying and pasting blocks and subsystems, maintaining the
model can become difficult. Individual signal lines and subsystems can crowd the diagram, reducing
readability and making simple changes difficult. Variables can also crowd workspaces, reducing
model portability. A model can develop these efficiency issues as you add to the design over time.

Explore Example Model

Open the example to access the models that are used in this topic.

The RepeatAlgorithm model processes and analyzes sensor data from three burners, which contain
three sensors each. Each subsystem uses the same algorithm for each burner, but different variables,
which the model loads into the base workspace. You can simplify the model by using for-each
subsystems.

Open the RepeatAlgorithm model.

10-34
Repeat an Algorithm Using a For-Each Subsystem

Each of the subsystems on the left receives three input signals. The subsystems on the right receive
the same input signals via duplicate Inport blocks, but Memory blocks delay the input signals before
they enter the subsystems on the right.

Open the Burner1Analysis subsystem.

10-35
10 Conditional Subsystems

The Burner1Analysis subsystem executes an algorithm by using the base workspace variables as
parameters in blocks such as Constant and Discrete-Time Integrator blocks. The Burner2Analysis
and Burner3Analysis subsystems execute the same algorithm as the Burner1Analysis
subsystem but use different workspace variables to parameterize the blocks.

Open the Burner1AnalysisDelay subsystem.

The Burner1AnalysisDelay subsystem executes a different algorithm with different base


workspace variables. The Burner2AnalysisDelay and Burner3AnalysisDelay subsystems
repeat this algorithm.

In the toolstrip, on the Modeling tab, click Model Settings. Open the Data Import/Export pane of
the Configuration Parameters dialog box. The model uses the variables SensorsInput and t as
simulation inputs. During simulation, each of the nine columns in the SensorsInput matrix variable
provides input data for an Inport block at the top level of the model.

Identify Opportunities to Simplify Model


This example has multiple subsystems that implement the same algorithms. To simplify the model,
one for-each subsystem can replace each set of subsystems that represents the same algorithm. An
array of buses can provide structured input for the for-each subsystems.

These features can make the model more compact and easier to manage.

Remove Redundant Blocks


With the goal in mind, remove the redundant blocks from the block diagram.

10-36
Repeat an Algorithm Using a For-Each Subsystem

1 For the subsystems that contain Burner2 and Burner3 in their names, delete all the blocks,
including the Subsystem blocks.
2 For the subsystem named Burner1Analysis, delete the Inport blocks named Burner1Sensor2
and Burner1Sensor3.
3 For the subsystem named Burner1AnalysisDelay, delete the Inport blocks named
Burner1Sensor2Duplicate and Burner1Sensor3Duplicate and the corresponding Memory
blocks.
4 Replace the Inport block named Burner1Sensor1Duplicate with a branched line from the
Inport block named Burner1Sensor1.
5 Resize the two remaining Subsystem blocks and reorganize the block diagram.

Simplify Interfaces with Buses


To group related signals into a single structured interface, use buses. Buses reduce line density and
improve model readability.

Each subsystem in the example model requires three input signals. A bus can group these three
signals for each subsystem. To pass each bus as structured input to the for-each subsystems via an
array of buses, the bus must be defined by a Simulink.Bus object.

1 Open the Type Editor. From the Simulink Toolstrip, on the Modeling tab, in the Design gallery,
click Type Editor.
2 Create a Simulink.Bus object in the base workspace named SensorData with three elements:
sensor1, sensor2, and sensor3.

10-37
10 Conditional Subsystems

3 Select the remaining Inport block. In the Type Editor, right-click the bus object named
SensorData. Then, select Assign type to selected blocks and ports.

The data type of the Inport block becomes Bus: SensorData. The block output becomes a bus
that contains the three signal elements: sensor1, sensor2, and sensor3.
4 In the subsystem named Burner1Analysis, update the interface for the bus input. For-each
subsystems do not support In Bus Element blocks. Therefore, use an Inport block and a Bus
Selector block.

10-38
Repeat an Algorithm Using a For-Each Subsystem

• Delete the output signal lines of the three Inport blocks.


• Delete the Inport blocks for ports 2 and 3.
• Connect a Bus Selector block to the Inport block for port 1.

5 In the Bus Selector block dialog box, in the Elements in the bus list, select the signals named
sensor1, sensor2, and sensor3. Then, to add the signals to the Output elements list, click

The Bus Selector block extracts the three signals from the input bus. Other blocks in the model
can use the extracted signals.
6 In the Burner1Analysis subsystem, connect the signals:

10-39
10 Conditional Subsystems

• Connect sensor1 to the Product block.


• Connect sensor2 to the Sum block.
• Connect sensor3 to the Discrete-Time Integrator block.

7 In the subsystem named Burner1AnalysisDelay, use a Bus Selector block to extract the
signals from the bus. Use the same steps as you did in the subsystem named Burner1Analysis
and connect the signals:

• Connect sensor1 to the Subtract block.


• Connect sensor2 to the Divide block.
• Connect sensor3 to the Discrete-Time Integrator block.

Repeat an Algorithm
A For Each Subsystem block partitions an input signal and sequentially executes an algorithm on
each partition. For example, if the input to the subsystem is an array of six signals, you can configure
the subsystem to execute the same algorithm on each of the six signals.

You can use for-each subsystems to repeat an algorithm in an iterative fashion. This approach
improves model readability and makes it easy to change the repeated algorithm.

1 Add two For Each Subsystem blocks to the model. Name one of the subsystems
BurnerAnalysis. Name the other subsystem BurnerAnalysisDelay.

10-40
Repeat an Algorithm Using a For-Each Subsystem

2 Copy the contents of the subsystem named Burner1Analysis into the subsystem named
BurnerAnalysis. Before you paste the blocks, delete the Inport and Outport blocks in the for-
each subsystem.
3 In the For Each block dialog box in the BurnerAnalysis subsystem, select the check box to
partition the input In1.
4 Copy the contents of the subsystem named Burner1AnalysisDelay into the subsystem named
BurnerAnalysisDelay.
5 In the For Each block dialog box in the BurnerAnalysisDelay subsystem, select the check box
to partition the input In1.
6 At the top level of the model, delete the subsystems named Burner1Analysis and
Burner1AnalysisDelay. Connect the new For Each Subsystem blocks in their place.
7 On the Signal Attributes tab of the Burner1Sensor1 Inport block dialog box, set Port
dimensions to 3.

The block output is a three-element array of buses. The for-each subsystems in the model repeat
an algorithm for each of the three buses in the array.
8 Create a Simulink.SimulationData.Dataset object that the Inport block can use to import
the simulation data. You can use this code to create the object and store it in the variable
SensorsInput.
% First, create an array of structures whose field values are
% timeseries objects.

for i = 1:3 % Burner number

% Sensor 1
eval(['tempInput(1,' num2str(i) ').sensor1 = ' ...
'timeseries(SensorsInput(:,' num2str(3*(i-1)+1) '),t);'])

% Sensor 2
eval(['tempInput(1,' num2str(i) ').sensor2 = ' ...
'timeseries(SensorsInput(:,' num2str(3*(i-1)+2) '),t);'])

% Sensor 3
eval(['tempInput(1,' num2str(i) ').sensor3 = ' ...
'timeseries(SensorsInput(:,' num2str(3*(i-1)+3) '),t);'])

end

% Create the Dataset object.

SensorsInput = Simulink.SimulationData.Dataset;
SensorsInput = addElement(SensorsInput,tempInput,'element1');

clear tempInput t i

The code first creates a variable tempInput that contains an array of three structures. Each
structure has three fields that correspond to the signal elements in the bus type SensorData,
and each field stores a MATLAB timeseries object. Each timeseries object stores one of the
nine columns of data from the variable SensorsInput, which stores the simulation input data
for each of the sensors.

The code then overwrites SensorsInput with a new Simulink.SimulationData.Dataset


object and adds tempInput as an element of the object.

10-41
10 Conditional Subsystems

9 Set the Input configuration parameter to SensorsInput.

Since SensorsInput provides simulation input data in the form of timeseries objects, you do
not need to specify a variable that contains time data.
10 Create an array of structures that initializes the remaining Memory block, and store the array in
the variable initForDelay. Specify the structure fields with the values of the existing
initialization variables, such as initDelay_1_sensor1.

for i = 1:3 % Burner number

% Sensor 1
eval(['initForDelay(' num2str(i) ').sensor1 = ' ...
'initDelay_' num2str(i) '_sensor1;'])

% Sensor 2
eval(['initForDelay(' num2str(i) ').sensor2 = ' ...
'initDelay_' num2str(i) '_sensor2;'])

% Sensor 3
eval(['initForDelay(' num2str(i) ').sensor3 = ' ...
'initDelay_' num2str(i) '_sensor3;'])
end

To view the contents of the new variable initForDelay, double-click the variable name in the
base workspace. The variable contains an array of three structures that each has three fields:
sensor1, sensor2, and sensor3.

11 In the Memory block dialog box, set Initial condition to initForDelay.

The Memory block output is an array of buses that requires initialization. Each signal element in
the array of buses acquires an initial value from the corresponding field in the array of
structures.

Organize Parameters into Arrays of Structures


The base workspace contains many variables that the example model uses for block parameters. To
reduce the number of workspace variables, package them into arrays of structures, and use the
individual structure fields to specify block parameters.

A For Each Subsystem block can partition an array of values that you specify as a mask parameter.
Each iteration of the subsystem uses a single partition of the array to specify block parameters. If you
specify the parameter as an array of structures, each iteration of the subsystem can use one of the
structures in the array.

10-42
Repeat an Algorithm Using a For-Each Subsystem

1 Create an array of structures that parameterizes the For Each Subsystem block named
BurnerAnalysis, and store the array in the variable paramsNormal. Specify the structure
fields by using the values of existing parameter variables, such as gainNormal_1,
offsetNormal_1, and initDelayed_1.
for i = 1:3
eval(['paramsNormal(' num2str(i) ').gain = gainNormal_' num2str(i) ';'])
eval(['paramsNormal(' num2str(i) ').offset = offsetNormal_' num2str(i) ';'])
eval(['paramsNormal(' num2str(i) ').init = initNormal_' num2str(i) ';'])
end

The variable contains an array of three structures that each has three fields: gain, offset, and
init.
2 In the model, right-click the BurnerAnalysis for-each subsystem and select Mask > Create
Mask.
3 On the Parameters & Dialog pane of the dialog box, under Parameter, click Edit. For the new
mask parameter, set Prompt to Parameter structure and Name to paramStruct. Click on
Save Mask.
4 In the mask for the BurnerAnalysis subsystem, set Parameter structure to paramsNormal.
5 Open the subsystem. In the For Each block dialog box, on the Parameter Partition pane, select
the check box to partition the parameter paramStruct. Set Partition dimension to 2.
6 For the blocks in the subsystem, set these parameters.

Block Parameter Name Parameter Value


Gain Gain paramStruct.gain
Discrete-Time Integrator Initial condition paramStruct.init
Constant Constant value paramStruct.offset
7 Create an array of structures that parameterizes the BurnerAnalysisDelay for-each
subsystem, and store the array in the variable paramsForDelay.
for i = 1:3
eval(['paramsForDelay(' num2str(i) ').gain = gainDelayed_' num2str(i) ';'])
eval(['paramsForDelay(' num2str(i) ').offset = offsetDelayed_' num2str(i) ';'])
eval(['paramsForDelay(' num2str(i) ').init = initDelayed_' num2str(i) ';'])
end
8 At the top level of the model, right-click the BurnerAnalysisDelay for-each subsystem and
select Mask > Create Mask.
9 On the Parameters & Dialog pane of the dialog box, under Parameter, click Edit. For the new
mask parameter, set Prompt to Parameter structure and Name to paramStruct. Click on
Save Mask.
10 In the mask for the For Each Subsystem block, set Parameter structure to paramsForDelay.
11 Open the subsystem. In the For Each block dialog box, on the Parameter Partition pane, select
the check box to partition the parameter paramStruct. Set Partition dimension to 2.
12 For the blocks in the subsystem, set these parameters.

Block Parameter Name Parameter Value


Gain Gain paramStruct.gain
Discrete-Time Integrator Initial condition paramStruct.init
Constant Constant value paramStruct.offset

10-43
10 Conditional Subsystems

13 Clear the unnecessary variables from the base workspace.

% Clear the old parameter variables that you replaced


% with arrays of structures
clear -regexp _

% Clear the iteration variables


clear i

The model requires few variables in the base workspace.

Inspect Converted Model


To view the new signal and subsystem organization, update the diagram.

The model input is an array of three buses. The model uses two for-each subsystems to execute the
two algorithms on each of the three buses in the input array.

In the base workspace, arrays of structures replace the many variables that the model used.
Mathematically, the modified model behaves the same way it did when you started because the arrays
of structures contain the values of all the old variables.

Tip You can log nonbus signals in a for-each subsystem. However, you cannot use signal logging for
buses or arrays of buses from within a for-each subsystem. Either use a Bus Selector block to select
the bus element signals that you want to log or add an Outport block outside of the subsystem and
then log that signal. For details, see “Log Signals in For-Each Subsystems” on page 78-66.

Additional Examples of Working with For-Each Subsystems


Vectorize Algorithms Using For-Each Subsystems

This example shows how to simplify modeling of vectorized algorithms. Using For Each Subsystem
blocks simplifies a model where three input signals are filtered by three identical Transfer Fcn
blocks. This example also shows how to add more control to the filters by changing their coefficients
for each iteration of the subsystem.

This model uses identical Transfer Fcn blocks to independently process each signal. A Vector
Concatenate block concatenates the resulting output signals. This repetitive process is graphically
complex and difficult to maintain. Adding another signal also requires significant reworking of the
model.

10-44
Repeat an Algorithm Using a For-Each Subsystem

You can simplify this model by replacing the repetitive operations with a single For Each Subsystem
block.

The For Each Subsystem block contains a For Each block and a model representing the algorithm of
the three blocks it replaces by way of the Transfer Fcn block. The For Each block specifies how to
partition the input signal vector into individual elements and how to concatenate the processed
signals to form the output signal vector. Every block that has a state maintains a separate set of
states for each input element processed during a given execution step.

10-45
10 Conditional Subsystems

For this example, the input signal is selected for partitioning. The Partition Dimension and
Partition Width parameters on the For Each block are both set to 1 for the input.

You can scale up this approach to add more signals without having to change the model significantly.
This approach is easily scalable and graphically simpler.
Model Parameter Variation Without Changing Model Structure

This example shows how to model parameter variation in an algorithm. It uses the for-each subsystem
partitioning model from the previous example and creates different filters for each input signal while
retaining model simplicity. An array of filter coefficients is fed to the For Each Subsystem block as a
mask parameter marked for partitioning. In each iteration of the For Each Subsystem block, a
partition of the filter coefficient array is fed to the Transfer Fcn block.

1 Open the model ex_ForEachSubsystem_Partitioning.

10-46
Repeat an Algorithm Using a For-Each Subsystem

2 Create a mask for the For Each Subsystem block and add an editable mask parameter. Set the
name to FilterCoeffs and the prompt to Filter Coefficient Matrix. For information on
how to add a mask parameter, see “Create a Simple Mask” on page 43-7.

3 Open the For Each Subsystem block. Inside the subsystem, open the For Each block dialog box.
4 In the Parameter Partition tab, select the check box next to the FilterCoeffs parameter to
enable partitioning of this parameter. Keep the Partition Width and Partition Dimension
parameters at their default value of 1.

10-47
10 Conditional Subsystems

5 Double-click the For Each Subsystem block and enter your filter coefficient matrix, having one
row of filter coefficients for each input signal. For example, enter [0.0284 0.2370 0.4692
0.2370 0.0284; -0.0651 0 0.8698 0 -0.0651; 0.0284 -0.2370 0.4692 -0.2370
0.0284] to implement different fourth-order filters for each input signal.
6 In the For Each Subsystem block, double-click the Transfer Fcn block and enter FilterCoeffs
for the Denominator Coefficients parameter. This setting causes the block to get its
coefficients from the mask parameter.

The For Each Subsystem block slices the input parameter into horizontal partitions of width 1, which
is equivalent to one row of coefficients. The parameter of coefficients starts as a single array.

10-48
Repeat an Algorithm Using a For-Each Subsystem

It transforms from a single array into three rows of parameters.

Improved Code Reuse Using For-Each Subsystems

This example shows how you can design models to improve code reuse when you have two or more
identical For Each Subsystem blocks. Consider the ForEachReuse model.

The intent is for the three subsystems — Vector SS1, Vector SS2, and Vector SS3 — to apply
the same processing to each scalar element of the vector signal at their respective inputs. Because
these three subsystems perform the same processing, it is desirable for them to produce a single
shared Output (and Update) function for all three subsystems in the code generated for this model.
For example, the Vector SS3 subsystem contains these blocks.

10-49
10 Conditional Subsystems

To generate a single shared function for the three subsystems, the configuration of the partitioning
they perform on their input signals must be the same. For Vector SS1 and Vector SS3, this
configuration is straightforward because you can set the partition dimension and width to 1.
However, in order for Vector SS2 to also partition its input signal along dimension 1, insert a Math
Function block to transpose the 1-by-8 row vector into an 8-by-1 column vector. To convert the output
of the subsystem back to a 1-by-8 row vector using a second Math Function block set to the
transpose operator. A reusable shared function can also be generated for the remaining two
subsystems that process matrix signals. For more information about generating C code for the model,
see “Generate Reusable Code from For Each Subsystems” (Simulink Coder).

Limitations of For-Each Subsystems


The For Each Subsystem block has these limitations and workarounds.

Limitation Workaround
You cannot log a bus or an array of buses directly Use one of these approaches:
in the for-each subsystem.
• Use a Bus Selector block to select the signals
you want to log and mark those signals for
signal logging.
• Attach the signal to an Outport block and log
the signal outside the for-each subsystem.
You cannot log a signal inside a referenced model For the first condition, use accelerator mode.
that is inside a for-each subsystem if either of
these conditions exists: For the second condition, use normal or rapid
accelerator mode.
• The for-each subsystem is in a model that
simulates in rapid accelerator mode.
• The for-each subsystem itself is in a model
referenced by a Model block in accelerator
mode.
You cannot log the states of the blocks in a for- Save and restore the simulation state.
each subsystem.

10-50
Repeat an Algorithm Using a For-Each Subsystem

Limitation Workaround
You cannot use Normal mode to simulate a Model Use accelerator or rapid accelerator mode.
block inside a for-each subsystem.
Reusable code is generated for two for-each Permute the signal dimensions to transform the
subsystems with identical contents if their input partition dimension and the concatenation
and output signals are vectors (1-D or 2-D row or dimension to the highest nonsingleton dimension
column vector). For n-D input and output signals, for n-D signals.
reusable code is generated only when the
dimension along which the signal is partitioned is
the highest dimension.

The For Each Subsystem block does not support these features:

• You cannot include these blocks or S-functions inside a for-each subsystem:

• Data Store Memory, Data Store Read, or Data Store Write blocks
• The From Workspace block if the input data uses the Structure with Time format and has
an empty time field
• To File blocks
• Goto and From blocks that cross the subsystem boundary
• Referenced model with simulation mode set to normal
• Shadow Inports
• ERT S-functions

For a complete list of the blocks that support for-each subsystems, enter
showblockdatatypetable in the MATLAB Command Window.

• You cannot use these types of signals:

• Signals with an external storage class inside the system


• Frame signals on subsystem input and output boundaries
• Variable-size signals of more than one dimension
• Creation of a linearization point inside the subsystem
• Propagating the Jacobian flag for the blocks inside the subsystem. You can check this condition in
MATLAB using J.Mi.BlockAnalyticFlags.jacobian, where J is the Jacobian object. To verify
the correctness of the Jacobian of the For Each Subsystem block:

• Look at the tag of the for-each subsystem Jacobian. If it is “not_supported”, then the
Jacobian is incorrect.
• Move each block out of the for-each subsystem and calculate its Jacobian. If any block is
“not_supported” or has a warning tag, the for-each subsystem Jacobian is incorrect.
• You cannot perform these types of code generation:

• Generation of a Simulink Coder S-function target


• Simulink Coder code generation under both of these conditions:

• A Stateflow or MATLAB Function block resides in the subsystem.


• This block tries to access global data outside the subsystem, such as Data Store Memory
blocks or Simulink.Signal objects of ExportedGlobal storage class.

10-51
10 Conditional Subsystems

• PLC code generation


• In some cases, a model using a for-each subsystem may take longer to simulate in normal mode
than it would take if the model were implemented using separate subsystems.
• Local solvers are not supported for referenced models inside for-each subsystems. For more
information, see “Use Local Solvers in Referenced Models” on page 27-5.

See Also
Objects
Simulink.Bus

Blocks
For Each Subsystem | For Each

Related Examples
• “Iteratively Process Nonvirtual Buses with Arrays of Buses” on page 82-90
• “Load Bus Data to Root-Level Input Ports” on page 76-62
• “Specify Bus Properties with Bus Objects” on page 82-65
• “Specify Initial Conditions for Bus Elements” on page 82-72
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Log Signals in For-Each Subsystems” on page 78-66
• “Create Custom Library” on page 45-2

10-52
Using Function-Call Subsystems

Using Function-Call Subsystems


A Function-Call Subsystem block is a conditionally executed subsystem that runs each time the
control port receives a function-call event. A Stateflow chart, Function-Call Generator block, MATLAB
Function block, S-Function block, or Hit Crossing block can provide function-call events.

A function-call subsystem is analogous to a function in a procedural programming language. Invoking


a function-call subsystem executes the output methods of the blocks within the subsystem in
execution order. For an explanation of the Function-Call Subsystem block parameters, see Subsystem.

Creating a Function-Call Subsystem


To create a function-call subsystem:

1 Add a Function-Call Subsystem block to your model.


2 Open the subsystem block. Add a block diagram defining the algorithm that is executed when the
subsystem receives a function-call event.
3 Set initial and disabled values for the Outport blocks. See “Conditional Subsystem Initial Output
Values” on page 10-57 and “Conditional Subsystem Output Values When Disabled” on page 10-
75.
4 Set how subsystem states are handled when the subsystem is executed:

Open the subsystem block, then open the block parameters dialog box for the Trigger block.
From the States when enabling drop-down list, select an option:

• held — States maintain their most recent values.


• reset — States set to their initial conditions.

10-53
10 Conditional Subsystems

• inherit — Use the held or reset setting from the parent subsystem initiating the function-
call.

For nested subsystems whose Function-Call Subsystem blocks have different parameter settings,
the settings for the child subsystem override the settings inherited from the parent subsystem.
See Trigger.
5 Attach a function-call initiator to the function-call input port.

If you attach an Inport block, open the block, select the Signal Attributes tab, then select the
Output function call check box.

Sample Time Propagation in a Function-Call Subsystem


Configure a Function-Call Subsystem block by setting the Sample time type of its Trigger Port block
to triggered or periodic.

• A triggered (aperiodic) function-call subsystem can execute zero, one, or multiple times during a
time step.

If a function-call subsystem is executed by a root-level function-call Inport block with a discrete


sample time, multiple function-calls during a time step are not allowed. To allow multiple function-
calls, set Sample time to -1 (inherited), and set the sample time for all blocks in the function-call
subsystem to -1 (inherited).
• A periodic function-call subsystem executes once during each time step when it receives a
function-call signal, and does not execute at a time step when it does not receive a function-call
signal. Set the sample time for all blocks in the function-call subsystem to -1 (inherited).

For more information about Sample time type settings, see Function-call subsystems examples in
“Simulink Subsystem Semantics”.

Note During range checking, the minimum and maximum parameter settings 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:


1 Add a Signal Conversion block and a Signal Specification block after the source port.
2 Set the Output of the Signal Conversion block to Signal copy.
3 Specify the minimum and maximum values for the Signal Specification block instead of specifying
them on the source port.

Latched Input Data for Function-Call Subsystems


You can latch input data for Inport blocks within Function-Call Subsystem blocks to ensure data
integrity. To latch input data, in the Inport block parameters, select Latch input for feedback
signals of function-call subsystem outputs.

In the following model, input data for the Inport block in the function-call subsystem
ReadDSAndCal1 is latched (indicated by <Li>) and cannot change during the execution of the
subsystem. The Data Store Read and Data Store Write blocks are called within each function-call

10-54
Using Function-Call Subsystems

subsystem. The first and second function-calls write data and the last function-call reads data to the
Data Store Memory block.

Note The root-level data Inport block connected to an internal Inport block is also latched if all of the
blocks connected to the root-level block are latched. For more information, see “Latch input for
feedback signals of function-call subsystem outputs”.

Note Data transfer signals are unprotected in the generated code by default. Use custom storage
classes to prevent data corruption in these signals due to preemption of the current task in the target
environment.

See Also
Blocks
Function-Call Subsystem | Function-Call Generator | Function-Call Split | Function-Call Feedback
Latch | Trigger | Subsystem

Checks
Check usage of function-call connections | Check for potentially delayed function-call subsystem
return values

Model Settings
Context-dependent inputs

Related Examples
• “Simulink Subsystem Semantics”

10-55
10 Conditional Subsystems

• “Export-Function Models Overview” on page 10-125


• “Generate Component Source Code for Export to External Code Base” (Embedded Coder)
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Conditional Subsystem Initial Output Values” on page 10-57
• “Conditional Subsystem Output Values When Disabled” on page 10-75

10-56
Conditional Subsystem Initial Output Values

Conditional Subsystem Initial Output Values


To initialize the output values for a conditional subsystem, initialize Outport blocks within the
subsystem by using one of these methods:

• Inherit initial output values from input signals connected to the Outport blocks.
• Specify initial output values using Outport block parameters.

Note If the conditional subsystem is driving a Merge block in the same model, you do not need to
specify an initial condition for the subsystem Outport block.

Inherit Initial Output Values from Input Signals


By default, for an Outport block, the software sets the Initial output parameter to [] and Output
when disabled parameter to held. With these settings, Simulink attempts to use input signals
connected to conditional subsystem Outport blocks to initialize output values.

Note If Source of initial output value parameter of an Outport block in a conditional subsystem is
set to Input signal, Simulink attempts to use input signals connected to conditional subsystem
Outport blocks to initialize output values. You can replicate this behavior by setting the Source of
initial output value parameter to Dialog, Initial output parameter to [] and Output when
disabled parameter to held.

Valid input signals for setting initial output values include:

• Output ports from another conditionally executed subsystem.


• Output ports from a Model block with a Trigger block with the Trigger type set to function-
call.
• Merge blocks.
• Constant blocks.
• IC (initial condition) blocks.
• Simulink signal objects attached to the signal line connected to the Outport block. If the
InitialValue parameter is defined, Simulink uses this value.
• Stateflow charts.
• C Function blocks.

If the input signal is from a block not listed here, the Outport block uses the default initial value of
the output data type.

When a conditional subsystem Outport block inherits its initial output value, after the model has been
updated or run, an badge is displayed next to the Outport block.

10-57
10 Conditional Subsystems

You can also determine whether a conditional subsystem Outport block inherits its initial output value
by using the Simulink.getOutportInheritsInitialValue function.

Note if you are using classic initialization mode, selecting Input signal causes an error. To inherit
the initial output value from an input signal, set the Source of initial output value parameter to
Dialog, set Output when disabled parameter to held, and set Initial output parameter to [].
The badge is not displayed in classic initialization mode. See “Classic Initialization Mode” on
page 10-78.

Specify Initial Output Values Using Dialog Parameters


Explicitly set the initial output values in cases where you want to:

• Test the behavior of a model with various initial values.


• Set initial values to steady state and reduce simulation time.
• Eliminate having to trace input signals to determine the initial output values.

To specify initial output values:

1 Open the dialog box for an Outport block within a conditional subsystem.
2 From the Source of initial output value options, select Dialog. This parameter is only
available in releases before R2024a. For models from R2024a, skip this and go to the next step.
3 In the Initial output box, enter the initial value.

See Also

More About
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Conditional Subsystem Output Values When Disabled” on page 10-75

10-58
Schedule Components to Avoid Data Dependency Issues

Schedule Components to Avoid Data Dependency Issues

You can control the execution of model components, such as Subsystem and Model blocks, by using
export-function models or rate-based models.

Benefits of scheduling components are:

• Full control over scheduling of model components rather than letting the software implicitly
schedule the components.
• No need to deal with data dependency issues between components. That is, there are only data
transfers.

See Also

More About
• “Sorting Rules for Explicitly Scheduled Model Components” on page 10-68
• “Create Export-Function Model” on page 10-98
• “Create Rate-Based Model” on page 10-60

10-59
10 Conditional Subsystems

Create Rate-Based Model


A rate-based model is a model with explicitly scheduled rates. You can schedule the execution rate of
blocks that have a Sample time parameter, such as Inport, Subsystem, and Delay blocks.

For a subsystem in a rate-based model, you can schedule the execution rate with the Sample time
parameter of any of these blocks.

• An Inport block connected to the Subsystem block. A subsystem has multiple rates when Inport
blocks provide different sample times to the subsystem.
• The Subsystem block. When a Subsystem block specifies a sample time, the blocks it contains
must use the same sample time or a constant sample time.
• A block within the Subsystem block where sample time can be specified. A subsystem has multiple
rates when the blocks it contains specify different sample times.

Subsystems with periodic sample times do not support continuous-time blocks, such as Integrator
blocks. Instead, use equivalent discrete-time blocks, such as Discrete-Time Integrator blocks.

Rate-Based Model with Scheduled Subsystem Blocks

The completed rate-based model ex_rate_based_model has two scheduled atomic Subsystem
blocks. The Subsystem blocks are scheduled by setting their Sample time parameters to a non-zero
positive number.

Open the Property Inspector and check the sample time of each Subsystem block.

• Click the Subsystem block named Subsystem1. The Sample time parameter is set to 0.2.
• Click the Subsystem block named Subsystem2. The Sample time parameter is set to 0.4.

Examine the contents of each subsystem.

The block named Subsystem1 multiplies its input by 2.

10-60
Create Rate-Based Model

The block named Subsystem2 multiplies its input by 4.

See Also
Subsystem | Inport

More About
• “Sorting Rules for Explicitly Scheduled Model Components” on page 10-68
• “Test Rate-Based Model Simulation Using Function-Call Generators” on page 10-62
• “Generate Code from Rate-Based Model” on page 10-65

10-61
10 Conditional Subsystems

Test Rate-Based Model Simulation Using Function-Call


Generators
To test a rate-based model, create a test harness for the rate-based model. The test harness is a
model that references the rate-based model from a Model block. The Model block has periodic
function-call event ports that receive function-call signals.

Create Test Model That References Rate-Based Model


In a new Simulink model:

1 Add a Model block and configure it in the Property Inspector.

• Set Model name to the file name of a rate-based model. For example, use model
ex_rate_based_model from “Create Rate-Based Model” on page 10-60.

The Model block icon updates.


• Under Model events simulation, select Schedule rates.

The Model block displays periodic function-call event ports.


2 Specify the execution rate using function-call initiators, such as Function-Call Generator blocks
or Stateflow charts. The function-call events and scheduling of the events are located outside of
the Model block that references the rate-based model.

For example, add one Function-Call Generator block per periodic event port. Then, set the
Sample time parameter of each Function-Call Generator block to match the sample time of the
corresponding port.

Subsystems or referenced models in a rate-based model with the same sample time must have a
common rate initiator. This requirement includes periodic scheduled subsystems and event-
driven Function-Call Subsystem blocks with the same rate.
3 Use a fixed-step solver for simulation. On the Modeling tab, click Model Settings. Then, in the
Solver pane of the Configuration Parameters dialog box, set Type to Fixed-step.
4 Add source and sink blocks that connect to the input and output ports of the referenced model.
For example, add Sine Wave and Scope blocks, respectively.
5 Optionally, add other controls, such as initialize, reinitialize, reset, and terminate functions to
trigger events. For more information, see “Using Initialize, Reinitialize, Reset, and Terminate
Functions” on page 10-208.

Simulate Test Harness for Rate-Based Model

The ex_model_test_harness_with_subsystems model uses Function-Call Generator blocks to


test the simulation of a rate-based model.

10-62
Test Rate-Based Model Simulation Using Function-Call Generators

The Model block references the rate-based model and schedules the rates of the model with periodic
event ports. The generated function-call signals connect to the periodic event ports.

To observe the behavior of the rate-based model, simulate the test harness. Then, open the Scope
block.

Avoid Common Compile and Run-Time Errors


Some common compile and run-time errors are caused by:

10-63
10 Conditional Subsystems

• A periodic event port that is not connected to a function-call initiator with the same specified
sample time
• A scheduled Inport block (Sample time parameter set to a value) in the referenced model that
does not specify one of the periodic function-call event port rates (sample times specified in the
Port discrete rates table)

See Also

More About
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Sorting Rules for Explicitly Scheduled Model Components” on page 10-68
• “Generate Code from Rate-Based Model” on page 10-65

10-64
Generate Code from Rate-Based Model

Generate Code from Rate-Based Model


Generate code from the rate-based model, not from the model test harness.

To generate code from a rate-based model:

1
In the Simulink Toolstrip, on the Apps tab, click Embedded Coder .
2
On the C Code tab that opens, click Build .

Code Generation Report for Rate-Based Models


The code generation report for a rate-based model describes the timing of the model.

To open the code generation report, on the C Code tab, select Open Latest Report.

Then, click Code Interface Report to view the timing of the functions in the generated code.

Generated Code Entry Points for Rate-Based Models


The combination of single-tasking versus multitasking and single-rate versus multirate controls the
entry points in the generated code.

To enforce single-tasking, clear the Treat each discrete rate as a separate task configuration
parameter. To allow for multitasking, select this parameter.

10-65
10 Conditional Subsystems

This table describes the generated code entry points for the ex_rate_based_model model, which
contains two atomic subsystems named Subsystem1 and Subsystem2.

• Subsystem1 multiplies its input by 2.


• Subsystem2 multiplies its input by 4.

Configuration Explicitly Scheduled Generated Code Entry Points


Rates
Single-tasking or Single-rate. One entry-point function called periodically every
multitasking. 0.2 seconds
Subsystem1 and
Subsystem2 use a void ex_rate_based_model_step(void)
sample time of 0.2. {
ex_rate_based_model_Y.Out1 = 2.0 * ex_rate_based_m
ex_rate_based_model_Y.Out2 = 4.0 * ex_rate_based_m
}
Single-tasking. Multirate. One entry-point function called periodically every
0.2 seconds.
Subsystem1 uses a
sample time of 0.2, and In the entry-point function, a counter
Subsystem2 uses a (Timing.TaskCounters.TID) and rate-
sample time of 0.4. scheduler function (rate_scheduler) determine
which code runs at which sample times.

void ex_rate_based_model_step(void)
{
ex_rate_based_model_Y.Out1 = 2.0 * ex_rate_based_m
if (ex_rate_based_model_M->Timing.TaskCounters.TID
ex_rate_based_model_Y.Out2 = 4.0 * ex_rate_bas
}
rate_scheduler();
}

The rate-scheduler function resets the counter


when the entry-point function runs.

static void rate_scheduler(void)


{
(ex_rate_based_model_M->Timing.TaskCounters.TID[1])
if ((ex_rate_based_model_M->Timing.TaskCounters.TID
ex_rate_based_model_M->Timing.TaskCounters.TID[1]
}
}

10-66
Generate Code from Rate-Based Model

Configuration Explicitly Scheduled Generated Code Entry Points


Rates
Multitasking. Multirate. Two entry-point functions: one called periodically
every 0.2 seconds and the other called
Subsystem1 uses a periodically every 0.4 seconds.
sample time of 0.2, and
Subsystem2 uses a Rates are executed using a prioritized preemptive
sample time of 0.4. multitasking scheme. Faster rates are assigned
higher priorities and thus executed first.

void ex_rate_based_model_step0(void)
{
ex_rate_based_model_Y.Out1 = 2.0 * ex_rate_based_m
}

void ex_rate_based_model_step1(void)
{
ex_rate_based_model_Y.Out2 = 4.0 * ex_rate_based_m
}

See Also

More About
• “Create Rate-Based Model” on page 10-60
• “Sorting Rules for Explicitly Scheduled Model Components” on page 10-68
• “Test Rate-Based Model Simulation Using Function-Call Generators” on page 10-62

10-67
10 Conditional Subsystems

Sorting Rules for Explicitly Scheduled Model Components

Simulink determines the execution order for model components, that is, subsystems and referenced
models.

Export-Function Models
Export-function models include Function-Call Subsystem blocks, function-call Model blocks, Simulink
Function blocks at the root level, and S-Function blocks invoked by function-call root Inport blocks.

Root function-call Inport blocks are sorted with the following rules:

• First compare block priorities. The block with the highest priority (smallest number) is sorted
before the others.
• If block priorities are the same, compare sample times. The block with a faster rate (smaller
sample time value) is sorted before the other.
• If sample times are the same, compare input port numbers. The block with the smaller port
number is sorted before the other.
• If the OrderFunctionsByDependency parameter is set to 'on', blocks that have the same
sample times are further sorted based on any relative data dependency of the functions to which
the blocks are connected. See “Execution Order for Root-Level Function-Call Inport Blocks” on
page 10-129.

10-68
Sorting Rules for Explicitly Scheduled Model Components

Root Simulink Function blocks are sorted after root function-call Inport blocks.

Test Harness for Export Function Models with Strict Scheduling


Reference the export-function model in a test harness and connect ports to Function Generator
blocks.

If you select the check box for the configuration parameter Enable strict scheduling checks for
referenced models, both compile time and run-time checks ensure initiators will invoke function-
calls based on the pre-defined scheduling order. Initiators are sorted based on their sample time
priorities. For this example, the scheduling order and the sample time priorities do not match. The
model mHarness_ExpFcnMdl displays an error.

Test Harness for Export-Function Models Without Strict Scheduling


Reference the export-function model in a test harness and connect ports to Function-Call Generator
blocks.

10-69
10 Conditional Subsystems

If you clear the check box for the configuration parameter Enable strict scheduling checks for a
referenced model and the test harness model is in signal taking mode, the function-call initiators
are sorted based on their sample time priorities. For this example, the execution order is
FcnCallGen0p1 > FcnCallGen0p2 > FcnCallGen0p3 > FcnCallGen0p1.

Data Dependency Error Caused by Data Sorting Rules


Consider a model where the output from one function-call initiator is the input to another.

10-70
Sorting Rules for Explicitly Scheduled Model Components

The function-call initiator FcnCallGen0p3 should be executed before FcnCallGen0p4 based on


their sample times. However, because FcnCallGen0p4 is also a source for FcnCallGen0p3 a data
dependency occurs and Simulink displays an error.

10-71
10 Conditional Subsystems

Test Harness for Models with Initialize, Reset, and Terminate Function
Blocks
If a Model block references a model that has an initialize, reset, or terminate ports, the function-call
initiators connected to these ports have a higher priority than other function-call input ports. For
example, export-function models, rate-based models, and JMAAB-B (Simulink Coder) models can have
other function-call input ports. Simulink sorts function-call initiators in the following order:

• Initialize, reset, and then terminate ports.


• If there is more than one reset port, initiators to those reset ports are not sorted. For example, if a
model has one initialize port driven by block A, two reset ports driven by blocks B and C, and one
terminate port driven by block D, then Simulink sorts in the order A, B or C, and then D. B and C
are sorted using general sorting rules.

Initiators for Model Block in Test Harness


Add function-call event ports to a Model block in a test harness that references a rate-based model or
JMAAB-B model by selecting the Model block parameter Schedule rates.

In a single tasking model, all discrete rates are in the same task. In a multi-tasking model, discrete
rates with the same value execute in the same task. Simulink sorts test harness initiators in the same
task in the following order:

• Initialize, reset, and then terminate ports.


• Function-call input ports mapped to asynchronous function-call root Inport blocks if adapted
model is a JMAAB-B model. Among those "async" function-call input ports, use the task priorities
specified by the Asynchronous Task Specification block connected to the function-call root Inport
block inside the referenced model to compare ports. In the following cases, do not compare ports:

• For two "async" function-call input ports with the same task priorities.

• For "async" function-call input ports with an empty (unspecified) task priority

10-72
Sorting Rules for Explicitly Scheduled Model Components

• Periodic function-call event input ports mapped to discrete rates. Use rate monotonic scheduling
(RMS) rules to compare.

In a single tasking model, all initiators are in the same task:

• InitGen > ResetGen1 or ResetGen2 > TermGen > A10aGen or A10bGen or A[]Gen > D1Gen >
D2Gen
• A10aGen or A10bGen > A20Gen
• Could swap relative ordering of (ResetGen1, ResetGen2) or (A10aGen, A10bGen), or (A[]Gen,
A20Gen), etc.

In a multi-tasking model, initiators of the same color are in the same task.

• InitGen > D1Gen > D2Gen


• A10aGen or A10bGen > A20Gen

10-73
10 Conditional Subsystems

10-74
Conditional Subsystem Output Values When Disabled

Conditional Subsystem Output Values When Disabled


Although a conditional subsystem does not execute while it is disabled, the output signal is still
available to other blocks. When a conditional subsystem is disabled and you have specified not to
inherit initial conditions from an input signal, you can hold the subsystem outputs at their previous
values or reset them to their initial conditions.

To specify output values when disabled:

1 Open the dialog box for an Outport block in a conditional subsystem.


2 From the Source of initial output value drop-down list, select Dialog. This parameter is
available only in releases before R2024a. For models starting in R2024a, skip this and go to step
3.
3 From the Output when disabled drop-down list, select one of these options:

• held — Maintain the most recent value.


• reset — Use the initial condition.

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.
4 In the Initial output box, enter the initial value.

Note If an Outport block in an Enabled Subsystem resets its output when disabled at a different rate
from the execution of the subsystem contents, both the disabled and execution outputs write to the
subsystem output. This behavior can cause unexpected results.

See Also

More About
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Conditional Subsystem Initial Output Values” on page 10-57

10-75
10 Conditional Subsystems

Simplified Initialization Mode


Initialization mode controls how Simulink handles:

• Initialization values for conditionally executed subsystems.


• Initial values for Merge blocks.
• Discrete-Time Integrator blocks.
• Subsystem elapsed time.

The default initialization mode for a model is simplified. This mode uses enhanced processing to
improve consistency of simulation results and helps to:

• Attain the same simulation results with the same inputs when using the same blocks in a different
model.
• Avoid unexpected changes to simulation results as you modify a model.

When to Use Simplified Initialization


Use simplified initialization mode for models that contain one or more of the following blocks:

• Conditional subsystem blocks.


• Merge blocks. If a root Merge block has an empty matrix ([]) for its initial output value, simplified
mode uses the default ground value of the output data type.
• Discrete-Time Integrator blocks. Simplified mode always uses the initial value as both the initial
and reset value for output from a Discrete-Time Integrator block.

Use simplified mode if your model uses features that require simplified initialization mode, such as:

• Specify a structure to initialize a bus.


• Branch merged signals inside a conditional subsystem.

Set Initialization Mode to Simplified


Simplified mode is the default initialization mode when creating a new Simulink model. If your model
is using classic mode, you might need to make changes after you select simplified mode. See
“Convert from Classic to Simplified Initialization Mode” on page 10-97.

1 Open the Configuration Parameters dialog box. On the Modeling tab and from the Setup
section, select Model Settings .
2 In the search box, enter Underspecified initialization detection.
3 From the drop-down list, select Simplified.

For examples configured to use simplified mode, see “Identity Transformation Can Change Model
Behavior” on page 10-79, “Inconsistent Output with Discrete-Time Integrator or S-Function Block”
on page 10-82 and “Execution Order Affecting Merge Block Output” on page 10-84.

10-76
Simplified Initialization Mode

See Also

More About
• “Classic Initialization Mode” on page 10-78
• “Conditionally Executed Subsystems Overview” on page 10-3

10-77
10 Conditional Subsystems

Classic Initialization Mode


Initialization mode controls how Simulink handles the initialization values for conditionally executed
subsystems.

Classic mode was the default initialization mode for Simulink models created in R2013b or before.
You can continue to use classic mode if:

• The model does not include any modeling elements affected by simplified mode.
• The behavior and requirements of simplified mode do not meet your modeling goals.
• The work involved in converting to simplified mode is greater than the benefits of simplified mode.
See “Convert from Classic to Simplified Initialization Mode” on page 10-97.

Set Initialization Mode to Classic


To set classic initialization mode:

1 Open the Configuration Parameters dialog box. On the Modeling tab and from the Setup
section, select Model Settings .
2 In the search box, enter Underspecified initialization detection.
3 From the drop-down list, select Classic.

Classic Initialization Issues and Limitations


Using classic initialization mode can result in one or more of the following issues. You can address
these issues by using simplified mode. The description of each issue includes an example of the
behavior in classic mode, the behavior when you use simplified mode, and a summary of the changes
you must make to use simplified mode.

• “Identity Transformation Can Change Model Behavior” on page 10-79.

Conditional subsystems that include identical subsystems can display different initial values
before the first execution if both of the following apply:

• The model uses classic initialization mode.


• One or more of the identical subsystems outputs to an identity transformation block.
• “Inconsistent Output with Discrete-Time Integrator or S-Function Block” on page 10-82

Conditional subsystems that use classic initialization mode and whose output connects to a
Discrete-Time Integrator block or S-Function block can produce inconsistent output.
• “Execution Order Affecting Merge Block Output” on page 10-84

The execution order of conditional subsystems that used classic mode initialization, when
connected to a Merge block, can affect the output of that Merge block. A change in block
execution order can produce unexpected results.
• When you rename the Merge block source subsystem blocks, the initial output of the Merge block
can change.

10-78
Classic Initialization Mode

When two or more subsystems are feeding different initial output values to a Merge block that
does not specify its own initial output value, renaming one of the subsystems can affect the initial
output of the Merge block in classic initialization mode.
• “Simulink does not provide correct consistency check” on page 10-96

Simulink does not provide the correct consistency check for settings between two Outport blocks
connected through a model reference boundary.

For additional information about the tasks involved to convert a model from classic to simplified
mode, see “Convert from Classic to Simplified Initialization Mode” on page 10-97.

Identity Transformation Can Change Model Behavior


Conditional subsystems that include identical subsystems can display different initial values before
the first execution if both of the following apply:

• The model uses classic initialization mode.


• One or more of the identical subsystems outputs to an identity transformation block.

An identity transformation block is a block that does not change the value of its input signal.
Examples of identify transform blocks are a Signal Conversion block or a Gain block with a value of 1.

In the ex_identity_transform_cl model, subsystems A and B are identical, but B outputs to a


Gain block, which in turn outputs to an Outport block.

10-79
10 Conditional Subsystems

When you simulate the model, the initial value for A (the top signal in the Scope block) is 2, but the
initial value of B is 0, even though the subsystems are identical.

10-80
Classic Initialization Mode

Use these steps to use simplified initialization mode and convert ex_identity_transform_cl to
ex_identity_transform_simpl:

1 Set Underspecified initialization detection to Simplified.


2 For the Outport blocks in subsystems A and B, set the Source of initial output value parameter
to Input signal.

You can also get the same behavior by setting the Source of initial output value parameter to
Dialog and the Initial output parameter to 3.

When you simulate the updated model, the connection of an identity transformation does not change
the result. The output is consistent in both cases.

10-81
10 Conditional Subsystems

Inconsistent Output with Discrete-Time Integrator or S-Function Block


Conditional subsystems that use classic initialization mode and whose output connects to a Discrete-
Time Integrator block or S-Function block can produce inconsistent output.

In the ex_discrete_time_cl model, the enabled subsystem includes two Constant blocks and
outputs to a Discrete-Time Integrator block. The enabled subsystem outputs to two Display blocks.

10-82
Classic Initialization Mode

When you simulate the model, the two display blocks show different values.

10-83
10 Conditional Subsystems

The Constant1 block, which is connected to the Discrete-Time Integrator block, executes, even
though the conditional subsystem is disabled. The top Display block shows a value of 2, which is the
value of the Constant1 block. The Constant2 block does not execute, so the bottom Display block
shows a value of 0.

Use the steps below to use simplified initialization mode and convert ex_discrete_time_cl to
ex_discrete_time_simpl. The converted model looks the same. The updated model corrects the
inconsistent output issue by using simplified mode.

1 Set Underspecified initialization detection to Simplified.


2 For the Outport blocks Out1 and Out2, set the Source of initial output value parameter to
Input signal. This setting explicitly inherits the initial value, which in this case is 2.

You can also get the same behavior by setting the Source of initial output value parameter to
Dialog and the Initial output parameter to 2.

When you simulate the updated model, the Display blocks show the same output. The output value is
2 because both Outport blocks inherit their initial value.

Execution Order Affecting Merge Block Output


The execution order of conditional subsystems that use classic mode initialization, when connected to
a Merge block, can affect the output of that Merge block. A change in block execution order can

10-84
Classic Initialization Mode

produce unexpected results. The behavior depends on how you set the Output When Disabled
parameter.

The ex_basic_merge_sorted_order_1_cl model has two identical enabled subsystems (Enable A


and Enable B) that connect to a Merge block. When you simulate the model, the red numbers show
the sorted execution order of the blocks.

10-85
10 Conditional Subsystems

When you simulate the model, the Scope block looks like the following:

10-86
Classic Initialization Mode

The ex_basic_merge_sorted_order_2_cl model is the same as


ex_basic_merge_sorted_order_1_cl, except that the block execution order is the reverse of the
default execution order. To change the execution order:

1 Open the Properties dialog box for the Enable A subsystem and set the Priority parameter to 2.
2 Set the Priority of the Enable B subsystem to 1.

10-87
10 Conditional Subsystems

When you simulate the model using the different execution order, the Scope block looks like the
following:

10-88
Classic Initialization Mode

The change in execution order produces different results from identical conditional subsystems.

To update the models and create ex_basic_merge_sorted_order_1_simpl and


ex_basic_merge_sorted_order_2_simpl that use simplified initialization mode :

1 Set Underspecified initialization detection to Simplified.

The Initial Output parameter of the Merge block is an empty matrix, [], by default. Hence, the
initial output value is set to the default initial value for this data type, which is 0. For information on
default initial value, see “Initialize Signal Values” on page 81-9. When you simulate each simplified
mode model, both models produce the same results.

10-89
10 Conditional Subsystems

Using Output When Disabled Parameter Set to Reset

The ex_merge_sorted_1_cl model has two enabled subsystems (Enable A and Enable B) that
connect to a Merge block. When you simulate the model, the red numbers show the sorted execution
order of the blocks.

10-90
Classic Initialization Mode

When you simulate the model, the Scope block looks like the following:

10-91
10 Conditional Subsystems

The ex_merge_sorted_2_cl model is the same as ex_merge_sorted_1_cl, except that the block
execution order is the reverse of the default execution order. To change the execution order:

1 Open the Properties dialog box for the Enable A subsystem and set the Priority parameter to 2.
2 Set the Priority of the Enable B subsystem to 1.

10-92
Classic Initialization Mode

When you simulate the model using the different execution order, the Scope block looks like:

10-93
10 Conditional Subsystems

The change in execution order produces different results from identical conditional subsystems.

To update the models and create ex_merge_sorted_1_simpl and ex_merge_sorted_2_simpl


that use simplified initialization mode:

1 Set Underspecified initialization detection to Simplified.


2 For the Outport blocks in Enable A and Enable B, set the Output when disabled parameter to
held. Simplified mode does not support reset for output ports of conditional subsystems driving
Merge blocks.

When you simulate each simplified mode model, both models produce the same results.

10-94
Classic Initialization Mode

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

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

10-95
10 Conditional Subsystems

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:

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.

Simulink does not provide correct consistency check


Simulink does not provide the correct consistency check for settings between two Outport blocks
connected through a model reference boundary.

Simulink either throws a false warning or no warning when all of the following conditions are true:

• The option Underspecified initialization detection is set to Classic.


• The model contains a Model block.
• In the referenced model, a root Outport block is driven directly (or indirectly through virtual
blocks) by a conditionally executed subsystem. In this scenario, the Outport block corresponding
to the conditionally executed subsystem output is a source Outport block.
• In the top model, the output port of the Model block that is driven by the source Outport block, in
turn, drives a destination Outport block of a conditionally executed subsystem.

If both the source and destination Outport blocks are in the same model, and the settings Initial
output and Output when disabled (if applicable) for both Outport blocks differ, Simulink throws an
error. However, in the case described above, Simulink either throws a false warning when the two
Outport blocks have the same settings or throws no warning or error when they are different.

10-96
Convert from Classic to Simplified Initialization Mode

Convert from Classic to Simplified Initialization Mode


If you switch the initialization mode from classic to simplified mode, you can encounter several issues
that you must fix. For most models, the following approach helps you to address conversion issues
more efficiently.

1 Save the existing model and simulation results for the model.
2 Simulate the model and address any warnings.
3 In the Model Advisor, in the Simulink checks section, run the checks in the folder “Migrating to
Simplified Initialization Mode Overview”.
4 Address the issues that Model Advisor identifies.
5 Simulate the model to make sure that there are no errors.
6 Rerun the Model Advisor checks in the folder “Migrating to Simplified Initialization Mode
Overview” check to confirm that the modified model addresses the issues related to initialization.

For examples of models that have been converted from classic initialization mode to simplified
initialization mode, see “Classic Initialization Issues and Limitations” on page 10-78.

Blocks to Consider
Discrete-Time Integrator Blocks

Discrete-Time Integrator block behaves differently in simplified mode than it does in classic mode.
The changes for simplified mode promote more robust and consistent model behavior. For details, see
“Behavior in Simplified Initialization Mode” in the Discrete-Time Integrator block reference
documentation.

Library Blocks

Simulink creates a library assuming that classic mode is in effect. If you use a library block that is
affected by simplified mode in a model that uses simplified mode, then use the Model Advisor to
identify changes you must make so that the library block works with simplified mode.

See Also

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3

10-97
10 Conditional Subsystems

Create Export-Function Model


The first step for creating independent functions in the generated code from a Simulink model is to
define the functions in the context of an export-function model. For high-level information about
export-function models, see “Export-Function Models Overview” on page 10-125.

Designate Model as Export-Function Model and Satisfy Export-


Function Model Requirements
To designate a model as an export-function model:

1 Click the canvas to clear the selection from any blocks.


2 Open the Property Inspector and go to the Execution tab.
3 Select the Set execution domain parameter.
4 From the Domain list, select Export function.

To satisfy export-function model requirements:

1 Open the Configuration Parameters dialog box. On the Modeling tab, select Model Settings
.
2 In the Solver pane, set solver selection Type to Fixed-step, Solver to auto, and Fixed-step
size to auto.
3 In the Code Generation pane, set System target file to ert.tlc. This step requires an
Embedded Coder license.

Create Model Algorithms


At the top level of an export-function model, functions are modeled within Function-Call Subsystem,
function-call Model, Simulink Function, and S-Function blocks. This example uses Function-Call
Subsystem blocks to model two functions.

1 Add two Function-Call Subsystem blocks.


2 In the first subsystem, model a unit delay that increments by 0.05 at each time step.

3 In the second subsystem, model the square of an input signal.

10-98
Create Export-Function Model

4 At the top level of the model, add Inport and Outport blocks.

Add Function-Call Inputs


Inport blocks configured to output function-call signals control the execution of Function-Call
Subsystem blocks during a simulation. The function-call Inport blocks also create an entry-point
function in the generated code.

1 Connect Inport blocks to the function() input ports on the Function-Call Subsystem blocks.
2 Specify sample times. Open the Inport block dialog boxes and select the Signal Attributes tab.
Select the Output function call parameter. Set Sample time for the delay function to 0.1 (100
ms) and the square function to 0.01 (10 ms).

Setting the sample time is only for simulation testing. Sample time values do not affect the
generated code. However, comments are added in the code identifying the rate you should call
the functions.

You could set the sample times to -1 and allow any function-call rate (periodic or aperiodic)
during simulation. By setting sample times, the software checks the calling rate with the
specified rate and displays an error if there is a mismatch.
3 Rename blocks. The names help to identify signals in the generated code.
4 Update the model (Ctrl+D). Dotted-and-dashed lines identify function-call signals.

Export-Function Model with Unit Delay and Square Functions

To open the completed export-function model, open the model named export_function_model.

10-99
10 Conditional Subsystems

The model contains two function-call subsystems. One subsystem contains a Unit Delay block, while
the other subsystem contains a Square block.

Test Model
After you create an export-function model, test it with simulations. Choose one of these simulation
testing methods:

• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101


• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114

See Also
Function-Call Subsystem

Related Examples
• “Export-Function Models Overview” on page 10-125
• “Generate Code for Export-Function Model” on page 10-118

10-100
Test Export-Function Model Simulation Using Input Matrix

Test Export-Function Model Simulation Using Input Matrix


When function-call sequencing is simple enough to be specified as a model input, simulation using an
input matrix is the preferred method for testing an export-function model.

1 Create time vectors that specify function-call times.


2 Create a matrix that adds input data to the time vectors.
3 Run a simulation.

To create an export-function model for this example, see “Create Export-Function Model” on page 10-
98.

Create Function-Call Inputs and Data Inputs


Create time-vectors indicating when events occur for root-level function-call Inport blocks and data-
vectors for root-level data Inport blocks.

1 For function-call Inport blocks 1 and 2, create column vectors with time steps of 0.1 and 0.01.
In the MATLAB Command Window, enter

t1 = [0:0.1:10]';
t2 = [0:0.01:10]';

• The time vector must be monotonically increasing and of double data type.
• If the sample time for a function-call Inport block is specified, the values in the corresponding
time vector must all be integer multiples of the specified value.
• To specify multiple function-calls at a given time step, repeat the time value accordingly. For
example, to specify three events at t = 0.1 and 2 events at t = 0.5, list 0.1 three times and 0.5
twice in your time vector, t1 = [0.1 0.1 0.1 0.5 0.5]'.
• To use nonperiodic sample times, set the Inport block Sample time to -1 and provide a
nonuniform time vector, e.g. t1 = [0, 0.1, 0.2, 0.4, 0.8].
2 Create a matrix with time steps and data values for data Inport block 3.

sine_data = sin(0:0.01:10)';
d3 = [t2,sine_data];

The data input can use any supported format as described in “Forms of Input Data” on page 76-
52.

The following table provides additional information for specifying the time vector t.

10-101
10 Conditional Subsystems

Sample time type for Root-level Function-Call Root-level Function-Call


internal Trigger Port block Inport block with inherited Inport block with discrete
set to: sample time (-1) sample time
triggered Nondecreasing column vector. Nondecreasing column vector.
Each element in the column
The function-call subsystem vector must be an integer
executes at the times specified multiple of the sample time
by the column vector. The specified by the Inport block.
sample times can be periodic or
aperiodic. The function-call subsystem
executes at the times specified
If you specify an empty matrix by the column vector.
([]), the function-call
subsystem does not execute. Alternatively, specify an empty
matrix ([]) and the function-call
subsystem executes once at
every sample time specified by
the Inport block.
periodic Configuration not allowed Empty matrix([]).

The function-call subsystem


executes at the times specified
by the Inport block calling it.

Simulate Export-Function Model


Simulate the export-function model to test and observe its behavior before generating code.

1 Import time and data from the MATLAB workspace.

On the Modeling tab, select Model Settings . In the Configuration Parameters dialog box,
select the Data Import/Export pane and set the Input parameter to t1, t2, d3.

t1 and t2 are column vectors containing event times for the function-call Inport blocks 1 and 2.
d3 is a table of input values versus time for the data Inport block 3.
2 Run a simulation.
3 Plot results. In the MATLAB Command Window, enter.

plot(yout.time, yout.signals(1).values)
hold
plot(yout.time, yout.signals(2).values)

10-102
Test Export-Function Model Simulation Using Input Matrix

4 Change t1 to provide events every 0.5 seconds (0.5 is an integer multiple of the sample time of
0.1 specified in Inport block 1).

t1 = [0:0.5:10]';
5 Rerun simulation.

After you test your model, you can generate code for the functions. See “Generate Code for Export-
Function Model” on page 10-118.

See Also
Function-Call Subsystem

10-103
10 Conditional Subsystems

Related Examples
• “Export-Function Models Overview” on page 10-125
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114
• “Generate Code for Export-Function Model” on page 10-118

10-104
Test Export-Function Model Simulation Using Function-Call Generators

Test Export-Function Model Simulation Using Function-Call


Generators
Use multiple Function-Call Generator blocks with distinct sample times and let the software schedule
the function-call components for simulation. This strategy is useful when the rate-monotonic
scheduling behavior in Simulink software is similar to the target OS behavior.
1 Create a Simulink model.
2 Add a Model block that references the export-function model.
3 Specify function-call events using Function-Call Generator blocks.
4 Specify data inputs.
5 Run a simulation.

Reference an Export-Function Model


Referencing an export-function model from a Model block allows you to add function-call events and
signal logging for testing without changing the model itself.
1 Add a Model block to a new Simulink model. In the Model name box, enter the name of an
export-function model. For example, use the export-function model created in “Create Export-
Function Model” on page 10-98.
2 Add and connect Outport blocks to the output_100ms and output_10ms ports on the Model
block.
3 Add a Sine Wave block to provide data input. Set Amplitude to 2 and Sample time to 0.01.
Connect the block to the input_10ms input port on the Model block.

Create Test Model (Harness) for Simulation


Use a Simulink test model only for simulation. After simulation testing, generate code from the
export-function model. Then, integrate exported function code with an externally coded scheduler.
1 Add a Function-Call Generator block. Set Sample time to 0.1. Connect the block to the
function_call_100ms input port.
2 Add a second Function-Call Generator block. Set Sample time to 0.01. Connect the block to the
function_call_10ms input port.

10-105
10 Conditional Subsystems

Scheduling Restrictions for Referenced Export-Function Models

If a test model references an export-function model, there are some restrictions to ensure consistency
with simulation results.

For the test model:

• You cannot use two Function-Call Generator blocks with the same sample time.
• Function-calls to the input ports on the Model block must follow the execution order of the root-
level function-call Inport blocks in the referenced export-function model. Function-Call Generator
blocks with smaller sample times execute first.

If the test model calls the referenced model functions out of order at any time step, the software
displays an error. For information on sorted execution order, see “Control and Display Execution
Order” on page 40-16. To disable this restriction, clear the Enable strict scheduling checks
for referenced model configuration parameter.
• You can use a Mux block to connect signals from the Function-Call Generator blocks with different
sample times before connecting them to the referenced export-function model. In the
Configuration Parameters dialog box, clear the Treat each discrete rate as a separate task
parameter.

For the export-function model:

• The sample times for the root-level function-call Inport blocks must be set to inherited (-1) or
match the sample time of the Function-Call Generator blocks that drive them.

Prepare Export-Function Model for Simulation


Before you test the export-function model, configure model settings and specify signals to log.

1
On the Modeling tab, click Model Settings .
2 On the Model Referencing pane, clear the configuration parameter Enable strict scheduling
check for referenced models.
3 Verify the settings for these configuration parameters on the Solver pane:

• Type is set to Fixed-step.

10-106
Test Export-Function Model Simulation Using Function-Call Generators

• Solver is set to discrete (no continuous states).


• Fixed-step size (fundamental sample time) is set to auto.
4 Set up logging for signals. Right-click a signal you want to log. Then, select Log selected signal.
In this example, the export-function model output signals are logged because they connect to
Outport blocks.

Note The software does not simulate preempting function-calls.

Test Export-Function Model with Function-Call Generator Blocks

To test and observe the export-function model behavior before generating code, simulate the
completed test model.

Optionally, open and simulate the completed test model named


ex_export_function_test_model_with_function_call_generators.

To view the simulation results, open the Simulation Data Inspector. On the Simulation tab, click
Data Inspector.

After you test your model, you can generate code for the functions. See “Generate Code for Export-
Function Model” on page 10-118.

See Also
Function-Call Subsystem

10-107
10 Conditional Subsystems

Related Examples
• “Export-Function Models Overview” on page 10-125
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114
• “Generate Code for Export-Function Model” on page 10-118

10-108
Test Export-Function Model Simulation Using Stateflow Chart

Test Export-Function Model Simulation Using Stateflow Chart


Use a Stateflow chart to provide a function-call scheduler where you can fully control the scheduling
process for periodic (synchronous) or aperiodic (asynchronous) call sequences.

1 Create a Simulink model.


2 Add a Model block that references the export-function model.
3 Specify function-call Inputs using a Stateflow chart.
4 Specify data inputs.
5 Run a simulation.

Reference an Export-Function Model


Referencing an export-function model from a Model block allows the addition of function-calls events
from a Stateflow chart and the logging of data signals for testing without changing the model itself.

1 Add a Model block to a new Simulink model. In the Model name box, enter the name of an
export-function model. For example, use the export-function model created in “Create Export-
Function Model” on page 10-98.
2 Add and connect Outport blocks to the output_100ms and output_10ms ports for saving
simulation data.
3 Add a Sine Wave block to provide data input. Set Amplitude to 2 and Sample time to 0.01.
Connect the block to the input_10ms input port on the Model block.

Create Periodic Scheduler Using Stateflow Chart


1 Create a Stateflow chart. This step requires a Stateflow license.
2
On the Modeling tab and from the Design section, select Model Explorer . In the Model
Hierarchy pane, select Chart.
3 Add function-call events with output ports to the chart. From the menu, select Add > Event. In
the Name box, enter out_100ms. From the Scope list, select Output to Simulink. Repeat
this step to create a function-call event and output port for out_10ms.

10-109
10 Conditional Subsystems

4 Open the chart by double-clicking the block. Add a State block and a Default transition arrow.

5 Rename the state to function_call_scheduler.


6 Add periodic function-calls every 10 and 100 milliseconds. In the state block, enter these
commands.

on every(10, tick):send(out_10ms);
on every(100, tick):send(out_100ms);

The keyword tick is an implicit event that counts the number of simulation steps while send is
an explicit event that outputs a function-call event to the output ports.

Create Test Model (Harness) for Simulation


Use a Simulink test model only for simulation. After simulation testing, generate code from the
export-function model. Then, integrate exported function code with an externally coded scheduler.

1 Add a Stateflow chart to your test model.


2 Connect the Stateflow chart outputs to Model block inputs.

10-110
Test Export-Function Model Simulation Using Stateflow Chart

Scheduling Restrictions for Referenced Export-Function Models

If a test model references an export-function model, there are some restrictions to ensure consistency
with simulation results.

For the test model:

• Function-calls to the input ports on the Model block must follow the execution order of the root-
level function-call Inport blocks in the referenced export-function model.

If the test model calls the referenced model functions out of order at any time step, the software
displays an error. For information on sorted execution order, see “Control and Display Execution
Order” on page 40-16. To disable this restriction, clear the configuration parameter Enable
strict scheduling checks for referenced models.

For the export-function model:

• The sample times for the root-level function-call Inport blocks must be set to inherited (-1) or
match the sample time of the function-calls from the Stateflow chart that drives them.

Prepare Export-Function Model for Simulation


Before you test the export-function model, configure model settings and specify signals to log.

1
On the Modeling tab, click Model Settings .
2 On the Model Referencing pane, clear the configuration parameter Enable strict scheduling
check for referenced models.
3 Verify the settings for these configuration parameters on the Solver pane:

• Type is set to Fixed-step.


• Solver is set to discrete (no continuous states).
• Fixed-step size (fundamental sample time) is set to auto.
4 Set up logging for signals. Right-click a signal you want to log. Then, select Log selected signal.
In this example, the export-function model output signals are logged because they connect to
Outport blocks.

10-111
10 Conditional Subsystems

Note When using export-function models in top-model simulations, do not change the enable/disable
status of the model during simulation. Enable it at the start of simulation and use function-calls to call
it.

Test Export-Function Model Using Stateflow Chart

To test and observe the export-function model behavior before generating code, simulate the
completed test model.

Optionally, open and simulate the completed test model named


ex_export_function_test_model_with_stateflow_chart.

To view the simulation results, open the Simulation Data Inspector. On the Simulation tab, click
Data Inspector.

After you test your model, you can generate code for the functions. See “Generate Code for Export-
Function Model” on page 10-118.

See Also
Function-Call Subsystem

Related Examples
• “Export-Function Models Overview” on page 10-125
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105

10-112
Test Export-Function Model Simulation Using Stateflow Chart

• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114


• “Generate Code for Export-Function Model” on page 10-118

10-113
10 Conditional Subsystems

Test Export-Function Model Simulation Using Schedule Editor


Use the Schedule Editor to schedule the function-call components for simulation. This strategy is
useful when you want to set the order of execution for function-call components and view data
dependencies between components.

1 Create a Simulink model.


2 Add a Model block that references the export-function model.
3 Specify function-call events using the Schedule Editor.
4 Specify data inputs.
5 Run a simulation.

Create Test Model (Harness) for Simulation


A Simulink test model is used only for simulation. After simulation testing, generate code from the
export-function model, then manually integrate exported function code with an externally coded
scheduler. Referencing an export-function model from a Model block allows the addition of function-
call events and logging of data signals for testing without changing the model itself.

1 Create a Simulink model.


2
On the Modeling tab and from the Setup section, select Model Settings .
3 In the left pane of the Configuration Parameters dialog box, select Solver. In the right pane,
select the Solver details arrow to display additional parameters. Select the parameters Treat
each discrete rate as a separate task and Automatically handle rate transition for data
transfer.
4 Add a Model block to your model.
5
On the Modeling tab, in the Design gallery, select Property Inspector .
6 In the Model name box, enter the name of an export-function model. For example, use the
export-function model created in “Create Export-Function Model” on page 10-98.
7 Select the Schedule rates parameter. From the Schedule rates list, select Schedule Editor.
8 Add and connect Outport blocks to the output_100ms and output_10ms ports of the Model
block.
9 Add a Sine Wave block to provide data input. Set Amplitude to 2 and Sample time to 0.01.
Connect the block to the input_10ms input port on the Model block.

10-114
Test Export-Function Model Simulation Using Schedule Editor

Create Function-Call Events Using the Schedule Editor


Use the Schedule Editor to provide function-call events by defining time-vectors that indicate when
events occur for root-level function-call Inport blocks.

1 Open the Schedule Editor. On the Modeling tab, in the Design section, select Schedule Editor
. The Schedule Editor partitions the function-call Inport blocks and names the partitions using
the block names.

2 Select the Model.function_call_2 partition. In the Hit Times box, enter a matrix with values
that begin at 0 and periodically increase by 0.01 to 10. You can also test asynchronous behavior
by entering a matrix with random values that are multiples of 0.01.

10-115
10 Conditional Subsystems

3 Select the Model.function_call_1 partition. In the Hit Times box, enter a matrix with values
that begin at 0 and increase by 0.1 to 10.

Prepare Export-Function Model for Simulation


Before you test the export-function model, configure model settings and specify signals to log.

1
On the Modeling tab, click Model Settings .
2 Verify the settings for these configuration parameters on the Solver pane:

• Type is set to Fixed-step.


• Solver is set to discrete (no continuous states) or auto (Automatic solver
selected).
• Fixed-step size (fundamental sample time) is set to auto.
3 Set up logging for signals. Right-click a signal you want to log. Then, select Log selected signal.
In this example, the export-function model output signals are logged because they connect to
Outport blocks.

Test Export-Function Model Using Schedule Editor

10-116
Test Export-Function Model Simulation Using Schedule Editor

To test and observe the export-function model behavior before generating code, simulate the
completed test model.

Optionally, open and simulate the completed test model named


ex_export_function_test_model_with_schedule_editor.

To view the simulation results, open the Simulation Data Inspector. On the Simulation tab, click
Data Inspector.

After you test your model, you can generate code for the functions. See “Generate Code for Export-
Function Model” on page 10-118.

See Also
Function-Call Subsystem

Related Examples
• “Using the Schedule Editor” on page 25-11
• “Export-Function Models Overview” on page 10-125
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Generate Code for Export-Function Model” on page 10-118

10-117
10 Conditional Subsystems

Generate Code for Export-Function Model


You generate code for independent functions from an export-function model, not the simulation test
model (harness). After generating the function code, you can integrate the functions with a scheduler
that you hand-code externally from Simulink software.

Generate Code for Exported Functions


Generate code from the model that contains the functions.

1 Open an export-function model. For example, use the export-function model created in “Create
Export-Function Model” on page 10-98.
2
On the Simulation tab and from the Prepare section, select Model Settings .

In the Solver pane, set Solver Type to Fixed-step. In the Code generation pane, set System
target file to ert.tlc. Requires an Embedded Coder license.
3 Display the C Code tab by selecting the Apps tab, and then in the Apps section, select

Embedded Coder . On the C Code tab, select Generate Code . Wait for the code
building process to complete.
4 On the C Code tab, select Open Latest Report.

10-118
Generate Code for Export-Function Model

In the generated code, each root-level function-call Inport block generates a void-void function. The
function name is the name of the output signal from the block. If there is no signal name, then the
function name is derived from the name of the block. In this example, the function name was derived
from the block name.

See Also
Function-Call Subsystem

Related Examples
• “Export-Function Models Overview” on page 10-125

10-119
10 Conditional Subsystems

• “Create Export-Function Model” on page 10-98


• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114

10-120
Generate Code for Export-Function Model with Rate-Based Model

Generate Code for Export-Function Model with Rate-Based


Model
You can generate code from a model that includes both function-call subsystems and scheduled
subsystems. Create a rate-based model with the scheduled subsystems. Then, reference the rate-
based model from an export-function model by using a Model block.

Create Export-Function Model with Scheduled Subsystems and Rate-


Based Model
1 Create a rate-based model with scheduled subsystems. See “Create Rate-Based Model” on page
10-60.

In this example, the Sample time for the scheduled subsystem is set to 0.01.

2 Create an export-function model with function-call subsystems. See “Create Export-Function


Model” on page 10-98.

3 Include the rate-based model in the export-function model by referencing the rate-based model
from a Model block.

10-121
10 Conditional Subsystems

4 Display periodic event ports on the Model block by selecting the Schedule rates block
parameter.

Connect Inport blocks to the periodic event ports.


5 For Inport blocks connected to periodic event ports, select the Output function-call block
parameter and specify the sample time with the same sample time from the scheduled
subsystem.

In this example, the Sample time for the Inport block named function-call 10ms is set to
0.01.

The completed export-function model includes both a function-call subsystem and a scheduled
subsystem.

10-122
Generate Code for Export-Function Model with Rate-Based Model

Generate Code for Export-Function Model with Rate-Based Model

When you generate code for an export-function model that references a rate-based model, the
generated code for the rate-based model is integrated into the generated code for the export-function
model.

Optionally, open the completed export-function model named


export_function_model_with_rate_based_model.

To generate code for the exported functions:

1 In the Simulink® Toolstrip, on the Modeling tab, click Model Settings. The Configuration
Parameters dialog box opens.
2 On the Solver pane, set Type to Fixed-step.
3 On the Code Generation pane, set System target file to ert.tlc, which requires an
Embedded Coder® license.
4 In the Simulink Toolstrip, on the Apps tab, in the Apps gallery, select Embedded Coder.
5 On the C Code tab that opens, click Generate Code.

In the Code Generation Report dialog box that opens, under Code > Model files, select the C file.

10-123
10 Conditional Subsystems

In the generated code, each root-level function-call Inport block generates a void-void function. The
function name is the name of the output signal from the block. If there is no signal name, then the
function name is derived from the name of the block. In this example, the function name was derived
from the block name.

See Also

Related Examples
• “Generate Code for Export-Function Model” on page 10-118
• “Generate Code from Rate-Based Model” on page 10-65

10-124
Export-Function Models Overview

Export-Function Models Overview

Export-function models are Simulink models that generate code for independent functions that can be
integrated with an external environment and scheduler. Functions are defined using Function-Call
Subsystem, function-call Model, Simulink Function, Message Triggered Subsystem, and S-Function
blocks.

The following export-function model contains two functions defined with Function-Call Subsystem
blocks. For a step-by-step procedure to create this model, see “Create Export-Function Model” on
page 10-98.

Code generated from this model has two independent functions, one for a delay function and the
other for a square function.
/*
* File: export_function_model.c
* Code generated for Simulink model 'export_function_model'.
*/

void function_call_100ms(void) /* Sample time: [0.1s, 0.0s] */


{
export_function_model_Y.output_100ms =
export_function_model_DW.UnitDelay_DSTATE;

export_function_model_DW.UnitDelay_DSTATE =
export_function_model_Y.output_100ms + 1.0;
}

void function_call_10ms(void) /* Sample time: [0.01s, 0.0s] */


{
export_function_model_Y.output_10ms = export_function_model_U.input_10ms *
export_function_model_U.input_10ms;
}

10-125
10 Conditional Subsystems

Workflows for Export-Function Models


Four common processes for creating export-function models differ in how you simulate and test your
model before generating code for the functions.

When function-call sequencing is simple enough to be specified as a model input, simulation using an
input matrix is the preferred method for testing an export-function model. For more information, see
“Test Export-Function Model Simulation Using Input Matrix” on page 10-101.

When function-call sequencing is too complicated to specify with an input matrix, create a test model
(harness) to mimic the target environment behavior. Use this test model to provide function-call
inputs to the export-function model. For more information, see “Test Export-Function Model
Simulation Using Function-Call Generators” on page 10-105, “Test Export-Function Model Simulation
Using Schedule Editor” on page 10-114 and “Test Export-Function Model Simulation Using Stateflow
Chart” on page 10-109.

Blocks Allowed at Top Level of Export-Function Models


At the top-level, an export-function model is limited to virtual blocks, blocks with constant (inf)
sample time, and the following blocks:

• Inport
• Outport
• Bus Creator
• Bus Selector
• In Bus Element
• Out Bus Element
• Function-Call Subsystem
• Model with function-call input ports

10-126
Export-Function Models Overview

• Simulink Function
• Function Element
• Function Element Call
• Message Triggered Subsystem
• Initialize Function
• Reinitialize Function
• Reset Function
• Terminate Function
• Data Store Memory
• Merge
• S-Function with function-call input port
• Function-Call Split
• Display
• Scope

For more information, see “Nonvirtual and Virtual Blocks” on page 40-2 and “Types of Sample
Time” on page 7-18.

Requirements for Export-Function Models


For an export-function model to successfully generate function code, the following requirements must
be met.

Model Configuration Parameters:

• Solver Type set to Fixed-step.


• Solver set to auto or discrete.
• Code Generation System target file set to ert.tlc. Selecting ert.tlc requires an Embedded
Coder license.
• For function-call Model blocks, Periodic sample time constraint for the referenced model set to
Ensure sample time independent.

Root-level function-call Inport blocks:

• Output function call check box selected.


• Cannot receive a signal from an Asynchronous Task Specification block.

Root-level Outport blocks must be connected to one of these blocks or left unconnected or grounded:

• Function-call block driven by root-level function-call Inport block. This block can be a Function-
Call Subsystem block, a function-call Model block, or an S-Function block with function-call input.
• Simulink Function block.
• Initialize Function, Reinitialize Function, Reset Function, or Terminate Function block.
• Merge or Mux block driven exclusively by such blocks.

Root-level data Inport and Outport blocks cannot connect to virtual bus data signals.

10-127
10 Conditional Subsystems

Root-level Function-Call Subsystem blocks and function-call Model blocks:

• All internal blocks within the block must support code generation.
• If the Trigger block Sample time type is set to:

• triggered, internal blocks must have Sample time set to -1.


• periodic, the root-level function-call Inport block must have its Sample time set to a
specified discrete time and all internal blocks must have Sample time set to -1 or the
specified discrete time.

Designating an Export-Function Model


When you create an export-function model, tell Simulink to treat your model as an export-function
model by designating it as an export-function model.

To designate a model as an export-function model, open the Property Inspector. With the root level of
the model displayed and with no blocks highlighted, go to the Execution tab and select the Set
execution domain check box. Then, from the Domain list, select Export function.

You can also designate a model as an export-function model by setting the


IsExportFunctionModel parameter of the model.

set_param(ModelName,'IsExportFunctionModel','on')

Simulink displays a badge in the lower-left corner of the canvas to indicate that a model is
specified as an export-function model.

After you designate a model as an export-function model, Simulink performs compile-time checks to
warn you if the model does not meet export-function model requirements.

If you load a model that was created and saved in a release prior to R2022a, Simulink designates the
model as an export-function model if the model meets the requirements to be an export-function
model. In some cases, you may need to manually designate such a model as an export-function model.

10-128
Export-Function Models Overview

Sample Time for Function-Call Subsystems


In an export-function model, you can specify sample time for root-level function-call Inport blocks and
the Trigger block inside a root-level Function-Call Subsystem block or function-call Model block. The
following table shows how to specify these sample times.

Trigger block Sample Trigger block Sample Inport block Sample Function-call rate
time type time time during simulation
Triggered Not specified, -1 (inherited) For simulation, the
parameter is inactive. function-call initiator
connected to the Inport
block sets the rate of
simulation.
Specified discrete time Function-call initiator,
in test model, connected
to Inport block must
have a sample time
equal to the specified
discrete time for the
Inport block.

For simulation,
component executes at
the specified discrete
rate. If a function-call
source uses a different
sample, Simulink
displays an error
message.
Periodic -1 (inherited) or the -1 (inherited) This configuration is not
specified discrete time allowed. Simulink
Periodic function-call for the Inport block. displays an error
run-time checks apply if message.
the export-function
Specified discrete time. For simulation,
model is referenced
component executes at
from a Model block.
the specified discrete
sample time. If a
function-call source
uses a different sample
time, Simulink displays
an error message.

Execution Order for Root-Level Function-Call Inport Blocks


By specifying sample time and priority for function-call Inport blocks you can control the execution
order of function-call subsystems and function-call models during simulation. Alternatively, you can
use the Schedule Editor or a Stateflow chart to test scheduling. For more information, see “Test
Export-Function Model Simulation Using Schedule Editor” on page 10-114 and “Test Export-Function
Model Simulation Using Stateflow Chart” on page 10-109.

10-129
10 Conditional Subsystems

1 Specify sample time for simulation execution. Right-click a function-call Inport block, then select
Block parameters.
2 Select the Signal Attributes tab. In the Sample time box, enter a discrete time.
3 Specify the block priority for simulation. Right-click a function-call Inport block, then select
Properties.
4 In the Priority box, enter a priority value.
5 Display block execution order for simulation. On the Debug tab, select Information Overlays
, then from the drop-down dialog, select Execution Order. This display has no impact on the
generated code.

In the following export-function model, Function-Call Subsystem 2 with Sample time for Inport block
2 set to 0.01 (10 ms) runs before Function-Call Subsystem 1 with Sample time for Inport block 1 set
to 0.1 (100 ms).

Determine Relative Execution Order

Simulink compares function-call Inport block properties to determine their relative execution order
using the following rules:

1 Priority – higher priority (smaller number) executes first


2 Sample time – smaller sample time executes first
3 Port number – smaller port number executes first
4 If the OrderFunctionsByDependency parameter for the model is set to 'on', blocks that have
the same sample times are further sorted based on the relative data dependency of the functions
to which the blocks are connected.

To see the effect of the OrderFunctionsByDependency parameter, consider the following model.

10-130
Export-Function Models Overview

Inport block 1 executes last because it has a longer sample time than Inport blocks 2 and 3, which
have the same sample time. If OrderFunctionsByDependency is set to 'off', Inport block 2
executes before Inport block 3 based on their port numbers. The execution order is 2, 3, 1.

The OrderFunctionsByDependency parameter is set to 'off' by default. To turn it on, use this
command.

set_param(ModelName,'OrderFunctionsByDependency','on')

With the OrderFunctionsByDependency set to 'on', Inport block 3 executes before Inport block 2
because of the data dependency between function-call subsystems 2 and 3. The execution order is 3,
2, 1.

10-131
10 Conditional Subsystems

Note that the OrderFunctionsByDependency parameter affects only the model for which it is set.
The parameter does not propagate into referenced models.

When two blocks have different values for the Priority parameter, the block with the higher priority
executes first. If the Priority parameter is equal, the block with the faster rate (smaller sample time)
executes first. If Priority and sample time are the same for both of the blocks, the block with the
lower port number executes first. The exception is when a data dependency exists between the blocks
and OrderFunctionsByDependency is set to 'on', in which case the dependent block executes
after the block on which it depends.

Note When the simulation mode of the top model is accelerator or rapid accelerator, Simulink does
not perform run-time simulation checks for the execution order of root-level function-call Inport
blocks inside referenced export-function models.

Suppose that an export-function model has five root-level function-call Inport blocks, A to E, with
block properties as shown in the table. The blocks have no data dependencies, or
OrderFunctionsByDependency is set to 'off'. To determine their relative execution order,
Simulink compares their Priority parameters, sample times (if distinct and non-inherited), and port
numbers.

Root-level A B C D E
function-call
Inport block
Priority 10 30 40 40 30

10-132
Export-Function Models Overview

Root-level A B C D E
function-call
Inport block
Sample Time –1 0.2 0.1 0.1 –1
Port Number 5 4 3 2 1

• Block A has the highest priority of the five blocks. A executes first.
• B and E execute after A but before C and D. Since B and E have the same priority, Simulink
compares their sample times to determine execution order. E has a sample time of -1 (inherited),
which is smaller than 0.2, the sample time of B. E executes before B.
• C and D have the same priority and the same distinct, non-inherited sample times. The port
number for D (2) is smaller than C (3), so D executes before C.

The relative execution order for these function-call Inport blocks is A, E, B, D, C.

Nested Export-Function Models


Nested export-function models provide an additional layer of organization. The following model has
two referenced export-function models that are referenced from a Model block.

Note An export-function model cannot contain a referenced model with asynchronous function-call
inputs, but can contain function-call subsystems and function-call models. A model with asynchronous

10-133
10 Conditional Subsystems

function-call inputs can contain an export-function model, a function-call subsystem, or a function-call


model.

Export-Function Model with a Multi-Instanced Function-Call Model


You can use Function-Call Subsystem blocks or function-call Model blocks within an export-function
model. If you use a function-call Model block, you can also create multiple instances of the model.

1 Define your algorithm with a model that contains a Trigger block. Set Trigger type to
function-call.

2 Reference the model from a Model block. The result is a function-call model.

3 Connect a function-call Inport block and select the Output function call check box. Add signal
Inport and Outport blocks. Update the model (Ctrl+D). The result is an export-function model
with a function-call model.

4 Copy the referenced model and port blocks to create a second instance of the model. The two
instances are called by different root-level function-call Inport blocks in different tasks.

10-134
Export-Function Models Overview

Note A top-level non-export-function model that contains a reference model that is set up as a multi-
instance export function, does not support code generation. For more information, see Total number
of instances allowed per top model.

Export-Function Models and Models with Asynchronous Function-Call


Inputs
Export-function model capability is available for models with asynchronous function-call input ports,
also referred to as JMAAB-B models. You use these models primarily in the Simulink environment
where the Simulink scheduler calls the functions.

Comparison Export-Function Models Models with Asynchronous Function-


Characteristi Call Inputs
c
Definition These models have root-level function- These models have root-level function-
call Inport blocks that are not connected call Inport blocks connected to
to an Asynchronous Task Specification Asynchronous Task Specification blocks.
block. These Inport blocks trigger These Inport blocks trigger function-call
function-call subsystems or function-call subsystems or function-call models.
models (Model block with Trigger block).
Root-level Only blocks executing in a function-call Blocks executing in a non-function-call
blocks context are allowed at the root level. context are also allowed.
Data transfer Use data transfer indicators to interpret Use Rate Transition blocks to protect
simulation results. Data transfer in data transferred between function-call
export-function models is not protected subsystems running at different rates.
by default in generated code. For more For more information, see Rate
details, see “Latched Input Data for Transition.
Function-Call Subsystems” on page 10-
54.

10-135
10 Conditional Subsystems

Comparison Export-Function Models Models with Asynchronous Function-


Characteristi Call Inputs
c
Simulation These models support standalone These models support test model
support simulation and test model simulation in simulation in all simulation modes and
all simulation modes. standalone simulation in Normal,
Accelerator, and Rapid Accelerator
modes.
Code Top-model and standalone code Top-model and standalone code
generation generation are supported. generation are supported.
support

See Also
Function-Call Subsystem | Trigger | Model | Simulink Function | Message Triggered Subsystem | S-
Function

Related Examples
• “Create Export-Function Model” on page 10-98
• “Test Export-Function Model Simulation Using Input Matrix” on page 10-101
• “Test Export-Function Model Simulation Using Function-Call Generators” on page 10-105
• “Test Export-Function Model Simulation Using Stateflow Chart” on page 10-109
• “Test Export-Function Model Simulation Using Schedule Editor” on page 10-114
• “Generate Code for Export-Function Model” on page 10-118

10-136
Using Resettable Subsystems

Using Resettable Subsystems


The Resettable Subsystem block is a Subsystem block preconfigured as a starting point for creating a
subsystem that resets the block states each time the Reset port receives a trigger signal.

The following sections describe behavior of resettable subsystem and compare it with a subset of
Simulink blocks which have Reset ports or other ports that can be configured to behave like Reset
ports.

Behavior of Resettable Subsystems


This model shows that the behavior of block reset ports and resettable subsystems is the same. A
resettable subsystem enables you to reset the states of all blocks inside it. In this model, the
resettable subsystem contains an integrator block that is configured similar to the root-level
Integrator block, but the block does not have a reset port. The subsystem resets the states of the
integrator block inside it in the same manner as the reset port of the Integrator block.

10-137
10 Conditional Subsystems

You can see this behavior by running the model and viewing the output in the Scope block. You can
observe the following in the scope:

• reset trigger signal represents the signal at the Reset port.


• At the rising edge of the reset trigger signal, both the resettable subsystem and the Integrator
block reset the Integrator block state to its initial condition (in this case 0).

Between every two rising edges of the reset trigger signal, both the resettable subsystem and
the Integrator block execute. The output from the resettable subsystem and the Integrator block
are represented in the scope by resettable output and integrator output signal
respectively. As shown by the signals, both the outputs are same.

Using resettable subsystems over other methods of resetting states of your block or subsystem has
these advantages:

• When you want to reset the states of multiple blocks in a subsystem, displaying and connecting
the reset port of each block is cumbersome and makes the block diagram hard to read. Instead,
place all the blocks in a resettable subsystem and configure the Reset block in the subsystem.

10-138
Using Resettable Subsystems

• Some blocks, such as the Discrete State-Space block, have states but do not have reset ports. You
cannot reset these blocks individually, and you must reset the subsystem they are inside. In such
cases, it is useful to place these blocks in a resettable subsystem.
• You can also reset blocks in enabled subsystems by setting the States when enabling parameter
on the enable port to reset. However, for this behavior, you must disable the subsystem and then
reenable it at a later time step. To reset your block states at the same time step, use resettable
subsystems. For more information, see “Comparison of Resettable Subsystems and Enabled
Subsystems” on page 10-139.

All blocks in a resettable subsystem must have the same sample time, and they execute at every
sample time hit of the subsystem. Resettable subsystems and the model use a common clock.

Note If a resettable subsystem contains a Stateflow chart that contains a Simulink Function block,
blocks inside the Simulink Function block do not revert to their initial conditions when the resettable
subsystem executes.

Comparison of Resettable Subsystems and Enabled Subsystems


If you set States when enabling for the Enable block to reset, the enabled subsystem resets the
states of all blocks in the subsystem. However, you must disable the subsystem for at least one time
step and then reenable it for the states to reset.

In contrast, resettable subsystems always execute and reset the states of their blocks instantaneously.

This model shows the difference in the execution behavior of these subsystems. It contains an
enabled subsystem and a resettable subsystem whose control ports are connected to Pulse Generator
block. The resettable subsystem is set to reset on the rising edge of the control signal, and the
enabled subsystem has the States when enabling parameter set to reset in the Enable port.

The subsystems contain identical Discrete-Time Integrator blocks, whose input is the Constant block
at the root level of the model. The figure shows the contents of the resettable subsystem.

10-139
10 Conditional Subsystems

The figure shows the simulation output in the Scope block. You can observe the following in the
scope:

• control signal represents the control signal at the Enable port.


• When the control signal is 0, the enabled subsystem is disabled and the integrator does not
change its output while the resettable subsystem continues to execute. The rising edge of the
control signal triggers the reset port of the resettable subsystem and enables the enabled
subsystem. Both subsystems reset their states at this time step.
• The output from the enabled subsystem and the resettable subsystem are represented in the
scope by enabled output and resettable output signal respectively . Notice that the
enabled subsystem must be disabled for at least one time step before its states can be reset. The
resettable subsystem does not have this limitation.

10-140
Using Resettable Subsystems

Model Examples
For model examples, see:

• “Resettable Subsystems”
• “Discrete and Continuous Resettable Subsystems”

See Also
Enabled Subsystem | Enable | Resettable Subsystem | Reset | Integrator | Discrete-Time Integrator |
Pulse Generator

Related Examples
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Using Enabled Subsystems” on page 10-12

10-141
10 Conditional Subsystems

Simulink Functions Overview


What Are Simulink Functions?
A Simulink function is a computational unit that calculates a set of outputs when provided with a set
of inputs. The function header uses a notation similar to programming languages such as MATLAB
and C++. You can define and implement a Simulink function in several ways:

• Simulink Function block — Function defined using Simulink blocks within a Simulink Function
block.
• Exported Stateflow graphical function — Function defined with state transitions within a
Stateflow chart, and then exported to a Simulink model.
• Exported Stateflow MATLAB function — Function defined with MATLAB language statements
within a Stateflow chart, and then exported to a Simulink model.
• S-function — Function defined using an S-function block. For an example with an S-function,
open sfcndemo_simulinkfunction_getset.

What Are Simulink Function Callers?


A Simulink function caller invokes the execution of a Simulink function from anywhere in a model or
chart hierarchy.

• Function Caller block — Call a function defined in Simulink or exported from Stateflow. See
Function Caller.
• Stateflow chart transition — In a Stateflow chart, call a function defined in Simulink or exported
from Stateflow.
• MATLAB Function block — Call a function from a MATLAB language script.
• S-Function block — Call a function using system methods. See ssDeclareFunctionCaller
and ssCallSimulinkFunction.
• MATLAB System block — Call a function using a System object™ and the MATLAB language.

Connect to Local Signals


In addition to Argument Inport and Argument Outport blocks, a Simulink Function block can
interface to signals in the local environment of the block through Inport or Outport blocks. These
signals are hidden from the caller. You can use port blocks to connect and communicate between two
Simulink Function blocks or connect to root Inport and Outport blocks that represent external I/O.

You can also connect the Outport blocks to sink blocks that include logging (To File, To Workspace)
and viewing (Scope, Display) blocks. However, these blocks execute last after all other blocks.

A Simulink Function block can output a function-call event to an Outport block.

10-142
Simulink Functions Overview

Reusable Logic with Functions


Use functions when you need reusable logic across a model hierarchy. Consider an example where a
Simulink Function with reusable logic is defined in a Stateflow chart.

You can move the reusable logic from inside the Stateflow chart to a Simulink Function block. The
logic is then reusable by function callers in Simulink subsystems (Subsystem and Model blocks) and
in Stateflow charts at any level in the model hierarchy.

The result is added flexibility for structuring your model for reuse.

Note Input and output argument names (x2, y2) for calling a function from a Stateflow chart do not
have to match the argument names in the function prototype (u, y) of a Simulink Function block.

Input/Output Argument Behavior


The function prototype for a Simulink Function block can have identical input and output arguments.
For example, a function that filters noise could input a signal and then return the signal after
filtering.

mySignal = filter(mySignal)

You can call the function with a Function Caller block and add noise to a test signal to verify the
function algorithm.

10-143
10 Conditional Subsystems

When generating code for this model, the input argument for the Simulink Function block passes a
pointer to the signal, not a copy of the signal value.

void filter(real_T *rtuy_mySignal)


{
. . .

*rtuy_mySignal = model_P.DiscreteFilter_NumCoef * DiscreteFilter_tmp;


}

Shared Resources with Functions


Use functions when you model a shared resource, such as a printer. The model
slexPrinterExample uses Simulink Function blocks as a common interface between multiple
computers and a single Stateflow chart that models a printer process.

To open slexPrinterExample, see “Monitor Ink Status on Shared Printer Using Simulink
Functions”.

10-144
Simulink Functions Overview

How a Function Caller Identifies a Function


The function interface uses MATLAB syntax to define its input and output arguments. The name of
the function is a valid ANSI® C identifier. The model hierarchy can contain only one function
definition with the identified function name. Simulink verifies that:

• The arguments in the Function prototype parameter for a Function Caller block matches the
arguments specified in the function. For example, a function with two input arguments and one
output argument appears as:
y = MyFunction(u1, u2)
• The data type, dimension, and complexity of the arguments must agree. For a Function Caller
block, you can set the Input argument specifications and Output argument specifications
parameters, but usually you do not need to specify these parameters manually. Simulink derives
the specification from the function.

The only case where you must specify the argument parameters is when the Function Caller block
cannot find the function in the model or in any child model it references. This situation can happen
when the Function Caller block and called function are in separate models that are referenced by
a common parent model. See “Simulink Function Blocks in Referenced Models” on page 10-171
and “Argument Specification for Simulink Function Blocks” on page 10-168.

10-145
10 Conditional Subsystems

Reasons to Use a Simulink Function Block


Function-Call Subsystem blocks with direct signal connections for triggering provide better signal
traceability than Simulink Function blocks, but Simulink Function blocks have other advantages.

• Eliminate routing of signal lines. The Function Caller block allows you to execute functions
defined with a Simulink Function block without a connecting signal line. In addition, functions and
their callers can reside in different models or subsystems. This approach eliminates signal routing
problems through a hierarchical model structure and allows greater reuse of model components.
• Use multiple callers to the same function. Multiple Function Caller blocks or Stateflow charts
can call the same function. If the function contains state (for example, a Unit Delay block), the
state is shared between the different callers.
• Separate function interface from function definition. Functions separate their interface
(input and output arguments) from their implementation. Therefore, you can define a function
using a Simulink Function block, an exported graphical function from Stateflow, or an exported
MATLAB function from Stateflow. The caller does not need to know how or where the function was
implemented.

Choose a Simulink Function or Reusable Subsystem


A consideration for using a Simulink Function block or a Subsystem block has to do with shared state
between function calls. A Simulink Function block has shared state while a Subsystem block, even if
specified as a reusable function, does not.

• For a Simulink Function block, when one block has multiple callers, code is always generated for
one function. If the Simulink Function block contains blocks with state (for example, Delay or
Memory), the state is persistent and shared between function callers. In this case, the order of
calls is an important consideration.
• For a Subsystem block, when a block has multiple instances and is configured as a reusable
function, code is usually generated for one function as an optimization. If the Subsystem block
contains blocks with state, code is still generated for one function, but a different state variable is
passed to the function. State is not shared between the instances.

When Not to Use a Simulink Function Block


Simulink Function blocks allow you to implement functions graphically, but sometimes using a
Simulink Function block is not the best solution.

For example, when modeling a PID controller or a digital filter and you have to model the equations
defining the dynamic system. Use an S-Function, Subsystem, or Model block to implement systems of
equations, but do not use a Simulink Function block, because these conditions can occur:

• Persistence of state between function calls. If a Simulink Function block contains any blocks
with state (for example, Unit Delay or Memory), then their state values are persistent between
calls to the function. If there are multiple calls to that function, the state values are also persistent
between the calls originating from different callers.
• Inheriting continuous sample time. A Simulink Function block cannot inherit a continuous
sample time. Therefore, do not use this block in systems that use continuous sample times to
model continuous system equations.

10-146
Simulink Functions Overview

Tracing Simulink Functions


Visually display connections between a Simulink function and their callers with lines that connect
callers to functions:


Turning on/off tracing lines — On the Debug tab, under Information Overlays , click
Connectors. Select Function Connectors option from the Connectors pane that appears on the
Simulink canvas.
• Direction of tracing lines — Lines connected at the bottom of a block are from a function caller.
Lines connected at the top of a block are to a Simulink function or a subsystem containing the
function.

• Navigation to functions — A function caller can be within a subsystem.

10-147
10 Conditional Subsystems

Navigate from a caller in a subsystem to a function by first opening the subsystem, and then
clicking a link to the function.

If the function is at the root level of a model, the function opens. If the function is within a
subsystem, the subsystem containing the function opens.

Monitor Ink Status on a Shared Printer Using Simulink Functions

After selecting Function Connectors, the model slexPrinterExample shows the relationships
between callers and functions.

In this example, the Function Caller in the Simulink Function block addPrintJob, calls the exported
Stateflow function queuePrintJob. The subchart Busy calls the Simulink Function block
printerInk. Tracing lines are drawn into and out of the Stateflow chart.

To open slexPrinterExample, see “Monitor Ink Status on Shared Printer Using Simulink
Functions”.

10-148
Simulink Functions Overview

Highlight and Animate Function Calls


Use animation to highlight function calls.

This example shows a still of an animated Simulink function call.

10-149
10 Conditional Subsystems

To access animation, in the toolstrip, on the Debug tab, in the Event Animation section, set the
animation speed to Slow, Medium, or Fast.

Event Animation is visible when you have event blocks in your model, such as blocks from the
Messages & Events library, Stateflow charts, Function-Call Subsystem blocks, Simulink functions, or
SimEvents® blocks.

See Also
Simulink Function | Argument Inport | Argument Outport | MATLAB Function | Function Caller

Related Examples
• “Monitor Ink Status on Shared Printer Using Simulink Functions”
• “Add a Simulink Function to a Model” on page 10-151
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-150
Add a Simulink Function to a Model

Add a Simulink Function to a Model


Simulink functions have an interface with input and output arguments similar to programming
languages. You can create the function definition for a Simulink function using:

• Simulink blocks within a Simulink Function block.


• Stateflow state transitions in a graphical function exported from a Stateflow chart.
• MATLAB code in a MATLAB function exported from a Stateflow chart.

The following sections show how to create a Simulink function for the function y = timestwo(x).
The function multiplies a value (x) from a caller by 2, and then sends the calculated value (y) back to
the caller. To call the function, see “Call a Simulink Function from a Model” on page 10-159.

Simulink Functions and Function Callers

The model named ex_simulink_functions_and_function_callers shows multiple ways to


create and call Simulink functions.

10-151
10 Conditional Subsystems

The model creates Simulink functions in three ways:

• Simulink Function block


• Stateflow chart that exports a graphical function
• Stateflow chart that exports a MATLAB function

The model calls each of the Simulink functions in three ways:

• Function Caller block


• MATLAB Function block
• Stateflow chart

10-152
Add a Simulink Function to a Model

To visually display the connections between the Simulink functions and their callers with lines, on the
Debug tab, under Information Overlays, the Function Connectors button is selected.

Create Simulink Function Using Simulink Function Block


Set up a Simulink Function block to receive data through an input argument from a function caller,
and then pass a calculated value back through an output argument.

1 Add a Simulink Function block to your model.


2 On the block face, enter the function prototype.

y = timestwo(x)

3 Double-click the block to open the subsystem defining the function algorithm.
4 Add a Gain block and set the Gain parameter to 2.

Create Simulink Function Using Exported Graphical Function from


Stateflow Chart
Set up a graphical function in a Stateflow chart to receive data through an input argument from a
function caller and pass the calculated value back through an output argument. Set chart parameters
to export the function to a Simulink model.

Define Graphical Function in Stateflow Chart

Create a graphical function in a Stateflow chart. Define the function interface and function definition.

1 Add a Stateflow Chart to your Simulink model. Double-click on the Simulink block diagram. In
the search box, enter chart, and then from the search results, select Chart.
2 Double-click to open the chart.
3 Add a graphical function. From the left-side toolbar, click and drag the graphical function icon
onto the chart.
4 Define the function interface. In the function box, replace the ? with the function interface y =
timestwo(x).
5 Define the function algorithm. Click the transition arrow and replace the ? with{y = 2*x}.

10-153
10 Conditional Subsystems

Test Graphical Function

Test the graphical function within the Stateflow chart before exporting to a Simulink model.

1 Add a default transition in the chart for testing the function. From the left-side toolbar, click and
drag a default transition arrow onto the chart.
2 Double-click the arrow and replace the ? with {y1 = timestwo(x1)}.
3 Add an input port to the chart. Open the Model Explorer. In the left pane, select Chart. From the
menu, select Add > Data. Set Name to x1 and Scope to Input.
4 Add an output port to the chart. From the menu, select Add > Data. Set Name to y1 and Scope
to Output.
5 Add a Sine Wave block to provide test data for the input and a Scope block to view results from
the output.

6 Run a simulation.

Set Argument Parameters for Graphical Function

Specify the size, complexity, and type of the function input and output arguments. A chart can export
only functions with fully specified prototypes.

1 Open the Model Explorer. On the Modeling tab and from the Design section, select Model
Explorer .
2 In the left pane, select the graphical function.

3
From the Column View list in the middle pane, select Stateflow. Select the filter icon ,
and then from the toggle list, select All Stateflow Objects. From the center pane table, select
an input or output argument.

10-154
Add a Simulink Function to a Model

4 In the right pane, set Size to 1 (scalar), Set Complexity to Off (real number), and set Type to
double.

5 Repeat steps 2 and 3 with the output function argument y.

Set Export Function Parameters for Graphical Function

Set parameters to export a graphical function to a Simulink model from a Stateflow chart during a
simulation.

1 Open the Model Explorer.


2 In the left pane, select the chart containing the graphical function.

3 In the property dialog box on the right side, select the Export Chart Level Functions check
box, click the Apply button, and then select the Treat Exported Functions as Globally Visible
check box.

If you are calling the exported graphical function from another Stateflow chart (not the chart that
exported the graphical function), you do not need to select the Treat Exported Functions as
Globally Visible check box.

10-155
10 Conditional Subsystems

Create Simulink Function Using Exported MATLAB Function from


Stateflow Chart
Set up a MATLAB function in a Stateflow chart to receive data through an input argument from a
function caller and then pass a calculated value back through an output argument. Set chart
parameters to export the function to a Simulink model.

Define MATLAB Function in Stateflow Chart

Create a MATLAB function in a Stateflow chart. Define the function interface and function definition.

1 Add a Stateflow Chart to your Simulink model. Double-click on the block diagram. In the search
box, enter chart, and then from the search results, select Chart.
2 Open the chart.
3
Add a MATLAB function. From the left-side toolbar, click and drag the graphical function icon
onto the chart.
4 Define the function interface. In the function box, replace the ? with the function interface y =
timestwo(x).

5 Double-click the function box to open the MATLAB code editor. Define the function algorithm
with the MATLAB code.

Test MATLAB Function

Test the MATLAB function within a Stateflow chart before exporting to a Simulink model.

1 Add a default transition in the chart for testing the function. From the left-side toolbar, click and
drag a default transition arrow onto the chart.
2 Double-click the arrow and replace the ? with {y1 = timestwo(x1)}.
3 Add an input port to the chart. Open the Model Explorer. In the left pane, select Chart. From the
menu, select Add > Data. Set Name to x1 and Scope to Input.
4 Add an output port to the chart. From the menu, select Add > Data. Set Name to y1 and Scope
to Output.
5 Add a Sine Wave block to provide test data for the input and a Scope block to view results from
the output.

10-156
Add a Simulink Function to a Model

6 Run a simulation.

Set Argument Parameters for MATLAB Function

Specify the size, complexity, and type of the function input and output arguments. A chart can export
only functions with fully specified prototypes.

1 Open the Model Explorer. On the Modeling tab and from the Design section, select Model
Explorer .
2 In the left pane, select the MATLAB function.

3
From the Column View list in the middle pane, select Stateflow. Select the filter icon ,
and then from the toggle list, select All Stateflow Objects. From the center pane table, select
an input or output argument.

4 In the right pane, set Size to 1 (scalar), Set Complexity to Off (real number), and set Type to
double.

10-157
10 Conditional Subsystems

5 Repeat steps 2 and 3 with the output function argument y.

Set Export Function Parameters for MATLAB Function

Set parameters to export a MATLAB function from a Stateflow chart during a simulation.

1 Open the Model Explorer.


2 From the left pane, select the chart containing the MATLAB function.

3 In the property dialog box on the right side, select the Export Chart Level Functions check
box, click the Apply button, and then select the Treat Exported Functions as Globally Visible
check box.

If you are calling the exported MATLAB function from another Stateflow chart (not the chart that
exported the MATLAB function), you do not need to select the Treat Exported Functions as
Globally Visible check box.

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-158
Call a Simulink Function from a Model

Call a Simulink Function from a Model


Simulink functions have an interface with input and output arguments similar to programming
languages. Simulink function callers send data through input arguments to Simulink functions,
execute the function, and then receive data back from the function through output arguments. You
can call a Simulink function using:

• Function Caller blocks


• MATLAB Function blocks
• Stateflow charts

The following sections show how to call a Simulink function. The function y = timestwo(x)
multiplies a value (x) from a caller by 2, and then sends the calculated value (y) back to the caller. To
create the functions, see “Add a Simulink Function to a Model” on page 10-151.

Simulink Functions and Function Callers

The model named ex_simulink_functions_and_function_callers shows multiple ways to


create and call Simulink functions.

10-159
10 Conditional Subsystems

The model creates Simulink functions in three ways:

• Simulink Function block


• Stateflow chart that exports a graphical function
• Stateflow chart that exports a MATLAB function

The model calls each of the Simulink functions in three ways:

• Function Caller block


• MATLAB Function block
• Stateflow chart

10-160
Call a Simulink Function from a Model

To visually display the connections between the Simulink functions and their callers with lines, on the
Debug tab, under Information Overlays, the Function Connectors button is selected.

Use a Function Caller Block to Call a Simulink Function Block


Set up a Function Caller block to send data through an input argument to a Simulink Function block,
and receive data back from the function through an output argument.

1 Add a Function Caller block to your model.


2 Open the Function Caller dialog box. In the Function prototype box, enter y = timestwo(x).
This function prototype creates an input port x and output port y on the Function Caller block.

Note Typing in a blank text box displays a list of previously created function prototypes that
match the text you are typing.
3 Add and setup a Simulink Function block as described in “Create Simulink Function Using
Simulink Function Block” on page 10-153.

Note The function and argument names for the Simulink Function block and the Function
prototype for the Function Caller block must match exactly.

Test the function call

1 Add a Sine Wave block to provide test data for the input and a Scope block to view results from
the output.

10-161
10 Conditional Subsystems

2 Run a simulation. The input sine wave with an amplitude of 2 is doubled.

Use a MATLAB Function Block to Call a Simulink Function Block


Set up a MATLAB Function block to send data through an input argument to a Simulink Function
block, and receive data back from the function through an output argument.

1 Add a MATLAB Function block to your model.


2 Double-click the block, which opens the MATLAB editor. Enter the function call y1 =
timestwo(x1).

Note The argument names for the function you define in the MATLAB Function block do not
have to match the argument names for the function that you define with a Simulink Function
block. For a Function Caller block that calls a Simulink Function block, argument names must
match.

10-162
Call a Simulink Function from a Model

Note MATLAB Function blocks only support discrete and fixed-in-minor sample times.
3 Add and setup a Simulink Function block as described in “Create Simulink Function Using
Simulink Function Block” on page 10-153.

Test the function call

1 Add a Sine Wave block to provide test data for the input and a Scope block to view results from
the output.

2 For the Sine Wave block, set the Sample time to 0.01. For the model, open the Configuration
Parameters dialog box to the solver pane. Set Type to Fixed-step and Fixed-step size to 0.01.
3 Run a simulation.

Use a Stateflow Chart to Call a Simulink Function Block


Set up a Stateflow chart to send data through an input argument to a Simulink Function block, and
receive data back from the function through an output argument.

1 Add a Stateflow chart to your Simulink model. Double-click on the Simulink block diagram. In the
search box, enter chart, and then from the search results, select Chart.
2 Double-click the chart to open it.
3 From the left-side toolbar, click and drag the default transition icon onto the chart.
4 Add an input port to the chart. Open the Model Explorer. In the left pane, select Chart. From the
menu, select Add > Data. Set Name to x1 and Scope to Input.

10-163
10 Conditional Subsystems

Note The argument names for the function you define in the Stateflow chart do not have to
match the argument names for the function that you define with a Simulink Function block. For a
Function Caller block that calls a Simulink Function block, argument names must match.
5 Add an output port to the chart. From the menu, select Add > Data. Set Name to y1 and Scope
to Output.
6 Add a Sine Wave block and connect signal output to the chart input port. Add a Scope block and
connect input to the chart output port.
7 Edit transition code to call a function. For example, to call the Simulink Function block, enter:

{y1=timestwo_sf(x1);}

Note Input signals to a Stateflow chart can be either continuous or discrete.


8 Add and setup a Simulink Function block as described in “Create Simulink Function Using
Simulink Function Block” on page 10-153.

Test the function call

1 Add a Sine Wave block to provide test data for the input and a Scope block to view results from
the output.

2 For the Sine Wave block, set the Sample time to 0.01. For the model, open the Configuration
Parameters dialog box to the solver pane. Set Type to Fixed-step and Fixed-step size to 0.01.
3 Run a simulation.

10-164
Call a Simulink Function from a Model

Call a Simulink Function Block from Multiple Sites


If you call a Simulink Function block from multiple sites, all call sites share the state of the function.
For example, suppose that you have a Stateflow chart with two calls and two Function Caller blocks
with calls to the same function.

A function defined with a Simulink Function block is a counter that increments by 1 each time it is
called with an input of 1.

The Unit Delay block has state because the block value is persistent between calls from the two
Function Caller blocks and the Stateflow chart. Conceptually, you can think of this function being
implemented in MATLAB code:
function y = counter(u)
persistent state;
if isempty(state)
state = 0;
end
y = state;
state = state + u;

10-165
10 Conditional Subsystems

Simulink initializes the state value of the Unit Delay block at the beginning of a simulation. After that,
each time the function is called, the state value is updated.

In this example, the output observed in Scope1 increments by 4 at each time step. Scope2, Scope3,
and Scope4 show a similar behavior. The only difference is a shift in the observed signal due to the
execution sequence of the function calls.

Diagnostic Settings With Multiple Callers

For multiple callers that share a function and have different sample time rates, data integrity and
consistency of real-time code might be a problem. Consider controlling the severity of diagnostics.

Select a Fixed-step solver. Set the Treat each discrete rate as a separate task parameter to:

• Clear (single-tasking), and then set the Single task data transfer parameter to none (default),
warning, or error.
• Select (multi-tasking), and then set the Multitask data transfer parameter to error (default) or
warning.

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177

10-166
Call a Simulink Function from a Model

• “Scoped Simulink Function Blocks in Subsystems” on page 10-181


• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-167
10 Conditional Subsystems

Argument Specification for Simulink Function Blocks


A Simulink Function block is considered to be out of scope of a Function Caller block when the two
blocks are in separate models referenced by a common parent model.

• When a Simulink Function block is within the scope of a Function Caller block, the Function Caller
block can inherit the input and output argument specifications. You do not have to specify
parameters of the Function Caller block.
• When a Simulink Function block is outside the scope of the Function Caller block, you must
specify the input and output argument specifications of a Function Caller block.

Example Argument Specifications for Data Types


This table lists possible input and output argument specifications.

Simulink Function Block Function Caller Block Description


Data Type Expression
double double(1.0) Double-precision scalar.
double double(ones(12,1)) Double-precision column vector of
length 12.
single single(1.0) Single-precision scalar.
int8, int16, int32 int8(1), int16(1), Integer scalars.
int32(1)
int32([1 1 1]) Integer row vector of length 3.
int32(1+1i) Complex scalar whose real and
imaginary parts are 32-bit integers.
uint8, int16, int32 uint8(1), uint16(1), Unsigned integer scalars.
uint32(1)
boolean boolean(true),boolean(fa Boolean, initialized to true (1) or false
lse) (0).
fixdt(1,16) fi(0,1,16) 16-bit fixed-point signed scalar with
binary point set to zero.
fixdt (signed, fi (value, signed,
word_length) word_length) Fixed-point numbers can have a word
size up to 128 bits.
fixdt(1,16,4) fi(0,1,16,4) 16-bit fixed-point signed scalar with
binary point set to 4.
fixdt(1,16,2^0,0) fi(0,1,16,2^0,0) 16-bit fixed-point signed scalar with
slope set to 2^0 and bias set to 0.
Bus: <object name> bus object name Simulink.Bus object
Enum: <class name> enumerated value Enumerated type set to an
enumerated value.
<alias name> parameter object name Simulink.Parameter object with
the DataType parameter set to a
Simulink.AliasType object and the
Value parameter set to a value.

10-168
Argument Specification for Simulink Function Blocks

Input Argument Specification for Bus Data Type


Create a bus with two signals, and then specify the Input argument specification parameter for a
Function Caller block. The Function Caller block calls a Simulink Function block that accepts the bus
as input.

A bus input to a Function Caller block must be a nonvirtual bus using a bus object.

1 Create a Simulink bus object myBus.

myBus = Simulink.Bus;
2 Add elements A and B.

myBus.Elements(1).Name = 'A';
myBus.Elements(2).Name = 'B';
3 For the Function Caller block dialog box, set the Input argument specification parameter to
myBus.
4 For the dialog box of an Argument Inport block within the Simulink Function block, set the Data
type parameter to Bus: myBus.

Input Argument Specification for Enumerated Data Type


Create an enumerated data type for the three primary colors, and then specify the Input argument
specifications parameter for a Function Caller block. The Function Caller block calls a Simulink
Function block that accepts a signal with the enumerated type as input.

1 Create a MATLAB file for saving the data type definition. On the MATLAB toolstrip, select New >
Class.
2 In the MATLAB editor, define the elements of an enumerated data type. The class BasicColors
is a subclass of the class Simulink.IntEnumType.

classdef BasicColors < Simulink.IntEnumType


enumeration
Red(0)
Yellow(1)
Blue(2)
end
end
3 Save the class definition in a file named BasicColors.m.
4 For the Function Caller block dialog box, set the Input argument specifications to
BasicColors(0).
5 For the dialog box of an Argument Inport block within the Simulink Function block, set the Data
type parameter to Enum: BasicColors.

Input Argument Specification for an Alias Data Type


Create an alias name for the data type single, and then specify the Input argument specification
parameter for a Function Caller block. The Simulink Function block called by the Function Caller
block also uses the alias name to define the input data type.

1 Create a Simulink alias data type object myAlias.

10-169
10 Conditional Subsystems

myAlias = Simulink.AliasType;
2 Assign a data type.

myAlias.BaseType = 'single';
3 Create a Simulink parameter object myAlias_parameter and assign the alias name to the
DataType parameter.

myAlias_parameter = Simulink.Parameter;
myAlias_parameter.DataType = 'myAlias';
myAlias_parameter.Value = 1;
4 For the Function Caller block dialog box, set the Input argument specification parameter to
myAlias_parameter.
5 For the dialog box of an Argument Inport block dialog box within the Simulink Function block,
set the Data type parameter to myAlias.

See Also
Blocks
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Objects
Simulink.Bus

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Model Client-Server Communication Using Function Ports” on page 10-195
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-170
Simulink Function Blocks in Referenced Models

Simulink Function Blocks in Referenced Models


You can place Simulink Function blocks and function callers (such as Function Caller blocks and
Stateflow charts) in a referenced model, but doing so requires some special considerations:

• The referenced model must follow export-function model rules and be designated as an export-
function model. See “Export-Function Models Overview” on page 10-125.
• Sometimes, you must explicitly define the argument data types for a Function Caller block.

These examples show four relationships between Function Caller blocks, Simulink Function blocks,
and referenced models. To visually display the connections between the Simulink functions and their
callers with lines, on the Debug tab, under Information Overlays, the Function Connectors
button is selected.

Simulink Function Block in Referenced Model

This example shows a parent model that contains a Function Caller block and a referenced model
that contains a Simulink Function block. The referenced model must follow export-function model
requirements.

Open the model named ex_referenced_model_with_simulink_function_block.

The Function Caller block can determine the argument data types of the function. You do not need to
define the Input argument specifications and Output argument specifications parameters of
the Function Caller block.

By default, the Simulink Function block is scoped to the model. Therefore, you must qualify a call to
the function name with the Model block name.

Open referenced model ex_Model_B.

10-171
10 Conditional Subsystems

Open the Simulink Function block.

Referenced model ex_Model_B contains a Simulink Function block that defines a function for
multiplying the input by 2. This model satisfies export-function model requirements and is configured
as an export-function model. For more information, see “Export-Function Models Overview” on page
10-125.

When the Trigger block in the Simulink Function block has its Function visibility block parameter
set to global, you can reference the model that contains the Simulink Function block anywhere in
the model hierarchy. For example, you can place a Model block that references model ex_Model_B in
a subsystem.

Function Caller Block in Referenced Model

This example shows a parent model that contains a Simulink Function block and a referenced model
that contains a Function Caller block. To use this modeling pattern, the Function visibility
parameter of the Trigger block in the Simulink Function block must be set to global.

Open the parent model named ex_referenced_model_with_function_caller_block.

10-172
Simulink Function Blocks in Referenced Models

For the parent model, set the solver type to Variable-step or Fixed-step.

The referenced model, named ex_Model_A, contains a Function Caller block.

For the Function Caller block to find the function in ex_Model_A, set the Function visibility
parameter of the Trigger block in the Simulink Function block to global and specify the Function
Caller block argument parameters:

• Input argument specifications: Specify to match the Simulink Function block input argument
data types, for example, double(1.0).
• Output argument specifications: Specify to match the Simulink Function block output
argument data types, for example, double(1.0).

For the Simulink Function block, specify the argument specification with the Data type parameter of
the Input Argument and Output Argument blocks.

Function and Function Caller Blocks in Separate Referenced Models

This example shows a parent model that contains two referenced models. One referenced model has
a Function Caller block, while the other referenced model has a Simulink Function block that
specifies a global function.

Open the parent model named


ex_referenced_model_with_simulink_function_and_function_caller.

Referenced model ex_Model_B1 contains a Simulink Function block.

10-173
10 Conditional Subsystems

The Simulink Function block defines a global function named timestwo, which multiples input by 2.
To specify that the function is global, in the Simulink Function block, the Trigger block sets Function
visibility to global.

Referenced model ex_Model_B1 satisfies export-function model requirements and is configured as


an export-function model. For more information, see “Export-Function Models Overview” on page 10-
125.

Referenced model ex_Model_A1 contains a Function Caller block.

The Function Caller block calls the global timestwo function without qualifying the call to the
function. The Function Caller block specifies a Function prototype of y = timestwo(u). The
Function Caller block also specifies the Input argument specifications and Output argument
specifications parameters.

Suppose you want to call a function that is scoped to a separate referenced model. For example, in
ex_Model_B1, set Function visibility of the Trigger block to scoped.

When the function is scoped to a separate referenced model, the Function Caller block must qualify
the call to the function with the file name, not the block name, of the model where the function is
expected to be resolved. For example, set the Function prototype parameter of the Function Caller
block to y = ex_Model_B1.timestwo(u).

You can also use function ports to call a Simulink function in a referenced model from another
referenced model. For more information, see “Model Client-Server Communication Using Function
Ports” on page 10-195.

Function and Function Caller in Same Model

This example shows a parent model that contains one referenced model. The referenced model
contains both a Function Caller block and a scoped Simulink Function block.

10-174
Simulink Function Blocks in Referenced Models

Open the model named FunctionAndFunctionCaller.

Open the referenced model named ex_Model_C.

When the referenced model is not configured as an export-function model, it does not need to follow
export-function model rules. Export-function model rules do not allow a Function Caller block at the
top level of an export-function model. For more information, see “Export-Function Models Overview”
on page 10-125.

When the Simulink Function block specifies a scoped function, as in ex_Model_C, a model hierarchy
supports multiple instances of the referenced model.

When the Simulink Function block specifies a global function, a model hierarchy supports only one
instance of the referenced model. Otherwise, multiple Model blocks attempt to define functions with
the same name and the software throws an error.

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Related Examples
• “Simulink Functions Overview” on page 10-142

10-175
10 Conditional Subsystems

• “Add a Simulink Function to a Model” on page 10-151


• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-176
Scoped, Global, and Port-Scoped Simulink Function Blocks Overview

Scoped, Global, and Port-Scoped Simulink Function Blocks


Overview
Defining the visibility of functions can help you to avoid name space conflicts when integrating your
referenced models. A Simulink Function block defines the visibility of its function in relationship to
the subsystem or model containing the block as either scoped, global, or port-scoped. By default,
Simulink Function blocks are scoped.

• Function Visibility. A scoped function is visible in its hierarchy. A function caller located at the
same level as the function, or one or more levels below can refer to the function. A global function
is visible across a model hierarchy. This means that a function caller located anywhere in the
current model or in the parent model hierarchy can refer to the function. A port-scoped function is
visible only to a particular exporting function port in the current model, and is not visible
elsewhere in the model hierarchy. The function can be called only from outside the current model,
and only through the exporting function port.
• Function accessibility is determined by the visibility of a function and the location of the function
caller relative to the Simulink Function block. For function callers one hierarchical level above the
function, qualify the function name with the virtual Subsystem block name or Model block name.
• Function exporting refers to functions exported from models. A function with global visibility,
placed anywhere in an export-function model, is exported to the top level of a model hierarchy in
addition to the model interface. A function with scoped visibility at the root level of an export-
function model is exported to the model interface. In both these cases, you can access the
exported function outside of the model. A function with port-scoped visibility must be placed at the
root level of an export-function model, and can be accessed by function callers in other export-
function models only through a connection between function ports in the respective models.

Use the Function visibility parameter for the Trigger block within a Simulink Function block to set
the function visibility to either scoped, global, or port. For a port-scoped function, specify the
name of the port in the Scope to port field.

10-177
10 Conditional Subsystems

Summary of Simulink Function Block Visibility and Access

Simulink Function Visibility Function Accessibility Function Exporting


Function
Block
Virtual scoped Function caller inside Does not apply.
Subsystem hierarchy or at parent level.
Function names at the
same hierarchical level Function caller inside
must be unique. Subsystem block hierarchy –
Unqualified, fcn(). See
Resolve to a Function
Hierarchically in “Scoped
Simulink Function Blocks in
Subsystems” on page 10-181.

Function caller at parent level


– Qualified with subsystem
block name,
subsystem.fcn(). See
Resolve to a Function by
Qualification in “Scoped
Simulink Function Blocks in
Subsystems” on page 10-181.
global Function caller at any level of Function at any level of
hierarchy down or up. model exported to the
Function name must be global name space of
unique. Function caller at any level of the top-level model.
hierarchy – Unqualified,
fcn().
port visibility not allowed. Does not apply. Does not apply.
Atomic scoped Function caller only inside Does not apply.
Subsystem hierarchy
Function names at the
same hierarchical level Function caller inside
must be unique Subsystem block hierarchy –
Unqualified, fcn(). See
Resolve to a Function
Hierarchically in “Scoped
Simulink Function Blocks in
Subsystems” on page 10-181.

Function caller at parent level


– not allowed.
global visibility not Function call not allowed. Does not apply.
allowed.
port visibility not allowed. Does not apply. Does not apply.

10-178
Scoped, Global, and Port-Scoped Simulink Function Blocks Overview

Simulink Function Visibility Function Accessibility Function Exporting


Function
Block
Model scoped Function caller inside Function at the root
hierarchy or at parent level. level of a model
Function names must be exported to the model
unique at the model root Function caller inside interface.
level. Subsystem block hierarchy –
unqualified, fcn(). See
Resolve to a Function
Hierarchically in “Scoped
Simulink Function Blocks in
Models” on page 10-188.

Function caller at parent level


– Qualified with Model block
name, model_block.fcn().
See Resolve to a Function by
Qualification in “Scoped
Simulink Function Blocks in
Models” on page 10-188.
global Function caller at any level of Function at any level of
hierarchy down or up. model exported to the
Function name must be global name space of
unique. Function caller at any level of the top-level model.
hierarchy – Unqualified,
fcn().
port Function caller associated with Function not visible
invoking function port except through
Function names at the connected to exporting exporting function port.
model root level do not function port to which function
have to be unique if scoped is scoped. Qualified with
to different ports. invoking port name,
PortName.fcn().

For more information, see


“Model Client-Server
Communication Using Function
Ports” on page 10-195.

See Also
Blocks
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function |
Function Element | Function Element Call

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151

10-179
10 Conditional Subsystems

• “Simulink Function Blocks in Referenced Models” on page 10-171


• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Model Client-Server Communication Using Function Ports” on page 10-195
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-180
Scoped Simulink Function Blocks in Subsystems

Scoped Simulink Function Blocks in Subsystems


The scope of a Simulink function is defined in its parent subsystem within the context of a model. If
you place a function in any Subsystem block, access to the function from outside the model is
prohibited by default. In both cases, the Trigger block Function visibility parameter is set to
scoped. The Simulink Function block can be located:

• In a virtual subsystem — Call the function from within the containing Subsystem block hierarchy
without qualifying the function name, or call the function from outside the subsystem by qualifying
the function name with the subsystem block name.
• In an atomic or non-virtual subsystem — Call the function from within the containing Subsystem
block hierarchy without qualifying the function name. Accessing the function from outside of the
subsystem is prohibited.

Resolve to a Function Hierarchically


Placing a scoped Simulink Function block within any Subsystem block (virtual or atomic) limits
access to the function and removes the function name from the global name space. When a function
caller resolves to a function hierarchically, it looks for the function using the following rules:

• Resolution Rule 1: Is the scoped Simulink Function block in the current Subsystem block with the
function caller?
• Resolution Rule 2. If the scoped function is not in the current subsystem, is the scoped Simulink
Function block in a parent or grandparent Subsystem block one or more levels above the function
caller, or in a parent Model?

If a function caller resolves to a function hierarchically, you can call the function without qualifying
the function name:

• Function caller located at the same hierarchic level as the function. In this case, the function
caller finds the scoped function in the current subsystem (Resolution Rule 1).

10-181
10 Conditional Subsystems

• Function caller located in a Subsystem block one or more Subsystem block levels below the
hierarchic level of the Simulink Function block. The function caller hierarchy cannot include a
Model block since the function caller cannot cross model reference boundaries. In this case, the
function caller didn't find the scoped function in the current subsystem, but it found the function
in the parent subsystem (Resolution Rule 2).

In this case, the function caller didn't find the scoped function in the current subsystem, but it
found the function in the parent model (Resolution Rule 2).

10-182
Scoped Simulink Function Blocks in Subsystems

• You can also call a Simulink Function block in a Subsystem block without qualification from a
MATLAB Function block or a Stateflow chart within the block.

Resolve to a Function by Qualification


When you place a Simulink Function block in a virtual Subsystem block, the function name is not
visible outside of the subsystem. However, you can call the function by qualifying the function name
with the Subsystem block name. When a function caller resolves to a qualified function hierarchically,
it looks for the virtual Subsystem block containing the function using the following rules:

• Resolution Rule 1: Is the virtual Subsystem block in the current component with the function
caller? A component can be a Subsystem block or Model.
• Resolution Rule 2. If the virtual Subsystem block is not in the current component, is the virtual
Subsystem block in a parent or grandparent component one or more levels above the function
caller?

If a function caller resolves to a virtual Subsystem block with a scoped function, you can call the
function by qualifying the function name:

• Function caller located outside of the subsystem one hierarchic level above the function. In this
case, the function caller finds the Subsystem block with the scoped function in the current model
(Resolution Rule 1).

10-183
10 Conditional Subsystems

• Calling the function from a Stateflow chart outside the subsystem one hierarchic level above the
function. In this case, the function caller finds the Subsystem block with the scoped function in the
current model (Resolution Rule 1).

10-184
Scoped Simulink Function Blocks in Subsystems

• Function caller is in another subsystem at the same hierarchic level as the function. In this case,
the function caller didn't find the Subsystem block with the scoped function in the current
subsystem, but it found the Subsystem block in the parent model (Resolution Rule 2).

10-185
10 Conditional Subsystems

• Function caller is in another subsystem one or more subsystem levels below the hierarchic level of
the function. In this case, the function caller didn't find the Subsystem block with the scoped
function in the current subsystem, but it found the Subsystem block in the grandparent model
(Resolution Rule 2).

The function caller hierarchy cannot include a Model block since the function caller cannot cross
model reference boundaries.

10-186
Scoped Simulink Function Blocks in Subsystems

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function |
Subsystem

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-187
10 Conditional Subsystems

Scoped Simulink Function Blocks in Models


The scope of a Simulink function is defined in the context of a model. If you place a Simulink Function
block in a model at the root level, the function is scoped to the model by default. The Trigger block
Function visibility parameter is set to scoped. Access the function with a function caller located:

• Within the model hierarchy containing the function. Call the function without qualifying the
function name.
• Outside the model. Call the function by qualifying the function name with the Model block
instance name, not the model file name.

Setting Function visibility for a Simulink Function block to global allows you to access the
function from anywhere in the model or a parent model. As a result, models with a Simulink Function
block set to global cannot be multi-instanced because function names must be unique.

Resolve to a Function Hierarchically


Placing a scoped Simulink Function block within a model at the root level limits access to the function
and removes the function name from the global name space.

• Function caller located in the current model.

• You cannot place a function caller inside a Model block and the Simulink Function block in the
parent model,

10-188
Scoped Simulink Function Blocks in Models

If you place a function caller inside a Model block, Simulink displays the following error:

Block is unable to call the function with scope name because the function
definition is not found.

This error occurs because the model containing the caller does not know the name of the function.
Function calls cannot cross model reference boundaries.

Resolve to a Function by Qualification


When you place a Simulink Function block in a Model block, the function name is not accessible
outside the model. However, you can call a function by qualifying the function name with the Model
block name. When a function caller resolves to a qualified function hierarchically, it looks for the
Model block containing the function using the following rules:

• Resolution Rule 1: Is the Model block in the current model with the function caller?
• Resolution Rule 2: If the Model block is not in the current model or subsystem, is the Model block
in a parent or grandparent model one or more levels above the function caller?

If a function caller resolves to a Model block with a scoped function, you can call the function by
qualifying the function name:

• Function caller located outside of the Model block one hierarchic level above the function. In this
case, the function caller finds the Model block with the scoped function in the current model
(Resolution Rule 1).

10-189
10 Conditional Subsystems

• Function caller in a subsystem at the same hierarchic level as the function. In this case, the
function caller didn't find the Model block in the current subsystem, but it found the Model block
in the parent model (Resolution Rule 2).

10-190
Scoped Simulink Function Blocks in Models

• You cannot place a Simulink Function block in one Model block and the function caller in another
Model block.

If you place a Simulink Function block in a referenced model and a function caller in another
referenced model, Simulink displays the following error:

10-191
10 Conditional Subsystems

Block is unable to call the function with scope name because the function
definition is not found.

This error occurs because the qualified function name using the Model block name is not visible to
the model containing the caller.

If you want to access the function using this modeling pattern, see the section Function Caller Block
in Referenced Model and Function and the section Function Caller in Separate Models in the topic
“Simulink Function Blocks in Referenced Models” on page 10-171.

Multi-Instance Modeling with Simulink Functions


Setting Function visibility for a Simulink Function block to scoped encapsulates the function
within the model, allowing you to multi-instance the model. Adding the model instance name to the
function name creates a qualified function name that is unique within the parent model.

1 Create a model containing Simulink Function blocks.

By default, the Function visibility parameter for the Trigger block within the Simulink Function
block is set to scoped.
2 Reference the model with Simulink functions from multiple Model blocks. Add a Function-Call
Subsystem block to schedule calls to the functions.

3 Add Function Caller blocks to the Function-Call Subsystem block. Access the function in separate
model instances by qualifying the function name with the block name.

10-192
Scoped Simulink Function Blocks in Models

4
On the Debug tab, select Information Overlays . From the drop-down box, select Function
Connectors .

Tracing lines are drawn to help you navigate from a function caller to the function.

For a model using Simulink Function blocks with multiple instances, see “Model Reusable
Components Using Multiply Instanced Simulink Functions”.

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177

10-193
10 Conditional Subsystems

• “Scoped Simulink Function Blocks in Subsystems” on page 10-181


• “Define Diagnostic Services Using Simulink Functions” on page 10-200

10-194
Model Client-Server Communication Using Function Ports

Model Client-Server Communication Using Function Ports


You can model service-oriented communication in Simulink using export-function models and function
ports. Function ports allow you to facilitate data sharing between component models. This topic
shows you how to use function ports to model client and server components in Simulink.

To start from Simulink, client or server component models that use function ports must be an export-
function model. If a model uses synchronous functions, the parent model of the components must also
be an export-function model. For the configuration, see “Export-Function Models Overview” on page
10-125.

If you want to model service-oriented communication at the architecture level, you can use
preconfigured Simulink export-function models for components in System Composer™ software
architectures. For more information, see “Service Interfaces Overview” (System Composer).

Model Server Component with Function Element Block


A server component is one that provides services. Services are modeled as Simulink Function blocks
that are scoped to Function Element ports. For each server port in your service interface, there is a
Simulink Function block where you can implement the desired algorithm. The Function Element
block is a function port with the function elements specified in your service interface.

To modify the port name or function elements, open the properties of the Function Element block.

10-195
10 Conditional Subsystems

Inside the Simulink Function block, there is a Trigger block. To associate the Simulink function with
the server port:
1 Set the Function visibility parameter of the Trigger block inside the Simulink Function block to
port.
2 Set the Scope to port parameter of the Trigger block to the port name.

The Simulink Function block is scoped to the server port, meaning that the port is not visible
elsewhere in the model hierarchy and you can only call the function through the server port. The dot
notation near the Function Element block shows the association of the function with the port. The
port name is first, followed by the function name.

To implement function behavior, double-click the Simulink Function block. Inside the Simulink
Function block is a Trigger block, an ArgIn block, and an ArgOut block. Add any necessary blocks to
the function subsystem and connect elements to the ArgIn block and the ArgOut block.

10-196
Model Client-Server Communication Using Function Ports

Model Client that Requires Services


A client model is one that requires services from other models. A required service is modeled using a
Function Caller block and a Function Element Call block.

To modify the port name or function elements, open the properties of the Function Element Call
block.

The Function Element Call block is connected to the Function-Call Subsystem block because the you
call the function through the function port.

Inside the Function-Call Subsystem block is a Function Caller block. To associate the function caller
with the client port, set the Function prototype parameter of the Function Caller block to use dot
notation with the port name followed by the function name.

10-197
10 Conditional Subsystems

The dot notation near the Function Element Call block shows the association of the function with the
port. The port name is first, followed by the function name. The Inport block is connected to the
Function-Call Subsystem block with a root-level input port connection.

To implement the function call inside the Function-Call Subsystem block, double-click the Function-
Call Subsystem block. Add any necessary blocks to the function call subsystem to represent an input
and an output.

Configure Asynchronous Execution with Function Ports


Asynchronous execution is when the client sends a request to the server, the function executes
asynchronously based on the priority order, and the function returns the output arguments to the
client.

The function executes based on the ordering you define in the Schedule Editor. The behavior of the
message payload can change depending on the number of function output arguments.

• If the function has one output argument, the output argument becomes the message payload.
• If the function has more than one output argument, the Function Caller block bundles the output
arguments as a structure that becomes the message payload.

For the server model, the Trigger block parameters are different than those of a synchronous system.
To associate the Simulink function with the server port:

1 Set the Trigger type parameter of the Trigger block to function-call.


2 Set the Treat as a Simulink Function parameter of the Trigger block to on.
3 Set the Function visibility parameter of the Trigger block to port.
4 Set the Execute function call asynchronously parameter of the Trigger block to on.

For the client model, to associate the function caller with the client port, set the Execute function
call asynchronously parameter of the Function Caller block to on. The Message Triggered
Subsystem block acts as a callback for the function. You must connect the Message Triggered
Subsystem block to the message output port of the Function Call Subsystem block.

10-198
Model Client-Server Communication Using Function Ports

For more information, see “Simulate Asynchronous Services for Vehicle Headlight Management”
(System Composer).

See Also
Simulink Function | Trigger | Function Caller | Function Element | Function Element Call | Function-
Call Subsystem | Model | Message Triggered Subsystem

Related Examples
• “Export-Function Models Overview” on page 10-125
• “Define Port Interfaces Between Components” (System Composer)
• “Software Component Modeling” on page 26-2
• “Service Interfaces Overview” (System Composer)
• “Model Service-Oriented Communication Between Sensors” (System Composer)
• “Simulate Asynchronous Services for Vehicle Headlight Management” (System Composer)

10-199
10 Conditional Subsystems

Define Diagnostic Services Using Simulink Functions

Diagnostic Messaging with Simulink Functions


Use Simulink functions when you define a diagnostic service where callers pass an error code. The
service tracks error codes for all errors that occur. One way to implement this service is to use an
indexed Data Store Memory block. A diagnostic monitoring system can then periodically check for the
occurrence of specific errors and modify system behavior accordingly.

Client-Server Architecture
You can use Simulink Function blocks and Function Caller blocks to model client-server architectures.
Uses for this architecture include memory storage and diagnostics.

As an example, create a model of a simple distributed system consisting of multiple control


applications (clients), each of which can report diagnostics throughout execution. Since client-server
architectures are typically constructed in layers, add a service layer to model the diagnostic
interface.

10-200
Define Diagnostic Services Using Simulink Functions

The services (servers), modeled using Simulink Function blocks, are in a separate model. Add the
service model to your system model as a referenced model.

The control applications (clients) interact with the diagnostic interface using Function Caller blocks.

Modifier Pattern
Application 1 reports a diagnostic condition by invoking the reportDiagnostic interface within the
service layer. The application calls this function while passing in a diagnostic identifier.

The interval test determines when to create a diagnostic identifier.

10-201
10 Conditional Subsystems

The implementation of the function (Simulink Function 1) tracks the passed-in identifier by
transferring the value to a graphical output of the function. A graphical output is a server-side signal
that is not part of the server interface but facilitates communication between service functions
through function arguments. The value of graphical outputs is held between function invocations.

The reportDiagnostic function is an example of a modifier pattern. This pattern helps to


communication of data from the caller to the function and later computations based on that data.

Observer Pattern
Application 2 invokes the inspectDiagnostic interface within the service layer to inspect whether
diagnostics were reported.

The implementation of the function (Simulink Function) uses a graphical input (id) to observe the
last reported diagnostic and transfer this value as an output argument (identifier) to the caller. A
graphical input is a server-side signal that is not part of the server interface.

10-202
Define Diagnostic Services Using Simulink Functions

The inspectDiagnostic function is an example of an observer pattern. This pattern helps to


communication of data from the function to the caller.

See Also
Simulink Function | Argument Inport | Argument Outport | Function Caller | MATLAB Function

Related Examples
• “Simulink Functions Overview” on page 10-142
• “Add a Simulink Function to a Model” on page 10-151
• “Simulink Function Blocks in Referenced Models” on page 10-171
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188

10-203
10 Conditional Subsystems

Resolve Error: Block Is Unable to Call The Scoped Simulink


Function

Issue
The scoped Simulink function must be accessible by the caller. The accessibility of a function is
determined by the visibility and location of the function caller relative to the Simulink Function block.
For more information on function visibility and accessibility, see “Scoped, Global, and Port-Scoped
Simulink Function Blocks Overview” on page 10-177.

If the function caller is unable to access the function definition and the caller has a scope name
specified, the software might produce this error.

Block is unable to call the function with scope name because the function
definition is not found.

If a scope name is not specified in the caller, the software might not produce an error during
compilation or code generation, because the function may be defined externally as a global function.
However, the simulation always gives an error if the function is not resolved. For the Function Caller
block, the software produces this error.

A definition for the function called by Function Caller block could not be
found.

Possible Solutions
This error message occurs when the function caller is unable to access the function definition. To
ensure that the function is accessible by the caller, use hierarchical guidelines depending on the
configuration of your model.

Call Function Inside Model

The Simulink Function block or its parent subsystem must be placed at the same or higher
hierarchical level of the caller block.

10-204
Resolve Error: Block Is Unable to Call The Scoped Simulink Function

If the Simulink Function block is placed at the same or higher hierarchical level as the caller block,
the caller can call the function name directly.

If the parent subsystem of the Simulink Function block is placed at the same or higher hierarchical
level than the caller block, the caller must use the subsystem name as the scope name to qualify the
function.

For more information, see “Resolve to a Function by Qualification” on page 10-183.

For an example, see “Monitor Ink Status on Shared Printer Using Simulink Functions” or “Dynamic
Priority Scheduling of Functions”.

Call Function from Reference Model

When the Simulink function is defined in a reference model, the corresponding Model block must be
placed at the same or higher hierarchical level of the caller block in the caller model. The reference
model containing the Simulink function must be an export-function model.

10-205
10 Conditional Subsystems

The caller must use the name of the Model block as the scope name to qualify the function. The name
of the Model block is the instance name, so it supports multiple instances.

For more information, see “Resolve to a Function by Qualification” on page 10-189.

Call Function from Separate Model

A Simulink function can also be defined in a separate export-function model that is not referenced in
the caller model. This separate export-function model must be on the MATLAB path and must have a
unique name.

10-206
Resolve Error: Block Is Unable to Call The Scoped Simulink Function

The caller must use the model file name as the scope name to qualify the function. Only a single
instance of the function model is allowed because the caller does not specify an instance.

You can simulate this scenario by having a parent model that references the model with the function
model and the model with the caller.

For more information, see “Function and Function Caller Blocks in Separate Referenced Models” on
page 10-173.

For an example, see “Model Service Access from Application Software Using Scoped Simulink
Functions”.

See Also

Related Examples
• “Scoped, Global, and Port-Scoped Simulink Function Blocks Overview” on page 10-177
• “Scoped Simulink Function Blocks in Subsystems” on page 10-181
• “Scoped Simulink Function Blocks in Models” on page 10-188
• “Simulink Function Blocks in Referenced Models” on page 10-171

10-207
10 Conditional Subsystems

Using Initialize, Reinitialize, Reset, and Terminate Functions


Some blocks maintain state information that they use during a simulation. For example, the Unit
Delay block uses the current state of the block to calculate the output signal value for the next
simulation time step.

Subsystem blocks have default initialize and termination routines. You can add custom routines to the
default routines using Initialize Function, Reinitialize Function, and Terminate Function blocks to
change or read block states. You can also implement custom routines using Reset Function blocks.
These function blocks contain:

• An Event Listener block that executes the combined routine when receiving an initialize,
reinitialize, or terminate function-call event, or the custom routine when receiving a reset
function-call event.
• A State Writer block to initialize or set a block state or a State Reader block to read the state.

To define the custom routine, edit the contents of the block. For example:

• Set the State owner block parameter of the State Writer or State Reader block.
• Add additional State Writer or State Reader blocks.
• Add Parameter Writer blocks to set the value of block parameters. See “Initialize and Reset
Parameter Values” on page 10-226.
• Add Data Store Write blocks to write or Data Store Read blocks to read data in a data store. See
“Model Global Data by Creating Data Stores” on page 79-10.
• Add blocks and signal lines to supply the values for State Writer, Parameter Writer, and Data Store
Write blocks to write, or to save the values read by State Reader or Data Store Read blocks.

Create Model Component with State


You can define model algorithms using Simulink blocks. In this example, a single Discrete-Time
Integrator block defines the algorithm for integrating an input signal.
1 Open a new Simulink model. Save this model with the name Model01.
2 Add a Discrete-Time Integrator block. Verify the default parameter values are 1.0 for Gain
value, 0 for Initial condition, Auto for Initial condition setting, and -1 for Sample time.
3 Connect a Constant block to the input of the Discrete-Time Integrator block to model an input
signal. Connect a Scope block to the output signal.

10-208
Using Initialize, Reinitialize, Reset, and Terminate Functions

4 Open the Configuration Parameters dialog box. Set the simulation parameters for the Solver
Type to Fixed-step, Solver to auto, and Fixed-step size to 1.
5 Open the Scope block, and then run simulation. The output signal increases by 1 at each time
step.

Initialize Block State


Some model algorithms contain states that you can initialize. For example, with an algorithm that
reads a sensor value, you can perform a computation to set the initial sensor state.

At the beginning of a simulation, initialize the state of a block using a State Writer block. To control
when initialization occurs, use an Initialize Function block that includes the State Writer block.

1 Add an Initialize Function block.

By default, the Initialize Function block includes an Event Listener block with the Event type
parameter set to Initialize. The block also includes a State Writer block, and a Constant
block as a placeholder for the source of the initial state value.

10-209
10 Conditional Subsystems

2 Model initial conditions. In this example, set the Constant value parameter for the Constant
block to 4.
3 Connect the state writer with the state owner. Open the State Writer dialog box. Expand the
State Owner Selector Tree, select Discrete-Time Integrator, and then click Apply.

10-210
Using Initialize, Reinitialize, Reset, and Terminate Functions

The State Writer block displays the name of the state owner block. The state owner block
displays a tag indicating a link to a State Writer block. If you click the label above the tag, a list
opens with a link for navigating to the State Writer block.
4 Run a simulation to confirm that your model simulates without errors.

The Initialize Function block executes at the beginning of a simulation. The output signal starts
with and initial value of 4 and then increases by 1 until the end of the simulation.

10-211
10 Conditional Subsystems

Reset Block State


During a simulation, you can reset the state of a block using a State Writer block. To control when
reset occurs, use a Reset Function block.

Note You can use either a Reinitialize Function block or a Reset Function block to reset the state of a
block. Both the Reinitialize Function block and the Reset Function blocks can write to block states or
perform whatever actions you specify when you configure the blocks. The difference between the
blocks is that a Reinitialize Function first implicitly resets the states of all blocks in the model back to
their initial conditions and then carries out whatever other actions, including writing to block states,
you specify when you configure the block. By contrast, a Reset Function block, carries out only the
actions that you specify when you configure the block. In this example, since the model contains no
other blocks with state besides the Discrete-Time Integrator block, a Reinitialize Function block could
be used in place of the Reset Function block with no difference in results.

1 Add a Reset Function block.


2 Open the Reset Function block.
3 Model reset conditions. In this example, set the Constant value parameter for the Constant
block to 2.
4 Connect state writer with the state owner. Open the State Writer block dialog box. Expand the
State Owner Selector Tree, select Discrete-Time Integrator, and then click Apply.
5 The event name for the Reset Function block, reset, is displayed on the face of the block.

10-212
Using Initialize, Reinitialize, Reset, and Terminate Functions

If you click above the tag, a list opens with a link for navigating to the State Writer blocks located
in the Initialize Function block and the Reset Function block.

Note If the Reset Function block were replaced by a Reinitialize Function block, then the
Reinitialize Function block would first set the state of the Discrete-Time Integrator block back to
its initial condition of 0, as specified in the Discrete-Time Integrator block dialog. The Reinitialize
Function block would then use the State Writer block to set the state of the Discrete-Time
Integrator block to 2, which would override the implicit reinitialization to 0. This sequence of
actions has the same effect as the Reset Function block, which simply sets the state of the
Discrete-Time Integrator block to 2.

If a Reinitialize Function block were used without a State Writer block, then it would set the state
of the Discrete-Time Integrator block to its initial condition of 0. If a Reset Function block were
used without a State Writer block, it would have no effect on the state of any other block.
6 Run a simulation to confirm that your model simulates without errors.

The Reset Function block does not execute during the simulation. The block needs a function-call
event signal.

10-213
10 Conditional Subsystems

To create a function-call event signal for the Reset Function block, see “Create Test Harness to
Generate Function Calls” on page 10-221.

Read and Save Block State


At the end of a simulation, you can read the state of a block, and save that state.

1 Add a Terminate Function block.

By default, the Terminate Function block includes an Event Listener block with the parameter
Event type set to Terminate. The block also includes a State Reader block, and a Terminator
block as a placeholder for saving the state value.

10-214
Using Initialize, Reinitialize, Reset, and Terminate Functions

2 Connect the state reader with the state owner. Open the State Reader block dialog box. From the
State Owner Selector Tree, select Discrete-Time Integrator, and then click Apply.

10-215
10 Conditional Subsystems

3 Run a simulation to confirm that your model simulates without errors. The Terminate Function
block executes at the end of a simulation.

10-216
Using Initialize, Reinitialize, Reset, and Terminate Functions

4 Delete the blocks that you added for testing. Replace the Constant block with an Inport block and
the Scope block with an Outport block.

Prepare Model Component for Testing


Make the following changes to avoid simulation errors when the component model is placed in an
export-function model for simulation testing.

10-217
10 Conditional Subsystems

1 Open the Block Parameters dialog box for the Discrete-Time Integrator block. Set Integrator
method to Accumulation:Forward Euler.
2 Open the Model Configuration Parameters dialog box. Confirm the solver Type is set to Fixed-
step and Solver is set to auto. Change the Fixed-step size from 1 to auto.

This change avoids a simulation error caused by having multiple sample times in a Function-Call
Subsystem.

Create an Export-Function Model


Placing a model component in a test harness for testing the initialize, reset, and terminate functions
requires the model to follow export-function rules. See “Export-Function Models Overview” on page
10-125 and “Create Test Harness to Generate Function Calls” on page 10-221.

To create an export-function model, place the model component in a Function-Call Subsystem block
using a Model block. Connect input and output ports from the model to the subsystem input and
output ports.

1 Create a Simulink model. Save this model with the name Model02.
2 Open the Configuration Parameters dialog box. Set the simulation parameter for the Solver Type
to Fixed-step. Confirm Solver is set to auto and Fixed-step size is set to auto.
3 Add a Function-Call Subsystem block. Open the subsystem by double-clicking the block.
4 Add a Model block to the subsystem and set Model name to Model01. Add Inport and Outport
blocks.

5 Navigate to the top level of the model.


6 Add an Inport block. This block is the control signal for executing the subsystem. Change the
block name to Run and connect it to the function() port.

Open the Inport block dialog box and on the Signal Attributes tab, select the Output function
call check box.

10-218
Using Initialize, Reinitialize, Reset, and Terminate Functions

7 Add a second Inport block and rename it to Signal In. Connect it to the In1 port of the
subsystem. This block is the signal for the integration algorithm.

Add an Outport block, rename it to Signal Out, and then connect it to the Out1 port of the
subsystem. This block is the integrated signal.

8 Designate the model as an export-function model by going to the Property Inspector and setting
the execution domain of the model to Export function. See “Designating an Export-Function
Model” on page 10-128.
9 Open the Configuration Parameters dialog box. On the Model Referencing pane, set the Total
number of instances allowed per top model to one.
10 Update your model and confirm that there are no errors by pressing Ctrl+D.

The next step is create a test harness. See “Create Test Harness to Generate Function Calls” on page
10-221.

See Also
Initialize Function | Reset Function | Terminate Function | Event Listener | State Reader | State
Writer | Parameter Writer

Related Examples
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Startup, Reset, and Shutdown Function Interfaces” (Simulink Coder)

10-219
10 Conditional Subsystems

External Websites
• Initialize and Terminate Functions (3 min, 12 sec)

10-220
Create Test Harness to Generate Function Calls

Create Test Harness to Generate Function Calls


After you create a model component to initialize, reinitialize, reset, and terminate the state of blocks
(see “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208), you can place
the model in a simulation test harness. A test harness is a Simulink model that you use to develop,
test, and debug a model component.

To create the test harness, reference the export-function model containing the model component in a
new model, and then add a Stateflow chart to model a function-call event scheduler.

Reference the Export-Function Model


The export-function model contains the model component for testing. To create the export-function
model, see “Create an Export-Function Model” on page 10-218.

1 Create a Simulink model. Save this model with the name Test_Model.
2 Set configuration parameters for Solver Type to Fixed-step, Solver to auto, and Fixed-step
size to 1.
3 Add a Model block. Double click on the Model to open the Block Parameters dialog box. In the
Model name text box, enter the name of your export-function model. In this example, enter
Model02.
4 Test the referenced model component by connecting a Function-Call Generator block to the Run
port. Connect a Constant block to the Signal In port and a Scope block to the Signal Out
port.

5 Run a simulation to verify your model simulates correctly from the parent model. When the
model is simulated without function-call event ports, the Initialize Function block executes at the
beginning of a simulation and the Terminate Function block executes at the end of the
simulation.

10-221
10 Conditional Subsystems

6 Expose function-call input ports on the Model block. Double click on the Model block to open the
Block Parameters dialog box. In the Block Parameters dialog box, select Show model initialize
port, Show model reset port, and Show model terminate port.
7 Delete the Function-Call Generator block and update the model by pressing Ctrl+D.

When you activate the initialize function-call input port on a Model block, the model has to
receive an initialize function call on the initialize port before it can execute. The reception of
a function call triggers the execution of the default model initialize routine, and then the
execution of the Initialize Function block contents.

The reception of a function call on the Reset port triggers the execution of the Reset Function
block contents.

The reception of a function call on the Terminate port triggers the execution of the Terminate
Function block contents, and then the execution of the default model terminate routine. The

10-222
Create Test Harness to Generate Function Calls

model then stops running. To execute the model again, you have to reinitialize the model by
sending a function-call event to the initialize port.

Model an Event Scheduler


Use a Stateflow chart to model an event schedule and generate the initialize and terminate function
call signals.

1 Add a Stateflow chart. Click the model diagram and start typing Chart. From the search list,

select .
2 Open the chart and add two state blocks, one above the other.
3 Add a default transition and connect it to the top state block. Edit the label:

{step = 0}
4 Add a transition from the top block to the bottom block. Edit the label:

[step == 2]/{Initialize}
5 Add a transition from the bottom block and back to the bottom block. Edit the label:

[step == 5]/{Reset}
6 Add a transition from the bottom block to top block. Edit the label:

[step == 9]/{Terminate}
7 Edit the content of the top block:

Inactive
entry: step = step + 1;
during: step = step + 1;
8 Edit the content of the bottom block:

Running
entry: step = step + 1; Run;
during: step = step + 1; Run;

10-223
10 Conditional Subsystems

Connect Chart to Test Model


Create function-call output ports on the chart to control and run the model component.

1 Open Model Explorer. On the Modeling tab and from the Design section, select Model

Workspace .
2 Create index variable. From the menu, select Add > Data. In the Data dialog box, enter Step for
the Name.
3 Create function-call output ports. For each function-call event you create, select Add > Event
and in the Event dialog box, enter, and select the following values.

Enter in Event Text Box Set Scope Set Trigger


Initialize Output to Simulink Function call
Reset Output to Simulink Function call
Terminate Output to Simulink Function call
Run Output to Simulink Function call
4 Navigate to the top level of the model. Connect the Initialize, Reset, Terminate, and Run
ports on the chart to the initialize, reset, terminate, and Run input ports on the Model
block.

5 Run a simulation.

The model cannot execute until the second time step, when the block state is initialized to 4. At
the fifth time step, a reset function call to the reset port triggers the Reset Function block to
execute. At the ninth time step, the subsystem stops executing, and the block state remains
constant.

10-224
Create Test Harness to Generate Function Calls

If the model receives a function call to run before an initialize function call, a simulation error
occurs.

Note You can create the same test harness using Simulink Test™. In this example, Simulink Test uses
a Stateflow chart to create the test harness scheduler and source. For more information, see
“Stateflow Chart as Test Harness Scheduler and Source” (Simulink Test). To set up Model02 for
Simulink Test, place the input signal source (connected to the Signal In port) at the root level of
Model02 and connect the source to the function-call subsystem. To visualize the output, connect a
Scope block to the output signal of Model02.

See Also
Initialize Function | Reinitialize Function | Reset Function | Terminate Function | Event Listener |
State Reader | State Writer | Parameter Writer

Related Examples
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• Initialize and Reset Parameter Values on page 10-226
• “Use Stateflow Chart for Test Harness Inputs and Scheduling” (Simulink Test)

External Websites
• Initialize and Terminate Functions (3 min, 12 sec)

10-225
10 Conditional Subsystems

Initialize and Reset Parameter Values


During a simulation, you can respond to an event such as reading an environment sensor value, and
then update an algorithm with a new parameter value.

The Initialize Function, Reinitialize Function, and Reset Function blocks can respond to events while
the Parameter Writer block can change parameter values. The Parameter Writer block can change
parameters in these ways:

• Writing directly to a parameter of a block that is tunable during simulation


• Writing to an instance parameter belonging to a Model block referencing a model, thus affecting
block parameters inside the referenced model
• Writing to a masked subsystem parameter, thus affecting block parameters inside the subsystem
• Writing to a model workspace variable, thus affecting block parameters that are based on that
variable

Adding a Parameter Writer Block


You can use a Parameter Writer block inside an Initialize Function, Reinitialize Function, or Reset
Function block to write a parameter value in response to events. You can also use a Parameter Writer
block inside a conditionally executed subsystem to write a parameter value whenever the subsystem
executes.

A block with a parameter that can be written by a Parameter Writer block is called a parameter
owner block. A parameter owner block can be a block with a tunable parameter, a Model block, or a
masked subsystem block.

To add a Parameter Writer block to your model, click on a parameter owner block to highlight it.
Then, from the current block tab of the Simulink toolstrip, click Parameter Writer. Alternatively,
click Reader-Writer, then select Parameter Writer Block from the list.

Note The current block tab of the toolstrip might be labeled with the name of the highlighted block,
for example, Constant, or it might be labeled Block, depending on the type of block you highlight.

10-226
Initialize and Reset Parameter Values

If the parameter owner block has multiple parameters to which the Parameter Writer block can write,
then the Parameter Writer block dialog box opens. Select a parameter from the Parameter Owner
Selector Tree.

After you add a Parameter Writer block, a badge and the name of the parameter being written to
appear above the parameter owner block. The names of the parameter owner block and the
parameter appear next to the Parameter Writer block.

After you add a Parameter Writer block, cut and paste it to move it to the desired location within the
model hierarchy.

Alternatively, you can add a Parameter Writer block to your model from the Simulink Library Browser,
then select a parameter owner block or a model workspace parameter from the block dialog.

Note When you create a library block with a Parameter Writer block, you must also include the
corresponding parameter owner block in the library block.

Writing to Tunable Block Parameters


A Parameter Writer block can write directly to a parameter of a block that is tunable during
simulation. See “Which Block Parameters Are Tunable During Simulation?” on page 41-34 The

10-227
10 Conditional Subsystems

parameter must take its value from the block dialog box and not from a port. Initial condition
parameters are not included. The Parameter Writer block must be in the same model as the block
whose parameter it is writing.

Writing to Model Instance Parameters


A Parameter Writer block can change the value of a block parameter inside a referenced model by
writing to an instance parameter of the model. This example shows how to use the Parameter Writer
block to change a parameter value for a Gain block inside a referenced model.

1 Create a model with a writable parameter, which is a block parameter that you can define with a
model parameter. In the example, add Constant, Gain, and Outport blocks to a new model.
Connect the blocks. Save the model with the name ParamRw_Sub.

2 Add a Simulink parameter to the Model Workspace. On the Modeling tab, in the Design section,

select Model Workspace . From the Model Explorer menu, select Add > Simulink
Parameter. Set Name to Parameter_1 and Value to 1. Select the Argument check box. Click
Apply.

3 Open the Gain Block Parameters dialog box. Set Gain to Parameter_1.
4 Create a model that initializes the parameter. Add an Initialize Function and Model block to a
new model. Save the model with the name ParamRw_Top.

5 Rename the Model block to Model_1. Open the Model Block Parameters dialog box. In the
Model name box, enter ParamRw_Sub. Select the Instance parameters tab. Set the Value for
Parameter_1 to 1. The model uses this default value before the Parameter Writer block updates
this parameter with a new value.

10-228
Initialize and Reset Parameter Values

6 Double-click the Initialize Function block. The block is preconfigured with a State Writer block.

7 Replace the State Writer block with a Parameter Writer block. Open the Parameter Writer Block
Parameters dialog box. From the Parameter Owner Selector Tree, select Parameter_1.

8 Open the Constant Block Parameters dialog box. Set Constant value to 3. This value sets the
gain with the Parameter Writer block.
9 Click OK to close the dialog. The Parameter Writer block displays a label indicating it writes to
the model instance parameter Parameter_1 for Model_1.

10-229
10 Conditional Subsystems

10
Click the ParamRw_Top tab. The Model block displays a badge , indicating a value is written
to Parameter_1.

Writing to Masked Subsystem Parameters


A Parameter Writer block can change the value of a block parameter inside a masked subsystem by
writing to a parameter of the subsystem. The mask parameter must have Evaluate selected and
Tunable set to on or run-to-run. See “Mask Editor Overview”. The subsystem can be atomic or
virtual.

10-230
Initialize and Reset Parameter Values

Writing to Model Workspace Variables


A Parameter Writer block can directly write the value of a model workspace variable. The block must
be in the same model as the workspace variable, and the variable must not be configured as a model
argument. You can write only to model workspace variables and not to variables in the base MATLAB
workspace or data dictionaries. The variable written to can be a regular MATLAB variable or a
Simulink.Parameter object.

To write to a model workspace variable, in the block dialog box, select Access model workspace
parameter and enter the variable name in Model workspace parameter name. Note that the
Parameter Owner Selector Tree does not appear.

See Also
Initialize Function | Reinitialize Function | Reset Function | Terminate Function | Event Listener |
State Reader | State Writer | Parameter Writer

Related Examples
• “Parameterize Instances of a Reusable Referenced Model” on page 8-80
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Initialize, Reinitialize, Reset, and Terminate Function Limitations” on page 10-232

External Websites
• Initialize and Terminate Functions (3 min, 12 sec)

10-231
10 Conditional Subsystems

Initialize, Reinitialize, Reset, and Terminate Function


Limitations

Initialize Function, Reinitialize Function, Reset Function, and Terminate Function blocks do not
support certain blocks, signals, and modeling patterns.

Unsupported Blocks and Signals


This table describes whether the Initialize Function, Reinitialize Function, Reset Function, and
Terminate Function blocks support the given blocks and signals.

Block or Signal Support


Model blocks Not supported.
Custom code blocks Not supported.
Stateflow charts Supported by only Reset Function blocks.
Resettable Subsystem blocks Not supported.
Blocks with states, for example, Supported by only Reset Function blocks.
Unit Delay blocks
Blocks with absolute time, for Not supported.
example, Clock blocks
MATLAB System blocks Not supported.
MATLAB Function blocks Initialize Function, Reinitialize Function, and Terminate Function
blocks support only MATLAB Function blocks without persistent or
global data.

Reset Function blocks support MATLAB Function blocks with or


without persistent or global data.
Simulink Function blocks Initialize Function, Reinitialize Function, Reset Function, and
Terminate Function blocks can call Simulink Function blocks as
long as the Simulink Function blocks do not have:

• Input or output ports


• An Initialize Function, Reinitialize Function, Reset Function, or
Terminate Function block
• Unsupported blocks
Variable-size signals Not supported.

Unsupported Modeling Patterns


This table describes requirements for model components that contain Initialize Function, Reinitialize
Function, Reset Function, and Terminate Function blocks.

10-232
Initialize, Reinitialize, Reset, and Terminate Function Limitations

Modeling Pattern Requirement


Nonvirtual blocks between When a model contains an Initialize Function block that has an
Initialize Function block and input port, the input port must connect to the root input port block
root input port block without intervening nonvirtual blocks. Virtual blocks, such as
Inport and From blocks, may intervene between the input port of
the Initialize Function block and the root input port block.

When a harness model simulates the initialization of a referenced


model with an initialize port on a Model block, the input ports of
the Model block may connect to nonvirtual blocks in the harness
model.
Nonvirtual blocks between When a model contains a Terminate Function block that has an
Terminate Function block and output port, the output port must connect to the root output port
root output port block block without intervening nonvirtual blocks. Virtual blocks, such as
Outport and Goto blocks, may intervene between the output port of
the Terminate Function block and the root output port block.

When a harness model simulates the termination of a referenced


model with a terminate port on a Model block, the output ports of
the Model block may connect to nonvirtual blocks in the harness
model.
Branched input signal in export- In an export-function model, a signal from a root Inport block to an
function model Initialize Function, Reinitialize Function, Reset Function, or
Terminate Function block must not branch to a Simulink Function
block.
Branched input signal in a In a model that is not an export-function model, a signal from a
model that is not an export- root Inport block to an Initialize Function, Reinitialize Function,
function model Reset Function, or Terminate Function block must not branch to
any other block.

For example, suppose you have a model that contains Initialize Function and Terminate Function
blocks.

10-233
10 Conditional Subsystems

The Initialize Function block connects to a root Inport block. The Terminate Function block connects
to a root Outport block. The signal from the root Inport block to the Initialize Function block does not
branch to any other blocks.

A harness model can simulate the model behavior.

To simulate the initialization of the referenced model, a control signal connects to the initialize port
of the Model block, which corresponds with the Initialize Function block in the referenced model.

To simulate the termination of the referenced model, a control signal connects to the terminate port
of the Model block, which corresponds with the Terminate Function block in the referenced model.

To provide an environment for the referenced model, nonvirtual blocks in the harness model connect
to the Model block input and output ports.

See Also
Initialize Function | Reinitialize Function | Reset Function | Terminate Function | Event Listener |
State Reader | State Writer | Parameter Writer

Related Examples
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Create Test Harness to Generate Function Calls” on page 10-221

10-234
Reinitialize States of Blocks in Subsystem

Reinitialize States of Blocks in Subsystem


The Reinitialize Function block allows you set the state of all blocks in a referenced model or
subsystem back to their initial condition, as well as to explicitly set block states or block parameters,
at any time during model simulation. This example demonstrates the use of the Reinitialize Function
block in a subsystem.

The model contains a subsystem with a reinitialize port. A Function-Call Generator block sends a
function-call signal to the port at time step 5.

Inside the subsystem, two Discrete-Time Integrator blocks integrate the input signal and output the
result. The blocks are identically configured, with the Initial condition set to 0.

The subsystem contains a Reinitialize Function block. Inside the Reinitialize Function block is a State
Writer block that is configured to set the state of one of the two Discrete-Time Integrator blocks to
10.

10-235
10 Conditional Subsystems

The Reinitialize Function block executes only when the subsystem receives a reinitialize event, that
is, when a function-call event is set to the reinitialize port of the subsystem. To expose a reinitialize
port on the subsystem block, in the Subsystem block parameters dialog box, select Treat as atomic
unit and then select Show subsystem reinitialize ports.

Note You can also use the Reinitialize Function block inside conditional subsystems. In such cases,
you do not need to select Treat as atomic unit.

A port is displayed on the Subsystem block with the reinitialize icon and the label reinit. This
label corresponds to the Event name specified in the Event Listener block inside the Reinitialize
Function block.

Sending a function-call event to the reinitialize port generates a subsystem reinitialize event, which
has these effects:
1 For each block with a state in the subsystem, the state is set to the initial condition, as specified
in the block parameters. In this example, the states of both Discrete-Time Integrator blocks are
set to 0.
2 The contents of the Reinitialize Function block corresponding to the port are executed. In this
example, the State Writer block sets the state of one of the Discrete-Time Integrator blocks to 10,
overriding the value set in the previous step.

10-236
Reinitialize States of Blocks in Subsystem

Note In addition to or instead of using State Writer blocks to set block states, you can configure a
Reinitialize Function block to take other actions, such as setting a block parameter value with a
Parameter Writer block or setting a data store value with a Data Store Write block.

In this example, a constant value of 5 is sent to both Discrete-Time Integrator blocks and integrated,
and a function-call event is sent to the reinitialize port at time step 5, generating a subsystem
reinitialize event. After you simulate the model, the Scope output shows that the first signal is reset
to 10 and the second signal is reset to 0 at time step 5.

See Also
Initialize Function | Reinitialize Function | Reset Function | Terminate Function | Event Listener |
State Writer | Parameter Writer | Data Store Write

Related Examples
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Initialize, Reinitialize, Reset, and Terminate Function Limitations” on page 10-232

10-237
10 Conditional Subsystems

Common Uses of the Initialize Function Block

This example shows how to use the Initialize Function block to perform these common initialization
actions.

• Initialize a block state.


• Initialize a block parameter.
• Initialize a data store created using a Data Store Memory block.

The initial value can be:

• Computed by a block in the model


• Provided by an external input to the model
• Provided by external functions in the target environment of the model

This example uses two models. The model initializeFunctionUses demonstrates common use
cases. The model initializeFunctionUsesEnv provides a mock target environment in which the
first model operates.

Open Use Case Model

Open the model initializeFunctionUses.


open_system('initializeFunctionUses.slx')

10-238
Common Uses of the Initialize Function Block

Initialize Block State

The Initialize Block State subsystem initializes a Unit Delay block state where the initial value
of the state is computed by another block. This subsystem implements a counter using the Unit Delay
block.

Open the Initialize Block State subsystem.

open_system('initializeFunctionUses/Initialize Block State')

The Initialize Function block initializes the Unit Delay block state to 5 using a Constant block via a
State Writer block. This value overrides the value of the Initial condition parameter of the Unit
Delay block, which is 0 in this example.

Open the Initialize Function block inside Initialize Block State subsystem.

open_system('initializeFunctionUses/Initialize Block State/Initialize Function')

10-239
10 Conditional Subsystems

Initialize Block Parameter

The Initialize Block Parameter subsystem initializes a block parameter with a value that is
dependent on an external input to the model. This subsystem initializes a Gain block parameter with a
constant value of 10 or 5 depending on the boolean external signal Use High Gain. The new Gain
value overrides the existing Gain value of 1.

Open Initialize Block Parameter subsystem.

open_system('initializeFunctionUses/Initialize Block Parameter')

The Initialize Function block uses a Parameter Writer block to write to the Gain block parameter
when the subsystem is initialized.

Open the Initialize Function block in the Initialize Block Parameter subsystem.

open_system('initializeFunctionUses/Initialize Block Parameter/Initialize Function')

10-240
Common Uses of the Initialize Function Block

Initialize Data Store

The Initialize Data Store Memory subsystem initializes a data store with a value that is
derived by calling an external function in the target environment for the model. The subsystem
implements a counter using the data store blocks. The Data Store Read2 block must be configured
to execute first to ensure the count value (DSM Count) is logged before the data store value
increases by 1.

Open the Initialize Data Store Memory subsystem.

open_system('initializeFunctionUses/Initialize Data Store Memory')

10-241
10 Conditional Subsystems

To configure the Data Store Read2 block to execute first, in the Block Properties dialog box, on the
General tab, set Execution Order property to First. For more information, see “Specify Block
Properties” on page 40-4.

Open the Block Properties dialog box for Data Store Read2 block.

open_system('initializeFunctionUses/Initialize Data Store Memory/Data Store Read2','property')

10-242
Common Uses of the Initialize Function Block

Close the Block Property dialog box.

close_system('initializeFunctionUses/Initialize Data Store Memory/Data Store Read2')

Upon initialization, the Initialize Function block initializes the Data Store Memory block inside
Initialize Data Store Memory subsystem.

Open the Initialization Function block in the Initialize Data Store Memory subsystem.

open_system('initializeFunctionUses/Initialize Data Store Memory/Initialize Function')

10-243
10 Conditional Subsystems

Upon termination, the Data Store Write block inside the Terminate Function block writes the count
value to the Data Store Memory block inside Initialize Data Store Memory subsystem.

Open the Terminate Function block in the Initialize Data Store Memory subsystem.

open_system('initializeFunctionUses/Initialize Data Store Memory/Terminate Function')

Open Environment Model

The environment model initializeFunctionUsesEnv uses external functions LoadCount and


SaveCount because the data store in the Initialize Data Store Memory subsystem call those
functions to load and save the counter values from a persistent storage MockExternalStorage
created using a Data Store Memory block in initializeFunctionUsesEnv.

Open the initializeFunctionUsesEnv model.

open_system('initializeFunctionUsesEnv.slx')

10-244
Common Uses of the Initialize Function Block

A Model block in the environment model initializeFunctionUsesEnv references the use case
model initializeFunctionUses. To enable the initialize and terminate ports of the Model block,
select Show model initialize port and Show model terminate port. This setting allows multiple
cycles of initialization and termination during simulation.

Open the Model Block Parameters dialog box.

open_system('initializeFunctionUsesEnv/Model','parameter')

10-245
10 Conditional Subsystems

Close the Model Block Parameters dialog box.

close_system('initializeFunctionUsesEnv/Model')

At the start of simulation, LoadCount is called to load the initial count value from the persistent
storage and upon termination SaveCount is called to save the count value in the persistent storage
MockExternalStorage.

Mock Environment Functions

Two Simulink Function blocks define two functions in the environment model. A Data Store Memory
block is represents the mock external storage in the environment model.

The LoadCount function loads the count value from the data store MockExternalStorage to the
data store inside the Data Store Memory subsystem.

Open the LoadCount function.

open_system('initializeFunctionUsesEnv/Simulink Function1')

10-246
Common Uses of the Initialize Function Block

The SaveCount function saves the count value from the data store inside the Data Store Memory
subsystem to the data store MockExternalStorage.

Open the SaveCount function.

open_system('initializeFunctionUsesEnv/Simulink Function2')

Schedule Initialize and Terminate Events

Together, the Function-Call Generator blocks, the Digital Clock block, and logical operator blocks
schedule the initialize event at t = 1s and t = 6s, and the terminate event at t = 5s. The environment
model (top model) simulates two initialize and terminate cycles for the use case model, which is the
referenced model.

• First cycle: t = 1s to t = 5s
• Second cycle: t = 6s to t = 10s (simulation stops)

10-247
10 Conditional Subsystems

Schedule High and Low Gain Values

The Digital Clock block and a Compare To Constant block provide the boolean input Use High
Gain. The use case model initializeFunctionUses uses a low gain value of 5 during the first
cycle and a high gain value of 10 during the second cycle.

Simulate the Model and Review Results

Simulate the model and visualize the result using Scope blocks.

sim('initializeFunctionUsesEnv.slx');

Unit Delay Counter

The Scope block named Unit Delay Counter shows the output of the counter implemented using
Unit Delay block in the Initialize Block State subsystem. The counter value resets to 5 every
time the use case model initializeFunctionUses is initialized.

Open the Scope block named Unit Delay Counter.

open_system('initializeFunctionUsesEnv/Unit Delay Counter')

10-248
Common Uses of the Initialize Function Block

Another Scope block named Amplified Sine Wave shows output of the Initialize Block
Parameter subsystem. A sine wave inside the subsystem is amplified by the low gain of 5 during the
first initialize and terminate cycle (t = 1s to t = 5s) and by the high gain value of 10 during the
second cycle (t = 6s to t = 10s).

Open the Scope block named Amplified Sine Wave.

open_system('initializeFunctionUsesEnv/Amplified Sine Wave')

Another Scope block named DSM Counter shows the output of the counter implemented in the
Initialize Data Store Memory subsystem. Unlike the Unit Delay Counter, the count value from
DSM Counter persists across all the initialize and terminate cycles.

Open the Scope block named DSM Counter.

open_system('initializeFunctionUsesEnv/DSM Counter')

10-249
10 Conditional Subsystems

See Also
Initialize Function | Terminate Function | Event Listener | Unit Delay | State Writer | Gain | Parameter
Writer | Data Store Memory | Data Store Write | Data Store Read | Simulink Function

Related Examples
• “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208
• “Create Test Harness to Generate Function Calls” on page 10-221
• “Initialize, Reinitialize, Reset, and Terminate Function Limitations” on page 10-232

10-250
Model House Heating System

Model House Heating System


This tutorial shows how to model and simulate a dynamic system using Simulink software. The model
is for a heating system that includes a heater (plant model), controlled by a thermostat (controller
model), to heat a room (environment model) to a set temperature. While this is a simple model, the
processes for creating model structure and algorithm design are the same processes you will use for
more complex models.

Open Completed House System Model

Open the example to access all the model and data files used in this topic.

To open the finalized model, use this command.

open_system("ex_househeat_modeling");

Define a House Heating System


Modeling begins with completion of tasks that are outside of the Simulink software environment.
Define model requirements and derive mathematical equations. Collect data for model parameters
and output signal data measurements to validate simulation results.

10-251
10 Conditional Subsystems

Determine Modeling Goals

Before designing a model, consider your goals and requirements. The goals for modeling the house
heating system are:

• Observe how the changing outdoor temperature affects the indoor temperature.
• Examine the effect of changing parameters on the indoor temperature.

Identify System Components

Once you understand your modeling requirements, you can begin to identify the components of the
system.

The house heating system in this tutorial defines a heating system and its relationship to a room. It
includes:

• Thermal characteristics of a house


• Thermal characteristics of a heater
• A thermostat to control the heater
• Outdoor environment
• Indoor environment

The thermostat monitors the room temperature regularly and turns the heater on or off, depending
on the difference between the set temperature and the room temperature.

10-252
Model House Heating System

The model for this system includes three components: heater, thermostat, and room.

Define System Equations

Three time-dependent variables define the heat exchange in the room:

• Temperature of the room (Troom)


• Heat gain: Thermal energy transferred from the heater (Qgain) to the room
• Heat loss: Thermal energy transferred from the room (Qloss) to the outdoor environment

A differential equation defines the relationship between these variables, but since heat transfer is
defined in terms of changing temperature, only room temperature is a state variable.

Rate of Heat Gain Equation

The temperature of the air in the heater is constant at Theater and the room temperature is Troom.
Thermal energy gain to the room is by convection of heated air from the heater, with a heat capacity
of cair. Heat gain for a mass of air in the heater, mheaterair , is proportional to the temperature
difference between the heater and the room:

Qgain = mheaterair cair (Theater − Troom).

The rate of thermal energy gain from the heater is

dQgain dmheaterair
= cair (Theater − Troom) .
dt dt

A fan takes room air, and passes it through the heater and back to the room. A constant amount of air,
Mheaterair , flows through the heater per unit time, and replacing dmheaterair /dtwith that constant
simplifies the equation to

dQgain
= Mheaterair cair (Theater − Troom) .
dt

10-253
10 Conditional Subsystems

Rate of Heat Loss Equation

Thermal energy loss from the room is by conduction through the walls and windows, and is
proportional to the temperature difference between the room temperature and the outside
temperature:

kA(Troom − Toutside)t
Qloss = .
D

The rate of thermal energy loss is

dQloss kA(Troom − Toutside)


= .
dt D

Replacing kA/D with 1/R where R is the thermal resistance simplifies the equation to

dQloss (Troom − Toutside)


= .
dt R

Changing Room Temperature Equation

Define the rate of temperature change in the room by subtracting the rate of heat loss from the rate
of heat gain:

dTroom 1 dQgain dQloss


= −
dt mroomair cair dt dt .

Collect Parameter Data

Most of the parameter values needed for the house heating model are published in standard property
tables. The flow rate for the heater is from a manufacturer data sheet.

List the variables and coefficients from your equations and check for dimensional consistency
between the units. Since the unit of time for the model is hours, convert published values for the
thermal property of materials from units of seconds to hours.

Equation Variables and Constants

You can use the constant names and values in this table when building the model.

Equation Description Units


Variable or
Coefficient
A Area of wall or window surfaceA_wall square meter
= 914, A_window = 6
D Depth of wall or window D_wall = meter
0.2, D_window 0.01
Q Thermal energy transferred joule
dQ/dt Rate of thermal energy transferred joule/hour

10-254
Model House Heating System

Equation Description Units


Variable or
Coefficient
k Thermal conductivity; property of a joule/meter· hour· degree
material to conduct heat transfer
k_fiberglass = 136.8, k_glass =
2808
r Thermal resistivity; property of a meter· hour· degree/joule
material to resist heat transfer r =
1/k
R Thermal resistance R = D/kA = (T1 hour· degree/joule
— T2)Q

R_wall = 1.599e-6, R_window =


5.935e-7

R_equivalent = (R_wall *
R_window)/(R_wall + R_window)
= 4.329e-7
m Mass of air in the room or heater kilogram
m_room_air = 1470

The mass of the heater m_heater_air


is not needed for this model.
dm/dt Rate of air mass passing through the kilogram/hour
heater
M Constant rate of air mass passing kilogram/hour
through the heater M_heater_air =
3600
c Specific heat capacity c_air = joule/kilogram· degree
1005.4
Theater Constant air temperature from heater degree Celsius
T_heater = 50
Troom Initial air temperature of room degree Celsius
T_roomIC = 20

Model House Heating System


Model the top-level structure with components that including interfaces for passing data between
individual components. Your model should be organized into a hierarchical structure that corresponds
to the components of the system.

10-255
10 Conditional Subsystems

Model Top-Level Structure

At the top level of the house heating model, use Subsystem blocks to organize your model and create
the structure. The model includes the subsystems Thermostat, Heater, and Room.
1 Open a new Simulink model: “Open New Model”.
2 Open the Library Browser: “Open Simulink Library Browser”
3 Add Subsystem blocks. Drag three Subsystem blocks from the Ports & Subsystems library to the
new model in the Simulink Editor.

4 Open a Subsystem block. Double-click the block.

Each new Subsystem block contains one Inport (In1) and one Outport (Out1) block. These blocks
define the signal interface with the next higher level in a model hierarchy.

Each Inport block creates an input port on the Subsystem block, and each Outport block creates
an output port. Add more blocks for additional input and output signals.
5
On the Simulink Toolstrip, click the Navigate Up To Parent button to return to the top level.
Rename the Subsystem blocks as shown. Double-click a block name and type the new name.

10-256
Model House Heating System

For each component, model the equations, define parameters, prepare the subsystem for simulation,
and simulate to verify its behavior.

Model Heater Component

Let’s start by modeling the heater system component. The heater model:

• Takes the current temperature from the room and a control signal from the thermostat as inputs
• Calculates the heat gain from the heater
• Outputs the heat gain when the control signal is on

To model the heater subsystem, model the rate of heat gain equation with Simulink blocks:

dQgain
= Mheaterair cair (Theater − Troom) .
dt

Subtract Room Air Temperature from Heater Air Temperature

The temperature difference is the current room temperature subtracted from the constant
temperature of the heater (T_heater).

1 Open the Heater subsystem.


2 Click the model and type Sum to display a list of blocks with Sum in the name. Click the Sum
block on the list. When prompted for a list of signs, type |-+ to place - and + input ports on the
block, and press Enter.

The vertical bar (|) changes the position of input ports by inserting spaces between the ports. A
vertical bar at the beginning of the sign list, places a space at the top of the block and shifts the
ports counter clockwise.
3 Add a Constant block to model the constant air temperature from the heater. Set the block
Constant value parameter to T_heater. You will define the value of T_heater in the Model
Workspace.

If the block displays -C-, resize the block to display the variable name.
4 Add a second Inport block to take the room temperature signal from another part of your model.
5 Add a Gain block to the Heater subsystem. Set the Gain parameter to M_heater_air*c_air.
You will define the values of these variables in the Model Workspace.
6 Connect the output of the Sum block to the input of the Gain block.
7 Add labels to the signal lines to help trace model components to the equations and model
requirements. Double-click above a signal line and enter a label.

10-257
10 Conditional Subsystems

8 Rename the blocks and connect them as shown in the figure.

Model a Heater Switch

The thermostat sends an on/off signal equal to 1 (on) or 0 (off) to the heater. Because the input signal
is binary, you can use a Product block to model a switch.
1 Remove the connection between the In1 and Out1 blocks. Select the line and press Delete.
2 Add a Product block. Resize the block vertically to align the block in your diagram. Connect the
In1 block to the first block input and the block output to the Out1 block. Rename the blocks as
shown.

3 Connect the output from the Gain block to the second input. Move all the connected blocks
together. Draw a selection box around the blocks you want to move, and then drag them to the
new location.
4 Rename blocks and add labels to signals as shown in the figure.

The Inport and Outport blocks create ports that connect this subsystem to other subsystems in
your model.

10-258
Model House Heating System

Define Heater Model Parameters

You can define parameters in the MATLAB Workspace and then enter their names in the block
parameter dialog boxes. However, a more robust method is to use the Simulink Model Workspace
because variable values are saved with the model.

1 In the Simulink Editor, on the Modeling tab, under Design, click Model Workspace.
2 In Model Explorer, select Add > MATLAB Variable. In the middle pane, click the new variable
Var and enter the variable name for a block parameter. For this example, enter T_heater.

3 Click the 0 value and enter the value for this variable. For this example, enter 50 degrees.

4 Using the same approach, add the variable M_heater_air with a value of 3600 kilogram/hour
and c_air with a value of 1005.4 joule/kilogram· degree.

Prepare Heater Model for Simulation

Set up the heater model for simulation. Think about the expected behavior and how you can test that
behavior with a simulation. When the thermostat output is 1 (on), and assuming constant room
temperature of 25, the expected output from the gain is (50 – 25) x 3600 × 1005.3 = 9.05 × 107.
Verify this output by running the model with these inputs:

• Heater on/off signal that changes from 0 to 1 after the 4th hour
• Room temperature constant at 25

1
From the Heater subsystem, click the Navigate Up To Parent button to navigate to the top
level of your model. You can resize the Heater block as shown in the figure.

Notice the Heater block has a second input port and that each port corresponds to an Inport
block or Outport block in the subsystem.
2 Add a Constant block to represent the room temperature, and set the value to 25 (degrees
Celsius). Add a Step block for a temporary Heater (on/off) signal. Set Step time to 4.
3 Add a Scope block and connect it to the Heat Gain output.

10-259
10 Conditional Subsystems

Simulate Heater Model and Evaluate Results

Use the default simulation settings to validate your model design.


1 Double-click the Scope block to open it.
2
Simulate the model. Click the Run button .

As the simulation runs, the Scope plots the results.


3 View the scope trace.

4 Determine if this result is what you expected.

When the heater on/off signal flips from 0 to 1 at 4 hours, the heater outputs 9.05 × 107 joule/
hour. The simulation validates the expected behavior.
5 Remove Constant, Step, and Scope blocks you added for testing the Heater component.

Model Thermostat Component

You can model a thermostat without using system equations. Requirements for this component:

• When the room temperature is below the set temperature, heater is on and the control signal
equals 1. When the room temperature is above the set temperature, the control signal equals 0.
• To avoid repeated switching around the set temperature, the thermostat allows a hysteresis of 2
degrees Celsius around the temperature set point. If the thermostat is on, the room temperature
must increase 2 degrees above the set temperature before turning off. If the thermostat is off, the
room temperature must drop 2 degrees below the set temperature before turning on.

10-260
Model House Heating System

This component models the operation of a thermostat, determining when the heating system is on or
off. It contains only one Relay block but logically represents the thermostat in the model.
Subtract Set Room Temperature from Room Temperature

If the set room temperature is warmer than the room temperature, the thermostat model sends an
“on” signal to the heater model. To determine if this is the case, begin by subtracting the room
temperature from the set temperature.

1 Open the Thermostat subsystem. Add a Sum block. Set the parameter List of signs to |+-.
2 Connect the Inport block to the + input of the Sum block. The Inport block sets the room
temperature.
3 Add a second Inport block and connect it to the – input of the Sum block. This second Inport
block is the current room temperature from the room subsystem. Move the output port to the top
of the block. Select the block. In the toolstrip, on the Format tab, select Rotate 90

counterclockwise . If you want, you can reshape the block as shown in the figure by
dragging the handles.
4 Rename the blocks as shown.

Model Thermostat Signal

Model the signal from the thermostat with a hysteresis value of 2 degrees Celsius.

1 In the Thermostat subsystem, add a Relay block. Set the Switch on point parameter to 2, and
the Switch off point parameter to -2.
2 Connect and rename the blocks as shown in the figure.

Prepare Thermostat Model for Simulation

Prepare the Thermostat subsystem for simulation. Think about the expected behavior of the
thermostat and how you can test that behavior with a simulation. When the room temperature rises
above the thermostat setting by 2 degrees, the thermostat output is 0. When the room temperature
moves below the thermostat setting by 2 degrees, the thermostat output is 1.

1
From the Thermostat subsystem, click the Navigate Up To Parent button to navigate to the
top level of your model. Resize the Thermostat block as shown in the figure.

10-261
10 Conditional Subsystems

Notice the Thermostat subsystem now has a second input port. Each input port corresponds to
an Inport block in the subsystem.
2 Add a Constant block for the set temperature. Set the Constant parameter to 25 (degrees
Celsius).
3 Add a Sine Wave block to represent the changing room temperature. Set the Amplitude
parameter to 10, the Bias to 20, and the Frequency to 0.5. These parameters give a variation
above and below the temperature set point of 25.
4 Create and connect Scope Viewer at the Heater port. See “Add Signal Viewer”.
5 Connect the two input signals to the Scope Viewer.

Simulate Thermostat Model and Evaluate Results

Use the default simulation settings to validate your model design.

1 Simulate the model. As the simulation runs, the Scope Viewer plots the results.
2 Open the Scope to view the scope trace.

10-262
Model House Heating System

3 Determine if this result is what you expected.

Initially the room temperature is below the set temperature and the relay is on. When the room
temperature reaches the set temperature, the relay continues to be on until the room
temperature increases by 2 more degrees. Simulation validates the expected behavior.

Model Room Component

Inputs to the room component are heat flow from the heater component and the external air
temperature. The room component uses these inputs to compute heat loss through the walls, heat
loss through the windows, and the current room temperature.

To design the room subsystem, use the Rate of Heat Loss equation and the Changing Room
Temperature Equation.
Model Changing Room Temperature

The rate of temperature change in the room (dTroom/dt) is defined by the equation

dTroom 1 dQgain dQloss


= −
dt mroomair cair dt dt .

The term dQgain/dt is a signal from the Heater subsystem.

1 Open the Room subsystem block. In the Room subsystem, add a Sum block. Set the List of signs
parameter to |+–.
2 Connect In1 to the + input. The input is the heat gain (dQgain/dt) from the heater component.
The – input connects to the heat loss (dQloss/dt) from the room.
3 Add a Gain block. Set the Gain parameter to 1/(m_room_air*c_air). Connect the output of
the Sum block to the input of the Gain block. Label signals as shown in the figure. Dotted signal
lines are signals you will connect later.

10-263
10 Conditional Subsystems

Model Room Temperature

The output of the Gain block is the change in room temperature (dTroom/dt). To get the current
room temperature (Troom), integrate the signal.

1 Add an Integrator block. Set the Initial condition parameter to Troom_IC.


2 Connect the output of the Integrator block to Out1 as shown.

Model Heat Loss Through Walls and Windows

This equation is the rate of thermal energy loss through the walls and windows:

dQloss (Troom − Toutside)


= .
dt R

1 In the Room subsystem, add a Sum block. Set the List of signs parameter to |+–. Select the

block. In the toolstrip, on the Format tab, click Flip left-right .


2 Connect Troom to the Sum block. Click the signal line for Troom and the + input on the Sum
block.
3 Add another Inport block and connect it to the – input of the Sum block. Rename it to Outside
Temperature.
4 Add another Gain block. Set the Gain parameter to 1/R_equivalent. Select the block. In the

toolstrip, on the Format tab, click Flip left-right .


5 Connect the blocks as shown in the figure.

10-264
Model House Heating System

Define Room Model Parameters

You can define parameters in the MATLAB Workspace and then enter their names in the block
parameter dialog boxes. However, a more robust method is to use the Simulink Model Workspace,
which saves parameter values with the model.
1 In the Simulink Editor, on the Modeling tab, under Design, click Model Workspace.
2 In the Model Explorer, select Add > MATLAB Variable.
3 In the middle pane, click the new variable Var and enter the name m_room_air. In the right
pane, enter the value 1470 (kilograms).
4 Add the variables T_roomIC = 20 (degrees Celsius) and R_equivalent = 4.329e-7 (hour·
degree/joule).

Prepare Room Model for Simulation

Prepare the Room subsystem for simulation. Think about the expected behavior and how you can test
that behavior with a simulation. When the heater is off (Heat Gain = 0) and the initial temperature of

10-265
10 Conditional Subsystems

the room (20) is above the outside temperature (10), heat loss should continue until the room
temperature is equal to the outside temperature.

1
From the Room subsystem, click the Navigate Up To Parent button to navigate to the top
level of your model. Resize the Room block as shown in the figure.

The Room block now has a second input port. Each input port corresponds to an Inport block in
the subsystem.
2 Add a Constant block and connect it to the Heat Gain input. Set the Constant value parameter
to 0 (degrees Celsius) to mean that the heater is turned off.
3 Add another Constant block and connect it to the Outside Temperature input. Set the Constant
value parameter to 10 (degrees Celsius).
4 Add and connect a Scope block to view the changing room temperature.

Simulate Room Model and Evaluate Results

1 In the toolstrip, set the Stop Time to 20.


2 Simulate the model.
3
Open the Scope and click the Autoscale button to view the scope trace.

10-266
Model House Heating System

4 Determine if this result is what you expected.

The room temperature starts at the initial room temperature set in the Integrator block. Because
the heat gain is 0, the signal decays to the outside temperature (10). The simulation validates the
expected behavior.

Prepare Room Model for Second Simulation

Set the constant outside temperature to a value above the initial room temperature (20).

In the Constant block that is connected to the Outside Temperature input, set Constant value to 30
(degrees Celsius).

Simulate Model and Evaluate Results

1 Simulate the model.


2
Open the Scope and click the Autoscale button to view the scope trace.

10-267
10 Conditional Subsystems

3 Determine if this result is what you expected.

Room temperature starts at the initially set temperature of 20, but with the heater off (heat gain
= 0) the room temperature rises to the outside temperature — a behavior that the model did not
explicitly specify, and might be considered unexpected.

The equation that models the heat loss also models the heat gain when the outside temperature
is above the inside room temperature. While the model did not explicitly specify this behavior
when the heater is turned off, the result makes sense physically.

Integrate a House Heating Model


Connect model components, add realistic input, and then simulate the model behavior over time to
validate the model design.

10-268
Model House Heating System

Integrate Heater and Thermostat Components

To simulate the heater and thermostat subsystems without the Room subsystem, you need a signal for
the changing room temperature. Use a Constant block to set the thermostat temperature and a Sine
Wave block for a realistic outside temperature signal.
Prepare Model for Simulation

1 Open your model with the completed subsystems. Remove any blocks you added to test the
separate components.
2 Open the Room subsystem. Double-click the Inport block labeled Heat Gain. In the Inport block
dialog box, set Port number to 2. The Heat Gain port moves to the bottom of the Room
subsystem.

3 Connect the Heater (on/off) signal from the Thermostat subsystem output to the Heater
subsystem input.
4 Add a Constant block to set the thermostat room temperature. Set Constant value to 20
(degrees Celsius).
5 Add a Sine Wave block to represent the changing room temperature. Set the parameters
Amplitude to 10 (degrees Celsius), Bias to 15, and Frequency to 0.5.
6 Connect the blocks as shown in the figure.

7 Add a Scope viewer and add the output signals from Heater, Constant, and Sine Wave blocks. See
“Add Signal Viewer”.
8
On the Scope viewer window, in the Configuration Properties button click the arrow and
then click Layout icon . Select two boxes. A second empty graph appears below the first.
9 In the Simulation tab under Prepare, select Viewers Manager.

10-269
10 Conditional Subsystems

10 From the Viewers and Generators Manager, select the Scope. Under Connected Signals, in the
rows for Constant and Sine Wave, select the Display entry and change the Display to 2.

Simulate Model and Evaluate Results

Simulate the model using the default stop time of 10.

1 Simulate the model.


2 Open the Scope Viewer and view the simulation results. The top graph is the heater gain while
the lower graph shows the changing room temperature modeled with a sine wave.

10-270
Model House Heating System

3 Determine if this result is what you expected.

From about 0 to 1.5 hours, the heater is turned on. Heat gain is not constant but changes
because heat gain is a function of the difference between the heater air temperature and the
room air temperature. From 1.5 to 5.6 hours, the heater is turned off and the heat gain (top
graph) is zero. The simulation confirms the expected behavior.

Integrate Room Component

To simulate the Heater and Thermostat subsystems with the Room subsystem, you need a signal for
the changing outside temperature. Simulating the model allows you to observe how the thermostat
setting and outdoor temperature affect the indoor temperature.
Prepare Model for Simulation

1 Open your model with completed subsystems. Remove any blocks you added to test the separate
components.

10-271
10 Conditional Subsystems

2 Connect the subsystems as shown.

3 Add a Constant block for setting the room temperature. Set Constant value parameter to 20
(degrees Celsius).
4 Add a Sine Wave block to represent the changing outside temperature. Set Amplitude to 5, Bias
to 12, Frequency to 2*pi/24, and Phase to 180.

5 Add a Scope Viewer block to view simulation results.


6
In the Signal Viewer, click the Signal Selector button . In the Signal Selector dialog box and
in the left pane, select the top model hierarchy. In the right pane, select the Room and Sine Wave
signals.

Simulate Model and Evaluate Results

1 Set the simulation stop time to 24 (hours) to represent a day.


2 Simulate the model.
3 Open the Scope Viewer and view results.

10-272
Model House Heating System

4 Determine if the simulation result matches your expectation.

When the outside temperature is below the set room temperature, the room temperature
fluctuates 2 degrees above and below the set temperature. Since the thermostat subsystem
includes a 2 degree hysteresis, this simulation result is expected.
5 You can compare your results with an example model. In the MATLAB Command Window, enter
the command below.

open_system('ex_househeat_modeling_prepared')

Refine Model Parameters

With Simulink models, you can interactively change model parameters and then observe changes in
the behavior of your model. This approach allows you to evaluate your model quickly and validate
your design.

Change the outside temperature in the Sine Wave block so that upper values are above the set
temperature.

1 In the Sine Wave dialog box, set Amplitude to 5 and Bias to 19. These settings show what
happens when outside temperature is higher than inside temperature.
2 Simulate the model and view the results.

10-273
10 Conditional Subsystems

3 Determine if the results match your expectations.

When the outside temperature is above the set temperature, the room temperature follows the
outside temperature with a slight delay. In this case, heat loss works in the reverse direction -
and represents the loss of heat from the outside environment into the room.

Model External Interface

Model the external interface for further testing and possible use in a larger model. In Simulink, you
model the external interface using Inport and Outport blocks.

1 Add Inport blocks to read data from the outside temperature and thermostat set temperature into
your model.
2 Add Outport blocks to connect the outside temperature and room temperature to a larger model
or to visualize results.

10-274
Model House Heating System

Specify Physical Units

By specifying physical units for model signals, you ensure the consistency of calculations across
model components. In Simulink, you specify signal units through Inport and Outport blocks.

1 Double-click the In1 block to open the Block Parameters dialog box. Select the Signal
Attributes tab.
2 In the Unit box, start typing degree. From the list of symbols and names, select °C
degree_Celsius.

For the remaining temperature Inport and Outport blocks, set the Unit parameter to °C
degree_Celsius.
3 Display units on block ports. On the Debug tab, select Information Overlays > Units.
4 Double-click the Heater Subsystem block. Double-click the Heat Gain Outport block to open the
Block Parameters dialog box. Select the Signal Attributes tab.

5 In the Unit box, start typing joule/hour. From the list of symbols and names, select joule/h
joule/hour.
6 Update the model. Press Ctrl+D.

Your next step is to verify the correctness of the model by comparing simulations with real system
data.

10-275
10 Conditional Subsystems

Prepare for Simulation


After initial simulations, you can use the results to improve the model to match model behavior to
measured data. After you prepare the model for simulation, you can use an interface to input
measured system data and set room temperature.

To load the finished example model, in the MATLAB Command Window, enter:

open_system('ex_househeat_simulation_prepared')

Verify that a simulation represents the behavior of the system you modeled. Begin by experimentally
measuring physical characteristics of the system that have comparable signals in your model:

• Collect data from physical system


• Prepare model for simulation

Collect and Plot System Data

Measure the dynamic characteristics from an actual house heating system. You will use the measured
data with model simulations to verify the behavior and accuracy of your model.

1 Measure the outside and inside temperatures of a house every 6 minutes for 24 hours.
2 Enter the measured data into a Microsoft Excel worksheet or open an example spreadsheet. In
the MATLAB Command Window, enter

winopen('ex_househeat_measured_data.xls')

10-276
Model House Heating System

3 Review a plot of the measured data. The inside temperature data shows temperature spikes when
the hot air heater turns on. This pattern is typical for a hot air heating system.

Prepare Model for Simulation

Prepare a model for simulation by adding an external interface for data input and input control
signals.

1 Use the model you created in the tutorial Model House Heating System or open the example
model. In the MATLAB Command Window, enter

open_system('ex_househeat_modeling')

10-277
10 Conditional Subsystems

2 Replace the Inport block In2 with a Constant block and set the Constant parameter to 20. The
Constant block sets the thermostat temperature.
3 Add an Inport block. Set Port number to 1. This action also sets the Port number of the outside
temperature signal to 2.
4 Rename the first Inport block to Inside Temperature. Rename the second Inport block to
Outside Temperature.
5 Add an Outport block and connect it to the first Inport block (Inside Temperature). The Outport
blocks are needed for saving (logging) the signals. Set Port number to 1.

Run and Evaluate Simulation


Verify the accuracy of the model and optimize parameters. Some parameters to consider for
optimization are heater hysteresis, temperature offset, and the resistance of the house to heat loss.
Follow these steps to verify your model:

• Import data
• Run a simulation

10-278
Model House Heating System

• Evaluate the simulation result


• Change model parameters
• Rerun the simulation

Import Data with Root Inport Mapping

You can use the Root Inport Mapper tool to bring measured signal data from an Excel spreadsheet
into a Simulink model.

1 Open any Inport block. Click the Connect Inputs button to open the Root Inport Mapper.
2 On the toolstrip, click From Spreadsheet.
3 In the From Spreadsheet dialog box, click the browse button. Browse to and select the file
ex_househeat_measured_data.xls. Click Open. Click OK to import the spreadsheet.
4 On the left side, select Sheet1. The Scenario Signal column shows the two signals from the
Excel spreadsheet and an icon indicating the signals are unmapped.

5 On the toolstrip, select the Map Mode Port Order option. From the Options drop-down list,
select the Update Model Automatically check box.
6 From the Check Map Readiness dropdown list, select Map Unconnected. The mapping
summary shows the signals from the Excel spreadsheet mapped to the Input port blocks.

The mapping summary shows Sheet1 is marked for simulation and a Dataset object is created
in the MATLAB Workspace.
7 Save the signal data in a MAT-file. In the MATLAB Command Window, type

10-279
10 Conditional Subsystems

save('ex_househeat_measured_data.mat', 'Sheet1')

Configure Model to Load Signal Data

Signal data mapped to input ports is located in a MATLAB workspace variable. With each new
MATLAB session, you have to manually reload the data or let the model preload function do it for you.

1 From the Simulink Editor, on the Modeling tab, select Model Settings > Model Properties to
open the Model Properties dialog box.
2 Select the Callbacks tab.
3 In the Model callbacks section, select PreLoadFcn.
4 In the Model pre-load function box, enter

load('ex_househeat_measured_data.mat')
5 Click OK.

Configure Model to Save Simulation Results

Configure your model to save (log) signal data during a simulation. You can then view logged signals
from a simulation using the Simulation Data Inspector.

1 In the model, on the Modeling tab, click Model Settings.


2 In the left pane, select Data Import/Export.
3 In the right pane, clear the Time and Output check boxes.
4 Select the Signal logging check box.
5 Select the Record logged workspace data in Simulation Data Inspector check box.
6 Click OK.

Select Signals to Save

Identify signals to display in the Simulation Data Inspector, name the signals if they are unnamed,
and set the logging parameters.

1 Right-click the Inside Temperature signal line and select Properties.


2 In the Signal name box, enter Measured Room Temperature. Select the Log signal data
check box. A logging badge appears above the signal line.
3 Name and select logging for these signals.

Location of signal Signal name


Outside Temperature from output port Measured Outside Temperature
2.
Room Temperature from Room Room Temperature
subsystem output port

Run Simulation

After importing data and enabling logging of data for the signals, you can run a simulation.

1 Use the model you prepared for simulation or open the example model. In the MATLAB
Command Window, enter

10-280
Model House Heating System

open_system('ex_househeat_simulation_prepared')

2 On the Simulink Toolstrip, set Stop Time to 24 (hours).


3
Click the Run button .

The model simulation runs from 0.0 to 24.0 hours using the outside temperature data from the
root import block as input.

Compare Simulation Results with Measured System Data

Use the Simulation Data Inspector to compare the simulated output signals with measured data.

1
On the Simulink Toolstrip, click the Simulation Data Inspector button .

A separate run appears in the Runs pane each time you simulate the model.
2 Select all the signal check boxes. The graph show the plot of each signal you select.

10-281
10 Conditional Subsystems

The top signal is the Measured Room Temperature. The middle signal is the Measured Outside
Temperature. The bottom signal is the simulated Room Temperature.

Determine Changes to Model

One obvious change to the model is the hysteresis of the thermostat. The simulated room
temperature oscillates 18–22 degrees around the temperature set point of 20 degrees. The measured
room temperature oscillates 20–25 degrees with the same set point.

1 Open the Relay block in the Thermostat subsystem.


2 Change Switch on point from 2 to 0 because the difference between the room temperature and
set point is 0.
3 Change Switch off point from -2 to -5. When the room temperature is 5 degrees above the set
point, you want to turn off the heater. The set point is 5 degrees below the room temperature.

Compare Results Between Simulations

Use the Simulation Data Inspector to compare differences between two simulations that use different
model parameters. This comparison shows how changes improve the accuracy of your model.

1 Simulate the model.


2 Open the Simulation Data Inspector.
3 Expand the list of logged signals by selecting the arrow to the left of the run. For Run1, select
the Measured Outside Temperature and Measured Room Temperature check boxes. For
Run2, select the Room Temperature check box.

10-282
Model House Heating System

4 Review the signals. The minimum and maximum values for the simulated room temperature now
match the measured room temperature values.

10-283
10 Conditional Subsystems

Wireless Tire Pressure Monitoring System with Fault Logging

This example shows how to design, model, and simulate a distributed monitoring system. In this
system, multiple sensors communicate wirelessly with a controller. The controller takes action when
it detects a fault condition and maintains a log of fault conditions. The example uses a model of an
automotive tire pressure monitoring system with identical pressure sensors at each wheel that
communicate wirelessly with a controller in the vehicle using a unique device ID that is known to the
controller. The controller checks the pressure readings against the acceptable range. If a pressure
reading is out of range, or if the controller has lost communication with one of the sensors, the
controller activates a warning lamp, and records the fault in a log.

Run this command to create and open a working copy of the project files for this example:

slexTirePressureMonitoringSystem

Model Overview

The model contains four identical tire pressure sensors modeled by multi-instanced Model blocks that
represent sensors on the four tires of a vehicle. The sensors periodically send messages to the
controller. Each message consists of a tire pressure reading and the device ID of the sensor. All
messages are routed to the controller via a Message Merge block and are buffered by a Queue block.

Messages in Simulink® combine events with related data. Messages are used to model
communication between components in a distributed system, such as the communication between the
sensors and the controller in this system. See “Simulink Messages Overview” on page 11-2.

The controller may also receive communications from sensors on other vehicles nearby. The
controller has the list of the device IDs of the relevant sensors so that it can determine which
communications to examine and which ones to reject.

To model the external environment in which the system operates, the model contains a fifth instance
of the sensor model, representing a tire pressure sensor on a nearby vehicle, and which transmits
messages that are received by the controller.

10-284
Wireless Tire Pressure Monitoring System with Fault Logging

Controller Unit

The controller receives discrete communications from each of the sensors as they are sent via
wireless communication, middleware, or a combination of both. Each communication consists of a tire
pressure reading from the physical hardware together with the unique device ID of the sensor unit.
The combination of pressure data and device ID form a composite signal of different data types
(double and character vector). This type of signal is reused throughout the model. Thus, defining a
Simulink.Bus type for this combination makes sense. The communications may or may not be
received periodically, so they are treated as asynchronous. The asynchronous communications are
modeled as messages in Simulink, with the bus as the message payload.

The controller may also receive communications from sensors on other vehicles nearby. These
communications are also modeled as messages with the same bus type. The controller model
controllerCoreAlgorithm.slx receives as a model argument the list of the device IDs of the
relevant sensors so that it can determine which communications to examine and which ones to reject.

Incoming communications from sensors are received and buffered in a Stateflow® chart and then
passed to a MATLAB Function block. The MATLAB Function block checks each the device ID in each
message against the valid device ID list, rejects messages with no match, and outputs these vectors
at each time step:

• A four-element logical vector indicating whether a current sensor reading was received from each
tire
• A four-element data vector containing the sensor readings

These vectors are passed to a for-each subsystem, which applies the same algorithm to each sensor.
Both of these inputs to the for-each subsystem are partitioned, along with the valid device ID list.

10-285
10 Conditional Subsystems

The controller model arguments include:

• The acceptable range for the tire pressure data measured by the sensors
• How frequently the sensors are expected to transmit data in order not to be considered to have
timed out.

Within the for-each subsystem, a Stateflow chart is used to model the temporal logic of checking for
timeouts as well as to check whether the pressure reading is within the valid range.

When the controller detects a fault, the fault is recorded in a fault log, which is modeled by a Data
Store Memory block, representing an area of RAM in the controller. Each log entry consists of the
device ID and the type of fault: pressure too high, pressure too low, lost contact with sensor. The type
of fault is an enumerated data type defined for this purpose. The combination of device ID and type of
fault used in the fault log entries form a composite signal type, is defined using a Simulink.bus
type with these two fields. The Simulink function logFault performs the fault logging by prepending
the new fault information to the fault log. The Stateflow chart calls this function each time it detects a
fault.

The Stateflow chart receptionStatusChart outputs a logical signal for each of the possible fault
conditions, and the for-each subsystem concatenates these output signals into logical vectors. These
signals are combined with logical operators into a single, scalar, logical output for the controller that

10-286
Wireless Tire Pressure Monitoring System with Fault Logging

indicates the presence or absence of a fault condition. This signal can be used to trigger a warning
lamp or audible alarm when there is a fault condition.

The list of acceptable sensor device IDs is an instance parameter of the controller model, as are the
minimum and maximum acceptable values for tire pressure and the timeout interval. The controller
algorithm can be deployed in different applications with different values of these parameters.

Sensor Units

Each sensor measures data from the physical environment, that is, tire pressure. In the sensor model,
this input is modeled with a root Inport block. The pressure measurement is combined with the
unique device ID into a bus signal using the Simulink.bus type defined for this purpose. The bus
signal is the payload of the message output of the sensor, which is created by a Message Send block
and sent to the root Outport. The sensors are designed to transmit readings periodically. However,
the communications are treated as asynchronous to account for uncertainty in transmission and
reception. Each message represents a discrete, asynchronous transmission sent through wireless
communication, middleware, or a combination of both.

The unique device ID is an instance parameter of the sensor model, which is multi-instantiated to
represent the multiple tires of the vehicle. The sensor models are identical apart from this instance
parameter.

System Model

In the system model, the controller unit is represented by a referenced model, and the sensor units
are represented by a multi-instantiated referenced model. The communication between the sensors
and the controller is modeled with messages in Simulink. The messages are combined with a
Message Merge block into a single channel and buffered by a Queue block that represents a queue in
the reception firmware.

The inputs to the system are the sensor readings from the physical environment, which are fed into
the input ports of the sensor models. Source blocks can be used to model sensor readings. Here,
varying inputs are modeled using Sine Wave blocks, with a sample time based on the frequency of
pressure measurements. The output of the system is the control signal, which indicates the presence
or absence of a fault condition.

In addition to the control signal at the outport, the system maintains a log of recorded fault
conditions. The log is internal to the system, but it represents in effect part of the system output that
can be examined and tested.

An additional sensor model represents a sensor on a nearby vehicle. The transmissions of this sensor
model can be received by the controller, though the device ID of this sensor is not on the list of valid
device IDs used by the controller. This model is also driven by a Sine Wave block. The message

10-287
10 Conditional Subsystems

outputs of this sensor unit are merged with the messages from the vehicle sensors and sent to the
controller unit.

Data types such as Simulink.bus types and enumerated types that are used by the models are
stored in a shared data dictionary commonData.sldd, which allows all models to have access to the
definitions. See “What Is a Data Dictionary?” on page 80-2.

Simulating the Model

The Sine Wave blocks used as inputs are configured so that some inputs are outside the acceptable
tire pressure range, which triggers a fault condition. After simulating the model, you can observe the
results in the Simulation Data Inspector.

The bottom plot shows when the control signal that activates the warning lamp is enabled. The
warning lamp is activated when the rear right tire pressure is in excess of the maximum acceptable
value of 4.5 and when the front left tire pressure is less than the minimum acceptable value of 1.25,
but the unrelated sensor does not trigger the warning lamp.

See Also
MATLAB Function | Simulink Function

Related Examples
• “Prepare Sensor and Controller Models in a Distributed Monitoring System for Code
Generation” on page 10-289

10-288
Prepare Sensor and Controller Models in a Distributed Monitoring System for Code Generation

Prepare Sensor and Controller Models in a Distributed


Monitoring System for Code Generation

This example shows how to take a Simulink® model containing a reusable algorithm and prepare that
model to generate code that is deployable on a target hardware platform where the algorithm is
implemented in a component as part of a system. The algorithms are contained in the controller and
sensor models from the tire pressure monitoring system described in “Wireless Tire Pressure
Monitoring System with Fault Logging” on page 10-284. The algorithms themselves do not depend on
the hardware platform, but the inputs and outputs at the component interfaces are platform-
dependent. The example shows how to integrate custom code to handle these aspects of the
operation of the components:

• Receiving data from the physical environment


• Communication between components
• Sending signals to other systems
• Interacting with non-volatile memory (NVM)

NVM is used to store the unique device IDs of the sensors in the system and to maintain the fault log
between power cycles. By using NVM, the same code can be burnt into the CPU on multiple devices
during manufacturing, and the unique IDs can be subsequently flashed into NVM.

Run this command to create and open a working copy of the project files for this example:

slexTirePressureMonitoringSystem

Sensor Wrapper Model

To generate code for the sensor units, the sensor model sensorCoreAlgorithm is placed inside a
wrapper model that is used as the top-level model for code generation. The local device ID parameter
of the sensor model is a dummy value. The wrapper model contains an Initialize Function block that
reads the local device ID for the sensor from NVM on power-up and writes it to the sensor model
device ID parameter using a Parameter Writer block. Reading from NVM is performed by a MATLAB
Function block, which calls custom code for this purpose.

10-289
10 Conditional Subsystems

Similarly, MATLAB Function blocks that call custom code are used to retrieve tire pressure
measurement data from the sensor and to send the data to the controller. The measurement data are
fed as input to the sensor model. A Message Receive block receives the messages that are output
from the sensor model and extracts the payload, which is passed to a MATLAB Function block for
transmission to the controller via wireless communication, middleware, or a combination of both.

The file SensorTargetSpecificCodeExternalDependency.m defines the MATLAB class


SensorTargetSpecificCodeExternalDependency as a subclass of the
coder.ExternalDependency (MATLAB Coder) class. The coder.ExternalDependency class is a
base class that is useful for interfacing with external C/C++ code from MATLAB code. See “Develop
Interface for External C/C++ Code” (MATLAB Coder). The classdef defines public methods to read
from NVM, read pressure data, and transmit data. The MATLAB Function blocks in the sensor
wrapper model call these methods to perform these functions. These methods in turn call custom C
code functions using coder.ceval (MATLAB Coder). These custom code functions are defined in
sensor_hand_code_header.h and sensor_hand_code_source.c. For the purpose of this
example, these files contain stub functions, which allow the model to compile and to generate code
that implements the desired algorithm using generic driver calls. To generate and deploy code on a
particular hardware target, replace the stubs with the corresponding target-specific code.

Controller Wrapper Model

To generate code for the controller units, the controller model controllerCoreAlgorithm is
placed inside a wrapper model that is used as the top-level model for code generation. The sensor
device ID list parameter of the controller model is a dummy value. The wrapper model contains an
Initialize Function block that reads the sensor device ID list for the system from NVM on power-up
and writes it to the sensor device ID list parameter using a Parameter Writer block. The Initialize
Function block also reads the previously saved contents of the fault log from NVM and loads them
into RAM by using a Data Store Write block to write them to the data store that is used for the fault
log while the system is operating.

10-290
Prepare Sensor and Controller Models in a Distributed Monitoring System for Code Generation

The wrapper model contains a Terminate Function block that executes on power-down. The
Terminate Function block reads the updated contents of the fault log using a Data Store Read block
and writes these contents to NVM. In this way, the fault log contents are maintained between power
cycles.

Reading from and writing to NVM are performed by MATLAB Function blocks, which call custom
code for this purpose. Interacting with NVM only on startup and shutdown and using RAM for
memory needs during operation minimizes wear and tear on NVM.

The controller wrapper model contains a MATLAB Function block that calls custom code to receive
message communications from the sensors. At one outport, the block outputs a function call signal
each time a message is received and outputs the message payload at the other outport. These outputs
are used to drive a function-call subsystem, which uses a Message Send block to send a message
containing the payload each time it receives a function-call signal.

10-291
10 Conditional Subsystems

This message is sent to the controller model message input port through a Queue block that
represents a LIFO, overwriting-type queue. The function-call subsystem and the Queue block
implement an internal queue in the code that is generated for deployment to the controller hardware.

The logical output signal of the controller block is fed into a MATLAB Function block in order to
enable a warning lamp and again calls custom code for this purpose.

The file ControllerTargetSpecificCodeExternalDependency.m defines the MATLAB class


ControllerTargetSpecificCodeExternalDependency as a subclass of the
coder.ExternalDependency class. The classdef defines public methods to read from and write
to NVM, receive message communications, and enable a warning lamp. The MATLAB Function blocks
in the controller wrapper model call these methods to perform these functions. These methods in turn
call custom C code functions using coder.ceval. These custom code functions are defined in
controller_hand_code_header.h and controller_hand_code_source.c. For the purpose of
this example, these files contain stub functions, which allow the model to compile and to generate
code that implements the desired algorithm using generic driver calls. To generate and deploy code
on a particular hardware target, replace the stubs with the corresponding target-specific code.

See Also
Initialize Function | Terminate Function

Related Examples
• “Wireless Tire Pressure Monitoring System with Fault Logging” on page 10-284

10-292
Fixed-Point Data Type Support for If Block

Fixed-Point Data Type Support for If Block


This topic explains how to use a Compare To Constant block for If block fixed-point data type support.

Floating-Point Model without Fixed-Point Data

Open this floating-point model without fixed-point data types.

open_system("ex_if_block_floatingpoint.slx");

Block and Model Configurations


In this model, the If Action Subsystem blocks use their default configurations. The simulation
parameters are set to their default values except for the parameters listed in this table.

Configuration Parameter Parameter Setting


Pane
Solver Start time 0.0
Stop time 1.0
Type Fixed-step
Solver discrete (no continuous
states)
Fixed-step size 0.1

The block parameters are set to their default values except for the parameters listed in this table.

Block Parameter Setting


Repeating Sequence Stair Vector of output values [-2 -1 1 2].'

10-293
10 Conditional Subsystems

Block Parameter Setting


Repeating Sequence Stair1 Vector of output values [0 0 0 0 1 1 1 1].'
If Number of inputs 2
If expression (u1 > 0) | (u2 > 0.5)
Show else condition Selected
Constant Constant value -4
Constant1 Constant value 4
Scope Number of axes 3
Time range 1

For this model, when input u1 is greater than 0 or input u2 is greater than 0.5, the output is 4.
Otherwise, the output is -4. The Scope block displays the output from the Merge block with inputs u1
and u2.

Model with If Action Subsystems and Fixed-Point Data Types

You can implement this block diagram as a model with fixed-point data types. Open this model with
fixed-point data types.

open_system("ex_if_block_fixedpoint.slx");

10-294
Fixed-Point Data Type Support for If Block

Model Analysis
The Repeating Sequence Stair blocks output fixed-point data types.

The Compare To Constant blocks implement two parts of the If expression that is used in the If block
in the floating-point version of the model, (u1 > 0) and (u2 > 0.5). The OR operation, (u1|u2),
can still be implemented inside the If block. For a fixed-point model, the expression must be partially
implemented outside of the If block as it is in this model.

The block and simulation parameters for the fixed-point model are the same as for the floating-point
model with these exceptions and additions.

Block Parameter Setting


Compare To Constant Operator >
Constant value 0
Output data type mode Boolean
Enable zero-crossing detection off
Compare To Constant1 Operator >
Constant value 0.5
Output data type mode Boolean
Enable zero-crossing detection off
If Number of inputs 2
If expression u1|u2

See Also
Action Port | If | If Action Subsystem | Subsystem

10-295
10 Conditional Subsystems

Related Examples
• “Simulink Subsystem Semantics”
• “Modeling Clutch Lock-Up Using If Blocks”
• “If-Then-Else Blocks”

10-296
11

Messages in Simulink

• “Simulink Messages Overview” on page 11-2


• “Animate and Understand Sending and Receiving Messages” on page 11-6
• “Use a Queue Block to Manage Messages” on page 11-13
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Connect Message Receive Interface with Simulink Functions” on page 11-27
• “Modeling Message Communication Patterns with SimEvents” on page 11-30
• “Build a Shared Communication Channel with Multiple Senders and Receivers” on page 11-32
• “Model Wireless Message Communication with Packet Loss and Channel Failure” on page 11-38
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48
• “Send and Receive Messages Carrying Bus Data” on page 11-59
• “Use Virtual Buses with Message Elements for Component Communication” on page 11-61
• “Merge Message Lines Using a Message Merge Block” on page 11-69
• “Specify Queue Properties for Message Interface” on page 11-71
• “Use the Sequence Viewer to Visualize Messages, Events, and Entities” on page 11-77
• “Using Message Polling and Message Triggered Subsystems” on page 11-87
• “Asynchronous Message Handling in Adaptive Cruise Control” on page 11-94
• “Temperature Control System Communicating with Messages” on page 11-101
11 Messages in Simulink

Simulink Messages Overview


Message-based communication is necessary in various applications, such as control system
architectures in which centralized architectures are replaced with distributed architectures due to
the complexity of the systems. In a distributed architecture, multiple components of the system
communicate via a shared network.

A distributed architecture has these three elements:

• Component — Represents partitions of a design that performs a set of functionalities or


algorithms with defined I/O interfaces. Generally, components generate events and data
asynchronously.
• Interface — Provides a shared boundary through which components of the system communicate.
To provide asynchronous communication, messages are useful modeling artifacts that combine
events with related data.
• Middleware — Provides the services needed by the components to support asynchronous
communication across the shared network.

Below is an illustration that shows the composition of a distributed architecture and its elements.

When modeling such an architecture, you typically model components that are clearly identifiable,
reusable, and deployable. To achieve asynchronous event-based communication between components,
use message send and receive interfaces. Model the middleware to facilitate the network topology
that represents the connectivity of components, such as one-to-many, many-to-one, or many-to-many
based on the number of message sending and receiving components. For an example, see “Build a
Shared Communication Channel with Multiple Senders and Receivers” on page 11-32.

To learn how to model a distributed architecture, using Simulink, SimEvents, and Stateflow, see the
illustration below. The illustration includes two message sending and three message receiving
components that are created as referenced models. You can model components with send and receive
interfaces using Simulink Send and Receive blocks. If your send and receive interfaces involve states

11-2
Simulink Messages Overview

or require decision logic, use a Stateflow chart. You can also model event-driven or message
triggered receive interfaces using Message Triggered Subsystem.

After you model your components and interfaces:

• Simulate the behavior of your distributed architecture by modeling the middleware using
SimEvents. Using the blocks from the SimEvents library, you can model custom routing and
communication patterns, such as merging, delaying, distributing, and broadcasting messages, and
investigate the effects of middleware on your communication network.
• Generate code for your components, including the interface, and connect to your middleware or
an operating system communication API.

Model Message Send and Receive Interfaces and Generate Code


Let us start by understanding how message blocks work. To create a model that uses messages, use
Send blocks to convert data and send messages and Receive blocks to receive and convert messages
to data. For a simple example that shows how Send and Receive blocks work, see “Animate and
Understand Sending and Receiving Messages” on page 11-6.

Use Send and Receive blocks to model message send and receive interfaces for your components. For
a simple example that shows the basics of creating send and receive interfaces, see “Establish
Message Send and Receive Interfaces Between Software Components” on page 11-23. To learn how
to generate code for the same model, see “Generate C++ Messages to Communicate Data Between
Simulink Components” (Embedded Coder).

11-3
11 Messages in Simulink

You can further modify send and receive interfaces for custom behavior. For example, you can
synchronize when a receive interface executes to when data is available. For more information, see
“Connect Message Receive Interface with Simulink Functions” on page 11-27.

After modeling, generate code for your send and receive interfaces and connect them to the
middleware or an operating system communication API. For an example that generates code for a top
model and allows your application to communicate in a distributed system that uses an external
message protocol service (for example, DDS, ROS, SOMEIP, or POSIX messages), see “Generate C++
Messages to Communicate Data Between Simulink and an Operating System or Middleware”
(Embedded Coder).

Model Event-Driven Receive Interfaces


Use Message Triggered Subsystem block to configure your subsystem to be triggered by messages
and to respond to events.

When you use Message Triggered Subsystem block in scheduled mode, the execution order of the
subsystem can be scheduled as aperiodic partitions using the Schedule Editor to model an
asynchronous behavior. The subsystems pull and process the data based on a schedule instead of
periodic execution. For an example, see “Asynchronous Message Handling in Adaptive Cruise
Control” on page 11-94.

Simulate Middleware Effects on a Distributed Architecture


Use Queue blocks to store, sort and queue messages. The Queue block allows you to specify message
storage capacity and the overwriting and sorting policies for message transitions. For a simple
example that shows how a Queue block works, see “Use a Queue Block to Manage Messages” on
page 11-13.

You can also use SimEvents to model and simulate middleware effects on your communication
network. Use the blocks provided by the SimEvents library to model message routing, peer-to-peer
communication, wireless communication, packet loss, and channel delays. For more information
about SimEvents, see “Discrete-Event Simulation in Simulink Models” (SimEvents).

For basic communication patterns that can be modeled by SimEvents, see “Modeling Message
Communication Patterns with SimEvents” on page 11-30. You can use combinations of these
patterns to create more complex communication behavior. For an example of a system with multiple
message sending and receiving components and an ideal shared channel with delay, see “Build a
Shared Communication Channel with Multiple Senders and Receivers” on page 11-32. To see a
model with shared wireless channel with channel failure and packet loss, see “Model Wireless
Message Communication with Packet Loss and Channel Failure” on page 11-38.

To see an example that shows how to model more complex network behavior, such as an Ethernet
communication network with CSMA/CD protocol, see “Model an Ethernet Communication Network
with CSMA/CD Protocol” on page 11-48.

Note SimEvents blocks do not support code generation.

See Also
Sine Wave | Send | Receive | Queue | Sequence Viewer

11-4
Simulink Messages Overview

More About
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-
23
• “Connect Message Receive Interface with Simulink Functions” on page 11-27
• “Generate C Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Model Message-Based Communication Integrated with POSIX Message Queues” (Embedded
Coder)
• “Discrete-Event Simulation in Simulink Models” (SimEvents)

11-5
11 Messages in Simulink

Animate and Understand Sending and Receiving Messages

This example shows how to send, receive, and visualize messages. The example also shows how to
use Simulation Data Inspector, Sequence Viewer, Animation, and Storage Inspector to understand
how messages flow in your model.

Model Description

The SimpleMessagesModel contains these blocks:

• Sine Wave — The signal source. The Sample time parameter of the block is set to 0.1.

• Send — Converts data signals and send messages. The specified value for the Sample time
parameter of the Sine Wave block determines the rate at which the Send block sends messages.
Therefore, the Send block sends one message every 0.1 simulation time.

• Queue — Stores messages. Observe the message line between the Send block and the Queue
block. The default capacity of the queue is 16, which means the Queue block can store at most 16
messages. The default message sorting behavior is LIFO, which means incoming messages are
sorted based on last-in-first-out policy. By default, the Overwrite the oldest element if queue is
full check box is selected. When the queue is full, an incoming message overwrites the oldest
message in the queue. For more information about using the Queue block, see “Use a Queue Block
to Manage Messages” on page 11-13.

• Receive — Receives messages and converts them to signal data. In the block, Sample time
parameter is set to 0.1. The Receive block receives a message every 0.1 simulation time.

• Scope — Visualizes messages received by the Receive block.

Simulate the Model and Review Results

In the model, data logging is enabled for the signal and message lines among Sine Wave, Send,
Queue, Receive, and Scope blocks.

Simulate the SimpleMessagesModel and observe from the Simulation Data Inspector that:

• The Sine Wave block generates the sine wave signal (green).

• Every 0.1 simulation time, Send block converts the value of the signal to a message and sends it
to the Queue block. Simulation Data inspector displays messages as stem plots. Observe the
Simulation Data Inspector displaying sent messages (purple).

11-6
Animate and Understand Sending and Receiving Messages

• The Queue block sends messages to the Receive block (blue).

• Receive block output is the reconstructed sine wave signal (orange).

Use Sequence Viewer to Visualize Messages

You can use the Sequence Viewer tool or the Sequence Viewer block to visualize messages, events,
and Simulink function calls. The Sequence Viewer displays message transition events and the data
that the messages carry. In the Sequence Viewer window, you can view event data related to
Stateflow chart execution and the exchange of messages between Stateflow charts.

To use the Sequence Viewer tool:

• To activate logging events, in the Simulink Toolstrip, on the Simulation tab, in the Prepare
section, click Log Events.

11-7
11 Messages in Simulink

• Simulate your model. To open the Sequence Viewer tool, on the Simulation tab, in the Review
Results section, click Sequence Viewer.

The Log events and Sequence Viewer buttons are visible when your model has blocks from the
Simulink® Messages & Events library, a Stateflow chart, Function-Call Subsystem, Simulink
Function, or SimEvents® blocks.

The Sequence Viewer window shows messages as they are created, sent, forwarded, received, and
destroyed at different times during model execution. The Sequence Viewer window also displays state
activity, transitions, and function calls to Stateflow graphical functions, Simulink functions, and
MATLAB functions.

You can also add the Sequence Viewer block to your model for visualizing message transitions. For
more information, see “Use a Queue Block to Manage Messages” on page 11-13.

11-8
Animate and Understand Sending and Receiving Messages

Use Animation and Storage Inspector

You can use Animation to animate the model and observe the message flow between model
components. You can specify the speed of the animation as Slow, Medium, or Fast. The option None
disables the model animation.

In the toolstrip, on the Debug tab, locate the Event Animation section.

From the Event Animation section, set the animation speed to Slow.

Simulate the model again. Observe the highlighted message lines representing message flow between
the blocks.

Animation highlights message lines and Simulink function calls based on events rather than time
passed. Within one simulation time, more than one message flow or Simulink function call event can
be highlighted.

Pause the animation. In the Simulink Toolstrip, on the Debug tab, click Pause. Observe that the last
highlighted message line is highlighted in violet.

The Storage Inspector allows you to visualize the details of the stored messages in Queue block.
When you pause the simulation, the Storage Inspector magnifying glass icon appears on the Queue
block. To open the Storage Inspector, click the magnifying glass.

11-9
11 Messages in Simulink

The Storage Inspector does not show any stored messages because messages arriving at the Queue
block are simultaneously received by the Receive block at the same simulation time.

To create a scenario with stored messages, stop the simulation and change the Sample time
parameter of the Receive block to 0.5. Now the Send block sends one message every 0.1 simulation
time, but the Receive block receives messages every 0.5 simulation time. This causes a backlog of
messages that are stored in the Queue block.

Simulate the model again with animation speed set to Slow, and pause the simulation to check the
status in the Storage Inspector. An entity in the Storage Inspector represents stored elements in the
Queue block, in this case, messages. Storage Inspector lists the messages stored in the Queue block
with their ID and data value carried by each message.

Display Message Payload Using Port Value Labels

To display message data using port value labels, right-click the message line emerging from a block
and select Show Port Value Label On Selected Signal.

In the example below, the port value label displayed on the message line that connects the Send block
to the Queue block.

11-10
Animate and Understand Sending and Receiving Messages

If a message carries data as a bus, you can also select the bus elements to display in the port value
label.

The SimpleMessagesPortValueModel is a variation of the SimpleMessagesModel where the


input to the Send block comes from a Bus Creator block. In this example, a bus object
Data_message is created with two elements, sinewave and constant.

To open this model, enter:

open_system('SimpleMessagesPortValueModel');

Right-click the message line emerging from the Send block, click Show Port Value Label On
Selected Signal, and select constant.

Only the values of the constant signal are displayed in the port value label.

11-11
11 Messages in Simulink

If the message transmission stops on a message line, the port value label keeps displaying the last
message payload value.

See Also
Sine Wave | Send | Receive | Queue | Hit Crossing Probe | Sequence Viewer

More About
• “Simulink Messages Overview” on page 11-2
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “View Signal Values Using Port Value Labels” on page 40-8
• “Use a Queue Block to Manage Messages” on page 11-13
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-
23
• “Use the Sequence Viewer to Visualize Messages, Events, and Entities” on page 11-77

11-12
Use a Queue Block to Manage Messages

Use a Queue Block to Manage Messages

This example shows how to use a Queue block to store and queue messages. The Queue block allows
you to specify message storage capacity, overwriting policy, and sorting policy during message
transitions.

Manipulate Message Transitions Using Queue Sorting Policies

The Queue block supports three message sorting policies:

• Last-in-first-out (LIFO) — The newest message in the storage departs first.

• First-in-first-out (FIFO) — The oldest message in the storage departs first.

• Priority — Messages are sorted based on their priority. The priority queue can be used only when
the Overwrite the oldest element if queue is full check box is cleared.

This example uses a simple message-based communication model that is introduced in “Animate and
Understand Sending and Receiving Messages” on page 11-6. The model includes Message Flow 1 and
Message Flow 2 in which messages flow from Sine Wave1 to Scope1 and Sine Wave2 to Scope2.

Model Description

In Message Flow 1 and Message Flow 2:

• The Sample time parameter of Sine Wave1 and Sine Wave2 are set to 0.1. They are identical
sine wave sources.

11-13
11 Messages in Simulink

• The Sample time parameter of Receive1 and Receive2 are set to 0.5. They are identical Receive
blocks.

• The capacity of the Queue1 and Queue2 are 100. Both queues have the same capacity.

• The sorting policy of the Queue1 is LIFO and Queue2 is FIFO, which is displayed under the block
labels. The only difference between two message flow scenarios is the queue sorting policy.

• The signals among Sine Wave1, Receive1, and Receive2 are logged.

Simulate the Model and Review the Results

Simulate the model and observe the results in the Simulation Data Inspector.

Observe the output from Sine Wave1. The output from SineWave2 is not displayed because it is
identical to SineWave1. Also observe that the signal from Receive1 is the representation of the sine
wave but with longer intervals between samples. However, the signal from Receive2 is the first part
of the sine wave reaching to the positive peak because the sorting policy of the Queue block is set to
FIFO and its capacity is large enough to store messages.

11-14
Use a Queue Block to Manage Messages

Queue Block Message Overwriting Policies

You can also specify the Queue block message overwriting policy when the queue is full:

• By default, the Overwrite the oldest element if queue is full check box is selected. The block
is set to always accept an incoming message, overwriting the oldest message in the storage. In
this case, the block overwrites the oldest message, but the message departing the block is
determined by the queue sorting policy.

In this example of queue behavior, messages are enumerated based on their arrival time at the FIFO
and LIFO queues with capacity 8. A new message with number 9 arrives. In FIFO and LIFO cases,
message 9 replaces message 1 because it is the oldest element in the queue. However, observe the
change of head and tail of the queue during this process. In the FIFO queue, message 2 departs first
because it is the oldest message after message 1 is replaced. In the LIFO queue, message 9 departs
first because it is the last message that arrives at the storage. After the message departure, a new
message 10 arrives. The queue accepts the new messages to its empty storage bin.

11-15
11 Messages in Simulink

• If the Overwrite the oldest element if queue is full check box is cleared, the icon of the Queue
block changes and the block does not accept new messages when the queue is full. This is a
blocking queue behavior.

Queue Block with Overwriting Policy Enabled

In the QueueSortingPoliciesModelSequenceViewer model, the capacities of the Queue blocks in


Message Flow 1 and Message Flow 2 are changed to 15. Decreasing the capacity causes the
incoming messages to overwrite the existing ones in the storage.

11-16
Use a Queue Block to Manage Messages

Simulate the model and open the Sequence Viewer block. In the Sequence Viewer block, scroll up or
click the Go to first event icon on the left. Observe the messages departing the block based on FIFO
and LIFO policies.

11-17
11 Messages in Simulink

Both Queue blocks have limited capacity. When their capacity is full, a new incoming message
overwrites the oldest existing message in the queue. Scroll down and observe that the Sequence
Viewer block displays the messages that overwrite the existing ones.

11-18
Use a Queue Block to Manage Messages

An Example of a Blocking Queue Behavior

Open the QueueOverWritingPolicyModel to inspect the blocking queue behavior.

11-19
11 Messages in Simulink

In the Receive block, set the Sample time parameter to 0.5.

Observe that in the Queue block:

• The Overwrite the oldest element if queue is full check box is cleared. Observe the block icon
change.

• The Capacity parameter is set to 16.

• In the Statistics tab, the Number of entities departed, d and Number of entities in block, n
check boxes are selected.

Simulate the Model and Review Results

Simulate the model. Observe the warning displayed in the Diagnostic Viewer. Messages sent by the
Send block were dropped during simulation.

The Queue block blocks the messages when the Overwrite the oldest element if queue is full
check box is cleared. You can increase the capacity of the Queue block to prevent message dropping.

Use Statistics to Analyze Queue Behavior

When the Overwrite the oldest element if queue is full check box is cleared the Statistics tab is
enabled. Use Statistics tab to enable output ports and observe the Queue block statistics. Statistics
are not supported for code generation.

Observe the signals labeled Number of Messages in Block and Number of Messages Departed. Up to
simulation time 2, there are 16 messages in the storage, which is the queue capacity. After that,
Number of Messages in Block takes values 15 and 16 because messages depart every 0.5 simulation
time and a new message arrives.

11-20
Use a Queue Block to Manage Messages

At simulation time 10, a total of 21 messages departs the block.

Use Event Actions

You can also use Event actions, when the Overwrite the oldest element if queue is full check
box is cleared. Event actions are not supported for code generation. For more information, see
“Events and Event Actions” (SimEvents).

Use Event actions to specify the behavior of the message in certain events. For instance, the Entry
and the Exit actions are called just after the message entry and just before message exit. The
Blocked action is called after a message is blocked.

For more information, see “Connect Message Receive Interface with Simulink Functions” on page 11-
27.

You can also model more complex communication policies by using blocks from the SimEvents®
library, which requires a SimEvents® license.

See Also
Sine Wave | Send | Receive | Queue | Hit Crossing Probe | Sequence Viewer

More About
• “Simulink Messages Overview” on page 11-2
• “Animate and Understand Sending and Receiving Messages” on page 11-6

11-21
11 Messages in Simulink

• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-
23
• “Use Virtual Buses with Message Elements for Component Communication” on page 11-61
• “Use the Sequence Viewer to Visualize Messages, Events, and Entities” on page 11-77

11-22
Establish Message Send and Receive Interfaces Between Software Components

Establish Message Send and Receive Interfaces Between


Software Components

This example shows how to model message-based communication between software components that
run in different applications. The example also shows how to prepare model components for C++
code generation.

In this example, the message-based communication is constructed between two components. Send
component sends data and receive component consumes data. In this scenario, after send component
sends messages, they are stored in a queue. Receive component pulls a message based on the logic it
represents.

Two Model blocks, labeled Send Component and Receive Component, represent the components
connected by a message line. Message-based communication is achieved using a Send block and a
Receive block that are connected to the root-level Outport and Inport blocks.

For more information about generating C or C++ code for the model, see “Generate C++ Messages
to Communicate Data Between Simulink Components” (Embedded Coder) and “Generate C Messages
to Communicate Data Between Simulink Components” (Embedded Coder).

You can also generate C++ code for each component, and the code contains necessary software
interfaces that are sufficient for you to connect with an operating system or message middleware. For
more information, see “Generate C++ Messages to Communicate Data Between Simulink and an
Operating System or Middleware” (Embedded Coder).

Send Component

The algorithm in the Send Component can contain logic of any complexity. In the example, a simple
Sine Wave block is used in a subsystem as the signal source. The Sample time parameter of the
block is set to 0.1.

11-23
11 Messages in Simulink

To prepare the Send Component for message-based communication, a Send block is connected to the
root-level Outport block. The Send block converts data signals and send messages.

To prepare the Send Component for code generation, in the Model Configuration Parameters:
1 In the Solver pane, in the Solver selection section, the Type is set to Fixed-step.
2 The Fixed-step size is set to 0.1.
3 In the Code Generation pane, the System target file is set to ert.tlc and Language to C++.
4 The model is saved as mSend.

Receive Component

In the Receive Component, a Scope block is used to represent the algorithm that receives messages.

To prepare the Receive Component, the Inport block is connected to a Receive block. The Receive
block receives messages and converts them to signal data. By default, the Sample time parameter of
the Receive block is -1.

To prepare the Receive Component for code generation, in the Model Configuration Parameters:
1 In the Solver pane, in the Solver selection section, the Type is set to Fixed-step.
2 The Fixed-step size is set to 0.1.
3 In the Code Generation pane, the System target file is set to ert.tlc and Language to C++.
4 The model is saved as mReceive.

Visualize Message Transitions Between Components Using the Sequence Viewer Block

This is a composition model with Send and Receive components. The Model blocks, Send Component
and Receive Component, refer to models mSend and mReceive, respectively.

Simulate the model. Observe the queue inserted by default. An icon above the message line
represents the default queue. The capacity of the default queue is 1 and the message overwriting
policy is enabled. You can customize the queue by using a Queue block between components. For
more information, see “Use a Queue Block to Manage Messages” on page 11-13.

11-24
Establish Message Send and Receive Interfaces Between Software Components

Open the Sequence Viewer block. The block allows you to visualize message transition events and the
data that the messages carry.

The Sequence Viewer block window shows the simulation time in the left vertical bar. Each time grid
row contains events that occur at the same simulation time. Each message transition event is
represented by an arrow that is labeled with the message data value. For more information about the
Sequence Viewer block, see “Use the Sequence Viewer to Visualize Messages, Events, and Entities”
on page 11-77.

In the Sequence Viewer block, scroll up or click Go to first event icon on the left. Observe that at
time zero the Send block sends a message with data value 0 to the Receive block, and at time 0.1 the
block sends another message with data value 0.0998. The block sends a message in every 0.1
simulation time.

See Also
Sine Wave | Send | Receive | Queue | Sequence Viewer

11-25
11 Messages in Simulink

More About
• “Simulink Messages Overview” on page 11-2
• “Connect Message Receive Interface with Simulink Functions” on page 11-27
• “Generate C Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Model Message-Based Communication Integrated with POSIX Message Queues” (Embedded
Coder)
• “Animate and Understand Sending and Receiving Messages” on page 11-6

11-26
Connect Message Receive Interface with Simulink Functions

Connect Message Receive Interface with Simulink Functions

This example shows how to synchronize execution with data availability in message-based systems.
We show how to model this behavior using events and actions. This example builds on another
example, “Establish Message Send and Receive Interfaces Between Software Components” on page
11-23, where two software components communicate using messages.

As with the previous example, the code generation process should apply to the SendComponent and
the ReceiveComponent. The Message Storage models the middleware and data notification events
provided by the middleware.

Below is the composition model with a SendComponent and a ReceiveComponent created by using
two Model blocks. These two Model blocks are connected through a Queue block with message lines.

When a message arrives at the Queue block, its arrival is communicated to the ReceiveComponent by
using Queue entry event action. This activates the Simulink Function block inside the
ReceiveComponent to accept a new message for processing.

To achieve this behavior, in the Queue block, in the Event action tab, in the Entry field, the block
calls the Simulink Function onMessageAvailable(). See “Event Action Languages and Random
Number Generation” (SimEvents) for more information on Event Actions.

11-27
11 Messages in Simulink

When the Simulink Function block is activated, it accepts a message and converts it to a signal.

As a result, messages sent from the SendComponent trigger execution within the ReceiveComponent.
To observe this behavior, use the Sequence Viewer block.

For example, observe the simulation time 0:

1 The arrow from the Send block to the Queue block represents that a message is sent with a data
value of 0.
2 The arrow from the Queue block to the Simulink Function block indicates a call to the
onMessageAvailable() function.
3 An arrow from the Queue block illustrates that the message with data value 0 is received by the
Receive block within this function call.
4 The horizontal, dashed arrow from the Simulink Function block to the Queue block indicates the
return of function onMessageAvailable().

11-28
Connect Message Receive Interface with Simulink Functions

For more information about the Sequence Viewer block, see “Use the Sequence Viewer to Visualize
Messages, Events, and Entities” on page 11-77.

See Also
Sine Wave | Send | Receive | Queue

More About
• “Simulink Messages Overview” on page 11-2
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Generate C Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink Components” (Embedded
Coder)
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Model Message-Based Communication Integrated with POSIX Message Queues” (Embedded
Coder)

11-29
11 Messages in Simulink

Modeling Message Communication Patterns with SimEvents

This example shows how to create common communication patterns using SimEvents®. In message-
based communication models, you can use SimEvents® to model and simulate middleware, and
investigate the effects of communication and the environment on your distributed architecture.

The systems in this example represent common communication patterns created by using
SimEvents® blocks that can be used to simulate various network types, such as cabled or wireless
communication, and channel behavior such as failure, or packet loss.

The communication patterns involve:

• Merging messages from multiple senders.


• Broadcasting messages to multiple receivers.
• Distributing work to multiple receivers.
• Multicasting messages among multiple senders and multiple receivers.
• Running a component based on message availability and data.
• Delaying messages for a set amount of time.

To create more complex networks and channel behavior, use combinations of these simple patterns.

By using these patterns, you can model:

• N -to- n communication with multiple senders and receivers with an ideal channel with
communication delay. For an example, see “Build a Shared Communication Channel with Multiple
Senders and Receivers” on page 11-32.

11-30
Modeling Message Communication Patterns with SimEvents

• N -to- n communication with channel failure and packet loss. For an example, see “Model Wireless
Message Communication with Packet Loss and Channel Failure” on page 11-38.

• An N -to- n Ethernet communication network with an inter-component communication protocol.


For an example, see “Model an Ethernet Communication Network with CSMA/CD Protocol” on
page 11-48.

See Also
Sine Wave | Send | Receive | Queue

More About
• “Simulink Messages Overview” on page 11-2
• “Discrete-Event Simulation in Simulink Models” (SimEvents)
• “Build a Shared Communication Channel with Multiple Senders and Receivers” on page 11-32
• “Model Wireless Message Communication with Packet Loss and Channel Failure” on page 11-
38
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48

11-31
11 Messages in Simulink

Build a Shared Communication Channel with Multiple Senders


and Receivers

This example shows how to model communication through a shared channel with multiple senders
and receivers by using Simulink® messages, SimEvents®, and Stateflow®.

For an overview about messages, see “Simulink Messages Overview” on page 11-2.

In this model, there are two software components that send messages and two components that
receive messages. The shared channel transmits messages with an added delay. SimEvents® blocks
are used to create custom communication behavior by merging the message lines, and copying and
delaying messages. A Stateflow chart is used in a send component to send messages based on a
decision logic.

Create Components to Send Messages

In the model, there are two software components that output messages, Send and StateflowSend.

In the Send component, the Sine Wave block is the signal source. The block generates a sine wave
signal with an amplitude of 1. The sample time for the block is 0.1. The Send block converts the
signal to a message that carries the signal value as data. The Send component sends messages to
Send Buffer 1.

In the StateflowSend component, another Sine Wave block generates a sine wave signal and a Noise
block injects noise into the signal. The Noise block outputs a signal whose values are generated from
a Gaussian distribution with mean of 0 and variance of 1. The sample time of the block is 0.1.

11-32
Build a Shared Communication Channel with Multiple Senders and Receivers

The Stateflow chart represents a simple logic that filters the signal and decides whether to send
messages. If the value of the signal is greater than 0.5 for a duration greater than 0.1, then the
chart sends a message that carries the signal value. If the signal value is below 0, then the chart
transitions to the ReceiveSignal state. The StateflowSend component sends messages to Send
Buffer 2.

For more information about creating message interfaces, see “Establish Message Send and Receive
Interfaces Between Software Components” on page 11-23.

Create Components to Receive Messages

In the model, there are two software components that receive messages, Receive and Listener.

In the Receive component, a Receive block receives messages and converts the message data to
signal values.

In the Listener component, there is a Simulink Function block. The block displays the function,
onOneMessage(data), on the block face.

11-33
11 Messages in Simulink

When a message arrives at Receive Buffer 2, the Listener block is notified and it takes the argument
data, which is the value from the message data, as the input signal. In the block, data values are
multiplied by 2. The block outputs the new data value.

Routing Messages using SimEvents®

In the shared channel, the message paths originating from the two message-sending components are
merged to represent a shared communication channel.

A SimEvents® Entity Input Switch block merges the message lines. In the block:

• Number of input ports specifies the number of message lines to be merged. The parameter
value is 2 for two message paths.

• Active port selection specifies how to select the active port for message departure. If you select
All, all of the messages arriving at the block are able to depart the block from the output port. If
you select Switch, you can specify the logic that selects the active port for message departure.
For this example, the parameter is set to All.

A SimEvents® Entity Server block is used to represent message transmission delay in the shared
channel. In the block:

• Capacity is set to 1, which specifies how many messages can be processed at a time.

11-34
Build a Shared Communication Channel with Multiple Senders and Receivers

• Service time value is set to 1, which specifies how long it takes to process a message

A SimEvents® Entity Replicator block is used to generate identical copies of messages. In the block:

• Replicas depart from specifies if the copies leave the block from separate output ports or the
same output port as the original messages. The parameter is set to Separate output ports.

• Number of replicas is set to 1, which specifies the number of copies generated for each
message.

• Hold original entity until all replicas depart holds the original message in the block until all of
its copies depart the block.

A SimEvents® Entity Terminator block is used to model Receive Buffer 2. In the block:

• Under the Event actions tab, in the Entry action field, you can specify MATLAB code that
performs calculations or Simulink® function calls that are invoked when the message enters the
block. In this example, onOneMessage(entity) is used to notify the Simulink Function block in
the Listener component. To visualize the function call, under Debug tab, select Information
Overlays and then Function Connectors.

Simulate the Model and Review Results

Simulate the model. Observe that the animation highlights the messages flowing through the model.
You can turn off the animation by right-clicking on the model canvas and setting Animation Speed to
None.

When you pause the animation, a magnifying glass appears on the blocks that store messages. If you
point to the magnifying glass, you see the number of messages stored in the block.

11-35
11 Messages in Simulink

To observe which messages are stored in the block, click the magnifying glass to open the Storage
Inspector. For instance, the graphic below illustrates the messages stored in Send Buffer 1.

Turn the animation off and open the Sequence Viewer block to observe the Simulink Function calls
and the flow of messages in the model.

For instance, observe the simulation time 0, during which a message carrying value 0 is sent from the
Send component to Send Buffer 1. From simulation time 0.1 to 0.5, the Send component keeps
sending messages to Send Buffer 1 with different data values. At time 0.5, the StateflowSend
component sends a message to Send Buffer 2. For more information about using the Sequence Viewer
block, see “Use the Sequence Viewer to Visualize Messages, Events, and Entities” on page 11-77.

11-36
Build a Shared Communication Channel with Multiple Senders and Receivers

See Also
Sine Wave | Send | Receive | Queue | Entity Input Switch (SimEvents) | Entity Server (SimEvents) |
Entity Replicator (SimEvents) | Entity Terminator (SimEvents)

More About
• “Simulink Messages Overview” on page 11-2
• “Discrete-Event Simulation in Simulink Models” (SimEvents)
• “Model Wireless Message Communication with Packet Loss and Channel Failure” on page 11-
38
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48

11-37
11 Messages in Simulink

Model Wireless Message Communication with Packet Loss and


Channel Failure

This example shows how to model wireless message communication with packet loss and channel
failure by using Simulink® messages, Stateflow®, and SimEvents®.

In this model, there are two components that send messages and two components that receive
messages. The messages are transmitted using a shared wireless channel with a transmission delay. A
Stateflow® chart models message-sending logic in a wireless component and SimEvents® blocks
model wireless message transmission, channel failure, and packet loss.

For an overview about messages, see “Simulink Messages Overview” on page 11-2.

Create Components to Send and Receive Messages

In the model, there are two software components that output messages, WirelessSend and
WirelessStateflowSend.

In the WirelessSend component, the Sine Wave block is the signal source. The Sine Wave block
generates a sine wave with an amplitude of 1. The block Sample time is set to 0.1. The Send block
converts the signal to a message that carries the data of the signal value. The
WirelessSendComponent is connected to Send Buffer 1.

In the WirelessStateflowSend component, another Sine Wave block generates a sine wave signal and
a Noise block is used to inject noise into the signal. The Noise block outputs a signal whose values
are generated from a Gaussian distribution with mean of 0 and variance of 1. The Stateflow® chart
represents a simple logic that filters a signal and decides whether to send messages. The
StateflowSend component sends messages to Send Buffer 2.

In the model, there are two software components that receive messages, WirelessReceive and
WirelessListener.

11-38
Model Wireless Message Communication with Packet Loss and Channel Failure

In the WirelessReceive component, a Receive block receives messages and converts message data to
signal values. The component is connected to Receive Buffer 1.

In the WirelessListener component, there is a Simulink Function block that runs the
onOneMessage(data) function. When a message arrives at Receive Buffer 3, the Simulink Function
block takes the argument data, which is the value from message data, as the input signal. In the
block, the data values are multiplied by 2. The block outputs the new data value.

To learn more about creating these components, see “Build a Shared Communication Channel with
Multiple Senders and Receivers” on page 11-32.

Model Wireless Message Communication Using Multicasting

The WirelessSend and WirelessStateflowSend components send messages to Send Buffer 1 and Send
Buffer 2, which are SimEvents® Entity Multicast blocks that can wirelessly transmit messages. The
Transmission Buffer block is a SimEvents® multicast receive queue that can receive messages sent
by Send Buffer 1 and Send Buffer 2.

To achieve this wireless communication between Send Buffer 1, Send Buffer 2, and the Transmission
Buffer block that is inside the Wireless Channel block:

1 In the Send Buffer 1 and Send Buffer 2 blocks, set the Multicast tag parameter to A.
2 In the Transmission Buffer block, set the Multicast tag parameter to A.

The Multicast tag parameter defines from which Entity Multicast blocks the messages are received.

11-39
11 Messages in Simulink

Model Channel Failure

A SimEvents® Entity Gate block is used to model channel failure. The block has two input ports. One
input port is for incoming messages from Transmission Buffer. The second input port is a control port
to decide when to open the gate.

Set the Operating mode parameter for the Gate block to Enable gate. In this mode:

• The block opens the gate and permits messages to advance when it receives an entity carrying a
value that is greater than 0 from its control port. This represents an operational channel.

• The block closes the gate and blocks messages passing if an entity carries data whose value is less
than or equal to 0. This represents a channel failure.

To control the Gate block, you can use the SimEvents® Entity Generator block, which is labeled
Control Gate in this example, to generate entities carrying different data values.

In the Control Gate block, in Event actions, in the Generate action field, the code below is used to
generate entities to open and close the Gate block. Initially, entity data is 1 and the gate is open and
the channel is in operational state. When a new entity is generated, its value changes to 0, which
closes the gate. Every generated entity changes the status of the gate from open to closed or from
closed to open.

11-40
Model Wireless Message Communication with Packet Loss and Channel Failure

In the Control Gate block, in the Intergeneration time action field, the code below is used to
represent the operational and failed state of the channel. The code initializes the channel as
operational. dt is the entity intergeneration time and is used to change the status of channel because
each generated entity changes the status of the Gate block.

11-41
11 Messages in Simulink

In the code, the repair time is generated from a uniform distribution that takes values between 0 and
10. The time interval between the failures is generated from another uniform distribution that takes
values between 0 and 50.

Model Packet Loss

To model the packet loss, a SimEvents® Entity Output Switch block is used.

The block has two input ports. One input port accepts messages. The other input port accepts entities
that determine the output port selection. If the entity is set to 1, the block selects output port 1 to
forward messages to the Wirelessly Share Messages block. If the entity is set to 2, the block selects
output port 2, which is connected to an Entity Terminator block that represents packet loss.

11-42
Model Wireless Message Communication with Packet Loss and Channel Failure

In the Output Switch block:

• The Number of output ports is set to 2.

• To determine which output is selected, the Switching criterion is set to From control port
and Initial port selection is set to 1.

To model a 0.1 probability of packet loss, in the Probabilistic Packet Loss block, select the Event
actions tab, and in the Generate action field includes this code:

persistent rngInit;
if isempty(rngInit)
seed = 12345;
rng(seed);
rngInit = true;
end

% Pattern: Uniform distribution


% m: Minimum, M: Maximum
m = 0; M = 1;
x = m + (M - m) * rand;

% x is generated from uniform distribution and


% takes values between |0| and |1|.
if x > 0.1
% Entity carries data |1| and this forces Output switch to select
% output |1| to forward entities to receive components.
entity = 1;
else
% Entity carries data |2| and this forces Output switch to select
% output |2| and this represents a packet loss.
entity = 1;
end

This means that entities entering the control port have a 0.9 probability of being set to 1, which
makes the block output messages to the Wirelessly Share Messages block.

11-43
11 Messages in Simulink

Simulate the Model and Review results

Simulate the model.

• Open the Scope block connected top the Transmission Buffer block. The block displays the total
number of messages transmitted through the shared channel.

4255 messages are transmitted through the channel.

The plot also displays the channel failures. For example, zoom into the first 100 seconds. Observer
that the channel failure occurs between 40 and 49 during which message transmission is blocked.

11-44
Model Wireless Message Communication with Packet Loss and Channel Failure

Open the Data Inspector to visualize the entities that control the Gate. Entity data changes from 1 to
0 for each generated entity.

11-45
11 Messages in Simulink

To see the number of lost messages, open the Scope block connected to the Packet Loss block.

409 messages are lost during transmission. This is 9.6 percent of the messages.

11-46
Model Wireless Message Communication with Packet Loss and Channel Failure

See Also
Sine Wave | Send | Receive | Queue | Entity Terminator (SimEvents) | Entity Output Switch
(SimEvents) | Entity Gate (SimEvents) | Entity Multicast (SimEvents)

More About
• “Simulink Messages Overview” on page 11-2
• “Discrete-Event Simulation in Simulink Models” (SimEvents)
• “Build a Shared Communication Channel with Multiple Senders and Receivers” on page 11-32
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48

11-47
11 Messages in Simulink

Model an Ethernet Communication Network with CSMA/CD


Protocol

This example shows how to model an Ethernet communication network with CSMA/CD protocol using
Simulink® messages and SimEvents®. In the example, there are three computers that communicate
through an Ethernet communication network. Each computer has a software component that
generates data and an Ethernet interface for communication. Each computer attempts to send the
data to another computer with a unique MAC address. An Ethernet interface controls the interaction
between a computer and the network by using a CSMA/CD communication protocol. The protocol is
used to respond to collisions that occur when multiple computers send data simultaneously. The
Ethernet component represents the network and the connection between the computers.

Software Components

In the model, each software component generates data (payload) and combines the data, its size, and
its destination into a message. Then, the message is sent to the Ethernet interface for
communication.

In each Software Component subsystem:

• A MATLAB Function block generates data with a size between 46 and 1500 bytes [ 1 ].

• A Constant block assigns destination addresses to data.

• A Bus Creator block converts the Data, PayloadSize, and DestAddress signals to a nonvirtual
bus object called dataPacket.

• A Send block converts dataPacket to a message.

• An Outport block sends the message to the Ethernet interface for communication.

11-48
Model an Ethernet Communication Network with CSMA/CD Protocol

Each computer generates data with a different rate. You can change the data generation rate from
the sample time of the MATLAB Function block.

To learn the basics of creating message send and receive interfaces, see “Establish Message Send
and Receive Interfaces Between Software Components” on page 11-23.

Ethernet Interface

Double-click Ethernet Interface 1. Observe that you can specify the Station ID and Transmission
buffer capacity.

The Ethernet Interface subsystems have three main parts:

1 Assemble Ethernet Frame — Converts an incoming message to an Ethernet (MAC) frame.


2 Transmission Buffer — Stores Ethernet frames for transmission.
3 Medium Access Control — Implements a CSMA/CD protocol for packet transmission [ 2 ].

11-49
11 Messages in Simulink

Assemble Ethernet Frame

The Assemble Ethernet Frame blocks convert messages to Ethernet frames by attaching Ethernet-
specific attributes to the message [ 1 ].

In the packet assembly process:

• A SimEvents® Entity Replicator block labeled Copy Message copies an incoming message. The
original message is forwarded to a SimEvents® Entity Generator block labeled Assemble MAC
Frame. Because the Entity Generator block Generation method parameter is set to Event-
based, it immediately produces an entity when the original message arrives at the block. A copy
of the message is forwarded to a Simulink Function block with the initPacket() function. The
terms message and entity are used interchangeably between Simulink® and SimEvents®.

• The Simulink Function block transfers the data, its size, and its destination address to the
Assemble MAC Frame block for frame assembly.

• The Assemble MAC Frame block generates the Ethernet frames that carry both Ethernet-specific
attributes and values transferred from the Simulink Function block.

Assemble MAC Frame block calls the initPacket() function as an action that is invoked by each
frame generation event.

11-50
Model an Ethernet Communication Network with CSMA/CD Protocol

These are the attributes of the generated Ethernet frame:

• entity.TxAddress is StationID.

• entity.RxAddress, entity.Data, and entity.PayloadSize are assigned the values from


the Simulink Function block.

• entity.TxDelay is the transmission delay. It is defined by the payload size and the bitrate. The
Bitrate parameter is specified by an initialization function in the Model Properties.

• entity.CRC is the cyclic redundancy check for error detection.

Transmission Buffer

The transmission buffer stores entities before transmission by using a first-in-first-out (FIFO) policy.
The buffer is modeled by a Queue block.

The capacity of the queue is determined by the Transmission buffer capacity parameter.

Medium Access Control

The Medium Access Control blocks are modeled by using six SimEvents® blocks.

• An Entity Gate block labeled Admit 1 Frame is configured as an enabled gate with two input ports.
One input port allows frames from the Transmission Buffer block. The other input port is called
the control port, which accepts messages from the CSMA/CD block. The block allows one frame to
advance when it receives a message with a positive value from CSMA/CD block.

• An Entity Input Switch block labeled Merge merges two paths. One input port accepts new frames
admitted by the Admit 1 frame block and the other input port accepts frames for retransmission
that are sent by the CSMA/CD block.

• An Entity Server block labeled Wait for Channel models the back off time of a frame before its
retransmission through the channel.

11-51
11 Messages in Simulink

• Another Entity Gate block labeled Send to Channel opens the gate to accept frames when the
channel is idle. The channel status is communicated by the CSMA/CD chart.

• An Entity Replicator block labeled Copy Transmitted Frame generates a copy of the frame. One
frame is forwarded to the Ethernet network, and the other is forwarded to the CSMA/CD chart.

• A Discrete-Event Chart block labeled CSMA/CD represents the state machine that models the
CSMA/CD protocol.

CSMA/CD Protocol

The CSMA/CD protocol [ 2 ] is modeled by a Discrete-Event Chart block that has two inputs:

• TxIn — Copy of the transmitted frame.

• RxIn — Received frame from the Ethernet network.

The chart has five outputs:

• IsIdle — Opens the Send to Channel gate to accept frames when the value is 1, and closes the
gate when the value is 0.

• TxRe — Retransmitted frame that is forwarded to the Merge block if there is a collision detected
during its transmission.

• TxNext — Opens the Admit 1 Frame gate to accept new frames when the value is 1.

• DataOut — Received data.

• Size — Size of the received data.

11-52
Model an Ethernet Communication Network with CSMA/CD Protocol

Transmitting and Receiving Messages

The block is initially in the Standby state and the channel is idle.

If the block is transmitting, after a delay, the block attempts to transmit the message and Isle.data
is set to 0 to declare that the channel is in use.

If the transmission is successful, the block sets TxNext.data to 1 to allow a new message into the
channel and resets to the Standby state.

If there is a collision, the block resends the message after delaying it for a random back off time. n is
the counter for retransmissions. The block retransmits a message a maximum of 16 times. If all of the
retransmission attempts are unsuccessful, then the block terminates the message and allows the
entry of a new message. Then it resets to StandBy.

Similarly, the block can receive messages from other computers. If there is no error, the messages are
successfully received and the block outputs the received data and its size.

Ethernet Hub

The Ethernet component represents the communication network and the cabled connections of the
computers to the network.

11-53
11 Messages in Simulink

Double-click the Ethernet block to see its parameters.

• Connected stations — These values are assigned to Stations, which is a vector with the station
IDs as elements.

• Length of cables (m) — These values are assigned to CableLength and represent the length of
the cables, in meters, for each computer connected to the hub.

• Packet error rate (PER) — These values are assigned to PER and represent the rate of error in
message transmission for each computer.

• Processing time (s) — These values are assigned to ProcessingTime and it represents the
channel transmission delay.

Three SimEvents® blocks are used to model the Ethernet network. The three computer connections
are merged by using an Entity Input Switch block. An Entity Server block is used to model the
channel transmission delay based on the cable length. An Entity Replicator block copies the
transmitted message and forwards it to the three computers.

11-54
Model an Ethernet Communication Network with CSMA/CD Protocol

Simulate the Model and Review the Results

Simulate the model and open the Scope block that displays the average channel utilization. The
channel utilization converges to approximately 0.12.

Open Software Component 1 as a top model and change the data generation rate by setting the
Sample time of the Generate Data 1 block to 0.01. Run the simulation again and observe that the
channel utilization increases to 0.2.

11-55
11 Messages in Simulink

Connect New Computers to the Network

You can connect more computers to the network.

To add a new computer to the network:

• Copy an existing computer and assign a new ID by double-clicking the Ethernet Interface block. In
this example, new computer has ID 4.

11-56
Model an Ethernet Communication Network with CSMA/CD Protocol

• Double-click the Ethernet block and add a station ID, cable length, and packet error rate for the
new computer.

References

1 Ethernet frame - Wikipedia (https://en.wikipedia.org/wiki/Ethernet_frame)

11-57
11 Messages in Simulink

2 Carrier-sense multiple access with collision detection - Wikipedia (https://en.wikipedia.org/wiki/


Carrier-sense_multiple_access_with_collision_detection)

See Also
Send | Receive | Queue | Entity Input Switch (SimEvents) | Entity Replicator (SimEvents) | Discrete-
Event Chart (SimEvents) | Entity Generator (SimEvents) | Entity Gate (SimEvents)

More About
• “Simulink Messages Overview” on page 11-2
• “Discrete-Event Simulation in Simulink Models” (SimEvents)
• “Build a Shared Communication Channel with Multiple Senders and Receivers” on page 11-32

11-58
Send and Receive Messages Carrying Bus Data

Send and Receive Messages Carrying Bus Data

This example shows how to send and receive messages carrying bus data between model
components.

In the model, there are two components, Send Component and Receive Component that send and
receive messages, respectively. This example builds on another example, “Establish Message Send
and Receive Interfaces Between Software Components” on page 11-23, where two software
components communicate using messages. The model is modified to send messages carrying bus
data.

Prepare the Model for Messages with Bus Data

The following steps are used to prepare the model for messages carrying bus data type.

• To create messages carrying non-virtual buses, in the Send Component, in the Bus Creator block,
set the Output data type to messageBus and select the Output as nonvirtual bus check box.

• To send messages carrying bus data, in the Send Component, in the Outport block, under the
Signal Attributes tab, set the Data type to messageBus and select the select the Output as
nonvirtual bus check box.

11-59
11 Messages in Simulink

• To receive messages carrying bus data, in the Receive Component, in the Inport block, under the
Signal Attributes tab, set the Data type to messageBus and select the select the Output as
nonvirtual bus check box.

Simulate the Model and Visualize the Results

Simulate the model and open the Sequence Viewer block. Observe the transmission of messages
carrying bus data.

See Also
Send | Receive | Queue

More About
• “Use Virtual Buses with Message Elements for Component Communication” on page 11-61
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Simulink Messages Overview” on page 11-2

11-60
Use Virtual Buses with Message Elements for Component Communication

Use Virtual Buses with Message Elements for Component


Communication

This example shows how to model message-based communication between software components that
communicate using virtual buses with message elements.

The model in this example is a flat non-holonomic robot that can move or rotate with the help of two
wheels, similar to a home vacuuming robot. This model assumes that the robot moves in one of two
ways:

• Linear — Both wheels turn in the same direction with the same speed, and the robot moves
linearly.
• Rotational — The wheels turn in opposite directions with the same speed, and the robot rotates in
place.

To learn how to create the model for the robot, see “System Definition and Layout”.

In this example, the robot sends its velocity in x- and y- directions to the base station and its relative
angle (direction of motion) values to a base station. The station's data consumption rate is slower
than the data sent by the robot. A Queue block is used as a message buffer.

Send Virtual Bus Message Elements with Nonvirtual Bus Payload

In this model, components that represent the mobile robot and the station communicate using virtual
buses with message elements. XVelocity and YVelocity represent x and y components of the
robot's velocity, respectively. Angle represents the robot's relative angle to the x-axis.

In the Mobile Robot Sending Data component, XVelocity and YVelocity signals are combined into
the nonvirtual bus Velocity. The Send 1 block creates messages with velocity data as the payload.
In this framework, messages provide asynchronous event-based communication between
components. Using messages with a nonvirtual bus payload allows the software to treat Velocity as
data containing XVelocity and YVelocity as its fields. Therefore, each message includes
XVelocity and YVelocity data.

The Send 2 block creates messages with Angle data as the payload. The Out Bus Element blocks
labeled SendVirtualBus.Velocity and SendVirtualBus.Angle specify Velocity and Angle
as elements of the virtual bus SendVirtualBus. You can combine messages into a virtual bus to

11-61
11 Messages in Simulink

create message send interfaces. In the message receive interfaces, you can access the bus as a whole
or select specific messages from the bus. For more information about message send and receive
interfaces, see “Simulink Messages Overview” on page 11-2.

The components communicate via the following:

• The model pre-load function load('Velocity.mat') loads the Velocity bus object to the
workspace.
• A Bus Creator block groups XVelocity and YVelocity into a nonvirtual bus defined by the
Velocity bus object.
• The Send 1 block creates messages with Velocity as the payload.
• The Out Bus Element block labeled SendVirtualBus.Velocity creates the virtual bus
SendVirtualBus with the Velocity element. In the block, Data Type is set to Bus:
Velocity, and Data mode is set to message.

• The Out Bus Element block labeled SendVirtualBus.Angle specifies Angle as a message
element of SendVirtualBus.

11-62
Use Virtual Buses with Message Elements for Component Communication

The Station Receiving Data component receives virtual buses and selects the message elements using
the In Bus Element block. Receive blocks convert messages to signals for processing and
visualization.

For more information about creating send and receive interfaces for messages with a nonvirtual bus
payload, see “Send and Receive Messages Carrying Bus Data” on page 11-59.

You can simulate the model or generate code for both Mobile Robot Sending Data component and
Station Receiving Data component. For more information, see “Generate C++ Messages to
Communicate Data Between Simulink and an Operating System or Middleware” (Embedded Coder).

Simulate the Model and Review Results

Simulate the model. Observe the communicated velocity of the robot in x and y directions. The robot
moves in y direction because its velocity in x direction is constant and 0.

11-63
11 Messages in Simulink

Observe the robot's constant relative angle in radians. The angle pi/2 confirms the motion in the y
direction.

11-64
Use Virtual Buses with Message Elements for Component Communication

Use the Sequence Viewer tool to display the virtual buses communicated between the robot and the
station. To open the Sequence Viewer tool, in the Simulink® toolstrip, on the Simulation tab, under
Review Results, select Sequence Viewer.

The Sequence Viewer window displays the virtual bus transitions from the Mobile Robot Sending
Data component to the Queue block and from the Queue block to the Station Receiving Data
component.

Queue Expansion

Expand the Queue lifeline in the Sequence Viewer window. Observe that the Queue block expands to
two Queue blocks that provide storage for two virtual bus message elements, Velocity and Angle.
The additional Queue block has the same configuration and capacity as the original Queue block. For
more information about the Queue block, see “Use a Queue Block to Manage Messages” on page 11-
13.

11-65
11 Messages in Simulink

Visualize Virtual Buses with Message Elements

Animation allows you to observe the virtual buses communicated between the robot and the station
during the simulation. To turn on animation, from the toolstrip, on the Debug tab, in the Event
Animation section, select the Animation Speed.

You can specify Slow, Medium, or Fast animation speed. Select None to turn off the animation. For
more information about animation and message visualizations, see “Animate and Understand Sending
and Receiving Messages” on page 11-6.

The animation highlights virtual buses sent from the robot to the Queue block and from the Queue
block to the station.

11-66
Use Virtual Buses with Message Elements for Component Communication

Pause the animation and point to the magnifying glass on the Queue block to open the Storage
Inspector. The Storage Inspector displays the bus elements and message data.

Virtual Buses with Message Elements in Architecture Models

You can model message-based communication between software components by first designing your
system from the architecture level using System Composer™. The architecture models in System
Composer support Simulink models with message input and output as component behavior.

Below is an example illustration that shows the design of architecture components to represent the
mobile robot and the station. The Simulink models used in the example above,
MessageSendRobotModel and MessageReceiveRobotModel, are attached to these components as
component behaviors. When you compile the model, a LIFO queue of capacity 1 is automatically
inserted to the architectural model for simulation. Designing message interfaces from the
architecture level requires a System Composer license.

11-67
11 Messages in Simulink

See Also
Send | Receive | Queue

More About
• “Send and Receive Messages Carrying Bus Data” on page 11-59
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48
• “Simulink Messages Overview” on page 11-2
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)

11-68
Merge Message Lines Using a Message Merge Block

Merge Message Lines Using a Message Merge Block

This example shows how to use a Message Merge block to route messages. In this example, message-
based communication is constructed between two components: a Send component creates messages
and sends them to a Receive component. A Queue block is used as a message buffer between the
components and is configured as a FIFO queue with capacity 100. For information about how to
create message communication between components, see “Establish Message Send and Receive
Interfaces Between Software Components” on page 11-23.

In this example, the Send component has two algorithms that generate data that is converted to
messages using two Send blocks. The Message Merge block combines two message lines into a single
message line.

You can prepare this model to generate C++ code for each component. The generated code contains
necessary software interfaces that allow you to connect with an operating system or message
middleware. For more information, see “Generate C++ Messages to Communicate Data Between
Simulink and an Operating System or Middleware” (Embedded Coder).

Simulate the Model and Review Results

Simulate the model. Observe the Scope block that displays the output. The value changes between 1
and 8 based on the two Constant blocks in the Send components.

11-69
11 Messages in Simulink

See Also
Send | Receive | Queue | Entity Input Switch (SimEvents) | Entity Output Switch (SimEvents)

More About
• “Use Virtual Buses with Message Elements for Component Communication” on page 11-61
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48
• “Simulink Messages Overview” on page 11-2

11-70
Specify Queue Properties for Message Interface

Specify Queue Properties for Message Interface

This topic explains how to specify queue properties for a message receive interface when you model
message-based communication with Simulink between software components that run in different
applications. In message-based communication, a send component sends messages, and a receive
component accepts messages based on the logic it represents. For more information about creating
message send and receive interfaces, see “Establish Message Send and Receive Interfaces Between
Software Components” on page 11-23.

In your model with message-based communication, a queue stores and sorts messages between send
and receive components. If you do not specify queue properties manually, a LIFO overwriting queue
of capacity 1 is automatically inserted between send and receive components. For more information
on message queue configurations, see “Use a Queue Block to Manage Messages” on page 11-13.

The topic shows you how to customize queue properties for your message receive interface and
summarizes their use in architecture and AUTOSAR applications.

Specify Queue Properties


Based on your application, specify queue properties for one of these three cases:

• Specify message queue properties for your composition. A composition represents components
and their integration. For more information, see “Simulink Messages Overview” on page 11-2.
• Specify message queue properties for individual components in your model.
• Specify message queue properties for both individual components and your composition.

Customize Message Queue Properties for Compositions

You can customize queue properties for your composition by manually adding a Queue block from the
Simulink Messages & Events library, or blocks from the SimEvents library.

In this example, a Queue block is manually placed to configure message queue properties when the
receive interface is modeled using an Inport block and a Receive block. In this case, use Queue block
parameters to specify the queue capacity, message sorting policy (FIFO or LIFO queue), and message
overwriting policy.

Customize Message Queue Properties for Individual Components

You can specify queue properties for the message receive interface of an individual component using
an In Bus Element block. These properties are then used by AUTOSAR to help generate target

11-71
11 Messages in Simulink

specific code for components. For more information, see “Configure AUTOSAR Queued Sender-
Receiver Communication” (AUTOSAR Blockset).

1 Open the In Bus Element block. Select the bus element and specify its data mode using the Data
mode parameter.

2 Select the message icon to configure queue properties for the selected message element.

3 Clear the Use default queue attributes check box to specify queue attributes for the message
element.

11-72
Specify Queue Properties for Message Interface

Customize Message Queue Properties for Components and Compositions

In this scenario, you combine components with queue receive interface specifications and explicit
queues. When you use both of these queue specifications, the explicit queue configuration will
overwrite other queue specifications.

If you choose both configurations at the same time, you will receive this warning, which indicates that
the configuration of the Queue block overwrites other queue configurations.

11-73
11 Messages in Simulink

Queue Expansion
If you use an automatically inserted Queue block or manually place a Queue block between send and
receive components, for all of the queue specification methods, the queue expands to multiple queues
to provide storage for each virtual bus message element. In this case, all of the queues have the same
configuration and capacity as the original queue. For an example, see “Use Virtual Buses with
Message Elements for Component Communication” on page 11-61.

If you use an In Bus Element block to model the receive interface, you can use multiple In Bus
Element blocks to insert a different message queue for each received message element. The queue
icon displays queue specifications for each message element.

Virtual Buses with Message Elements in Architecture Models


You can model message-based communication between software components by first designing your
system from the architecture level using System Composer. The architecture models in System
Composer support Simulink models with message input and output as component behaviors.
Designing message interfaces from the architecture level requires a System Composer license.

This illustration shows the design of the architecture with send and receive components.. The
Simulink models used in the example above, mSend and mReceive, are attached to these components

11-74
Specify Queue Properties for Message Interface

as component behaviors. When you compile the model, a LIFO queue of capacity 1 is automatically
inserted to the architecture model for simulation.

You can also use the In Bus Element block to manually specify queue properties for the receive
interface behavior of your architecture component. After you update your model, you can point to the
queue icon to view the queue configurations for each bus element in the component behavior.

See Also
Send | Receive | Queue

11-75
11 Messages in Simulink

More About
• “Use Virtual Buses with Message Elements for Component Communication” on page 11-61
• “Generate C++ Messages to Communicate Data Between Simulink and an Operating System or
Middleware” (Embedded Coder)
• “Establish Message Send and Receive Interfaces Between Software Components” on page 11-23
• “Model an Ethernet Communication Network with CSMA/CD Protocol” on page 11-48
• “Simulink Messages Overview” on page 11-2

11-76
Use the Sequence Viewer to Visualize Messages, Events, and Entities

Use the Sequence Viewer to Visualize Messages, Events, and


Entities

To see the interchange of messages and events between the blocks from the Simulink Messages &
Events library, Stateflow charts in Simulink models, and SimEvents blocks, you can:

• Use the Sequence Viewer tool from the Simulink toolstrip.


• Add a Sequence Viewer block to your Simulink model.

The Sequence Viewer allows you to visualize message transition events and the data that the
messages carry. In the Sequence Viewer, you can view event data related to Stateflow chart execution
and the exchange of messages between Stateflow charts. The Sequence Viewer window shows
messages as they are created, sent, forwarded, received, and destroyed at different times during
model execution. The Sequence Viewer window also displays state activity, transitions, and function
calls to Stateflow graphical functions, Simulink functions, and MATLAB functions.

With the Sequence Viewer, you can also visualize the movement of entities between blocks when
simulating SimEvents models. All SimEvents blocks that can store entities appear as lifelines in the
Sequence Viewer window. Entities moving between these blocks appear as lines with arrows. You can
view calls to Simulink Function blocks and to MATLAB Function blocks.

You can add a Sequence Viewer block to the top level of a model or any subsystem. If you place a
Sequence Viewer block in a subsystem that does not have messages, events, or state activity, the
Sequence Viewer window informs you that there is nothing to display.

For instance, open the Stateflow example sf_msg_traffic_light.


openExample("sf_msg_traffic_light")

11-77
11 Messages in Simulink

This model has three Simulink subsystems: Traffic Light 1, Traffic Light 2, and GUI. During
simulation, the Stateflow charts in these subsystems exchange data by sending messages. As
messages pass through the system, you can view them in the Sequence Viewer window. The
Sequence Viewer window represents each block in the model as a vertical lifeline with simulation
time progressing downward.

Components of the Sequence Viewer Window


Navigation Toolbar

At the top of the Sequence Viewer window, a navigation toolbar displays the model hierarchy path.
Using the toolbar buttons, you can:


Show or hide the Property Inspector.

Select an automatic or manual layout.

Show or hide inactive lifelines.

Save Sequence Viewer settings.

Restore Sequence Viewer settings.

Configure Sequence Viewer parameters.

Access the Sequence Viewer documentation.

11-78
Use the Sequence Viewer to Visualize Messages, Events, and Entities

Property Inspector

In the Property Inspector, you can choose filters to show or hide:

• Events
• Messages
• Function Calls
• State Changes and Transitions

Header Pane

The header pane below the Sequence Viewer toolbar shows lifeline headers containing the names of
the corresponding blocks in a model.

• Gray rectangular headers correspond to subsystems.


• White rectangular headers correspond to masked subsystems.
• Yellow headers with rounded corners correspond to Stateflow charts.

To open a block in the model, click the name in the corresponding lifeline header. To show or hide a
lifeline, double-click the corresponding header. To resize a lifeline header, click and drag its right-
hand side. To fit all lifeline headers in the Sequence Viewer window, press the space bar.

Message Pane

Below the header pane is the message pane. The message pane displays messages, events, and
function calls between lifelines as arrows from the sender to the receiver. To display sender, receiver,
and payload information in the Property Inspector, click the arrow corresponding to the message,
event, or function call.

11-79
11 Messages in Simulink

Navigate the Lifeline Hierarchy


In the Sequence Viewer window, the hierarchy of lifelines corresponds to the model hierarchy. When
you pause or stop the model, you can expand or contract lifelines and change the root of focus for the
viewer.

Expand a Parent Lifeline

In the message pane, a thick, gray lifeline indicates that you can expand the lifeline to see its
children. To show the children of a lifeline, click the expander icon below the header or double-
click the parent lifeline.

For example, expanding the lifeline for the Traffic Light 1 block reveals two new lifelines
corresponding to the Stateflow charts Ped Button Sensor and Controller.

11-80
Use the Sequence Viewer to Visualize Messages, Events, and Entities

Expand a Masked Subsystem Lifeline

The Sequence Viewer window displays masked subsystems as white blocks. To show the children of a
masked subsystem, point over the bottom left corner of the lifeline header and click the arrow.

For example, the GUI subsystem contains four masked subsystems: Traffic Lamp 1,Traffic Lamp 2,
Ped Lamp 1, and Ped Lamp 2.

You can display the child lifelines in these masked subsystems by clicking the arrow in the parent
lifeline header.

11-81
11 Messages in Simulink

Change Root of Focus

To make a lifeline the root of focus for the viewer, point over the bottom left corner of the lifeline
header and click the arrow. Alternatively, you can use the navigation toolbar at the top of the
Sequence Viewer window to move the current root up and down the lifeline hierarchy. To move the
current root up one level, press the Esc key.

The Sequence Viewer window displays the current root lifeline path and shows its child lifelines. Any
external events and messages are displayed as entering or exiting through vertical slots in the
diagram gutter. When you point to a slot in the diagram gutter, a tooltip displays the name of the
sending or receiving block.

View State Activity and Transitions


To see state activity and transitions in the Sequence Viewer window, expand the state hierarchy until
you have reached the lowest child state. Vertical yellow bars show which state is active. Blue
horizontal arrows denote the transitions between states.

11-82
Use the Sequence Viewer to Visualize Messages, Events, and Entities

In this example, you can see a transition from Go to PrepareToStop followed, after 1 second, by a
transition to Stop.

To display the start state, end state, and full transition label in the Property Inspector, click the
arrow corresponding to the transition.

To display information about the interactions that occur while a state is active, click the yellow bar
corresponding to the state. In the Property Inspector, use the Search Up and Search Down
buttons to move through the transitions, messages, events, and function calls that take place while
the state is active.

View Function Calls


The Sequence Viewer displays function calls and replies. This table lists the type of support for each
type of function call.

Function Call Type Support


Calls to Simulink Fully supported.
Function blocks

11-83
11 Messages in Simulink

Function Call Type Support


Calls to Stateflow • Scoped — Select the Export chart level functions chart option. Use
graphical or Stateflow the chartName.functionName dot notation.
MATLAB functions • Global — Select the Treat exported functions as globally visible
chart option. You do not need the dot notation.
Calls to function-call Fully supported and displayed.
subsystems
Calls from MATLAB Supports displaying function call events with the limitation of calls
Function block crossing model reference boundaries.

The Sequence Viewer window displays function calls as solid arrows labeled with the format
function_name(argument_list). Replies to function calls are displayed as dashed arrows labeled
with the format [argument_list]=function_name.

For example, in the model slexPrinterExample, a subsystem calls the Simulink Function block
addPrinterJob. The function block replies with an output value of false.

To open this example, enter:

openExample("slexPrinterExample")

Simulation Time in the Sequence Viewer Window


The Sequence Viewer window shows events vertically, ordered in time. Multiple events in Simulink
can happen at the same time. Conversely, there can be long periods of time during simulation with no
events. As a consequence, the Sequence Viewer window shows time by using a combination of linear
and nonlinear displays. The time ruler shows linear simulation time. The time grid shows time in a
nonlinear fashion. Each time grid row, bordered by two blue lines, contains events that occur at the
same simulation time. The time strip provides the times of the events in that grid row.

11-84
Use the Sequence Viewer to Visualize Messages, Events, and Entities

To show events in a specific simulation time range, use the scroll wheel or drag the time slider up and
down the time ruler. To navigate to the beginning or end of the simulation, click the Go to first event
or Go to last event buttons. To see the entire simulation duration on the time ruler, click the Fit to
view button .

When using a variable step solver, you can adjust the precision of the time ruler. In the Model
Explorer, on the Main tab of the Sequence Viewer Block Parameters pane, adjust the value of the
Time Precision for Variable Step field.

Redisplay of Information in the Sequence Viewer Window


The Sequence Viewer saves the order and states of lifelines between simulation runs. When you close
and reopen the Sequence Viewer window, it preserves the last open lifeline state. To save a particular

viewer state, click the Save Settings button in the toolbar. Saving the model then saves that

state information across sessions. To load the saved settings, click the Restore Settings button .

Note When you update your model or rerun simulation, the Sequence Viewer clears results from
past runs. To save results from past runs, use the Simulation Data Inspector.

You can modify the Time Precision for Variable Step and History parameters only between
simulations. You can access the buttons in the toolbar before simulation or when the simulation is
paused. During a simulation, the buttons in the toolbar are disabled.

See Also
Blocks
Sequence Viewer

Tools
Sequence Viewer

11-85
11 Messages in Simulink

More About
• “Communicate with Stateflow Charts by Sending Messages” (Stateflow)
• “Model Distributed Traffic Control System by Using Messages” (Stateflow)

11-86
Using Message Polling and Message Triggered Subsystems

Using Message Polling and Message Triggered Subsystems

This example shows how Message Polling Subsystem and Message Triggered Subsystem blocks
operate and demonstrates the differences between them. Both Message Polling Subsystem and
Message Triggered Subsystem blocks contain a Trigger block. Based on the configuration of the
Trigger block, you can create these behaviors:

• Message Polling Subsystem block — The subsystem pulls messages from a queue periodically
based on the sample time of the subsystem.
• Message Triggered Subsystem block in immediate mode — The message sender and the Message
Triggered Subsystem are synchronized. The message sender invokes the subsystem by pushing
messages.
• Message Triggered Subsystem block in scheduled mode — The execution order of the subsystem
can be scheduled in the Schedule Editor to model an asynchronous behavior.

This example shows differences between these three modes and explains use cases for each mode.

11-87
11 Messages in Simulink

Overview

This model contains three identical message sources: Sender1, Sender2, and Sender3. Each source
generates messages with payload values from two Repeating Stair Sequence blocks.

11-88
Using Message Polling and Message Triggered Subsystems

Sender1, Sender2, and Sender3 all have sample time of 1 and generate two messages at each time
step. This figure shows the payload values of generated messages. The sequence repeats starting at
time step 6.

Inside each message receiving subsystem, the message payload is read, multiplied by 2 using a Gain
block, and used as the payload for a message.

Message Polling Subsystem

Use a Message Polling Subsystem block when you want to define the rate of the subsystem block
when pulling messages. The block pulls a message from a queue based on its sample time, and the
sample time can be specified on the subsystem block parameter. The block can pull only one message
at each time step. You can configure the block to pull messages with a slower or faster rate.

In this example, the Message Polling Subsystem block has a sample time of 2. In each time step, the
block checks for available messages at the Queue block. If a message is available, the Message
Polling Subsystem block pulls one message and executes. A Queue block operating in FIFO mode with
a capacity of 16 stands between the message sender and the Message Polling Subsystem block. This
figure shows that the subsystem pulls messages with a slower rate using the sample times.

11-89
11 Messages in Simulink

The scope output shows that the subsystem pulls and processes only one message every 2 time units,
whereas two messages are sent to the Queue block at each time unit. During simulation, the Queue
block fills up, and some messages are lost.

Message Triggered Subsystem in Immediate Mode

The first Message Triggered Subsystem block operates in immediate mode. That is, in the Trigger
block inside the subsystem, the Schedule as aperiodic partition check box is not selected. Use this
mode to represent the simple cases when you do not have to schedule the subsystem execution. In
this configuration, the message sender invokes the Message Triggered Subsystem block for execution
by pushing the available messages to the subsystem. The subsystem executes as soon as a message is
pushed by the sender. If you use a Message Triggered Subsystem block in immediate mode, you do
not have to use a Queue block between the message sender block and the subsystem. This mode
supports code generation for the top model and its components. In the generated code, the

11-90
Using Message Polling and Message Triggered Subsystems

subsystem acts as a function that takes the message payload as an argument and is called by the
sender.

This figure shows that the sample times are synchronized because the sender invokes the subsystem.

The scope output shows that the subsystem receives and processes two messages at each time unit.

Message Triggered Subsystem in Scheduled Mode

The second Message Triggered Subsystem block operates in scheduled mode. That is, in the Trigger
block inside the subsystem, the Schedule as aperiodic partition check box is selected, which is the
default configuration. Aperiodic partitions are partitions that are not necessarily periodically
triggered or bound to a periodic time trigger and can be bound to an event. This mode allows you to
schedule the execution of the subsystem using the Schedule Editor. For more information, see “Using
the Schedule Editor” on page 25-11. In this case, the top model does not support code generation

11-91
11 Messages in Simulink

because scheduling does not support code generation. However, you can move the Message
Triggered Subsystem block inside a referenced model and connect to the root Inport and generate
code for that component alone, which can then be integrated with the message middleware.

In this example, a Queue block operating in FIFO mode stands between the message source and the
Message Triggered Subsystem block. When a message arrives at the Queue block, the message raises
an event that triggers the Message Triggered Subsystem block to pull the message from the Queue
block. Then, the subsystem pulls the message based on the message availability and the schedule.
This figure shows the sample times of the message sender and the Message Triggered Subsystem
block.

For example, this figure shows the Schedule Editor displaying the Message Triggered Subsystem
block that is scheduled to execute first. In this case, a message arrives at the Queue block based on
D1, and this event triggers the Message Triggered Subsystem to pull the message. The Message
Triggered Subsystem pulls the message as soon as it arrives at the Queue block because it is
scheduled first in the order. In this case, the Message Triggered Subsystem in scheduled mode
behaves identically to a Message Triggered Subsystem in immediate mode. However, scheduled mode
allows you change the order and schedule the execution of the subsystem based on your modeling
requirements.

Simulate the model. The scope output shows that the Message Triggered Subsystem receives and
processes two messages at each sample time hit.

11-92
Using Message Polling and Message Triggered Subsystems

See Also
Message Triggered Subsystem | Queue

11-93
11 Messages in Simulink

Asynchronous Message Handling in Adaptive Cruise Control

This example shows how to model an event-based adaptive cruise control (ACC) system using
messages and message-triggered subsystems to reduce communication traffic and increase system
efficiency. Components representing the physical system and control logic are simplified to show how
sensory events can asynchronously trigger the ACC system. The model includes a front radar. The
radar detects the distance between the vehicle and the vehicle ahead and identifies events for
braking and acceleration. Then, the radar sends messages (in adaptive AUTOSAR this corresponds to
adaptive events) to the ACC system. The ACC system converts messages to control signals and sends
them to the brake actuator and powertrain to control the breaking and acceleration of the vehicle.
The model allows you how to manually brake or accelerate and observe the vehicle speed and engine
rpm. For more information about messages, see “Simulink Messages Overview” on page 11-2.

Using this model, you can generate adaptive AUTOSAR code for the ACCModule component when
you open the component as a top model. The DistanceSensorModule (inside FrontRadarSensor),
BrakeControlModule (inside BrakeActuator), and PowertrainControlModule (inside
Powertrain) components can generate classic AUTOSAR code when you open them as the top
model. These reference models are highlighted with blue.

For more information about modeling adaptive cruise control logic, see “Collision Avoidance
Assistance” (Automated Driving Toolbox).

Adaptive Cruise Control Module

In the model, the ACCModule component is subscribed to sensor (radar) events. The ACCModule has
two Message Triggered Subsystem blocks, Brake Event Handler and Acceleration Event
Handler. The subsystems respond to the braking and acceleration events asynchronously. In real
applications, invoking event handlers is usually done by message middleware, and the order of
execution can be random depending on the environment. However, in simulations, you can schedule
the execution of your model partitions and generate deterministic results. To test the behavior of your
model for various simulation scenarios, change the order of execution of your model partitions. To

11-94
Asynchronous Message Handling in Adaptive Cruise Control

create such model partitions in this model, Message Triggered Subsystem blocks are used in
scheduled mode. In scheduled mode, you can schedule the execution of the subsystems as aperiodic
partitions using the Schedule Editor. The subsystems pull and process the data based on a schedule
instead of periodic execution, which reduces communication traffic and increases system efficiency.

In the ACCModule component, the Function-Call Subsystem Process Data periodically reads the
CAN bus and generates the data of vehicle states. The data is used by the two Message Triggered
Subsystems Brake Event Handler and Acceleration Event Handler. You can set the period
of the Process Data component by using the Sample time parameter of the root Inport block.

The ACCModule component is an export-function model. This modeling pattern also allows you to
generate code for independent functions that can be integrated with an external environment and
scheduler. For more information about export-function models, see “Export-Function Models
Overview” on page 10-125. Because the ACCModule component is an AUTOSAR adaptive software
component, it acts as message middleware and can generate code to be asynchronously triggered via
the AUTOSAR adaptive platform.

11-95
11 Messages in Simulink

Schedule Message-Triggered Subsystem Execution Using Schedule Editor

Open the Schedule Editor to observe the partitions of the model, including the message-triggered
subsystems ACCModule.AccelerationEventHandler and ACCModule.BrakeEventHandler. For
more information about the Schedule Editor tool, see “Using the Schedule Editor” on page 25-11.

You can use the Schedule Editor tool to change the order of the execution of the partitions so that
when multiple partitions (tasks) are scheduled to be executed at the same time, the higher priority
task is executed first. If a lower priority task is already running, the higher priority task preempts the
lower priority one.

Simulate Model and Review Results

Simulate the model. Open the Sequence Viewer tool to observe the interchange of messages and
event triggering between the blocks and components in your model. Also, you can see the order of
the interchanges based on the current order of execution priority. In the current order, the
ACCModule.AccelerationEventHandler and the ACCModule.BrakeEventHandler partitions
have higher priority. The message from FrontRadarSensor with the SensorEventBus payload is
transitioned to the ACCModule component and triggers the corresponding Message Triggered
Subsystem prior to the CANBus messages as shown in the red box. For more information about the
Sequence Viewer tool, see “Use the Sequence Viewer to Visualize Messages, Events, and Entities”
on page 11-77.

11-96
Asynchronous Message Handling in Adaptive Cruise Control

You can change the order of priority so that the asynchronous event handlers have lower priority. In
this order, Process Data subsystem executes first and provides the latest vehicle state to the
message triggered subsystems.

If you simulate the model again, you can observe that the transition from FrontRadarSensor to
ACCModule occurs after the CANBus messages.

11-97
11 Messages in Simulink

Review Results of Simulation

Open the Dashboard component to manually control the vehicle and review the results.

• The Monitor Panel shows the speed of the vehicle and the speed of the vehicle ahead. It also
displays the distance between the vehicles.

• The Control Panel allows you to manually stop or accelerate the vehicle. You can also specify the
target distance between the vehicles at the equilibrium along with the expected deviation.

• Gauges display the engine rpm and the vehicle speed in mph.

11-98
Asynchronous Message Handling in Adaptive Cruise Control

Use Manual Break Pedal

Simulate the model again. Press the Brake Pedal in the Control Panel after 50 seconds. Release the
pedal around 150 seconds. Observe the vehicle speed and distance between the vehicles during and
after your manual brake.

11-99
11 Messages in Simulink

See Also
Message Triggered Subsystem

Related Examples
• “Wireless Tire Pressure Monitoring System with Fault Logging” on page 10-284
• “Temperature Control System Communicating with Messages” on page 11-101
• “Using Message Polling and Message Triggered Subsystems” on page 11-87

11-100
Temperature Control System Communicating with Messages

Temperature Control System Communicating with Messages

This example shows how to use message communication within a distributed system where the
controller manages multiple incoming messages from different senders in an iterative manner and
sends messages to communicate commands to the different receivers. The example uses a model of a
control system managing temperatures in two different rooms with separate thermostats. The
algorithmic modeling of the components basically follows the Stateflow example “Model Bang-Bang
Temperature Control System” (Stateflow), while the communication between the components is
modeled using Simulink® messages and SimEvents® blocks. The referenced models Controller and
Thermometer, colored in blue, are software components expected to generate standalone code, while
the other components model the environment.

Model Overview

The model contains N identical rooms with thermostats (modeled by multi-instanced model blocks),
where N = 2 is a Simulink parameter defined in the Simulink data dictionary file slddMsg.sldd,
which is linked to the top model and referenced models. Each room can set the setpoint temperature
separately. The thermostats for the rooms are remotely controlled by a controller, using the same
control algorithm for all thermostats.

The thermostats send temperature messages to the controller every 0.2 seconds, while the controller
sends command messages to the thermostats to command heating on or off every 1 second. An Entity
Output Switch (SimEvents) block routes the messages from the controller to one of the thermostats
according to the message bus data field deviceID. (The bus is also defined in the data dictionary and
shared across all models.) A Message Merge block routes the messages from different thermostats to
the controller.

Initially, the model is configured using bus types with floating-point type fields that are defined in the
data dictionary file slddMsg.sldd. To switch from floating-point to fixed-point, change the data

11-101
11 Messages in Simulink

dictionary for the model from slddMsg.sldd to slddMsgFixpt.sldd. On the Modeling tab, go to
Model Settings > Model Properties > External Data.

The model is easily scalable by changing the value of N, adding more instances of the model block,
and increasing the port number of the Entity Output Switch and Message Merge blocks. Each
Thermometer model inside the Room model has an ID argument, which must be set with a value that
matches the output port index of the Entity Output Switch.

A Queue block (FIFO, overwriting type queue) in front of the controller model buffers the message,
which models the queue inside the message middleware of the controller. Here, a capacity of N is
good enough for the queue to overwrite the oldest messages with the new ones from each sender,
assuming no message loss in transit. A capacity of 5*N is needed for the worst scenario with message
loss, where 5 is the sample time of the controller divided by the sample time of the thermostats. In
addition, a queue in front of each thermostat with capacity 1 is automatically inserted and shows a
badge icon of sandwiched "1", because a capacity-1 queue is automatically inserted if you do not
intentionally place a Queue block. See “Use a Queue Block to Manage Messages” on page 11-13.

To view the sequences of messages and events, on the Simulink Toolstrip, on the Simulation tab, in
the Review Results section, click Sequence Viewer. See Sequence Viewer.

Controller Model

In the Controller model, the Update Temperature subsystem connected with the Inport block first
receives all messages containing temperature information from the rooms. The subsystem stores that
information in two vectors of temperature setpoint and current temperature. Then, the For Each
subsystem reads the vectors, processes the signals, and sends out the control messages via the
Simulink function sendCtrlMsg.

11-102
Temperature Control System Communicating with Messages

The Update Temperature subsystem is a do-while subsystem whose termination condition port is fed
by the Receive block's status port, meaning it runs until cannot receive any more messages from the
external queue (in the top model). The message data is of DeviceMsg bus type, which is defined in
the data dictionary file, and has two fields: temperature and deviceID. Thus, when the output
signal of the Receive block propagates to the enabled subsystem whose enable port is connected to
the Receive block's status port, the Bus Selector block decomposes the signal into deviceID,
temperature, and setpoint signals. The setpoint and temperature signals are then assigned
to the respective vector elements associated with the deviceID. Finally, the vectors maintained by
the Unit Delay blocks are output as signals by the enabled subsystem and Update Temperature
subsystem to the For Each subsystem.

11-103
11 Messages in Simulink

The For Each subsystem, whose block settings are shown above, is set to have N iterations, and both
of its input ports are partitioned. A Stateflow chart models the Bang-Bang Controller, which
resembles the one explained in “Model Bang-Bang Temperature Control System” (Stateflow). Its
output port outputs a Boolean signal indicating whether or not to turn on heating. This signal is
packed into a nonvirtual signal at the Bus Creator block with the deviceID (one-based) from the
iteration number (zero-based). The signal is given to the Function Caller block, which calls the
Simulink Function SendCtrlMsg (placed outside the For Each Subsystem) to send the message out
from the model.

11-104
Temperature Control System Communicating with Messages

Room Model

In the Room model, the Thermostat subsystem interacts with the environment. The Thermostat has
two inputs, the control message and the setpoint temperature signal, and two outputs, the heating
rate and the temperature message to the controller. The Gain and Integrator blocks simulate the
physics of the room heating or cooling with respect to the heating rate and room size.

The Thermostat subsystem is composed of a Thermometer Sensor subsystem, a Thermometer


Software model block, and a Temperature Actuator subsystem. The Thermometer Software model
block periodically receives a control message from the controller and unpacks it into a Boolean
command (on/off) to the Temperature Actuator subsystem, which determines the heating rate. The
Thermometer Software also inputs a temperature signal from Thermometer Sensor subsystem, which
detects the analog temperature, converts it to a digital signal, and sends the message back to the
controller.

11-105
11 Messages in Simulink

Thermometer Model

In the Thermometer model, a Receive block connects with the Inport block to receive a control
message from the external queue at each time step. The message data is decomposed into a
command signal, which is an output, and a deviceID signal, which must match the ID argument of the
model. The ID argument should be set in the model block in the top model. The Receive block's initial
value is set to a MATLAB® structure with the deviceID field equal to the model argument ID and
the command field taking a value of false. Meanwhile, the signals of digital temperature, setpoint,
and deviceID are packed into a nonvirtual bus signal and sent as a message to the Outport block.

Code Generation

For code generation and deployment, the referenced models Controller and Thermometer (colored
blue) can generate standalone embedded-target C++ code and can be deployed separately on
embedded devices with message middleware. For more information, see “Generate C++ Messages to
Communicate Data Between Simulink and an Operating System or Middleware” (Embedded Coder);
see also “Model Message-Based Communication Integrated with POSIX Message Queues” (Embedded
Coder).

Message root-level Inport/Outport does not support C code generation and code customization. If you
need to generate C code and call into a message middleware API for sending messages, consider
moving the Simulink function sendCtrlMsg to the top model and customizing the name properly so
that the referenced model generates a customizable call site of an external function. Similarly, for the
receive side, consider using a Simulink function containing a Receive block in the top model and
using a Function Caller block in the referenced model to replace the Receive block.

See Also
Integrator | Gain | Simulink Function | Function Caller | For Each Subsystem | Receive

11-106
12

Modeling Variant Systems

• “What Are Variants and When to Use Them” on page 12-3


• “Variant Terminology” on page 12-20
• “Define and Configure Variant Sources and Sinks” on page 12-35
• “Visualize Variant Implementations in a Single Layer” on page 12-41
• “Provide Variation in Signal Source and Destination Using Manual Variant Source and Manual
Variant Sink Blocks” on page 12-43
• “Create a Simple Variant Model” on page 12-45
• “Implement Variations in Separate Hierarchy Using Variant Subsystems” on page 12-48
• “Working with Variant Choices” on page 12-59
• “Introduction to Variant Controls” on page 12-62
• “Variant Control Modes in Variant Blocks” on page 12-64
• “Use Variant Control Variables in Variant Blocks” on page 12-78
• “Create Variant Controls Programmatically” on page 12-91
• “Activate Variant During Different Stages of Simulation and Code Generation Workflow”
on page 12-93
• “Verify and Validate Variant Models with Code Compile Activation Time” on page 12-105
• “Simulate Variant Subsystem with Startup Activation Using parsim” on page 12-110
• “Simulate a Protected Model with Code Compile or Startup Activation Time” on page 12-113
• “Simulate Variant Blocks in Accelerator and Rapid Accelerator Modes with Startup Activation
Time” on page 12-116
• “Run Iterative Simulations Without Recompiling Model for Variant Systems Using Fast Restart”
on page 12-118
• “Verify and Validate Variant Models with Startup Activation Time” on page 12-124
• “Known Limitations of startup variant activation time” on page 12-129
• “Considerations and Limitations for startup Variant Activation Time” on page 12-130
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133
• “Assemble Variant Conditions Propagated from Variant Blocks” on page 12-137
• “Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems”
on page 12-140
• “Propagate Variant Conditions to Define Variant Regions Using Variant Source and Variant Sink
Blocks” on page 12-150
• “Variant Elements Within Buses” on page 12-155
• “Propagate Variant Conditions to Define Variant Regions in Virtual and Nonvirtual Subsystems”
on page 12-157
• “Propagate Variant Conditions to Control Execution of Conditional Subsystems” on page 12-162
• “Propagate Variant Conditions to Enable or Disable Model or Subsystem References in Hierarchy”
on page 12-170
12 Modeling Variant Systems

• “Conditionally Execute Custom Initialize, Reinitialize, Reset, and Terminate Routines”


on page 12-173
• “Conditionally Execute Simulink Functions” on page 12-176
• “Approaches to Control Active Variant Choice of a Variant Block Using Mask or Model Workspace”
on page 12-178
• “Control Structural Variations Using Mask Parameters and Model Arguments” on page 12-183
• “Prevent Creation of Unused Variables for Unconditional and Conditional Variant Choices”
on page 12-186
• “Prevent Creation of Unused Variables for Lenient Variant Choices” on page 12-189
• “Control Active Choice of Locked Custom Library Variant Subsystem Using Mask Parameter”
on page 12-192
• “Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files”
on page 12-195
• “Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter
Object” on page 12-208
• “Automatic Mask Icon Promotion in Variant Subsystems” on page 12-217
• “Prepare Variant-Containing Model for Code Generation” on page 12-220
• “Generate Code from Nested Variant Subsystem with Code Compile and Startup Activation”
on page 12-225
• “Create Real-Time Applications Using Variants and Simulink Real-Time” on page 12-229
• “Create Standalone Executables with Variants Using Simulink Compiler” on page 12-235
• “Export and Import Function Mockup Unit (FMU) from Model with Variant Subsystem Blocks”
on page 12-239
• “Simulink Variant Examples” on page 12-242
• “V-Model for System Development with Simulink Variants” on page 12-243
• “Use find_system with Built-In MatchFilter Options for Variant Blocks” on page 12-258
• “Convert Variant Subsystem to Variant Assembly Subsystem” on page 12-262
• “Convert Configurable Subsystem to Variant Subsystem” on page 12-269

12-2
What Are Variants and When to Use Them

What Are Variants and When to Use Them


In this section...
“What Are Variants?” on page 12-3
“Advantages of Using Variants” on page 12-3
“When to Use Variants” on page 12-4
“Types of Variants in Simulink” on page 12-5
“Variant Blocks in Simulink” on page 12-6
“Use Variants to Create One Model for Many Systems” on page 12-8
“Working with Variants” on page 12-10

What Are Variants?


In Model-Based Design workflows, creating multiple design variations for system components is
essential to meet different sets of requirements. These requirements can cater to diverse market
needs, customer preferences, or geographical features. Throughout the development lifecycle, from
requirements to deployment, you may need to switch between these design choices.

Simulink variant capabilities allow you to represent all design alternatives of a system in a single
model. Each design choice is incorporated into the model as a variant choice. Such models have a
fixed common structure and a finite set of variable components that are activated depending on the
variant choice. This model shows how Variant Source blocks help you implement variant choices for
the input signals to a system. The inactive choice appears faded.

For an example, see “Use Variants to Create One Model for Many Systems” on page 12-8.

Advantages of Using Variants


Using variants in Model-Based Design provides several advantages:

12-3
12 Modeling Variant Systems

• Variants allow you to design one model for many systems.


• You can rapidly prototype design possibilities as variants without having to comment out sections
of your model.
• Variants help you develop modular design platforms for reuse and customization. This approach
improves workflow speed by reducing complexity.
• If a model component has several alternative configurations, you can explore the alternatives
without altering the fixed components.
• You can use different variant configurations for simulation or code generation from the same
model.
• You can simulate every design possibility for a given test suite.
• If you are working with large-scale designs, you can distribute the process of testing these designs
on a cluster of multicore computers. Alternatively, you can map different test suites to design
alternatives for efficient management of design-specific tests.
• You can generate a reduced model for a subset of variant configurations from a model with many
variants.

When to Use Variants


Here are three scenarios where you can use variants.

Models that represent multiple


simulation, code generation, or testing
workflows.

12-4
What Are Variants and When to Use Them

Models that contain multiple design


choices at the component level.

Models that are mostly similar but


have slight variations, such as in cases
where you want to separate a test
model from a debugging model. The
test model on the left has a fixed
design. On the right, the same test
model includes a variant that is
introduced for debugging purposes.

Types of Variants in Simulink


Variant blocks help you represent multiple structural or algorithmic implementations of a system
component in a single model and allow you to switch between them as per requirements. For an
overview of the types of variant blocks in Simulink, see “Variant Blocks in Simulink” on page 12-6.

Variant parameters help you implement design variations that require varying values for block
parameters. For more information, see “Use Variant Parameters to Reuse Block Parameters with
Different Values” on page 90-2.

Variant transitions allow you to transition to multiple design configurations within the same Stateflow
chart. For more information, see “Control Indicator Lamp Dimmer Using Variant Conditions”
(Stateflow).

Dimension variants allow you to specify symbolic dimensions that vary based on variant conditions.
See “Implement Symbolic Dimensions for Array Sizes in Generated Code” (Embedded Coder).

AUTOSAR variants enable you to use variant blocks to implement AUTOSAR software components
with variation points. See “Model AUTOSAR Variants” (AUTOSAR Blockset).

Tip For a list of examples that show variant capabilities in Simulink, see “V-Model for System
Development with Simulink Variants” on page 12-243.

To see definitions for key terms and parameters used with variants, see “Variant Terminology” on
page 12-20.

For examples that show variant code generation capabilities, see “Variant Systems” (Simulink Coder).

12-5
12 Modeling Variant Systems

Variant Blocks in Simulink


Use these variant blocks depending on the model design:

• Hierarchical variant blocks to create multiple implementations of a component in a separate


hierarchy in the model.
• Inline variant blocks to represent all variant implementations at the same level in the model.
• Event-based variants to use variants to model context-dependent system behaviors.

Type of Variant Variant Block Use


Hierarchical variant Variant Subsystem The Variant Subsystem block is a
blocks template preconfigured with Subsystem
blocks to represent the variant choices.

The Variant Subsystem block allows a


combination of Subsystem blocks, Model
blocks, or Subsystem Reference blocks
as variant choices.
Variant Model The Variant Model block is a template
preconfigured with two Model blocks to
represent the variant choices.

The Variant Model block allows a


combination of Subsystem blocks, Model
blocks, or Subsystem Reference blocks
as variant choices.
Variant Assembly Subsystem The Variant Assembly Subsystem block
enables you to add or remove its variant
choices from external files.

The Variant Assembly Subsystem allows


a combination of Model blocks, or
Subsystem Reference blocks as variant
choices.
Inline variant blocks Variant Source The Variant Source block allows you to
define variant choices as block regions
connected to each of its inports. The
block provides variation on the source of
a signal.
Variant Sink The Variant Sink block allows you to
define variant choices as block regions
connected to each of its outports. The
block provides variation on the
destination of a signal.

12-6
What Are Variants and When to Use Them

Type of Variant Variant Block Use


Variant Start The Variant Start block allows you to
define the start of the bounded region.
You can limit the variant condition
propagation in the bounded region.
Every Variant Start block has a
corresponding Variant End block.
Variant End The Variant End block allows you to
define the end of the bounded region.
You can limit the variant condition
propagation in the bounded region.
Manual Variant Source The Manual Variant Source block is a
toggle switch that allows you to define
multiple variant choices at its inports.
Manual Variant Sink The Manual Variant Sink block is a
toggle switch that allows you to define
multiple variant choices at its outports.
Variant Connector The Variant Connector block lets you
define variant choices in a physical
network. You can switch between
components in the network during
simulation without having to physically
remove the components or exclude them
from simulation.
Event-based variants Simulink Function The variant functionality in the Simulink
Function block allows the block to be
conditionally available. You can specify
variant conditions on the function call
port block or the block can inherit the
condition from its function caller blocks.
Initialize Function, Reset The variant functionality in Initialize,
Function, and Terminate Reset, and Terminate blocks allow the
Function blocks blocks to be conditionally available. You
can specify variant conditions on the
event listener block.

Compare Variant Blocks

This table presents a comparison between hierarchical and inline variant blocks.

Feature Variant Source and Variant Subsystem and Variant Model


Variant Sink blocks blocks
Variant choice Number of ports Subsystem, Model, or Subsystem Reference
representation blocks
Allows to implement No Yes
variant choices in a
separate hierarchy

12-7
12 Modeling Variant Systems

Feature Variant Source and Variant Subsystem and Variant Model


Variant Sink blocks blocks
Supports flexible number No Yes, if the Propagate conditions outside
of inputs and outputs of variant subsystem parameter is set to
among variant choices (the on.
choices do not have similar
interface)
Option to specify default Yes Yes
variant
Supports control ports No Yes
Can be saved as No No
standalone file
Supports Connection Port No Only when the Variant activation time
used for modeling physical parameter is set to update diagram.
connection lines
Comment a variant choice No Yes
(by adding the % symbol
before the variant control
in the Block Parameters
dialog box)

Use Variants to Create One Model for Many Systems


This example shows variant design in a Simulink model. Consider the requirement to model a system
that represents an automobile with several configurations. These configurations, although similar in
several aspects, can differ in properties such as fuel consumption, motor type, or emission standard.

Instead of designing separate models for each configuration, you can represent the configurations as
variant choices in a single model. You can choose to activate any one of the variant choices based on
your requirements. This approach keeps the common components fixed.

This model contains a Variant Subsystem block, Motor Variant Subsystem, that represents the
motor of the vehicle. The motor has two possible configurations, Gas and Electric, that are

12-8
What Are Variants and When to Use Them

represented as variant choices within the Variant Subsystem block. A Variant Subsystem block adapts
its interface according to the state of the underlying blocks. Here, the Electric motor does not have
an exhaust temperature input. When you activate the Electric variant, Simulink automatically
disables the corresponding port on the Motor Variant Subsystem and any other model
components associated with that input.

For the exhaust temperature sensor for this model, consider the need to switch between five
different sensors provided by two vendors. You can use Variant Source blocks to represent all the
choices in the same model and activate only one choice at a time.

12-9
12 Modeling Variant Systems

Working with Variants


Visual Elements in Variant Models

Visual Element Use


Variant Condition Legend The Variant Condition Legend dialog box helps you visualize the
variant conditions applied on the model. Simulink annotates
model components that have variant conditions, and the Variant
Condition Legend displays the conditions for each annotation.
See “Visualize Propagated Variant Conditions in Variant
Conditions Legend” on page 12-133.

Variant Badges Each variant block displays a badge that changes with different
parameter values set on the block. See “Variant Badges” on page
12-11.

12-10
What Are Variants and When to Use Them

Visual Element Use


Variant Fading and Signal The color of inactive variant choices fades by default. You can
Highlighting choose to disable the fading effect by using the Variant Fading
option in the Information Overlays menu on the Debug tab of
the Simulink Editor.

Highlighting a signal that passes through variant blocks


highlights the path of the active variant choice. See “Signal
Highlighting in Variant Systems” on page 81-34.

Variant Badges

Each variant block displays a badge. The color and icon of the variant badge changes according to
values of these parameters set on the block:

• Variant activation time


• Variant control mode
• Allow zero active variant controls (for Variant Source and Variant Sink blocks)
• Propagate conditions outside of variant subsystem (for Variant Subsystem block)

Variant Badges also provide quick access to some variant commands. Right-click the variant badge to
access these commands.

Note The Refresh Blocks (Ctrl+K) option on the variant badge does not re-evaluate the variables
that are defined in the mask workspace of the variant blocks. For example, consider a masked Variant
Subsystem block with the variant control variable defined in the mask workspace of the block. To
change the active choice of the block, you change the value of the variant control variable. When you
then click the Refresh Blocks (Ctrl+K) option, the variant control variable is not re-evaluated and
so the active choice of the block is not updated. You must click Apply on the mask dialog or update
the diagram for the latest active choice to reflect.

12-11
12 Modeling Variant Systems

Variant Badge Icons for Different Settings on Variant Blocks

Variant Badge Variant Source Variant Sink Variant Subsystem


Default Variant badge when
no option is selected.

Variant block with Label


selected as Variant control
mode and an active variant
choice is selected from Label
mode active choice option.

Variant block with Allow


zero active variant
controls option selected.

Variant block with


expression selected as
Variant control mode and
update diagram selected
as Variant activation time.

12-12
What Are Variants and When to Use Them

Variant Badge Variant Source Variant Sink Variant Subsystem


Variant block with
expression selected as
Variant control mode and
update diagram analyze
all choices selected as
Variant activation time.

Variant block with


expression selected as
Variant control mode and
code compile selected as
Variant activation time.

Variant block with


expression selected as
Variant control mode and
startup selected as Variant
activation time.

Variant block with sim


codegen switching
selected as Variant control
mode and update diagram
selected as Variant
activation time.

12-13
12 Modeling Variant Systems

Variant Badge Variant Source Variant Sink Variant Subsystem


Variant block with sim
codegen switching
selected as Variant control
mode and update diagram
analyze all choices
selected as Variant
activation time.

Variant block with Not applicable Not applicable


Propagate conditions
outside of variant
subsystem option selected.
Variant block with update
diagram selected as Variant
activation time and Allow
zero active variant
controls option selected.

Variant block with update


diagram analyze all
choices selected as Variant
activation time and Allow
zero active variant
controls option selected.

Variant block with code


compile selected as Variant
activation time and Allow
zero active variant
controls option selected.

12-14
What Are Variants and When to Use Them

Variant Badge Variant Source Variant Sink Variant Subsystem


Variant block with startup
selected as Variant
activation time and Allow
zero active variant
controls option selected.

Variant block with inherit


from
Simulink.VariantContro
l selected as Variant
activation time before
model compile.

Variant block with update Not applicable Not applicable


diagram selected as Variant
activation time and
Propagate conditions
outside of variant
subsystem option selected.
Variant block with update Not applicable Not applicable
diagram analyze all
choices selected as Variant
activation time and
Propagate conditions
outside of variant
subsystem option selected.
Variant block with code Not applicable Not applicable
compile selected as Variant
activation time and
Propagate conditions
outside of variant
subsystem option selected.
Variant block with startup Not applicable Not applicable
selected as Variant
activation time and
Propagate conditions
outside of variant
subsystem option selected.

12-15
12 Modeling Variant Systems

Variant Badge Variant Source Variant Sink Variant Subsystem


Variant block with Allow Not applicable Not applicable
zero active variant
controls and Propagate
conditions outside of
variant subsystem option
selected.
Variant block with sim Not applicable Not applicable
codegen switching
selected as Variant control
mode and Propagate
conditions outside of
variant subsystem option
selected.

Define and Control Variant Choices

You must associate each variant choice in a model with a variant control that is used to determine if
the choice is active or inactive. For variant blocks, you can choose the mode in which you want to
specify the variant controls using the Variant control mode parameter. For more information, see
“Introduction to Variant Controls” on page 12-62.

Automatically Identify Variant Regions Using Variant Condition Propagation

Simulink determines the model components that are active during simulation by the process of
variant condition propagation. This process evaluates the variant controls specified on the variant

12-16
What Are Variants and When to Use Them

blocks and automatically propagates the variant conditions to the connecting blocks. Variant
conditions can propagate through signal lines, buses, and function calls. The process deactivates the
model components associated with the inactive choices and they are not included in simulation. You
can stop condition propagation to define variant regions in the model. See “Propagate Variant
Conditions to Define Variant Regions with Variant Blocks” on page 12-133.

Choose a Variant Activation Time

You can also choose when the active variant choice is determined using the Variant activation time
parameter. This parameter also determines how the active and inactive choices participate in the
simulation and code generation workflows. See “Activate Variant During Different Stages of
Simulation and Code Generation Workflow” on page 12-93.

Note You can choose the variant activation time for a variant block only when Variant control
mode is set to expression.

Manual Variant Source and Manual Variant Sink blocks do not support variant controls and variant
activation time. They determine the active variant choice based on the active inports and outports,
respectively.

Variant Connector blocks do not support variant activation time.

Manage All Variants Using Variant Manager

Variant Manager is a tool that allows you to visualize the model hierarchy and centrally manage the
usage of variant elements across the hierarchy.

The tool is available as a support package named Variant Manager for Simulink with these main
capabilities:

• Variant Manager — Visualize the model hierarchy, manage the usage of variant elements across
the hierarchy, create and manage variant configurations.
• Variant Reducer — Generate a reduced model that contains only selected variant configurations.
• Variant Analyzer — Compare and contrast variant configurations to identify errors or
inconsistencies.

Create and Activate Variant Configurations:

12-17
12 Modeling Variant Systems

A model hierarchy may contain several variant blocks, each with many variant choices. Combinations
of these variant choices correspond to specific configurations of the system. Switching between these
configurations and validating them manually can be complicated and can introduce errors. You can
use the Variant Manager to create and save variant configurations for a model and run the model
under any of the configurations. You can also validate the configurations against a set of constraints.

Analyze and Reduce Variant Configurations:

You can use the Variant Analyzer tool in the Variant Manager to compare variant configurations for a
model and to determine which blocks are used in each configuration. The tool helps in model
verification and validation workflows because it can identify unused regions in the model.

You can use the Variant Reducer tool in the Variant Manager to automatically generate a reduced
model for a subset of variant configurations and analyze the reduced model in a detailed report. The
reduction process removes inactive components for the specified variant configurations. Variant
Reducer reduces associated model references, subsystem references, and libraries in the model. The
tool also reduces any dependent artifacts, such as MAT or .sldd files, and packages all the reduced
artifacts in a specified output folder.

See “Variant Manager for Simulink”.

12-18
What Are Variants and When to Use Them

Generate Code from Variant Models

You can use Simulink Coder or Embedded Coder to generate code from variant models. See “Prepare
Variant-Containing Model for Code Generation” on page 12-220.

For examples that show variant code generation capabilities, see “Variant Systems” (Simulink Coder).

See Also

Related Examples
• “V-Model for System Development with Simulink Variants” on page 12-243
• “Create a Simple Variant Model” on page 12-45
• “Create a Simple Variant Parameter Model” on page 90-5
• “Create and Activate Variant Configurations” on page 89-10
• “Implement Variations in Separate Hierarchy Using Variant Subsystems” on page 12-48
• “Variant Source and Variant Sink Blocks” on page 12-150
• “Control Indicator Lamp Dimmer Using Variant Conditions” (Stateflow)
• “Transform Model to Variant System” (Simulink Check)
• “Create Custom Check to Evaluate Active and Inactive Variant Paths from a Model” (Simulink
Check)

More About
• Variant System Design
• “Variant Terminology” on page 12-20
• “Introduction to Variant Controls” on page 12-62
• “Working with Variant Choices” on page 12-59
• “Create and Activate Variant Configurations” on page 89-10
• Managing Design Variants
• Using Variant Subsystems (3 min, 38 sec)
• Variant Source and Sink Blocks with Condition Propagation
• Variant Condition Propagation
• Variant Configuration Management
• Generate Code from Variant Source and Sink Blocks
• Model AUTOSAR Variants

12-19
12 Modeling Variant Systems

Variant Terminology
Simulink variant terminology helps you to understand various parameters and terms.

Variant Terminology Description


Variant Subsystem, Variant Model, Variant Contains one or more choices where each choice
Assembly Subsystem is a Subsystem or Model block.
Variant Source Provides variation on the source of a signal.
Variant Sink Provides variation on the sink (destination) of a
signal.
Variant Model Variant Subsystem block containing Model block
as variant choices. See Variant Subsystem,
Variant Model, Variant Assembly Subsystem.
Active choice on page 12-60 Variant choice associated with a variant control
that evaluates to true.
Variant control mode on page 12-64 expression, label or sim codegen
switching for modeling variant blocks and
variant parameters.
Variant control variable MATLAB variable,
Simulink.VariantExpression object, or a
Simulink.Parameter object. See “Types of
Variant Control Variables (Operands) in Variant
Blocks” on page 12-66.
Variant object Container of variant control expression. See
Simulink.VariantExpression.
Variant Manager Central tool that allows you to manage various
variation points that are modeled using variant
blocks in a system model.
Variant Reducer on page 89-44 Reduces variant models to simplified, standalone
model depending on the selected variant
configurations.

12-20
Variant Terminology

Variant Terminology Description


Variant Configuration, Variant Configuration data A variant configuration consists of a named set of
object variant control variables, their values, and
configurations to be used by referenced models.
It can be used to activate a variation of a
Simulink model.

A variant configuration data object (instance of


the Simulink.VariantConfigurationData
class) associated with a model stores:

• Collection of all variant configurations for the


model.
• Set of constraints that must be satisfied by the
model for all variant configurations.
• Default configuration for the model.

You can create new variant configurations and


group them into a variant configuration data
object from Variant Manager or programmatically
using the
Simulink.VariantConfigurationData class.

To associate the variant configuration data object


to a model, use the Export variant configuration
data object functionality in Variant Manager, or
use the VariantConfigurationObject
parameter. Example:

variantConfig = Simulink.VariantConfigurationData;
set_param(model, 'VariantConfigurationObject',...
'variantConfig');

Command Line Parameters


Variant Subsystem Parameters

This section lists the command line parameters you can use to control a Variant Subsystem block
during simulation or code generation.

You can add variant choices to the Variant Subsystem block using the add_block command:

add_block('simulink/Ports & Subsystems/BlockName', ...


[ModelName '/VariantSubsystemChoicePath'], ...
VariantControl='VariantControlName');

Here, BlockName is the block to add as a variant choice to the Variant Subsystem block at path
VariantSubsystemChoicePath in the model ModelName. VariantControlName is the name of
the variant control for the newly added variant choice.

For example, to add the Subsystem block named Discrete as a variant choice to the Controller
subsystem in the slexVariantSubsystemsAdaptiveInterface model, use this command. Specify
the variant control as V == 3.

12-21
12 Modeling Variant Systems

add_block('simulink/Ports & Subsystems/Subsystem', ...


'slexVariantSubsystemsAdaptiveInterface/Controller/Discrete', ...
VariantControl='V == 3');

Note If you do not specify a variant control, a variant block with an empty variant control is created.
You are then required to specify the variant control parameter in the subsequent line of code.

Parameter name Description


Variant Used to check if the subsystem is a Variant
Subsystem block. Returns on if the subsystem is
a Variant Subsystem block, else it returns off.
Example: get_param(gcb, 'Variant')

This is a read-only parameter.


VariantChoices Gets the list of variant choices in a Variant
Subsystem block. Example: get_param(gcb,
'VariantChoices');

Returns a 1-by-N struct array with fields:

Name: Name of the variant control

BlockName: Block path name

This is a read-only parameter.


VariantControl Subsystem block and Model block parameter,
which applies to a choice block of a Variant
Subsystem block and returns the variant control
for the choice block.

• get_param behavior: Returns variant controls


for choice block of a Variant Subsystem block.
Example: get_param(gcb,
'VariantControl')
• set_param behavior: Sets variant control for
current block. Example: set_param(gcb,
'VariantControl', 'A==1')

12-22
Variant Terminology

Parameter name Description


VariantControlMode Specifies the mode for modeling Variant blocks,
which can be either expression or label or
sim codegen switching.

• get_param behavior:

Returns the mode set for modeling Variant


blocks. Example: get_param(gcb,
'VariantControlMode')
• set_param behavior:

Sets the mode for modeling Variant blocks.


Example: set_param(gcb,
'VariantControlMode', 'Label')

See “Variant control mode”.


LabelModeActiveChoice Returns the variant control label of the selected
choice for the Variant Subsystem block when
VariantControlMode is specified as label . If
VariantControlMode is specified as
expression, this parameter returns empty
('').

• get_param behavior:

Returns the variant control label of the


selected choice for the Variant Subsystem
when VariantControlMode is set to label.
If VariantControlMode is set to
expression, this parameter returns empty
('').
• set_param behavior:

When VariantControlMode is specified as


expression, set_param makes the label
selected as the active choice. When
VariantControlMode is label, set_param
switches between specified labels.

See “Label mode active choice”.

12-23
12 Modeling Variant Systems

Parameter name Description


TreatAsGroupedWhenPropagatingVariantCo Returns on if the Subsystem is treated as a group
nditions when propagating variant conditions else returns
off.

• get_param behavior:

Indicates if the subsystem is treated as a


group when propagating Variant conditions or
not by returning on or off. Example:
get_param(gcb,
'TreatAsGroupedWhenPropagatingVaria
ntConditions')
• set_param behavior:

Enables or disables treating subsystem as a


group when propagating variant conditions.
Example: set_param(gcb,
'TreatAsGroupedWhenPropagatingVaria
ntConditions', 'on')

See “Propagate Variant Conditions to Define


Variant Regions in Virtual and Nonvirtual
Subsystems” on page 12-157.
GeneratePreprocessorConditionals Indicates if all the choices are to be analyzed and
preprocessor conditionals to be generated by
returning on or off.

• get_param behavior:

Indicates if all the choices are to be analyzed


and preprocessor conditionals be generated
by returning on or off. Example:
get_param(gcb,
'GeneratePreprocessorConditionals')
• set_param behavior:

Enables or disables analyzing all the choices


and generating preprocessor conditionals.
Example: set_param(gcb,
'GeneratePreprocessorConditionals',
'on')

Note Use the “Variant activation time”


parameter instead.

12-24
Variant Terminology

Parameter name Description


CompiledActiveChoiceControl Returns the variant control corresponding to the
active choice of the Variant Subsystem block and
returns empty (' ') when no choice is active.
When the block is commented or is inside a
commented subsystem, this parameter returns
empty(' '). Example: get_param(gcb,
'CompiledActiveChoiceControl').

This is a read-only parameter.


CompiledActiveChoiceBlock Returns the full block path name of the active
Variant Subsystem block choice and returns
empty (' ') when no choice is active. When the
block is commented or is inside a commented
Subsystem, the value is returned as empty(' ').
Example: get_param(gcb,
'CompiledActiveChoiceBlock').

This is a read-only parameter.


CompiledVariantInfo Block parameter that indicates the variant
activeness of a block after model compilation.
Returns a structure with three fields, with values
set to on or off:

• IsActive: Value is on if the block is active in


simulation.
• IsInCodegen: Value is on if the block is part
of generated code.
• IsInStartup: Value is on if the block is
active or can become active in simulation (the
propagated value of Variant activation time
on the block is startup) after model
compilation.

For an example, see “Identify Variant Activeness


of a Block After Model Compilation” on page 12-
33.

This is a read-only parameter.


CompiledVariantActivationTime Returns the variant activation time of the block
after model compilation. Before the model is
compiled, this parameter returns update diagram
activation time. Example:
get_param(gcb,'CompiledVariantActivati
onTime')

This is a read-only parameter.

12-25
12 Modeling Variant Systems

Parameter name Description


PropagateVariantConditions Indicates if conditions on ports inside the Variant
Subsystem block are to be propagated outside
the block.

• get_param behavior:

Indicates if conditions on ports inside the


Variant Subsystem block are to be propagated
outside the block.
• set_param behavior:

Enables or disables propagating conditions


outside Variant Subsystem block. Example:
set_param(gcb,
'PropagateVariantConditions','on')

See “Propagate conditions outside of variant


subsystem”.
AllowZeroVariantControls Indicates if the Variant Subsystem block is
allowed to have no active choices.

• get_param behavior:

Indicates if the Variant Subsystem block is


allowed to have no active choices.
• set_param behavior:

Enables or disables having active choices in


Variant Subsystem block. Example:
set_param(gcb,
'AllowZeroVariantControls','on')

See “Allow zero active variant controls”.

12-26
Variant Terminology

Parameter name Description


VariantActivationTime Determines if Simulink sets the active choice of a
Variant Subsystem block during update diagram
or code compile.

• get_param behavior:

Returns the Variant Activation Time of


a Variant Subsystem block. This parameter
can be set to update diagram, update
diagram analyze all choices, or code
compile.

Example: get_param(gcb,
'VariantActivationTime')
• set_param behavior:

• When you set the Variant control mode


to expression, this parameter can be set
to update diagram, update diagram
analyze all choices, or code
compile.
• When you set the Variant control mode
to sim codegen switching, this
parameter can be set to either update
diagram or update diagram analyze
all choices. The code compile option
becomes unavailable.

Example:
set_param(gcb,'VariantActivationTim
e', 'update diagram')

Note The get_param and set_param behavior


of VariantActivationTime parameter with the
code compile option is equivalent to that of the
parameter
GeneratePreprocessorConditionals.

See “Variant activation time”.

12-27
12 Modeling Variant Systems

Parameter name Description


VariantControlVariable Specifies the variant control variable of a Variant
Assembly Subsystem block that is in expression
mode.

• get_param behavior:

Returns the variant control variable of a


Variant Assembly Subsystem block.

Example: get_param(gcb,
'VariantControlVariable')
• set_param behavior:

Sets the variant control variable of a Variant


Assembly Subsystem block.

Example:
set_param(gcb,'VariantControlVariab
le', 'variantCtrlVar')

See “Variant control variable”.


VariantChoicesEnumeration Specifies the variant choices of a Variant
Assembly Subsystem block that is in expression
mode.

• get_param behavior:

Returns the enumeration class name that


contains the variant choice names as its
members.

Example: get_param(gcb,
'VariantChoicesEnumeration')
• set_param behavior:

Sets the variant choices using the


enumeration class.

Example:
set_param(gcb,'VariantChoicesEnumer
ation', 'controllerEnum')

See “Variant choices enumeration”.

12-28
Variant Terminology

Parameter name Description


VariantChoicesSpecifier Specifies the variant choices of a Variant
Assembly Subsystem block that is in label
mode.

• get_param behavior:

Returns the specifier that evaluates to the


variant choice names.

Example: get_param(gcb,
'VariantChoicesSpecifier')
• set_param behavior:

Sets the variant choices using the specifier.

Example:
set_param(gcb,'VariantChoicesSpecif
ier',"{'ControllersList/*',
'ControllersList/*/*'}")

See “Variant choices specifier”.


AllowFlexibleInterface Indicates if the Variant Subsystem block has a
flexible interface.

• get_param behavior:

Indicates if the Variant Subsystem has a


flexible interface.
• set_param behavior:

Enables or disables the flexible interface of


the Variant Subsystem block.

See Allow flexible interface.

Variant Source and Variant Sink Parameters

This section lists the command line parameters you can use to control Variant Source and Variant
Sink blocks during simulation or code generation.

You can add these blocks using the add_block command:

add_block('simulink/Signal Routing/BlockName', ...


[ModelName '/VariantBlockPath']

Here, BlockName is the variant block to be added to VariantBlockPath in model ModelName.

For example, to add the Variant Source block named Discrete in the slexVariantSourceAndSink
model, use this command. Specify the variant control as V == 3.
add_block('simulink/Signal Routing/Subsystem', ...
'slexVariantSourceAndSink/Discrete', ...
VariantControl='V == 3');

12-29
12 Modeling Variant Systems

Parameter name Description


VariantControls Returns a 1-by-N cell array of variant control
expressions corresponding to each of the N ports
of the Variant Source or Variant Sink blocks.

• get_param behavior:

Returns a cell array of variant control


expressions corresponding to each ports of
the Variant Source or Variant Sink blocks.
Example: get_param(gcb,
'VariantControls')
• set_param behavior:

Sets the cell array of Variant control


expressions corresponding to each of ports of
Variant Source or Variant Sink blocks.
Example: set_param(gcb,
'VariantControls', ('{A==1}, '4'))
VariantControlMode Specifies the mode for modeling variant blocks,
which can be either Expression or Label.

• get_param behavior:

Returns the mode set for modeling Variant


blocks. Example: get_param(gcb,
'VariantControlMode')
• set_param behavior:

Sets the mode for modeling Variant blocks.


Example: set_param(gcb,
'VariantControlMode', 'Label')

See “Variant control mode”.

12-30
Variant Terminology

Parameter name Description


LabelModeActiveChoice Returns the variant control label of the selected
choice for Variant Source or Variant Sink block
when VariantControlMode is specified as
Label. If VariantControlMode is specified as
Expression, this parameter returns empty
('').

• get_param behavior:

Returns the variant control label of the


selected choice for the Variant Subsystem
when VariantControlMode is set to Label.
If VariantControlMode is set to
Expression, this parameter returns empty
('').
• set_param behavior:

When VariantControlMode is specified as


Expression, set_param makes the label
selected as the active choice. When
VariantControlMode is Label, set_param
switches between specified labels.

See “Label mode active choice”.


GeneratePreprocessorConditionals Indicates if all the choices are to be analyzed and
preprocessor conditionals to be generated by
returning on or off.

• get_param behavior:

Indicates if all the choices are to be analyzed


and preprocessor conditionals to be generated
by returning on or off. Example:
get_param(gcb,
'GeneratePreprocessorConditionals')
• set_param behavior:

Enables or disables analyzing all the choices


and generating preprocessor conditionals.
Example: set_param(gcb,
'GeneratePreprocessorConditionals',
'on')

Note Use the “Variant activation time”


parameter instead.

12-31
12 Modeling Variant Systems

Parameter name Description


ShowConditionOnBlock Indicates if the VariantControlExpression is
to be displayed on the block by returning on or
off.

• get_param behavior:

Indicates if the
VariantControlExpression is to be
displayed on the block or not.
• set_param behavior:

Enables or disables the displaying of


VariantControlExpression on the block.
Example: set_param(gcb,
'ShowConditionOnBlock','on')

See “Show variant condition on block”.


AllowZeroVariantControls Indicates if the block is allowed to have no active
ports by returning on or off.

• get_param behavior:

Indicates if the Variant Source or Variant Sink


block is allowed to have no active choices.
• set_param behavior:

Enables or disables having active choices in


Variant Source or Variant Sink block.
Example: set_param(gcb,
'AllowZeroVariantControls','on')

See “Allow zero active variant controls”.


CompiledActiveVariantControl Returns the variant control corresponding to the
active port from the last compilation instance. If
no port is active, returns empty (' '). If the
block is commented or inside a commented
Subsystem or inside an inactive choice of a
Variant Subsystem block, the value is not
computed and returns empty (' '). Example:
get_param(gcb,
'CompiledActiveVariantControl')

This is a read-only parameter.

12-32
Variant Terminology

Parameter name Description


CompiledActiveVariantPort Returns the "index" of the active port from the
last compilation instance or returns -1 when no
port is active. If the block is commented or inside
a commented Subsystem or inside an inactive
choice of a Variant Subsystem block (with
generate preprocessor conditionals Off), the
value is not computed, and returns empty (' ').
Example: get_param(gcb,
'CompiledActiveVariantPort')

This is a read-only parameter.


CompiledVariantActivationTime Returns the variant activation time of the block
after model compilation. Before the model is
compiled, this parameter returns update diagram
activation time. Example:
get_param(gcb,'CompiledVariantActivati
onTime')

This is a read-only parameter.


OutputFunctionCall Indicates if the Variant Source or Variant Sink
blocks are allowed to output function-call signals.

• get_param behavior:

Indicates if the variant block is allowed to


output function-call signals.

Example: get_param(gcb,
'OutputFunctionCall')
• set_param behavior:

Enables or disables the ability of the variant


block to output function-call signals. Example:
set_param(gcb,
'OutputFunctionCall','on')

See “Output function call”.

Examples
Identify Variant Activeness of a Block After Model Compilation

This example shows the behavior of the CompiledVariantInfo command line parameter. Consider a
model with two Variant Subsystem blocks, StartupVSS and UDVSS, with the Variant activation
time parameter set to startup and update diagram, respectively. The result of
CompiledVariantInfo parameter after model compilation is shown for each variant choice.

• The active choice in both StartupVSS and UDVSS has IsInStartup set to on because the blocks
are active in simulation.

12-33
12 Modeling Variant Systems

• The inactive choice in StartupVSS gets the propagated startup variant activation time from its
parent, so IsInStartup is on.
• The inactive choice in UDVSS has the update diagram variant activation time, so IsInStartup
is off.

See Also

Related Examples
• Variant Subsystem, Variant Model, Variant Assembly Subsystem
• Variant Source
• Variant Sink

More About
• Variant System Design

12-34
Define and Configure Variant Sources and Sinks

Define and Configure Variant Sources and Sinks


Simulink provides two blocks, Variant Source and Variant Sink, that you can use to visualize all
possible implementations of variant choices in a model graphically. This example shows how to
configure variant choices using the Variant Source and Variant Sink blocks.

Represent Variant Choices in Variant Source and Variant Sink Blocks


The variant conditions at the inports and outports of Variant Source and Variant Sink blocks,
respectively, determine the activation and deactivation of the blocks connected to them. You can
specify the conditions for activating a variant choice using a variant control. While each variant
choice is associated with a variant control, only one variant control can evaluate to true. When a
variant control evaluates to true, Simulink activates the corresponding variant choice. You can also
specify at most one variant choice as the default choice.

You can choose the mode in which you want to specify the variant controls using the Variant control
mode parameter. This example uses the expression mode. Here, we specify the variant controls as
Boolean condition expressions that contain Simulink.Parameter objects defined in the base
workspace of the model.

Tip For information on different variant control modes, see “Introduction to Variant Controls” on
page 12-62.

For information on the types of variant control variables supported in variant condition expressions,
see “Types of Variant Control Modes in Variant Blocks” on page 12-64.

1 Add Variant Source and Variant Sink blocks to your model.

2 Using blocks from the Simulink Library Browser, create sources and sinks that represent variant
choices. Connect choices to the input and output ports of the Variant Source and Variant Sink
blocks.

12-35
12 Modeling Variant Systems

3 In the MATLAB Command Window, run these commands to create the variant control variables.

V = Simulink.Parameter(1);
W = Simulink.Parameter(2);
4 Open the block parameter dialog box of the Variant Source block. Double-click the block or right-
click the block and select Block Parameters (Variant Source).

Tip For information on all block parameters, see Variant Source and Variant Sink.

The Ports and associated conditions table in the block parameter dialog box has a row for
each variant choice connected to the input port of the Variant Source block. If there are no
variant choices, the table is empty.

You can use buttons to the left of the table to modify the elements in the table.

Action Button
Add a new input port: Create a new input port as a variant choice
and add an entry for the new choice in the table.
Delete selected port: Delete the selected variant choice from the
block and the variant choice entry from the table.

12-36
Define and Configure Variant Sources and Sinks

Action Button
Create/Edit selected variant object: Create or edit a
Simulink.VariantExpression object for the selected variant
choice in the base workspace and specify the variant condition using
the Simulink.VariantExpression object parameter dialog box.

Note For a model that uses the base workspace, this operation
creates the Simulink.VariantExpression object in the base
workspace, and the object is available only for the current MATLAB
session. To permanently store the data, save the object in a MAT file
or MATLAB script.
5 In the block parameters dialog box, in the Variant control expression column, type V==1 for
one choice and V==2 for the other.

To specify one choice as the default variant, select (default) from the Variant control
expression list. If none of the variant controls evaluate to true, Simulink uses the default
variant for simulation and code generation.

6 Click Apply.
7 Double-click the Variant Sink block. In the block parameters dialog box, in the Variant control
expression column, type W==1 for one choice and W==2 for the other.

12-37
12 Modeling Variant Systems

8 Click Apply.
9 Simulate the model. Simulink propagates the variant conditions to identify which model
components to activate.

10 You can visualize the conditions that activate each variant choice. In the Debug tab of toolstrip,
select Information Overlays > Variant Conditions.

12-38
Define and Configure Variant Sources and Sinks

11 In the Variant Condition Legend dialog box, click through the hyperlinked variant condition
annotations to observe which parts of the model each condition activates.

Generate Code for Variant Source and Variant Sink Blocks


For an example on generating code, see “Generate Code for Variant Source and Variant Sink Blocks”
(Simulink Coder).

12-39
12 Modeling Variant Systems

See Also

Related Examples
• “Visualize Variant Implementations in a Single Layer” on page 12-41
• “Working with Variant Choices” on page 12-59

More About
• “Introduction to Variant Controls” on page 12-62
• “Create a Simple Variant Model” on page 12-45
• Variant System Design

12-40
Visualize Variant Implementations in a Single Layer

Visualize Variant Implementations in a Single Layer


Simulink provides two blocks that you can use to propagate conditions throughout the model and
visualize all possible implementations of variant choices in a model. These blocks are called Variant
Source and Variant Sink.

When you compile the model, Simulink determines which variant control evaluates to true. Simulink
then deactivates blocks that are not tied to the variant control being true.

How Variant Sources and Sinks Work


The Variant Source block has one or more input ports and one output port. You can define variant
choices as blocks that are connected to the input port so that, at most, one choice is active. The
active choice is connected directly to the output port of the Variant Source and the inactive choices
are eliminated during simulation.

The Variant Sink block has one input port and one or more output ports. You can define variant
choices as blocks that are connected to the output port so that, at most, one choice is active. The
active choice is connected directly to the input port of the Variant Sink, and the inactive choices are
eliminated during simulation.

Connect one or more blocks to the input port of the Variant Source block or the output port of the
Variant Sink block. Then, you define variant controls for each variant choice entering the Variant
Source block and exiting the Variant Sink block. For more information, see “Propagate Variant
Conditions to Define Variant Regions Using Variant Source and Variant Sink Blocks” on page 12-150.

Advantages of Using Variant Sources and Sinks


Using Variant Source and Variant Sink blocks in Model-Based Design provides these advantages:

• The blocks enable the propagation of variant conditions throughout the model and allow you to
visualize variant choices in a single layer of your model.
• By visualizing all possible implementations of variant choices, you can improve the readability of
your model.

12-41
12 Modeling Variant Systems

• During model compilation, Simulink eliminates inactive blocks throughout the model, improving
the runtime performance of your model.
• Variant sources and sinks provide variant component interfaces that you can use to quickly model
variant choices.

Limitations of Using Variant Sources and Sinks


• Variant Source and Variant Sink blocks work with time-based, function-call, or action signals. You
cannot use SimEvents, Simscape Multibody™, or other non-time-based signals with these blocks.
• The code generation variant report does not contain Variant Source and Variant Sink blocks.

Generate Code for Variant Source and Variant Sink Blocks


For an example on generating code, see “Generate Code for Variant Source and Variant Sink Blocks”
(Simulink Coder).

See Also

Related Examples
• “Define and Configure Variant Sources and Sinks” on page 12-35

More About
• “Propagate Variant Conditions to Define Variant Regions Using Variant Source and Variant Sink
Blocks” on page 12-150
• Variant System Design

12-42
Provide Variation in Signal Source and Destination Using Manual Variant Source and Manual Variant Sink Blocks

Provide Variation in Signal Source and Destination Using


Manual Variant Source and Manual Variant Sink Blocks

This example shows how to use the inline variant blocks Manual Variant Source and Manual Variant
Sink. The Manual Variant Source Block provides variation on the source of a signal. The block is a
switch that can have two or more input ports and one output port. Each input port is associated with
a variant choice. Only one input port is active during simulation. The active input port determines the
active variant region. Similarly, the Manual Variant Sink block provides variation on the destination of
a signal. The block can have two or more output ports and one input port. Only one output port can
be active during simulation, and the blocks connected to that port determine the active variant.

Explore the Model

Open the model slexVariantManualBlocks.


open_system('slexVariantManualBlocks');

The model has two inline variant blocks, Manual Variant Source and Manual Variant Sink. Both blocks
have two variant regions at their input and output ports, respectively. The blocks indicate the
currently active variant using a line that connects the input to the output.

Switch the Active Variant

To change the variant choices in the Manual Variant Source or Manual Variant Sink block, double-
click the block. Instead of double-clicking the block, you can type these commands in the MATLAB®
Command Window.
open_system([bdroot,'/Manual Variant Source']);
open_system([bdroot,'/Manual Variant Sink']);

Access Block Parameters

To access the block parameters on a Manual Variant Source or Manual Variant Sink block, right-click
the block and select Mask > Mask Parameters. You can change the number of input ports on a

12-43
12 Modeling Variant Systems

Manual Variant Source block or the number of output ports on a Manual Variant Sink block using the
Number of Choices parameter.

Code Generation Behavior

Simulink® determines the active variant during model compilation, and the generated code contains
only the active choices.

See Also
Manual Variant Sink | Manual Variant Source

12-44
Create a Simple Variant Model

Create a Simple Variant Model

This example shows you how to create a simple model with variant blocks.

Variant blocks provide you a way to design alternatives of a system in a single model. Each design
choice is incorporated into the model as a variant choice in a single layer or a separate hierarchy.
Each variant choice is associated with a variant control. During simulation, the variant choices are
activated or deactivated depending on the variant controls you specify.

Use variant blocks to switch among blocks for multiple simulation, code generation, or testing
workflows.

Model Description

Open the slexVariantSubsystems model that contains a Variant Subsystem block.

open_system('slexVariantSubsystems')

Define Variant Control for Variant Subsystems

This section explains how to define variant control variables that determine the condition under
which a variant choice is active.

1. Right-click the variant block and click Block Parameters.

2. To choose the active Variant based on the evaluation of the Variant conditions, use the expression
mode, else select label mode. When you select the Variant control mode as label, the Label mode
active choice option is available. In label mode, Variant control need not be created in the base
workspace or data dictionary used by the model. You can select an active Variant choice from Label
mode active choice options.

3. Use the options available on the Block Parameter dialog box to add variant controls and its
corresponding variant condition.

A sample screenshot for expression mode:

12-45
12 Modeling Variant Systems

Note: The variables used to specify the variant control and variant condition must be defined in the
base workspace, model workspace, mask workspace or data dictionary for the model.

4. Specify a default variant condition to be used when there is no active variant choice. Use the
Variant control list to specify the default.

5. To activate a variant choice, type the variant choice in MATLAB® command window. For example,
type VSS_MODE = 2.

6. To simulate the model, on the toolstrip, click Run. The model simulates for the specified active
choice.

sim('slexVariantSubsystems');

7. Modify the active choice and simulate the model again, if necessary.

Generate Code for Variant Subsystems

This section explains how to generate code for the variants model with preprocessor conditionals. For
detailed information, see “Compile Code Conditionally for Variations of Component Represented
Using Variant Block” (Simulink Coder).

Note: You must have an Embedded Coder® license to generate the code.

1. In the Block Parameters dialog box, from the Variant activation time list, select code compile.

2. Open the Subsystem Block Parameters dialog boxes. Select the Treat as atomic unit parameter.

12-46
Create a Simple Variant Model

3. In the Code Generation section of Configuration Parameters dialog box, specify the System
target file as ert.tlc.

4. In Model Explorer, define the variables used to specify the variant choice as a MATLAB variable or
as a Simulink.Parameter. The data type of the Simulink.Parameter can be of type Integer,
Boolean, or Enumerated and the storage class can be either importedDefine(Custom),
Define(Custom), or CompilerFlag.

Export Control Variables to MAT-File

For the variants that are defined in the base workspace, you can export the control variables to a
MAT-file. For example, type the following in the MATLAB command window:

• save <MAT-File Name> <Variable Name>

• PostLoadCallback > load <MAT-File Name>

Note: To update or refresh active models that contain Variant Subsystem blocks, on the Modeling
tab, click Update Model (Ctrl + D) in Simulink.

See Also
“Implement Variations in Separate Hierarchy Using Variant Subsystems” on page 12-48 | “Working
with Variant Choices” on page 12-59 | “Create Variant Controls Programmatically” on page 12-91 |
“Variant Terminology” on page 12-20

12-47
12 Modeling Variant Systems

Implement Variations in Separate Hierarchy Using Variant


Subsystems

This example shows how to configure and use a Variant Subsystem block in Simulink®. The Variant
Subsystem block is a hierarchical variant block. The block allows you to encapsulate multiple
implementations or variations of a system component in a separate hierarchy in the model. Each
variation of the component represented within a Variant Subsystem block is referred to as a choice.
Only one of the variant choices within the Variant subsystem block can be active during model
execution. You can use a combination of Subsystem blocks, Model blocks, or “Create and Use
Referenced Subsystems in Models” on page 4-38 blocks to represent the choices within the Variant
Subsystem block.

For information on the block and its parameters, see Variant Subsystem, Variant Model, Variant
Assembly Subsystem.

Explore the Model

• Open the model slexVariantSubsystems. A variant subsystem block, Controller,


encapsulates two different implementations of the controller component in the system.

• Open the variant subsystem Controller. Two Subsystem blocks represent the two possible
variations of the Controller component. The first choice is a Linear Controller, and the
second choice is a Nonlinear Controller. Note that there are no drawn connections between
the blocks inside the Variant Subsystem block. Simulink automatically wires the active variant to
the Inport and Outport blocks of the Variant Subsystem block during simulation and disables the
inactive ports.

12-48
Implement Variations in Separate Hierarchy Using Variant Subsystems

• Open the Block Parameters dialog box for the Controller block. The Variant choices table lists
the choices of the variant subsystem. Each variant choice in the Controller block is associated
with a variant control. Here, the variant controls are the Simulink.VariantExpression
objects VSS_LINEAR_CONTROLLER and VSS_NONLINEAR_CONTROLLER. Simulink determines the
active choice of the variant subsystem by evaluating the variant controls of all the choices. When a
variant control evaluates to true, Simulink activates the variant choice that corresponds to that
variant control and disables the inactive choices. So, while each variant choice is associated with a
variant control, only one variant control must evaluate to true. This allows you to swap the active
and inactive choice in the variant subsystem without modifying the model structure.

Configure a Variant Subsystem Block

In this model, the Controller variant subsystem is preconfigured with two subsystems, Linear
Controller and Nonlinear Controller, as variant choices. To add more Variant Subsystem
blocks to this model and configure the blocks, perform these steps:
1 Add a Variant Subsystem block to your model using the Simulink Library Browser or the Quick
Insert menu and name the block. This block serves as the container for the variant choices.
2 To open the Variant Subsystem block and view its variant choices, double-click the block and then
click the Up to Parent button located in the toolbar at the top of the Simulink® model canvas.

12-49
12 Modeling Variant Systems

The Variant Subsystem block, by default, is a template preconfigured with two Subsystem blocks
to represent the variant choices.
3 Inside the Variant Subsystem block, add Inport and Outport blocks so that they match the inputs
into and outputs from the Variant Subsystem block.
4 Name the variant choice blocks.

NOTE:

• You can add only Inport, Outport, Subsystem, Model, and Subsystem Reference blocks inside a
Variant Subsystem block. You can pass control signals through data ports.

• If your variant choices have different numbers of input and output ports, see Represent Variant
Choices That Have Different Interfaces.

• When you add a Variant Subsystem block to your model, the Variant activation time parameter
is set to update diagram and the Propagate conditions outside of variant subsystem
parameter is set to off by default.

Types of Variant Choices in Variant Subsystem

You can add subsystems, Simulink models, and subsystem references as variant choices in a variant
subsystem.

Include Subsystem Block as Variant Choice

You can add a Subsystem block as a variant choice from the Block Parameters dialog box of the
Variant Subsystem block or using the action bar in the Simulink Editor from inside the variant
subsystem. Simulink creates an empty Subsystem block with the same number of input and output
ports as the containing Variant Subsystem block.

a. Using Block Parameters Dialog Box

1 Open the block parameter dialog box of the Variant Subsystem block. Right-click the badge on
the Variant Subsystem block and select Block Parameters (Subsystem).

12-50
Implement Variations in Separate Hierarchy Using Variant Subsystems

2 The “Variant choices (table of variant systems)” in the block parameter dialog box shows the
variant choices that you added. You can use buttons to the left of the table to add or modify
elements in the table.
3 To include a Subsystem block as a new variant choice inside the Variant Subsystem, click the
Create and add a new subsystem variant choice button to the left of the Variant choices table.
4 Open the new Subsystem block and add the model elements that represent a variant choice.

b. Using Action Bar


1 Double-click the Variant Subsystem block and then click the Up to Parent button located in the
toolbar at the top of the Simulink model canvas.
2 Drag a selection box around an empty area inside the Variant Subsystem block. The action bar
shows subsystem insertion options that are based on the type of subsystem choices in the block.
3 From the action bar, select the Variant Subsystem Choice option to add a subsystem block.
4 Open the new Subsystem block and add the model elements that represent a variant choice.

NOTE:

• If your variant choices have different numbers of input and output ports, see Represent Variant
Choices That Have Different Interfaces.

• You can use conditionally executed subsystems such as Enabled, Triggered, Reset, and the
Function-Call subsystems as variant choices within the Variant Subsystem block. For more
information, see “Propagate Variant Conditions to Control Execution of Conditional Subsystems”
on page 12-162.

12-51
12 Modeling Variant Systems

• When you prototype variants, you can create empty Subsystem blocks with no inputs or outputs
inside the Variant Subsystem block. The empty subsystem recreates the situation in which that
subsystem is inactive without the need for completely modeling the variant choice.

Include Simulink Model as Variant Choice

1 To include a Simulink model (Model block) as a new variant choice inside the variant subsystem,
click the Create and add a new model variant choice button to the left of the Variant choices
table. Simulink creates an unresolved Model block in the Variant Subsystem block.
2 Double-click the unresolved Model block. In the Model name box, enter the name of the model
you want to use as a model variant choice and click OK.

NOTE: The referenced model must have the same number of input and output ports as the containing
Variant Subsystem block. If your model has different number of input and output ports, see Represent
Variant Choices That Have Different Interfaces.

12-52
Implement Variations in Separate Hierarchy Using Variant Subsystems

Include Subsystem Reference as Variant Choice

1 To include a subsystem reference as a new variant choice inside the variant subsystem, add a
Subsystem Reference block using the Simulink Library Browser or the Quick Insert menu.
Simulink creates an empty Subsystem Reference block in the Variant Subsystem block.
2 Double-click the Subsystem Reference block. In the Block Parameters dialog box, specify the
subsystem block diagram file and click OK.

12-53
12 Modeling Variant Systems

Choose a Variant Control Mode

You must associate each variant choice in a model with a variant control that determines if the choice
is active or inactive. You can choose the mode in which you want to specify the variant controls using
the “Variant control mode” block parameter. The Variant control mode parameter for the
Controller block in this example is set to expression. In this mode, you can specify the variant
control for a choice as a Boolean condition expression, a Simulink.VariantExpression object,
the default variant choice, or an empty choice. For information on the different types of variant
control modes, see “Variant Control Modes in Variant Blocks” on page 12-64.

Use Variant Controls to Activate and Switch Between Variant Choices

In this model, the variant control for each choice is defined using two
Simulink.VariantExpression objects, VSS_LINEAR_CONTROLLER and
VSS_NONLINEAR_CONTROLLER. To see the definitions of the Simulink.VariantExpression
objects used in this model, click Model Settings > Model Properties > PreLoadFcn callback.
When you open the model, the PreLoadFcn callback runs and creates the objects in the base
workspace of the model.

A Simulink.VariantExpression object allows you to encapsulate a Boolean condition expression


that activates a specific variant choice when it evaluates to true. You can build the condition
expression using one or more variant control variables, which are defined as MATLAB® variables or
Simulink.Parameter objects in the base workspace or a data dictionary. In this example, a normal
MATLAB variable, VSS_MODE, is used to build the condition expression for the
Simulink.VariantExpression objects.

12-54
Implement Variations in Separate Hierarchy Using Variant Subsystems

To associate the Simulink.VariantExpression objects, VSS_LINEAR_CONTROLLER and


VSS_NONLINEAR_CONTROLLER, with the variant choices of the Controller block:

• In the Block Parameters dialog box, enter the name of the object in the Variant control
expression column for each choice.
• The Condition column automatically shows the boolean condition that the
Simulink.VariantExpression object represents.

Since VSS_MODE is set to 2 , the NonLinear Controller gets activated by default. To switch the
active choice to Linear Controller, set VSS_MODE = 1 in the base workspace and simulate the
model.

Specify Default Variant Choice: When the variant control mode is set to expression, you can
specify at most one variant choice as the default for the model. Simulink evaluates the variant
controls and verifies that only one variant choice is active during simulation. If none of the variant
controls evaluate to true, Simulink uses the default variant for simulation and code generation. To
set a variant choice as the default, select the (default) keyword in the Variant control
expression column for that choice.

Specify Empty Variant Choice: If you added an empty variant choice, you can either specify a
variant activation condition for the choice or comment out the existing variant condition by placing a
% symbol before the condition. If this variant choice is active during simulation, Simulink ignores the
empty variant choice. However, Simulink continues to execute block callbacks inside the empty
variant choices.

12-55
12 Modeling Variant Systems

For information on other ways to define variant controls, see “Use Variant Control Variables in Variant
Blocks” on page 12-78.

Choose a Variant Activation Time

The Variant activation time that you specify for the Variant Subsystem block determines the stage
when Simulink sets the active choice for the block. This parameter also determines how the active
and inactive choices participate in the simulation and code generation workflows.

For the Controller block, this parameter is set to update diagram. So, Simulink sets the active
choice at the start of the model compilation stage and the inactive choices are removed. When you
execute the model, only the active choice is analyzed for consistency. Generated code contains only
the active choice. For information on other variant activation times, see “Activate Variant During
Different Stages of Simulation and Code Generation Workflow” on page 12-93.

Represent Variant Choices That Have Different Interfaces

In this example, the two variant choices, Linear Controller and NonLinear Controller, have
the same number of input and output ports as the Controller variant subsystem. The blocks that
represent the variant choices can also have input and output ports that differ in number from the
input and output ports on the parent Variant Subsystem block. The Variant Subsystem block can
adapt its interface based on the activeness of the underlying blocks. This allows you to model
component variations that do not have a similar interface. In this case, these conditions must be
satisfied by the variant choices:

• The Allow flexible interface parameter must be set to 'on'.


• The variant choices must have same set of inports as the Variant Subsystem container block or it
must be a subset of ports on the container block.
• The variant choices must have same set of outports as the Variant Subsystem container block or it
must be a subset of ports on the container block.
• If the Variant Subsystem container block has control ports, the type of control port blocks in all
the variant choices must be same as the Variant Subsystem block. For example, you cannot use
Enabled Subsystem and Function-Call Subsystem blocks as choices within a Variant Subsystem
block. The control port on the Variant Subsystem block and the corresponding control ports on its
variant choices must have the same name. For example, if the name of the control port on the
Variant Subsystem is fcn, then the name of the corresponding control ports on all its variant
choices must also be fcn.

For an example, see “Adaptive Interface for Variant Subsystems” on page 12-141.

When simulating models, a Variant Subsystem or Variant Assembly Subsystem block may have
missing or unused ports. This can occur when a Variant Subsystem does not have a port that is

12-56
Implement Variations in Separate Hierarchy Using Variant Subsystems

present in one of its variant choices, or conversely, has a port that is not used by any variant choice.
To address this, you can use the Simulink.VariantUtils.updateVariantSubsystemPorts
function to automatically adjust the interface of the Variant Subsystem or Variant Assembly
Subsystem block by adding any missing ports and removing any unused ports.

Allow Zero Active Variant Controls for Variant Subsystem

The Allow zero active variant controls parameter on the Variant Subsystem block determines
whether the block allows simulation even if none of the variant choices are active. When you select
this option and if there is no active variant choice, Simulink simulates the model without any active
variant choice in the variant subsystem. When you clear the option, Simulink generates an error
when there is no active variant choice. This parameter is available only if there are no (default)
variant choices in the variant subsystem and if you set Variant control mode to expression.

Propagate Variant Conditions Outside Variant Subsystem

During simulation, Simulink automatically propagates variant conditions from variant blocks to
connecting blocks to determine which components of the model remain active. For a variant
subsystem, the variant conditions defined on the choices do not propagate outside the Variant
Subsystem block by default. To enable this, you can set the Propagate conditions outside of
variant subsystem parameter on the Variant Subsystem block.

When you select the Propagate conditions outside of variant subsystem parameter, Simulink
propagates the variant condition of the underlying blocks to the Variant Subsystem container block so
that the subsystem can adapt its interface to the state of the underlying blocks. Ports that are
mapped to the ports on the active choice becomes active. Ports that are mapped to the ports on the
inactive choice becomes inactive. Selecting this option ensures that the components outside of the
Variant Subsystem are aware of the active and inactive state of blocks within the Variant Subsystem
block. For more information, see “Propagate Variant Conditions to Define Variant Regions Outside
Variant Subsystems” on page 12-140.

Convert to Variant Subsystem Block

In the Simulink Editor, you can convert these blocks to a Variant Subsystem block:

• Subsystem block
• Model block
• Conditionally executed subsystems

To do so, right-click the block and in the context menu click Subsystem & Model Reference >
Convert to > Variant Subsystem.

You can also convert these blocks to a Variant Subsystem block programmatically using the
Simulink.VariantUtils.convertToVariantSubsystem method.

Generate Code for Variant Subsystems

For an example on generating code, see “Generate Code for Variant Subsystem Blocks” (Simulink
Coder).

See Also
“Working with Variant Choices” on page 12-59 | “Propagate Variant Conditions to Control Execution
of Conditional Subsystems” on page 12-162

12-57
12 Modeling Variant Systems

Related Examples
• “Generate Code for Variant Subsystem Blocks” (Simulink Coder)

12-58
Working with Variant Choices

Working with Variant Choices


In this section...
“Default Variant Choice” on page 12-60
“Active Variant Choice” on page 12-60
“Inactive Variant Choice” on page 12-60
“Empty Variant Choice” on page 12-60
“List of Variant Choices” on page 12-61
“Open Active Variant” on page 12-61

Each variant choice in your model is associated with a conditional expression called variant control.
The way you specify your variant controls determines the active variant choice. The Variant control
mode parameter available in the block parameters dialog box allows you to select Expression or
Label mode for modeling Variant blocks.

This image shows the block parameters dialog box of a Variant Subsystem block that contains four
variant choices:

• The first choice is commented out by adding the % symbol before the variant control.
• The second choice is the (default) and is activated when no variant control evaluates to true.
• The third choice is activated when the expression mode==3 && version==2 evaluates to true.
• The fourth choice is activated when the expression mode==2 && version==1 evaluates to true.

12-59
12 Modeling Variant Systems

Default Variant Choice


You can specify at most one variant choice as the default for the model. As shown in the image above,
the Linear Controller subsystem is defined as the default variant choice. During model
compilation, if Simulink finds that no variant control evaluates to true, it uses the default choice.

In the dialog box, select the variant choice and change its Variant control property to (default).

Active Variant Choice


While each variant choice is associated with a variant control, only one variant control can evaluate
to true at a time. When a variant control evaluates to true, Simulink activates the variant choice
that corresponds to that variant control. At most one variant choice can be active. The active variant
cannot be changed once model is compiled.

In this example, you can activate either the Model variant choice or the Nonlinear Controller
variant choice by specifying appropriate values for mode and version.

Value of mode Value of version Active variant choice


2 1 Nonlinear Controller
3 2 Model

You can specify the values of mode and version at the MATLAB Command Window.

Inactive Variant Choice


When a variant control activates one variant choice, Simulink considers the other variant choices to
be inactive. Simulink ignores inactive variant choices during simulation. However, Simulink continues
to execute block callbacks inside the inactive variant choices.

The color of inactive choices fades by default. You can choose to disable the fading effect by using the
Variant Fading option. The Variant Fading option is available in the Information Overlays menu
on the Debug tab of the Simulink Editor. You can use get_param and set_param commands to view
or change the fading state of inactive choices programmatically. For example,

• get_param('bdroot','VariantFading') % To view the fading state of inactive


choices
• set_param('bdroot','VariantFading','on') % To turn on the fading effect of
inactive choices

Empty Variant Choice


When you are prototyping variant choices, you can create empty Subsystem blocks with no inputs or
outputs inside the Variant Subsystem block. The empty subsystem recreates the situation in which
that subsystem is inactive without the need for completely modeling the variant choice.

For an empty variant choice, you can either specify a variant activation condition or comment out the
variant condition by placing a % symbol before the condition.

If this variant choice is active during simulation, Simulink ignores the empty variant choice. However,
Simulink continues to execute block callbacks inside the empty variant choices.

12-60
Working with Variant Choices

List of Variant Choices


You can get a list of variant choices in a Variant Subsystem block using the read-only parameter
VariantChoices.

varchoices = get_param(gcb, 'VariantChoices');

In this example, the VariantChoices parameter returns the following:

Open Active Variant


When you open a model, variant blocks display the name of the variant that was active the last time
that you saved your model. Use the Variant menu to open the active variant. Right-click the block
and select Variant > Open. Then select the active variant.

Use this command to find the current active choice:

get_param(gcb,'CompiledActiveChoiceControl')

Use this command to find the path to the current active choice:

get_param(gcb,'CompiledActiveChoiceBlock')

Note

• The CompiledActiveChoiceBlock parameter is supported only for the Variant Subsystem


block.
• Active variant cannot be changed once the model is compiled.

See Also

Related Examples
• “Create a Simple Variant Model” on page 12-45

More About
• “Introduction to Variant Controls” on page 12-62
• Variant System Design
• “V-Model for System Development with Simulink Variants” on page 12-243

12-61
12 Modeling Variant Systems

Introduction to Variant Controls


The components of a Simulink model that contain variants are activated or deactivated based on the
variant choice that you select.

Each variant choice in your model is associated with a variant control. Variant controls determine
which variant choice is active. By changing the value of a variant control, you can switch the active
variant choice. While each variant choice is associated with a variant control, only one variant control
can evaluate to true. When a variant control evaluates to true, Simulink activates the variant choice
that corresponds to that variant control.

Suppose you want to simulate a model that represents a vehicle with three possible engine
configurations: 1-cylinder gas, 4-cylinder gas, and 8-cylinder gas. In this scenario, the value of
throttle is an input to the engine that differs for different configurations. You could implement each
engine configuration as a separate subsystem inside the Variant Subsystem block named Engine and
then switch between the subsystems based on the value of EngineType. Similarly, you could use a
variant parameter kv to store multiple values of throttle and then switch between the values based
on the value of nc. For example, if the value of EngineType is 1 and the value of nc is 2, a throttle
value of 20 is provided as an input to the Engine_2_cyl_petrol subsystem during simulation.

In this example:

• Structural variations are controlled by using the variant controls EngineType == 1,


EngineType == 2, and EngineType == 3 in the Variant Subsystem block named Engine. For
more information on how to control structural variations, see “Variant Control Modes in Variant
Blocks” on page 12-64.
• Value variations are controlled by using the variant controls nc == 1 and nc == 2 in the variant
parameter kv. For more information on how to control value variations, see “Variant Control Mode
in Variant Parameters” on page 90-13.

12-62
Introduction to Variant Controls

See Also

Related Examples
• “Use Variant Control Variables in Variant Blocks” on page 12-78
• “Use Variant Control Variables in Variant Parameters” on page 90-18

More About
• “Variant Control Modes in Variant Blocks” on page 12-64
• “Variant Control Mode in Variant Parameters” on page 90-13

12-63
12 Modeling Variant Systems

Variant Control Modes in Variant Blocks


The components of a Simulink model that contain variants are activated or deactivated based on the
variant choice that you select.

Each variant choice in your model is associated with a variant control. Variant controls determine
which variant choice is active. By changing the value of a variant control, you can switch the active
variant choice. While each variant choice is associated with a variant control, only one variant control
can evaluate to true. When a variant control evaluates to true, Simulink activates the variant choice
that corresponds to that variant control. For a simple example, see “Introduction to Variant Controls”
on page 12-62.

Types of Variant Control Modes in Variant Blocks


These are types of variant control modes in Simulink:

• expression — In expression mode, Simulink chooses the active variant based on the
evaluation of the variant conditions. When a condition expression evaluates to true, the
corresponding variant choice becomes active. When a condition expression evaluates to false,
the corresponding variant choice becomes inactive. See “Switch Between Choices Using Condition
Expressions in Variant Blocks” on page 12-65.
• label — In label mode, Simulink chooses the active variant based on the name of the variant.
The variant control is a string and does not require you to create any variable in any workspaces.
See “Switch Between Choices Using Labels in Variant Blocks” on page 12-71.
• sim codegen switching — To automatically switch between the variants for simulation and
code generation workflows without creating any workspace variable, use sim codegen
switching mode. When you simulate a model, Simulink automatically chooses the sim branch as
the active choice. Similarly, when you do a software-in-the-loop (SIL) or processor-In-Loop (PIL)
simulation, generate code, or use external mode, Simulink automatically chooses the codegen
branch. See “Switch Between Choices for Simulation and Code Generation Workflows Without
Using Control Variables in Variant Blocks” on page 12-73.

12-64
Variant Control Modes in Variant Blocks

Switch Between Choices Using Condition Expressions in Variant Blocks


In expression mode, Simulink chooses the active variant based on the evaluation of the variant
conditions. When a condition expression evaluates to true, the corresponding variant choice
becomes active. When a condition expression evaluates to false, the corresponding variant choice
becomes inactive.

You can use the expression type of variant controls in variant blocks and in variant parameters.

Note You can simulate and generate code from the model containing a variant block with Variant
control mode set to expression mode. The generated code can contain active and inactive choices
that are enclosed in preprocessor conditionals #if and #elif, or regular if conditions.

Use expression Type of Variant Control in Variant Blocks

To specify the variant condition expressions in variant blocks:

• Right-click the badge on the variant block, select Block Parameters, and then specify the variant
condition expression in the Variant control expression parameter of the block parameter dialog
box.

Variant control mode: expression

• Use this command.

12-65
12 Modeling Variant Systems

set_param('Model/Controller/Linear Controller',...
'VariantControl', 'VSS_MODE == 1')

In this command, Model/Controller/Linear Controller is the full path of the variant


choice, and VSS_MODE == 1 is the expression associated with the variant choice in the model
Model.

Types of Variant Controls in expression Mode

The variant controls can be:

• Boolean condition expression for rapid prototyping. For example, A == 1, A ~= B, A && B ==


1, and so on.
• A Simulink.VariantExpression object that contains condition expressions for condition
reuse. See “Simulink.VariantExpression Objects for Variant Condition Reuse of Variant Blocks” on
page 12-86.
• A default variant control if none of the choices evaluates to true. You can specify at most one
variant choice as the default for the block. During simulation, if none of the variant controls
evaluate to true, Simulink uses the default variant as the active variant choice. To set a variant
choice as the default, select the (default) keyword in the Variant control expression column
for that choice.

Here, A and B are operands called as variant control variables. +, ==, and && are operators in the
condition expression. The condition expression can contain one or more such variant control
variables and operators. For information on supported types and storage location of variant control
variables, see “Types of Variant Control Variables (Operands) in Variant Blocks” on page 12-66 and
“Storage Locations for Variant Control Variables (Operands) in Variant Blocks” on page 12-67. For
information on operators, see “Types of Operators in Variant Blocks for Different Activation Times” on
page 12-68.

Note You can comment out the variant controls by placing a % symbol before the control expressions.
During simulation, if the corresponding variant choice is active, Simulink ignores the variant choice.
However, Simulink continues to execute block callbacks inside the variant choice.

Types of Variant Control Variables (Operands) in Variant Blocks

In expression mode, you can specify the variant control variables as any of these types, from
options to use while prototyping to options required for generating code from your model.

Specification Purpose Example


Simulink.VariantControl Associate a variant activation A == 1, where A is a
time to switch choices Simulink.VariantControl
coherently object. See
“Simulink.VariantControl
Variables for Coherent
Switching of Choices in Variant
Blocks” on page 12-78.

12-66
Variant Control Modes in Variant Blocks

Specification Purpose Example


Scalar variable Rapid prototyping A == 1, where A is a scalar
variable. See “Scalar Variant
Control Variables for Rapid
Prototyping in Variant Blocks”
on page 12-80.
Simulink.Parameter object Generate preprocessor Vssmode == 1, where
conditionals for code generation Vssmode is a
Simulink.Parameter object.
See “Simulink.Parameter Type
of Variant Control Variables for
Code Generation in Variant
Blocks” on page 12-81.
“Simulink Enumerations” on Improved code readability LEVEL == Level.Advanced,
page 74-2 because condition values are where Level is an integer-
represented as meaningful based enumeration class and
names instead of integers Advanced is the enumerated
value. See “Enumerated Types
To Improve Code Readability of
Variant Control Variables of
Variant Blocks” on page 12-83.
Simulink.Variant object Reuse variant conditions LinearController == 1,
where LinearController is a
Simulink.VariantExpressi
on object that encapsulates the
condition expression FUEL==2
&& EMIS==1. See
“Simulink.VariantExpression
Objects for Variant Condition
Reuse of Variant Blocks” on
page 12-86.

Note A Variant Assembly


Subsystem block does not
support
Simulink.VariantExpressi
on type of variant control
variable.
struct Group related variant control Controller.Linear == 1,
variables where Controller is a struct
and Linear is its field. See
“Structures to Group Related
Variant Control Variables of
Variant Blocks” on page 12-87.

For list of all examples, see “Use Variant Control Variables in Variant Blocks” on page 12-78.

Storage Locations for Variant Control Variables (Operands) in Variant Blocks

You can define the variant control variables in different storage locations based on your requirement.

12-67
12 Modeling Variant Systems

Note

• All the variant control variables in a variant block must originate from the same storage location.
• You can use Simulink.SimulationInput in the base, mask, and model workspace when Variant
activation time is set to startup.

Storage Location Use for Storage Supported Types of For More Information
Location Variant Control
Variables (See “Types
of Variant Control
Variables (Operands)
in Variant Blocks” on
page 12-66)
Base workspace Store variables while Scalar variables, “Temporary Data: Base
you experiment with Simulink.VariantEx Workspace” on page 73-
temporary models pression, 111
Simulink.Parameter,
enumerated type,
Simulink.VariantCo
ntrol, and struct
Mask workspace Permanently store data Scalar variables, “Approaches to Control
that is local to the mask enumerated type, and Active Variant Choice of
of a block. Simulink.VariantCo a Variant Block Using
ntrol Mask or Model
Workspace” on page 12-
178
Model workspace Permanently store data Scalar variables, “Approaches to Control
that is local to a model enumerated type, and Active Variant Choice of
Simulink.VariantCo a Variant Block Using
ntrol Mask or Model
Workspace” on page 12-
178
Data dictionary Permanently store Scalar variables, “What Is a Data
global data, share data Simulink.VariantEx Dictionary?” on page
between models, and pression, 80-2
track changes made to Simulink.Parameter,
data. enumerated type,
Simulink.VariantCo
ntrol, and struct

For capabilities and advantages of each storage location, see “Determine Where to Store Variables
and Objects for Simulink Models” on page 73-109

Types of Operators in Variant Blocks for Different Activation Times

Variant condition expressions can contain MATLAB operators, provided the expression evaluates to a
Boolean value.

In variant blocks, the operators that you can use to form a variant condition expression depends on
the Variant activation time.

12-68
Variant Control Modes in Variant Blocks

When you specify the Variant activation time as:

• update diagram — Any condition expression that evaluates to true or false.


• update diagram analyze all choices or code compile — The supported operators are:

• Parentheses for grouping


• “Arithmetic Operators”, “Relational Operators”, “Logical Operators”, and “Bit-Wise
Operations”, as listed in this table.

This table lists the MATLAB operators and their representation in the generated code. In these
examples, A and B are expressions that evaluate to an integer, and x is a constant integer
literal.

MATLAB Expressions That Support Equivalent Expression in C


Generation of Preprocessor Preprocessor Conditional of Generated
Conditionals Code
Arithmetic
• A + B • A + B
• +A • A
• A - B • A - B
• -A • -A
A * B A * B
idivide(A,B) A / B

If the value of the second operand (B) is 0,


the behavior is undefined.
rem(A,B) A % B

If the value of the second operand (B) is 0,


the behavior is undefined.
Relational
A == B A == B
A ~= B A != B
A < B A < B
A > B A > B
A <= B A <= B
A >= B A >= B
Logical
~A !A, where A is not an integer
A && B A && B
A || B A || B
Bitwise (A and B cannot both be constant integer literals)
bitand(A,B) A & B
bitor(A,B) A | B

12-69
12 Modeling Variant Systems

MATLAB Expressions That Support Equivalent Expression in C


Generation of Preprocessor Preprocessor Conditional of Generated
Conditionals Code
bitxor(A,B) A ^ B
bitcmp(A) ~A
bitshift(A,x) A << x
bitshift(A,-x) A >> x
• startup — The supported operators are:

• Parentheses for grouping


• “Relational Operators” and “Logical Operators”, as listed in this table.

This table lists the MATLAB operators and their representation in the generated code. In these
examples, A and B are expressions that evaluate to an integer.

Supported Operators in Variant Equivalent Expression in Regular if of


Condition Expression Generated Code
Relational
A == B A == B
A ~= B A != B
Logical
~A !A, where A is not an integer
A && B A && B
A || B A || B

Note

• For the variant blocks with any activation time, the variant control variables that originate from
the mask or the model workspace cannot be used in the MATLAB in-built functions such as
idivide, bitand, and so on to form expressions.
• AUTOSAR post-build variants support only == and && operators. For more information, see
“Configure Postbuild Variant Conditions for AUTOSAR Software Components” (AUTOSAR
Blockset).

Evaluate Variant Condition Expressions at Different Variant Activation Times

In expression mode, you can specify if Simulink must evaluate condition expressions during model
compile, simulation-loop, code compile, or model start up stage of simulation and code generation
workflow using variant activation times. For information on stages of simulation and code generation
and supported variant activation times in expression mode, see “Activate Variant During Different
Stages of Simulation and Code Generation Workflow” on page 12-93.

Automatically Identify Variant Regions Using Variant Condition Propagation

Simulink determines the model components that are active during simulation by the process of
variant condition propagation. This process evaluates the variant controls specified on the variant

12-70
Variant Control Modes in Variant Blocks

blocks and automatically propagates the variant conditions to the connecting blocks. Variant
conditions can propagate through signal lines, buses, and function calls to reach other blocks in the
model. The process deactivates the model components associated with the inactive choices and they
do not participate in simulation. You can stop condition propagation to define variant regions in the
model.

You can limit variant condition propagation in a bounded region using the Variant Start and Variant
End blocks. For more information on bounded region, see Variant Start.

You can use the Variant Conditions Legend to visualize the propagated variant conditions that
activate each variant choice. Simulink annotates model components if there are variant conditions on
them, and the Variant Conditions Legend displays the condition that corresponds to each annotation.

For more information, see “Propagate Variant Conditions to Define Variant Regions with Variant
Blocks” on page 12-133.

Switch Between Choices Using Labels in Variant Blocks


In label mode, Simulink chooses the active variant based on the name of the variant. The variant
control is a string and does not require you to create variable in any workspaces.

Note In label mode, the activation time of the variant block is set to update diagram by default.
In other words, when you simulate a model or generate code from a model, Simulink determines the
active choice in the model compilation stage and generates code only for the active choice. See
“Activate Variant During Different Stages of Simulation and Code Generation Workflow” on page 12-
93.

Use label Mode in Variant Blocks

To specify the labels for choices in variant blocks, right-click the badge on the variant block, select
Block Parameters, and then specify the labels in the Variant control label parameter of the block
parameter dialog box.

12-71
12 Modeling Variant Systems

Variant control mode: label

Set Active Choices Using Variant Control Labels

You can follow any of these approaches to set active choices in label mode:

• Specify a name for each variant choice in the Variant control label parameter of the variant
block dialog box. All the names that you specify are listed in the Label mode active choice drop-
down. The label that you select from the list becomes the active choice.
• Right-click the badge on the variant block and select Label Mode Active Choice.
• From the mask workspace using the initialization code. Using the mask initialization code, you can
specify the active choice from variant block or any subsystem in the hierarchy. The active choice
you specify in the mask initialization code overrides the active choice you specify using the Label
mode active choice drop-down or the Label Mode Active Choice menu item. For more
information, see “Mask a Variant Subsystem” on page 43-91.
• Use this command:

set_param(blockName,'LabelModeActiveChoice', 'variantChoiceLabel')

where blockName is the name of the variant block and variantChoiceLabel is the label associated
with the variant choice.

12-72
Variant Control Modes in Variant Blocks

Switch Between Choices for Simulation and Code Generation


Workflows Without Using Control Variables in Variant Blocks
To automatically switch between the choices for simulation and code generation workflows without
creating any workspace variable, use the sim codegen switching variant control mode.

Note In sim codegen switching mode, only the update diagram and the update diagram
analyze all choices activation times are supported. In other words, when you simulate or
generate code from a model, Simulink determines the active choice in the model compilation stage
and generates the code only for the choice. See, “Activate Variant During Different Stages of
Simulation and Code Generation Workflow” on page 12-93.

Use sim codegen switching Mode in Variant Blocks

To specify simulation and code generation branches for variant choices, right-click the badge on the
variant block, select Block Parameters, and then specify the (sim) and (codegen) keywords in
the Variant control switch parameter of the block parameter dialog box.

When you simulate a model in normal, accelerator, or rapid Accelerator mode, Simulink automatically
chooses the (sim) branch as the active choice. Similarly, when you do a software-in-the-loop (SIL),
processor-In-Loop (PIL) simulation or generate code or use external mode, Simulink automatically
chooses the (codegen) branch. The code is generated only for the active choice. Inactive choices are
not included in the generated code. In this mode, you can at most have only two choices in the variant
block.

12-73
12 Modeling Variant Systems

Variant control mode: sim codegen switching

Compare Different Types of Variant Control Modes in Variant Blocks


This table explains the capabilities of different variant control modes to help you choose one that
caters to your requirement.

12-74
Variant Control Modes in Variant Blocks

Variant control mode Capabilities


expression — Simulink chooses the active Use expression mode to:
variant based on the evaluation of the variant
conditions. When a condition expression • Control the active choice from different
evaluates to true, the corresponding variant sources such as base, mask, model workspace,
choice becomes active. When a condition and data dictionary. Each source defines a
expression evaluates to false, the scope of visibility, which allows you to
corresponding variant choice becomes inactive. efficiently set different active choices for
blocks in different scope. For more
information, see “Storage Locations for
Variant Control Variables (Operands) in
Variant Blocks” on page 12-67.
• Set different active choices for multiple
instances of a variant block that belongs to a
custom locked library. For more information,
see “Control Active Choice of Locked Custom
Library Variant Subsystem Using Mask
Parameter” on page 12-192.
• Propagate the state of the underlying blocks
outside of Variant Subsystem to improve the
accuracy of the model and to simplify model
construction. You are not required to manually
compute the variant conditions assigned to
the dependent or connected blocks. For more
information, see “Propagate conditions
outside of variant subsystem”.
• Use “code compile” on page 12-96
activation time to:

• Generate a code that contains active and


inactive choices of the model in C
preprocessor conditionals #if and #elif.
The preprocessor conditionals are
conditionally compiled for the active choice
that you provide as an input to the
compiler. For more information, see
“Compile Code Conditionally for Variations
of Component Represented Using Variant
Block” (Simulink Coder).
• Generate conditionally compiling code for
AUTOSAR targets.
• Identify incorrect model constructs, detect
design errors, and generate test cases for
model coverage of active variants. For
more information, see “Verify and Validate
Variant Models with Code Compile
Activation Time” on page 12-105.
• Use “startup” on page 12-96 activation
time to:

12-75
12 Modeling Variant Systems

Variant control mode Capabilities


• Improve the speed of iterative simulations
and Simulink Test workflows using fast
restart. For more information, see “Run
Iterative Simulations Without Recompiling
Model for Variant Systems Using Fast
Restart” on page 12-118.
• Simulate multiple configurations in parallel
with different active choices in each run.
For more information, see “Simulate
Variant Subsystem with Startup Activation
Using parsim” on page 12-110.
• Identify incorrect model constructs, detect
design errors, and generate test cases for
model coverage of active and inactive
variants. For more information, see “Verify
and Validate Variant Models with Startup
Activation Time” on page 12-124.
• Generate a code that contains active and
inactive choices of the model in regular if
conditions. The if condition is evaluated
and conditionally executed for the active
choice that you provide as an input to the
executable. For more information, see
“Create Standalone Executables with
Variants Using Simulink Compiler” on page
12-235.
• For AUTOSAR variants, include post-build
variation points in ARXML files. For more
information, see “Configure Postbuild
Variant Conditions for AUTOSAR Software
Components” (AUTOSAR Blockset).
label — Simulink chooses the active variant Use label mode to:
based on the name of the variant. The variant
control is a string and does not require you to • Control active choices without creating any
create variable in any workspace. workspace variables.
• Generate code only for active choice in the
model.
sim codegen switching — When you simulate Use sim codegen switching switching mode
a model in normal, accelerator, or rapid to:
Accelerator mode, then Simulink automatically
chooses the sim branch as the active choice. • To automatically switch between the choices
Similarly, when you do a software-in-the-loop for simulation and code generation workflows
(SIL), processor-In-Loop (PIL) simulation or without creating any workspace variables.
generate code or use external mode, Simulink • Generate code only for active choice in the
automatically chooses the codegen branch. model.

12-76
Variant Control Modes in Variant Blocks

Variant Activation Times for Different Variant Control Modes in Variant


Blocks
This table explains the variant activation time supported for different variant control modes in variant
blocks. For information on variant activation times, see “Activate Variant During Different Stages of
Simulation and Code Generation Workflow” on page 12-93.

Variant activation time


Variant blocks Variant update update code compile startup
control mode diagram diagram
analyze all
choices
Variant expression ✓ ✓ ✓ ✓
Subsystem, label ✓ x x x
Variant Model,
Variant Source, sim codegen ✓ ✓ x x
Variant Sink switching
Variant expression ✓ x x x
Connector, label not supported
Manual Variant
Source, Manual sim codegen not supported
Variant Sink switching
Simulink expression ✓ ✓ ✓ x
Function, label not supported
Initialize
Function, Reset sim codegen not supported
Function, and switching
Terminate
Function

See Also

Related Examples
• “Create a Simple Variant Model” on page 12-45
• “Use Variant Control Variables in Variant Blocks” on page 12-78

More About
• “Introduction to Variant Controls” on page 12-62

12-77
12 Modeling Variant Systems

Use Variant Control Variables in Variant Blocks


This topic explains how to use different types of variant control variables in variant blocks.

Consider the slexVariantSubsystems model.

The Controller subsystem block dialog specifies two potential variants Linear Controller and
Nonlinear Controller. Linear Controller and Nonlinear Controller blocks are
associated with variant condition expressions V == 1 and V == 2. Here, V is the variant control
variable that determines the active choice. You can change V to any of these types based on your
requirement.

In this section...
“Simulink.VariantControl Variables for Coherent Switching of Choices in Variant Blocks” on page 12-
78
“Scalar Variant Control Variables for Rapid Prototyping in Variant Blocks” on page 12-80
“Simulink.Parameter Type of Variant Control Variables for Code Generation in Variant Blocks” on
page 12-81
“Enumerated Types To Improve Code Readability of Variant Control Variables of Variant Blocks” on
page 12-83
“Simulink.VariantExpression Objects for Variant Condition Reuse of Variant Blocks” on page 12-86
“Structures to Group Related Variant Control Variables of Variant Blocks” on page 12-87

Simulink.VariantControl Variables for Coherent Switching of Choices in


Variant Blocks

You can associate a variant control variable of type Simulink.VariantControl with a variant
activation time. Simulink.VariantControl variant control variables help you switch variant
elements such as blocks and parameters coherently.

Consider a group of blocks that represents a design choice, with each block having the same variant
control variable of type Simulink.VariantControl. If you set the variant activation time of these
blocks to inherit from Simulink.VariantControl, the blocks inherit the activation time from
the variant control variable. As a result, all the blocks have the same activation time and are
activated simultaneously to generate rational simulation results and valid code.

12-78
Use Variant Control Variables in Variant Blocks

You can define Simulink.VariantControl type of control variables in storage locations as listed in
“Storage Locations for Variant Control Variables (Operands) in Variant Blocks” on page 12-67.

Open the slexVariantSubsystems model.


open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

In the block parameters dialog box of the Controller block:

1. Specify the variant controls, V == 1 and V == 2.


set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'V==1')
set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'V==2')

2. Set Variant activation time to inherit from Simulink.VariantControl to inherit the


activation time from V.
set_param('slexVariantSubsystems/Controller', 'VariantActivationTime', 'inherit from Simulink.Var

In the base workspace, define a Simulink.VariantControl object, V. Set its value to 1, variant
activation time to update diagram, and then simulate the model.
V = Simulink.VariantControl('Value', 1, 'ActivationTime', 'update diagram')

V =
VariantControl with properties:

12-79
12 Modeling Variant Systems

Value: 1
ActivationTime: 'update diagram'

During simulation, the Controller block inherits the update diagram activation time from V and
the Linear Controller block becomes active.

Double-click the Controller block to see the active choice.


sim ('slexVariantSubsystems');

If you change the value of V to 2, the Nonlinear Controller block becomes active during
simulation. You can change the value of V using this command or from Simulink.VariantControl
dialog box.
V.Value = 2;
sim ('slexVariantSubsystems');

If you change the variant activation time of V to update diagram analyze all choices, the
Controller block inherits the update diagram analyze all choices activation time from V.
You can observe the inherited activation time using CompiledVariantActivationTime.
V.ActivationTime = 'update diagram analyze all choices';
sim ('slexVariantSubsystems');
get_param('slexVariantSubsystems/Controller', 'CompiledVariantActivationTime')

ans =
'update diagram analyze all choices'

Scalar Variant Control Variables for Rapid Prototyping in Variant


Blocks

Scalar MATLAB® variant control variables allow you to rapidly prototype variant choices when you
are still building your model. Scalar MATLAB variant control variables help you focus more on
building your variant choices than on developing the expressions that activate those choices.

You can define scalar control variables in storage locations as listed in “Storage Locations for Variant
Control Variables (Operands) in Variant Blocks” on page 12-67.

Open the slexVariantSubsystems model.


open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

12-80
Use Variant Control Variables in Variant Blocks

VSS_MODE = 2

In the block parameters dialog box of the Controller block, specify variant controls in their
simplest form as scalar variables, V == 1 and V == 2.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'V==1')


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'V==2')

In the base workspace, define a variant control variable, V, set its value to 1, and then simulate the
model.

V = 1;

During simulation, the Linear Controller block becomes active. Double-click the Controller
block to see the active choice.

sim ('slexVariantSubsystems');

Similarly, if you change the value of V to 2, the Nonlinear Controller block becomes active
during simulation.

V = 2;
sim ('slexVariantSubsystems');

Simulink.Parameter Type of Variant Control Variables for Code


Generation in Variant Blocks

If you intend to generate code for a model containing variant blocks, specify variant control variables
as Simulink.Parameter objects. Simulink.Parameter objects allow you to specify other
attributes, such as data type and storage class, and control the appearance and placement of variant
control variables in generated code.

12-81
12 Modeling Variant Systems

• You can define a variant control variable of type Simulink.Parameter only in the base
workspace or in a data dictionary. Defining Simulink.Parameter type of variant control
variables in the mask or model workspace is not supported. For more information on storage
locations for variant control variables, see “Storage Locations for Variant Control Variables
(Operands) in Variant Blocks” on page 12-67.
• Simulink.Parameter objects within structures and that have data types other than
Simulink.Bus objects are not supported.

Open the slexVariantSubsystems model.

open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

In the MATLAB Editor, define a Simulink.Parameter object, V and set its value to 1. The parameter
object V uses the custom storage class ImportedExtern to define V in a separate header file
external_params.h. You can further control the appearance and placement of V and prevent
optimizations from eliminating storage for V using the storage class property.

V = Simulink.Parameter;
V.Value = 1;
V.DataType = 'int32';
V.CoderInfo.StorageClass = 'ImportedExtern';
configSet = getActiveConfigSet(gcs);
set_param(configSet,CustomHeaderCode="external_params.h")

Note:

Variant control variables defined as Simulink.Parameter objects can have any of the storage
classes listed in “Storage Classes for Different Variant Activation Times” on page 12-103.

You can also convert a scalar variant control variable into a Simulink.Parameter object. For more
information, see “Convert Variant Control Variables into Simulink.Parameter Objects” on page 12-
220.

Specify the Simulink.Parameter object as the variant control variable in the block parameters
dialog box of the Controller block. Also, change the Variant activation time to code compile.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'V==1')


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'V==2')
set_param('slexVariantSubsystems/Controller', 'VariantActivationTime', 'code compile')

Ensure that the Linear Controller and NonLinear Controller blocks are atomic.

12-82
Use Variant Control Variables in Variant Blocks

set_param('slexVariantSubsystems/Controller/Linear Controller', 'TreatAsAtomicUnit', 'on');


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'TreatAsAtomicUnit', 'on');

During simulation, the Linear Controller block becomes active. Double-click the Controller
block to see the active choice.

sim ('slexVariantSubsystems');

Similarly, if you change the value of V to 2, the Nonlinear Controller block becomes active
during simulation.

V .Value = 2;
sim ('slexVariantSubsystems');

Generate code from the model and observe the code as described in “Use Simulink.Parameter Type of
Variant Control Variables for Code Generation in Variant Blocks” (Simulink Coder).

Enumerated Types To Improve Code Readability of Variant Control


Variables of Variant Blocks

Use enumerated types to give meaningful names to integers used as variant control values. For more
information on enumerated type data, see “Use Enumerated Data in Simulink Models” on page 74-
5.

In the MATLAB® Editor, define the classes that map enumerated values to meaningful names.

Open the slexVariantSubsystems model.

open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

12-83
12 Modeling Variant Systems

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

In the base workspace, define the classes that map enumerated values to meaningful names.

Here, EngType is an integer-based enumeration class that is derived from the built-in data type,
int32. The class has two enumeration values, Linear and NonLinear. These enumerated values
have underlying integer values 0 and 1.

type EngType

classdef EngType < Simulink.IntEnumType


enumeration
Small (1)
Big (2)
end
methods (Static)
function retVal = addClassNameToEnumNames()
% ADDCLASSNAMETOENUMNAMES Specifies whether to add the class name
% as a prefix to enumeration member names in generated code.
% Return true or false.
% If you do not define this method, no prefix is added.
retVal = true;
end
end
end

Specify the enumeration names as variant control variables in the block parameters dialog box of the
Controller block. Also, change the Variant activation time to code compile.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'V==EngType.Sma


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'V==EngType.
set_param('slexVariantSubsystems/Controller', 'VariantActivationTime', 'code compile')

Ensure that the Linear Controller and NonLinear Controller blocks are atomic.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'TreatAsAtomicUnit', 'on');


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'TreatAsAtomicUnit', 'on');

12-84
Use Variant Control Variables in Variant Blocks

Define the variant control variable, V in the base workspace, specify its value as EngType.Small and
then simulate the model.
V = EngType.Small;

During simulation, the Linear Controller block becomes active. Double-click the Controller
block to see the active choice.
sim ('slexVariantSubsystems');

The code that you generate using enumerated types contains the names of the values rather than
integers. Here, values 1 and 2 are represented as EngType_Small and EngType_Big.
% slexVariantSubsystems_types.h
% #ifndef V
% #define V EngType_Small
% #endif
%
% #ifndef DEFINED_TYPEDEF_FOR_EngType_
% #define DEFINED_TYPEDEF_FOR_EngType_
%
% typedef int32_T EngType;
%
% /* enum EngType */
% #define EngType_Small (1) /* Default value */
% #define EngType_Big (2)
% #endif

% slexVariantSubsystems.c
% void slexVariantSubsystems_step(void)
% {
% #if V == EngType_Small
% logic of Linear Controller
% #elif V == EngType_Big
% logic of Nonlinear Controller

12-85
12 Modeling Variant Systems

% #endif
% }

Note that for variant blocks with “startup” on page 12-96 activation time, only enumerations that
are defined using these techniques are supported:

• Using the function Simulink.defineIntEnumType


• By subclassing built-in integer data types int8, int16, int32, uint8, or uint16, or by
subclassing Simulink.IntEnumType

These enumerations are also supported when permanently stored in a Simulink® data dictionary. See
“Enumerations in Data Dictionary” on page 80-13.

Simulink.VariantExpression Objects for Variant Condition Reuse of


Variant Blocks

After identifying the variant values that your model requires, you can construct complex variant
conditions to control the activation of your variant blocks by defining variant conditions as
Simulink.VariantExpression objects. Simulink.VariantExpression objects enable you to
reuse common variant conditions across models and help you encapsulate complex variant condition
expressions.

You can specify the whole of a variant condition expression or only the variant control variable inside
the Condition property of the Simulink.VariantExpression object.

Note:

• You can define a variant control variable of type Simulink.VariantExpression only in the
base workspace or in a data dictionary. Defining variant controls using
Simulink.VariantExpression objects in the mask or model workspace is not supported. For
more information on storage locations for variant control variables, see “Storage Locations for
Variant Control Variables (Operands) in Variant Blocks” on page 12-67.
• Using Simulink.VariantExpression within structures is not supported.

Open the slexVariantSubsystems model.

open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

12-86
Use Variant Control Variables in Variant Blocks

In the MATLAB® Command Window, define variant control expressions in


Simulink.VariantExpression objects.

V_LinearController = Simulink.VariantExpression('V==1');
V_NonLinearController = Simulink.VariantExpression('V==2');

Specify the Simulink.VariantExpression objects as the variant control variables in the block
parameters dialog box of the Controller block.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'V_LinearContro


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'V_NonLinear

Open the Block Parameters dialog box for the Controller block in the model. The Condition
column of the Variant Choices table automatically shows the Boolean conditions that the
Simulink.VariantExpression objects represent.

Set the value of variant control variable V as 1 and simulate the model.

V = 1;
sim('slexVariantSubsystems');

During simulation, the Linear Controller block becomes active. Double-click the Controller
block to see the active choice. Using this approach, you can develop complex variant condition
expressions that are reusable.

Structures to Group Related Variant Control Variables of Variant


Blocks

Use MATLAB® structure elements to group related variant control variables. You can control the
characteristics of structures in the generated code and the placement of structures in memory. For
more information, see struct.

12-87
12 Modeling Variant Systems

Note that you can define a variant control variable of type structure only in the base workspace or in
a data dictionary. Defining the structure type of variant control variables in the mask or model
workspace is not supported. For more information on storage locations for variant control variables,
see “Storage Locations for Variant Control Variables (Operands) in Variant Blocks” on page 12-67.

Open the slexVariantSubsystems model.

open_system('slexVariantSubsystems');

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

In the base workspace, define a structure to store related variant control variables. Add fields to the
structure using dot notation.

Controller.Linear = 1;
Controller.NonLinear = 0;

In the block parameters dialog box of the Controller block, specify variant controls using dot
notation. Also, change the Variant activation time to code compile.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'VariantControl', 'Controller.Lin


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'VariantControl', 'Controller.
set_param('slexVariantSubsystems/Controller', 'VariantActivationTime', 'code compile');

Ensure that the Linear Controller and NonLinear Controller blocks are atomic.

set_param('slexVariantSubsystems/Controller/Linear Controller', 'TreatAsAtomicUnit', 'on');


set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'TreatAsAtomicUnit', 'on');

12-88
Use Variant Control Variables in Variant Blocks

Simulate the model. During simulation, the Linear Controller block becomes active.

sim('slexVariantSubsystems');

Double-click the Controller block to see the active choice.

Now, generate code from the model. For information on how to generate code, see “Generate Code
Using Embedded Coder” (Embedded Coder).

The generated code contains both Linear and Nonlinear choices in the preprocessor conditionals #if
and #elif because of the code compile activation time.

The generated header file slexVariantSubsystems_types.h defines a structure type that has a
random name and initializes the variables Controller_Linear and Controller_NonLinear.

% #ifndef Controller_Linear
% #define Controller_Linear 1
% #endif
%
% #ifndef Controller_NonLinear
% #define Controller_NonLinear 0
% #endif
%
% #ifndef DEFINED_TYPEDEF_FOR_struct_XfS20q0AY2qBc3cwjMQEtF_
% #define DEFINED_TYPEDEF_FOR_struct_XfS20q0AY2qBc3cwjMQEtF_
%
% typedef struct {
% real_T Linear;
% real_T NonLinear;
% } struct_XfS20q0AY2qBc3cwjMQEtF;

The source file slexVariantSubsystems.c defines the logic for Controller_Linear and
Controller_NonLinear choices.

12-89
12 Modeling Variant Systems

% void slexVariantSubsystems_step(void)
% {
% #if Controller_Linear == 1
% logic of Linear Controller
% #elif Controller_NonLinear == 1
% logic of Nonlinear Controller
% #endif
% }

For more information, see “Organize Data into Structures in Generated Code” (Embedded Coder).

See Also

More About
• “Variant Control Modes in Variant Blocks” on page 12-64
• “Introduction to Variant Controls” on page 12-62

12-90
Create Variant Controls Programmatically

Create Variant Controls Programmatically


In this section...
“Create and Export Variant Controls” on page 12-91
“Reuse Variant Conditions” on page 12-91
“Enumerated Types as Variant Controls” on page 12-91

Create and Export Variant Controls


Create control variables, define variant conditions, and export control variables.

1 Create control variables in the base workspace or a data dictionary.


FUEL=2;
EMIS=1;
2 Use the control variables to define the control condition using a
Simulink.VariantExpression object.
LinearController=Simulink.Variant('FUEL==2 && EMIS==1');

Note Before each simulation, define Simulink.VariantExpression objects representing the


variant conditions.
3 If you saved the variables in the base workspace, select the control variables to export in the
workspace. Right-click and click Save As to specify the name of a MAT-file.

Reuse Variant Conditions


If you want to reuse common variant conditions across models, specify variant control conditions
using Simulink.VariantExpression objects.

Reuse Simulink.VariantExpression objects to change the model hierarchy dynamically to reflect


variant conditions by changing the values of the control variables that define the condition
expression.

The example “Simulink.VariantExpression Objects for Variant Condition Reuse of Variant Blocks” on
page 12-86 shows the use of Simulink.Variant objects to define variant control conditions.

Note You must use Simulink.VariantExpression objects to define variant control conditions for
AUTOSAR workflows.

Enumerated Types as Variant Controls


Use enumerated types to give meaningful names to integers used as variant control values.

1 In the MATLAB Editor, define the classes that map enumerated values to meaningful names.
classdef sldemo_mrv_CONTROLLER_TYPE < Simulink.IntEnumType
enumeration
NONLINEAR (1)

12-91
12 Modeling Variant Systems

SECOND_ORDER (2)
end
end

classdef sldemo_mrv_BUILD_TYPE < Simulink.IntEnumType


enumeration
PROTOTYPE (1)
PRODUCTION (2)
end
end
2 Define Simulink.VariantExpression objects for these classes in the base workspace.

VE_NONLINEAR_CONTROLLER = Simulink.VariantExpression...
('E_CTRL==sldemo_mrv_CONTROLLER_TYPE.NONLINEAR')
VE_SECOND_ORDER_CONTROLLER =Simulink.VariantExpression...
('E_CTRL==sldemo_mrv_CONTROLLER_TYPE.SECOND_ORDER')
VE_PROTOTYPE =Simulink.VariantExpression...
('E_CURRENT_BUILD==sldemo_mrv_BUILD_TYPE.PROTOTYPE')
VE_PRODUCTION =Simulink.VariantExpression...
('E_CURRENT_BUILD==sldemo_mrv_BUILD_TYPE.PRODUCTION')

Using enumerated types simplifies the generated code because it contains the names of the
values rather than integers.

See Also

Related Examples
• “Compile Code Conditionally for Variations of Component Represented Using Variant Block”
(Simulink Coder)
• “Create and Activate Variant Configurations” on page 89-10

More About
• “Introduction to Variant Controls” on page 12-62
• Variant System Design

12-92
Activate Variant During Different Stages of Simulation and Code Generation Workflow

Activate Variant During Different Stages of Simulation and


Code Generation Workflow
Using variant activation time, Simulink sets active choices in variant blocks and variant parameters
during different stages of simulation and code generation workflows.

The active choice is set:

• During the model compile stage, or the simulation-loop stage of the simulation workflow.
• During the model compile stage, the code compile stage, or the model startup stage of the code
generation workflow.

See “Stages to Set Active Choices in Variant Blocks and Variant Parameters” on page 12-94.

To set the active choice, Simulink evaluates the variant controls that you specify in the workspace
browser, at the command line, or in the callbacks, such as InitFcn, PreLoadFcn, and
PostLoadFcn. For more information on callbacks, see “Model Callbacks” on page 4-70.

Setting the active choice at intermediate stages improves the speed of simulation and allows you to
reuse the artifacts from the previous run in code generation workflows. It also enables you to analyze
variant choices for incompatibilities, such as datatype and dimension mismatches, prior to simulation
and code generation.

For example, the code that you generate with code compile activation time contains all the choices.
Prior to the code compilation, you can specify the value of the variant control variable. Based on the
value of the variant control variable, Simulink sets the active choice, and the code is conditionally
compiled only for the active choice. You can reuse the same code every time you change the value of
the variant control variable. The code conditionally compiles for the given active choice.

Similarly, the code that you generate with startup activation time also contains all the choices. Prior
to running the executable of the code, you can specify the active choice by changing the value of the
variant control variable. You can reuse the same executable every time you change the value of the
variant control variable. The executable conditionally runs for the given active choice. Additionally,
startup activation time enables you to skip recompilation and directly start simulating the model.

Note Only one choice can be active any given stage of the simulation and code generation workflow.

12-93
12 Modeling Variant Systems

Stages to Set Active Choices in Variant Blocks and Variant Parameters


These tables describe the stages at which Simulink sets the active choice of variant blocks and
variant parameters during simulation and code generation workflow.

Stages of Simulation Description Variant Activation Time


Workflow
model compile This is the first stage of the • “update diagram” on page
simulation workflow. In this 12-95
stage, the block parameter • “update diagram analyze all
expressions and callback choices” on page 12-95
functions of the model are
evaluated, signal attributes,
sample time attributes, and
block execution order is
determined, and the block is
optimized to improve the
simulation speed.
simulation-loop Simulink successively computes “startup” on page 12-96
the states and outputs of the
system at intervals from the
simulation start time to the
finish time.

12-94
Activate Variant During Different Stages of Simulation and Code Generation Workflow

For more information on stages in the simulation workflow, see “Simulation Phases in Dynamic
Systems” on page 3-2.

Stages of Code Generation Description Variant Activation Time


Workflow
model compile This is the first stage of the • “update diagram” on page
simulation workflow. In this 12-95
stage, the block parameter • “update diagram analyze all
expressions and callback choices” on page 12-95
functions of the model are
evaluated, signal attributes,
sample time attributes, and
block execution order is
determined, and the block is
optimized to improve the
simulation speed.
code compile The C code is translated to “code compile” on page 12-96
machine code.
model startup This stage involves initializing “startup” on page 12-96
variables, allocating memory,
and configuring interfaces for
simulation and code generation,
ensuring proper initialization,
and resource allocation before
runtime.

Types of Variant Activation Time in Variant Blocks and Variant


Parameters
Simulink sets the active choice of variant blocks and variant parameters during different stages of
simulation and code generation workflow using these variant activation times:

update diagram

During simulation, Simulink sets and retains the active choice at the start of the model compilation
stage before the signal attributes are propagated to the blocks. The inactive choices are removed
from the simulation workflow. Signal attributes are then propagated only to the active choice, so only
the active choice participates in the subsequent stages of simulation. The signal attributes are not
analyzed for consistency across the model.

The code generation workflow is same as the simulation workflow. Since only active choices are
retained and inactive choices are removed in the model compilation stage, the code that is generated
in the codegen stage contains only the active choice.

For information on how to use the update diagram activation time in variant blocks and in variant
parameters, see “Variant activation time” and “ActivationTime”.

update diagram analyze all choices

During simulation, Simulink propagates signal attributes to all variant choices. The signal attributes
in the choices are analyzed to check if each block can accept the signals connected to its inputs.

12-95
12 Modeling Variant Systems

Simulink then sets and retains the active choice late in the model compilation stage. The inactive
choices are removed from the simulation workflow, so only active choice participates in the
subsequent stages of simulation.

The code generation workflow is same as the simulation workflow. Since only active choices are
retained and inactive choices are removed in the model compilation stage, the code that is generated
in the codegen stage contains only the active choice.

For information on how to use the update diagram analyze all choices activation time in
variant blocks and in variant parameters, see “Variant activation time” and “ActivationTime”.

Note Simulating and generating code for variant blocks with the variant activation time set to
update diagram analyze all choices and that are connected to continuous state blocks is not
supported.

code compile

The simulation workflow is same as update diagram analyze all choices.

During code generation, Simulink propagates signal attributes to all variant choices. The signal
attributes in all the choices are analyzed to check if each block can accept the signals connected to
its inputs. All the choices participate in the codegen stage of the workflow. Thus, the generated code
includes all the choices. In the code, the choices are enclosed in the C preprocessor conditionals #if
and #else.

Simulink sets the active choice only when you compile the code to generate an executable from it. In
other words, when you compile the code, the compiler accepts the active choice as input. The
compiler compiles the preprocessor conditionals for the active choice and generates an executable
for only the active choice. This option does not require you to regenerate the code next time you
specify a different active choice. You generate the code only once, and you can then specify a
different active choice prior to code compile and build the executable for that active choice.

In code compile:

• You must install Simulink Coder to generate code for only active choices in the model.
• You must install Embedded Coder to generate code for active and inactive choices in the model.

Note Simulating and generating code for variant blocks with the variant activation time set to code
compile and that are connected to continuous state blocks is not supported.

For information on how to use the code compile activation time in variant blocks and in variant
parameters, see “Variant activation time” and “Compile Code Conditionally for All Values of Variant
Parameters with Same and Different Dimensions” on page 90-29. For an example on generating
code, see “Compile Code Conditionally for Variations of Component Represented Using Variant Block”
(Simulink Coder).

startup

During simulation, Simulink propagates signal attributes to all variant choices. The signal attributes
in all the choices are analyzed to check if each block can accept the signals connected to its inputs.
Simulink then sets and retains the active choice and removes the inactive choices in the loop

12-96
Activate Variant During Different Stages of Simulation and Code Generation Workflow

initialization phase of simulation-loop stage. Only the active choice participates in the simulation-loop
stage. This option does not require you to compile the model next time you change the active choice.
You compile the model only once, and you can then specify a different active choice prior to the
simulation-loop stage and simulate the model. Simulink successively computes the states and outputs
of the model for that active choice.

During code generation, Simulink propagates signal attributes to all the variants choices. The signal
attributes in all the choices are analyzed to check if each block can accept the signals connected to
its inputs. All the choices participate in the codegen stage of the workflow and hence, the generated
code includes all the choices. In the code, the choices are enclosed in regular if conditions.

Simulink sets the active choice only when you run the executable that is built from the generated
code. In other words, when you run the executable, the central processing unit accepts the active
choice as input. The processor executes the if conditions for the active choice and generates the
output for only the active choice. The advantage of using this option is that you are not required to
regenerate the executable the next time you specify a different active choice. You generate the
executable only once. You can then specify a different active choice prior to running the executable
and then generate the output for that active choice.

In startup, you must install either Simulink Coder or Embedded Coder to generate code for active
and inactive choices in the model.

This list highlights the key capabilities of startup variants. For a comprehensive list of all the
capabilities of startup variants, see “V-Model for System Development with Simulink Variants” on
page 12-243.

• Perform a fast restart simulation on your model and change the active choice prior to the
simulation-loop stage without the need to recompile the model each time. This improves the
Simulink Test workflow with fast restart. For more information, see “Run Iterative Simulations
Without Recompiling Model for Variant Systems Using Fast Restart” on page 12-118, “Simulate
Variant Subsystem with Startup Activation Using parsim” on page 12-110, and “Verify and Validate
Variant Models with Startup Activation Time” on page 12-124.
• Perform an accelerator or rapid accelerator simulation on your models. You can simulate a model
incrementally with different variant configurations by changing the active variant each time
without the need to regenerate code when there are no structural changes in the model. For more
information, see “Simulate Variant Blocks in Accelerator and Rapid Accelerator Modes with
Startup Activation Time” on page 12-116, “Run Executables for Variant Blocks Without
Recompiling Code for Changing Active Choices” (Simulink Coder), and “Run Executable for
Different Variant Parameter Values Without Recompiling Code” on page 90-35.
• Collect and aggregate coverage results from multiple simulations of Variant Subsystem, Variant
Source, and Variant Sink blocks. With activation time set to startup, the coverage report
displays all variant choices, regardless of whether they activate during the simulation. If a variant
is not active during a simulation, the coverage analysis reports 0% coverage for that variant
choice. For more information, see “Model Coverage for Variant Blocks” (Simulink Coverage).
• Simulate and create real-time applications from Simulink models with Variant blocks and run them
on Speedgoat® target computer hardware connected to your physical systems. To create real time
models, you must change the Variants to atomic and set the variant parameter as
Simulink.Parameter. For more information, see “Create Real-Time Applications Using Variants
and Simulink Real-Time” on page 12-229.
• Create standalone executables outside of Simulink with different variant configurations and
simulate the standalone executable by changing the active variant via an input to the executable.

12-97
12 Modeling Variant Systems

For more information see, “Create Standalone Executables with Variants Using Simulink
Compiler” on page 12-235.
• Generate HDL code that contains both active and inactive choices of a Variant Subsystem block. In
the generated HDL code, the variant control variable is a tunable port. You can set the active
choice by providing the value of the variant control variable at the model startup. For more
information, see “Variant Subsystem: Using Variant Subsystems for HDL Code Generation” (HDL
Coder).
• Export and import models with inline variant blocks, and variant subsystems to a standalone
Functional Mock-up Unit (FMU). The Variant activation time of the variant blocks must be set to
startup. You can also import an existing FMU by using the FMU block. For more information,
see “Export and Import Function Mockup Unit (FMU) from Model with Variant Subsystem Blocks”
on page 12-239.
• Simulate and generate code for variant choices of startup variant blocks comprising of continuous
state blocks. For more information, see “Run Executables for Variant Blocks Without Recompiling
Code for Changing Active Choices” (Simulink Coder).

For information on limitations with the startup activation time, see “Known Limitations of startup
variant activation time” on page 12-129.

inherit from Simulink.VariantControl

The variant block inherits the activation time from its variant control variable of type
Simulink.VariantControl. Inheriting the activation time from variant control variables help you
switch variant elements such as blocks and parameters coherently. If a variant block has at least one
variant control variable of type Simulink.VariantControl, then setting the activation time of the
block to inherit from Simulink.VariantControl is recommended, so that the block inherits
the activation time from the variant control variable.

Note If a variant block has multiple variant control variables of type Simulink.VariantControl,
then all those variables must have the same activation time.

For information on how to use the inherit from Simulink.VariantControl activation time in
variant blocks, see “Variant activation time”. For an example, see “Simulink.VariantControl Variables
for Coherent Switching of Choices in Variant Blocks” on page 12-78.

Illustration of Different Variant Activation Times

This figure shows the stages at which Simulink sets the active choice for different variant activation
times.

12-98
Activate Variant During Different Stages of Simulation and Code Generation Workflow

Variant Activation Time for Variant Blocks


This section explains how to specify the variant activation time, the supported variant control modes,
and the variant condition propagation for different activation times in variant blocks.

Use Variant Activation Time in Variant Blocks

This example explains how to specify active choice using variant activation time in variant blocks.

Consider this model. The Variant Subsystem VSS1 has two potential variants, Linear and
Nonlinear. The variant condition expression associated with the Linear is V == 1. The variant
condition expression associated with the Nonlinear is V == 2. On the dialog box of VSS1, the
Variant activation time parameter is specified as code compile.

When you generate code from this model, the generated code contains all variant choices of VSS1. In
the code, the choices are enclosed in the C preprocessor conditional statements #if and #elif.
Before you compile the code to generate an executable, you can specify a value for V as an input to
the compiler. Upon compiling the code, the compiler accepts the value of V to evaluate each
preprocessor conditional statement. Based on the condition that evaluates to true, the compiler sets
the active choice and then generates the executable only for the active choice. For example, if you
provide the input to the compiler as 1, the executable contains only the Linear variant choice.

12-99
12 Modeling Variant Systems

To generate an executable for Nonlinear variant choice, change the input value to compiler to 2 and
recompile the generated code.

Supported Variant Activation Time in Variant Blocks

This section lists the variant activation time supported by each type of variant blocks:

• Hierarchical variant blocks and inline variant blocks

• Variant Subsystem, Variant Model, Variant Source, Variant Sink— The availability of activation
times depends on the type of the variant control mode that you specify for the block. For
information on variant control modes, see “Introduction to Variant Controls” on page 12-62.
• Variant Connector, Manual Variant Source, Manual Variant Sink— The variant activation time is
by default set to update diagram. You cannot set it to any other activation time.
• Event-based variant blocks

• Simulink Function— The block by default inherits the variant activation time from the
corresponding Function Caller block. You can overwrite the inherited activation time to code
compile or to update diagram by selecting or clearing the Generate preprocessor
conditionals parameter on its block parameter dialog box, respectively.
• Initialize Function, Reset Function, and Terminate Function— The variant activation time is by
default set to update diagram. You can change it to code compile by selecting the
Generate preprocessor conditionals parameter on its block parameter box.

12-100
Activate Variant During Different Stages of Simulation and Code Generation Workflow

This table lists the variant activation time supported by variant blocks in different control modes.

Variant activation time


Variant blocks Variant update update code compile startup
control mode diagram diagram
analyze all
choices
Variant expression ✓ ✓ ✓ ✓
Subsystem, label ✓ x x x
Variant Model,
Variant Source, sim codegen ✓ ✓ x x
Variant Sink switching
Variant expression ✓ x x x
Connector, label not supported
Manual Variant
Source, Manual sim codegen not supported
Variant Sink switching
Simulink expression ✓ ✓ ✓ x
Function, label not supported
Initialize
Function, Reset sim codegen not supported
Function, and switching
Terminate
Function

Note The operators that you can use to form a variant condition expression in variant blocks depend
on its variant activation time. See “Types of Operators in Variant Blocks for Different Activation
Times” on page 12-68.

Variant Condition Propagation for Different Activation Times in Variant Blocks

Variant condition propagation allows you to assign condition expressions outside the variant blocks to
the connecting blocks to improve performance. When you propagate conditions outside the Variant
block, the inactive choices do not run during simulation, which can improve performance, particularly
in large models. The propagation of variant condition outside the variant block varies for different
activation times. For information, see “Propagate Variant Conditions to Define Variant Regions
Outside Variant Subsystems” on page 12-140.

Propagating conditions through cascading blocks results in compounding conditions. Simulink does
not support compounding conditions from variant blocks with startup and code compile variant
activation times. For more information, see “Considerations and Limitations for startup Variant
Activation Time” on page 12-130.

Variant Activation Time in Variant Parameters


This section explains how to specify the variant activation time, and the supported variant control
modes in variant parameters.

12-101
12 Modeling Variant Systems

Use Variant Activation Time in Variant parameters

This example explains how to specify active choice using variant activation time in variant
parameters.

Consider this model. The Gain parameter of the Gain block is a variant parameter with its value set
to K. The variable K has two values: 3.5 and 8.5. The Variant activation time of K is specified as
code compile using the Simulink.VariantControl. This setting means that you can specify the
active choice before code compilation starts.

V = Simulink.VariantControl('Value', 1, 'ActivationTime', 'code compile')


K = Simulink.VariantVariable('Choices', {'V==1', 3.5, 'V==2', 8.5})

When you generate code from this model, the generated code contains both active and inactive
choices of K. In the code, the choices are enclosed in the C preprocessor conditional statements #if
and #elif. When you compile this code to generate an executable, the compiler accepts the value of
V as input to evaluate each preprocessor conditional statement. Based on the condition that evaluates
to true, the compiler sets the active choice and then generates the executable only for the active
choice. For example, if you provide the input to the compiler as 1, the executable is built for K set to
3.5.

To generate an executable with K set to 8.5, change the input value to compiler to 2 and compile the
generated code again. You do not need to regenerate the code to generate an executable for different
variant values.

Supported Variant Activation Time in Variant Parameters

This table lists the variant activation times available for variant parameters.

Note The operators that you can use to form a variant condition expression in variant parameters
are listed in “Types of Operators in Variant Parameters” on page 90-15.

Variant control Variant activation time


mode
update diagram update diagram code compile startup
analyze all
choices
expression ✓ ✓ ✓ ✓
label not supported

12-102
Activate Variant During Different Stages of Simulation and Code Generation Workflow

Variant control Variant activation time


mode
sim codegen not supported
switching

Storage Classes for Different Variant Activation Times


When you specify a condition expression to determine the active choice, each variant control variable
of the expression has a storage class associated with it. Use storage classes to control the appearance
and placement of the variant control variables in the generated code. Storage classes also prevent
the optimizations such as elimination of the storage for variant control variables in the generated
code. For more information, see “Choose Storage Class for Controlling Data Representation in
Generated Code” (Simulink Coder).

The variables used in the variant condition expressions must satisfy these criteria to generate code
with Simulink Coder or Embedded Coder.

• The variant control variables in variant condition expressions must have these storage classes.

• This table lists the built-in storage classes supported for different activation times to generate
code using Simulink Coder and Embedded Coder.

Built-in Storage Class Variant activation time


code compile startup
“ExportedGlobal” (Simulink x ✓
Coder)
“Model Default” (Simulink x ✓
Coder)
“ImportedExtern, x ✓
ImportedExternPointer”
(Simulink Coder)
“Auto” (Simulink Coder) x x
• This table lists the custom storage classes supported for different activation times to generate
code using Embedded Coder.

Custom Storage Class Variant activation time


code compile startup
“GetSet” (Embedded Coder) x ✓
“Define, ImportedDefine” ✓ x
(Embedded Coder)
“CompilerFlag” (Embedded ✓ x
Coder)
Const and ConstVolatile. x x
See, “Const, Volatile, and
ConstVolatile” (Embedded
Coder)

12-103
12 Modeling Variant Systems

Custom Storage Class Variant activation time


“Bitfield” (Embedded x ✓
Coder)
“Struct” (Embedded Coder) x ✓
“ExportToFile” (Embedded x ✓
Coder)
“ImportFromFile” x ✓
(Embedded Coder)
Volatile. See, “Const, x ✓
Volatile, and ConstVolatile”
(Embedded Coder)
• If the activation time of a variant control variable is set to startup, then specifying its storage
class to any of these is not supported:

• Storage classes such as Define that generates macros in the code.


• Storage classes such as Const that generates constant qualified variables in the code.
• To use scalar MATLAB variables as variant control variables in variant blocks without any storage
class for code generation, select Tunable as the Default parameter behavior from the Model
Settings under Code Generation > Optimization. This criteria is not applicable to AUTOSAR
post build variants.

For an example on storage classes for variant control variables, see “Use Simulink.Parameter Type of
Variant Control Variables for Code Generation in Variant Blocks” (Simulink Coder).

See Also

More About
• “Options to Represent Variant Parameters in Generated Code” (Embedded Coder)
• “Simulate a Protected Model with Code Compile or Startup Activation Time” on page 12-113

12-104
Verify and Validate Variant Models with Code Compile Activation Time

Verify and Validate Variant Models with Code Compile


Activation Time

This example shows how to verify and validate variant models with code compile variant activation
time using Simulink® Design Verifier™ and Simulink Test™.

Overview of Simulink Design Verifier and Simulink Test

Simulink Design Verifier identifies hidden design errors and detects model constructs that result in
integer overflow, dead logic, array access violations, and division by zero. It also generates test cases
for model coverage. For more information, see “About Systematic Model Verification Using Simulink
Design Verifier” (Simulink Design Verifier).

Simulink Test provides tools for authoring, managing, and executing systematic, simulation-based
tests of models, generated code, and simulated or physical hardware. You can create nonintrusive
test harnesses to isolate the component under test and use the Test Manager to manage and execute
user-defined tests. For more information, see “Functional Testing for Verification” (Simulink Test).

Note: The variant model slexVariantVnVWorkflow used in this example uses the code compile
variant activation time. For such models, Simulink Test analyzes only the active variant choice by
default. You must switch the active variant choice and rerun the tests to analyze all choices. To make
the Simulink Test workflow iterative, you can use the startup variant activation time and run the
test iterations in fast restart. The startup variant with the fast restart workflow allows you to switch
the active variant choice in each iteration without the need to recompile the model to change the
active variant. For an example that shows the Simulink Test workflow with startup variants and fast
restart, see “Verify and Validate Variant Models with Startup Activation Time” on page 12-124.

Explore the Model

Open the model, slexVariantVnVWorkflow.

open_system('slexVariantVnVWorkflow');

12-105
12 Modeling Variant Systems

The model contains a Variant Subsystem block, ComputeTargetSpeed, with two variant choices,
ComputeTargetSpeed_Config1 and ComputeTargetSpeed_Config2. In this example, we use
Simulink Design Verifier to generate test cases that satisfy condition and decision coverage
objectives. The model uses a test harness, slexVariantVnVWorkflow_mdlHarness, created using
Simulink Test and contains requirements based tests for each variant choice. The harness is saved
with the model.

• To launch Simulink Design Verifier and automatically generate test cases for the variant choices in
the model, double-click the SLDV Run button.

• To launch Simulink Test Manager and to view the test suites in the test harness,
slexVariantVnVWorkflow_mdlHarness, double-click the Open Simulink Test Manager
button.

Use Simulink Design Verifier to Generate Test Cases

Simulink Design Verifier analyzes only the active variant choice in a variant model by default. You can
write a MATLAB® script to generate test cases for all variant choices.

To view the configuration parameters associated with Simulink Design Verifier for this model:

• In the Simulink Editor, on the Modeling tab, click Model Settings.


• In the Configuration Parameters dialog box, click Design Verifier in the left side pane. In the
Analysis options section, Mode is set to Test Generation. In the Test Generation category,
Model coverage objectives is set to Condition Decision.

12-106
Verify and Validate Variant Models with Code Compile Activation Time

In the MATLAB Command Window, run the script corresponding to each of these steps. The SLDV
Run button in the model automates the same script.

Step 1: Set the required Simulink Design Verifier options. For information on the options, see
sldvoptions (Simulink Design Verifier).

modelName='slexVariantVnVWorkflow';
open_system(modelName);
%Create a design verification options object for the model.
opts = sldvoptions(modelName);
%Specify the optimization strategy to use when generating test cases.
opts.TestSuiteOptimization = 'Auto';
%Generate and save a Simulink Design Verifier report.
opts.SaveReport='on';
%Create unique reports for each variant choice.
opts.MakeOutputFilesUnique ='on';
%Create a harness model generated by the Simulink Design Verifier analysis.
opts.SaveHarnessModel ='off';
%Specify the analysis mode.
opts.Mode = 'TestGeneration';

Step 2: Set the variant choice for which tests need to be generated, then analyze the model.

%Set the active variant choice to ComputeTargetSpeed_Config1 in the base workspace.


assignin('base','speedConfig',1);
%Specify a file name for the analysis report to indicate the variant choice being analyzed.
opts.ReportFileName = ([modelName 'report_speedConfig1']);
%Track the execution progress from MATLAB command prompt.
disp([newline 'Performing SLDV Run for Model ' modelName ' with variant choice : SpeedConfig 1'])
%Invoke the model update command to activate the variant choice.
set_param(modelName, 'SimulationCommand', 'Update');
%Analyze the model to generate test cases and display messages in the log window.
[status,fileNames] = sldvrun(modelName, opts, true);

12-107
12 Modeling Variant Systems

Step 3: Repeat Step 2 for the variant choice ComputeTargetSpeed_Config2.

assignin('base','speedConfig',2);
opts.ReportFileName = ([modelName 'report_speedConfig2']);
disp([newline 'Performing SLDV Run for Model ' modelName ' with variant choice : SpeedConfig 2'])
set_param(modelName, 'SimulationCommand', 'Update');
[status1,fileNames] = sldvrun(modelName, opts, true);

Step 4: Display the test generation status.

if status & status1


disp('Simulink Design Verifier test generation completed.');
end

After the analysis is complete, the Simulink Design Verifier Results Summary window opens and
shows different ways you can use the results. See “Review Analysis Results” (Simulink Design
Verifier). To export the generated tests to Simulink Test, click Export test cases to Simulink Test.

Use Simulink Test to Execute Tests

You can use Simulink Test to execute user-defined tests or tests imported from Simulink Design
Verifier. To execute the tests and analyze the results, use the Test Manager. Simulink Test analyzes
only the active variant choice by default for variant models that use the code compile variant
activation time. To analyze all variant choices in such models:

1. On the Apps tab, in the Model Verification, Validation, and Test section, click Simulink Test.

2. On the Tests tab, click Simulink Test Manager.

3. Create a test harness with the required test cases and select the harness model in the Test
Manager.

4. Add the variant control variables to a parameter set in the Parameter Overrides section.

5. For each test case, change the value of the variant control variables in the parameter set according
to each variant choice, then re-run the tests.

Note: If your model has variant configurations defined using “Variant Manager for Simulink”, you can
use those configurations when running programmatic tests for both test cases and test iterations
(since R2024a). With this workflow, you do not need to create parameter sets to re-define the variant
control variable values to use with the test cases or test iterations. For an example, see “Run Tests for
Variant Models Using Variant Configurations” on page 89-106.

Explore the test harness model

To see the test suites in the harness model, slexVariantVnVWorkflow_mdlHarness, double-click


the Open Simulink Test Manager button in the model.

• In the test suite CruiseControl_SpeedConfig_1, the active variant choice is set to


ComputeTargetSpeed_Config1. In CruiseControl_SpeedConfig_2, the active choice is set
to ComputeTargetSpeed_Config2.

12-108
Verify and Validate Variant Models with Code Compile Activation Time

• Select a test suite and click Run in the Simulink toolstrip to run the tests. When the test finishes,
click the Results and Artifacts tab in the Test Manager to review the aggregated results and
coverage metrics. See “Perform Functional Testing and Analyze Test Coverage” (Simulink Test).

See Also

• “Analyze a Model” (Simulink Design Verifier)


• “Review Results” (Simulink Design Verifier)
• “Test Harness and Model Relationship” (Simulink Test)
• Simulink Test Manager (Simulink Test)
• “Export Test Cases to Simulink Test” (Simulink Design Verifier)
• “Model Coverage Objectives for Test Generation” (Simulink Design Verifier)

12-109
12 Modeling Variant Systems

Simulate Variant Subsystem with Startup Activation Using


parsim

This example shows how you can simulate a Variant Subsystem with startup activation time using
parsim. You can simulate multiple configurations in parallel with the Variant activation time set to
startup using parsim. Each configuration will have one active variant.

Model

Open the model slexVariantSubsystemsWithParSim. The model contains a variant subsystem


block Controller with two choices Linear Controller and Nonlinear Controller with the
conditions VSS_MODE == 1 and VSS_MODE == 2 respectively. Set the Variant activation time to
startup in the Block Parameters dialog.
open_system('slexVariantSubsystemsWithParSim.slx')

Step 1 - Setup the active variant selection for each variant choice

Setup the active variant selection for each variant choice and set the number of simulations to be
equal to the number of variant choices. In this example model, we have two variant choices.
mdl = 'slexVariantSubsystemsWithParSim';
numSims = 2;
varControl = [1,2];

Step 2 - Create the SimulationInput object

Create the SimulationInput object for each simulation run and set the variant control value for
each run.
in(1:numSims) = Simulink.SimulationInput(mdl);
for idx = 1:numSims
in(idx) = in(idx).setModelParameter('SimulationMode', 'rapid', ...

12-110
Simulate Variant Subsystem with Startup Activation Using parsim

'RapidAcceleratorUpToDateCheck', 'on', ...


'SaveTime', 'on', ...
'SaveOutput', 'on');
in(idx) = in(idx).setVariable('VSS_MODE',varControl(idx));
end

Note: If your model has variant configurations defined using Variant Manager for Simulink®, you can
use the setVariantConfiguration function on the Simulink.SimulationInput object to set
the variant configuration to be applied before simulation. With this workflow, there is no need to
specify the set of variant control values individually using the setVariable method to activate a
specific variant. For an example, see “Run Simulations for Variant Models Using Variant
Configurations” on page 89-104.

Step 3 - Use parsim to simulate the model

Use parsim to simulate the model in parallel for each variant control value.

out = parsim(in, 'ShowProgress', 'on');

[10-Jan-2024 17:59:17] Checking for availability of parallel pool...


Starting parallel pool (parpool) using the 'Processes' profile ...
10-Jan-2024 18:00:30: Job Queued. Waiting for parallel pool job with ID 12 to start ...
Connected to parallel pool with 8 workers.
[10-Jan-2024 18:01:25] Starting Simulink on parallel workers...
[10-Jan-2024 18:02:19] Configuring simulation cache folder on parallel workers...
[10-Jan-2024 18:02:20] Loading model on parallel workers...
[10-Jan-2024 18:02:48] Running simulations...
[10-Jan-2024 18:04:57] Completed 1 of 2 simulation runs
[10-Jan-2024 18:04:57] Completed 2 of 2 simulation runs
[10-Jan-2024 18:04:57] Cleaning up parallel workers...

You can simulate the model using parsim with SetupFcn. This is optional. If you run parsim
without SetupFcn, set the RapidAcceleratorUpToDateCheck to on.

out = parsim(in, 'ShowProgress', 'on', 'SetupFcn', @() slexVariantSubsystemsWithParSim_script_s

The setup script, slexVariantSubsystemsWithParSim_script_setup.m builds the rapid


acceleration target for the model.

Step 4 - Plot the output values

Now plot the results from each run.

for i = 1:numSims
simOut = out(i);
t = simOut.tout;
y = simOut.yout;
plot(t, y)
hold all
end

12-111
12 Modeling Variant Systems

12-112
Simulate a Protected Model with Code Compile or Startup Activation Time

Simulate a Protected Model with Code Compile or Startup


Activation Time

This example shows you how to simulate a protected model in the code compile and startup
variant activation times.

Model

Open the model slexVariantMdlRefCondProp.slx. The model contains two Model blocks, sub1
and sub2. The variant condition V == 1 is propagated to the Model Block sub1. However, the
condition is not propagated to the blocks within sub1. The blocks within sub1 implicitly inherit the
condition. The Model block sub2 propagates the Out variant conditions.

12-113
12 Modeling Variant Systems

Simulate with code compile Activation Time

Before you simulate, protect the Model block sub2. To protect the model reference of sub2, select
the block sub2 and enter this command in the MATLAB Command Window. For more information on
protecting models, see “Protect Models to Conceal Contents” (Simulink Coder).

Simulink.ModelReference.protect(gcb);

When the Variant activation time is set to code compile, changing the active variant for variant
blocks in a protected model is not supported.

Simulate with startup Activation Time

Before you simulate the model with startup activation time, delete the protected model.

delete('slexVariantMdlRefCondProp_sub2.slxp');

Set the Variant activation time of the Variant Sink block in the Model Block sub2 to startup.
Change the variant control to 'W' and change the storage class specification of W to
'ExportedGlobal'.

12-114
Simulate a Protected Model with Code Compile or Startup Activation Time

W = copy(V);
W.CoderInfo.StorageClass = 'ExportedGlobal';

Protect the model and change the active variant to simulate the model. To tune W in the protected
model during simulation,

Simulink.ModelReference.protect(gcb, 'TunableParameters', {'W'})


W.Value = int32(3);

The condition W == 3 is propagated to the Gain6 and Out4.

12-115
12 Modeling Variant Systems

Simulate Variant Blocks in Accelerator and Rapid Accelerator


Modes with Startup Activation Time

This example shows how to simulate Variant Source and Variant Sink blocks in accelerator and rapid
accelerator mode with startup variant activation time.

Both modes enable faster simulation without changing the model itself. The accelerator and rapid
accelerator modes replace the normal interpreted code with compiled target code. Using compiled
code speeds up simulation of many models, especially those where runtime is long compared to the
time associated with compilation and checking to see if the target is up to date. For more information
on accelerator modes, see “How Acceleration Modes Work” on page 38-3.

Combined with the startup variant activation time, simulating in accelerator or rapid accelerator
mode retains all variant choices. Thus incremental simulation does not regenerate code when there
are no structural changes in the model and you only change the variant control value.

Model

Open the model slexVariantSourceAndSinkWithStartup.slx. The Variant Source1 has


conditions X==1 and X==2 for its input ports. The block named Variant Source1 has an update
diagram activation time. X is a variant control variable and is defined in the PostLoadFcn of File ->
Model Properties -> Callbacks. The Sine3 block is active when X==1 is true, and the Sine4 block
is active when X==2 is true.

In the block named Variant Source2 block, the first input port is active when V==1 is true. The
second input port is active when V==2 is true. The Variant Source2 has a startup activation
time.

The block named Variant Sink has the conditions W==1 and W==2 on its output ports. These
conditions are propagated to the connected blocks. The Gain5 block is assigned the condition
W==1.The second output port of the Variant Sink block has the condition W==2. This condition is
propagated to the Out4 block.

Since the Variant Source2 and Variant Sink blocks have a startup activation time, all the
choices are available. You can toggle the active or inactive branch just before simulation.

12-116
Simulate Variant Blocks in Accelerator and Rapid Accelerator Modes with Startup Activation Time

Simulate the Model

Before you run the simulation, set the mode to be either Accelerator or Rapid Accelerator.

sim(slexVariantSourceAndSinkWithStartup);

You can generate code by clicking on Build ERT or Build GRT. The generated code from Embedded
Coder (ERT) or Simulink Coder (GRT) will have regular if conditions. For more information on
generating code with startup activation time, see “Run Executables for Variant Blocks Without
Recompiling Code for Changing Active Choices” (Simulink Coder).

12-117
12 Modeling Variant Systems

Run Iterative Simulations Without Recompiling Model for


Variant Systems Using Fast Restart

This example shows how to run iterative simulations on a fog lamp controller system using fast
restart. The fog lamp controller system can operate in Driver Switch mode or in Sensor Connected
mode. In Driver Switch mode, the driver controls the intensity of the fog lamps. In Sensor Connected
mode, a sensor adjusts the intensity of the fog lamps based on the intensity of ambient light in the
external environment.

When you run iterative simulations on the fog lamp controller system with fast restart enabled,
Simulink does not need to recompile the model each time you simulate the model. Using fast restart,
you compile a model only once. You can then change the control modes or type of fog lamps and
simulate the model again without recompiling the model. For more information on fast restart, see
“How Fast Restart Improves Iterative Simulations” on page 87-2.

Model

Consider the model slexVariantsWithStartup.

The Variant Subsystem block named Controller represents the structural variation. The variant
parameter lightVolt represents the parameter variation in the model.

The Controller subsystem enables you to switch between Sensors Connected and Driver Switch
modes by using the variant control variable CTRL_MODE. Sensors Connected mode is a sensor-based
mode that automatically adjusts the intensity of fog lamps based on the sensor voltage for the varying
intensity of ambient light. The Drivers Switch mode represents driver manually switching the fog
lamps on and off.

The lightVolt parameter contains fog lamp intensities for different types of fog lamps,
LIGHT_TYPE, in Sensor Connected mode. The fog lamp intensities are mapped to the sensor voltage
using the 1-D Lookup Table block.

In this example, the variables CTRL_MODE, LIGHT_TYPE, and lightVolt are defined in the
PreLoadFcn callback. To view or modify the value of these variables, on the Modeling tab, select
Model Settings > Model Properties. On the Callbacks tab, in the Model callback pane, select
PreLoadFcn.

To run iterative simulations using fast restart, the activation time of the Controller block and
lightVolt is set to startup.

Explore Model Inputs and Outputs

The Signal Editor block generates two signal groups Sensor and Driver that are provided as inputs
to the Controller subsystem block.

• In the Sensor signal group, the x-axis represents time in seconds. The y-axis represents the
sensor voltages for varying ambient light intensities in external environment.

• In the Driver signal group, the x-axis represents time in seconds. The y-axis represents the driver
action. 1 indicates that the driver has turned on the fog lamps and 0 indicates that the driver has
turned off the fog lamps.

In this example, the driver turns on the fog lamps for first two seconds. During this time, the output is
a delayed driver switch signal. From two seconds onward, the sensor generates voltages based on the

12-118
Run Iterative Simulations Without Recompiling Model for Variant Systems Using Fast Restart

intensity of the ambient light. The sensor voltage is then provided as an input to the 1-D Lookup Table
block in the Sensor Connected mode. The lookup table then maps the sensor voltages to the fog lamp
intensities in lightVolt. lightVolt has multiple values of fog lamp intensities that vary for
different types of fog lamps, which are represented by LIGHT_TYPE.

The Scope block outputs these parameter values. The time axis is in seconds.

• LightCommand: In the Driver Switch mode, LightCommand is a delayed driver switch signal. The
LightCommand signal is high if the Driver signal is high, and LightCommand is low if the Driver
signal is low. In other words, when the driver turns on the fog lamps, the fog lamps are
illuminated. When the driver turns off the fog lamps, the fog lamps turn dim.

In the Sensor Connected mode, LightCommand is same as SensorOutput, provided the sensor is
working. LightCommand is high if SensorOutput output is high, and LightCommand is low if
SensorOutput is low. LightCommand is independent of the Driver signal. However, LightCommand
honors the Driver signal if the sensor is faulty.

• Driver: 0 indicates that the driver has turned off the fog lamps. 1 indicates that the driver has
turned on the fog lamps.

• SensorFault: A sensor voltage between 0.5 and 5 indicates that the sensor is working correctly
and the SensorFault is 0.

• SensorOutput: Fog lamp intensities correspond to the sensor voltages specified in the 1-D
Lookup Table block.

Iteratively Simulate Fog Lamp Controller System in Driver Switch and Sensor Connected
Modes

To simulate the model in Driver Switch mode, perform these settings:

1. To enable fast restart, on the Simulation tab, in the Simulate section, click Fast Restart.

2. In the MATLAB® Command Window, set CTRL_MODE to 2 to activate the Driver Switch mode.
Check that the activation time of the Controller subsystem is set to startup.

12-119
12 Modeling Variant Systems

CTRL_MODE.Value = int32(2);

3. Run the simulation. Use the Scope block to visualize the results.

In the Driver Switch mode, the fog lamps are turned on and off based on the action performed by the
driver. So, the LightCommand is high when the Driver signal is high and the LightCommand is low
when the Driver signal is low. The sensors are not active in this mode and hence the value of
SensorFault and SensorOutput is 0. For more information, see Model Inputs and Outputs.

sim('slexVariantsWithStartup');
open_system('slexVariantsWithStartup/Scope')

4. Now, simulate the model in Sensor Connected mode by changing the value of CTRL_MODE to 1. The
type of fog lamp, LIGHT_TYPE, is set to LightType.Type1.

CTRL_MODE.Value = int32(1);

5. Run the simulation again. Because fast restart is enabled, Simulink skips compilation and directly
starts simulating the model. With fast restart enabled, recompiling is not required for accurate
results when there is no structural change in the model. Use the Scope block to visualize the results.

LightCommand is high until SensorOutput is high and is independent of the Driver signal. For
more information, see Model Inputs and Outputs.

sim('slexVariantsWithStartup');
open_system('slexVariantsWithStartup/Scope')

12-120
Run Iterative Simulations Without Recompiling Model for Variant Systems Using Fast Restart

Iteratively Simulate Fog Lamp Controller System with Varying Ambient Light in Sensor
Connected Mode

1. To enable fast restart, on the Simulation tab, in the Simulate section, click Fast Restart.

2. In the MATLAB Command Window, set CTRL_MODE to 1 to activate the Sensors Connected mode
and set the value of LIGHT_TYPE to LightType.Type1.

Check that the activation time of lightVolt is set to startup.

CTRL_MODE.Value = int32(1);
LIGHT_TYPE.Value = LightType.Type1;

3. Run the simulation. Use the Scope block to visualize the results.

For the first two seconds, the Driver signal from the Signal Editor block is high, so the
LightCommand signal is also high. From two seconds onward, the sensor is working and generates
SensorOutput based on the sensor voltages from the Signal Editor block. LightCommand is high
until SensorOutput is high and is independent of the Driver signal. For information on how sensor
voltages are mapped to SensorOutput, see Model Inputs and Outputs.

sim('slexVariantsWithStartup');
open_system('slexVariantsWithStartup/Scope')

12-121
12 Modeling Variant Systems

4. Change the value of LIGHT_TYPE to LightType.Type2 and run the simulation again. Because
fast restart is enabled, Simulink skips compilation and immediately starts simulating the model.
Recompiling is not required for accurate results when no structural changes occur in the model.

LIGHT_TYPE.Value = LightType.Type2;

Use the Scope block to visualize the results. For more information, see Model Inputs and Outputs.

sim('slexVariantsWithStartup');
open_system('slexVariantsWithStartup/Scope')

12-122
Run Iterative Simulations Without Recompiling Model for Variant Systems Using Fast Restart

See Also

“Improve Code Readability of Variant Parameters Using Enumerated Types” on page 90-42

12-123
12 Modeling Variant Systems

Verify and Validate Variant Models with Startup Activation


Time

This example shows how to verify and validate variant models with startup variant activation time
using Simulink® Design Verifier™ and test it using Simulink Test™.

Explore Model

Open the model slexStartupVariantVnVWorkflow. The model contains a Variant Subsystem


block, ComputeTargetSpeed, with two variant choices, ComputeTargetSpeed_Config1 and
ComputeTargetSpeed_Config2. In this example, we use Simulink Design Verifier to generate test
cases for models that contain startup variants and run predefined tests cases for the model using
Simulink Test Manager.

• To launch Simulink Design Verifier and automatically generate test cases for the variant choices in
the model, double-click the SLDV Run button.

• To launch the Simulink Test Manager, click the Open Simulink Test Manager button in the
model. The Simulink Test Manager is launched with predefined tests cases for the
slexStartupVariantVnVWorkflow model. To run each parameter set iteratively across the
selected baseline, click Run. Once the test runs successfully, you will notice that the model output
matches the expected output.

12-124
Verify and Validate Variant Models with Startup Activation Time

Use Simulink Design Verifier to Generate Test Cases

Simulink Design Verifier can analyze all variant choices in single analysis run if the activation time is
set to startup. To analyze all variant choices in a single run, the Analyze all Startup Variants
configuration parameter must be enabled. To enable the configuration parameter:

• In the Simulink Editor, on the Modeling tab, click Model Settings.

• In the Configuration Parameters dialog box, click Design Verifier in the left side pane and select
Parameters and Variants. In the Parameters and Variants pane, the Analyze all Startup
Variants parameter is selected by default. If you de-select this parameter, Simulink Design
Verifier analyzes only the active variant of the variant blocks with Variant activation time
parameter set to startup.

In the MATLAB Command Window, run the script corresponding to each of these steps. The SLDV
Run button in the model automates the same script.

Step 1: Set the required Simulink Design Verifier options. For information on the options, see
sldvoptions (Simulink Design Verifier).
modelName='slexStartupVariantVnVWorkflow';
open_system(modelName);
%Create a design verification options object for the model.
opts = sldvoptions(modelName);
%Specify the optimization strategy to use when generating test cases.
opts.TestSuiteOptimization = 'Auto';
%Generate and save a Simulink Design Verifier report.
opts.SaveReport = 'on';
%Create unique reports for each variant choice.
opts.MakeOutputFilesUnique = 'on';

12-125
12 Modeling Variant Systems

%Create a harness model generated by the Simulink Design Verifier analysis.


opts.SaveHarnessModel = 'off';
%Specify the analysis mode.
opts.Mode = 'TestGeneration';
%Display Simulink Design Verifier report.
opts.DisplayReport = 'off';
%Analyze the models for startup Variant.
opts.AnalyzeAllStartupVariants = on ;

Step 2: Set the variant choice for which tests need to be generated, then analyze the model.

%Set the active variant choice to ComputeTargetSpeed_Config1 in the base workspace.


assignin('base','speedConfig',1);
%Specify a file name for the analysis report to indicate the variant choice being analyzed.
opts.ReportFileName = ([modelName 'report_speedConfig1']);
%Track the execution progress from MATLAB command prompt.
disp([newline 'Performing SLDV Run for Model ' modelName ' for all variant choices']);
disp(newline);
%Analyze the model to generate test cases and display messages in the log window.
[status,fileNames] = sldvrun(modelName, opts, true);

Step 3: Repeat Step 2 for the variant choice ComputeTargetSpeed_Config2.

assignin('base','speedConfig',2);
opts.ReportFileName = ([modelName 'report_speedConfig2']);
disp([newline 'Performing SLDV Run for Model ' modelName ' with variant choice : SpeedConfig 2'])
set_param(modelName, 'SimulationCommand', 'Update');
[status1,fileNames] = sldvrun(modelName, opts, true);

Step 4: Display the test generation status.

if status & status1


disp('Simulink Design Verifier test generation completed.');
end

After the analysis is complete, the Simulink Design Verifier Results Summary window opens and
shows different ways you can use the results. See “Review Analysis Results” (Simulink Design
Verifier).For more information about analyzing models with variants using Simulink Design Verifier,
see Analyze all Startup Variants in “Design Verifier Pane: Parameters and Variants” (Simulink Design
Verifier)

Use Simulink Test to Execute Tests

The startup variant with the fast restart workflow allows you to switch the active variant choice in
each iteration without the need to recompile the model to change the active variant. You can create
parameter sets with different variant configurations in fast restart mode to test your systems without
needing to recompile the model. To make the Simulink Test workflow iterative, use the startup variant
activation time and run the test iterations in fast restart.

Start Test Manager

To setup and run the test iterations in Fast restart and compare the model output with the expected
output, follow the steps in this tutorial.

1 Open the model, slexStartupVariantVnVWorkflow.

12-126
Verify and Validate Variant Models with Startup Activation Time

open_system('slexStartupVariantVnVWorkflow');

2 To start Test manager, on the Apps tab, under Model Verification Validation, and Test click on
Simulink Test. On the Tests tab, click Simulink Test Manager.

Associate Model and Test Harness

Test suites contain one or more test cases and the default test case is a baseline test. Create a test
suite and a new baseline test.

1 From the Test Manager toolstrip, select New > Test Suite. Right click on Test Suite to create a
new Baseline Test.

2 Set the test case to use the model. In the above example, the model in use is
slexStartupVariantVnVWorkflow. In Test Manager, under System Under Test, click the Use
current model button.

3 Select the slexStartupVariantVnVWorkflow_mdlHarness from the Harness drop down under


Test Harness.

Create Parameter Sets

Create parameter sets and add the variant control variable with the respective value. Each parameter
set aligns with a specific variant control value. In the above example,there are two parameter sets
corresponding to the variant control expressions speedConfig = 1 and speedConfig = 2. To
override a model parameter,

1 Expand the Parameter Overrides section in the test case and click Add.

2 Click on update diagram to get model parameters.

3 Select the variant control parameter from the list. In the above example, it is speedConfig.

Simulink Test Manager allows iterations in the Iterations section of the test case. The Table
Iterations provide a quick way to add iterations based items in your model or test case. Click on
Auto-generate the iterations. Select the Parameter Set option from the list.

Note: If your model has variant configurations defined using “Variant Manager for Simulink”, you can
use those configurations when running programmatic tests for both test cases and test iterations
(since R2024a). With this workflow, you do not need to create parameter sets to re-define the variant
control variable values to use with the test cases or test iterations. For an example, see “Run Tests for
Variant Models Using Variant Configurations” on page 89-106.

Capture Baseline

When a baseline test case executes, the Test Manager captures signal data from signals in the model
marked for logging and compares them to the baseline data. You can capture the baseline test
outputs in Test Manager as an Excel® file or a MAT-file. Alternatively, you can add an external file to
the test case as the baseline. In the test case under Baseline Criteria, click Capture and select the
option Capture Baselines for Iterations. Specify the path to the iterations. In the above
example,the path to DisengageWithDisable has been specified. Notice that the Baseline gets
populated in the Table Iterations corresponding to each parameter set.

12-127
12 Modeling Variant Systems

Run the Baseline Test

Baseline tests compare the outputs from a simulation against the expected outputs. Ensure you have
selected the Run Test Iterations in Fast Restart in the Table Iterations section. To run each
parameter set iteratively across the selected baseline, click Run.

12-128
Known Limitations of startup variant activation time

Known Limitations of startup variant activation time


The following are currently not supported with startup variant activation time:

• Blocks with Simscape physical connection ports.


• The variant condition expression can contain only "==", "~=", "&&", "||" and "~" operators.
• Simulink.Parameter with custom storage classes having const and macro types are not
supported for ERT based code generation.
• Variant conditions with mix of code compile and startup gets combined during variant activation
during propagation. Variant condition propagation with mix of code compile (#if) and startup
(if) is not supported. Whenever code compile and startup gets combined it results in update
diagram error. For more information, see “Considerations and Limitations for startup Variant
Activation Time” on page 12-130.
• Multi-input variant source with ‘Output function call’ selected to merge function-call signals is
not supported.
• A Variant Subsystem block with startup activation time and more than one variant choice does
not support function-call signals on its outports.
• Variant Manager constraints are not validated when variant control variable values are changed
as part of fast restart workflows for variant blocks with startup activation time. For information
on constraints, see “Define Constraints for Variant Configurations” on page 89-15.

12-129
12 Modeling Variant Systems

Considerations and Limitations for startup Variant Activation


Time

Combining startup and code compile Variant Activation Times in


Variant Conditions

Simulink does not support combining variant conditions with startup and code compile variant
activation times in a model.

Case 1: Variant Source Block with startup Activation Time Connected to a Variant Source
Block with code compile Activation Time

Consider a model with two Variant Source blocks, VS_CC and VS_ST, with the Variant activation
time parameter set to code compile and startup, respectively.

During model compilation, the VS_ST block propagates the variant condition, B==2 to the VS_CC
block. So, the propagated variant condition on the VS_CC block is (A == 1 && B == 2) || (A ==
2 && B == 2), which combines conditions with startup and code compile activation times. This
combination results in a compilation error.

Case 2: Variant Source Block with startup Activation Time Connected to a Variant
Subsystem Block with code compile Activation Time

In this model, a Variant Source block with the Variant activation time parameter set to startup is
connected to a Variant Subsystem block with the Variant activation time parameter set to code
compile. The Propagate conditions outside of variant subsystem and the Allow zero active
variant controls parameters on the Variant Subsystem block are set to on. These settings result in
propagation of conditions that combines startup and code compile activation times and produces
a compilation error.

12-130
Considerations and Limitations for startup Variant Activation Time

Note This constraint is applicable to any Simulink block that supports variant condition propagation.
For example, you cannot combine startup variant conditions with Simulink Function blocks or
Initialize, Reset, and Terminate blocks that have the Generate preprocessor conditionals
parameter set to on. This parameter works similarly to the code compile variant activation time.
For information on condition propagation with different blocks, see “Propagate Variant Conditions
from Variant Blocks Upstream and Downstream” on page 12-135.

The compilation error for this scenario normally indicates the block that caused the error. If the error
message does not indicate the block, then the variant condition that combined startup and code
compile activation times could have propagated to a hidden block that Simulink inserted for internal
use. Such blocks are not visible in the model.

Exception Scenarios That Support Combining Variant Conditions with startup and code
compile Variant Activation Times

These modeling scenarios support combining variant conditions with startup and code compile
activation times:

• Simulink Function blocks that inherit variant conditions from Function Caller blocks in a model.
The variant condition assigned to the Simulink Function block is a logical OR of the variant
conditions propagated to the Function Caller blocks. In such cases, the Function Caller blocks can
have startup and code compile activation times.
• Data Store Memory blocks in a model. These blocks receive a logical OR of the variant conditions
propagated to the corresponding Data Store Read and Data Store Write blocks in the model. The
reader and writer blocks in such models can have startup and code compile activation times.

In this model, the Variant control parameter on the function-call port block in the Simulink Function
block is set to (inherit). The Function Caller blocks, Function Caller A and Function
Caller B, receive variant conditions with code compile and startup activation times from the
connected Variant Source blocks. The Simulink Function block inherits a combination of these variant
conditions. This case does not result in a compilation error.

12-131
12 Modeling Variant Systems

Use of Variant Control Variables with startup Variant Activation Time


in Another Variant Block
You cannot use a variant control variable used in a block with startup activation time in another
variant block with a different activation time.

Consider a model with two variant blocks, VSrc and VSink, with the Variant activation time
parameter set to startup and update diagram, respectively. Both the blocks use the same variant
control variable, A. This results in a compile-time error.

See Also

More About
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133
• “Activate Variant During Different Stages of Simulation and Code Generation Workflow” on page
12-93

12-132
Propagate Variant Conditions to Define Variant Regions with Variant Blocks

Propagate Variant Conditions to Define Variant Regions with


Variant Blocks
Variant condition propagation is the process whereby Simulink determines which model components
are active during simulation. This process evaluates the variant controls specified on the variant
blocks and propagates the conditions of blocks using variant conditions. Variant conditions can
propagate through signal lines, buses, and function calls to reach other blocks in the model. This
process deactivates the model components associated with the inactive choices, and they are not
included in the simulation. You can control the condition propagation to define the variant regions in
the model. Simulink uses the variant activation time to determine when it chooses the active variant
choice. For more information on variant activation time, see “Activate Variant During Different Stages
of Simulation and Code Generation Workflow” on page 12-93.

Propagating the conditions of the blocks can:

• Improve the accuracy of the model and avoid the manual computation of variant conditions. By
propagating block conditions, you can ensure that each block is always in the correct state, and
that the state is consistent across the entire model. This approach also makes it easier to modify
and maintain your model over time, as you don't have to manually assign variant conditions to
every dependent block. Instead, you can rely on the propagation mechanism to automatically
manage the block states.
• Reduce the computational load of your model and improve its performance. By using variant
condition propagation, you can turn off the execution of blocks that are not currently active.
Deactivating inactive components can help you manage the complexity of your model and make it
easier to navigate.

Visualize Propagated Variant Conditions in Variant Conditions Legend

You can use the Variant Conditions Legend to visualize the propagated variant conditions that
activate each variant choice. Simulink annotates model components if there are variant conditions on
them, and the Variant Conditions Legend displays the condition that corresponds to each annotation.

Consider this model containing multiple variant choices feeding into the Variant Source blocks. A
specific variant condition activates each variant choice.

12-133
12 Modeling Variant Systems

To view the Variant Conditions Legend, on the Debug tab, select Information Overlays > Variant
Legend. If Variant Legend is not available, on the Debug tab, select Information Overlays >
Variant Conditions. Alternatively, to view the Variant Condition Legend programmatically, use the
variantLegend function in the MATLAB Command Window.

Note Variant Conditions Legend does not display the variant conditions for variant parameters. Use
the Variant Parameters tab in the Variant Manager window to view the values and variant
conditions for choices of variant parameters.

By default, the Variant Conditions Legend displays these fields:

• Annotation — Annotations for the variant conditions on the blocks. The variant conditions are
annotated as v:C, where v is the variant semantic indicator and C represents the variant condition
index. You can click through the hyperlinked variant annotations to observe which parts of the
model the variant condition corresponds to. For example, if you click v:1, the parts of the model
that have the variant condition V == 1 are highlighted.
• Simulation — Computed variant conditions on the blocks.
• Workspace — Source of variant control variables in variant blocks. The variables can originate
from a mask, a model, or a base workspace. All the variables used in a block must originate from a
single source. If variables in a model come from different mask workspaces, they can share the
same name, but their values must be different. To observe the source of the variables, click the
hyperlinked workspaces. For more information, see “Storage Locations for Variant Control
Variables (Operands) in Variant Blocks” on page 12-67.

Note When you set the Variant activation time parameter to update diagram, the inactive
choices are removed prior to the propagation of the signal attributes and are therefore not

12-134
Propagate Variant Conditions to Define Variant Regions with Variant Blocks

evaluated. As a result, the source of variables displayed for the inactive choices may be
inaccurate.

To view the variant condition in the generated code, select Show generated code conditions.

When you pause on a block that has a variant condition, the tooltip displays the variant annotation
and the related variant condition for the block. To view the variant condition annotation tooltip, you
must select the Variant Condition option.

Variant condition annotations have these properties:

• There are no annotations on unconditional blocks.


• To reduce clutter, the legend displays only the final computed variant conditions. For example, if
you enter a variant condition in a Variant Source block, that variant condition appears in the
annotations only when you apply your changes.
• The variant conditions in the legend are sorted alphabetically.
• A variant condition is set to false if the blocks associated with that variant condition are never
active.

For example, the Inport4 block is connected to the Variant Source1 block, whose variant
condition is V == 1. Variant Source1 is connected to the Variant Source2 block, which
activates Variant Source1 only when V == 4. Therefore, Inport4 can only be active when V
== 1 && V == 4, a condition that is always false.
• The (default) variant condition is displayed as a negated condition. For example, the default
choice of the Variant Source2 block Inport3 has a negated condition W ~= 1. During
simulation, if none of the inputs to Variant Source2 is active, the default choice Inport3
becomes active. For more information of default choices, see “Default Variant Choice” on page 12-
60.

Propagate Variant Conditions from Variant Blocks Upstream and


Downstream
You can expand the variability control to any region of your model by automatically propagating
variant conditions from variant blocks to other blocks upstream and downstream. Variant conditions
can propagate through signal lines, buses, and function calls to reach blocks in a model affected by
variant selection. For information on how variant conditions are constructed, see “Assemble Variant
Conditions Propagated from Variant Blocks” on page 12-137.

Note When variant control variables are defined within a mask or model workspace, the variant
conditions that contain these variables are limited to the scope of that workspace and do not
propagate beyond it. For more information, see “Approaches to Control Active Variant Choice of a
Variant Block Using Mask or Model Workspace” on page 12-178.

This table lists the examples that explain how variant condition propagation works with different
model components.

12-135
12 Modeling Variant Systems

Example Goal
“Propagate Variant Conditions to Define Variant Propagate the states of the underlying blocks
Regions Outside Variant Subsystems” on page 12- outside of the parent variant block.
140
“Propagate Variant Conditions to Define Variant Propagate the states of the variant blocks to all
Regions Using Variant Source and Variant Sink their connected blocks.
Blocks” on page 12-150
“Variant Elements Within Buses” on page 12-155 Reduce visual complexity by propagating variant
conditions in composite signals.
“Propagate Variant Conditions to Define Variant Conditionally execute subsystem blocks using
Regions in Virtual and Nonvirtual Subsystems” on variant blocks.
page 12-157
“Propagate Variant Conditions to Control Conditionally provide input signals to conditional
Execution of Conditional Subsystems” on page subsystems using variant blocks.
12-162
“Propagate Variant Conditions to Enable or Conditionally execute referenced models or
Disable Model or Subsystem References in subsystems using variant blocks.
Hierarchy” on page 12-170
“Conditionally Execute Custom Initialize, Conditionally execute custom model initialize,
Reinitialize, Reset, and Terminate Routines” on reset, and terminate routines using variant
page 12-173 blocks.
“Conditionally Execute Simulink Functions” on Conditionally execute Simulink functions
page 12-176 (analogous to functions in a procedural
programming language) using variant blocks.
Stop propagating variant conditions upstream
and downstream.

Limitations
Signals from variant blocks to a Mux, Demux, or Vector Concatenate block must have the same
variant condition.

See Also

More About
• “Using Variant Connectors to Implement Variations in Physical Networks” (Simscape)

12-136
Assemble Variant Conditions Propagated from Variant Blocks

Assemble Variant Conditions Propagated from Variant Blocks


During simulation, Simulink propagates the variant conditions specified on the variant blocks to the
connecting blocks. The variant conditions propagated from multiple variant blocks are combined
using the AND (&&) and OR (||) operators.

Cross-Coupling of Inputs and Outputs


In this model, the Variant Source block has two inputs with variant conditions Var == 1 and Var ==
2, respectively. The first input to the Variant Source block branches into its second input before
connecting to the block and are active when Var == 1 or Var == 2 evaluates to true.

During simulation, this model exhibits three modes of operation:

Variant Condition Active Choice


Var == 1 First input of Variant Source
Var == 1 || Var == 2 Second input of Variant Source and the branch of the first
input
Var == 2 Second input of Variant Source

Cascading Blocks and Compounding Conditions


In this model, Variant Source A and Variant Source B are two Variant Source blocks, each fed
by two input ports and connected in a cascading manner. The inputs to Variant Source A are
active when VarA == 1 or VarA == 2. The output of Variant Source A branches into one of the
inputs of Variant Source B. The inputs to Variant Source B are active when VarB == 1 or
VarB == 2 evaluates to true.

12-137
12 Modeling Variant Systems

During simulation, this model exhibits eight modes of operation:

Variant Condition Active Choice


VarA == 1 && VarB == 1 First inputs of Variant Source A and Variant Source
B
VarA == 1 && VarB == 2 First input of Variant Source A and the second input of
Variant Source B
VarA == 2 && VarB == 1 Second input of Variant Source A and the first input of
Variant Source B
VarA == 2 && VarB == 2 Second inputs of Variant Source A and Variant
Source B
VarA == 1 && VarB != (1,2) First input of Variant Source A
VarA == 2 && VarB != (1,2) Second input of Variant Source B
VarA != (1,2) && VarB == 1 None
VarA != (1,2) && VarB == 2 Second input of Variant Source B
VarA != (1,2) && VarB != (1,2) None

Hierarchical Nesting of Blocks


In this model, multiple Variant Source blocks are used to create hierarchical nesting of variant
choices and provide variations on sensor inputs. Multiple choices for sensors are first grouped by
series: A Series, B Series, and C Series. The Variant Source block, Device Model, selects a
sensor from one of the series. The Vendor block then chooses from the sensor choices provided by
Device Model and X Sensor .

Simulink propagates complex variant control conditions to determine which model components are
active during compilation.

12-138
Assemble Variant Conditions Propagated from Variant Blocks

12-139
12 Modeling Variant Systems

Propagate Variant Conditions to Define Variant Regions


Outside Variant Subsystems
Simulink propagates variant conditions from Variant Subsystem blocks to their connecting blocks.
The propagation of variant conditions enables Simulink to determine which components of the model
remain active during simulation. Simulink then deactivates the model components associated with
the inactive choices and highlights the active connections. By default, variant conditions do not
propagate outside the Variant Subsystem block. To allow variant conditions to propagate to the
connecting blocks, select the Propagate conditions outside of variant subsystem parameter on
the Variant Subsystem block. For more information about the Variant Subsystem block, see Variant
Subsystem, Variant Model, Variant Assembly Subsystem.

Tip Variant condition annotations on model components help you visualize the propagated
conditions. To view the annotations, on the Debug tab, select Information Overlays > Variant
Legend. If Variant Legend is not available, on the Debug tab, select Information Overlays >
Variant Conditions. For more information, see “Visualize Propagated Variant Conditions in Variant
Conditions Legend” on page 12-133.

Factors That Affect Propagation of Variant Conditions Outside of


Variant Subsystem Blocks
The propagation of variant conditions outside of a Variant Subsystem block depends on the variant
activation time of the block and the interface of the underlying variant choices. The Variant
activation time parameter determines if Simulink must analyze only the active choice or both active
and inactive choices of the block when simulating the model. If the interface of the analyzed variant
choices matches the interface of the Variant Subsystem block, the variant conditions do not
propagate outside the Variant Subsystem block. In other words, if the analyzed variant choices use all
the input and the output signals of the Variant Subsystem block, the variant conditions do not

12-140
Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems

propagate outside of the block. The variant conditions propagate outside of the Variant Subsystem
block only if the interfaces do not match.

Adaptive Interface for Variant Subsystems

This example shows how propagating variant conditions outside a Variant Subsystem block enables
the block to adapt its interface according to the states of the underlying blocks for different activation
times. The example also explains the code that is generated for different activation times. For
information on factors that affect the propagation, see “Factors That Affect Propagation of Variant
Conditions Outside of Variant Subsystem Blocks” on page 12-140.

Consider the slexVariantSubsystemsAdaptiveInterface model containing a Variant


Subsystem block named Controller with two variant choices, Linear and Nonlinear. The
Linear controller is active when V == 1, and the Nonlinear controller is active when V == 2. V is
a variant control variable and is defined in the PreLoadFcn callback of the model.

To change the value of the variant control variable, in the MATLAB™ Command Window, type V = 1
or V = 2.

Double-click the Controller block to view its contents. The Linear and Nonlinear controller
blocks do not have the same interface. The inports sensor1 and sensor3 are used in Linear
controller and Nonlinear controller blocks, but sensor2 is used only in Linear controller block.
Hence, the sensor2 block is active only when the Linear controller is active and is not executed
when the Nonlinear controller is active. To make the model components outside the Controller
block aware of the active or inactive state of blocks within the Controller block, the block variant
conditions must propagate outside the boundaries of the block. To propagate the variant conditions
outside of the Controller block, select Propagate conditions outside of variant subsystem in
the Block Parameters dialog box of the block. By default, this parameter is set to off.

12-141
12 Modeling Variant Systems

To simulate the model and generate code for Linear and Nonlinear controllers, perform these
steps:

1. In the Block Parameters dialog box of the Controller block, set an activation time in the Variant
activation time parameter.

2. To activate the Linear controller and its connected blocks, change the value of V to 1.

3. Simulate the model and observe the propagated conditions as described in “Propagation with
Different Activation Times” on page 12-142.

4. Generate code from the model by using Embedded Coder®. For information on how to generate
the code, see “Generate Code Using Embedded Coder” (Embedded Coder). Observe the results as
described in “Propagation with Different Activation Times” on page 12-142.

Note

In the model, the saturate port is an unconnected output port and so it is not included in the
generated code for any variant activation times.

5. Similarly, to activate the Nonlinear controller and its connected blocks, change the value of V to 2
and simulate the model. Generate code from the model and observe the results.

Propagation with Different Activation Times


This section explains the simulation results and the code generated for Linear and Nonlinear
controllers with different activation times.

Propagate Variant Conditions for update diagram Activation Time

This table compares the propagation of variant conditions and the generated code for the Linear
and Nonlinear controller choices for update diagram activation time.

12-142
Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems

When V == 1 and Linear controller is active When V == 2 and Nonlinear controller is


active
• Only the Linear controller is analyzed. • Only the Nonlinear controller is analyzed.
• The Linear controller uses only the • The Nonlinear controller uses all the input
sensor1, sensor3 and u ports, so these and output ports of the Controller
ports and their connected blocks are active. subsystem block, so all the input ports,
The Linear controller does not use the sensor1, sensor2, and sensor3, and all
sensor2 and saturate ports, so these ports their connected blocks are active. Also, both
and their connected blocks are inactive. Since output ports, u and saturate, and all their
the interface of the Linear controller is connected blocks are active. Because the
different from the interface of the interface of the Nonlinear controller
Controller subsystem, the variant matches the interface of the Controller
conditions are propagated outside of the subsystem, the variant conditions do not
subsystem. The variant conditions are propagate outside of the Controller
propagated only to the ports that are not used subsystem block.
by at least one of the variant choices. In this
example, the variant annotation v:2 with
condition set to false propagates to
sensor2, saturate, and all their connected
blocks. In the Variant Conditions Legend, a
variant condition is set to false if the blocks
associated with that variant condition are
never active.

• The code that you generate contains only the


active ports. In this example, all the input and
the output ports are active and so they are
part of the generated code.

//slexVariantSubsystemsAdaptiveInterface.h
/* External inputs (root inport signals with defau
typedef struct {
real_T In1; /* '<Root>/
• The code that you generate contains only the real_T In2; /* '<Root>/
active ports. In this example, the input port real_T In3; /* '<Root>/
In2 is inactive, so it is not part of the } ExternalInputs;
generated code.
/* External outputs (root outports with default st
//slexVariantSubsystemsAdaptiveInterface.h typedef struct {
/* External inputs (root inport signals with default
real_T u; storage) */ /* '<Root>/u'
typedef struct { } ExternalOutputs;
real_T In1; /* '<Root>/In1' */
real_T In3; The active choice
/* '<Root>/In3' */ is unconditional. The
} ExternalInputs; unconditional statements are not enclosed in
any conditional statements and are compiled
/* External outputs (root outports with default storage)
or executed */
irrespective of the state of the
typedef struct {
variant choices.
real_T u; /* '<Root>/u' */
} ExternalOutputs; /* Model step function */
void step(void)
The active choice is unconditional. The {
unconditional statements are not enclosed in // Logic for Nonlinear choice
any conditional statements and are compiled }

12-143
12 Modeling Variant Systems

When V == 1 and Linear controller is active When V == 2 and Nonlinear controller is


active
or executed irrespective of the state of the /* Model initialize function */
variant choices. void initialize(void)
{
//slexVariantSubsystemsAdaptiveInterface.c /* (no initialization code required) */
/* Model step function */ }
void step(void)
{
// Logic for Linear choice
}
/* Model initialize function */
void initialize(void)
{
/* (no initialization code required) */
}

Note When propagating the variant conditions outside of a Variant Subsystem with update
diagram activation time:

• If you set Allow zero active variant controls to on, Simulink propagates the variant conditions
to all the blocks (including the unconditional or always true blocks) of the variant region.
Propagating conditions to all the blocks of the variant region enables Simulink to completely
remove the variant region from the model when none of the variant choices are active.
• The code that you generate is the same regardless of the setting of Allow zero active variant
controls.

Propagate Variant Conditions for update diagram analyze all choices Activation Time

This table compares the propagation of variant conditions for the Linear and Nonlinear controller
choices with update diagram analyze all choices activation time. The generated code is the
same as update diagram.

12-144
Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems

When V == 1 and Linear controller is active When V == 2 and Nonlinear controller is


active
• The Linear controller and Nonlinear • The Linear controller and Nonlinear
controller choices are analyzed. controller choices are analyzed.
• The Linear controller uses only the • The Nonlinear controller uses all the input
sensor1, sensor3 and u ports, so these and output ports of the Controller
ports and their connected blocks are active. subsystem, so all the input ports, sensor1,
The Linear controller does not use sensor2 sensor2, and sensor3, and all their
and saturate ports, so these ports and their connected blocks are active. Also, both output
connected blocks are inactive. ports, u and saturate, and all their
• Since the interface of the Linear controller connected blocks are active.
does not match the interface of the • Since the interface of the Linear controller
Controller subsystem, the variant does not match the interface of the
conditions propagate outside of the Controller subsystem, the variant
Controller subsystem block. The variant conditions propagate outside of the
conditions propagate only to the ports that are Controller subsystem block. The variant
not used by at least one of the variant choices. conditions propagate only to the ports that are
In this example, the variant with annotation not used by at least one of the variant choices.
v:1 and with variant condition set to V == 2 In this example, the variant with annotation
propagates to the sensor2, saturate, and v:1 and with variant condition set to V == 2
their connected blocks. propagates to sensor2, saturate, and their
connected blocks.

Note When propagating variant conditions outside of a Variant Subsystem with update diagram
analyze all choices activation time:

• If you set Allow zero active variant controls to on, Simulink propagates the variant conditions
to the all the blocks (including the always trueor unconditional blocks) of the variant region.
Propagating conditions to all the blocks of the variant region enables Simulink to completely
remove the variant region from the model when none of the variant choices are active.
• The code that you generate is the same regardless of the setting of Allow zero active variant
controls.

Propagate Variant Conditions for code compile Activation Time

The propagation of variant conditions for Linear and Nonlinear controller choices with code
compile activation time is the same as propagation with update diagram analyze all
choices. The code that is generated for the Linear and Nonlinear controllers is as shown.

12-145
12 Modeling Variant Systems

The code contains Linear and Nonlinear choices enclosed in necessary preprocessor conditionals
#if and #elif.

//slexVariantSubsystemsAdaptiveInterface.c
/* Model step function */
void step(void)
{
#if V == 1
// Logic for Linear choice
#elif V == 2
// Logic for Nonlinear choice
}
/* Model initialize function */
void initialize(void)
{
/* (no initialization code required) */
}

The port sensor2, which is not used by all the variant choices, is also enclosed in preprocessor
conditional #if.

//slexVariantSubsystemsAdaptiveInterface.h
External inputs (root inport signals with default storage)*/
typedef struct {
real_T In1; /* '<Root>/In1' */

#if V == 2
real_T In2; /* '<Root>/In2' */

#define EXTERNALINPUTS_VARIANT_EXISTS
#endif

real_T In3; /* '<Root>/In3' */


} ExternalInputs;
// External outputs (root outports fed by
// signals with default storage)
typedef struct {
real_T u;
} ExternalOutputs;

Note When propagating variant conditions outside of a Variant Subsystem block with the code
compile activation time, if you set Allow zero active variant controls to on, Simulink propagates
the variant conditions to all the blocks (including the always true or unconditional blocks) of the
variant region. In the generated code, the blocks of the variant region are enclosed in an additional
variant condition that is the logical OR of conditions from the variant choices. This enables Simulink
to remove the variant regions completely from the model when none of the variant choices are active.
In this example, the always true blocks In1 and In3, and the variant choices Linear and
Nonlinear are enclosed in the logical OR of variant conditions, V == 1 || V == 2. When V == 1
and V == 2 each evaluate to false, Simulink skips the compilation of these blocks thus removing
the variant regions completely.

12-146
Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems

Propagate Variant Conditions for startup Activation Time

The propagation of variant conditions for the Linear and Nonlinear controller choices with
startup activation time is the same as propagation with update diagram analyze all
choices activation time.

The code that is generated for the Linear and Nonlinear controllers is as shown.

The code contains Linear and Nonlinear choices enclosed in regular if and else if conditions.
//slexVariantSubsystemsAdaptiveInterface.c
/* Model step function */
void step(void)
{
if (V == 1)
// Logic for Linear choice
else if (V == 2)
// Logic for Nonlinear choice
}
/* Model initialize function */
void initialize(void)
{
startupVariantChecker();
}
static void startupVariantChecker(void)
{
/* startup variant condition checks */
utAssert((rtP.V == 1.0) + (rtP.V == 2.0) == 1);
}

The ports are unconditional.


//slexVariantSubsystemsAdaptiveInterface.h
/* External inputs (root inport signals with default storage) */
typedef struct {
real_T In1; /* '<Root>/In1' */
real_T In2; /* '<Root>/In2' */
real_T In3; /* '<Root>/In3' */
} ExternalInputs;

// External outputs (root outports fed by signals


// with default storage) */
typedef struct {
real_T u; /* '<Root>/u' */
} ExternalOutputs;

Note When propagating variant conditions outside of a Variant Subsystem block with the startup
activation time, if you set Allow zero active variant controls to on, Simulink propagates the variant
conditions to all the blocks (including the always true or unconditional blocks) of the variant region.
In the generated code, the blocks of the variant region are enclosed in an additional variant condition
that is the logical OR of conditions from the variant choices. This enables Simulink to remove the
variant regions completely from the model when none of the variant choices are active. In this
example, the always true blocks In1 and In3, and the variant choices Linear and Nonlinear are
enclosed in the logical OR of variant conditions, V == 1 || V == 2. When V == 1 and V == 2
each evaluate to false, Simulink skips the compilation of these blocks thus removing the variant
regions completely.

12-147
12 Modeling Variant Systems

Propagation Without Inport and Outport Blocks


Consider this model that has a Variant Subsystem block Controller with two variant choices. The
block does not have any inports or outports. The first variant choice has the condition V == 1, while
the second variant choice has the condition W == 1.

In this model, the variant conditions from the Controller block without inports or outports
propagate outside the subsystem in the same way as a Variant Subsystem block with inports and
outports. The activation times and the allowance of zero active variant controls also have the same
impact on condition propagation.

During simulation with these settings, the variant conditions propagate as follows:

• When you set the Propagate conditions outside of variant subsystem parameter to off, no
variant conditions apply to the Controller block. This is because the interface of the
Controller block remain the same regardless of the active choice due to its shared interface
with the choice blocks. When you set the Propagate conditions outside of variant subsystem
parameter to on, the variant condition of the active choice applies to the Controller block so
that the variant condition propagates to the connected blocks, if any. In this example, no blocks
that connected.
• With the Allow zero active variant controls parameter set to on, the variant conditions
propagate to all blocks within the variant region, including unconditional blocks such as the
Controller block in this example, enabling the complete elimination of the variant region when
none of the choices are active.
• Setting the Variant activation time parameter to code compile or startup, adds an
additional variant condition in the generated code that encloses the blocks within the variant
region. In this example, the variant condition is a logical OR of the variant conditions V == 1 and
W == 1.

Limitations
Propagated variant conditions from variant subsystems can be set on Simscape or Stateflow blocks
only for the update diagram variant activation time.

12-148
Propagate Variant Conditions to Define Variant Regions Outside Variant Subsystems

See Also

More About
• “Implement Variations in Separate Hierarchy Using Variant Subsystems” on page 12-48
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133
• “Propagate Variant Conditions to Define Variant Regions Using Variant Source and Variant Sink
Blocks” on page 12-150

12-149
12 Modeling Variant Systems

Propagate Variant Conditions to Define Variant Regions Using


Variant Source and Variant Sink Blocks
Simulink automatically propagates the variant conditions from the Variant Source and Variant Sink
blocks to their connecting blocks. The propagation of variant conditions enables Simulink to
determine which components of the model remain active during simulation. Simulink then
deactivates the model components associated with the inactive choices and highlights the active
connections.

Tip The variant condition annotations on model components help you visualize the propagated
conditions. To view the annotations, on the Debug tab, select Information Overlays > Variant
Legend. If Variant Legend is not available, on the Debug tab, select Information Overlays >
Variant Conditions. For more information, “Visualize Propagated Variant Conditions in Variant
Conditions Legend” on page 12-133.

Variant Source and Variant Sink Blocks

Consider the slexVariantSourceAndSink model containing two Variant Source blocks Variant
Source1 and Variant Source2, and a Variant Sink block. The variant conditions at the inports and
the outports of the Variant Source and the Variant Sink blocks determine the activation and
deactivation of the blocks connected to them. V and W are the variant control variables and are
defined in the PostLoadFcn callback of the model.

open_system("slexVariantSourceAndSink");

12-150
Propagate Variant Conditions to Define Variant Regions Using Variant Source and Variant Sink Blocks

12-151
12 Modeling Variant Systems

When you simulate the model, the variant conditions are propagated as follows:

12-152
Propagate Variant Conditions to Define Variant Regions Using Variant Source and Variant Sink Blocks

• In Variant Source1, when W == 1 evaluates to true, the Sine3 block is active, and when V
== 4 evaluates to true, the Sine4 block is active.
• In Variant Source2, when V == 1 evaluates to true, the Sine1 block is active, and when V
== 2, the Add1 block is active.
• For the Variant Source1 block to be active, the Add1 block must be active. This further
propagates to the Sine3 block and Sine4 blocks, making the Sine3 block active when V == 2
and W == 1 evaluate to true and the Sine4 block active when V == 2 and W == 2 evaluate to
true.
• The Gain3 block is active when V == 1 or V == 2 evaluates to true. The variant condition is
further propagated to Scope1 and Out1.
• The blocks connected to the outport of the Variant Sink block are active when W == 1
(Gain5), or W == 2 (Sine, Subtract, Terminator).
• The Sum block illustrates two key concepts of variant condition propagation: Signals are variant
only if explicitly marked or when all paths can be proven to be variant. For example, the Sine6,
Sum, and Out2 blocks are unconditional. To mark the blocks as conditional, place a single-input,
single-output Variant Source block before Out2 or after Sine6. Reading an inactive signal is
equivalent to reading ground. For example, when W == 1 evaluates to false, the bottom input to
the Sum block is inactive and Out2 = Sine6 + ground.

If you set Allow zero active variant controls of the Variant Sink block to on, Simulink® also
propagates the variant conditions to the unconditional blocks Sine5 and Gain4 of the variant region
also. The variant conditions on Sine5 and Gain4 are the logical OR of the variant conditions, W == 1
and W == 2 of the Variant Sink block. When W == 1 and W == 2 evaluate to false, the condition W
== 1 OR W == 2 evaluates to false, thus making Sine5 and Gain4 inactive. This ensures that

12-153
12 Modeling Variant Systems

Sine5 and Gain4 are removed from simulation and are not left unused when the Variant Sink block
is inactive.

Generate Code for Variant Source and Variant Sink Blocks


For an example on generating code, see “Generate Code for Variant Source and Variant Sink Blocks”
(Simulink Coder).

See Also

More About
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-154
Variant Elements Within Buses

Variant Elements Within Buses

This example explains how to create buses with elements having different variant conditions.

Explore the Model

Open the slexVariantBus model.

open_system("slexVariantBus")

The model consists of two signals, a and b, which are merged to form a bus. These signals have
variant conditions, V == 1 and W == 1 respectively. During simulation, the bus selector receives two
signals with different variant conditions V == 1 and W == 1.

sim("slexVariantBus")

ans =

Simulink.SimulationOutput:

SimulationMetadata: [1x1 Simulink.SimulationMetadata]


ErrorMessage: [0x0 char]

When you select individual signals from the bus using the bus selector, the corresponding variant
condition is also selected. There is no difference in the propagation behavior of variant conditions
when passing through virtual or nonvirtual buses. For more information on buses, see “Explore
Simulink Bus Capabilities”.

12-155
12 Modeling Variant Systems

Generate Code for Variant Buses

A virtual bus does not appear as a structure or any other coherent unit in the generated code. A
separate copy of any algorithm that manipulates the bus exists for each bus element. Whereas, a
nonvirtual bus appears as a structure in the generated code, and only one copy exists of any
algorithm that uses the bus. The use of a structure in the generated code can be helpful when tracing
the correspondence between the model and the code. For more information, see “Generate Code for
Variant Elements Within Buses” (Simulink Coder).

Variant Bus with Model Block

Consider this model containing a Model block.

This model has two signals a and b which have different variant conditions, V == 1 and V == 2. The
Model block feeds the bus selector two signals having two different variant conditions (V == 1 and V
== 2). During simulation, the Model block propagates the variant conditions received from the
referenced model mVarBus_bot at its output ports. The variant condition at each output port is the
logical OR of the variant conditions V == 1 and V == 2 from the variant choices of the
mVarBus_bot model. For more information on variant condition propagation with Model blocks, see
“Propagate Variant Conditions to Enable or Disable Model or Subsystem References in Hierarchy” on
page 12-170.

Known Limitations

States logging of blocks (for example, Unit Delay) that accept buses with inactive elements is not
supported.

See Also

“Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-156
Propagate Variant Conditions to Define Variant Regions in Virtual and Nonvirtual Subsystems

Propagate Variant Conditions to Define Variant Regions in


Virtual and Nonvirtual Subsystems

A Subsystem block can be either a virtual (grouped or ungrouped) or a nonvirtual (atomic) subsystem
depending on the selections made in its Block Parameters dialog box. Using a virtual subsystem as
opposed to a nonvirtual subsystem provides a graphical hierarchy in a model and does not impact the
execution of a model. A nonvirtual subsystem executes as a single unit within a model. For more
information, see Subsystem.

This example shows the propagation of variant conditions from a Variant Source block to Subsystem
blocks. Simulink® propagates variant conditions to these types of subsystems different.

Explore the Model

Open the model slexVariantCondPropToSubsystems.

The model contains three Subsystems: Subsystem1, Subsystem2, and Atomic Subsystem.
Subsystem1 is a grouped virtual subsystem, Subsystem2 is an ungrouped virtual subsystem, and
Atomic Subsystem is a nonvirtual subsystem.

12-157
12 Modeling Variant Systems

12-158
Propagate Variant Conditions to Define Variant Regions in Virtual and Nonvirtual Subsystems

Simulate this model and observe the variant conditions propagated from the Variant Source blocks to
their connecting blocks.

Propagate Variant Conditions to Conditionally Execute Grouped Subsystem Blocks

A grouped subsystem represents a system of equations. A grouped subsystem has a continuous


boundary line. The variant conditions do not propagate inside the grouped subsystem. Instead, they
stay on the boundary. However, all blocks inside that subsystem inherit the variant conditions from
the grouped subsystem. A Subsystem block becomes a grouped subsystem when you select the Treat
as grouped when propagating variant conditions check box in the Block Parameters dialog box.

In this example, the Variant Source2 block has a variant condition V == 1 that propagates to
Subsystem1. Since Subsystem1 is a grouped virtual subsystem, the variant condition stays on the
boundary and applies to the blocks within the subsystem. If Subsystem1 is active, the blocks within

12-159
12 Modeling Variant Systems

Subsystem1 are also active. If Subsystem1 is inactive, the blocks within Subsystem1 are also
inactive, thus making Subsystem1 conditional.

Propagate Variant Conditions to Conditionally Execute Blocks Within Ungrouped Subsystem


Blocks

An ungrouped subsystem does not represent a system of equations. The blocks within it have
ungrouped semantics. An ungrouped subsystem has a dotted boundary line, and the variant
conditions propagate into the subsystem. A Subsystem block becomes an ungrouped subsystem when
you clear the Treat as group when propagating variant conditions check box in the Block
Parameters dialog box.

In this example, the Variant Source2 block has a variant condition V == 1 that propagates to
Subsystem2. Since Subsystem2 is an ungrouped subsystem, the variant condition propagates to the
blocks within the subsystem.

The dotted lines on the Subsystem2 icon indicate that the subsystem is flattened during Simulink
compilation, and hence you can see the variant conditions for the blocks inside it. Due to the
unconditional block To Workspace1, the propagation stops and the condition V == 1 is set only to
the Out1 port.

The To Workspace1 block illustrates a key concept of variant condition propagation: signals are
variant only if explicitly set or when all paths can be proven to be variant. Here, Subsystem2 is
unconditional because all paths within Subsystem2 cannot be proven variant due to the presence of
the To Workspace1 block.

Propagate Variant Conditions to Conditionally Execute Atomic Subsystem Blocks

A nonvirtual (atomic) subsystem always represents a system of equations. Nonvirtual subsystems


always behave like a single entity and its contents execute only when the variant condition assigned
to the subsystem is satisfied. A nonvirtual subsystem has a continuous solid boundary line. The
variant condition propagates the same as in the grouped subsystem blocks as the grouped subsystem
blocks. A Subsystem block becomes a nonvirtual subsystem when you select the Treat as atomic
unit check box in the Block Parameters dialog box.

12-160
Propagate Variant Conditions to Define Variant Regions in Virtual and Nonvirtual Subsystems

In this example, the Variant Source3 block has a variant condition V == 1 that propagates to
Atomic Subsystem. Since Atomic Subsystem is a nonvirtual subsystem, the variant condition
applies to Atomic Subsystem and to all blocks within the subsystem. Like the grouped virtual
subsystem Subsystem1, Atomic Subsystem is conditional.

Note

Since conditional subsystems are nonvirtual subsystems, variant conditions in conditional subsystems
propagate the same as in atomic subsystems. For more information, see “Propagate Variant
Conditions to Control Execution of Conditional Subsystems” on page 12-162.

Net Variant Condition on Subsystems

A Subsystem block can propagate variant conditions from its output port if that variant condition
originates at a port inside the subsystem. The net variant condition is the combination of the local
variant condition and its preceding variant condition. In the slex_netvariant model, Variant
Source and Variant Source1 are two single-input, single-output Variant Source blocks with the
variant conditions V == 1 and W == 1, respectively. When you simulate this model, the Variant
Source1 block and the other blocks within the Subsystem block receive a local variant condition W
== 1 propagated from the Variant Source1 block. The preceding condition V == 1 propagates
from the Variant Source block onto the Subsystem block. Therefore, the net variant condition on
the Variant Source1 block and other blocks within the Subsystem block is V == 1 && W == 1.

See Also

“Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-161
12 Modeling Variant Systems

Propagate Variant Conditions to Control Execution of


Conditional Subsystems
Conditional subsystems such as Enabled, Triggered, Reset, and Function-Call subsystems are
nonvirtual subsystems that allow you to control its execution with external signals. You can control
the execution by conditionally providing the signals to the conditional subsystems using variant
blocks. The variant condition that propagates to the conditional subsystem stays on the boundary of
the subsystem. All blocks inside inherit the condition from the subsystem. The same condition is set
to all the ports of the subsystem.

For more information on conditionally executed systems, see “Conditionally Executed Subsystems
Overview” on page 10-3.

Variant Signals from Variant Source Outport to Function-Call


Subsystem

This example shows how to conditionalize function-call signals to control the execution of a function-
call subsystem using the Variant Source block. The variant condition that propagates to the Function-
Call Subsystem block is set to all the ports of the subsystem.

Explore the Model

Consider the model slexVariantSourceFunctionCall.

The model contains a Variant Source block with the variant conditions A == 1 and A == 2 at its
input ports. A is the variant control variable defined in the PreLoadFcn model callback. The variant
conditions at the input and output ports of the Variant Source block determine the activation and
deactivation of the blocks connected to it.

A Sine Wave block is connected to two MATLAB Function blocks, Filter Positive inputs and
Filter Negative inputs. The Filter Positive inputs block generates a function call when
the value of the Sine Wave block is positive. The Filter Negative inputs block generates a
function call when the Sine Wave block value is 0 or negative. The Variant Source block receives
these function-call signals at its input ports. The output port of the Variant Source block is connected
to a Function-Call Subsystem block named Counter. The subsystem is triggered when A == 1 and
the Sine Wave block outputs positive values, and when A == 2 and the Sine Wave block outputs 0 or
negative values.

The Output function call parameter on the Variant Source1 block is set to on. This option
enables the block to receive and output the function-call signals.

open_system("slexVariantSourceFunctionCall");

12-162
Propagate Variant Conditions to Control Execution of Conditional Subsystems

Simulate the Model

When you simulate the model, the logical OR of variant conditions A == 1 and A == 2 propagates to
the Counter subsystem and all its ports to determine the active and inactive variant choices.

• When A == 1, Filter Positive inputs is active.


• When A == 2, Filter Negative inputs is active.

12-163
12 Modeling Variant Systems

In both cases, the count value in the Counter subsystem is incremented. If A ~= 1 and A ~= 2,
then Counter does not execute because the Sine Wave block is inactive.

sim("slexVariantSourceFunctionCall")

To explore how the variant conditions propagate in other conditional subsystems such as enabled
subsystems, simulate the slexVariantControlPorts model and observe the results.

Note

If the function-call subsystem is placed inside a virtual grouped subsystem, the variant condition
triggering the function-call subsystem must match the corresponding condition on the input of the
higher-level subsystem block.

Variant Signals from Variant Subsystem Inport to Function-Call


Subsystems

This example shows how to include multiple implementations of a Function-Call Subsystem block as
variant choices in a Variant Subsystem block and execute them one at a time. The variant condition
that propagates to the function-call subsystem is set to all the ports of the subsystem. When you use
conditionally executed subsystems as variant choices:

• The type of control port blocks in all the variant choices must be same as the Variant Subsystem
block. For example, you cannot use enabled subsystem and function-call subsystem as choices
within a Variant Subsystem block.

• The control port on the Variant Subsystem block and the corresponding control ports on its
variant choices must have the same name. For example, if the name of the control port on the
Variant Subsystem is fcn, then the name of the corresponding control ports on all its variant
choices must also be fcn.

Note

The properties set on the control ports that are inside the Variant Subsystem block are ignored
during simulation and code generation.

Explore the Model

Consider the slexVariantSubsystemExportFunction model.

12-164
Propagate Variant Conditions to Control Execution of Conditional Subsystems

open_system("slexVariantSubsystemExportFunction")

The Variant Subsystem block VariantFcnCall has Function-Call Subsystem blocks as choices.

The inport fcn on VariantFcnCall corresponds to the control input ports on the variant choice
blocks. During simulation, the VariantFcnCall block gets the variant condition of the signal
connected to the fcn port. The variant condition assigned to the block then propagates to the blocks
connected to its input and output ports. When you simulate the model, the logical OR of variant
conditions from the variant choices, VSSMODE == 0 and VSSMODE == 1, propagates to the
VariantFcnCall block and its ports. During simulation, if VSSMODE == 0 evaluates to true, the
Linear block runs each time fcn receives a function-call event. If VSSMODE == 1 evaluates to true,
the Nonlinear block runs each time fcn receives a function-call event.

sim("slexVariantSubsystemExportFunction");

To explore how the variant conditions from a Variant Subsystem block propagate to other underlying
conditional subsystems such as enabled subsystems, simulate the
slexVariantSubsystemEnableChoice model and observe the results. For more information on
enabled subsystems, see “Using Enabled Subsystems” on page 10-12.

open_system("slexVariantSubsystemEnableChoice");
sim("slexVariantSubsystemEnableChoice");

12-165
12 Modeling Variant Systems

Generate Code for Export-Function Model

Export-function models are Simulink® models that generate code for independent functions that you
can integrate with an external environment or scheduler. You can use a Variant Subsystem block with
Function-Call Subsystem blocks as variant choices to create an export-function model. For more
information on export-function models, see “Conditionalize Export Function Calls in Code using
Variant Blocks” (Simulink Coder).

Limitations

The following are not supported when you use conditionally executed systems as variant choices
within a Variant Subsystem block:

• Action Port blocks in the variant choices


• Iterator subsystems as variant choices with the Variant activation time of the Variant Subsystem
block set to code compile
• Configuring a model as an AUTOSAR component with runnable as a variant choice
• Initialize Function, Reset Function, Terminate Function, and Simulink Function blocks

To explore how to create export-function models for function-call subsystems connected to Variant
Source blocks, simulate the slexVariantExportedFcn model and observe the results.

open_system("slexVariantExportedFcn");
sim("slexVariantExportedFcn");

12-166
Propagate Variant Conditions to Control Execution of Conditional Subsystems

Variant Signals from Variant Subsystem Outport to Function-Call


Subsystems

This example shows how to conditionalize the function-call signals to control the execution of a
Function-Call Subsystem block using the Variant Subsystem block. The variant condition that
propagates to the Function-Call Subsystem block is set to all the ports of the subsystem.

Explore the Model

Open the model slexVariantSubsystemFunctionCall.

The model contains a Variant Subsystem block with two Chart blocks, Chart1 and Chart2, as variant
choices. The variant control variable A is defined in the PreLoadFcn model callback. The variant
conditions on Chart1 and Chart2 are A == 1 and A == 2 respectively. A Pulse Generator block is
connected to the Variant Subsystem block.

open_system("slexVariantSubsystemFunctionCall");

12-167
12 Modeling Variant Systems

Chart1 and Chart2 are configured with port names that match the corresponding port names of the
Variant Subsystem block.

open_system("slexVariantSubsystemFunctionCall/Variant Subsystem");

The Output function call parameter is selected on the Signal Attributes tab of the Block
Parameters dialog box of the Outport block named activate(). This option allows the outport of the
Counter subsystem to emit function-call signals.

Simulate the Model

When you simulate the model, the logical OR of variant conditions A == 1 and A == 2 propagates to
the Counter subsystem and all its ports to determines the active and inactive variant choices.

• When A == 1, Chart1 is active.


• When A == 2, Chart2 is active.

The outport activate() gets function-call signal from the choices Chart1 and Chart2. When the
Function-Call Subsystem block is triggered, there is a sine wave output at Out2.

12-168
Propagate Variant Conditions to Control Execution of Conditional Subsystems

sim("slexVariantSubsystemFunctionCall");

See Also

More About
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-169
12 Modeling Variant Systems

Propagate Variant Conditions to Enable or Disable Model or


Subsystem References in Hierarchy

Simulink® compiles referenced models before propagating variant conditions. A variant condition
can activate or deactivate a Model block, but the variant condition does not propagate into the
referenced model. Instead, it stays on the boundary. However, the blocks inside the referenced model
inherit the variant condition from the Model block.

Explore the Model

Consider the slexVariantMdlRefCondProp model.

open_system("slexVariantMdlRefCondProp")

12-170
Propagate Variant Conditions to Enable or Disable Model or Subsystem References in Hierarchy

In the model, the Variant Source1 block has a variant condition V == 1 that propagates to the
Model block sub1. Since sub1 is a Model block, the variant condition stays on the boundary and
applies to the referenced model within the Model block. If sub1 is active, the blocks within sub1 are
also active. If sub1 is inactive, the blocks within sub1 are also inactive, thus making sub1
conditional.

A Model block can propagate variant conditions from its interface (input, output, or control port), if
those variant conditions originate at ports inside the block. In this example, the Model block sub2
propagates the variant conditions received from the referenced model
slexVariantMdlRefCondProp_sub2 at the outports.

sim("slexVariantMdlRefCondProp");

Note

• The Model block does not propagate variant conditions from its interface if those variant
conditions originate from the Initialize Function or Terminate Function blocks inside the Model
block. For more information, see “Conditionally Execute Custom Initialize, Reinitialize, Reset, and
Terminate Routines” on page 12-173.

12-171
12 Modeling Variant Systems

• “Create and Use Referenced Subsystems in Models” on page 4-38 blocks propagate the variant
conditions in the same way as Model blocks.

Generate Code for Model Reference Blocks

For an example on how to generate code, see “Generate Code for Model References Connected to
Variant Blocks” (Simulink Coder).

See Also

“Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-172
Conditionally Execute Custom Initialize, Reinitialize, Reset, and Terminate Routines

Conditionally Execute Custom Initialize, Reinitialize, Reset, and


Terminate Routines

The custom routine blocks(Initialize Function, Reinitialize Function, Reset Function, and Terminate
Function) blocks are preconfigured subsystem blocks that enable you to add custom routines to the
default initialize, reset, and terminate routines to change or read block states. You can execute the
custom routine conditionally by specifying variant conditions on the Event Listener block within
custom routine blocks.

For example, consider a model algorithm that reads a sensor value. The Initialize Function block
enables you to perform a computation to set the initial sensor state. To control when to reset the state
of the sensor, use a Reset Function block. To save the state of the sensor at the end of the simulation,
use a Terminate block. You can conditionally initialize, reset, or save the state of the sensor by
specifying a variant condition for the Event Listener block within the Initialize, Reset, and Terminate
function blocks. For more information, see “Using Initialize, Reinitialize, Reset, and Terminate
Functions” on page 10-208.

Explore the Model

Consider the slexVariantIRTVariantCondProp model.

open_system("slexVariantIRTVariantCondProp")

The model contains a Model block ResetRefModel. The ResetRefModel block contains Initialize
Function, Reset Function, and Terminate Function blocks to set the state of the Discrete-Time
Integrator block. The Event Listener block within the Initialize, Reset, and Terminate Function blocks
have the Enable variant condition option selected. The Variant control parameter of the Event
Listener block is specified as V == 1. During simulation, the Function-Call Generator blocks send
function-call signals to initialize, reset, and terminate ports at time step 2, 5, and 7 respectively.

When you simulate the model with V = 1, the ResetRefModel block propagates the variant
condition, V == 1, that originates from the Reset Function blocks to the reset port. The block does
not propagate the variant conditions from the Initialize and Terminate blocks. This makes the

12-173
12 Modeling Variant Systems

initialize and terminate ports unconditional because they control both the model default and
block-specific initialize and terminate events of the referenced model. The Scope output shows that
the signal is initialized to a custom value 5 at time step 2, reset to a custom value 10 at time step 5,
and terminated at a custom time step 7.

V = 1;
sim("slexVariantIRTVariantCondProp");
open_system("slexVariantIRTVariantCondProp/Scope");

When you simulate the model with V = 2, the ResetRefModel block propagates the variant
condition, V == 1, from the Reset Function block, thus making the blocks connected to the reset
port inactive. The initialize and terminate ports are unconditional. The Scope output shows that the
signal is initialized to a default value 0 at time step 2 and continues to increase by 1 until the
simulation terminates at step 7.

V = 2;
sim("slexVariantIRTVariantCondProp");
open_system("slexVariantIRTVariantCondProp/Scope");

12-174
Conditionally Execute Custom Initialize, Reinitialize, Reset, and Terminate Routines

See Also

“Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-175
12 Modeling Variant Systems

Conditionally Execute Simulink Functions

With variant blocks, you can conditionalize functions defined using Simulink Function blocks. A
variant condition from a variant block does not propagate inside a Simulink Function block. Instead,
it stays on the boundary and controls the entire Simulink Function block. For more information, see
Simulink Function.

Explore the Model

Consider the model slexVariantSimulinkFunctionInherit.

open_system("slexVariantSimulinkFunctionInherit")

In this example, the function-call port block within the Simulink Function block has the Enable
variant condition option selected and the Variant control parameter is set to (inherit). During
simulation, the Simulink Function block inherits the logical OR of the variant conditions, A == 1 and
B == 1, from the corresponding Function Caller blocks Function Caller1 and Function
Caller2. The Generate preprocessor conditionals parameter value that determines whether to
include only the active choice, or both active and inactive choice in the generated code is also
inherited from the Function Caller blocks.

sim("slexVariantSimulinkFunctionInherit")

Consider the model slexVariantSimulinkFunctionSpecify.

open_system("slexVariantSimulinkFunctionSpecify")

12-176
Conditionally Execute Simulink Functions

In this example, the function-call port block within the Simulink Function block has the Enable
variant condition option selected and the Variant control parameter is set to V == 1. During
simulation, the variant condition V == 1 propagates from the Variant Source block to the Function
Caller block. To ensure the agreement between the function caller and its callee, Simulink® checks if
the propagated variant condition on the Function Caller block is same as the variant condition
specified in the Simulink Function block during simulation. The simulation fails if the variant
condition that propagates to the Function Caller block is not same as the variant condition
propagated to the Simulink Function block.

Note

The Configure C Step Function Interface dialog box allows you to configure the input and output data
types, the function name, and other parameters for the generated code. However, if the input and
output ports of the subsystem share an argument name and have propagated variant conditions, you
cannot customize the generated C code for those ports and you must use the default settings.

Limitations

• Variant condition propagation from a Simulink Function block inside Stateflow block is not
supported.

• Argument Inport and Argument Outport blocks interfacing with Simulink Function blocks cannot
be connected to Variant Source or Variant Sink variant blocks.

See Also

“Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133

12-177
12 Modeling Variant Systems

Approaches to Control Active Variant Choice of a Variant Block


Using Mask or Model Workspace

This example shows different approaches to control the active choice of inline variant and Variant
Subsystem blocks from a mask or a model workspace. For more information on Variant blocks, see
“What Are Variants and When to Use Them” on page 12-3.

Model

In this example, four Simulink® models are highlighted in green, and one model is highlighted in red.
The models in green represent the recommended approaches to control the active choice of Variant
blocks. These approaches let you limit the scope of the variant control variable, avoid name conflicts,
and establish a clear ownership of the variable between Variant blocks. They also allow you to use the
same names for variables in different scopes.

12-178
Approaches to Control Active Variant Choice of a Variant Block Using Mask or Model Workspace

Limitations of Recommended Approaches

• Work only if the Variant control mode parameter is set to expression and the Variant
activation time parameter is set to update diagram or update diagram analyze all
choices. When you use update diagram, Simulink does not analyze signal attributes of variant
choices for consistency and generates code only for the active choice. When you use update
diagram analyze all choices, Simulink analyzes signal attributes of active and inactive
choices. However, it generates code only for the active choice.
• Do not support using Simulink.VariantExpression objects or Simulink.Parameter as
variant control variables.
• Do not support using model arguments variables as variant control variables.
• The number of characters in the variant control variable must not exceed 40.
• The variant control variable originating from a mask workspace must not start with SLMASK.

Approach 1: Use Mask Parameter as a Variant Control Variable

This section explains how to control the active variant choice of Variant Subsystem blocks and inline
variant blocks by using a mask parameter.

Control Active Choice of a Variant Subsystem Block using Mask Parameter

Consider the model with Variant Subsystem block VSS1. The VSS1 subsystem specifies two potential
variants, x2 and x3. The control expression for x2 is B == 1 and for x3 is B == 2. The variable B is a
mask parameter. To view the properties of B:

1. Right-click the VSS1 subsystem.

2. Select Mask > Edit Mask. In the Parameters & Dialog pane, under Parameters, the Prompt
column specifies the label of the parameter on the mask dialog box, and the Name column specifies
the name of the mask parameter. In this example, Prompt is specified as Enter the choice, and
Name is specified as B.

3. To open the mask dialog box, double-click the VSS1 subsystem. During simulation, the index of the
value that you specify here is mapped to the underlying variable B, which is then used to evaluate the
variant condition expressions associated with the block. In this example, the default value of Enter
the choice is 2. When you simulate this model, the variant condition B == 2 evaluates to true. The
x2 subsystem becomes inactive, and the x3 subsystem becomes active.

4. To modify the active choice, specify the value as 1 in the mask dialog box, then simulate the model
again. During simulation, the value of the B is set to 1 which in turn evaluates the Variant condition, B
== 1 to true. The x2 subsystem becomes active, and the x3 subsystem becomes inactive.

12-179
12 Modeling Variant Systems

Control Active Choice of Inline Variant Blocks using Mask Parameter

Consider the model with masked Subsystem block SS1. The SS1 subsystem has a mask parameter VC
that is used as a variant control variable in the underlying Variant Source block Vsrc. The first input
port is associated with the control expression VC == 1 and the second input port is associated with
the control expression VC == 2. To view the properties of VC:

1. Right-click the SS1 subsystem.

2. Select Edit Mask. In the Parameters & Dialog pane, under Parameters, the Prompt column
specifies the label of the parameter on the mask dialog box, and the Name column specifies the name
of the mask parameter. In this example, Prompt is specified as Choose the signal, and Name is
specified as VC.

3. To open the mask dialog box, double-click the SS1 subsystem. During simulation, the index of the
value that you select here is mapped to the underlying variable VC, which is then used to evaluate the
variant condition expressions associated with the Vsrc block. In this example, the default value of
Choose the signal is Sine Wave. When you simulate this model, the index of the Sine Wave, 2, is
mapped to VC. The variant condition VC == 2 evaluates to true. As a result, the first input port of
the Vsrc block that is associated with VC == 1 becomes inactive and the second input port that is
associated with VC == 2 becomes active.

4. To modify the active choice, select the value as Constant in the mask dialog box, then simulate
the model again. During simulation, the value of the VC is set to 1 which in turn evaluates the variant
condition, VC == 1 to true. The first input port of the Vsrc block becomes active and the second
input port becomes inactive.

Approach 2: Use Mask Initialization Variable as a Variant Control Variable

This section explains how to control the active variant choice of Variant Subsystem blocks using a
mask initialization variable. You can follow this approach to control the active variant choice of inline
variant blocks as well.

Consider the model with Variant Subsystem block VSS2. 1. In the VSS2 subsystem, the control
expression for x2 is A == 1 and for x3 is A == 2. The variable A used in the control expression is a
regular MATLAB® variable that is defined using a function in the Code tab of the mask workspace.
To view the properties of A:

a. Right-click the VSS2 subsystem.

12-180
Approaches to Control Active Variant Choice of a Variant Block Using Mask or Model Workspace

b. Select Mask > Edit Mask. In the Code tab, under Initialization code section, set the value of A
to 1 using the function initialization().

During simulation, this value is used to evaluate the variant condition expressions associated with the
block. When you simulate this model, the variant condition A == 1 evaluates to true. The x2
subsystem becomes active, and the x3 subsystem becomes inactive.

3. To modify the active choice, specify the value of A as 2 in the function initialization() in the
Code tab, then simulate the model again. During simulation, A == 2 evaluates to true. The x2
subsystem becomes active, and the x3 subsystem becomes inactive.

Approach 3: Use Model Workspace Variable as a Variant Control Variable in a Variant


Subsystem Block

This section explains how to control the active variant choice of Variant Subsystem blocks using a
model workspace variable. You can follow this approach to control the active variant choice of inline
variant blocks as well.

Consider the model with Variant Subsystem block VSS3. 1. In the VSS3 subsystem, the control
expression for x2 is C == 1 and for x3 is C == 2. The variable C used in the condition expression is
a regular MATLAB® variable that is defined in the model workspace. To view the properties of C:

a. On the Modeling tab, click Model Explorer.

b. In the Model Hierarchy pane, click Model Workspace. The value of C is set to 1.

During simulation, this value is used to evaluate the variant condition expressions associated with the
block. When you simulate this model, the variant condition C == 1 evaluates to true. The x2
subsystem becomes active, and the x3 subsystem becomes inactive. To modify the active choice,
specify the value of C as 2, then simulate the model again. During simulation, the Variant condition C
== 2 evaluates to true. The x2 subsystem becomes active, and the x3 subsystem becomes inactive.

12-181
12 Modeling Variant Systems

Approach 4: Use Mask Initialization Script to Control Active Variant Choices of a Variant
Subsystem Block

This approach is not recommended for controlling the active variant choice of Variant Subsystems.
However, if the Variant control mode of the subsystem is set to Label mode, you can follow this
approach. For more information, see “Mask a Variant Subsystem” on page 43-91.

See Also

“Control Active Choice of Locked Custom Library Variant Subsystem Using Mask Parameter” on page
12-192

12-182
Control Structural Variations Using Mask Parameters and Model Arguments

Control Structural Variations Using Mask Parameters and


Model Arguments

This example shows you how to control structural variations using mask parameters and model
arguments in a model. You can use mask and model workspace to simulate and generate code for
variant blocks with startup activation time.

Model

The models represent a fog lamp controller system that operates in driver switch mode and in Sensor
Connected mode. In the Driver Switch mode, the intensity of the fog lamps is controlled by the driver.
In Sensor Connected mode, the sensor adjusts the intensity of different types of fog lamps based on
the intensity of ambient light in the external environment.

Simulate Using Mask Parameters in Driver Switch and Sensor Connected Modes

The model slexVariantsWithMaskParametersInStartup contains two instances of the


Controller variant subsystem block with a mask. The variant control variable CTRL_MODE is
defined as a mask parameter. The values of the CTRL_MODE mask parameter in the Controller
block mask dialog represent the variant choices which are populated using the enumeration
'InputType' which is available on path.

The Controller variant subsystem in Sensor Connected mode has the condition
CTRL_MODE==InputType.Sensor and the Driver Switch mode has the condition CTRL_MODE==
InputType.Driver.

In the Driver Switch mode, the LightCommand output is a delayed DriverSwitch signal. This is the
equivalent action of the driver manually switching on or off the fog light.

In the sensors connected mode as the active choice, the LightCommand output is high until the
SensorOutput is high, independent of the DriverSwitch signal. This is equivalent to sensors
overriding the manual switching based on the ambient light.

To simulate, set the activation time of the Controller block to 'startup' and select the active
choice from the Block Parameters. Double-click the block parameter mask of the Controller variant
subsystem block to select the active choice. Scope shows the Driver Mode output.

sim('slexVariantsWithMaskParametersInStartup');
open_system('slexVariantsWithMaskParametersInStartup/Scope')

12-183
12 Modeling Variant Systems

Simulate Using Model Arguments in Driver Switch and Sensor Connected Modes

The model slexVariantsWithModelArguments contains two instances of a referenced model,


which contains the Variant Subsystem block. The variant control variable CTRL_MODE of the Variant
Subsystem block is defined in the model workspace of the referenced model. This model workspace
variable is marked as a Model Argument. The model arguments are used as controls for the Variant
Subsystem blocks with startup activation time.

To simulate Driver Switch or Sensors Connected mode in Fast restart, change the value of Instance
parameter CTRL_MODE of the model reference from the Block Parameters dialog of either the
'Model' or 'Model1' blocks. You can also generate code. The generated code will contain regular
if conditions. Scope shows the Driver Mode output of 'Model', and Scope1 shows the Sensor
Connected Mode output of 'Model1'.

NOTE : When using the SimulationInput object to create the model workspace variable, the
variant control variable must be present in the model workspace.

sim('slexVariantsWithModelArguments');
open_system('slexVariantsWithModelArguments/Scope')

12-184
Control Structural Variations Using Mask Parameters and Model Arguments

12-185
12 Modeling Variant Systems

Prevent Creation of Unused Variables for Unconditional and


Conditional Variant Choices

This example shows how to prevent Simulink® models from creating unused variables in generated
code when the variant condition of the source block is unconditional and the variant condition of the
destination block is conditional. Preventing the creation of unused variables in generated code
increases the likelihood of generating C code that is compliant with Rule 2.2 of the MISRA C:2012
guidelines.

Model Description

In this model, the Variant Sink block has the variant condition expressions V == 1 and V == 2.

Generate C Code Using Embedded Coder

Suppose that the value of V is set to 3.

When you generate code using Embedded Coder™, the variant condition expressions V == 1 and V
== 2 evaluate to false. Simulink disables all the blocks connected to the input and output stream of
the Variant Sink block. However, code is generated for all the variant choices in the model.

12-186
Prevent Creation of Unused Variables for Unconditional and Conditional Variant Choices

A variable Add is created in the generated code. During code compilation, this variable remains
unused since both choices evaluate to false.

To avoid modeling issues that may create unused variables in generated code, select Model Settings
> Diagnostics. Expand the Advanced parameters section and scroll to the bottom of the dialog box.
In the Modeling issues related to variants section, set the Variant condition mismatch at
signal source and destination parameter to warning or error. Setting this parameter warns you
about unused variables during code generation.

See Also
Variant condition mismatch at signal source and destination

12-187
12 Modeling Variant Systems

Related Examples
• “Prevent Creation of Unused Variables for Lenient Variant Choices” on page 12-189

12-188
Prevent Creation of Unused Variables for Lenient Variant Choices

Prevent Creation of Unused Variables for Lenient Variant


Choices

This example shows how to prevent Simulink® models from creating unused variables in generated
code when the variant condition of the source block is more lenient than the variant condition of the
destination block. Preventing the creation of unused variables in generated code increases the
likelihood of generating C code that is compliant with Rule 2.2 of the MISRA C:2012 guidelines.

Model Description

In this model, the source of the highlighted signal is the block named EvlnB. The destination of the
signal is the block named VariantSource3. The variant condition of EvlnB is A > 0, which is more
lenient than the variant condition A > 0 && B == 1 of VariantSource3.

Generate C Code Using Embedded Coder

Suppose that the value of A is 1, and the value of B is 0.

When you generate code using Embedded Coder™, the variant condition of EvlnB, A > 0, evaluates
to true, and the condition of VariantSource3, A > 0 && B == 1, evaluates to false. However,
code is generated for all variant choices. In the generated code, the variable rtb_Switch is created.
This variable corresponds to the Switch block that is located inside the block named EvlnB.
rtb_Switch is used only when A > 0 && B == 1 evaluates to true. In this example, since A > 0
&& B == 1 evaluates to false, rtb_Switch remains unused.

12-189
12 Modeling Variant Systems

To avoid modeling issues that may create unused variables in generated code, select Model Settings
> Diagnostics. Expand the Advanced parameters section and scroll to the bottom of the dialog box.
In the Modeling issues related to variants section, set the Variant condition mismatch at
signal source and destination parameter to warning or error. Setting this parameter warns you
about unused variables during code generation.

12-190
Prevent Creation of Unused Variables for Lenient Variant Choices

See Also
Variant condition mismatch at signal source and destination

Related Examples
• “Prevent Creation of Unused Variables for Unconditional and Conditional Variant Choices” on
page 12-186

12-191
12 Modeling Variant Systems

Control Active Choice of Locked Custom Library Variant


Subsystem Using Mask Parameter
In this section...
“Model” on page 12-192
“Switch Between Active Choices” on page 12-193

This example shows how to control the active choice of a Variant Subsystem that belongs to a locked
custom library by using a mask parameter as Variant control variable. Mask parameters limit the
scope of the variable, which allows you to use the same names for control variables in different
scopes. This example includes promoted parameters and control expressions with enumeration
classes to simplify the interface of the mask dialog and control expressions with enumeration classes
to improve the readability of the variant condition expressions. For more information on Variant
Subsystems, see “Implement Variations in Separate Hierarchy Using Variant Subsystems” on page
12-48.

Model
Open the Simulink model by typing the following command in the MATLAB Command Window :
openExample("simulink_variants/SimulinkVariantsExample",...
"supportingFile","slexVariantSubsystemUsingMaskAndEnums.slx")

Consider the Engine subsystem block in the locked custom library, slexVarEngineLibrary.

The mask dialog box of the subsystem contains these parameters:

• Engine type: When you select a value for this parameter, Simulink assigns the index of that value
to the mask parameter engine. During simulation, the value of engine is used to evaluate the
variant condition expressions to activate or deactivate the underlying Turbo Engine and Non
Turbo Engine subsystems.
• Fidelity type for turbo engine: This parameter becomes available only if the Engine type
parameter is set to Turbo. This parameter is promoted on to the mask dialog of the Engine
subsystem from the underlying layer of the Turbo Engine subsystem. When you select a value for
this parameter, Simulink assigns the index of that value to the mask parameter enginetype of
the Turbo Engine subsystem. During simulation, the value of enginetype is used to evaluate the
variant condition expression to activate or deactivate the underlying High, Medium, and Low
subsystems.
• Fidelity type for non turbo engine: This parameter becomes available only if the Engine type
parameter is set to Non Turbo. This parameter is promoted on to the mask dialog of the Engine

12-192
Control Active Choice of Locked Custom Library Variant Subsystem Using Mask Parameter

subsystem from the underlying layer of the Non Turbo Engine subsystem. When you select a value
for this parameter, Simulink assigns the index of that value to the mask parameter enginetype of
the Non Turbo Engine subsystem. During simulation, the value of enginetype is used to evaluate
the variant condition expression to activate or deactivate the underlying High, Medium, and Low
subsystems.

The scope of enginetype in the Turbo Engine subsystem is different from the scope of enginetype
in the Non Turbo Engine subsystem. enginetype of Turbo Engine is visible only to the underlying
layers of the Turbo Engine subsystem. Similarly, enginetype of Non Turbo Engine is visible only to
the underlying layers of the Non Turbo Engine subsystem. Limiting the scope by using mask
parameters as Variant control variables allows you to use the same name for variables with holding
different values in the Turbo Engine and the Non Turbo Engine subsystems.

Switch Between Active Choices


1 To simulate the model, on the Simulation tab, click Run. On the mask dialog of the Engine
subsystem, the Engine type parameter is set to Non Turbo, and the Fidelity type for non
turbo engine is set to Medium. As these parameters are mapped to the index of the mask
parameters engine and engineType, the value of engine is set to 2, and the value of
engineType is set to 1. Here, 2 specifies the index of the Non Turbo option, and 1 specifies the
index of the High option. For more information on how the parameters on the mask dialog box
are mapped to the underlying mask parameters, see “Create a Simple Mask” on page 43-7.

During simulation, the condition expressions engine == Engine.NONTURBO and engineType


== EngineFidelity.MEDIUM evaluate to true. Here, Engine and EngineFidelity are
integer-based enumeration classes defined in Engine.m and EngineFidelity.m files with
values for Engine.TURBO and Engine.NONTURBO specified as 1 and 2, and the values for
EngineFidelity.HIGH, EngineFidelity.MEDIUM, and EngineFidelity.LOW specified as
1, 2, and 3.

12-193
12 Modeling Variant Systems

The NonTurbo Engine subsystem becomes active and the Turbo Engine subsystem becomes
inactive.
2 To modify the active choice, select Turbo in the mask dialog box, then simulate the model again.
During simulation, the value of engine is set to 1, which evaluates the variant condition engine
== Engine.TURBO to true. The Turbo Engine subsystem becomes active, and the Non Turbo
Engine subsystem becomes inactive.

See Also

Related Examples
• “Approaches to Control Active Variant Choice of a Variant Block Using Mask or Model
Workspace” on page 12-178

12-194
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

Add or Remove Variant Choices of Variant Assembly


Subsystem Blocks Using External Files
A Variant Assembly Subsystem block can use Model blocks, “Create and Use Referenced Subsystems
in Models” on page 4-38 blocks, or both as its variant choices. The variant choices are maintained in
a separate model and subsystem files that are on the MATLAB path. You can add or remove the
variant choices from the Variant Assembly Subsystem block without modifying the model. You use an
external source such as an enumeration class or a MATLAB function to manage the variant choices of
the Variant Assembly Subsystem block. Unlike when you use Variant Subsystem blocks, you are not
required to navigate inside the Variant Assembly Subsystem block to add or remove the variant
choices from the block. For more information, see “Variant Assembly Subsystem”.

This example explains how to:

• “Manipulate Variant Choices of Variant Assembly Subsystem Block in Label Mode” on page 12-195
• “Manipulate Variant Choices of Variant Assembly Subsystem Block in Expression Mode” on page
12-201

Manipulate Variant Choices of Variant Assembly Subsystem Block in


Label Mode
This section shows how to add or remove the variant choices of a Variant Assembly Subsystem block
in label mode.

Maintain Variant Choices of Variant Assembly Subsystem Block in Model and Subsystem
Files

A Variant Assembly Subsystem block can contain Model blocks, “Create and Use Referenced
Subsystems in Models” on page 4-38 blocks, or both as its variant choices. The variant choices are
maintained in separate model and subsystem files that are on the MATLAB® path.

1. Open the slexVariantAssemblySubsystemInLabel model. The model contains a Variant


Assembly Subsystem block Controller.

12-195
12 Modeling Variant Systems

2. To add variant choices to the Controller block, open the Block Parameters dialog box and specify
this MATLAB expression in the “Variant choices specifier” parameter.

{'linear_generic1','linear_generic2','nonlinear_generic1','nonlinear_generic2'}

In this example, the linear_generic1 and the linear_generic2 choices are Model blocks. The
nonlinear_generic1 and nonlinear_generic2 blocks are Subsystem Reference blocks. These
variant choices are maintained in their respective files inside the ControllersList folder. To create
the ControllersList folder, run the createFolderStructureForVAS function.

createFolderStructureForVAS(pwd)

Ensure that the ControllersList folder and all its subfolders are added to the search path of your
current MATLAB session by using the addpath function.

12-196
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

3. After you specify an expression in the Variant choices specifier parameter, click the Validate
button. The expression is evaluated to ensure that it is a valid MATLAB expression that returns a one-
dimensional cell array of model or subsystem file names or file name patterns that are on the
MATLAB path. On successful validation, the variant choices are added to the Controller block. Any
errors encountered during the validation are displayed in the block dialog.

4. Double-click the Controller block to observe the four variant choices linear_generic1,
linear_generic2, nonlinear_generic1, and nonlinear_generic2 that are added to the
Controller block. The file name and the path of the newly added variant choices are displayed in
the Variant Choices table in the Reference tab.

5. From Label mode active choice, select linear_generic1 and simulate the model. Observe that
the linear_generic1 choice becomes active.

6. You can modify the expression in the Variant choices specifier parameter as described in
“Specify Variant Choices of Variant Assembly Subsystem Block in Variant Choices Specifier
Parameter” on page 12-197, then simulate the model again.

Specify Variant Choices of Variant Assembly Subsystem Block in Variant Choices Specifier
Parameter

To add Model or Subsystem Reference blocks as variant choices to a Variant Assembly Subsystem
block, specify the names of the files to be referenced. The file names must be specified as a MATLAB
expression that returns a one-dimensional cell array of character vectors when evaluated. You can
then validate the expression using the Refresh button. On a successful validation, the blocks are
added as variant choices to the Variant Assembly Subsystem block. For each choice, a variant control
label is generated. The name of the variant control label is same as the name of the choice. The newly
added variant choices and their corresponding control labels are displayed in the Variant choices
table.

The MATLAB expression that you specify must contain either of these:

• Model or subsystem file names that are on the search path of your current MATLAB session. For
example, if you specify {'model1.slx', 'subsystemRef1.slx'} as a specifier, the blocks

12-197
12 Modeling Variant Systems

that reference the model1.slx and subsystemRef1.slx files are added as variant choices of
the Variant Assembly Subsystem block.
• File name patterns which match the model or subsystem file names on the MATLAB path. The
paths in the pattern can be absolute or relative to the parent folder of the model that contains the
Variant Assembly Subsystem block. For example, if you specify {'folder_1/*.slx',
'folder_2/*.slx'} as a specifier, Simulink passes the character vectors folder_1/* and
folder2/* to the dir function. The function then returns the model and the subsystem files that
are located inside the folder1 and folder2 folders. The blocks that reference the returned files
are added as variant choices of the Variant Assembly Subsystem block.

For information on how to add files or folders to the search path, see addpath.

The following table shows different ways in which you can specify the Variant choices specifier
parameter in the Controller block. Specify these expressions in the Variant choices specifier
parameter and validate them by clicking the Refresh button. On successful validation, the variant
choices are added to the Controller block.

Variant Choices Specifier Added Variant Choices


Description — Specify a relative path to a folder The model or subsystem files that are located
that contains model or subsystem files. inside the ControllersList folder are added as
variant choices. Files inside the subfolders of
Value — {'ControllersList/*'} ControllersList are not added. The added
choices are:

• controller_generic1
• controller_generic2
Description — Specify relative path to a folder The model or subsystem files that are located
and its subfolders that contain model or inside the ControllersList folder are added as
subsystem files. variant choices. Files inside the subfolders of
ControllersList are also added. The added
Value — {'ControllersList/**'} choices are:

• linear_groupA_type1
• linear_groupA_type2
• linear_groupB_type1
• linear_groupB_type2
• linear_generic1
• linear_generic2
• nonlinear_groupA_type1
• nonlinear_groupA_type2
• nonlinear_groupB_type1
• nonlinear_groupB_type2
• nonlinear_generic1
• nonlinear_generic2
• controller_generic1
• controller_generic2

12-198
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

Variant Choices Specifier Added Variant Choices


Description — Specify relative path to a folder The model or subsystem files that are located
and its subfolders one level down that contain inside the ControllersList folder are added as
model or subsystem files. variant choices. Files inside the subfolders
linear and nonlinear are also added. The
Value — {'ControllersList/*', added choices are:
'ControllersList/*/*'}
• linear_generic1
• linear_generic2
• nonlinear_generic1
• nonlinear_generic2
• controller_generic1
• controller_generic2
Description — Specify relative path to a folder The model or subsystem files that are located
that contain model or subsystem files and has inside the linear_groupA and
subfolder names with a certain ending. nonlinear_groupA subfolders are added as
variant choices. The added choices are:
Value — {'ControllersList/**/
*groupA/*'} • linear_groupA_type1
• linear_groupA_type2
• nonlinear_groupA_type1
• nonlinear_groupA_type2
Description — Specify an absolute path to a The model or subsystem files that are located
folder that contains model or subsystem files inside the ControllersList folder are added as
variant choices. Files inside the subfolders of
Value — In Windows systems, {'C:\VAS ControllersList are not added. The added
\ControllersList\*'} choices are:

In UNIX systems, {'/VAS/ • controller_generic1


ControllersList/*'} • controller_generic2
Description — Specify the model or subsystem The specified model and subsystem files are
file names in a cell array added as variant choices. The added choices are:

Value — {'linear_groupA_type1', • linear_groupA_type1


'linear_groupB_type2', • linear_groupB_type2
'nonlinear_generic1',
• nonlinear_generic1
'controller_generic2'}
• controller_generic2

12-199
12 Modeling Variant Systems

Variant Choices Specifier Added Variant Choices


Description — Create a MATLAB workspace The model or subsystem files specified in
variable that returns a cell array of models or controllers are added as variant choices. The
subsystem file names. You can then specify the added choices are:
variable name as a variant choices specifier.
• linear_groupA_type1
For example, controllers: • linear_groupB_type2
• nonlinear_generic1
controllers = {'linear_groupA_type1', 'linear_groupB_type2', ...
'nonlinear_generic1', 'controller_generic2'};
• controller_generic2
Value — controllers
Description — Create a MATLAB function that The model or the subsystem files returned by
returns a cell array of models or subsystem file getMyListOfControllerChoices are added
names. You can then specify the function name as as variant choices. The added choices are:
a variant choices specifier.
• linear_groupA_type1
For example, the • linear_groupB_type2
getMyListOfControllerChoices function is
available for you to use. • nonlinear_generic1
• controller_generic2
function choices = getMyListOfControllerChoices
choices = {'linear_groupA_type1', 'linear_groupB_type2', ...
'nonlinear_generic1', 'controller_generic2'};
end

Value — getMyListOfControllerChoices
Description — Create a MATLAB function that The model and subsystem files returned by
returns a cell array of models or subsystem file getMyListOfControllers are added as a
names, and a file name pattern. You can then variant choices. The added choices are:
specify the function name as a variant choices
specifier. • nonlinear_groupA_type1
• nonlinear_groupA_type2
For example, getMyListOfControllers.
• nonlinear_groupB_type1
function choices = getMyListOfControllers
• nonlinear_groupB_type2
choices = {'controller_generic1', 'ControllersList/nonlinear/**'};
end
• nonlinear_generic1
Value — getMyListOfControllers • nonlinear_generic2
• controller_generic1

12-200
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

Variant Choices Specifier Added Variant Choices


Description — Create a MATLAB function to The model or subsystem files of
exclude certain files or folders from the selection. ControllersList except those in
You can then specify the function name as a ControllersList/linear/linear_groupA
variant choices specifier. are added as variant choices. The added choices
are:
For example, the
getMyFilteredListOfControllerChoices • linear_groupB_type1
function is available for you to use. • inear_groupB_type2
function choices = getMyFilteredListOfControllerChoices • linear_generic1
% Pattern to include all the files inside 'ControllersList/'
patternToInclude = 'ControllersList/**'; • linear_generic2
• nonlinear_groupA_type1
% Pattern to exlude all the files inside 'ControllersList/linear/linear_groupA/'
patternToExclude = 'ControllersList/linear/linear_groupA/*';
• nonlinear_groupA_type2
% Set difference of files to include and exclude
• nonlinear_groupB_type1
choices = setdiff(getSLXFileNames(patternToInclude), getSLXFileNames(patternToExclude))';

function fileNames = getSLXFileNames(pattern) • nonlinear_groupB_type2


[~, fileNames, fileExts] = fileparts({dir(pattern).name});
fileNames = fileNames(strcmp(fileExts, '.slx')); • nonlinear_generic1
end
end • nonlinear_generic2

Value — • controller_generic1
getMyFilteredListOfControllerChoices • controller_generic2

Manipulate Variant Choices of Variant Assembly Subsystem Block in


Expression Mode

This example shows how to add or remove variant choices from a Variant Assembly Subsystem block
that is in the expression mode.

Maintain Variant Choices of Variant Assembly Subsystem Block in Model and Subsystem
Files

Open the slexVariantAssemblySubsystemInExpression model. The model contains a Variant


Assembly Subsystem block Controller. The block is in the expression mode and has two variant
choices linearConroller and nonlinearController. The linearController and the
nonlinearController blocks are Subsystem Reference blocks that are saved as subsystem files in
your current working folder.

mdl = 'slexVariantAssemblySubsystemInExpression';
open_system(mdl)
vasBlkPath = [mdl, '/Controller'];

12-201
12 Modeling Variant Systems

The linearController and nonlinearController blocks are added as choices to the


Controller block using enumerations that are created using one of these methods. If you set the
Variant activation time parameter of the Controller block to code compile or startup,
Simulink sets the Treat as atomic unit parameter of the linearController and
nonlinearController blocks to on. The Treat as atomic unit parameter enables Simulink to
treat the blocks as a unit. For example, if the linearController block is set to atomic, Simulink
simulates all the blocks within the linearController block before simulating the next block at the
same level as the linearController.

• Use a classdef block in a MATLAB™ file.


• Use the function Simulink.defineIntEnumType. You do not need a script file to define the
type.
• Use a Simulink® data dictionary to permanently store the enumeration definition.

Define Enumeration Class Using classdef Block in MATLAB File

In this example, controllerTypesMfile is an integer-based enumeration class that is derived from


the built-in class Simulink.IntEnumType. controllerTypesMfile is integer-based because
IntEnumType is derived from int32. For more information on enumeration classes that are defined
using the classdef block, see “Create Simulink Enumeration Class” on page 74-5.

type controllerTypesMfile

classdef controllerTypesMfile < Simulink.IntEnumType


%

% Copyright 2023 The MathWorks, Inc.

enumeration
linearController(0)

12-202
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

nonlinearController(1)
end
end

The enumeration section specifies the enumerated values linearController(0) and


nonlinearController(1). Each enumerated value consists of an enumerated member and an
underlying integer. Here, enumerated members are filenames of the variant choices
linearController and nonlinearController and the underlying integers are 0 and 1.

1. To configure the Controller block, set the Variant control variable parameter to
variantCtrlVar and the Variant choices enumeration parameter to controllerTypesMFile in
the Block Parameters dialog box.

set_param(vasBlkPath, 'VariantChoicesEnumeration', 'controllerTypesMfile')


set_param(vasBlkPath, 'VariantControlVariable', 'variantCtrlVar')

2. To activate the linearController choice, set variantCtrlVar to


controllerTypesMFile.linearController and then simulate the model. During simulation, the
variantCtrlVar == controllerTypesMFile.linearController expression evaluates to
true. Subsequently, the linearController choice becomes active.

variantCtrlVar = controllerTypesMfile.linearController;
sim(mdl);

Similarly, to activate the nonlinearController choice, set variantCtrlVar to


controllerTypesMfile.nonlinearController and simulate the model again.

variantCtrlVar = controllerTypesMfile.nonlinearController;
sim(mdl);

Additionally, you can simulate both the variants and plot their values using this script.

in(1:2) = Simulink.SimulationInput(mdl);
in(1) = in(1).setVariable('variantCtrlVar', controllerTypesMfile.linearController);
in(2) = in(2).setVariable('variantCtrlVar', controllerTypesMfile.nonlinearController);
out = sim(in);
figure;
plot(out(1).tout, out(1).yout)
hold on
plot(out(2).tout, out(2).yout)
xlabel('Time (seconds)')
ylabel('Data')

[13-Feb-2024 08:40:13] Running simulations...


[13-Feb-2024 08:40:14] Completed 1 of 2 simulation runs
[13-Feb-2024 08:40:14] Completed 2 of 2 simulation runs

12-203
12 Modeling Variant Systems

3. You can then add more variant choices to the Controller block by adding the variant choice
filenames to the enumeration class. Similarly, you can remove choices from the Controller block by
deleting the corresponding enumerated values from the enumeration class.

Define Dynamic Enumeration Class in Memory Using Simulink.defineIntEnumType

Create an enumeration class controllerTypesInMem in the MATLAB workspace using


Simulink.defineIntEnumType.

Simulink.defineIntEnumType('controllerTypesInMem', ...
{'linearController', 'nonlinearController'}, 0:1);

The enumeration section specifies the enumerated values linearController(0) and


nonlinearController(1). Each enumerated value consists of an enumerated member and an
underlying integer. Here, enumerated members are filenames of the variant choices
linearController and nonlinearController and the underlying integers are 0 and 1.

1. To configure the Controller block, set the Variant control variable parameter to
variantCtrlVar and the Variant choices enumeration parameter to controllerTypesInMem in
the Block Parameters dialog box.

set_param(vasBlkPath, 'VariantChoicesEnumeration', 'controllerTypesInMem')


set_param(vasBlkPath, 'VariantControlVariable', 'variantCtrlVar')

2. To activate the linearController choice, set variantCtrlVar to


controllerTypesInMem.linearController and then simulate the model. During simulation, the

12-204
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

variantCtrlVar == controllerTypesInMem.linearController expression evaluates to


true. Subsequently, the linearController choice becomes active.

variantCtrlVar = controllerTypesInMem.linearController;
sim(mdl);

Similarly, to activate the nonlinearController choice, set variantCtrlVar to


controllerTypesInMem.nonlinearController and simulate the model again.

variantCtrlVar = controllerTypesInMem.nonlinearController;
sim(mdl);

Additionally, you can simulate both the variants and plot their values using this script.

in(1:2) = Simulink.SimulationInput(mdl);
in(1) = in(1).setVariable('variantCtrlVar', controllerTypesInMem.linearController);
in(2) = in(2).setVariable('variantCtrlVar', controllerTypesInMem.nonlinearController);
out = sim(in);
plot(out(1).tout, out(1).yout)
hold on
plot(out(2).tout, out(2).yout)
xlabel('Time (seconds)')
ylabel('Data')

[13-Feb-2024 08:40:17] Running simulations...


[13-Feb-2024 08:40:17] Completed 1 of 2 simulation runs
[13-Feb-2024 08:40:18] Completed 2 of 2 simulation runs

12-205
12 Modeling Variant Systems

3. To add more variant choices to the Controller block, redefine the controllerTypesInMem
class with the new variant choice filenames as enumerated values. Similarly, to remove a choice,
redefine the class with the corresponding enumerated value removed.

Permanently Store the Enumeration Definition in a Simulink Data Dictionary

Create an enumeration class controllerTypesInDD and a variant control variable


variantCtrlVarInDD in the persistent repository data dictionary vas_controllersData.sldd.
The enumeration section specifies the enumerated values linearController(0) and
nonlinearController(1). Each enumerated value consists of an enumerated member and an
underlying integer. Here, enumerated names are filenames of the variant choices
linearController and nonlinearController and the underlying integers are 0 and 1. For more
information on data dictionaries, see “Permanently Store Enumerated Type Definition” on page 74-
10.

1. To configure the Controller block, set the Variant control variable parameter to
variantCtrlVarInDD and the Variant choices enumeration parameter to
controllerTypesInDD in the Block Parameters dialog box.

set_param(vasBlkPath, 'VariantChoicesEnumeration', 'controllerTypesInDD')


set_param(vasBlkPath, 'VariantControlVariable', 'variantCtrlVarInDD')

2. To activate the linearController choice, set variantCtrlVarInDD to


controllerTypesInDD.linearController and then simulate the model. During simulation, the
variantCtrlVarInDD == controllerTypesInDD.linearController expression evaluates to
true. Subsequently, the linearController choice becomes active.

vasDDObj = Simulink.data.dictionary.open('vas_controllersData.sldd');
dDataSectObj = getSection(vasDDObj, 'Design Data');
evalin(dDataSectObj, 'variantCtrlVarInDD = controllerTypesInDD.linearController;');
out1 = sim(mdl)

out1 =

Simulink.SimulationOutput:
tout: [1001x1 double]
yout: [1001x1 double]

SimulationMetadata: [1x1 Simulink.SimulationMetadata]


ErrorMessage: [0x0 char]

Similarly, to activate the nonlinearController choice, set variantCtrlVar to


controllerTypesInDD.nonlinearController and simulate the model again.

evalin(dDataSectObj, 'variantCtrlVarInDD = controllerTypesInDD.nonlinearController;');


out2 = sim(mdl)

out2 =

Simulink.SimulationOutput:
tout: [1001x1 double]
yout: [1001x1 double]

SimulationMetadata: [1x1 Simulink.SimulationMetadata]

12-206
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files

ErrorMessage: [0x0 char]

Additionally, you can simulate both the variants and plot their values using this script.

figure;
plot(out1.tout, out1.yout)
hold on
plot(out2.tout, out2.yout)
xlabel('Time (seconds)')
ylabel('Data')

3. You can then add more variant choices to the Controller block by adding the variant choice
filenames to the enumeration class. Similarly, you can remove choices from the Controller block by
deleting the corresponding enumerated values from the enumeration class.

Generate Code for Variant Subsystems


For an example on generating code, see “Generate Code for Variant Subsystem Blocks” (Simulink
Coder).

See Also
“Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter
Object” on page 12-208 | “Convert Variant Subsystem to Variant Assembly Subsystem” on page 12-
262

12-207
12 Modeling Variant Systems

Control Variant Choices in Masked Variant Assembly


Subsystem Block Using Mask Parameter Object
This section shows how to specify variant choices and set an active choice in a masked “Variant
Assembly Subsystem” block using a mask parameter object.

Switch Between Variant Choices of Masked Variant Assembly


Subsystem Block in Label Mode

In this example, you create one MATLAB® class per variant choice. To activate a variant choice, you
instantiate the corresponding class using a mask parameter object. You then access the class
property to get the names of the variant choices and to set a variant choice to be active.

Explore Model

Open the model slexVariantAssemblySubsystemWithMaskInLabel, which contains a masked


Variant Assembly Subsystem block, Controller.
open_system('slexVariantAssemblySubsystemWithMaskInLabel')

Define Classes for Reference Models

In this example, the vas_controller class is a superclass that includes a property and two
methods. The getVariantChoices method returns a cell array of variant choices to be added to the
Variant Assembly Subsystem block. From the list of choices, the setActiveVariant method sets the
choice, specified as subsystemFile, to be active.
type vas_controller.m

classdef (Abstract) vas_controller

12-208
Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter Object

properties
subsystemFile char
end
methods (Static)
function list = getVariantChoices()
list = {'linearController','nonlinearController'};
end
end

methods
function setActiveVariant(obj,blk)
set_param(blk,'LabelModeActiveChoice',obj.subsystemFile)
end
end
end

The two classes vas_linearController and vas_nonlinearController inherit from the


vas_controller superclass. The vas_linearController class stores the name of the active
choice as linearController in the inherited property subsystemFile. The class also stores
numerator and denominator values used in the Discrete Transfer Fcn block of the linearController
model.

type vas_linearController.m

classdef vas_linearController < vas_controller


properties
numerator
denominator
end

methods
function obj = vas_linearController()
obj.numerator = [1 .7];
obj.denominator = [1 .09 0.5];
obj.subsystemFile = 'linearController';
end
end
end

Similarly, the vas_nonlinearController class stores the name of the active choice as
nonlinearController in subsystemFile. The class also stores breakpoint and table values used
in the 1-D Lookup Table of the nonLinearController model.

type vas_nonlinearController.m

classdef vas_nonlinearController < vas_controller


properties
breakpoints
table
end

methods
function obj = vas_nonlinearController()
obj.breakpoints = -5:5;
obj.table = tanh(-5:5);
obj.subsystemFile = 'nonlinearController';

12-209
12 Modeling Variant Systems

end
end
end

Set Parameter Object Value in Parent Model

Double-click the Controller block to open the mask dialog box.

The value that you specify for vssObj in the mask dialog box is mapped to the mask parameter object
obj.

Using obj, you can instantiate the class vas_linearController or vas_nonlinearController.


You can then call its methods, getVariantChoices and setActiveVariant.

For example, to specify the variant choices of the Controller block, the “Variant choices specifier”
parameter in the Block Parameters dialog box is set to obj.getVariantChoices().

To set an active choice in the Variant Assembly Subsystem block, the obj.setActiveVariant()
method is used in its mask initialization code.

Set Active Choice by Instantiating Classes Using Mask Parameter Object

Case 1: linearController Is Active and nonlinearController Is Inactive

12-210
Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter Object

When you specify vssObj as vas_linearController, the value vas_linearController is


mapped to the mask parameter object obj. The Variant choices specifier parameter value
obj.getVariantChoices() evaluates to a cell array that contains the filenames
linearController and nonlinearController to be added as variant choices to the Controller
block. obj.setActiveVariant(gcb) in the mask initialization code sets the linearController
subsystem to be active.
vssObj = vas_linearController;
out = sim('slexVariantAssemblySubsystemWithMaskInLabel');
plot(out.tout, out.yout);
xlabel('Time (seconds)')
ylabel('data')

Case 2: linearController Is Inactive and nonlinearController Is Active

When you specify vssObj as vas_nonlinearController, the value vas_nonlinearController


is mapped to the mask parameter object obj. The Variant choices specifier parameter value
obj.getVariantChoices() evaluates to a cell array that contains the filenames
linearController and nonlinearController to be added as variant choices to the Controller
block. obj.setActiveVariant(gcb) in the mask initialization code sets the
nonlinearController subsystem to be active.
vssObj = vas_nonlinearController;
out = sim('slexVariantAssemblySubsystemWithMaskInLabel');
plot(out.tout, out.yout);
xlabel('Time (seconds)')
ylabel('data')

12-211
12 Modeling Variant Systems

See Also

“Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files” on page
12-195

Switch Between Variant Choices of Masked Variant Assembly


Subsystem Block in Expression Mode

In this example, you create one MATLAB™ class per variant choice. To activate a variant choice, you
instantiate the corresponding class using a mask parameter object. You then access the class
property to get the name of the variant file to be activated. Simulink® then compares the variant
filename to the variant choice names by evaluating the variant control expressions and activates the
variant choice for the expression that evaluates to true.

Explore Model

Open the model slexVariantAssemblySubsystemWithMaskInExpression, which contains a


masked Variant Assembly Subsystem block, Controller.

mdl = 'slexVariantAssemblySubsystemWithMaskInExpression';
open_system(mdl)

12-212
Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter Object

The Controller block has two Subsystem Reference choices, linearController and
nonlinearController. The choices are added to the Controller block using the
slexVasExprControllerTypes enumeration class. To add more choices, add members to
slexVasExprControllerTypes.

type slexVasExprControllerTypes.m

classdef slexVasExprControllerTypes < Simulink.IntEnumType


%

% Copyright 2023 The MathWorks, Inc.

enumeration
linearController(0)
nonlinearController(1)
end
end

Define Classes for Reference Models

In this example, the slexVasExprControllerVariant class is a superclass that includes a


property, variantFile, of enumerated type slexVasExprControllerTypes.

type slexVasExprControllerVariant.m

classdef (Abstract) slexVasExprControllerVariant


%

% Copyright 2023 The MathWorks, Inc.

properties
variantFile slexVasExprControllerTypes;
end
end

12-213
12 Modeling Variant Systems

The two classes slexVasExprLinearController and slexVasExprNonLinearController


inherits property from the slexVasExprController superclass. The
slexVasExprLinearController class represents the linearController variant. This class
stores the name of the active choice as linearController in the inherited property variantFile.
The class also stores numerator and denominator values used in the Discrete Transfer Fcn block of
the linearController model.
type slexVasExprLinearController.m

classdef slexVasExprLinearController < slexVasExprControllerVariant


%

% Copyright 2023 The MathWorks, Inc.

properties
numerator
denominator
end

methods
function obj = slexVasExprLinearController()
% Values for the properties of this variant
obj.numerator = [1 .7];
obj.denominator = [1 .09 0.5];
% Specify which subsystem file it corresponds to
obj.variantFile = 'linearController';
end
end
end

Similarly, the slexVasExprNonLinearController class represents the nonlinearController


variant. It stores the name of the active choice as nonlinearController in the inherited property
variantFile. This class stores breakpoint and table values used in the 1-D Lookup Table of the
nonLinearController model.
type slexVasExprNonLinearController.m

classdef slexVasExprNonLinearController < slexVasExprControllerVariant


%

% Copyright 2023 The MathWorks, Inc.

properties % parameters specific to this variant


breakpoints
table
end
methods
function obj = slexVasExprNonLinearController()
% values for the additional parameters
obj.breakpoints = -5:5;
obj.table = tanh(-5:5);
% and the file
obj.variantFile = 'nonlinearController';
end
end
end

12-214
Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter Object

Set Active Choice by Instantiating Classes Using Mask Parameter Object

In this example, the value that you specify for ctrlObj in the mask dialog box of the Controller
block is mapped to the mask parameter object obj. Using obj, you can instantiate the class
slexVasExpLinearController or slexVasExpNonLinearController. You can then access its
property, variantFile to get the filename of the variant choice to be activated.

Case 1: linearController Is Active and nonlinearController Is Inactive

When you specify ctrlObj as slexVasExprLinearController, the class


slexVasExprLinearController is instantiated. The class properties including variantFile are
initialized.

ctrlObj = slexVasExprLinearController;

During simulation, slexVasExprLinearController, the value of ctrlObj, is mapped to the mask


parameter object obj. The left side and the right side of the variant control expression
obj.variantFile == slexVasExprControllerTypes.linearController each resolve to
linearController. The expression evaluates to true and linearController becomes active.

sim(mdl);

Similarly, to set nonlinearController to be active, set ctrlObj to


slexVasExprNonLinearController.

ctrlObj = slexVasExprNonLinearController;
sim(mdl);

Optionally, you can plot the results for both the variant choices as shown:

in(1:2) = Simulink.SimulationInput(mdl);
in(1) = in(1).setVariable('ctrlObj',slexVasExprLinearController);
in(2) = in(2).setVariable('ctrlObj',slexVasExprNonLinearController);
out = sim(in);
figure
plot(out(1).tout, out(1).yout);
hold on
plot(out(2).tout, out(2).yout)
xlabel('Time (seconds)')
ylabel('Data')

12-215
12 Modeling Variant Systems

[13-Feb-2024 08:38:05] Running simulations...


[13-Feb-2024 08:38:06] Completed 1 of 2 simulation runs
[13-Feb-2024 08:38:06] Completed 2 of 2 simulation runs

See Also

“Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files” on page
12-195

12-216
Automatic Mask Icon Promotion in Variant Subsystems

Automatic Mask Icon Promotion in Variant Subsystems

This example demonstrates how Simulink® automatically displays the mask icon of the active variant
block on the parent Variant Subsystem block. The example shows mask icon promotion for these
types of icons:

• Plain text

• Plot

• Built-in icon

• Image

Explore the Model

Open the example model slexVariantSubsystemMaskIconPromotion.

• VSS 1: The mask icon on the active variant block is plain text.

12-217
12 Modeling Variant Systems

• VSS 2: The mask icon on the active variant block is a plot.

• VSS 3: The mask icon on the active variant block is a built-in icon.

• VSS 4: The mask icon on the active variant block is an image.

12-218
Automatic Mask Icon Promotion in Variant Subsystems

Simulate the Model to View Mask Icon Promotion

On the Simulation tab, click Run to see how the mask icon of the active choice gets promoted to the
parent subsystem.

12-219
12 Modeling Variant Systems

Prepare Variant-Containing Model for Code Generation


In this section...
“Convert Variant Control Variables into Simulink.Parameter Objects” on page 12-220
“Configure Model for Generating Preprocessor Conditionals” on page 12-221

Using Embedded Coder, you can generate code from Simulink models containing one or more variant
choices. The generated code contains preprocessor conditionals that control the activation of each
variant choice.

Note Simulink supports using multi-instance referenced models with variant Simulink Functions for
code generation.

For information on using STF_make_rtw_hook file to customize build process, see “Customize Build
Process with STF_make_rtw_hook File” (Simulink Coder).

Convert Variant Control Variables into Simulink.Parameter Objects


MATLAB variables allow you to rapidly prototype variant control expressions when you are building
your model and generate preprocessor conditionals for code generation. However, if you want to
specify other code generation attributes (such as data type), you can convert MATLAB variables into
Simulink.Parameter objects.

1 Specify the model in which you want to replace MATLAB variant control variables with
Simulink.Parameter objects.

model = 'my_model_containing_variant_choices';
open_system(model);
2 Get the variables that are referenced in variant control expressions.

vars = Simulink.VariantManager.findVariantControlVars(model)

vars =

4x1 struct array with fields:

Name
Value
Exists
Source
SourceType
3 Create an external header file for specifying variant control values so that the variable definitions
are imported when the code runs.
headerFileName = [model '_importedDefines.h'];
headerPreamble = strrep(upper(headerFileName),'.','_');

fid = fopen(headerFileName,'w+');
fidErr = (fid == -1);
if (fidErr)
fprintf('There was an error creating header file %s:\n',...
headerFileName);
else
fprintf('+++ Creating header file ''%s'' with variant control variable definitions.\n\n',...

12-220
Prepare Variant-Containing Model for Code Generation

headerFileName);
fprintf(fid, '#ifndef %s\n', headerPreamble);
fprintf(fid, '#define %s\n', headerPreamble);
end

Variant control variables defined as Simulink.Parameter objects can have one of these
storage classes.

• Define or ImportedDefine with header file specified


• CompilerFlag
• SystemConstant (AUTOSAR)
• Your own storage class that defines data as a macro

Note If you generate code with startup activation time, specify the supported custom storage
class for the objects. For more information on built-in and custom storage classes supported with
startup activation time see “Storage Classes for Different Variant Activation Times” on page 12-
103.
4 Loop through all the MATLAB variables to convert them into Simulink.Parameter objects.

count = 0;
for countVars = 1:length(vars)
var = vars(countVars).Name;
val = vars(countVars).Value;
if isa(val, 'Simulink.Parameter')
% Do nothing
continue;
end
count = count+1;

% Create and configure Simulink.Parameter objects


% corresponding to the control variable names.
% Specify the storage class as Define (Custom).
newVal = Simulink.Parameter(val);
newVal.DataType = 'int16';
newVal.CoderInfo.StorageClass = 'Custom';
newVal.CoderInfo.CustomStorageClass = 'Define (Custom)';
newVal.CoderInfo.CustomAttributes.HeaderFile = headerFileName;

Simulink.data.assigninGlobal(model, var, newVal);

if ~fidErr
fprintf(fid, '#endif\n');
fclose(fid);
end
end

Note The header file can be empty for the Define storage class.

Configure Model for Generating Preprocessor Conditionals


If you represent variant choices inside a Variant Subsystem block or a Variant Model block, code
generated for each variant choice is enclosed within C preprocessor conditionals #if, #else, #elif,
and #endif.

12-221
12 Modeling Variant Systems

If you represent variant choices using a Variant Source block or a Variant Sink block, code generated
for each variant choice is enclosed within C preprocessor conditionals #if and #endif.

Therefore, the active variant is selected at compile time and the preprocessor conditionals determine
which sections of the code to execute.

Note You must have an Embedded Coder license to generate code.

1 In the Modeling tab of the Simulink toolstrip, click Model Settings.


2 Select the Code Generation pane, and set System target file to ert.tlc.
3 In the Report pane, select Create code generation report.

Note In the Code Placement pane, if Compact option is selected from File packaging format
drop-down list, model_types.h file is not generated and contents of model_types.h file are
moved to model.h file.
4 Select the Code Generation pane, and clear Ignore custom storage classes and Apply.
5 In your model, right-click the block containing the variant choices (Variant Subsystem, Variant
Source, Variant Sink, or Variant Model block) and select Block Parameters.
6 Ensure that Expression (default option) is selected for Variant control mode parameter.
7 From the Variant activation time list, select code compile.

12-222
Prepare Variant-Containing Model for Code Generation

Simulink analyzes all variant choices during an update diagram or simulation. This analysis
provides early validation of the code generation readiness for all variant choices.
8 Build the model.

See Also

Related Examples
• “Compile Code Conditionally for Variations of Component Represented Using Variant Block”
(Simulink Coder)
• “Run Executables for Variant Blocks Without Recompiling Code for Changing Active Choices”
(Simulink Coder)
• “Generate Code from Nested Variant Subsystem with Code Compile and Startup Activation” on
page 12-225

More About
• “Generate Code for Variant Source and Variant Sink Blocks” (Simulink Coder)
• “Generate Code for Variant Subsystem Blocks” (Simulink Coder)

12-223
12 Modeling Variant Systems

• “Model AUTOSAR Variants” (AUTOSAR Blockset)


• Variant System Design

12-224
Generate Code from Nested Variant Subsystem with Code Compile and Startup Activation

Generate Code from Nested Variant Subsystem with Code


Compile and Startup Activation

This example illustrates how code compile and startup variant activation time can be used
together in two nested variant subsystems.

Model

Open the model slexNestedVSSWithCCAndST.slx. The model contains a Variant Subsystem block
Engine Controller with two choices Diesel Engine and Petrol Engine with the conditions
ENGINE_TYPE == 1 and ENGINE_TYPE == 2 respectively. The Variant activation time
parameter of the Engine Controller block is set to code compile.The two variants Diesel
Engine and Petrol Engine have startup as the Variant activation time parameter. Each
engine type has two choices Effficient Mode and Normal Mode. The Petrol Engine has the
conditions PMODE == 1 and PMODE == 2, and the Diesel Engine has the conditions DMODE == 1
and DMODE == 2. One of the engine types can be selected while building the generated code and one
of the controller modes can be selected before the start of execution of the code.

Both the variant subsystems have Propagate conditions outside of variant subsystem and Allow
zero active variant controls turned off. When these flags are turned on, this model will error out
during compilation as the conditions with code compile and startup variant activation time will
get mixed for the Inport and Outport blocks. For more information, see “Considerations and
Limitations for startup Variant Activation Time” on page 12-130

open_system('slexNestedVSSWithCCAndST.slx');

12-225
12 Modeling Variant Systems

Generate Code

Click on Generate Code Using Embedded Coder to generate code with ERT target. In the
generated code, you can see the variant conditions related to Engine Controller appear with the
preprocessor #if conditions and the conditions related to the mode appear as regular if.

12-226
Generate Code from Nested Variant Subsystem with Code Compile and Startup Activation

12-227
12 Modeling Variant Systems

The mix of code compile and startup variant activation times enables you to fine tune the variant
selection. In the generated executable, you can have either the Petrol Engine controller or the
Diesel Engine controller. At startup, you can decide if you want the Efficient Mode or the
Normal Mode of either Petrol Engine or Diesel Engine controllers. To do this, write a custom
code which can help to select different variants at startup activation time in the System
Initialize block. To select different variants, navigate to Model Settings > Code Generation >
Custom Code. Specify the Header file and Source file as #include
"ChangeDieselController.h" and ChangeDieselController.c respectively.

The ChangeDieselController.c is responsible for selecting the startup variant in the initialize
function.

#include "rtwtypes.h"
extern int32_T DMODE;
void ChangeDieselEngineController()
{
// select the diesel controller at startup.
// This is just an example, so the value is hard coded.
// In practical scenario, this can read value from sensor and
// decide which controller you want at startup.
DMODE = 1;
}

With the help of this code, you can select the startup variant in the model_initialize function and
generate code.

void slexNestedVSSWithCCAndST_initialize(void)
{
ChangeDieselEngineCOntroller();
utAssert((DMODE == 1) + (DMODE == 2) == 1);
utAssert((PMODE == 1) + (PMODE == 2) <= 1);
slexNestedVSSWithCCAndST_DW.systemEnable = 1;
}

12-228
Create Real-Time Applications Using Variants and Simulink Real-Time

Create Real-Time Applications Using Variants and Simulink


Real-Time

This example shows you how to create a real-time application with a variant subsystem by using the
Simulink® Real-Time™ workflow. Simulink Real-Time lets you create real-time applications from
Simulink models and run them on Speedgoat® target computer hardware connected to your physical
system.

To run a Simulink Real-Time model on a target computer, connect the development and target
computers in a network. For the steps, see “Set Up and Configure Simulink Real-Time” (Simulink
Real-Time).

Explore and Set Up Model

Open the model sldemo_variant_subsystems. The model contains a variant subsystem block
Controller with two choices, Linear Controller and Nonlinear Controller, and has the
conditions VSS_MODE == 1 and VSS_MODE == 2 respectively.

To create a real-time application:

1 In the Block Parameters dialog box, set the Variant activation time to startup.

2 Check that the Variant control expression is set to VSS_MODE == 1 for Linear Controller*
or VSS_MODE == 2 for Nonlinear Controller.

3 Create the variant parameter VSS_MODE as a Simulink.Parameter with a value of 1 and data
type of int32.
VSS_MODE = Simulink.Parameter(int32(1));

4 Set the storage class of VSS_MODE to ExportedGlobal.


VSS_MODE.CoderInfo.StorageClass = 'ExportedGlobal';

5 Change the variant choices to atomic.


open_system('sldemo_variant_subsystems');

12-229
12 Modeling Variant Systems

To provide information to Simulink Coder on how to build a real-time application from the model, set
the simulation and real-time run parameters in the Configuration Parameters dialog box. To open the
Configuration Parameters dialog box, on the Modeling tab, click Model Settings.

1 On the Solver pane, under Solver selection, from the Type list, select Fixed-step.

2 On the Code Generation pane, in the Target selection section, from the System target file list,
select an STF for a Simulink Real-Time model.This selection is required to build a real-time
application.

3 In the Optimization pane, select the Default parameter behaviour to Tunable.

4 On the Interface pane, under the Data exchange interface, clear the External mode check box.

The model is now ready to be used to build a standalone real-time application using the current
configuration parameter settings.

Create and Run Real-Time Application

Create the real-time application using the slbuild command. This generates the real-time
application MLDATX file.

slbuild('sldemo_variant_subsystems');

Open the Simulink Real-Time Explorer, using the slrtExplorer (Simulink Real-Time) command.

slrtExplorer

Load the real-time application sldemo_variant_subsystems.mldatx by clicking Load


Application. In slrtExplorer, you can:

1 View a hierarchical display of signals in the Signals tab. You can see all the signals available under
Signals available on target computer. Select the signal that you want to observe and add it to
Signals in Instrument.

12-230
Create Real-Time Applications Using Variants and Simulink Real-Time

2 Tune parameters in the Parameters tab. The value of the variant control variable VSS_MODE is set
to 2 by default, as this was the value specified at compile-time. Before starting the simulation, you
can choose to change the value to 1. This variable is set back to the default value at the end of the
simulation.

12-231
12 Modeling Variant Systems

3 Stream data to the Simulation Data Inspector. Run the real-time simulation. Open the Simulation
Data Inspector and observe the different results for VSS_MODE == 1 and VSS_MODE == 2.

NOTE: Check that you do not change the variant control value VSS_MODE while the simulation is
running. Simulink does not issue an error in case you change the variant control in between steps.

Output when VSS_MODE == 1

12-232
Create Real-Time Applications Using Variants and Simulink Real-Time

Output when VSS_MODE == 2

12-233
12 Modeling Variant Systems

See Also

• “Activate Variant During Different Stages of Simulation and Code Generation Workflow” on page
12-93
• “Create and Run Real-Time Application from Simulink Model” (Simulink Real-Time)
• Simulink Real-Time Explorer (Simulink Real-Time)

12-234
Create Standalone Executables with Variants Using Simulink Compiler

Create Standalone Executables with Variants Using Simulink


Compiler

This example shows you how to create a standalone executable with a Variant Subsystem using the
Simulink® Compiler™ workflow. You can use the same workflow for the Variant Source and Variant
Sink blocks as well. Set the Variant activation time of the Variant block to startup. With 'startup'
variant activation time, you can change the active variant via an input to the executable.

Simulink Compiler enables you to share Simulink simulations as standalone executables. You can
build the executables by packaging the compiled Simulink model and the MATLAB® code used to set
up, run, and analyze a simulation.

In this example you will:

1. Create and Deploy a Script with Simulink Compiler.

2. Write MATLAB app which can tune the variant control value externally.

Explore the Model

Open the model sldemo_variant_subsystems. The model contains a variant subsystem block
Controller with two choices Linear Controller and Nonlinear Controller with the
conditions VSS_MODE == 1 and VSS_MODE == 2 respectively.

Set the Variant activation time to startup in the Block Parameters dialog.

Create and Deploy a Script with Simulink Compiler

1. Write the script to deploy - Create a function called deployedScript. This code creates a
Simulink.SimulationInput object for the model. variantControl is the value that we pass
through the setVariable method for the tunable parameter VSS_MODE.

To configure the Simulink.SimulationInput object for deployment, use the function


simulink.compiler.configureForDeployment.This sets the simulation mode to Rapid
Accelerator.

12-235
12 Modeling Variant Systems

function deployedScript(variantControl)
in = Simulink.SimulationInput('sldemo_variant_subsystems');
in = in.setVariable('VSS_MODE',variantControl);
in = simulink.compiler.configureForDeployment(in);
out = sim(in);
plot(out.yout);
end

2. Compile Script for Deployment - Before compiling the script that you want to deploy, ensure that
the files for the model and script, in this case sldemo_variant_subsystems and the
deployedScript.m, are included on the MATLAB search path.

To compile the script, use the mcc command with the script name. For more information, see mcc
(MATLAB Compiler). This generates the stand alone application, deployedScript.exe, which you
can execute outside of MATLAB or Simulink.

mcc -m deployedScript.m

3. Run the Deployed Script - To run the deployed executable, you need an appropriate runtime
environment. To install the MATLAB Runtime, see https://www.mathworks.com/products/compiler/
matlab-runtime.html. You can run the deployed application only on the platform that the deployed
application was developed on. Run the deployed application, deployedScript.exe, from the
Windows command prompt.

To see the output for when the active variant choice is VSS_MODE = 1,

./run_deployedScript.exe 1

To see the output for when the active variant choice is VSS_MODE = 2,

./run_deployedScript.exe 2

12-236
Create Standalone Executables with Variants Using Simulink Compiler

Create the App in App Designer

You can write MATLAB app which can tune the variant control value externally. To learn more about
how to create an app using the App Designer, see App Designer and “Create and Run a Simple App
Using App Designer”.

1. Launch App Designer from the MATLAB command prompt.


appdesigner

2. Drag and drop a Edit Field and a push Button as shown below.

3. Write a callback function for the Simulate button.

12-237
12 Modeling Variant Systems

Callback function: SimulateButton, VariantControlVSS_MODEEditField


function SimpleButtonPushed(app, event)
in = Simulink.SimulationInput('sldemo_variant_subsystems');
in = in.setVariable('VSS_MODE',app.VariantControlVSS_MODEEditField.Value);
in = simulink.compiler.configureForDeployment(in);
out = sim(in);
ax = uiaxes;
plot(ax, out.yout);
end

4. Launch the app to tune the value of the variant control. Simulate with different values to see the
result.

See More

• Variant Subsystem, Variant Model, Variant Assembly Subsystem


• “Implement Variations in Separate Hierarchy Using Variant Subsystems” on page 12-48

12-238
Export and Import Function Mockup Unit (FMU) from Model with Variant Subsystem Blocks

Export and Import Function Mockup Unit (FMU) from Model


with Variant Subsystem Blocks

This example shows you how to export a standalone Functional Mock-up Unit (FMU) from a model
containing a Variant Subsystem block, then import it into a new model.

Explore and Export Model to Standalone FMU

1. Open the model slexVariantSubsystems. The model contains a variant subsystem block
Controller with two choices Linear Controller and Nonlinear Controller with the
conditions VSS_MODE == 1 and VSS_MODE == 2 respectively.
open_system('slexVariantSubsystems')

2. Set Variant activation time to startup in the Block Parameters dialog box of the Controller
block. Also, set the Linear Controller and Nonlinear Controller choices as atomic.
set_param('slexVariantSubsystems/Controller','VariantActivationTime', 'startup');
set_param('slexVariantSubsystems/Controller/Linear Controller', 'TreatAsAtomicUnit', 'on');
set_param('slexVariantSubsystems/Controller/Nonlinear Controller', 'TreatAsAtomicUnit', 'on');

3. Set the active choice to Nonlinear Controller by setting VSS_MODE to 2, then simulate the
model.
VSS_MODE = 2;
sim('slexVariantSubsystems');

4. To export the model to an FMU:

a. In the Simulation tab, click the Save drop-down.

b. In the Export Model To section, click Standalone FMU.....

c. In FMU Export dialog, specify the location to save the FMU to be generated.

d. Click Create to export to FMU.

12-239
12 Modeling Variant Systems

The generated FMU file, with the extension .fmu is at your specified location. You can now use this
FMU file in the FMU block.

Create Model with Standalone FMU

The FMU block lets you import your applications, contained in FMUs, into Simulink® to create a
model with a standalone FMU.

To create a standalone FMU:

1. Create a model and add an FMU block from the Simulink Extras/FMU Import library.

2. Specify the name of the generated FMU file in the FMU name parameter in the Block Parameters
dialog of the FMU block. The FMU block icon and port labels update to the labels of the
corresponding FMU. You now have a standalone FMU.

When you double-click the FMU block, the Parameters tab of the Block Parameters has the same
active choice as when you export the FMU, as the parameter VSS_MODE is equal to 2. You can change
the value of the active choice by changing VSS_MODE to 1.

12-240
Export and Import Function Mockup Unit (FMU) from Model with Variant Subsystem Blocks

See Also

• “Implement an FMU Block” on page 53-6


• “Import FMUs” on page 53-2

12-241
12 Modeling Variant Systems

Simulink Variant Examples

The slexVariantExamples model contains a set of conceptual examples that demonstrate


capabilities of Simulink® variants.

open_system('slexVariantExamples');

See Also

Related Examples
• “V-Model for System Development with Simulink Variants” on page 12-243

12-242
V-Model for System Development with Simulink Variants

V-Model for System Development with Simulink Variants


Simulink is often used to model systems that represent a product line. The systems in a product line,
although based on the same definition, can differ in several aspects. For example, consider a product
line of passenger cars where each variant has different set of features. Instead of designing multiple
models to represent all possible variants, you can use Simulink variants to model all the variations in
a product line in a single model. Simulink variant capabilities allow you to create flexible models with
built-in variabilities to more efficiently manage, configure, and reuse your designs. For information on
Simulink variants basics, see “What Are Variants and When to Use Them” on page 12-3.

The V-model represents a development process. The model demonstrates the relationship between
each phase of the development cycle on the left side and its associated validation phase on the right
side. Simulink variants supports the V-model development process by providing variant capabilities
from the System Level Model phase, down to Code Generation, and up to the Interaction and Test
phase. In the System Level Model and Component phases, you can use variant blocks and variant
parameters to capture structural and data variations. You can use the Variant Manager for Simulink
to prevent invalid variant combinations and reduce the variant model to contain only the selected
variants. The generated code contains the variations defined in the model and the components. In the
Test phases, you can use the Simulink Design Verifier to generate test cases to identify hidden design
errors and use Simulink Test to execute user-defined tests. Also, you can use Simulink Coverage to
get coverage for all variants.

Depending on your application and its role in the process, you might focus on one or more of the
steps called out in the V-model or repeat steps at several stages of the V-model.

These tables list goals that you might have as you apply variations in your model and guides you on
how to meet those goals. You can open and run the examples linked below to apply variants and
generate code. For a list of models that show variant capabilities in Simulink, see “Simulink Variant
Examples” on page 12-242.

• “System-Level Model” on page 12-244


• “Components — Create Models with Structural Variations” on page 12-244
• “Components — Create Models with Parameter Value Variations” on page 12-249
• “Components — Create Models with Variations in Transition Paths” on page 12-251
• “Components — Create Models with Variations in Dimensions” on page 12-251
• “Components — Create Models with Variations in AUTOSAR Interfaces” on page 12-252

12-243
12 Modeling Variant Systems

• “Components — Manage Structural Variations in a Model” on page 12-252


• “Generated Code” on page 12-253
• “Component Tests and System-Level Tests” on page 12-256

System-Level Model
You can model variations for any component in a system architecture model. A component may have
two or more than two variant options that represent alternate structural decompositions. You can also
define a mix of behaviors (defined in a Simulink model) and architectures (defined in a System
Composer architecture model) as variant choices. For more information on System Composer
architecture models, see “Compose Architectures Visually” (System Composer).

Goal Capability Example


Add components with Variant Component “Create Variants” (System
alternative structural designs in Composer)
architecture model.
Add or remove variant choices Variant Assembly Component “Add or Remove Variant Choices
without modifying the model. of Variant Assembly Component
Blocks Using External File”
(System Composer)
Manage systems with variations “Variant Manager for Simulink” “Manage, Configure, Reduce,
in structural components. and Analyze System Variants
with Variant Manager for
Simulink” on page 89-95

Components — Create Models with Structural Variations


Once you understand your modeling requirements, you can begin to identify the varying components
of the system. Identifying components and their relationships within a top-level structure help build a
potentially complex model systematically. With variant blocks in Simulink you can design multiple
design alternatives of a system in a single model. Each design choice is incorporated into the model
as a variant choice. You can choose to activate or deactivate the variant choices as per your
requirement during simulation. For more information, see “What Are Variants and When to Use
Them” on page 12-3.

This section covers:

• “Implement Structural Variabilities for Components” on page 12-244


• “Propagate Conditions from Variant Blocks Upstream and Downstream” on page 12-246
• “Control Visibility of Variant Regions” on page 12-247
• “Variant Controls in Structurally Varying Systems” on page 12-248
• “Control Variant Activation Times of Structurally Varying Systems” on page 12-248

Implement Structural Variabilities for Components

You can implement structural variabilities in all domains, including controls logic, state machines,
flow charts, and physical plants by using variant blocks in your model. For more information on
variant blocks, see “Variant Blocks in Simulink” on page 12-6.

12-244
V-Model for System Development with Simulink Variants

Goal Capability Example


Encapsulate variations of a Variant Subsystem, Variant “Implement Variations in
component in a separate in your Model Separate Hierarchy Using
model. You can encapsulate Variant Subsystems” on page
subsystem (virtual and non- 12-48
virtual) blocks, model blocks,
and subsystem reference blocks
to conditionally execute them.
• Represent all variations of a Variant Source and Variant Sink • Variant Source and Variant
component at the same level Sink Blocks in Car Wiper
in your model. Motor Skeleton (Model:
• Represent components with slexVariantWiper)
variations in source or • “Variant Source and Variant
destination signals. Sink Blocks” on page 12-150
Represent components that Variant Subsystem, Variant “Adaptive Interface for Variant
have a fixed common structure, Model Subsystems” on page 12-141
but varying input and output
interfaces.
Represent variations at the Manual Variant Source and “Provide Variation in Signal
same level in your model and Manual Variant Sink Source and Destination Using
toggle between the variant Manual Variant Source and
choices using a simple toggle Manual Variant Sink Blocks” on
switch mechanism. page 12-43
Conditionally execute event- Initialize Function, Reset “Conditionally Execute Custom
driven functions on a model Function, and Terminate Initialize, Reinitialize, Reset,
initialize, reset, and terminate Function and Terminate Routines” on
events. page 12-173
Conditionally execute trigger- Enabled Subsystem, Triggered “Propagate Variant Conditions
driven functions (execution is Subsystem, Enabled and to Control Execution of
controlled by external signal). Triggered Subsystem, and Conditional Subsystems” on
“Using Function-Call page 12-162
Subsystems” on page 10-53
Conditionally execute Simulink Simulink Function “Conditionally Execute Simulink
functions (analogous to a Functions” on page 12-176
function in procedural
programming language).
Encapsulate Simulink models or Variant Subsystem, Variant “Propagate Variant Conditions
subsystem files as variant Model to Enable or Disable Model or
choices and execute them Subsystem References in
conditionally. Hierarchy” on page 12-170
Add or remove variant choices Variant Assembly Subsystem “Add or Remove Variant Choices
without modifying the model. of Variant Assembly Subsystem
Blocks Using External Files” on
page 12-195

12-245
12 Modeling Variant Systems

Goal Capability Example


Implement variations in real Variant Connector • “Model Variants in a
physical components. Mechanical System Using
Variant Connector Blocks”
(Simscape)
• “Model Variants in an
Electrical Circuit Using
Variant Connector Blocks”
(Simscape)
• Active variant is fixed before “Use label Mode in Variant “Switch Between Choices Using
the simulation starts and Blocks” on page 12-71 Labels in Variant Blocks” on
does not change during page 12-71
intermediate stage of
simulation.
• Switch between active
variants using strings with
minimal data management.
Create branches in your model “Use sim codegen switching “Switch Between Choices for
that apply only to simulation or Mode in Variant Blocks” on page Simulation and Code Generation
only to code generation. 12-73 Workflows Without Using
Control Variables in Variant
Blocks” on page 12-73

Propagate Conditions from Variant Blocks Upstream and Downstream

You can expand the variability control to any region of your model by automatically propagating
variant conditions from variant blocks to other blocks upstream and downstream. Variant conditions
can propagate through signal lines, buses, and function calls to reach blocks in a model affected by
variant selection. For more information, see “Propagate Variant Conditions to Define Variant Regions
with Variant Blocks” on page 12-133.

Goal Capability Example


Improve accuracy of the model Variant Subsystem, Variant “Propagate Variant Conditions
and avoid manual computation Model to Define Variant Regions
of variant conditions to assign to Outside Variant Subsystems” on
the dependent blocks by page 12-140
propagating the state of the
underlying blocks outside of the
parent variant block.
Improve accuracy of the model • Variant Source “Propagate Variant Conditions
and avoid manual computation • Variant Sink to Define Variant Regions Using
of variant conditions to assign to Variant Source and Variant Sink
the dependent blocks by Blocks” on page 12-150
propagating the state of the
variant blocks to all its
connected blocks.

12-246
V-Model for System Development with Simulink Variants

Goal Capability Example


Remove variant region “Allow zero active variant “Propagate Variant Conditions
completely from model controls” to Define Variant Regions
execution when no variant is Outside Variant Subsystems” on
active. page 12-140
Reduce visual complexity by • Group Signal Lines into • “Variant Elements Within
propagating variant elements in Virtual Buses Buses” on page 12-155
composite signals. • Simscape Bus • “Variant Connector Block
with Simscape Bus Block”
(Simscape)

Control Visibility of Variant Regions

You can control the visibility of variant regions by defining the variant control in appropriate
workspaces as per your requirement. Limiting the scope helps avoid name conflicts and establish
clear ownership of the variant controls between the blocks. It also enables you to use same names for
variant controls in different scopes. For more information, see “Storage Locations for Variant Control
Variables (Operands) in Variant Blocks” on page 12-67 and “Types of Operators in Variant Blocks for
Different Activation Times” on page 12-68.

Goal Capability Example


• Create custom user interface “Masking Fundamentals” on • “Approaches to Control
for variants. page 43-3 Active Variant Choice of a
• Prevent unintended Variant Block Using Mask or
modification of variant Model Workspace” on page
controls by encapsulating it 12-178
behind a mask. • “Mask Workspace Variable in
• Use same names for variant Variant Connector Block”
controls in different masks (Simscape)
by limiting the scope of • “Control Variant Choices in
controls. Masked Variant Assembly
Subsystem Block Using Mask
Parameter Object” on page
12-208
• Improve model portability by “Local Data: Model Workspace” “Approaches to Control Active
permanently storing variant on page 73-111 Variant Choice of a Variant
controls that is local to the Block Using Mask or Model
model. Workspace” on page 12-178
• Use same names for variant
controls in different models
by limiting the scope of
controls.
Store global variant controls. • “What Is a Data Dictionary?” “Create a Simple Variant Model”
on page 80-2 on page 12-45
• “Temporary Data: Base
Workspace” on page 73-111

12-247
12 Modeling Variant Systems

Goal Capability Example


Set different active variants for “Approaches to Control Active “Control Active Choice of
multiple instances of custom Variant Choice of a Variant Locked Custom Library Variant
locked library block. Block Using Mask or Model Subsystem Using Mask
Workspace” on page 12-178 Parameter” on page 12-192
Define global variant controls Data Store Memory Variant Conditions and Data
for multiple variant regions at Stores (Model:
different levels of a model. slexVariantDataStores)

Variant Controls in Structurally Varying Systems

Each variant choice in your model is associated with a variant control. Variant controls determine
which variant choice is active. By changing the value of a variant control, you can switch the active
variant choice. You can use different types of variant controls variables while implementing variant
regions in your model. For more information, see “Types of Variant Control Variables (Operands) in
Variant Blocks” on page 12-66 and “Storage Locations for Variant Control Variables (Operands) in
Variant Blocks” on page 12-67.

Goal Capability Example


Switch variant choices in Simulink.VariantControl “Simulink.VariantControl
related blocks and parameters Variables for Coherent
coherently. Switching of Choices in Variant
Blocks” on page 12-78
Rapidly prototype variant Scalar variable “Scalar Variant Control
controls when you are still Variables for Rapid Prototyping
building your model. in Variant Blocks” on page 12-80
Reduce complexity of variant Simulink.Variant “Simulink.VariantExpression
controls by encapsulating them. Objects for Variant Condition
Reuse of Variant Blocks” on
page 12-86
Improve readability by “Simulink Enumerations” on “Represent Variant Conditions
representing variant controls as page 74-2 of Enumerated Type in
meaningful names instead of Generated Code” (Simulink
integers. Coder)
Improve readability by grouping struct “Structures to Group Related
related variant controls in a Variant Control Variables of
structure. Variant Blocks” on page 12-87

Control Variant Activation Times of Structurally Varying Systems

Prior to simulation or code generation, you can check for incompatibilities, such as datatype and
dimension mismatches in variants. You can design variants that can be activated in different stages of
simulation and code generation workflows. During code generation, you can choose which
variabilities to include in the generated code and activate them at different stages based on the
requirements and the target platform. You can also check for incompatibilities, such as datatype and
dimension mismatches in variants. For more information, see “Activate Variant During Different
Stages of Simulation and Code Generation Workflow” on page 12-93.

12-248
V-Model for System Development with Simulink Variants

Goal Capability Example


Retain active variant and “update diagram” on page 12-95 Consider a scenario where you
remove inactive variant early in want to simulate only the active
the model compilation stage, so variant. You have installed all
that, the variants with the products required to
incompatible signal attributes simulate the active variant, but
coexist in the simulation you do not have licenses that
workflow. are required to simulate inactive
variants. In this case, you can
use update diagram
activation time to remove
inactive variants from execution
at the beginning of the
simulation workflow.
Analyze active and inactive “update diagram analyze all “Activate Variant During
variants for incompatibilities in choices” on page 12-95 Different Stages of Simulation
signal attributes such as and Code Generation Workflow”
dimension and data type prior to on page 12-93
the simulation-loop stage.
Perform iterative simulations “startup” on page 12-96 • “Run Iterative Simulations
and enhance simulation speed Without Recompiling Model
without having to recompile the for Variant Systems Using
model or terminating the Fast Restart” on page 12-118
simulation each time you • “Simulate Variant Blocks in
change the active variant. Accelerator and Rapid
Accelerator Modes with
Startup Activation Time” on
page 12-116

Components — Create Models with Parameter Value Variations


You may have a set of requirements where the structure of the model remains the same, but the
values of the parameters for each requirement are different. You can create a single model with fixed
structure and create parameters with a finite set of values where each value corresponds to different
requirements. You can then choose to activate or deactivate the variant choices during simulation.
For more information on value variations, see “Use Variant Parameters to Reuse Block Parameters
with Different Values” on page 90-2.

This section covers:

• “Implement Variabilities in Parameter Values” on page 12-249


• “Variant Controls for Varying Parameter Values” on page 12-250
• “Control Variant Activation Times of Varying Parameter Values” on page 12-250

Implement Variabilities in Parameter Values

You can implement value variabilities in all domains, including controls logic, state machines, flow
charts, and physical plants by using variant parameters in your model.

12-249
12 Modeling Variant Systems

Goal Capability Example


Design variants in block “Use Variant Parameters to “Create a Simple Variant
parameter values Reuse Block Parameters with Parameter Model” on page 90-
Different Values” on page 90- 5
2
Create parameters with variants Allow symbolic dimension “Compile Code Conditionally for
having different dimensions. specification All Values of Variant Parameters
with Same and Different
Dimensions” on page 90-29

Variant Controls for Varying Parameter Values

Variant controls are Simulink.VariantControl objects that associates the Value of a variant
control with an ActivationTime. Use the variant control objects to determine the active value of a
variant parameter during different stages of simulation and code generation workflow. You can
specify different types of values for variant control objects while implementing variant regions in your
model. For more information, see “Storage Locations for Variant Control Variables (Operands) in
Variant Parameters” on page 90-15 and “Types of Variant Control Variables (Operands) in Variant
Parameters” on page 90-14.

Goal Capability Example


Rapidly prototype variant Numeric values “Numeric Variant Control Values
controls when you are still for Rapid Prototyping of Variant
building your model. Parameters” on page 90-18
• Reuse common variant Simulink.Variant “Simulink.VariantExpression
controls across models. Objects for Variant Condition
• Reduce complexity of variant Reuse of Variant Parameters” on
controls by encapsulating page 90-26
them.
Improve readability by “Simulink Enumerations” on “Enumerated Types to Improve
representing variant controls as page 74-2 Code Readability of Variant
meaningful names instead of Control Variables of Variant
integers. Parameters” on page 90-23
Improve readability by “Simulink Enumerations” on “Improve Code Readability of
representing variant parameter page 74-2 Variant Parameters Using
values as meaningful names Enumerated Types” on page 90-
instead of integers. 42

Control Variant Activation Times of Varying Parameter Values

Prior to simulation or code generation, you can check for incompatibilities, such as datatype and
dimension mismatches in variants. You can design variants that can be activated in different stages of
simulation and code generation workflows. During code generation, you can choose which
variabilities to include in the generated code and activate them at different stages based on the
requirements and the target platform. You can also check for incompatibilities, such as datatype and
dimension mismatches in variants. For more information, see “Activate Variant During Different
Stages of Simulation and Code Generation Workflow” on page 12-93.

12-250
V-Model for System Development with Simulink Variants

Goal Capability Example


Retain active variant and “update diagram” on page 12-95 “Change Active Values and
remove inactive variant early in Activation Time of Variant
the model compilation stage, so Parameters” on page 90-10
that, the variants with
incompatible signal attributes
coexist in the simulation
workflow.
Analyze active and inactive “update diagram analyze all
variants for incompatibilities in choices” on page 12-95
signal attributes such as
dimension and data type prior to
the simulation-loop stage.
Perform iterative simulations “startup” on page 12-96 “Run Iterative Simulations
without having to recompile the Without Recompiling Model for
model or terminating the Variant Systems Using Fast
simulation each time you Restart” on page 12-118
change the active variant.

Components — Create Models with Variations in Transition Paths


You can control the transition to multiple design configurations within the Stateflow charts using
variant transitions.

Goal Capability Example


Conditionally execute transition “Conditions” (Stateflow) “Control Indicator Lamp
path from source object to and“Condition Actions” Dimmer Using Variant
destination object. (Stateflow) Conditions” (Stateflow)

Components — Create Models with Variations in Dimensions


You can use symbolic dimensions to simulate various sets of dimension choices without regenerating
code for every set. These symbols propagate throughout the model during simulation, and then go
into the generated code.

Goal Capability Example


Store dimensions in symbols to Allow symbolic dimension “Generate Code for Variant
flexibly switch between variant specification Subsystem with Child
choices. Subsystems of Different Output
Signal Dimensions” (Embedded
Coder)
Create parameters with variants “Symbolic Dimensions in “Compile Code Conditionally for
having different dimensions. Generated Code” (Simulink All Values of Variant Parameters
Coder) with Same and Different
Dimensions” on page 90-29

12-251
12 Modeling Variant Systems

Components — Create Models with Variations in AUTOSAR Interfaces


You can enable or disable AUTOSAR interfaces or implementations in the execution path using
variation points in AUTOSAR software components. In Simulink, AUTOSAR system constants serve as
inputs to control component variation points. Variation points present a choice between two or more
variants. For more information, see “Model AUTOSAR Variants” (AUTOSAR Blockset).

Goal Capability Example


Enable or disable AUTOSAR “Variants for Ports and “Configure Variants for
ports and runnables. Runnables” (AUTOSAR AUTOSAR Elements”
Blockset) (AUTOSAR Blockset)
Vary implementation of “Variants for Runnable “Configure Variants for
AUTOSAR runnable by Implementations” (AUTOSAR AUTOSAR Runnable
specifying variant conditions Blockset) Implementations” (AUTOSAR
inside the runnable. Blockset)
Model AUTOSAR calibration “Export Variation Points for AUTOSAR Calibration Data”
data in combination with (AUTOSAR Blockset)
different types of variant
conditions.
Import variation points in “Predefined Variants and “Control AUTOSAR Variants
AUTOSAR software System Constant Value Sets” with Predefined Value
components. (AUTOSAR Blockset) Combinations” (AUTOSAR
Blockset)
Store dimensions of AUTOSAR “Variants for Array Sizes” “Configure Dimension Variants
elements, such as a ports, in (AUTOSAR Blockset) for AUTOSAR Array Sizes”
symbols to flexibly switch (AUTOSAR Blockset)
between variation points during
code compilation.
Flexibly switch between “Configure Postbuild Variant Conditions for AUTOSAR Software
AUTOSAR components after the Components” (AUTOSAR Blockset)
code is compiled and deployed
on an electronic control unit
(ECU).
Flexibly switch between value “Configure Variant Parameter Values for AUTOSAR Elements”
combinations for AUTOSAR (AUTOSAR Blockset)
elements prior to code compile,
or after the code is compiled
and deployed on an ECU.

Components — Manage Structural Variations in a Model


Variant Manager enables you to visually trace variations, manage variabilities simultaneously, and
prevent invalid variant combinations in a system model or variant transitions in a Stateflow chart. You
can also simplify a variant model by automatically reducing it to contain only the selected variants.
For more information, see “Variant Manager for Simulink”.

12-252
V-Model for System Development with Simulink Variants

Goal Capability Example


Visualize a tree view of a variant “Manage Variant Elements”
model hierarchy and edit
properties of variant elements.
Create Variant Configurations to “Variant Manager for Simulink” “Create and Activate Variant
represent combinations of Configurations” on page 89-10
variant choices across a model
hierarchy.
Define constraints for variant “Constraints on Variant “Define Constraints for Variant
configurations to prevent invalid Configurations” on page 89-3 Configurations” on page 89-15
variant combinations.
Create a variant configuration “Variant Configuration Data “Save and Reuse Variant
data object to store, distribute, Object” on page 89-3 Configurations Using Variant
and reuse variant configurations Configuration Data Object” on
for a model. page 89-34
Validate and apply a variant “Activate a Variant “Create and Activate Variant
configuration to a model early in Configuration” on page 89-5 Configurations” on page 89-10
the update diagram stage.
Automatically generate a “Reduce Variant Models Using “Reduce Model Containing
reduced model that contains Variant Reducer” on page 89- Variant Blocks” on page 89-61
only selected variant 44
configurations from a parent
model with many variants.
Visualize and compare variant “Analyze Variant Configurations in Models Containing Variant
configurations to locate and Blocks” on page 89-77
diagnose potential faults or
inconsistencies in the
configurations.
Run single or multiple “Run Simulations “Run Simulations for Variant
simulations programmatically Programmatically” on page 28- Models Using Variant
for models that have variant 2 Configurations” on page 89-104
configurations defined.

Generated Code
You can include variabilities in generated code to reuse and configure the code for different stages of
development, such as testing different implementations or providing multifunctional code to third
parties.

Generate Code for Structurally Varying Systems

You can specify the variabilities of the variant blocks to be included in the generated code. You can
also control the appearance, placement, definition, and declaration of variant controls in the
generated code.

12-253
12 Modeling Variant Systems

Goal Capability Example


Generate a code that contains “code compile” on page 12-96 “Compile Code Conditionally for
active and inactive variants, and Variations of Component
enables you to switch between Represented Using Variant
the variants prior to code Block” (Simulink Coder)
compile.
Generate an executable that “startup” on page 12-96 • “Run Executables for Variant
contains active and inactive Blocks Without Recompiling
variants, and enables you to Code for Changing Active
switch between the variants at Choices” (Simulink Coder)
model startup. • “Create Standalone
Executables with Variants
Using Simulink Compiler” on
page 12-235
• “Variant Subsystem: Using
Variant Subsystems for HDL
Code Generation” (HDL
Coder)
Share variant controls among Simulink.Parameter “Use Simulink.Parameter Type
multiple blocks, separate values of Variant Control Variables for
from their data types and other Code Generation in Variant
properties, control the Blocks” (Simulink Coder)
appearance, placement,
definition, and declaration of
variant controls in the
generated code.
Improve code readability by “Simulink Enumerations” on • “Represent Variant
representing variant controls as page 74-2 Conditions of Enumerated
meaningful names instead of Type in Generated Code”
integers in generated code. (Simulink Coder)
• Variant Subsystems -
Enumerations (Model:
sldemo_variant_subsyst
ems_enum)

Generate Code for Varying Parameter Values

You can specify the variabilities of the variant parameters to be included in the generated code. You
can also control the appearance, placement, definition, and declaration of variant controls and variant
parameters in the generated code. For more information, see “Options to Represent Variant
Parameters in Generated Code” (Embedded Coder).

Goal Capability Example


Generate a code that contains “code compile” on page 12-96 “Compile Code Conditionally for
all variants and enables you to All Values of Variant Parameters
switch between the variants with Same and Different
prior to code compile. Dimensions” on page 90-29

12-254
V-Model for System Development with Simulink Variants

Goal Capability Example


Generate an executable that “startup” on page 12-96 “Run Executable for Different
contains all variants and Variant Parameter Values
enables you to switch between Without Recompiling Code” on
the variants at model startup. page 90-35
Generate code that groups Simulink.VariantBank “Group Variant Parameter
variant parameters with the Values and Conditionally Switch
same variant conditions into a Active Value Sets in Generated
structure called variant Code” on page 90-50
parameter bank and uses a
pointer variable to switch the
set of active parameter values.
Specify code generation Simulink.VariantBankCode “Group Variant Parameter
properties for a variant rInfo Values and Conditionally Switch
parameter bank. Active Value Sets in Generated
Code” on page 90-50
Share variant controls among • Simulink.Parameter “Simulink.Parameter Type of
multiple blocks, separate values • “Storage Classes for Variant Control Variables for
from their data types and other Different Variant Activation Code Generation of Variant
properties, control the Times” on page 12-103 Parameters” on page 90-20
appearance, placement,
definition, and declaration of
variant controls in the
generated code.
Improve code readability by “Simulink Enumerations” on “Enumerated Types to Improve
representing variant controls as page 74-2 Code Readability of Variant
meaningful names instead of Control Variables of Variant
integers. Parameters” on page 90-23
Improve code readability by “Simulink Enumerations” on “Improve Code Readability of
representing variant parameter page 74-2 Variant Parameters Using
values as meaningful names Enumerated Types” on page 90-
instead of integers. 42

Generate Code for Varying Transition Paths

You can use variant transitions to create Stateflow charts in Simulink models that generate code to be
used in a variety of different software situations. Variant transitions allow you to model a full subset
of variations within one Stateflow chart so that you can choose which variation you want when you
generate code or when you compile the generated code.

Goal Capability Example


Generate code that only “Generate C or C++ Code from “Control Indicator Lamp
contains the data members Stateflow Blocks” (Stateflow) Dimmer Using Variant
needed to execute the currently Conditions” (Stateflow)
selected software configuration.

12-255
12 Modeling Variant Systems

Generate Code for Varying Dimensions

You can use symbolic dimensions to simulate various sets of dimension choices without regenerating
code for every set. These symbols propagate throughout the model during simulation, and then go
into the generated code.

Goal Capability Example


Store dimensions in symbols to Allow symbolic dimension “Generate Code for Variant
flexibly switch between variants specification Subsystem with Child
during code compilation. Subsystems of Different Output
Signal Dimensions” (Simulink
Coder)
Store dimensions in “Symbolic Dimensions in “Compile Code Conditionally for
automatically generated Generated Code” (Simulink All Values of Variant Parameters
symbols to flexibly switch Coder) with Same and Different
between variant parameter Dimensions” on page 90-29
values during code compilation.
Store dimensions of AUTOSAR “Variants for Array Sizes” “Configure Dimension Variants
elements, such as a ports, in (AUTOSAR Blockset) for AUTOSAR Array Sizes”
symbols to flexibly switch (AUTOSAR Blockset)
between variation points during
code compilation.

Component Tests and System-Level Tests


You can identify hidden design errors and detect model constructs in variants that result in integer
overflow, dead logic, array access violations, and division by zero by generating test cases using
Simulink Design Verifier. For more information, see “About Systematic Model Verification Using
Simulink Design Verifier” (Simulink Design Verifier).

You can further execute user-defined tests on both active and inactive variants in a model by using
Simulink Test. If your model has variant configurations defined using Variant Manager for Simulink,
you can use the configurations to run tests programmatically for variant paths in the model.

Goal Capability Example


Analyze active variant to detect “code compile” on page 12-96 See SLDV Run workflow in
design errors and requirement “Verify and Validate Variant
violations by generating test Models with Code Compile
cases for debugging. Activation Time” on page 12-
105
Analyze active and inactive “startup” on page 12-96 See SLDV Run workflow in
variants to detect design errors “Verify and Validate Variant
and requirement violations by Models with Startup Activation
generating test cases for Time” on page 12-124
debugging.

12-256
V-Model for System Development with Simulink Variants

Goal Capability Example


Analyze only active variant and “code compile” on page 12-96 See Simulink Test Manager
re-run the tests to analyze all workflow in “Verify and Validate
variants. Variant Models with Code
Compile Activation Time” on
page 12-105
Run iterative tests on active and “startup” on page 12-96 See Simulink Test Manager
inactive variants without workflow in “Verify and Validate
recompiling the model for each Variant Models with Startup
variant. Activation Time” on page 12-
124
Run iterative tests “Create and Run Test Case “Run Tests for Variant Models
programmatically for models Iterations” (Simulink Test) Using Variant Configurations”
that have defined variant on page 89-106
configurations

See Also

Related Examples
• “Simulink Variant Examples” on page 12-242

12-257
12 Modeling Variant Systems

Use find_system with Built-In MatchFilter Options for Variant


Blocks

This example compares the pre-compile and post-compile time results when using the find_system
function with the built-in “MatchFilter” functions. These filters help to find variant blocks that are
active in simulation or part of the generated code:

• Simulink.match.activeVariants
• Simulink.match.codeCompileVariants

Open the model sldemo_variant_subsystems.

model="sldemo_variant_subsystems";
open_system(model);

Before Model Compilation

Using the built-in match filters before compiling the model returns all blocks in the model,
irrespective of their variant activeness.

find_system(model,[email protected])

ans = 26x1 cell


{'sldemo_variant_subsystems' }
{'sldemo_variant_subsystems/Controller' }
{'sldemo_variant_subsystems/Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Discrete...' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/1-D Lookup Table'}
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Out1' }
{'sldemo_variant_subsystems/More Info' }
{'sldemo_variant_subsystems/Scope' }
{'sldemo_variant_subsystems/sine1' }
{'sldemo_variant_subsystems/sine2' }
{'sldemo_variant_subsystems/sine3' }
{'sldemo_variant_subsystems/Out1' }

find_system(model,[email protected])

ans = 26x1 cell


{'sldemo_variant_subsystems' }

12-258
Use find_system with Built-In MatchFilter Options for Variant Blocks

{'sldemo_variant_subsystems/Controller' }
{'sldemo_variant_subsystems/Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Discrete...' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/1-D Lookup Table'}
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Out1' }
{'sldemo_variant_subsystems/More Info' }
{'sldemo_variant_subsystems/Scope' }
{'sldemo_variant_subsystems/sine1' }
{'sldemo_variant_subsystems/sine2' }
{'sldemo_variant_subsystems/sine3' }
{'sldemo_variant_subsystems/Out1' }

After Model Compilation

Compile the model.

set_param(model,"SimulationCommand","update");

Using the Simulink.match.activeVariants filter returns the blocks that are active in simulation.

find_system(model,[email protected])

ans = 19x1 cell


{'sldemo_variant_subsystems' }
{'sldemo_variant_subsystems/Controller' }
{'sldemo_variant_subsystems/Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/1-D Lookup Table'}
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Out1' }
{'sldemo_variant_subsystems/More Info' }
{'sldemo_variant_subsystems/Scope' }
{'sldemo_variant_subsystems/sine1' }
{'sldemo_variant_subsystems/sine2' }
{'sldemo_variant_subsystems/sine3' }
{'sldemo_variant_subsystems/Out1' }

12-259
12 Modeling Variant Systems

Using the Simulink.match.codeCompileVariants filter returns the blocks that are part of the
generated C code.

sldemo_variant_subsystems([],[],[],"compileForCodegen");
sldemo_variant_subsystems([],[],[],"term");
find_system("sldemo_variant_subsystems",[email protected])

ans = 19x1 cell


{'sldemo_variant_subsystems' }
{'sldemo_variant_subsystems/Controller' }
{'sldemo_variant_subsystems/Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/1-D Lookup Table'}
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Out1' }
{'sldemo_variant_subsystems/More Info' }
{'sldemo_variant_subsystems/Scope' }
{'sldemo_variant_subsystems/sine1' }
{'sldemo_variant_subsystems/sine2' }
{'sldemo_variant_subsystems/sine3' }
{'sldemo_variant_subsystems/Out1' }

Find All Blocks Irrespective of Block Activeness

Use the Simulink.match.allVariants() filter to find all blocks irrespective of whether the block
is active or inactive due to variants.

find_system(model,[email protected])

ans = 26x1 cell


{'sldemo_variant_subsystems' }
{'sldemo_variant_subsystems/Controller' }
{'sldemo_variant_subsystems/Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Linear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Discrete...' }
{'sldemo_variant_subsystems/Controller/Linear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor1' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor2' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/sensor3' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/1-D Lookup Table'}
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Add' }
{'sldemo_variant_subsystems/Controller/Nonlinear Controller/Out1' }
{'sldemo_variant_subsystems/Controller/Out1' }
{'sldemo_variant_subsystems/More Info' }

12-260
Use find_system with Built-In MatchFilter Options for Variant Blocks

{'sldemo_variant_subsystems/Scope' }
{'sldemo_variant_subsystems/sine1' }
{'sldemo_variant_subsystems/sine2' }
{'sldemo_variant_subsystems/sine3' }
{'sldemo_variant_subsystems/Out1' }

See Also

find_system

12-261
12 Modeling Variant Systems

Convert Variant Subsystem to Variant Assembly Subsystem


A “Variant Assembly Subsystem” block enables you to add or remove its variant choices from external
sources without modifying the model. The Variant Assembly Subsystem block can contain Model
blocks, “Create and Use Referenced Subsystems in Models” on page 4-38 blocks, or both as its
variant choices. The choices are maintained in corresponding model or subsystem files that are on
the MATLAB path.

Convert Variant Subsystem Block with Expressions to Variant


Assembly Subsystem Block Interactively

This example shows how to convert a Variant Subsystem block that is in expression mode to a
Variant Assembly Subsystem block through the Block Parameters dialog box. The Variant Assembly
Subsystem block has the same variant choices as the Variant Subsystem block. However, the
subsystem choices are converted to Subsystem Reference choices and saved as subsystem files
during block conversion.

1. Consider the Controller block in the slexVariantSubsystems model. The Controller block
is a Variant Subsystem block that is to be converted to a Variant Assembly Subsystem block.

modelName = 'slexVariantSubsystems';
open_system(modelName);

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

2. Open the Block Parameters dialog box of the Controller block. From the Variant control mode
list, select expression.

3. Click the Convert to Variant Assembly button.

4. In the Convert Variant Subsystem to Variant Assembly Subsystem dialog box, specify these
properties for the converted block.

• Name of the variant control variable — Specify a valid variable name that adheres to the rules
in “Valid Names” or specify a valid structure field name that adheres to the rules in “Generate
Field Names from Variables”. During the conversion, Simulink® creates the specified variable or
the specified structure field to use as a variant control variable. The value of this variant control
variable determines the active choice of the converted block during simulation.
• Name of the enumeration class to be created — Specify a valid enumeration class name.
During the conversion, Simulink creates the specified enumeration class with the
Linear_Controller and Nonlinear_Controller choices as the members of the class. You

12-262
Convert Variant Subsystem to Variant Assembly Subsystem

can specify a folder to contain the enumeration class by clicking the Browse button. After
specifying the enumeration class, the Absolute path to the folder of the enumeration file
parameter displays the absolute path to the folder of that enumeration class.

5. During the conversion process, Simulink validates the types of variant choices in the Controller
block. The Model and Subsystem Reference choices do not change. The Subsystem choices are
converted to Subsystem Reference choices and are saved as subsystem files. The names of the newly
created subsystem files are the same as the Subsystem choices. In this example, the Subsystem
choices Linear Controller and Nonlinear Controller are converted to Subsystem Reference
choices and are saved in the subsystem files Linear_Controller.slx and
Nonlinear_Controller.slx. For more information on how Simulink converts the subsystem
blocks to Subsystem Reference blocks, see “Convert Subsystem to a Referenced Subsystem” on page
4-46.

These parameters display the details of the subsystem files:

• List of new subsystem filenames — Lists the names of the subsystem files to be created.
• Absolute path to the folder for new subsystem files — Displays the absolute path to the folder
of the subsystem files to be created.
• Location of new subsystem files — Displays the name of the folder where the subsystem files
are to be created. To change the location of the subsystem files, specify a path relative to your
current working folder or specify an absolute path. You can also select a folder from the file
system by clicking the Browse folder button.

6. The Variant choices (table of variant systems) table lists the names of the variant choices in
the converted block. For each variant choice, Simulink generates a Variant control expression. The
variant control variable is on the left side and the members of the variant enumeration class are on
the right side of the generated expressions. Both sides of the expression are related by ==. When an
expression evaluates to true during simulation, the corresponding variant choice becomes active.

7. To validate the current configuration of the Controller block, click Convert. If these validations
pass, the Controller block is converted to a Variant Assembly Subsystem block. You may need to
resolve any issues with the folders you specify for the enumeration class and subsystem files.

• If either folder exists in the file system but not on the MATLAB path, you must resolve the issue by
clicking Add to path or by using the addpath function.
• If either folder does not exist in the file system, Simulink creates the folder by using the mkdir
command and then adds it to the MATLAB path.
• If either folder contains files with the same names as the enumeration class or subsystem files,
you must determine if you want to replace them.

8. To simulate the model for Linear_Controller, specify the value of myVCV to


myEnum.Linear_Controller and simulate the model. During simulation, the control expression
myVCV == myEnum.Linear_Controller evaluates to true and Linear_Controller becomes
active.

For information on how to use the Variant Assembly Subsystem block, see “Add or Remove Variant
Choices of Variant Assembly Subsystem Blocks Using External Files” on page 12-195.

12-263
12 Modeling Variant Systems

Convert Variant Subsystem Block with Expressions to Variant


Assembly Subsystem Block Programmatically

This example explains how to convert a Variant Subsystem block to a Variant Assembly Subsystem
block using the Simulink.VariantUtils.convertToVariantAssemblySubsystem method. The
Variant Assembly Subsystem block has the same variant choices as the Variant Subsystem block.
However, the subsystem choices are converted to Subsystem Reference choices and saved as
subsystem files during block conversion.

1. Consider the Controller block in the slexVariantSubsystems model. The Controller block
is a Variant Subsystem block that is to be converted to a Variant Assembly Subsystem block.

modelName = 'slexVariantSubsystems';
open_system(modelName);

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

vssBlockPath = [modelName,'/Controller'];

2. Set the variant control mode of the Controller block to expression.

set_param(vssBlockPath,'VariantControlMode','expression');

3. To convert the Controller block to a Variant Assembly Subsystem block, use the
convertToVariantAssemblySubsystem method. During the conversion,

• The subsystem choices Linear Controller and Nonlinear Controller are converted to
Subsystem Reference blocks because the Variant Assembly Subsystem block does not support
subsystem choices. The name of the Subsystem Reference blocks are the same as the subsystem
blocks and are saved in the subsystem files Linear_Controller.slx and
Nonlinear_Controller.slx in the folder that you specify. For more information on how
Simulink converts the subsystem blocks to Subsystem Reference blocks, see “Convert Subsystem
to a Referenced Subsystem” on page 4-46.
• An enumeration class controllerClass is created in the folder that you specify. The
controllerClass class has Linear_Controller and Nonlinear_Controller choices as its
members.

You may need to resolve any issues with the folders you specify for the enumeration class and
subsystem files.

• If either folder does not exist in the file system, Simulink creates the folder by using the mkdir
command and then adds it to the MATLAB path.

12-264
Convert Variant Subsystem to Variant Assembly Subsystem

• If either folder contains files with the same names as the enumeration class or subsystem files,
Simulink overwrites them.

vcvName = 'EngType';
enumClassFilePath = 'controllerClass.m';
Simulink.VariantUtils.convertToVariantAssemblySubsystem ...
(vssBlockPath,VariantControlVariableName=vcvName,EnumerationClassFilePath=enumClassFilePath,Subs

After successfully converting the Controller block to a Variant Assembly Subsystem block, observe
the expressions in Variant control expression for each variant choice. Simulink generates the
expressions with the “Variant control variable” on the left side and the members of the “Variant
choices enumeration” on the right side. Both sides of the expression are related by ==. When an
expression evaluates to true during simulation, the corresponding variant choice becomes active.

4. Set Linear_Controller active by specifying the value of EngType to


controllerClass.Linear_Controller and simulate the model. During simulation, the control
expression EngType == controllerClass.Linear_Controller evaluates to true and
Linear_Controller becomes active.

EngType = controllerClass.Linear_Controller;
sim(modelName);

For information on how to use Variant Assembly Subsystem blocks, see “Add or Remove Variant
Choices of Variant Assembly Subsystem Blocks Using External Files” on page 12-195.

Convert Variant Subsystem Block with Labels to Variant Assembly


Subsystem Block Interactively

This example shows how to convert a Variant Subsystem block that is in label mode to a Variant
Assembly Subsystem block through Block Parameters dialog box. The Variant Assembly Subsystem
block has the same variant choices as the Variant Subsystem block. However, the subsystem choices
are converted to Subsystem Reference choices and saved as subsystem files during block conversion.

1. Consider the Controller block in the slexVariantSubsystems model. The Controller block
is a Variant Subsystem block that is to be converted to a Variant Assembly Subsystem block.

modelName = 'slexVariantSubsystems';
open_system(modelName);

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

12-265
12 Modeling Variant Systems

2. Open the Block Parameters dialog box of the Controller block. From the Variant control mode
list, select label.

3. Click the Convert to Variant Assembly button.

4. During the conversion process, Simulink validates the types of variant choices in the Controller
block. The Model and Subsystem Reference choices do not change. The Subsystem choices are
converted to Subsystem Reference choices and are saved as subsystem files. The names of the newly
created subsystem files are the same as the Subsystem choices. In this example, the Subsystem
choices Linear Controller and Nonlinear Controller are converted to Subsystem Reference
choices and are saved in the subsystem files Linear_Controller.slx and
Nonlinear_Controller.slx. For more information on how Simulink converts the subsystem
blocks to Subsystem Reference blocks, see “Convert Subsystem to a Referenced Subsystem” on page
4-46.

These parameters display the details of the subsystem files:

• List of new subsystem filenames — Lists the names of the subsystem files to be created.
• Absolute path to the folder for new subsystem files — Displays the absolute path to the folder
of the subsystem files to be created.
• Location of new subsystem files — Displays the name of the folder where the subsystem files
are to be created. To change the location of the subsystem files, specify a path relative to your
current working folder or specify an absolute path. You can also select a folder from the file
system by clicking the Browse folder button.

5. The Variant choices (table of variant systems) table lists the names of the variant choices in
the converted block. For each variant choice, Simulink generates a Variant control label. The
variant choice that corresponds to the control label selected in Label mode active choice of the
converted block becomes active during simulation or code generation.

6. To validate the current configuration of the Controller block, click Convert. If these validations
pass, the Controller block is converted to a Variant Assembly Subsystem block:

• If the specified folder exists in the file system but not on the MATLAB path, you must resolve the
issue by clicking Add to path or by using the addpath function.
• If the specified folder does not exist in the file system, Simulink creates the folder by using mkdir
command and adds it to the MATLAB path.
• If the specified folder contains a file with the same name as one of the new subsystem files, you
must determine if you want to replace it.

After successfully converting the Controller block to a Variant Assembly Subsystem block, observe
the expression in the “Variant choices specifier” parameter. The expression is of the form
{'Linear_Controller', 'Nonlinear_Controller'}, where Linear_Controller and
Nonlinear_Controller are the variant choices of the converted block. To add or remove variant
choices from the Controller block, change the specifier as described in “Add or Remove Variant
Choices of Variant Assembly Subsystem Blocks Using External Files” on page 12-195.

7. To simulate the model for Linear_Controller, set the value of Label mode active choice to
Linear_Controller and simulate the model.

12-266
Convert Variant Subsystem to Variant Assembly Subsystem

Convert Variant Subsystem Block with Labels to Variant Assembly


Subsystem Block Programmatically

This example explains how to convert a Variant Subsystem block to a Variant Assembly Subsystem
using the Simulink.VariantUtils.convertToVariantAssemblySubsystem method. The
Variant Assembly Subsystem block has the same variant choices as the Variant Subsystem block.
However, the subsystem choices are converted to Subsystem Reference choices and saved as
subsystem files during block conversion.

1. Consider the Controller block in the slexVariantSubsystems model. The Controller block
is a Variant Subsystem block that is to be converted to a Variant Assembly Subsystem block.

modelName = 'slexVariantSubsystems';
open_system(modelName);

VSS_LINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==1'

VSS_NONLINEAR_CONTROLLER =
VariantExpression with properties:

Condition: 'VSS_MODE==2'

VSS_MODE = 2

vssBlockPath = [modelName,'/Controller'];

2. Set the variant control mode of the Controller block to label.

set_param(vssBlockPath,'VariantControlMode','label');

3. To convert the Controller block to a Variant Assembly Subsystem block, use the
convertToVariantAssemblySubsystem method. During the conversion, the subsystem choices
Linear Controller and Nonlinear Controller are converted to Subsystem Reference blocks
because the Variant Assembly Subsystem block does not support subsystem choices. The name of the
newly created Subsystem Reference blocks are the same as the subsystem blocks and are saved in
the subsystem files Linear_Controller.slx and Nonlinear_Controller.slx in the folder
that you specify. For more information on how Simulink converts the subsystem blocks to Subsystem
Reference blocks, see “Convert Subsystem to a Referenced Subsystem” on page 4-46.

You may need to resolve any issues with the folders you specify for the subsystem files.

• If the specified folder does not exist in the file system, Simulink creates the folder by using mkdir
command.
• If the specified folder contains files with the same name as the new subsystem files, Simulink
overwrites them.

Simulink.VariantUtils.convertToVariantAssemblySubsystem(vssBlockPath,SubsystemFilesFolderPath=pwd

After successfully converting the Controller block to a Variant Assembly Subsystem block, observe
the expression in the “Variant choices specifier” parameter. The expression is of the form

12-267
12 Modeling Variant Systems

{'Linear_Controller', 'Nonlinear_Controller'}, where Linear_Controller and


Nonlinear_Controller are the variant choices of the converted block. To add or remove variant
choices from the Controller block, change the specifier as described in “Add or Remove Variant
Choices of Variant Assembly Subsystem Blocks Using External Files” on page 12-195.

4. To simulate the model for Linear_Controller, set the value of Label mode active choice to
Linear_Controller and simulate the model.

set_param(vssBlockPath,'LabelModeActiveChoice','Linear_Controller');
sim(modelName);

See Also
“Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files” on page
12-195

12-268
Convert Configurable Subsystem to Variant Subsystem

Convert Configurable Subsystem to Variant Subsystem

Note Configurable Subsystem will be removed in a future release. Convert Configurable Subsystem
blocks in existing models to Variant Subsystem blocks.

Variant Subsystems have the following advantages over Configurable Subsystems:

Feature Configurable Subsystem Variant Subsystem


Library You need to create a template You do not need to create a
block in a Simulink library to library to create an instance of
create an instance of a the variant subsystem.
configurable subsystem.
Variant Control You do not need variant controls You can control variant blocks
to control Configurable through label mode and other
Subsystem blocks. modes.
Code Generation Generated code contains only Generated code can contain
the active block choice. both the active and inactive
choices.
Model blocks and Subsystem You cannot mix Model blocks You can mix Model blocks and
blocks as choices. and Subsystem blocks as Subsystem blocks as variant
choices. choices.
Nested Workflows It is not easy to control block Nested variant subsystem
choices in nested configurable workflow is easy and not
subsystem hierarchy problematic.
Variant Manager There is no centralized system Variant Manager has advanced
to manage configurable variant management
subsystem blocks. capabilities.

You can convert a Configurable Subsystem block to a Variant Subsystem block in these ways:

• Using Upgrade Advisor interactively


• Using Upgrade Advisor programmatically
• Using the convertToVariantSubsystem method
• Using the context menu of the Configurable Subsystem block

Using Upgrade Advisor interactively


When you compile a model containing Configurable Subsystem blocks, a warning is displayed in the
Diagnostic Viewer to convert the Configurable Subsystem block to a Variant Subsystem block.

1 In the Diagnostic Viewer, click Open in the Suggested Actions section. This opens the
Upgrade Advisor. For more information on Upgrade Advisor, see “Upgrade Models Using
Upgrade Advisor” on page 6-2.
2 Run the Identify configurable subsystem blocks for converting to variant subsystem
blocks check by clicking Run This Check. Upgrade Advisor displays a list of all the
Configurable Subsystem blocks in the model and the Recommended Action.

12-269
12 Modeling Variant Systems

3 In the model, perform the Recommended Action of running Analyze model hierarchy and
continue upgrade sequence check. Upgrade Advisor guides you through the recommended
sequence of steps to upgrade your models. Click Continue Upgrade Sequence to open the
libraries in a sequence.
4 In the library, run the Identify configurable subsystem blocks for converting to variant
subsystem blocks again. Click Convert All to convert all the configurable subsystem blocks in
the libraries in the sequence. You must run the Identify configurable subsystem blocks for
converting to variant subsystem blocks check as many times as the number of libraries.

Note To upgrade Configurable Subsystem instances created by Model Discretizer in the model or
subsystem level, perform the Recommended Action. The recommended action ensures that
information regarding discretization is retained. To convert to Variant Subsystem block, right-click
each of the Configurable Subsystem instances provided in the list and select Subsystem and Model
Reference > Convert to> Variant Subsystem.

Using Upgrade Advisor Programmatically


Use the upgradeadvisor function to convert Configurable Subsystem blocks in a model to Variant
Subsystem blocks programmatically.
1 Open a model containing a Configurable Subsystem block.

2 Convert the library template blocks to Variant Subsystem blocks using the upgradeadvisor
function. Create an object for upgradeadvisor and run the upgrade method with the
upgrader object.

12-270
Convert Configurable Subsystem to Variant Subsystem

upgrader = upgradeadvisor(bdroot);
upgrader.upgrade

A report with the status of the block conversion is generated. For information on how to use the
upgradeadvisor function, see “Programmatically Analyze and Upgrade Model”.

Using convertToVariantSubsystem Method


Use the convertToVariantSubsystem method to convert Configurable Subsystem blocks in a
model to Variant Subsystem blocks.

Perform these steps to convert Configurable Subsystem blocks in a model to Variant Subsystem
blocks:

1 Open a model containing a Configurable Subsystem block.

2 In the Command Window, use the find_system command to find all Configurable Subsystem
blocks in the model:
find_system(bdroot, 'Regexp', 'on',...
'LookUnderMasks', 'on', 'FollowLinks', 'on',...
'MatchFilter', @Simulink.match.allVariants, 'TemplateBlock', '.')

{'mconfigsub/config_sub'}
{'mconfigsub/nested config'}
3 Find the library template blocks from the list using get_param command.
get_param('mconfigsub/nested config',...
'TemplateBlock')
ans =
'mconfiglib/nested config'

get_param('mconfigsub/config_sub',...
'TemplateBlock')
ans =
'mconfiglib/Subsystem/config_sub'

4 Convert the library template blocks to Variant Subsystem blocks using the
convertToVariantSubsystem method.
Simulink.VariantUtils.convertToVariantSubsystem('mconfiglib/nested config')
Simulink.VariantUtils.convertToVariantSubsystem('mconfiglib/Subsystem/config_sub')

5 Save the libraries. You can use save_system command to save the libraries.
6 Close and open the model again. The Configurable Subsystem blocks in the model will be
converted to Variant Subsystem blocks.

Using Context Menu of Configurable Subsystem Block


1 Open a model containing a Configurable Subsystem block.

12-271
12 Modeling Variant Systems

2 Right-click the Configurable Subsystem block. In the context menu, select Subsystem & Model
Reference > Convert to > Variant Subsystem.
3 By default, Copy without creating links to the configurable subsystem library is selected.
This creates variant choices without creating links to a library.

4 Click OK. The Configurable Subsystem block is converted to a Variant Subsystem block and is
displayed in a new window.
5 Manually replace the Configurable Subsystem block with the converted Variant Subsystem block
in the original model.

12-272
Convert Configurable Subsystem to Variant Subsystem

Changing Active Variant


When you convert a Configurable Subsystem to a Variant Subsystem block, Block Choice of the
Configurable Subsystem block is changed to Label mode active choice in the Variant Subsystem
block.

If the Block choice of the Configurable Subsystem template block is linked, then the block is copied
to the Variant Subsystem and the copied blocks will have their links retained. If the Block choice of
the Configurable Subsystem template block is not linked, then the block is copied to the Variant
Subsystem and the block in the Configurable Subsystem library is linked to it.

To change the active variant:

• Right-click the badge on the Variant Subsystem block and select Block Parameters
(Subsystem). In the block parameters dialog box, select the active variant from Label Mode
Active Choice drop-down list.
• Right-click the badge on the Variant Subsystem block and select Label Mode Active Choice.

Note When a Configurable Subsystem block with a mask is converted to Variant Subsystem block,
the Label mode active choice option and all other parameters in block parameters dialog box
are disabled. To change the active variant, right-click the badge on the Variant Subsystem block
and select Label Mode Active Choice.

See Also
Variant Subsystem, Variant Model

More About
• “V-Model for System Development with Simulink Variants” on page 12-243
• Variant System Design

12-273
13

Managing Model Configurations

• “Set Model Configuration Parameters for a Model” on page 13-2


• “Manage Configuration Sets for a Model” on page 13-6
• “Share a Configuration with Multiple Models” on page 13-12
• “Share a Configuration Across Referenced Models” on page 13-20
• “Automate Model Configuration by Using a Script” on page 13-24
• “Configuration Object Functions” on page 13-27
13 Managing Model Configurations

Set Model Configuration Parameters for a Model

In this section...
“Set Configuration Parameters Programmatically” on page 13-2
“Set Configuration Parameters by Using the Dialog Box” on page 13-2

Model configuration parameters determine how your model runs by specifying the type of solver
used, import and export settings, and other settings that control model behavior. Every model has a
configuration set that contains the model configuration parameters and their specified values. When
you create a new model, it contains the default configuration set, called Configuration, that
specifies the default values for the model configuration parameters. You can view and set
configuration parameters programmatically or by using the Configuration Parameters dialog box.

For more information about each parameter, see the links in “Configuration Panes” on page 13-4.

Set Configuration Parameters Programmatically


To interact with model configuration parameters programmatically, use the get_param and
set_param functions. For example, you can get and set the Solver type parameter for the model
vdp.

openExample('simulink_general/VanDerPolOscillatorExample');
get_param('vdp', 'SolverType')

ans =

'Variable-step'

set_param('vdp', 'SolverType', 'Fixed-step');

For more information on how to use configuration parameters programmatically, see “Automate
Model Configuration by Using a Script” on page 13-24.

Set Configuration Parameters by Using the Dialog Box


To view and set the configuration parameters for your model, open the Configuration Parameters
dialog box. In the Simulink Editor, on the Modeling tab, click Model Settings.

Alternatively, to open the Configuration Parameters dialog box for a referenced model, click the
Model Settings button arrow. Then, in the Referenced Model section, select Model Settings.

13-2
Set Model Configuration Parameters for a Model

The Configuration Parameters dialog box opens and shows the configuration parameters for the
model.

Use the dialog box to view and set the parameters. If you cannot change the value of a parameter, the
parameter is disabled for one of these reasons:

• The parameter has a dependency on another parameter. In this case, the parameter becomes
enabled or disabled depending on the setting of the other parameter. To enable a parameter that
has a dependency, see the complete documentation for that parameter.

13-3
13 Managing Model Configurations

• The configuration is a configuration reference. In this case, all of the parameters are disabled in
the dialog box. To change the parameter values in the referenced configuration, see “Change
Parameter Values in a Referenced Configuration Set” on page 13-16.

To get more information about a parameter, right-click the parameter name and select What's This?
A dialog opens and displays:

• A short parameter description.


• The parameter name that you can use in scripts.
• Parameter dependencies.

From the What's This? dialog box, click Show more information for the complete parameter
documentation.

To find a parameter by using its name, command-line name, value, or description, use the Search box
at the top of the dialog box. The search tool supports regular expressions. Type . in the search box to
see a list of all parameters.

Configuration Panes

The configuration set is organized in panes that contain parameters related to that category. To
display the parameters for a specific category, click the associated pane in the tree on the left side of
the dialog box. You can access the advanced parameters for each pane by mousing over the ellipsis
toward the bottom of the dialog box and clicking Advanced parameters.

For more information about the parameters on each of the panes, see:

• “Solver Pane”
• “Model Configuration Parameters: Data Import/Export”
• “Math and Data Types Pane”
• “Model Configuration Parameters: Diagnostics”
• “Hardware Implementation Pane”
• “Model Configuration Parameters: Model Referencing”
• “Model Configuration Parameters: Simulation Target”

Some MathWorks products that work with Simulink define additional parameters. If such a product is
installed on your system, the configuration set also contains the associated configuration parameters
and panes.

• Simulink Coder — “Model Configuration Parameters: Code Generation” (Simulink Coder)


• HDL Coder — “Model Configuration Parameters: HDL Code Generation” (HDL Coder)
• Simulink PLC Coder — “PLC Coder: General Tab Overview” (Simulink PLC Coder)
• Simulink Coverage — “Specify Coverage Options” (Simulink Coverage)
• Simulink Real-Time™ — “Simulink Real-Time Options Pane” (Simulink Real-Time)
• Simulink Desktop Real-Time™ — “Simulink Desktop Real-Time Pane” (Simulink Desktop Real-
Time)
• Simscape — “Simscape Pane Overview” (Simscape)
• Simulink Design Verifier — “Design Verifier Pane” (Simulink Design Verifier)

13-4
Set Model Configuration Parameters for a Model

See Also

More About
• “Manage Configuration Sets for a Model” on page 13-6
• “Automate Model Configuration by Using a Script” on page 13-24

13-5
13 Managing Model Configurations

Manage Configuration Sets for a Model

In this section...
“Create a Configuration Set in a Model” on page 13-6
“Change Configuration Parameter Values in a Configuration Set” on page 13-7
“Activate a Configuration Set” on page 13-8
“Copy, Delete, and Move a Configuration Set” on page 13-8
“Save a Configuration Set” on page 13-9
“Load a Saved Configuration Set” on page 13-10
“Compare Configuration Sets” on page 13-10

A model configuration set is a named collection of values for the parameters of a model.

You can associate multiple sets of parameter values with your model. The configuration sets
associated with a model can specify different values for any or all configuration parameters. The
model uses the parameter values of the active configuration. You can quickly change the active
configuration to any of the configuration sets that are attached to the model.

Use multiple configuration sets in a model when you want to:

• Compare the difference in model execution after changing the values of several parameters.
• Use different configurations for your model when you use the model in different contexts.

For this example, you set up the model sldemo_fuelsys_dd to have two configuration sets that
specify different solvers. You then copy one of the configurations to the model vdp and compare it
with the default configuration set of vdp. This example uses the configuration dialog boxes to manage
the configuration sets. For an example of how to manage configurations programmatically, see
“Automate Model Configuration by Using a Script” on page 13-24.

Create a Configuration Set in a Model

The model sldemo_fuelsys_dd contains one configuration set, which uses a variable-step solver.
Add another configuration to use a fixed-step solver.

1 Open the model. At the command line, type sldemo_fuelsys_dd.


2 Open the Model Explorer. On the Modeling tab, click Design > Model Explorer.
3 In the Model Hierarchy pane, expand the model node and select the model name
sldemo_fuelsys_dd.
4 You can create a new configuration set in any of these ways:

• From the Add menu, select Configuration.



On the toolbar, click the Add Configuration button .
• Select the Configurations node below the model node. In the Contents pane, right-click an
existing configuration set and copy and paste the configuration set.

13-6
Manage Configuration Sets for a Model

5 Select the Configurations node below the model node. The new configuration set,
Configuration1, appears in the Contents pane. The default configuration, Configuration, is
still the active configuration for the model.
6 On the Contents pane, double-click the name Configuration1 and rename the configuration
to FixedStepConfig. You specify the fixed-step solver in the following section.
7 Rename the configuration Configuration to VariableStepConfig.

Change Configuration Parameter Values in a Configuration Set


To change the parameter values of a configuration set, open the Configuration Parameters dialog box
for that configuration. You can open and change any configuration set, whether or not it is active.

For this example, change the configuration FixedStepConfig to specify a fixed-step solver instead
of the default variable-step solver.

1 Open the Model Explorer.


2 Expand the model node and select the Configurations node below it.
3 In the Contents pane, right-click the configuration set FixedStepConfig and click Open.

The configuration set opens in the Configuration Parameters dialog box.

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.
4 On the Solver pane, set the Type parameter to Fixed-step. Click OK.

The model now contains two configurations, VariableStepConfig and FixedStepConfig, which
use different solver types. You can compare how the solver settings affect simulation by changing the
active configuration and simulating the model.

13-7
13 Managing Model Configurations

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 parameter values in the
active or inactive set at any time (except when executing the model). In this way, you can quickly
reconfigure a model for different purposes, such as testing and production.

To activate the fixed-step configuration that you created in the previous section:

1 Open the Model Explorer.


2 Expand the model node and select the Configurations node below it.
3 In the Contents pane, right-click the configuration set FixedStepConfig and click Activate.

The active configuration displays (Active) to the right of the configuration name.

Copy, Delete, and Move a Configuration Set


You can use the Model Explorer Edit or context menus to delete, copy, and move configuration sets
among models displayed in the Model Hierarchy pane.

For this example, copy your configuration FixedStepConfig to the model vdp.

1 Open the model vdp and open the Model Explorer. At the command line, enter
openExample('VanDerPolOscillatorExample').
2 In the Model Hierarchy pane, expand the node of the model sldemo_fuelsys_dd and select
the Configurations node below it.
3 In the Contents pane, right-click FixedStepConfig and click Copy in the context menu.
4 In the Model Hierarchy pane, right-click the model node vdp and click Paste.
5 Activate the configuration FixedStepConfig for the model vdp.

13-8
Manage Configuration Sets for a Model

To copy the configuration set using drag-and-drop, hold down the right mouse button and drag the
configuration set to the Configurations 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 to the Configurations node of the destination model.

Note You cannot move or delete an active configuration set from a model.

Save a Configuration Set


When you store a configuration set in a model, the configuration set is saved when you save the
model. Alternatively, you can store the configuration set outside of the model as a freestanding
configuration set to share the configuration with other models. You can save the configuration set in a
Simulink data dictionary, or export the configuration set to a MAT-file or to a script. If you store a
freestanding configuration set in the base workspace, to save it, you must export it to a MAT-file or
script.

Simulink Data Dictionary

To save your configuration set outside of the model, store the configuration in a Simulink data
dictionary. You can share and archive the configuration by using the data dictionary. To use the
configuration in a model, use a configuration reference. For more information, see “Share a
Configuration with Multiple Models” on page 13-12.

Exported File

You can also save the settings of a configuration set as a Simulink.ConfigSet object in a MAT-file
or as a MATLAB function or script. Export the configuration set to a MATLAB function or script when
you want to compare the settings in different configuration sets. However, when you want to preserve
a freestanding configuration set, exporting the configuration to a file is not recommended because
you must manually load the configuration set when you want to use it. Save the configuration set in a
Simulink data dictionary instead.

For this example, use the Model Explorer to save the configuration set FixedStepConfig, which you
copied to the model vdp.

1 Open the Model Explorer.


2 In the Model Hierarchy pane, expand the model node vdp and select the Configurations node
below it.
3 In the Contents pane, right-click the configuration FixedStepConfig and select Export.
4 In the Export Configuration to File dialog box, specify the name of the file and the file type. For
this example, save the configuration as FixedStepConfig.m.

If you specify a .m extension, the file contains a MATLAB 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.

13-9
13 Managing Model Configurations

• To use the configuration set in a later release, specify a .mat extension. If you specify a .m
extension, in rare cases, parameter values might change due to changing dependencies.

5 Click Save. The Simulink software saves the configuration set.

Load a Saved Configuration Set


To load the configuration set that you saved from the model vdp:

1 Open the model vdp.


2 Open the Model Explorer.
3 In the Model Hierarchy pane, right-click the model and select Configuration > Import.
4 In the Import Configuration 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. For
this example, select FixedStepConfig.m.
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 (Simulink Coder) parameter to ert.tlc.
• If you load a configuration set that contains a component that is not available on your system,
the parameters in the missing component are reset to their default values.

Compare Configuration Sets


When you save two configuration sets as M files or as MAT-files, you can visually compare them by
using the visdiff function. This function opens the Comparison Tool and presents the differences
between the two files. For more information about the Comparison Tool, see “Review Changes in
Simulink Models” on page 21-2.

For this example, compare the default configuration Configuration to the configuration
FixedStepConfig, which you copied to the model vdp.

1 Save the configuration FixedStepConfig to the file FixedStepConfig.m, as shown in “Save a


Configuration Set” on page 13-9.
2 Save the second configuration, Configuration, to the file DefaultConfig.m by following the
same procedure.
3 Compare the files.

visdiff('FixedStepConfig.m','DefaultConfig.m');

See Also

More About
• “Set Model Configuration Parameters for a Model” on page 13-2

13-10
Manage Configuration Sets for a Model

• “Automate Model Configuration by Using a Script” on page 13-24

13-11
13 Managing Model Configurations

Share a Configuration with Multiple Models

In this section...
“Create a Configuration Set in the Data Dictionary” on page 13-13
“Create and Attach a Configuration Reference” on page 13-13
“Resolve a Configuration Reference” on page 13-14
“Activate a Configuration Reference” on page 13-15
“Create a Configuration Reference in Another Model” on page 13-15
“Change Parameter Values in a Referenced Configuration Set” on page 13-16
“Change Parameter Value in a Configuration Reference” on page 13-16
“Save a Referenced Configuration Set” on page 13-18
“Load a Saved Referenced Configuration Set” on page 13-18
“Configuration Reference Limitations” on page 13-18

To share a configuration set with multiple models, store it as a freestanding configuration set in a
Simulink data dictionary or in the base workspace. By default, a configuration set resides within a
single model so that only that model can use it. A freestanding configuration set is a
Simulink.ConfigSet object that you store outside of your models so that multiple models can use
it.

To use a freestanding configuration set in a model, create a configuration reference in the model that
points to the freestanding configuration set. You can then activate the configuration reference in the
same way as a standard configuration set. Multiple models can reference the same freestanding
configuration set.

Use configuration references when you want to:

• Use the same configuration parameters in multiple models. When you change parameter values in
the freestanding configuration, the changes apply to each model that references the configuration.

To share a configuration set across a model hierarchy, you can propagate the reference from the
top model to its referenced models. For more information, see “Share a Configuration Across
Referenced Models” on page 13-20.
• Change configuration parameters for any number of models without changing the model files.
When you store a configuration set in a Simulink data dictionary, changing parameter values in
the configuration changes the data dictionary file. Models that are linked to the data dictionary
and reference the configuration set use the new values, but their model files are not changed.
• Quickly replace the configuration sets of any number of models without changing the model files.
When you store a configuration set in a Simulink data dictionary, you can point to that
configuration from a reference that is also stored in the data dictionary. Your models can then
reference the data dictionary's configuration reference. When you change the data dictionary's
reference to point to a different configuration set, the models use the new configuration.

When a configuration reference references a configuration in the base workspace, it points to a


variable that represents the Simulink.ConfigSet object. Assigning a different configuration set
to the variable assigns that configuration set to each model that references the variable.

13-12
Share a Configuration with Multiple Models

For this example, you store a configuration set in a Simulink data dictionary and reference the
configuration set from models that are linked to the data dictionary. To create and link a Simulink
data dictionary, see “Migrate Models to Use Simulink Data Dictionary” on page 80-7. To share a
configuration set that is already saved in a model, convert the configuration to a referenced
freestanding configuration, as shown in “Share a Configuration Across Referenced Models” on page
13-20.

Create a Configuration Set in the Data Dictionary


Before you reference a freestanding configuration set from your models, create the configuration in a
Simulink data dictionary and link it to your models. For this example, use the Simulink project
Airframe. The project contains the Simulink data dictionary system_model and multiple models that
are linked to the data dictionary.

1 Open the project. At the command line, type openExample('simulink/


AirframeProjectExample').
2 In the project folder, in the folder data, double-click the Simulink data dictionary
system_model.sldd. The data dictionary opens in the Model Explorer.
3 In the Model Hierarchy pane, expand the data dictionary node for system_model. Right-click
the node and click Show Empty Sections.
4
Select the Configurations node and click the Add Configuration button . The configuration
set object appears in the Contents pane, with the default name, Configuration.
5 Name the new configuration SharedConfig.

Models that have access to the data dictionary system_model.sldd can reference the new
configuration.

Create and Attach a Configuration Reference


To use your freestanding configuration set in a model, attach a configuration reference that points to
the configuration set. For this example, use the model LinearActuator. The model is linked to the

13-13
13 Managing Model Configurations

Simulink data dictionary system_model.sldd, which contains your new configuration


SharedConfig.

1 Open the model. At the command line, type LinearActuator.


2 In the Model Explorer, in the Model Hierarchy pane, select the model node.
3
Select Add > Configuration Reference or click the Add Configuration Reference button .
4 Under the model node, click Configurations. A new configuration reference named Reference
is listed.
5 Name the configuration reference LinActuatorRef.

The new configuration reference is attached to the model, but it does not point to a freestanding
configuration yet and it is not active. To complete the setup, resolve and activate the configuration
reference.

Resolve a Configuration Reference


An unresolved configuration reference is a configuration reference that is not pointing to a valid
configuration set object. When you create a configuration reference by using the preceding steps, the
reference is unresolved.

To resolve the configuration reference that you created:

1 In the Model Hierarchy pane, under the model node for the LinearActuator model, select the
Configurations node. In the Contents pane, select the unresolved configuration reference,
LinActuatorRef.

The right pane shows that the configuration reference is unresolved.

13-14
Share a Configuration with Multiple Models

2 Use the Name drop-down menu to select SharedConfig, which you created in the data
dictionary.

Tip You can specify the name of a configuration reference instead of a configuration set.
However, nesting a configuration reference beyond this depth results in an error.
3 Click Apply. The warning icon disappears and the reference points to your freestanding
configuration set.

If your configuration reference is already resolved, you can follow these steps to change which
configuration set it references.

Activate a Configuration Reference


After you create the configuration reference and attach it to the model, activate the reference to use
the referenced configuration in the model.

1 In the Model Hierarchy pane, under the model node for the LinearActuator model, select the
Configurations node. In the Contents pane, select the configuration reference
LinActuatorRef.
2 Right-click the configuration reference LinActuatorRef and select Activate.

When the configuration reference is active, the Model Explorer shows the name of the reference with
the suffix (Active). The freestanding configuration set now provides the configuration parameters
for the model.

Create a Configuration Reference in Another Model


For this example, you will update the configuration set and see how it affects its associated models.
Repeat the process above to associate SharedConfig with a second model:

1 Open the model NonLinearActuator. This model is also linked to the data dictionary that
contains the freestanding configuration set.

13-15
13 Managing Model Configurations

2 In Model Explorer, add a configuration reference to the model NonLinearActuator.


3 Name the configuration reference NonLinActuatorRef.
4 Point the reference to the freestanding configuration set SharedConfig.
5 Activate the configuration reference.

Both models now contain a configuration reference that points to the same configuration set object in
the Simulink data dictionary.

Change Parameter Values in a Referenced Configuration Set


You can edit a freestanding configuration set by opening it from the Configuration Reference dialog
box of a reference that points to the configuration set. Changing the freestanding configuration set
affects the configuration references that refer to it, except for parameters that are overridden in
those references. To edit the configuration set that you reference from the models:
1 Open one of the models that references the configuration set. For this example, open the model
LinearActuator.
2 To open the Configuration Reference dialog box, on the Modeling tab, click the Model Settings

button . The Configuration Reference dialog box displays a read-only view of the referenced
configuration SharedConfig. In the dialog box you can browse, search, and get context-
sensitive help for the parameters in the same way you do in the Configuration Parameters dialog
box.
3 At the top of the Configuration Reference dialog box, click the Model Configuration Parameters
icon . The Configuration Parameters dialog box opens. You can now change and apply
parameter values as you would for any configuration set.

Note Some options in the configuration set cannot be used in a freestanding configuration
because they perform actions on one specific model. For example, the Data Import/Export >
Connect Inputs button is not supported in freestanding configuration sets because it opens the
Root Inport Mapper for the model that uses the configuration.
4 On the Solver pane, set the Type parameter to Fixed-step. Click Apply, then OK.
5 Your applied changes appear in the Configuration Reference dialog box. The models that
reference the freestanding configuration SharedConfig use the new solver type.

Change Parameter Value in a Configuration Reference

You can override individual parameter values for models that reference freestanding configuration
sets without changing the freestanding configuration. For an overridden parameter, the reference
uses the value you assign locally instead of the value in the referenced configuration set. For
example, suppose that LinearActuator and NonLinearActuator are both in the same model
hierarchy. You want LinearActuator to be referenced as many times as it needs to be, but want
Simulink to return an error if NonLinearActuator is referenced more than one time. In this
example, you can override the Model Referencing > Total number of instances allowed per top
model parameter for only the NonLinearActuator model.

For this example, override the parameter in the configuration reference for the model
NonLinearActuator.

13-16
Share a Configuration with Multiple Models

1 Open the model NonLinearActuator.


2 To open the Configuration Reference dialog box, on the Modeling tab, click the Model Settings

button . The active configuration reference displays a read-only view of the referenced
configuration.
3 Right-click the parameter you want to change and select Override from the context menu. You
can now change the parameter value as you would for any configuration set. For this example,
override the parameter Model Referencing > Total number of instances allowed per top
model and set the value to One.

In the left pane, each pane displays the number of overridden parameters it contains.

4 Click Apply to keep the changes or Cancel to restore the parameter to the referenced value.

Changes you make to a parameter value apply only to the configuration reference in which you
override and edit the parameter. They do not affect other references to the referenced
configuration set. For this example, the model NonLinearActuator allows a top model to
reference it once, while the model LinearActuator allows a top model to reference it multiple
times.

13-17
13 Managing Model Configurations

To restore an overridden parameter to its value from the referenced configuration set, right-click the
overridden parameter and select Restore from the context menu. The overridden parameter resets to
the value in the referenced configuration and becomes read-only again.

Save a Referenced Configuration Set


If you store your freestanding configuration set in a Simulink data dictionary, you can save changes to
the configuration by saving the data dictionary.

If your model references a configuration set that you store in the base workspace, before you exit
MATLAB, you need to save the referenced configuration set to a MAT-file or MATLAB script.

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 “Customize Model Behavior with Callbacks” on page 4-68.

Load a Saved Referenced Configuration Set


If your configuration reference uses a configuration set that you exported to a MAT-file or MATLAB
script, you need to load the referenced configuration set from the file 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.

Configuration Reference Limitations


• A configuration reference can point to another configuration reference, but you cannot nest a
configuration reference beyond the second reference.
• 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” (Simulink Coder).
• Not all parameters in a reference can be overridden, for example, parameters that must be
consistent in a model reference hierarchy cannot be overridden.

13-18
Share a Configuration with Multiple Models

See Also

Related Examples
• “Share a Configuration Across Referenced Models” on page 13-20
• “Create Template from Model” on page 4-2

13-19
13 Managing Model Configurations

Share a Configuration Across Referenced Models


This example shows how to share the same configuration set for the top model and referenced models
in a model reference hierarchy. You can use a configuration reference in each of the models to
reference the same configuration set object in a Simulink data dictionary that the models are linked
to.

In the diagram, each model shown in the Dependency Analyzer specifies a configuration reference as
its active configuration set. Each reference points to the freestanding configuration set,
my_configuration. Therefore, the parameter values in my_configuration apply to all four
models. Any parameter change in my_configuration applies to all four models. For more
information about configuration references, see “Share a Configuration with Multiple Models” on
page 13-12.

Link Models to Simulink Data Dictionary

Create a Simulink data dictionary to store the configuration set. When you link the models in the
hierarchy to the data dictionary, they can reference the configuration set.
1 Open the sldemo_mdlref_depgraph model. At the command line, enter this command.
openExample('simulink/VisualizeModelReferenceHierarchiesExample')
2 On the Modeling tab, under Design, click Link to Data Dictionary.
3 In the Model Properties dialog box, click New. Name the new Simulink data dictionary
SharedDataDictionary and click Save.

13-20
Share a Configuration Across Referenced Models

4 Click OK. Because this model includes referenced models, a pop-up window asks you if
SharedDataDictionary.sldd should be used for all referenced models that do not already
use a dictionary. Click Change all models. The current model and all of its referenced models
are linked to the new data dictionary. When the data dictionary is linked, click OK.

The models are now linked to the Simulink data dictionary, SharedDataDictionary.sldd. When
you store a configuration set in this data dictionary, the models that are linked to it can reference the
configuration set.

Convert Configuration Set to Configuration Reference

In the top model, you must convert the active configuration set to a configuration reference:

1 Open the Model Explorer.


2 In the Model Hierarchy pane, expand the top model, sldemo_mdlref_depgraph. In the list,
select the Configurations node, and right-click Configuration (Active) in the Contents
pane. In the context menu, select Convert to Configuration Reference.
3 In the Name field, use the default name, Configuration. This configuration set object is stored
in the data dictionary SharedDataDictionary.sldd.
4 Click OK.

The original configuration set is now stored as a configuration set object, Configuration, in the
Simulink data dictionary. The active configuration for the top model is now a configuration reference
that points to the configuration set object in the data dictionary.

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 and makes it the active configuration. The
configuration references point to the configuration set object in the data dictionary.

1 In the Model Explorer, in the Model Hierarchy pane, expand the sldemo_mdlref_depgraph
node and select the Configurations node.

13-21
13 Managing Model Configurations

2 In the Contents pane, 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 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.
6 In the Configuration Reference Propagation dialog box, the Propagation Report is updated and
the Status for each referenced model is marked as Converted.

Now, each model in the hierarchy references the freestanding configuration Configuration. If you
want one model to use a different value for a parameter, you can override individual parameters
within the reference that the model uses. For more information, see “Change Parameter Value in a
Configuration Reference” on page 13-16.

13-22
Share a Configuration Across Referenced Models

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.

See Also

Related Examples
• “Share a Configuration with Multiple Models” on page 13-12

13-23
13 Managing Model Configurations

Automate Model Configuration by Using a Script

If you want to use the same configuration setup for many models, you can write a script to
programmatically configure each model in the same way. You can use the script to archive and
compare the configuration settings that your models use.

This example shows three different ways to programmatically set up your model's configuration:

• Edit the model's existing active configuration set


• Create and edit a new configuration set in the model
• Create a configuration reference that points to a freestanding configuration set

For this example, use the damped_nonlin_spring model.

model = 'damped_nonlin_spring';
open_system(model);

Edit the Active Configuration Set

To manipulate a configuration set that is associated with a model, use the ConfigSet object that
represents the configuration set. For this example, use the configuration that is active for the model.

activeConfigObj = getActiveConfigSet(model);
get_param(activeConfigObj,'Name')

ans =
'Configuration'

The active configuration for the model is Configuration. To see the current values of parameters in
the configuration, use the get_param function and the ConfigSet object.

get_param(activeConfigObj,'StopTime')

ans =
'10'

Rename the configuration set to UpdatedConfig.

set_param(activeConfigObj,'Name','UpdatedConfig');

For this example, set a stop time of 200 and change the solver type to a variable-step solver.

set_param(activeConfigObj,'StopTime','200');
set_param(activeConfigObj,'SolverType','Variable-step');

Create and Activate a Configuration Set

When you want to change the model's configuration and preserve the original parameter values of its
active configuration, create and activate a new configuration set in the model. To create another
configuration set, copy an existing configuration set and attach the copy to the model. To avoid
naming conflicts when you attach the copy, either rename the copy before attaching it or set
allowRename, the optional third argument of attachConfigSet, to true.

For this example, copy the active configuration set. Rename the copy to ConfigCopy and attach it to
the model.

13-24
Automate Model Configuration by Using a Script

newConfigObj = copy(activeConfigObj);
set_param(newConfigObj,'Name','ConfigCopy');
attachConfigSet(model, newConfigObj);

When you attach a configuration set to a model, it is inactive. You can manipulate inactive
configurations in the same way that you manipulate the active configuration set. To use the new
configuration, activate it for the model.
set_param(newConfigObj,'SolverType','Fixed-step');

setActiveConfigSet(model,'ConfigCopy');
activeConfigSet = getActiveConfigSet(model);
get_param(activeConfigSet,'Name')

ans =
'ConfigCopy'

Now, ConfigCopy is the active configuration set.

Set Up a Configuration Reference

If you want to store the configuration set outside of your model, create a script that sets up a
configuration reference in the model. The reference is stored in the model and it points to a
freestanding configuration set, which is stored in either a Simulink® data dictionary or in the base
workspace. Use a freestanding configuration set and configuration references to share one
configuration with multiple models. You can also use a freestanding configuration set when you want
to edit the configuration without changing the model file.

For this example, configure the model vdp to use a configuration reference. First, create a
freestanding configuration set in the base workspace by copying the model's active configuration set.
The freestanding configuration is a ConfigSet object represented by the variable freeConfigSet.
You can skip this step if you want to reference an existing freestanding configuration set.
model = 'vdp';
open_system(model)

freeConfigSet = copy(getActiveConfigSet(model));

Create a configuration reference. To point the reference to your freestanding configuration, set the
SourceName property to freeConfigSet, the variable that represents your configuration. The new
reference is a ConfigSetRef object represented by the variable configRef. Name the reference
vdpConfigRef.
configRef = Simulink.ConfigSetRef;
set_param(configRef,'SourceName','freeConfigSet')
set_param(configRef,'Name','VdpConfigRef')

Attach the configuration reference to the model vdp by using the ConfigSetRef object. You can
attach the reference to only one model. To use the configuration reference in the model, activate it.
attachConfigSet('vdp',configRef);
setActiveConfigSet('vdp','VdpConfigRef');

Now, when you change the configuration set that the object freeConfigSet represents, the changes
apply to the model.

You can obtain parameter values in a configuration reference by using get_param. However, you
cannot change parameter values directly in the configuration reference. To change the values, you

13-25
13 Managing Model Configurations

must use the ConfigSet object that represents the referenced freestanding configuration set. Get
the freestanding configuration set from a configuration reference by using the getRefConfigSet
method.

referencedConfigObj = getRefConfigSet(configRef);

Now, referencedConfigObj represents the same freestanding configuration set that your models
reference. freeConfigSet represents that configuration set as well. Use the configuration set
object to change parameter values in the referenced configuration set. These changes apply to each
model that references the configuration.

set_param(referencedConfigObj,'SignalLogging','off');
set_param(referencedConfigObj,'StartTime','10');

See Also
Simulink.BlockDiagram.saveActiveConfigSet

Related Examples
• “Manage Configuration Sets for a Model” on page 13-6
• “Create Template from Model” on page 4-2

13-26
Configuration Object Functions

Configuration Object Functions


To interact with a configuration, programmatically, use a Simulink.ConfigSet object or a
Simulink.ConfigSetRef object. You can use the following functions to get information about the
configuration. For more information about using configurations, see “Manage Configuration Sets for a
Model” on page 13-6.

Function Purpose
getFullName Return the full path name of a configuration set
or configuration reference as a character vector.
getModel Return the model that owns the configuration set
or configuration reference as a handle to the
model.
getRefConfigSet Return the configuration set that a configuration
reference points to.
isActive Determine if the configuration set or
configuration reference is the active
configuration of the model, returned as a boolean
value.
isValidParam Determine if a specified parameter is a valid
parameter of a configuration set.
refresh Update a configuration reference after using the
API to change any property of the reference, or
after providing a configuration set that did not
exist at the time the set was originally specified
in SourceName. If you omit executing refresh
after any such change, the configuration
reference handle will be stale, and using it will
give incorrect results.
saveAs Save a configuration set to a MATLAB file.

13-27
14

Configuring Models for Targets with


Multicore Processors

• “Concepts in Multicore Programming” on page 14-2


• “Multicore Programming with Simulink” on page 14-8
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17
• “Configure Your Model for Concurrent Execution” on page 14-20
• “Specify a Target Architecture” on page 14-21
• “Partition Your Model Using Explicit Partitioning” on page 14-26
• “Implicit and Explicit Partitioning of Models” on page 14-31
• “Configure Data Transfer Settings Between Concurrent Tasks” on page 14-33
• “Optimize and Deploy on a Multicore Target” on page 14-36
• “Programmatic Interface for Concurrent Execution” on page 14-43
• “Supported Targets for Multicore Programming” on page 14-44
• “Limitations with Multicore Programming in Simulink” on page 14-46
• “Multithreaded Simulation Using For Each Subsystem” on page 14-47
14 Configuring Models for Targets with Multicore Processors

Concepts in Multicore Programming

In this section...
“Basics of Multicore Programming” on page 14-2
“Types of Parallelism” on page 14-2
“System Partitioning for Parallelism” on page 14-5
“Challenges in Multicore Programming” on page 14-6

Basics of Multicore Programming


Multicore programming helps you create concurrent systems for deployment on multicore processor
and multiprocessor systems. A multicore processor system is a single processor with multiple
execution cores in one chip. By contrast, a multiprocessor system has multiple processors on the
motherboard or chip. A multiprocessor system might include a Field-Programmable Gate Array
(FPGA). An FPGA is an integrated circuit containing an array of programmable logic blocks and a
hierarchy of reconfigurable interconnects. A processing node processes input data to produce
outputs. It can be a processor in a multicore or multiprocessor system, or an FPGA.

The multicore programming approach can help when:

• You want to take advantage of multicore and FPGA processing to increase the performance of an
embedded system.
• You want to achieve scalability so your deployed system can take advantage of increasing numbers
of cores and FPGA processing power over time.

Concurrent systems that you create using multicore programming have multiple tasks executing in
parallel. This is known as concurrent execution. When a processor executes multiple parallel tasks, it
is known as multitasking. A CPU has firmware called a scheduler, which handles the tasks that
execute in parallel. The CPU implements tasks using operating system threads. Your tasks can
execute independently but have some data transfer between them, such as data transfer between a
data acquisition module and controller for the system. Data transfer between tasks means that there
is a data dependency.

Multicore programming is commonly used in signal processing and plant-control systems. In signal
processing, you can have a concurrent system that processes multiple frames in parallel. In plant-
control systems, the controller and the plant can execute as two separate tasks. Using multicore
programming helps to split your system into multiple parallel tasks which run simultaneously.

Simulink tries to optimize the host computer performance regardless of the modeling method you
use. For more information on the ways that Simulink helps you to improve performance, see
“Optimize Performance”.

To model a concurrently executing system, see “Partitioning Guidelines” on page 14-31.

Types of Parallelism
The concept of multicore programming is to have multiple system tasks executing in parallel. Types
of parallelism include:

14-2
Concepts in Multicore Programming

• Data parallelism
• Task parallelism
• Pipelining

Data Parallelism

Data parallelism involves processing multiple pieces of data independently in parallel. The processor
performs the same operation on each piece of data. You achieve parallelism by feeding the data in
parallel.

The figure shows the timing diagram for this parallelism. The input is divided into four chunks, A, B,
C, and D. The same operation F() is applied to each of these pieces and the output is OA, OB, OC, and
OD respectively. All four tasks are identical, and they run in parallel.

The time taken per processor cycle, known as cycle time, is t = tF.

The total processing time is also tF, since all four tasks run simultaneously. In the absence of
parallelism, all four pieces of data are processed by one processing node. The cycle time is tF for
each task but the total processing time is 4*tF, since the pieces are processed in succession.

You can use data parallelism in scenarios where it is possible to process each piece of input data
independently. For example, a web database with independent data sets for processing or processing
frames of a video independently are good candidates for data parallelism.

Task Parallelism

In contrast to data parallelism, task parallelism doesn’t split up the input data. Instead, it achieves
parallelism by splitting up an application into multiple tasks. Task parallelism involves distributing
tasks within an application across multiple processing nodes. Some tasks can have data dependency
on others, so all tasks do not run at exactly the same time.

Consider a system that involves four functions. Functions F2a() and F2b() are in parallel, that is, they
can run simultaneously. In task parallelism, you can divide your computation into two tasks. Function
F2b() runs on a separate processing node after it gets data Out1 from Task 1, and it outputs back to
F3() in Task 1.

14-3
14 Configuring Models for Targets with Multicore Processors

The figure shows the timing diagram for this parallelism. Task 2 does not run until it gets data Out1
from Task 1. Hence, these tasks do not run completely in parallel. The time taken per processor cycle,
known as cycle time, is

t = tF1 + max(tF2a, tF2b) + tF3.

You can use task parallelism in scenarios such as a factory where the plant and controller run in
parallel.

Model Pipeline Execution (Pipelining)

Use model pipeline execution, or pipelining, to work around the problem of task parallelism where
threads do not run completely in parallel. This approach involves modifying your system model to
introduce delays between tasks where there is a data dependency.

In this figure, the system is divided into three tasks to run on three different processing nodes, with
delays introduced between functions. At each time step, each task takes in the value from the
previous time step by way of the delay.

Each task can start processing at the same time, as this timing diagram shows. These tasks are truly
parallel and they are no longer serially dependent on each other in one processor cycle. The cycle
time does not have any additions but is the maximum processing time of all the tasks.

t = max(Task1, Task2, Task3) = max(tF1, tF2a, tF2b, tF3).

14-4
Concepts in Multicore Programming

You can use pipelining wherever you can introduce delays artificially in your concurrently executing
system. The resulting overhead due to this introduction must not exceed the time saved by pipelining.

System Partitioning for Parallelism


Partitioning methods help you to designate areas of your system for concurrent execution.
Partitioning allows you to create tasks independently of the specifics of the target system on which
the application is deployed.

Consider this system. F1–F6 are functions of the system that can be executed independently. An
arrow between two functions indicates a data dependency. For example, the execution of F5 has a
data dependency on F3.

Execution of these functions is assigned to the different processor nodes in the target system. The
gray arrows indicate assignment of the functions to be deployed on the CPU or the FPGA. The CPU
scheduler determines when individual tasks run. The CPU and FPGA communicate via a common
communication bus.

14-5
14 Configuring Models for Targets with Multicore Processors

The figure shows one possible configuration for partitioning. In general, you test different
configurations and iteratively improve until you get the optimal distribution of tasks for your
application.

Challenges in Multicore Programming


Manually coding your application onto a multicore processor or an FPGA poses challenges beyond the
problems caused by manual coding. In concurrent execution, you must track:

• Scheduling of the tasks that execute on the embedded processing system multicore processor
• Data transfers to and from the different processing nodes

Simulink manages the implementation of tasks and data transfer between tasks. It also generates the
code that is deployed for the application. For more information, see “Multicore Programming with
Simulink” on page 14-8.

In addition to these challenges, there are challenges when you want to deploy your application to
different architectures and when you want to improve the performance of the deployed application.

Portability: Deployment to Different Architectures

The hardware configuration that runs the deployed application is known as the architecture. It can
contain multicore processors, multiprocessor systems, FPGAs, or a combination of these. Deployment
of the same application to different architectures can require effort due to:

• Different number and types of processor nodes on the architecture


• Communication and data transfer standards for the architecture
• Standards for certain events, synchronization, and data protection in each architecture

To deploy the application manually, you must reassign tasks to different processing nodes for each
architecture. You might also need to reimplement your application if each architecture uses different
standards.

Simulink helps overcome these problems by offering portability across architectures. For more
information, see “How Simulink Helps You to Overcome Challenges in Multicore Programming” on
page 14-9.

Deployment Efficiency

You can improve the performance of your deployed application by balancing the load of the different
processing nodes in the multicore processing environment. You must iterate and improve upon your
distribution of tasks during partitioning, as mentioned in “System Partitioning for Parallelism” on
page 14-5. This process involves moving tasks between different processing nodes and testing the
resulting performance. Since it is an iterative process, it takes time to find the most efficient
distribution.

Simulink helps you to overcome these problems using profiling. For more information, see “How
Simulink Helps You to Overcome Challenges in Multicore Programming” on page 14-9.

Cyclic Data Dependency

Some tasks of a system depend on the output of other tasks. The data dependency between tasks
determines their processing order. Two or more partitions containing data dependencies in a cycle
creates a data dependency loop, also known as an algebraic loop.

14-6
Concepts in Multicore Programming

Simulink identifies loops in your system before deployment. For more information, see “How Simulink
Helps You to Overcome Challenges in Multicore Programming” on page 14-9.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Multicore Programming with Simulink” on page 14-8

14-7
14 Configuring Models for Targets with Multicore Processors

Multicore Programming with Simulink


In this section...
“Basic Workflow” on page 14-8
“How Simulink Helps You to Overcome Challenges in Multicore Programming” on page 14-9

Using the process of partitioning, mapping, and profiling in Simulink, you can address common
challenges of designing systems for concurrent execution.

Partitioning enables you to designate regions of your model as tasks, independent of the details of the
embedded multicore processing hardware. This independence enables you to arrange the content and
hierarchy of your model to best suit the needs of your application.

In a partitioned system, mapping enables you to assign partitions to processing elements in your
embedded processing system. Use the Simulink mapping tool to represent and manage the details of
executing threads, HDL code on FPGAs, and the work that these threads or FPGAs perform. While
creating your model, you do not need to track the partitions or data transfer between them because
the tool does this work. Also, you can reuse your model across multiple architectures.

Profiling simulates deployment of your application under typical computational loads. It enables you
to determine the partitioning and mapping for your model that gives the best performance, before
you deploy to your hardware.

Simulink tries to optimize the host computer performance regardless of the modeling method you
use. For more information on the ways that Simulink helps you to improve performance, see
“Optimize Performance”.

Basic Workflow
To deploy your model to the target.

1 Set up your model for concurrent execution.

For more information about configuring your model for concurrent execution, see “Configure
Your Model for Concurrent Execution” on page 14-20. With these settings, Simulink partitions
your model based on the sample time of blocks at the root level, with each sample time in your
model corresponding to a partition, and all blocks of a single rate or sample time belonging to
the same partition.

If you want to specify how to partition your model, use explicit partitioning. With explicit
partitioning, you must specify a target architecture, and then explicitly partition your model. For
more information, see “Specify a Target Architecture” on page 14-21, and “Partition Your Model
Using Explicit Partitioning” on page 14-26.
2 Generate code and deploy it to your target. You can choose to deploy onto multiple targets.

• To build and deploy on a desktop target, see “Build on Desktop” on page 14-37.
• To deploy onto embedded targets using Embedded Coder, see “Deploy Generated Software”
(Embedded Coder).
• To build and deploy on a real-time target using Simulink Real-Time, see “Standalone
Operation” (Simulink Real-Time).

14-8
Multicore Programming with Simulink

• To deploy onto FPGAs using HDL Coder, see “Deployment” (HDL Coder).

Note Deployment onto FPGAs is supported only for explicitly partitioned models.
3 Optimize your design. This step is optional, and includes iterating over the design of your model
and mapping to get the best performance, based on your metrics. One way to evaluate your
model is to profile it and get execution times.

Product Information
Desktop target “Profile and Evaluate Explicitly Partitioned Models
on a Desktop” on page 14-38
Simulink Real-Time “Execution Profiling for Real-Time Applications”
(Simulink Real-Time)
Embedded Coder “Code Execution Profiling” (Embedded Coder)
HDL Coder “Speed and Area Optimization” (HDL Coder)

How Simulink Helps You to Overcome Challenges in Multicore


Programming
Manually programming your application for concurrent execution poses challenges beyond the
typical challenges with manual coding. With Simulink, you can overcome the challenges of portability
across multiple architectures, efficiency of deployment for an architecture, and cyclic data
dependencies between application components. For more information on these challenges, see
“Challenges in Multicore Programming” on page 14-6.

Portability

Simulink enables you to determine the content and hierarchical needs of the modeled system without
considering the target system. While creating model content, you do not need to keep track of the
number of cores in your target system. Instead, you select the partitioning methods that enable you
to create model content. Simulink generates code for the architecture you specify.

You can select an architecture from the available supported architectures or add a custom
architecture. When you change your architecture, Simulink generates only the code that needs to
change for the second architecture. The new architecture reuses blocks and functions. For more
information, see “Supported Targets for Multicore Programming” on page 14-44 and “Specify a
Target Architecture” on page 14-21.

Deployment Efficiency

To improve the performance of the deployed application, Simulink allows you to simulate it under
typical computational loads and try multiple configurations of partitioning and mapping the
application. Simulink compares the performance of each of these configurations to provide the
optimal configuration for deployment. This is known as profiling. Profiling helps you to determine the
optimum partition configuration before you deploy your system to the desired hardware.

You can create a mapping for your application in which Simulink maps the application components
across different processing nodes. You can also manually assign components to processing nodes. For
any mapping, you can see the data dependencies between components and remap accordingly. You
can also introduce and remove data dependencies between different components.

14-9
14 Configuring Models for Targets with Multicore Processors

Cyclic Data Dependency

Some tasks of a system depend on the output of other tasks. The data dependency between tasks
determines their processing order. Two or more partitions containing data dependencies in a cycle
creates a data dependency loop, also known as an algebraic loop. Simulink does not allow algebraic
loops to occur across potentially parallel partitions because of the high cost of solving the loop using
parallel algorithms.

In some cases, the algebraic loop is artificial. For example, you can have an artificial algebraic loop
because of Model-block-based partitioning. An algebraic loop involving Model blocks is artificial if
removing the use of Model partitioning eliminates the loop. You can minimize the occurrence of
artificial loops. In the Configuration Parameter dialog boxes for the models involved in the algebraic
loop, select Model Referencing > Minimize algebraic loop occurrences.

Ensuring deterministic delay for periodic signals can also help break algebraic loops. To configure
this setting, open Model Settings> Solver > Additional parameters > Configure Tasks. In the
Data Transfer pane, set the default option for Periodic Signals to Ensure deterministic
transfer (maximum delay).

Additionally, if the model is configured for the Generic Real-Time target (grt.tlc) or the Embedded
Real-Time target (ert.tlc) in the Configuration Parameters dialog box, clear the Single output/
update function check box.

If the algebraic loop is a true algebraic condition, you must either contain all the blocks in the loop in
one Model partition, or eliminate the loop by introducing a delay element in the loop.

The following examples show how to implement different types of parallelism in Simulink. These
examples contain models that are partitioned and mapped to a simple architecture with one CPU and
one FPGA.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Concepts in Multicore Programming” on page 14-2
• “Supported Targets for Multicore Programming” on page 14-44
• “Limitations with Multicore Programming in Simulink” on page 14-46

14-10
Implement Data Parallelism in Simulink

Implement Data Parallelism in Simulink

This example shows how to model data parallelism for a system to be deployed on a multicore
processor. The ex_data_parallelism_intial model consists of an input, a functional component
that applies to each input, and a concatenated output. For more information on data parallelism, see
“Types of Parallelism” on page 14-2.

Set this model for concurrent execution. To see the completed model, open the
ex_data_parallelism_top model.

Configure Model for Concurrent Execution

1 Open the ex_data_parallelism_initial model.


2 Convert areas in this model to referenced models. Use the same referenced model to replace
each of the functional components that process the input.

Set Model Configuration Parameters

1 Click Configure Tasks. In the Concurrent Execution dialog box, in the right pane, select the
Enable explicit model partitioning for concurrent behavior check box. With explicit
partitioning, you can partition your model manually.
2 On the Modeling tab, click Model Settings.
3 Select Code Generation > Interface > Advanced parameters. Clear the MAT-file logging
check box.
4 Select Solver, set Type to Fixed-step, and click Apply.
5 On the Solver pane, expand Solver details. Check that Periodic sample time constraint is set
to Unconstrained. Under Tasking and sample time options, select Allow tasks to execute
concurrently on target.

14-11
14 Configuring Models for Targets with Multicore Processors

Partition Model Using Explicit Partitioning

Partition the top model.

In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task four
times to add four new tasks.

Map Blocks to Tasks

In the Concurrent Execution tree, select Tasks and Mapping. On the Map block to tasks pane:

• Under Block: Input, click select task and select Periodic: Task.
• Under Block: Function 1, select Periodic: Task1.
• Under Block: Function 2, select Periodic: Task2.
• Under Block: Function 3, select Periodic: Task3.
• Under Block: Output, select Periodic: Task.

This maps your partitions to the tasks you created. The Input and Output model blocks are on one
task. Each functional component is assigned a separate task.

In the Concurrent Execution tree, select Data transfer. In the Data Transfer Options pane, set
the parameter Periodic signals to Ensure deterministic transfer (minimum delay). Click
Apply and close the Concurrent Execution dialog box.

Finalize Model

Share Configuration Parameters with Referenced Models

Apply configuration parameters to all referenced models.

Initialize Data Dictionary to Store Configuration Set

1 Create a Simulink.data.dictionary.Entry object that represents the configuration set,


which is an entry in the dictionary. For this example, suppose the name of the dictionary is
myData.sldd and the name of the Simulink.ConfigSet object is myConfigs.
2 Store a copy of the target Simulink.ConfigSet object in a temporary variable.
3 Save changes made to the dictionary.
4 Create a freestanding configuration set in the base workspace by copying the active
configuration set of the model.
5 Create a separate configuration reference for the top model and each reference model. To point
the reference to your freestanding configuration, set the SourceName property to
freeConfigSet, the variable that represents your configuration.
6 Attach the configuration reference to each model by using the ConfigSetRef object. To use the
configuration reference in the model, activate it for each model.

For more information, see “Share a Configuration with Multiple Models” on page 13-12, “Automate
Model Configuration by Using a Script” on page 13-24, and “Make Changes to Configuration Set
Stored in Dictionary” on page 80-45.

14-12
Implement Data Parallelism in Simulink

See Also

Related Examples
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44
• “Limitations with Multicore Programming in Simulink” on page 14-46

14-13
14 Configuring Models for Targets with Multicore Processors

Implement Task Parallelism in Simulink

This example shows how to implement task parallelism for a system represented in a Simulink®
model. The ex_task_parallelism_initial model consists of an input, functional components
applied to the same input, and a concatenated output. For more information on task parallelism, see
“Types of Parallelism” on page 14-2.

Set this model for concurrent execution. To see the completed model, open the
ex_task_parallelism_top model.

Configure Model for Concurrent Execution

1 Open the ex_task_parallelism_initial model.


2 Convert areas in this model to referenced models. Use the same referenced model to replace
each of the functional components that process the input.

Set Model Configuration Parameters

1 Click Configure Tasks. In the Concurrent Execution dialog box, in the right pane, select the
Enable explicit model partitioning for concurrent behavior check box. With explicit
partitioning, you can partition your model manually.
2 On the Modeling tab, click Model Settings.
3 Select Code Generation > Interface > Advanced parameters. Clear the MAT-file logging
check box.
4 Select Solver, set Type to Fixed-step, and click Apply.

14-14
Implement Task Parallelism in Simulink

5 On the Solver pane, expand Solver details. Check that Periodic sample time constraint is set
to Unconstrained. Under Tasking and sample time options, select Allow tasks to execute
concurrently on target.
6 Click Configure Tasks.

Partition Model Using Explicit Partitioning

Partition the top model.

In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task three
times to add three new tasks.

Map Blocks to Tasks

In the Concurrent Execution tree, select Tasks and Mapping. On the Map block to tasks pane:

• Under Block: Input, click select task and select Periodic: Task.
• Under Block: Function 1, select Periodic: Task1.
• Under Block: Function 2, select Periodic: Task2.
• Under Block: Output, select Periodic: Task.

The Input and Output model blocks are on one task. Each functional component is assigned a
separate task.

In the Concurrent Execution tree, select Data Transfer. In the Data Transfer Options pane, set
the parameter Periodic signals to Ensure deterministic transfer (minimum delay). Click
Apply and close the Concurrent Execution dialog box.

Finalize Model

Share Configuration Parameters with Referenced Models

Apply configuration parameters to all referenced models.

Initialize Data Dictionary to Store Configuration Set

1 Create a Simulink.data.dictionary.Entry object that represents the configuration set,


which is an entry in the dictionary. For this example, suppose the name of the dictionary is
myData.sldd and the name of the Simulink.ConfigSet object is myConfigs.
2 Store a copy of the target Simulink.ConfigSet object in a temporary variable.
3 Save changes made to the dictionary.
4 Create a freestanding configuration set in the base workspace by copying the active
configuration set of the model.
5 Create a separate configuration reference for the top model and each reference model. To point
the reference to your freestanding configuration, set the SourceName property to
freeConfigSet, the variable that represents your configuration.
6 Attach the configuration reference to each model by using the ConfigSetRef object. To use the
configuration reference in the model, activate it for each model.

For more information, see “Share a Configuration with Multiple Models” on page 13-12, “Automate
Model Configuration by Using a Script” on page 13-24, and “Make Changes to Configuration Set
Stored in Dictionary” on page 80-45.

14-15
14 Configuring Models for Targets with Multicore Processors

Update your model to see the tasks mapped to individual model blocks.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44

14-16
Implement Pipelining in Simulink

Implement Pipelining in Simulink

This example shows how to implement pipelining for a system represented in a Simulink® model. The
ex_task_parallelism_initial model consists of an input, functional components applied to the
same input, and a concatenated output. This example shows how to break up data dependencies
between the tasks so that they can run completely in parallel. For more information on pipelining, see
“Types of Parallelism” on page 14-2.

Set up this model for concurrent execution. To see the completed model, open ex_pipelining_top.

Configure Model for Concurrent Execution

1 Open the ex_task_parallelism_initial model.


2 Convert areas in this model to referenced models. Use the same referenced model to replace
each of the functional components that process the input.

Set Model Configuration Parameters

1 Click Configure Tasks. In the Concurrent Execution dialog box, in the right pane, select the
Enable explicit model partitioning for concurrent behavior check box. With explicit
partitioning, you can partition your model manually.
2 On the Modeling tab, click Model Settings.
3 Select Code Generation > Interface > Advanced parameters. Clear the MAT-file logging
check box.
4 Select Solver, set Type to Fixed-step, and click Apply.

14-17
14 Configuring Models for Targets with Multicore Processors

5 On the Solver pane, expand Solver details. Check that Periodic sample time constraint is set
to Unconstrained. Under Tasking and sample time options, select Allow tasks to execute
concurrently on target.

Partition Model Using Explicit Partitioning

Partition the top model.

In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task three
times to add three new tasks.

Map Blocks to Tasks

In the Concurrent Execution tree, select Tasks and Mapping. On the Map block to tasks pane:

• Under Block: Input, click select task and select Periodic: Task.
• Under Block: Function 1, select Periodic: Task1.
• Under Block: Function 2, select Periodic: Task2.
• Under Block: Output, select Periodic: Task.

This action maps your partitions to the tasks you created. The Input and Output model blocks are on
one task. Each functional component is assigned a separate task.

Finalize Model

Close the Concurrent Execution dialog box.

Share Configuration with Referenced Models

Apply configuration parameters to all referenced models.

Initialize Data Dictionary to Store Configuration Set


1 Create a Simulink.data.dictionary.Entry object that represents the configuration set,
which is an entry in the dictionary. For this example, suppose the name of the dictionary is
myData.sldd and the name of the Simulink.ConfigSet object is myConfigs.
2 Store a copy of the target Simulink.ConfigSet object in a temporary variable.
3 Save changes made to the dictionary.

Set Up Configuration Reference


1 Create a freestanding configuration set in the base workspace by copying the active
configuration set of the model.
2 Create a separate configuration reference for the top model and each reference model. To point
the reference to your freestanding configuration, set the SourceName property to
freeConfigSet, the variable that represents your configuration.
3 Attach the configuration reference to each model by using the ConfigSetRef object. To use the
configuration reference in the model, activate it for each model.

For more information, see “Share a Configuration with Multiple Models” on page 13-12, “Automate
Model Configuration by Using a Script” on page 13-24, and “Make Changes to Configuration Set
Stored in Dictionary” on page 80-45.

Update your model to see the tasks mapped to individual model blocks.

14-18
Implement Pipelining in Simulink

Notice that delays are introduced between different tasks, indicated by the z-1 badge. Introducing
these delays may cause different model outputs in Simulink. Ensure that your model has an expected
output on simulating the parallelized model.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44

14-19
14 Configuring Models for Targets with Multicore Processors

Configure Your Model for Concurrent Execution

Follow these steps to configure your Simulink model to take advantage of concurrent execution.

1 Open your model.


2 On the Modeling tab, click Model Settings.
3 Select Solver, then in the Solver selection section, choose Fixed-step for the Type and auto
(Automatic solver selection) for the Solver.
4 Under Solver details, select Allow tasks to execute concurrently on target. Selecting this
check box is optional for models referenced in the model hierarchy. When you select this option
for a referenced model, Simulink allows each rate in the referenced model to execute as an
independent concurrent task on the target processor.
5 Select Code Generation > Interface > Advanced parameters, clear the MAT-file logging
check box.

Once you have a model that executes concurrently on your computer, you can further configure your
model in the following ways:

• “Specify a Target Architecture” on page 14-21


• “Partition Your Model Using Explicit Partitioning” on page 14-26
• “Configure Data Transfer Settings Between Concurrent Tasks” on page 14-33

See Also

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Implicit and Explicit Partitioning of Models” on page 14-31
• “Specify a Target Architecture” on page 14-21
• “Partition Your Model Using Explicit Partitioning” on page 14-26
• “Configure Data Transfer Settings Between Concurrent Tasks” on page 14-33

14-20
Specify a Target Architecture

Specify a Target Architecture


In this section...
“Choose from Predefined Architectures” on page 14-21
“Define a Custom Architecture File” on page 14-22

For models configured for concurrent execution, you can choose the architecture to which you want
to deploy your model. Choose from a set of predefined architectures in Simulink, or you can create an
interface for a custom architecture. After selecting your architecture, you can use explicit
partitioning to specify which tasks run on it. For more information, see “Partition Your Model Using
Explicit Partitioning” on page 14-26.

Choose from Predefined Architectures


You can choose from the predefined architectures available in Simulink, or you can download support
packages for different available architectures.
1 In the Concurrent Execution dialog box, in the Concurrent Execution pane, click Select. The
concurrent execution target architecture selector appears.

2 Select your target.

Property Description
Multicore Single CPU with multiple cores.
Sample Architecture Single CPU with multiple cores and two FPGAs.
Get more ... Click OK to start the Support Package Installer.
From the list, select the target and follow the
instructions.
3 In the Target architecture window, clear the Preserve compatible properties check box to
reset existing target property settings to their default. Alternatively, select the Preserve
compatible properties check box to preserve existing target property settings.
4 Click OK.

Simulink adds the corresponding software and hardware nodes to the configuration tree
hierarchy. For example, the following illustrates one software node and two hardware nodes
added to the configuration tree when you select Sample architecture as the target
architecture.

14-21
14 Configuring Models for Targets with Multicore Processors

Define a Custom Architecture File


A custom architecture file is an XML file that allows you to define custom target properties for tasks
and triggers. For example, you may want to define custom properties to represent threading APIs.
Threading APIs are necessary to take advantage of concurrency on your target processor.

The following is an example custom architecture file:


<architecture brief="Multicore with custom threading API"
format="1.1" revision="1.1"
uuid="MulticoreCustomAPI" name="MulticoreCustomAPI">
<configurationSet>
<parameter name="SystemTargetFile" value="ert.tlc"/>
<parameter name="SystemTargetFile" value="grt.tlc"/>
</configurationSet>
<node name="MulticoreProcessor" type="SoftwareNode" uuid="MulticoreProcessor"/>
<template name="CustomTask" type="Task" uuid="CustomTask">
<property name="affinity" prompt="Affinity:" value="1" evaluate="true"/>
<property name="schedulingPolicy" prompt="Scheduling policy:" value="Rate-monotonic">
<allowedValue>Rate-monotonic</allowedValue>
<allowedValue>Round-robin</allowedValue>
</property>
</template>
</architecture>

An architecture file must contain:

14-22
Specify a Target Architecture

• The architecture element that defines basic information used by Simulink to identify the
architecture.
• A configurationSet element that lists the system target files for which this architecture is
valid.
• One node element that Simulink uses to identify the multicore processing element.

Note The architecture must contain exactly one node element that identifies a multicore
processing element. You cannot create multiple nodes identifying multiple processing elements or
an architecture with no multicore processing element.
• One or more template elements that list custom properties for tasks and triggers.

• The type attribute can be Task, PeriodicTrigger, or AperiodicTrigger.


• Each property is editable and has the default value specified in the value attribute.
• Each property can be a text box, check box, or combo box. A check box is one where you can
set the value attribute to on or off. A combo box is one where you can optionally list
allowedValue elements as part of the property.
• Each text box property can also optionally define an evaluate attribute. This lets you place
MATLAB variable names as the value of the property.

Assuming that you have saved the custom target architecture file in C:\custom_arch.xml,
register this file with Simulink using the Simulink.architecture.register function.

For example:

1 Save the contents of the listed XML file in custom_arch.xml.


2 In the MATLAB Command Window, type:

Simulink.architecture.register('custom_arch.xml')
3 In the MATLAB Command Window, type:

openExample('slexMulticoreSolverExample')
4 In the Simulink editor, open the Configuration Parameters > Solver pane and click Configure
Tasks. The Concurrent Execution dialog box displays.
5 In the Concurrent Execution pane, click Select... under Target Architecture. The Target
architecture window displays.
6 Select MulticoreCustomAPI and click OK.

14-23
14 Configuring Models for Targets with Multicore Processors

Your Concurrent Execution dialog box updates to contain Code Generation properties for the tasks as
shown. These are the properties defined in the XML file.

14-24
Specify a Target Architecture

See Also

More About
• “Configure Your Model for Concurrent Execution” on page 14-20
• “Partition Your Model Using Explicit Partitioning” on page 14-26
• “Implicit and Explicit Partitioning of Models” on page 14-31

14-25
14 Configuring Models for Targets with Multicore Processors

Partition Your Model Using Explicit Partitioning


When you have a model that is configured for concurrent execution, you can add tasks, create
partitions, and map individual tasks to partitions using explicit partitioning. This enables you to
execute different parts of your model to different parts of your architecture. For more information,
see “Implicit and Explicit Partitioning of Models” on page 14-31.

Prerequisites for Explicit Partitioning


To use explicit partitioning, you must meet the following prerequisites:

1 Set up your model for concurrent execution. For more information, see “Configure Your Model
for Concurrent Execution” on page 14-20.
2 Convert all blocks at the root level of your model into one of the following types of blocks.

• Models that are referenced using Model blocks


• Subsystem blocks
• MATLAB System blocks
• MATLAB Function blocks
• Stateflow charts

For more information, see “Implicit and Explicit Partitioning of Models” on page 14-31.

Note When using referenced models, replicate the model configuration parameters of the top
model to the referenced models. Consider using a single configuration reference to use for all of
your referenced models. For more information, see “Model Configuration Sets”.
3 Select the target architecture on which to deploy your model. For more information, see “Specify
a Target Architecture” on page 14-21.

Add Periodic Triggers and Tasks

Add periodic tasks for components in your model that you want to execute periodically. To add
aperiodic tasks whose execution is trigger based, see “Add Aperiodic Triggers and Tasks” on page 14-
27.

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 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 default color. If you enable sample time colors for your
model, the software honors the setting.

14-26
Partition Your Model Using Explicit Partitioning

4 Click Apply as necessary.

To create more periodic triggers, click the Add periodic trigger symbol. You can also create
multiple periodic triggers with their own trigger sources.

Note Periodic triggers let you represent multiple periodic interrupt sources such as multiple timers.
The periodicity of the trigger is either the base rate of the tasks that the trigger schedules, or the
period of the trigger. Data transfers between triggers can only be Ensure Data Integrity Only
types. With blocks mapped to periodic triggers, you can only generate code for ert.tlc and
grt.tlc system target files.

To delete tasks and triggers, right-click them in the pane and select Delete.

When the periodic tasks and trigger configurations are complete, configure the aperiodic (interrupt)
tasks as necessary. If you do not need aperiodic tasks, continue to “Map Blocks to Tasks, Triggers,
and Nodes” on page 14-28.

Add Aperiodic Triggers and Tasks


Add aperiodic tasks for components in your model whose execution is interrupt-based. To add
periodic tasks whose execution is periodic, see “Add Periodic Triggers and Tasks” on page 14-26.

1 To create an aperiodic trigger, in the Concurrent Execution dialog box, right-click the
Concurrent Execution node and click the Add aperiodic trigger symbol.

A node named InterruptN appears in the configuration tree hierarchy, where N is an integer.
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.

14-27
14 Configuring Models for Targets with Multicore Processors

4 Click Apply.

The software services aperiodic triggers as soon as possible. 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.

To delete tasks and triggers, right-click them in the pane and select Delete.

Once you have created your tasks and triggers, map your execution components to these tasks. For
more information, see “Map Blocks to Tasks, Triggers, and Nodes” on page 14-28.

Tip To set up your model for aperiodic tasks, connect the function call ports of the Model blocks to
Asynchronous Task Specification blocks. Then map the Asynchronous Task Specification blocks to
aperiodic triggers. For more information regarding mapping interrupts, see “Map Blocks to Tasks,
Triggers, and Nodes” on page 14-28.

Map Blocks to Tasks, Triggers, and Nodes


After you create the tasks and triggers, you can explicitly assign partitions to these execution
elements.

1 In the Concurrent Execution dialog box, click the Tasks and Mapping node.

The Tasks and Mapping pane appears. If you add a Model block to your model, the new block
appears in the table with a select task entry under it.

14-28
Partition Your Model Using Explicit Partitioning

2 If you want to add a task to a block, in the Name column, right-click a task under the block and
select Add new entry.
3 To assign a task for the entry, click the box in the Name column and select an entry from the list.
For example, periodic tasks and an aperiodic trigger are mapped to specific blocks.

The block-to-task mapping symbol appears on the top-left corner of the Model block for periodic
tasks or triggers and the top-left corner of the Inport block for aperiodic tasks or triggers.

If you assign a Model block to multiple tasks, multiple task symbols are displayed in the top-left
corner.

To display the Concurrent Execution dialog box from the block, click the block-to-task mapping
symbol.
4 Click Apply.

Note

• System tasks allow you to perform mapping incrementally. If only one periodic trigger is present,
Simulink assigns any Model blocks, subsystem blocks, or MATLAB System blocks that you have
not explicitly mapped to a task, trigger, or hardware node to a task created by the system.
Simulink creates at most one system task for each rate in the model. If multiple periodic triggers

14-29
14 Configuring Models for Targets with Multicore Processors

are created, explicitly map the Model block partitions, subsystems, or MATLAB System blocks to a
task, trigger, or hardware node.
• Map Model block partitions that contain continuous blocks to the same periodic trigger.
• You can map only Model blocks to hardware nodes. Also, if you map the Model block to a
hardware node and the Model block contains multiple periodic sample times, clear the Allow
tasks to execute concurrently on target check box in the Solver pane of the Configuration
Parameters dialog box.

When the mapping is complete, simulate the model again.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Implicit and Explicit Partitioning of Models” on page 14-31

14-30
Implicit and Explicit Partitioning of Models

Implicit and Explicit Partitioning of Models


When implementing multicore programming for your application in Simulink, there are two ways to
partition your model for running on individual processing nodes. If you are new to multicore
programming in Simulink, use the default (implicit partitioning) for your first iteration of
implementing multicore programming.

The automated way of creating tasks and mapping them to your processing nodes is called implicit
partitioning. Simulink partitions your model based on the sample time of blocks at the root level.
Each sample time in your model corresponds to a partition, and all blocks of a single rate or sample
time belong to the same partition. Simulink maps these partitions to tasks that run on your processor.
Implicit partitioning assumes your architecture to be a single multicore CPU. The CPU task scheduler
handles all the partitioned tasks.

If you want to specify how to partition your model, use explicit partitioning. In explicit partitioning,
you create partitions in the root-level model by using referenced models, MATLAB system blocks,
MATLAB Function blocks, Stateflow charts, and Simulink subsystems. For example, if your model has
data acquisition and a controller, partition your model by putting these components in two referenced
models at the model root-level. Each sample time of the blocks in the model corresponds to a
partition. You can add tasks to run on processing nodes in the Concurrent Execution dialog box and
assign your partitions to these tasks. If some partitions are left unassigned, Simulink automatically
assigns them to tasks.

In explicit partitioning, you can specify your own architecture. The default architecture is a multicore
CPU, the same as the assumed architecture in implicit partitioning. Explicit partitioning has more
restrictions on your root-level model than implicit partitioning. For more information, see
“Limitations with Multicore Programming in Simulink” on page 14-46.

Partitioning Guidelines
There are multiple ways to partition your model for concurrent execution in Simulink. Rate-based and
model-based approaches give you primarily graphical means to represent concurrency for systems
that are represented using Simulink and Stateflow blocks. You can partition MATLAB code using the
MATLAB System block and the MATLAB Function block. You can also partition models of physical
systems using multisolver methods.

Each method has additional considerations to help you decide which to use.

Goal Valid Partitioning Methods Considerations


Increase the performance of a No partitioning method Simulink tries to optimize the host
simulation on the host computer. computer performance regardless
of the modeling method you use.
For more information on the ways
that Simulink helps you to improve
performance, see “Optimize
Performance”.

14-31
14 Configuring Models for Targets with Multicore Processors

Goal Valid Partitioning Methods Considerations


Increase the performance of a plant You can use any of the partitioning The processing characteristics of
simulation in a multicore HIL methods and their combinations. the HIL system and the embedded
(hardware-in-the-loop) system. processing system can vary greatly.
Consider partitioning your system
into more units of work than there
are number of processing elements
in the HIL or embedded system.
This convention allows flexibility in
the mapping process.
Create a valid model of a multirate You can use any of the partitioning Partitioning can introduce signal
concurrent system to take methods and their combinations. delays to represent the data
advantage of a multicore processing transfer requirements for
system. concurrent execution. For more
information, see “Configure Data
Transfer Settings Between
Concurrent Tasks” on page 14-33.
Create a valid model of a • Multicore processing: Use any of Consider partitioning for FPGA
heterogeneous system to take the partitioning methods. processing where your
advantage of multicore and FPGA • FPGA processing: Partition your computations have bottlenecks that
processing. model using Model blocks. could be reduced using fine-grained
hardware parallelism.

See Also

Related Examples
• “Implement Data Parallelism in Simulink” on page 14-11
• “Implement Task Parallelism in Simulink” on page 14-14
• “Implement Pipelining in Simulink” on page 14-17

More About
• “Concepts in Multicore Programming” on page 14-2
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44

14-32
Configure Data Transfer Settings Between Concurrent Tasks

Configure Data Transfer Settings Between Concurrent Tasks


Data dependencies arise when a signal originates from one block in one partition and is connected to
a block in another partition. To create opportunities for parallelism, Simulink provides multiple
options for handling data transfers between concurrently executing partitions. These options help you
trade off computational latency for numerical signal delays.

Use the Data Transfer Options pane to define communications between tasks. Set the values for the
Use global setting option of the Data Transfer tab in the Signal Properties dialog box. The table
provides the model-level options that you can apply to each signal that requires data transfer in the
system.

Data Transfer Options

Goal Data Transfer Type Simulation Deployment


• Create opportunity Ensure data integrity Data transfer is Simulink Coder ensures
for parallelism. only. simulated using a one- data integrity during
• Reduce signal step delay. data transfer. Simulink
latency. generates code to
operate with maximum
responsiveness and data
integrity. However, the
implementation is
interruptible, which can
lead to loss of data
during data transfer.

Use a deterministic
execution schedule to
achieve determinism in
the deployment
environment.
• Create opportunity Ensure deterministic Data transfer is Simulink Coder ensures
for parallelism. transfer (maximum simulated using a one- data integrity during
• Produce numeric delay). step delay, which can data transfer. In
results that are have impact on the addition, Simulink
repeatable with each numeric results. To Coder ensures that data
run of the generated compensate, you might transfer is identical with
code. need to specify an initial simulation.
condition for these
delay elements.
• Enforce data Ensure deterministic Data transfer occurs
dependency. transfer (minimum within the same step.
• Produce numeric delay).
results that are
repeatable with each
run of the generated
code.

You can also override these options for each signal from the Data Transfer pane of the Signal
Properties dialog box. For more information, see “Data Transfer Options for Concurrent Execution”.

14-33
14 Configuring Models for Targets with Multicore Processors

For example, consider a control application in which a controller that reads sensory data at time T
must produce the control signals to the actuator at time T+Δ.

• If the sequential algorithm meets the timing deadlines, consider using option 3.
• If the embedded system provides deterministic scheduling, consider using option 2.
• Otherwise, use option 1 to create opportunities for parallelism by introducing signal delays.

For continuous signals, Simulink uses extrapolation methods to compensate for numerical errors that
were introduced due to delays and discontinuities in data transfer.

To avoid numerical errors in signals configured for Ensure Data Integrity Only and Ensure
deterministic transfer (maximum delay) data transfers, you may need to provide an initial
condition. 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 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.

14-34
Configure Data Transfer Settings Between Concurrent Tasks

3 Apply your changes.

See Also

More About
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44
• “Implicit and Explicit Partitioning of Models” on page 14-31

14-35
14 Configuring Models for Targets with Multicore Processors

Optimize and Deploy on a Multicore Target

In this section...
“Generate Code” on page 14-36
“Build on Desktop” on page 14-37
“Profile and Evaluate Explicitly Partitioned Models on a Desktop” on page 14-38
“Customize the Generated C Code” on page 14-42

This topic shows how to use a model that is configured for concurrent execution using explicit
partitioning and deploy it onto a target. To set up your model for concurrent execution, see
“Configure Your Model for Concurrent Execution” on page 14-20. To specify the target architecture,
see “Specify a Target Architecture” on page 14-21. To use explicit partitioning in a model that is set
up for concurrent execution, see “Partition Your Model Using Explicit Partitioning” on page 14-26.

Generate Code
To generate code for a model that is configured for concurrent execution, on the Apps tab of the
Simulink editor, select Simulink Coder. On the C Code tab, select Build. The resulting code
includes:

• C code for parts of the model that are mapped to tasks and triggers in the Concurrent Execution
dialog box. C code generation requires a Simulink Coder license. For more information, see “Code
Generation” (Simulink Coder) and “Code Generation” (Embedded Coder).
• HDL code for parts of the model that are mapped to hardware nodes in the Concurrent Execution
dialog box. HDL code generation requires an HDL Coder license. For more information, see “HDL
Code Generation from Simulink” (HDL Coder).
• Code to handle data transfer between the concurrent tasks and triggers and to interface with the
hardware and software components.

The generated C code contains one function for each task or trigger defined in the system. The task
and trigger determines the name of the function:

void <TriggerName>_TaskName(void);

The content for each such function consists of target-independent C code, except for:

• Code corresponding to blocks that implement target-specific functionality


• Customizations, including those derived from custom storage classes (see “Organize Parameter
Data into a Structure by Using Struct Storage Class” (Embedded Coder)) or “Code Replacement
Libraries” (Simulink Coder)
• Code that is generated to handle how data is transferred between tasks. In particular, Simulink
Coder uses target-specific implementations of mutual exclusion primitives and data
synchronization semaphores to implement the data transfer as described in the following table of
pseudocode.

14-36
Optimize and Deploy on a Multicore Target

Data Transfer Initialization Reader Writer


Data Integrity BufferIndex = 0; Begin mutual exclusion Write Buffer[ BufferIndex ];
Initialize Buffer[1] with IC Tmp = 1 - BufferIndex; Begin mutual exclusion
Only End mutual exclusiton BufferIndex = 1 - BufferIndex;
Read Buffer[ Tmp ]; End mutual exclusion

Ensure WriterIndex = 0; Read Buffer[ ReaderIndex ]; Write Buffer[ WriterIndex ]


ReaderIndex = 1; ReaderIndex = 1 - ReaderIndex; WriterIndex = 1 - WriterIndex;
Determinism Initialize Buffer[1] with IC
(Maximum
Delay)
Ensure N/A Wait dataReady; Wait readDone;
Read data; Write data;
Determinism Post readDone; Post dataReady;
(Minimum
Delay)
Data Integrity The Simulink Coder and HDL Coder products both take advantage of target-specific
Only communication implementations and devices to handle the data transfer between hardware
and software components.
C-HDL interface

The generated HDL code contains one HDL project for each hardware node.

Build on Desktop
Simulink Coder and Embedded Coder targets provide an example target to generate code for
Windows, Linux and macOS operating systems. It is known as the native threads example, which is
used to deploy your model to a desktop target. The desktop may not be your final target, but can help
to profile and optimize your model before you deploy it on another target.

If you have specified an Embedded Coder target, make the following changes in the Configuration
Parameters dialog box.

1 Select the Code Generation > Templates > Generate an example main program check box.
2 From the Code Generation > Templates > Target Operating System list, select
NativeThreadsExample.
3 Click OK to save your changes and close the Configuration Parameters dialog box.
4 Apply these settings to all referenced models in your model.

Once you have set up your model, press Ctrl-B to build and deploy it to your desktop. The native
threads example illustrates how Simulink Coder and Embedded Coder use target-specific threading
APIs and data management primitives, as shown in “Threading APIs Used by Native Threads
Example” on page 14-37. The data transfer between concurrently executing tasks behaves as
described in Data Transfer Options. The coder products use the APIs on supported targets for this
behavior, as described in “Data Protection and Synchronization APIs Used by Native Threads
Example” on page 14-38.

Threading APIs Used by Native Threads Example

Aspect of Concurrent Linux Implementation Windows macOS


Execution Implementation Implementation
Periodic triggering POSIX timer Windows timer Not applicable
event

14-37
14 Configuring Models for Targets with Multicore Processors

Aspect of Concurrent Linux Implementation Windows macOS


Execution Implementation Implementation
Aperiodic triggering POSIX real-time signal Windows event POSIX non-real-time
event signal
Aperiodic trigger For blocks mapped to Thread waiting for an For blocks mapped to
an aperiodic task: event an aperiodic task:
thread waiting for a thread waiting for a
signal signal

For blocks mapped to For blocks mapped to


an aperiodic trigger: an aperiodic trigger:
signal action signal action
Threads POSIX Windows POSIX
Threads priority Assigned based on Priority class inherited Assigned based on
sample time: fastest from the parent sample time: fastest
task has highest priority process. task has highest priority

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.
Example of overrun Yes Yes No
detection

Data Protection and Synchronization APIs Used by Native Threads Example

API Linux Implementation Windows Implementation macOS Implementation


Data protection • pthread_mutex_init • CreateMutex • pthread_mutex_init
API • pthread_mutex_‐ • CloseHandle • pthread_mutex_‐
destroy • WaitForSingleObject destroy
• pthread_mutex_lock • ReleaseMutex • pthread_mutex_lock
• pthread_mutex_unlock • pthread_mutex_unlock
Synchronization • sem_init • CreateSemaphore • sem_open
API • sem_destroy • CloseHandle • sem_unlink
• sem_wait • WaitForSingleObject • sem_wait
• sem_post • ReleaseSemaphore • sem_post

Profile and Evaluate Explicitly Partitioned Models on a Desktop


Profile the execution of your code on the multicore target using the Profile Report pane of the
Concurrent Execution dialog box. You can profile using Simulink Coder (GRT) and Embedded Coder
(ERT) targets. Profiling helps 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, you can compare the average execution times of the tasks. If a task is computation

14-38
Optimize and Deploy on a Multicore Target

intensive, or does not satisfy real-time requirements and overruns, you can break it into tasks that
are less computation intensive and that can run concurrently.

When you generate a profile report, the software:

1 Builds the model.


2 Generates code for the model.
3 Adds tooling to the generated code to collect data.
4 Executes the generated code on the target and collects data.
5 Collates the data, generates an HTML file (model_name_ProfileReport.html) in the current
folder, and displays that HTML file in the Profile Report pane of the Concurrent Execution
dialog box.

Note If an HTML profile report exists for the model, the Profile Report pane displays that file.

To generate a new profile report, click .

Section Description
Summary Summarizes model execution statistics, such as total
execution time and profile report creation time. It also lists
the total number of cores on the host machine.
Task Execution Time Displays the execution time, in microseconds, for each task
in a pie chart color coded by task.

Visible for Windows, Linux, and macOS platforms.


Task Affinitization to Processor Cores Platform-dependent. For each time step and task, Simulink
displays the processor core number the task started
executing on at that time step, color coded by processor.

If there is no task scheduled for a particular time step, NR


is displayed.

Visible for Windows and Linux platforms.

After you analyze the profile report, consider changing the mapping of Model blocks to efficiently use
the concurrency available on your multicore system (see “Map Blocks to Tasks, Triggers, and Nodes”
on page 14-28).

Generate Profile Report

This topic assumes a previously configured model ready to be profiled for concurrent execution. For
more information, see “Configure Your Model for Concurrent Execution” on page 14-20.

1 In the Concurrent Execution dialog box, click the Profile report node.

The profile tool looks for a file named model_name_ProfileReport.html. If such a file does
not exist for the current model, the Profile Report pane displays the following.

14-39
14 Configuring Models for Targets with Multicore Processors

Note If an HTML profile report exists for the model, the Profile Report pane displays that file.

To generate a new profile report, click .


2 Enter the number of time steps for which you want the profiler to collect data for the model
execution.
3 Click the Generate task execution profile report button.

This action builds the model, generates code, adds data collection tooling to the code, and
executes it on the target, which also generates an HTML profile report. This process can take
several minutes. When the process is complete, the contents of the profile report appear in the
Profile Report pane. For example:

14-40
Optimize and Deploy on a Multicore Target

The profiling report shows the summary, execution time for each task, and the mapping of each
task to processor cores. We see that tasks 1 and 2 run on core 0, where tasks 3 and 4 run on core
1. The Task Execution Time section of the report indicates that task 1 and task 3 take the most
amount of time to run. Note that the period of task 3 is twice that of tasks 1 and 2, and the period
of task 4 is twice that of task 3.
4 Analyze the profile report. Create and modify your model or task mapping if needed, and
regenerate the profile report.

Generate Profile Report at Command Line

Alternatively, you can generate a profile report for a model configured for concurrent execution at the
command line. Use the Simulink.architecture.profile function.

For example, to create a profile report for the model slexMulticoreSolverExample:

openExample('slexMulticoreSolverExample');
Simulink.architecture.profile('slexMulticoreSolverExample');

To create a profile report with a specific number of samples (100) for the model
slexMulticoreSolverExample:

Simulink.architecture.profile('slexMulticoreSolverExample',120);

14-41
14 Configuring Models for Targets with Multicore Processors

The function creates a profile report named


slexMulticoreSolverExample_ProfileReport.html in your current folder.

Customize the Generated C Code


The generated code is suitable for many different applications and development environments. To
meet your needs, you can customize the generated C code as described in “Code and Tool
Customization” (Embedded Coder). In addition to those customization capabilities, for multicore and
heterogeneous targets you can further customize the generated code as follows:

• You can register your preferred implementation of mutual exclusion and data synchronization
primitives using the code replacement library.
• You can define a custom target architecture file that allows you to specify target specific
properties for tasks and triggers in the Concurrent Execution dialog box. For more information,
see “Define a Custom Architecture File” on page 14-22.

See Also

Related Examples
• “Assign Tasks to Cores for Multicore Programming”

More About
• “Multicore Programming with Simulink” on page 14-8

14-42
Programmatic Interface for Concurrent Execution

Programmatic Interface for Concurrent Execution


Use these functions to configure models for concurrent execution.

To Use
Create or convert configuration Simulink.architecture.config
for concurrent execution.
Add triggers to the software Simulink.architecture.add
node or add tasks to triggers.
Delete triggers or tasks. Simulink.architecture.delete
Find objects with specified Simulink.architecture.find_system
parameter values.
Get configuration parameters Simulink.architecture.get_param
for target architecture.
Import and select architecture. Simulink.architecture.importAndSelect
Generate profile report for Simulink.architecture.profile
model configured for concurrent
execution.
Add custom target architecture. Simulink.architecture.register
Set properties for a concurrent Simulink.architecture.set_param
execution object (such as task,
trigger, or hardware node).
Configure concurrent execution Simulink.GlobalDataTransfer
data transfers.

Map Blocks to Tasks


To map blocks to tasks, use the set_param function.

Map a block to one task:


set_param(block,'TargetArchitectureMapping',[bdroot 'CPU/PeriodicTrigger1/Task1']);

Map a block to multiple tasks:


set_param(block,'TargetArchitectureMapping',...
{[bdroot 'CPU/PeriodicTrigger1/Task1'];...
[bdroot 'CPU/PeriodicTrigger1/Task2']});

Get the current mapping of a block:

get_param(block,'TargetArchitectureMapping');

See Also

More About
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44

14-43
14 Configuring Models for Targets with Multicore Processors

Supported Targets for Multicore Programming

Supported Multicore Targets


You can build and download models that are implicitly or explicitly partitioned for the following
multicore targets using system target files:

• Linux, Windows, and macOS using ert.tlc and grt.tlc.


• Simulink Real-Time using slrealtime.tlc.

Note

• To build and download your model, you must have Simulink Coder software installed.
• To build and download your model to a Simulink Real-Time system, you must have Simulink Real-
Time software installed. You must also have a multicore target system supported by the Simulink
Real-Time product.
• Deploying to an embedded processor that runs Linux and VxWorks operating systems requires the
Embedded Coder product.

Supported Heterogeneous Targets


In addition to multicore targets, Simulink also supports building and downloading partitions of an
explicitly partitioned model to heterogeneous targets that contain a multicore target and one or more
field-programmable gate arrays (FPGAs).

Select the heterogeneous architecture using the Target architecture option in the Concurrent
Execution dialog box Concurrent Execution pane:

Item Description
Sample Architecture Example architecture consisting of single CPU with
multiple cores and two FPGAs. You can use this
architecture to model for concurrent execution.
Simulink Real-Time Simulink Real-Time target containing FPGA boards.
Xilinx Zynq ZC702 evaluation kit Xilinx® Zynq® ZC702 evaluation kit target.
Xilinx Zynq ZC706 evaluation kit Xilinx Zynq ZC706 evaluation kit target.
Xilinx Zynq Zedboard Xilinx Zynq ZedBoard™ target.
Altera Cyclone V SoC development Altera® Cyclone® SoC Rev. C development kit target.
kit Rev. C
Altera Cyclone V SoC development Altera Cyclone SoC Rev. D development kit target.
kit Rev. D
Arrow SoCKit development board Arrow® SoCKit development board target.

Note Building HDL code and downloading it to FPGAs requires the HDL Coder product. You can
generate HDL code if:

14-44
Supported Targets for Multicore Programming

• You have an HDL Coder license


• You are building on Windows or Linux operating systems

You cannot generate HDL code on Macintosh systems.

See Also

More About
• “Multicore Programming with Simulink” on page 14-8

14-45
14 Configuring Models for Targets with Multicore Processors

Limitations with Multicore Programming in Simulink


The following limitations apply when partitioning a model for concurrent execution.

• Configure the model to use the fixed-step solver.


• These model settings should not be used for models in the concurrent execution environment:

• External mode for Mac desktop targets.


• Logging to MAT-files (MAT-file logging check box selected). However, you can use the To
Workspace and To File blocks.
• 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.
• If you want to use explicit partitioning, at the root level of your model, the model must consist
entirely of

• Models that are referenced using Model blocks


• Subsystem blocks
• MATLAB System blocks
• MATLAB Function blocks
• Stateflow charts
• Rate Transition blocks
• Virtual connectivity blocks

The following are valid virtual connectivity blocks:

• Goto and From blocks


• Ground and Terminator blocks
• Inport and Outport blocks
• Virtual subsystem blocks that contain permitted blocks

See Also

More About
• “Multicore Programming with Simulink” on page 14-8
• “Supported Targets for Multicore Programming” on page 14-44

14-46
Multithreaded Simulation Using For Each Subsystem

Multithreaded Simulation Using For Each Subsystem

This example shows how to speed up execution of a model on multiple cores using a For Each
subsystem in Rapid Accelerator simulation mode.

Measure the Single-Threaded Simulation Time

In this model, a For Each subsystem accepts a numeric array input. Each element of the array serves
as an upper bound in each iteration and feeds into a computationally-intensive algorithm represented
by the MATLAB Function block inside the subsystem. The algorithm implemented in the MATLAB
Function block computes the largest prime number within a given range using a brute force method,
which is for illustrative purposes only.

modelName = 'slexForEachMultithreaded';
open_system(modelName);

By default, the multithreaded simulation support for the For Each subsystem is enabled. To opt out of
multithreaded simulation, issue a set_param command in the MATLAB® Command Window. In a
single-threaded simulation, the computations in different iterations of the For Each subsystem are
executed sequentially during each time step.

set_param(modelName, 'MultithreadedSim', 'off');

Build the Rapid Accelerator target for the model. The progress of the code generation and build
process is displayed in the MATLAB Command Window. To suppress this display, wrap the command
inside evalc.

evalc('Simulink.BlockDiagram.buildRapidAcceleratorTarget(modelName)');

14-47
14 Configuring Models for Targets with Multicore Processors

This build step is optional because Simulink® automatically generates the Rapid Accelerator
simulation target the first time you simulate the model. In the example, this step serves to separate
the overhead in generating the Rapid Accelerator target from the actual model execution time.

Once the Rapid Accelerator target is generated, simulate the model and measure the simulation time
using tic and toc.

tic
evalc('sim(modelName)');
toc

Elapsed time is 61.810143 seconds.

Use Multithreaded Simulation for Speedup on Multiple Cores

To explicitly opt in to multithreading support, issue a set_param command in the MATLAB


Command Window. In a multithreaded simulation, the computations in different iterations of the For
Each subsystem are assigned to multiple cores and executed in parallel for speedup.

set_param(modelName, 'MultithreadedSim', 'auto');

Build the Rapid Accelerator target again, since the model has been reconfigured.

evalc('Simulink.BlockDiagram.buildRapidAcceleratorTarget(modelName)');

Simulate the model again and measure the multithreaded simulation time. Notice that the model
simulation runs over two times faster than the single-threaded simulation on a machine with four or
more cores. Remember that operating system context-switching in multithreaded simulations always
results in extra overhead.

tic
evalc('sim(modelName)');
toc

Elapsed time is 27.171541 seconds.

Clean Up

Close the model and remove the generated files.

bdclose(modelName);

See Also
For Each Subsystem | For Each

14-48
15

Modeling Best Practices

• “General Considerations When Building Simulink Models” on page 15-2


• “Model a Continuous System” on page 15-6
• “Best-Form Mathematical Models” on page 15-9
• “Model a Simple Equation” on page 15-12
• “Model Differential Algebraic Equations” on page 15-14
• “Basic Modeling Workflow” on page 15-23
• “Model a System Algorithm” on page 15-25
• “Create Model Components” on page 15-27
• “Manage Signal Lines” on page 15-30
• “Manage Model Data” on page 15-36
• “Reuse Model Components from Files” on page 15-38
• “Create Interchangeable Variations of Model Components” on page 15-41
• “Set Up a File Management System” on page 15-43
15 Modeling Best Practices

General Considerations When Building Simulink Models


In this section...
“Avoiding Invalid Loops” on page 15-2
“Shadowed Files” on page 15-3
“Model Building Tips” on page 15-5

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 15-6) 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 “Using Function-Call Subsystems” on page 10-53 for a
description of function-call subsystems)
• Self-triggering subsystems and loops containing non-latched triggered subsystems (see “Using
Triggered Subsystems” on page 10-18 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

For triggered and function-call subsystem examples, see “Simulink Subsystem Semantics”.

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 Model from the Modeling tab of
the toolstrip. If the model contains invalid loops, the invalid loops are highlighted. This is illustrated
in the following model.

15-2
General Considerations When Building Simulink Models

and displays an error message in the Diagnostic Viewer.

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

15-3
15 Modeling Best Practices

Tip To help avoid problems with shadowed files, turn on the Simulink preference Do not load
models that are shadowed on the MATLAB path. See “Do not load models that are shadowed on
the MATLAB path”.

The rules Simulink software uses to find Model files are similar to those used by MATLAB software.
See “What Is the MATLAB Search Path?”. 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.

Making Sure the Correct Block Diagram Is Loaded

When using libraries and referenced models, you can load a block diagram without showing its
window. If the MATLAB path or the current MATLAB folder changes while block diagrams are in
memory, these block diagrams can interfere with the use of other files of the same name.

For example, open a model with a library called mylib, change to another folder, and then open
another model with a library also called mylib. When you run the first model, it uses the library
associated with the second model.

This can lead to problems including:

• Simulation errors
• "Unresolved Link" icons on blocks that are library links
• Wrong results

Detecting and Fixing Problems

To help avoid problems with shadowed files, you can turn on the Simulink preference Do not load
models that are shadowed on the MATLAB path. See “Do not load models that are shadowed on
the MATLAB path”.

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

15-4
General Considerations When Building Simulink Models

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:

• 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 “Group Blocks into Subsystems” on page 4-20.
The Model Browser provides useful information about complex models (see Simulink Editor).
• 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 81-4 and “Annotate Models” on page 1-76.
• Modeling strategies

If several of your models use the same blocks, you can save these blocks for easy reuse. For
example, you can save a collection of blocks in a custom library. Then, when you build new
models, you can copy these blocks from the library.

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.

See Also

Related Examples
• “Model a Continuous System” on page 15-6
• “Best-Form Mathematical Models” on page 15-9
• “Model a Simple Equation” on page 15-12
• “Model Differential Algebraic Equations” on page 15-14

More About
• “Component-Based Modeling Guidelines” on page 23-2

15-5
15 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 on the Format tab,
click Flip left-right . 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 “Connect Single
Output Port to Multiple Input Ports” on page 1-38.

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.

The Scope displays x at each time step. For a simulation lasting 10 seconds, the output looks like this:

15-6
Model a Continuous System

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

15-7
15 Modeling Best Practices

See Also

More About
• “General Considerations When Building Simulink Models” on page 15-2
• “Component-Based Modeling Guidelines” on page 23-2

15-8
Best-Form Mathematical Models

Best-Form Mathematical Models


In this section...
“Series RLC Example” on page 15-9
“Solving Series RLC Using Resistor Voltage” on page 15-9
“Solving Series RLC Using Inductor Voltage” on page 15-10

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.

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.

V AC = V R + V L + V C

Using Ohm's law to solve for the voltage across each element of the circuit, the equation for this
circuit can be written as


di 1 t
V AC = Ri + L + 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.

Solving Series RLC Using Resistor Voltage


Solving the RLC circuit for the resistor voltage yields

V R = Ri


di 1 t
Ri = V AC − L − 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.

15-9
15 Modeling Best Practices

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. 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 Loop Concepts” 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.

di
VL = L
dt


di 1 t
L = V AC − 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.

15-10
Best-Form Mathematical Models

This model contains only integrator blocks and no algebraic loops. As a result, the model simulates
faster and more accurately.

See Also

Related Examples
• “Model a Simple Equation” on page 15-12
• “Model Differential Algebraic Equations” on page 15-14

More About
• “General Considerations When Building Simulink Models” on page 15-2
• “Component-Based Modeling Guidelines” on page 23-2

15-11
15 Modeling Best Practices

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.

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.

15-12
Model a Simple Equation

See Also

Related Examples
• “Best-Form Mathematical Models” on page 15-9
• “Model Differential Algebraic Equations” on page 15-14

More About
• “General Considerations When Building Simulink Models” on page 15-2
• “Component-Based Modeling Guidelines” on page 23-2

15-13
15 Modeling Best Practices

Model Differential Algebraic Equations


In this section...
“Overview of Robertson Reaction Example” on page 15-14
“Simulink Models from ODE and DAE Equations” on page 15-14
“Simulink Model from ODE Equations” on page 15-14
“Simulink Model from DAE Equations” on page 15-17
“Simulink Model from DAE Equations Using Algebraic Constraint Block” on page 15-19

Overview of Robertson Reaction Example


Robertson [1] on page 15-21 created a system of autocatalytic chemical reactions to test and
compare numerical solvers for stiff systems. The reactions, rate constants (k), and reaction rates (V)
for the system are given as follows:
k1
A B k1 = 0.04 V 1 = k1[A]
k2
7
B+B C + B k2 = 3 ⋅ 10 V 2 = k2[B][B]
k3
4
B+C A + C k3 = 1 ⋅ 10 V 3 = k3[B][C]

Because there are large differences between the reaction rates, the numerical solvers see the
differential equations as stiff. For stiff differential equations, some numerical solvers cannot converge
on a solution unless the step size is extremely small. If the step size is extremely small, the simulation
time can be unacceptably long. In this case, you need to use a numerical solver designed to solve stiff
equations.

Simulink Models from ODE and DAE Equations

This example uses these three models:

• ex_hb1ode — Simulink® model from ordinary differential equations (ODE).


• ex_hb1dae — Simulink model from differential algebraic equations (DAE).
• ex_h1bdae_acb — Simulink model from DAE equations using Algebraic Constraint block.

To access these files, open the live script.

Simulink Model from ODE Equations


A system of ordinary differential equations (ODE) has the following characteristics:

• All of the equations are ordinary differential equations.


• Each equation is the derivative of a dependent variable with respect to one independent variable,
usually time.
• The number of equations is equal to the number of dependent variables in the system.

15-14
Model Differential Algebraic Equations

Using the reaction rates, you can create a set of differential equations describing the rate of change
for each chemical species. Since there are three species, there are three differential equations in the
mathematical model.

4
A′ = − 0.04A + 1 ⋅ 10 BC
4 7 2
B′ = 0.04A − 1 ⋅ 10 BC − 3 ⋅ 10 B
7 2
C′ = 3 ⋅ 10 B
Initial conditions: A = 1, B = 0, and C = 0.

Build the Model

Create a model, or open the model ex_hb1ode.

1 Add three Integrator blocks to your model. Label the inputs A', B', and C', and the outputs A, B,
and C respectively.
2 Add Sum, Product, and Gain blocks to solve each differential variable. For example, to model the
signal C',

a Add a Math Function block and connect the input to signal B. Set the Function parameter to
square.
b Connect the output from the Math Function block to a Gain block. Set the Gain parameter to
3e7.
c Continue to add the remaining differential equation terms to your model.
3 Model the initial condition of A by setting the Initial condition parameter for the A Integrator
block to 1.
4 Add Out blocks to save the signals A, B, and C to the MATLAB variable yout.

15-15
15 Modeling Best Practices

Simulate the Model

Create a script that uses the sim command to simulate your model. This script saves the simulation
results in the MATLAB variable yout. Since the simulation has a long time interval and B initially
changes very fast, plotting values on a logarithmic scale helps to visually compare the results. Also,
4
since the value of B is small relative to the values of A and C, multiply B by 1 ⋅ 10 before plotting the
values.

1 Enter the following statements in a MATLAB script. If you built your own model, replace
ex_hblode with the name of your model.

sim('ex_hb1ode')
yout(:,2) = 1e4*yout(:,2);
figure;
semilogx(tout,yout);
xlabel('Time');
ylabel('Concentration');
title('Robertson Reactions Modeled with ODEs')
2 From the Simulink Editor, on the Modeling tab, click Model Settings.

— In the Solver pane, set the Stop time to 4e5 and the Solver to ode15s (stiff/NDF).

— In the Data Import pane, select the Time and Output check boxes.
3 Run the script. Observe that all of A is converted to C.

15-16
Model Differential Algebraic Equations

Simulink Model from DAE Equations


A system of differential algebraic equations (DAE) has the following characteristics:

• It contains both ordinary differential equations and algebraic equations. Algebraic equations do
not have any derivatives.
• Only some of the equations are differential equations defining the derivatives of some of the
dependent variables. The other dependent variables are defined with algebraic equations.
• The number of equations is equal to the number of dependent variables in the system.

Some systems contain constraints due to conservation laws, such as conservation of mass and energy.
If you set the initial concentrations toA = 1, B = 0, and C = 0, the total concentration of the three
species is always equal to 1 since A + B + C = 1. You can replace the differential equation for C′with
the following algebraic equation to create a set of differential algebraic equations (DAEs).

C=1− A−B

The differential variables A and B uniquely determine the algebraic variable C.

4
A′ = − 0.04A + 1 ⋅ 10 BC
4 7
B′ = 0.04A − 1 ⋅ 10 BC − 3 ⋅ 10 B2
C=1− A−B

Initial conditions: A = 1and B = 0.

Build the Model

Make these changes to your model or to the model ex_hb1ode, or open the model ex_hb1dae.

1 Delete the Integrator block for calculating C.

15-17
15 Modeling Best Practices

2 Add a Sum block and set the List of signs parameter to +– –.


3 Connect the signals A and B to the minus inputs of the Sum block.
4 Model the initial concentration of A with a Constant block connected to the plus input of the Sum
block. Set the Constant value parameter to 1.
5 Connect the output of the Sum block to the branched line connected to the Product and Out
blocks.

Simulate the Model

Create a script that uses the sim command to simulate your model.

1 Enter the following statements in a MATLAB script. If you built your own model, replace
ex_hbldae with the name of your model.

sim('ex_hb1dae')
yout(:,2) = 1e4*yout(:,2);
figure;
semilogx(tout,yout);
xlabel('Time');
ylabel('Concentration');
title('Robertson Reactions Modeled with DAEs')
2 From the Simulink Editor, on the Modeling tab, click Model Settings.

— In the Solver pane, set the Stop time to 4e5 and the Solver to ode15s (stiff/NDF).

— In the Data Import pane, select the Time and Output check boxes.
3 Run the script. The simulation results when you use an algebraic equation are the same as for
the model simulation using only differential equations.

15-18
Model Differential Algebraic Equations

Simulink Model from DAE Equations Using Algebraic Constraint Block


Some systems contain constraints due to conservation laws, such as conservation of mass and energy.
If you set the initial concentrations toA = 1, B = 0, and C = 0, the total concentration of the three
species is always equal to 1 since A + B + C = 1.

You can replace the differential equation for C′with an algebraic equation modeled using an Algebraic
Constraint block and a Sum block. The Algebraic Constraint block constrains its input signal F(z) to
zero and outputs an algebraic state z. In other words, the block output is a value needed to produce a
zero at the input. Use the following algebraic equation for input to the block.

0= A+B+C−1

The differential variables A and B uniquely determine the algebraic variable C.

4
A′ = − 0.04A + 1 ⋅ 10 BC
4 7
B′ = 0.04A − 1 ⋅ 10 BC − 3 ⋅ 10 B2
C=1− A−B

−3
Initial conditions: A = 1, B = 0, and C = 1 ⋅ 10 .

Build the Model

Make these changes to your model or to the model ex_hb1ode, or open the model ex_hb1dae_acb.

1 Delete the Integrator block for calculating C.


2 Add an Algebraic Constraint block. Set the Initial guess parameter to 1e-3.
3 Add a Sum block. Set the List of signs parameter to –+++.
4 Connect the signals A and B to plus inputs of the Sum block.

15-19
15 Modeling Best Practices

5 Model the initial concentration of A with a Constant block connected to the minus input of the
Sum block. Set the Constant value parameter to 1.
6 Connect the output of the Algebraic Constraint block to the branched line connected to the
Product and Out block inputs.
7 Create a branch line from the output of the Algebraic Constraint block to the final plus input of
the Sum block.

Simulate the Model

Create a script that uses the sim command to simulate your model.

1 Enter the following statements in a MATLAB script. If you built your own model, replace
ex_hbl_acb with the name of your model.
sim('ex_hb1dae_acb')
yout(:,2) = 1e4*yout(:,2);
figure;
semilogx(tout,yout);
xlabel('Time');
ylabel('Concentration');
title('Robertson Reactions Modeled with DAEs and Algebraic Constraint Block')
2 From the Simulink Editor, on the Modeling tab, click Model Settings.

— In the Solver pane, set the Stop time to 4e5 and the Solver to ode15s (stiff/NDF).

— In the Data Import pane, select the Time and Output check boxes.
3 Run the script. The simulation results when you use an Algebraic Constraint block are the same
as for the model simulation using only differential equations.

15-20
Model Differential Algebraic Equations

Using an Algebraic Constraint block creates an algebraic loop in a model, If you set the Algebraic
Loop parameter to warning (on the Modeling tab, click Model Settings, then select Diagnostics),
the following message displays in the Diagnostic Viewer during simulation.

For this model, the algebraic loop solver was able to find a solution for the simulation, but algebraic
loops don’t always have a solution, and they are not supported for code generation. For more
information about algebraic loops in Simulink models and how to remove them, see “Algebraic Loop
Concepts” on page 3-39.

References
[1] Robertson, H. H. “The solution of a set of reaction rate equations.” Numerical Analysis: An
Introduction (J. Walsh ed.). London, England:Academic Press, 1966, pp. 178–182.

15-21
15 Modeling Best Practices

See Also

Related Examples
• “Best-Form Mathematical Models” on page 15-9

More About
• “General Considerations When Building Simulink Models” on page 15-2
• “Compare Capabilities of Model Components” on page 23-8

15-22
Basic Modeling Workflow

Basic Modeling Workflow


In large, well-defined projects, you define file management and model architecture upfront. Your
predefined requirements drive components and interfaces.

To understand how to create such projects, you must know how to create scalable models that
represent system equations. This example shows how file storage and model architecture change to
satisfy evolving project requirements as model size and complexity increases.

The example starts with a simple model that represents an algorithm.

The model grows and evolves into a simple project that manages the model, subsystem, and
supporting files required by the model hierarchy.

Walk through these steps to follow along with the modeling decisions as the model hierarchy evolves.

1 “Model a System Algorithm” on page 15-25


2 “Create Model Components” on page 15-27
3 “Manage Signal Lines” on page 15-30
4 “Manage Model Data” on page 15-36

15-23
15 Modeling Best Practices

5 “Reuse Model Components from Files” on page 15-38


6 “Create Interchangeable Variations of Model Components” on page 15-41
7 “Set Up a File Management System” on page 15-43

You can use the files provided at any of these steps as starting points for your design. The final
example helps you create a project that contains the model components and supporting files
developed in this example set.

15-24
Model a System Algorithm

Model a System Algorithm

When incomplete system requirements and a developing system design prevent you from defining file
management and model architecture upfront, you can still model fundamental system algorithms. By
organizing the model into inputs, outputs, and systems, you create a general framework for model
components as the model grows.

To show the first stage of a modeling workflow that begins with limited information, this example
uses a simple mechanical system composed of a mass, spring, and damper.

This second-order differential equation characterizes the system.

In this equation:

• is mass.
• is the damping coefficient.
• is the spring constant.
• is acceleration.
• is velocity.
• is displacement.
• is external force.

Solving for provides a form of this equation that maps more clearly to a Simulink® model.

The model named ex_modeling_simple_system represents this equation.

15-25
15 Modeling Best Practices

A Sum block computes the net force applied to the mass. The Gain block labeled 1/m computes the
acceleration of the mass by multiplying the net force by . The Integrator, Second-Order block
solves for the velocity and position of the mass.

The model organizes the blocks into three areas:

• The area named Sources contains system inputs.


• The area named System contains blocks that represent the system, or plant.
• The area named Sinks contains system outputs.

By organizing the model upfront, you create a general framework for model components as the model
grows.

Because this example shows a model in the preliminary stages of development, the actual input force
is unknown and can be represented by a variety of standard source blocks. The model uses a Step
block connected as input to the system. Some alternative source blocks are shown but commented
out. For example, you can use the From Spreadsheet block to load empirical data if the data is
available.

Similarly, a variety of sink blocks can accept the output displacement. To check whether simulation
results meet expectations, the model uses a Scope block to visualize the signals.

See Also

More About
• “Sources”
• “Sinks”

15-26
Create Model Components

Create Model Components

As you gather requirements for a system, you identify model components. You can identify where
component interfaces exist even with incomplete specifications.

To define model components without affecting simulation results and specifying an interface that may
change, you can create subsystems and visually organize the model.

Some components, such as digital controllers, should execute as a single unit within the model. For
these standalone components with known boundaries, you can use an atomic subsystem. Defining
atomic components upfront prevents costly refactoring when you want to generate standalone code.

Model ex_modeling_components contains four common model components.

• Mechanical System — A mass separated from a surface by a spring and damper


• Controller — Algorithm that controls the motion of the mechanical system
• Operator — Logic that defines the commands sent to the controller
• Environment — External disturbances that affect the mechanical system

The thicker line weight on the Controller block indicates that the controller is an atomic subsystem.

The ports on each of the Subsystem blocks correspond to input and output blocks within the
subsystem. The block label shows the name of the corresponding port. For example, the Inport block
labeled disturbance corresponds with the disturbance port of the Mechanical System block.

15-27
15 Modeling Best Practices

The four model components interact to determine the position of the mass.

The controller computes the force required to move the mechanical system to its goal position.

The operator determines the goal position of the mass and implements the related procedural logic
with a Stateflow® chart.

The environment generates a disturbance force that affects the mechanical system.

During simulation, the operator tells the controller to wait 2 seconds, then move the mass up 2
meters. When the mass overshoots the goal position, the operator tells the controller to position the
mass 1 meter above its original position. After 5 seconds, an environmental disturbance applies a
steady force to the physical system and the controller reacts to stabilize the mass at the goal position.

15-28
Create Model Components

See Also

More About
• “Group Blocks into Subsystems” on page 4-20
• “Expand Subsystem Contents” on page 4-30
• “Share Data with Simulink and the MATLAB Workspace” (Stateflow)

15-29
15 Modeling Best Practices

Manage Signal Lines

As a model grows, model components help functionally and visually organize blocks in the model. To
similarly organize signal lines in the model, you can apply a variety of strategies, such as grouping
signals into buses.

To demonstrate how to reduce signal line clutter, this example implements a model with multiple
sensors and actuators. The system has two springs, dampers, and masses. A beam connects the two
masses.

Sensors read the displacement of the masses. The controller regulates the height at the center of the
beam and levels the beam by computing the force the actuators must apply to the masses. The
controller uses the height difference between the beam ends, , to level the beam.

The model named ex_modeling_signals represents the system and its environment, operator, and
controller.

15-30
Manage Signal Lines

To display signals after simulation, the model uses two Scope blocks. One Scope block shows the goal
and actual beam levelness. The other Scope block shows the goal and actual position of the beam at
its center, along with the actual beam position at both ends.

15-31
15 Modeling Best Practices

Mark Signals for Logging

To reduce the number of signal lines, you can connect a viewer directly to signal lines or enable data
logging for signal lines. By choosing a way to visualize simulation data without using a sink block, you
can avoid extra signal lines.

The model named ex_modeling_simulation_data_inspector removes the Scope blocks and


related signal lines then enables data logging for those signals.

In the Operator subsystem, the signals labeled x_goal and delta_goal are marked for logging, as
indicated by the icon that appears above each signal.

In the Controller subsystem, the signals labeled x and delta are marked for logging.

15-32
Manage Signal Lines

In the Mechanical System subsystem, the signals labeled x1 and x2 are marked for logging.

The Simulation Data Inspector lets you view the logged signal data after simulation.

15-33
15 Modeling Best Practices

Group Signals in Buses

To further reduce the number of signal lines, you can group signal lines into a bus by using a Bus
Creator or Out Bus Element block. All signal lines retain their identities when grouped in a bus and
can be separated downstream from the bus.

By creating buses, the model named ex_modeling_composite_signals provides an even more


readable system representation.

15-34
Manage Signal Lines

This model enables data logging for the signal lines associated with the buses named x_sensor and
goal instead of logging data individually for each of the signals in these buses.

The simulation results remain the same after signals are grouped in buses.

See Also

More About
• “Decide How to Visualize Simulation Data” on page 33-2
• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Inspect Simulation Data” on page 31-179
• “Composite Interface Guidelines” on page 82-2
• “Explore Simulink Bus Capabilities”

15-35
15 Modeling Best Practices

Manage Model Data

To define a parameter value that multiple blocks or models use, you can use variables. Separately
updating numerical parameter values at each instance of the parameter can be inefficient and error
prone. You can update the value of a variable in the workspace or source file that defines it. Having a
single source for this information facilitates scalability and reusability of model components.

To specify value ranges, data types, tunability, and other characteristics of signals, states, and block
parameters, you can use the Simulink.Parameter and Simulink.Signal objects. While you can
use variables or objects to specify parameter values, this example uses variables for simplicity.

You can define variables by using these supporting file types:

• MAT-file
• MATLAB file
• Data dictionary

To load data for small models, you can use model callbacks. For large model hierarchies, different
loading methods are more efficient.

In model ex_modeling_data, a PreLoadFcn model callback evaluates MATLAB file


ex_modeling_data_variables.m, which defines variables , , and in the base workspace. Gain
blocks in the mechanical system and PID Controller blocks in the controller use these variables.

15-36
Manage Model Data

You can interactively change variable values at the MATLAB® command prompt. You can also use
tools like the Model Data Editor to edit values.

See Also

More About
• “Create, Edit, and Manage Workspace Variables” on page 73-124
• “Determine Where to Store Variables and Objects for Simulink Models” on page 73-109
• “Data Objects” on page 73-76

15-37
15 Modeling Best Practices

Reuse Model Components from Files

When working on a large model, you can separate it into multiple files so that team members can
develop different model components at the same time. You can reuse these components multiple
times in a model and in other models.

Model, library, and subsystem files provide a single source for multiple instances of the same model
component. To learn when you should use each of these componentization methods, see “Component-
Based Modeling Guidelines” on page 23-2.

Subsystems

Model ex_modeling_component_reuse references the contents of subsystem file


ex_modeling_mechanical_system.slx twice to represent identical mechanical subsystems.

While you can define a subsystem for reuse in either a library or subsystem file, subsystem files allow
for easier editing. When you edit a referenced subsystem, the changes apply to the subsystem file and
all instances of the referenced subsystem.

15-38
Reuse Model Components from Files

Models

Model ex_modeling_component_reuse references the contents of model file


ex_modeling_controller.slx. Controller code is often deployed on embedded systems, so having
a standalone controller model is useful.

An embedded processor might not support default properties for the controller. Since a controller
model might be used to generate code for an embedded processor, these constraints apply to the
referenced controller model and the interface with its parent model:

• Fixed Signal Attributes — To require that buses at model interfaces share the same signal
attributes, bus objects specify signal attributes at the three sets of input and output ports.

15-39
15 Modeling Best Practices

• Discrete Sample Time — To specify a discrete sample time, model ex_modeling_controller


specifies a discrete execution domain and script ex_modeling_data_controller.m specifies
discrete PID controller values.
• Fixed Data Type — To apply the single-precision data type required by the embedded processor,
Data Type Conversion blocks convert the bus element data types before they reach the model
interface.

See Also

More About
• “Component-Based Modeling Guidelines” on page 23-2
• “Create Custom Library” on page 45-2
• “Model Reference Basics” on page 8-2

15-40
Create Interchangeable Variations of Model Components

Create Interchangeable Variations of Model Components

To add flexibility to a model so that it can cater to different requirements, you can use variant
subsystems and models. Variants allow you to choose among multiple variations of a component
within a single model. You can change the active variant without modifying the model by changing
the values of variant control variables at the MATLAB® command prompt.

Model ex_modeling_variants includes three variant choices for the operator subsystem.

Operator 1 is the active variant, which is defined by script ex_modeling_variant_choice.m. To


determine the goal position for the mechanical system, this operator implements procedural logic
with a Stateflow® chart.

Inactive variants and their contents are grayed out. To define the goal position for the mechanical
system position, inactive variant subsystem Operator 2 uses a Waveform Generator block.

15-41
15 Modeling Best Practices

Variant choice Operator 3 is an inactive variant model. Variant Subsystem blocks allow both
subsystems and models as variant choices.

See Also

More About
• “What Are Variants and When to Use Them” on page 12-3
• “Working with Variant Choices” on page 12-59

15-42
Set Up a File Management System

Set Up a File Management System

As a model grows, managing referenced files and dependencies becomes more complicated. To
reduce the complexity of managing large models, you can use projects. Projects in Simulink help to
organize large model hierarchies by finding required files, managing and sharing files and settings,
and interacting with source control.

Open the project BasicModelingProject, which contains these files:

• Subsystem file ex_modeling_mechanical_system.slx


• Model file ex_modeling_variants.slx
• Model file ex_modeling_controller.slx
• Model file ex_modeling_operator_variant.slx
• MATLAB script ex_modeling_data_mechanical_system.m
• MATLAB script ex_modeling_data_controller.m
• MATLAB script ex_modeling_variant_choice.m
• MATLAB function ex_modeling_bus_objects.m

The MATLAB scripts and function are configured to Run at Startup.

The top model in the model hierarchy has a project shortcut. To open this model, on the Project
Shortcuts tab, click Open Top Model.

Using this project, you can explore project capabilities, such as these capabilities:

• Automate tasks
• Create shortcuts for common actions
• Analyze file dependencies
• Analyze the impact of changing files
• Compare model files

In the Views pane of the project, select Dependency Analyzer.

15-43
15 Modeling Best Practices

To run a dependency analysis on all the files in the project, click Analyze.

In the dependency graph that opens, click a dependency arrow to display its properties, including its
dependency type, in the Properties pane. In this example, the MATLAB scripts and functions are run
by model callbacks. Since these files run at startup in the project, the model callbacks are redundant
and can be removed.

The dependency graph also shows the two-level model hierarchy, in which the top model depends on
a referenced subsystem and referenced models.

See Also
Dependency Analyzer | Comparison Tool

More About
• “What Are Projects?” on page 16-3
• “Automate Startup Tasks” on page 16-30
• “About Source Control with Projects” on page 19-2

15-44
Set Up a File Management System

• “Perform an Impact Analysis” on page 18-15

15-45
16

Project Setup

• “Organize Large Modeling Projects” on page 16-2


• “What Are Projects?” on page 16-3
• “Explore Project Tools with the Airframe Project” on page 16-5
• “Create a Project from a Model” on page 16-12
• “Set MATLAB Projects Preferences” on page 16-14
• “Create a New Project from a Folder” on page 16-18
• “Add Files to the Project” on page 16-22
• “Create a New Project from an Archived Project” on page 16-24
• “Create a New Project Using Templates” on page 16-25
• “Open Recent Projects” on page 16-26
• “Specify Project Details, Startup Folder, and Derived Files Folders” on page 16-27
• “Specify Project Path” on page 16-28
• “What Can You Do with Project Shortcuts?” on page 16-29
• “Automate Startup Tasks” on page 16-30
• “Automate Shutdown Tasks” on page 16-32
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Use Shortcuts to Find and Run Frequent Tasks” on page 16-35
• “Create Templates for Standard Project Settings” on page 16-36
16 Project Setup

Organize Large Modeling Projects


You can use projects to help you organize your work. 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 “Explore
Project Tools with the Airframe Project” on page 16-5.
2 Create a new project. See “Create a New Project from a Folder” on page 16-18.
3 Use the Dependency Analyzer to analyze your project and check required files. See “Run a
Dependency Analysis” on page 18-5.
4 Explore views of your files. See “Work with Project Files” on page 17-7.
5 Create shortcuts to save and run frequent tasks. See “Use Shortcuts to Find and Run Frequent
Tasks” on page 16-35.
6 Run custom task operations on batches of files. See “Run a Project Custom Task and Publish
Report” on page 17-29.
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 “About Source Control with Projects” on page 19-2.

For guidelines on structuring projects, see “Component-Based Modeling Guidelines” on page 23-2.

See Also

More About
• “Explore Types of Model Components” on page 23-4
• “Compare Capabilities of Model Components” on page 23-8
• “Define Interfaces of Model Components” on page 23-24
• “Configuration Management” on page 23-28

16-2
What Are Projects?

What Are Projects?


You can use 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.

If your work involves any of the following:

• More than one model file


• More than one model developer
• More than one model version

— then a project can help you organize your work. You can manage all the files you need in one place
— all MATLAB and Simulink files, and any other file types you need such as data, requirements,
reports, spreadsheets, tests, or generated files.

Projects can promote more efficient team work and individual productivity by helping you:

• Find all the files that belong with your project.


• Create standard ways to initialize and shut down a project.
• Create, store, and easily access common operations.
• View and label modified files for peer review workflows.
• Share projects using built-in integration with Subversion® (SVN) or Git, external source control
tools.

Starting in R2019a, you can use projects in MATLAB, with or without Simulink. You can share
projects with users who do not have Simulink.

For information on basic project workflows in MATLAB, see “Projects”.

Projects provide additional tools to help with Simulink workflows. For example:

• Opening models and running customizations on startup


• Checking for shadowed model files
• Dependency analysis of models, subsystems, libraries and library blocks, data files, requirements,
and generated code
• Automatic refactoring help for models, libraries, library links, model references, model callbacks,
S-functions, buses and bus elements
• Comparing and merging differences in models.

For help on project workflows in Simulink, see “Project Management”.

See the Web page https://www.mathworks.com/products/simulink/projects.html for the


latest information, downloads, and videos.

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 “Explore
Project Tools with the Airframe Project” on page 16-5.
2 Create a new project. See “Create a New Project from a Folder” on page 16-18.
3 Analyze your project and check required files by using the Dependency Analyzer. See “Run a
Dependency Analysis” on page 18-5.

16-3
16 Project Setup

4 Explore views of your files. See “Work with Project Files” on page 17-7.
5 Create shortcuts to save and run frequent tasks. See “Use Shortcuts to Find and Run Frequent
Tasks” on page 16-35.
6 Run custom task operations on batches of files. See “Run a Project Custom Task and Publish
Report” on page 17-29.
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 “About Source Control with Projects” on page 19-2.

For guidelines on structuring projects, see “Collaborative Modeling”.

See Also

More About
• “Component-Based Modeling Guidelines” on page 23-2
• “Define Interfaces of Model Components” on page 23-24
• “Configuration Management” on page 23-28

16-4
Explore Project Tools with the Airframe Project

Explore Project Tools with the Airframe Project

In this section...
“Explore the Airframe Project” on page 16-5
“Set Up Project Files and Open the Project” on page 16-5
“View, Search, and Sort Project Files” on page 16-6
“Open and Run Frequently Used Files” on page 16-6
“Review Changes in Modified Files” on page 16-7
“Run Dependency Analysis” on page 16-8
“Run Project Integrity Checks” on page 16-10
“Commit Modified Files” on page 16-10
“View Project and Source Control Information” on page 16-10

Explore the Airframe Project


Try an example project to see how the tools can help you organize your work. Projects can help you
manage:

• Your design (model and library files, .m, .mat, and other files, source code for S-functions, and
data)
• A set of actions to use with your project (run setup code, open models, simulate, build, and 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 source control.
2 Examine project shortcuts to access frequently used files and tasks.
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.

Set Up Project Files and Open the Project


Run this command to create a working copy of the project files and open the project:

openExample('simulink/AirframeProjectExample')

The project example copies files to your temporary folder so that you can edit them and put them
under Git source control.

The Project window 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.

16-5
16 Project Setup

Note Alternatively, you can try this example project using SVN source control, by specifying
openExample('simulink/UsingAProjectWithSVNExample'). The following example shows the
options when using Git.

View, Search, and Sort Project Files


1 In a Project, examine the Files view to manage the files within your project. When the Project
(number of files) view is selected, only the files in your project are shown.
2 To see all the files in your sandbox, click All. 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 from your sandbox.
3 To find particular files or file types, in any file view, type in the search box or click the Filter
button. You can also search inside files.

Click the x to clear the search.


4 To view files as a list instead of a tree, use the Layout control.
5 To sort files and to customize the columns, click the Organize view button at the far right of the
search box.
6 You can dock and undock the Project into the MATLAB Desktop. If you want to maximize space
for viewing your project files, undock the Project. Drag the title bar to undock it.

Open and Run Frequently Used Files


You can use shortcuts to make scripts easier to find in a large project. View and run shortcuts on the
Project Shortcuts toolstrip. You can organize the shortcuts into groups.

In this example, the script that regenerates S-functions is set as 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.slx, is a shortcut.

Regenerate the S-functions.

1 On the Project Shortcuts tab in the toolstrip, click the shortcut Rebuild Project's S-functions.

The shortcut file builds a MEX-file. If you do not have a compiler set up, follow the instructions to
choose a compiler.
2 Open the rebuild_s_functions.m file to explore how it works.

Open the top model.

16-6
Explore Project Tools with the Airframe Project

• On the Project Shortcuts tab, click the shortcut F14 Model to open the root model for this
project.
• To create shortcuts to access frequently used files, select the Files view, right-click a file, and
select Create Shortcut.

You can also specify files to run at startup and shutdown. See “Automate Startup Tasks” on page 16-
30.

Review Changes in Modified Files


Open and make changes to files and review changes.
1 Select the Files view. View folders using the tree layout, and then expand the utilities folder.
2 Either double-click to open the find_top_models file for editing from the project, or right-click
and select Open.
3 Make a change in the Editor, such as adding a comment, and save the file.
4 In the project Files view, select the tab Modified (number of files). After editing the file, you
see Modified (2). The files you changed appear in the list. You edited a file in the utilities folder.
Observe that the Modified files list also includes a resources folder. The files stored in the
resources folder are internal project definition files generated by your changes. The project
definition files allow you to add metadata to files, for example, by creating shortcuts, adding
labels, and adding a project description. Project definition files also define the files that are
added to your project. You can review changes in revisions of project definition files like any
other project files. See “Project Definition Files” on page 19-44.
5 To review changes, right-click the find_top_models file in the Modified files view and select
Compare > Compare to Ancestor.

16-7
16 Project Setup

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. The comparison report type can
differ depending on the file you select. If you select a Simulink model to Compare > Compare
to Ancestor, this command runs a Simulink model comparison.

To compare models, try the following example.

1 In the Files view, select the Project (number of files) tab, and expand the models folder.
2 Either double-click to open the AnalogControl file for editing from the project, or right-click
and select Open.
3 Make a change in the model, such as opening a block and changing some parameters, and then
save the model.
4 To review changes, select the Modified (number of files) tab. Right-click the modified model
file and select Compare > Compare to Ancestor.

The Comparison Tool opens a report.

Run Dependency Analysis


To check that all required files are in the project, run a file dependency analysis on the modified files
in your project.

1 On the Project tab, click on the down arrow to expand the Tools gallery. Under Apps, click
Dependency Analyzer.

The dependency graph displays the structure of all analyzed dependencies in the project. The
Properties pane lists required products, add-ons, and any problem files.

16-8
Explore Project Tools with the Airframe Project

2 To highlight the problem files, in the Properties pane, in the Problems section, point to the

message File not in Project and click the magnifying glass icon .
3 Select the dependency arrow to examine the dependency type. timesthree.mexw64 is an S-
function binary file required by f14_airframe.slx. You can 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.

4 To remove the file from the problem files list, right-click the file and select Hide Warnings. The
next time you run a dependency analysis, the file does not appear as a problem file.

In this example, you do not want to add the binary file to the project, but instead use the script to
regenerate the binary file from the source code in the project. Use Hide Warnings to stop such
files being marked as problems.
5 View dependencies of the modified files.

a In the Dependency Analyzer toolstrip, in the Views section, click Source Control. The color
of each file in the graph now represents its source control status.
b In the dependency graph, select the modified files. To select multiple files, press Shift and
click the files.
c In the Dependency Analyzer toolstrip, in the Impact Analysis section, click All
Dependencies.

16-9
16 Project Setup

Run Project Integrity Checks


To make sure that your changes are ready to commit, check your project. To run the project integrity
checks, on the Project tab, click the down arrow to expand the Tools gallery. Under Project Checks,
click Check Project. The checks look for missing files, files to add to source control or retrieve from
source control, and other issues. The checks dialog box can offer automatic fixes to problems found.
When you click a Details button in the Checks dialog box, you can view recommended actions and
decide whether to make the changes.

Commit Modified Files


After you modify files and you are satisfied with the results of the checks, you can commit your
changes to the source control repository.

1 In the Files view, select the Modified (number of files) tab. The files you changed appear in the
list.
2 To commit your changes to source control, on the Project tab, in the Source Control section, click
Commit.
3 Enter a comment for your submission, and click Submit.

Watch the messages in the status bar as the source control commits your changes. Git commits to
your local repository. To commit to the remote repository, use Push in the Source Control
section. See “Pull, Push, and Fetch Files with Git” on page 19-54.

View Project and Source Control Information


• To view and edit project details, on the Project tab, in the Environment section, click Details.
View and edit details such as the name, description, project root, startup folder, and generated
files folders such as the slprj folder.
• To view details about the source control integration and repository location, on the Project tab, in
the Source Control section, click Git Details. This Airframe example project uses Git source
control.

Alternatively, use the project API to get the current project:

project = currentProject;

You can use the project API to get all the project details and manipulate the project at the command
line. See currentProject.

For next steps, see “Project Management”.

See Also

Related Examples
• “Create a New Project from a Folder” on page 16-18
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Automate Startup Tasks” on page 16-30
• “Perform an Impact Analysis” on page 18-15

16-10
Explore Project Tools with the Airframe Project

• “Add a Project to Source Control” on page 19-5


• “View Modified Files” on page 19-44

More About
• “What Are Projects?” on page 16-3
• “What Can You Do with Project Shortcuts?” on page 16-29
• “Sharing Projects” on page 17-31
• “About Source Control with Projects” on page 19-2

16-11
16 Project Setup

Create a Project from a Model

Create a project to organize your model and any dependent files. Use Create Project from Model to
run a dependency analysis on your top model to identify required files.

Tip For a simpler option that automates more steps for you, see instead “Create a New Project from
a Folder” on page 16-18.

Projects can help you organize your work and collaborate in teams. The project can help you to:

• Find all your required files


• Manage and share files, settings, and user-defined tasks
• Interact with source control.

1 In a Simulink model, on the Simulation tab, select New > Project > New Project from this
Model.

Simulink runs dependency analysis on your model to identify required files and a project root
location that contains all dependencies.
2 In the Create Project dialog box, edit any settings you want to change:

• Name — By default, the name of the suggested project root folder. Edit if desired.
• Folder — A folder that dependency analysis identified to contain all dependencies. If you
want, click to select a different folder in the file system hierarchy between the file system root
and the model folder.

All file dependencies in the project root folder are included in the project. All external
dependencies are listed under Dependencies. If required files are outside your project root
folder, then you cannot add these files to your project. An external 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.
3 Click OK to create the project containing your model and any other specified files.

For an example showing what you can do with projects, see “Explore Project Tools with the Airframe
Project” on page 16-5.

See Also

Related Examples
• “Create a New Project from a Folder” on page 16-18
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Automate Startup Tasks” on page 16-30
• “Open Recent Projects” on page 16-26
• “Explore Project Tools with the Airframe Project” on page 16-5

16-12
Create a Project from a Model

More About
• “What Are Projects?” on page 16-3
• “What Can You Do with Project Shortcuts?” on page 16-29
• “Sharing Projects” on page 17-31
• “About Source Control with Projects” on page 19-2

16-13
16 Project Setup

Set MATLAB Projects Preferences

You can set MATLAB projects preferences to specify project definition files type, detect project files
that are shadowed by open models, and detect project-wide references when you rename, remove,
and delete files.

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Project.
Then, adjust preference options as this table describes. Not all project preferences are available in
MATLAB Online.

Preference Usage
New Projects To specify where to create new projects, in Default folder, browse to a
folder on your system.
To specify the Project definition files type for new projects, select an
option based on your use case:

• Use multiple project files (fixed path length) is preferable if you


need to work with long paths (default).
• Use multiple project files avoids file conflicts when you perform
merge on shared projects.
• Use a single project file (not recommended for source control) is
fast but often causes merge issues when two users submit changes in
the same project to a source control tool.

For details, see “Project Definition Files”.


The Project definition folder path, relative to the project root, contains
the project metadata files. Select one of the available options to specify
the folder name.
To open the project welcome page after you create a new project, select
Show the welcome dialog after new project creation.
Project Startup To receive a warning about files that are shadowed by open models when
you open a project, select Detect project files shadowed by open
models.

For details, see “Manage Shadowed and Dirty Models and Other Project
Files” on page 17-8.
Git does not track empty folders and ignores them when you commit.
MATLAB enables you to recreate an empty folder structure in your
project. Doing so is useful for small projects intended for training or as
procedure templates.

For large projects, to avoid performance issues on startup, disable


Recreate empty project folders in a project under Git.

16-14
Set MATLAB Projects Preferences

Preference Usage
To disable the warning you receive when opening a project from an
unknown source for the first time, clear Warn when opening projects
from unknown sources.

For details, see “Unsafe Content Warning”.

This preference is available only in MATLAB Online.


Project Shutdown To receive a warning about files with unsaved changes when you close a
project, select Interrupt project close if there are dirty project files.
To automatically close project models when you close a project unless the
project models contain unsaved changes, select Check for open project
models and close them, unless they are dirty.
File Management To disable the message that lists which files have changed after calling
update to get the latest revisions from your SVN repository, clear Show
changes on source control updates.
To disable automatic updates when you rename, delete, or remove files in
a project, clear Detect project-wide references when renaming,
removing and deleting files.

For details, see “Manage Project Files”.


To disable the project prompt and analysis when you rename buses or bus
elements while keeping automatic updates enabled for other files, clear
Detect project-wide references when renaming Simulink buses and
bus elements.

This option is available only if you have Simulink installed.


To specify the project behavior when you attempt to modify Read-only
project files, select an option based on your use case:

• Ask when a read-only project file needs to be modified (default)


• Set writable using the file system
• Checkout using source control
When you open a file, you can have a project check for conflict markers
that the source control tool inserts. This check helps you to identify
conflicted files and offers a fix to rescue binary files, such as SLX files,
from corruption.

To choose which files a project checks for conflict markers, specify


Conflict marker detection when loading project files. Select one of
these options:

• Only check conflicted files (default)


• Check all files
• Never check files

16-15
16 Project Setup

Preference Usage
When you add project files to a folder that is not on the path, you can
choose whether MATLAB notifies you before adding the folder to the
project path. In Update project path when adding files to a folder
that is not on the path, select one of these options:

• Ask before adding folder to project path (default)


• Always update project path
• Never update project path

This preference is available only in MATLAB Online.


Warnings Calling SVN update to get the latest revision overwrites all of your files.
To receive a warning before overwriting the files, select Warn about
updating from source control.
To receive a warning when you perform an action that a project cannot
reverse, select Warn when performing an action that the project
cannot undo.

For example, a project cannot undo extracting a folder to a referenced


project.
Only one project can be open at a time. To receive a warning that the
current project will close when you open a referenced project as a top-
level project, select Warn when opening a project reference that the
current project will be closed.
To receive a warning when you remove a reference to another project,
select Warn when removing references to another project.
Logging To save the Java stack trace in a log file whenever project shows an error
dialog, select Log errors.
Projects can log startup and shutdown events. Log files include timing
details that enable you to identify which action is hanging or taking a long
time to run.

To save project action messages, such as how long shortcuts take to start
up, select Log messages.
To specify where to store your project log files, in Log folder, browse to a
folder on your system.

If you enabled Log messages, the project stores the events in a date-
stamped file in the location you specified in Log folder.

See Also

More About
• “Create Projects”
• “Manage Project Files”
• “Project Definition Files”

16-16
Set MATLAB Projects Preferences

• “Manage Shadowed and Dirty Models and Other Project Files” on page 17-8

16-17
16 Project Setup

Create a New Project from a Folder

If you have many files that you want to organize into a project, with or without source control, use the
following steps to create a new project.

Note If you want to retrieve a project from a source control repository, see instead “Clone Git
Repository” on page 19-33 or “Check Out SVN Repository” on page 19-35.

Easily convert a folder of files into a project by using the Folder to Project template in the Simulink
start page. The template automatically adds your files to the project and prompts you to set up the
path and startup files. This simple, quick process sets up your project to manage your files and
introduces you to project features. When you open the project, it automatically puts the folders you
need on the path, and runs any setup operations to configure your environment. Startup files
automatically run (.m and .p files), load (.mat files), and open (Simulink models) when you open the
project.

To create a new project to manage your files:

• On the MATLAB Home tab, select New > Project > From Folder.
• Alternatively, in the Simulink start page, click the Folder to Project template. You can also, on
the Simulation tab, select New > Project > New Project from the Model Editor.

1 In the New Project dialog box, enter a project name, browse to select the folder containing your
files, and click OK.
2 In the Welcome to your project dialog box, click Set Up Project to continue.

3 In the Set Up Project (Step 1 of 2) dialog box, optionally choose folders to add to the project
path. When you open the project, it adds these folders to your MATLAB search path, and removes

16-18
Create a New Project from a Folder

them when you close the project. Add project folders to ensure dependency analysis detects
project files. To add all project folders, click Add with Subfolders and then select the project
folder containing all your subfolders. Alternatively, you can set up the project path later. Click
Next.

4 In the Set Up Project (Step 2 of 2) dialog box, optionally specify startup and shutdown files.

• Use startup files to configure settings when you open the project. Startup files automatically
run (.m and .p files), load (.mat files), or open (Simulink models) when you open the project.
• Use shutdown files to specify MATLAB code to run as the project shuts down. You do not need
to use shutdown files to close models when you close a project, because it automatically
closes any project models that are open, unless they are dirty. The project prompts you to
save or discard changes.

Click Add to specify startup or shutdown files. Alternatively, you can setup these files later.

16-19
16 Project Setup

5 Click Finish and your new project opens. The Folder to Project template automatically adds all
your files to the project. The template does not add derived files to your project.

For next steps, try dependency analysis to visualize the structure of your project, or consider
adding source control to help you manage versions. For details, see “Run a Dependency Analysis”
on page 18-5 or “Add a Project to Source Control” on page 19-5.

As alternatives to the Folder to Project template, you can:

• Create a project from a model by analyzing it for dependent files that you want to put in a project.
See “Create a Project from a Model” on page 16-12
• Create projects manually, but then you need to add files to the project and configure the path,
startup, and shutdown files. To examine the alternative templates, or to use your own templates:
1 In the Simulink start page, click templates in the list to read the descriptions. If you selected a
new project option to open the start page, the list shows only project templates, or you can
filter the list for Project Templates using the list next to the Search box.

• Select the Blank Project template if you are creating a project in a folder with existing
files and want to set up the project manually. The Blank Project template creates a
project in your selected folder and leaves any other files untouched. You must manually set
up the project, for example by adding files to the project, configuring startup files,
configuring the project path, etc.
• Try the Simple Project template if you are creating a project in a new folder and want
a blank model. The Simple Project template creates a simple project containing a blank
model and some utilities. The model is a shortcut so you can open it from the toolstrip. The

16-20
Create a New Project from a Folder

project manages your path and the location of the temporary files (slprj folder) when you
open and close the project. You can modify any of these files, folders, and settings later.
• You can create your own templates. See “Using Templates to Create Standard Project
Settings” on page 16-36.
2 In the start page, select a template and click Create Project.
3 In the Create Project dialog box, specify your project folder and edit the project name, and
click Create Project. You can control the default folder for new projects using the project
preferences.

The Project displays the project files view for the specified project root. You need to add files
to the project. See “Add Files to the Project” on page 16-22.

For next steps using your new project, try dependency analysis to visualize the structure of your files.

See Also

Related Examples
• “Run a Dependency Analysis” on page 18-5
• “Create a Project from a Model” on page 16-12
• “Add Files to the Project” on page 16-22
• “Work with Project Files” on page 17-7
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Add a Project to Source Control” on page 19-5

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-21
16 Project Setup

Add Files to the Project


If you create a project from a folder, from a model, or with a Git or SVN template from the start page,
then the project setup helps you add initial files to the project. If you create a new blank project, then
the project files view is empty and you need to add files to the project.

To display all files in your project folder (or projectroot), in the Files view, click All. You might not
want to include all files in your project. For example, you might want to exclude some files under
projectroot from your project, such as SVN or CVS source control folders.

To add existing files to your project:

1 On the Project tab, click the down arrow to expand the Tools gallery. Under Project Files, click
Add Files.
2 Select from the list of unmanaged files in the project folder.

Use Add Files any time you want to check for new files not yet added to the project.

Alternatively, you can use these methods to add files:

• In the All files view, select files or folders, right-click, and select Add to Project or Add to
Project (including child files).
• To add files to your project, cut and paste or drag and drop files from a file browser or the Current
Folder browser onto the Project files view. If you drag a file from outside the project root, this
moves the file and adds it to your project. You can drag files within project root to move them.
• Add and remove project files at the command line using addFile.

To create new files or folders in the project, right-click a white space in the Files view and select
New Folder or New File. The new files are added to the project.

To learn how to set up your project with all required files, see “Run a Dependency Analysis” on page
18-5.

To add or remove project folders from the MATLAB search path, see “Specify Project Path” on page
16-28.

To configure your project to automatically run startup and shutdown tasks, see “Automate Startup
Tasks” on page 16-30.

You can access your recent projects direct from MATLAB. See “Open Recent Projects” on page 16-
26.

If you want to add source control, see “Add a Project to Source Control” on page 19-5.

See Also

Related Examples
• “Work with Project Files” on page 17-7
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Add a Project to Source Control” on page 19-5

16-22
Add Files to the Project

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-23
16 Project Setup

Create a New Project from an Archived Project


To create a new project from an archived project:

1 Locate and double-click the mlproj file in the Current Folder, Windows Explorer, or Apple
Finder.

If you do not have a product that the project requires, you see a warning with a link to the Add-
On Explorer to get missing products.
2 In the Extract Project to dialog box, specify the location of the new project and click Select
Folder.

The new project opens. The current working folder is the location of the new project, which is a
new subfolder of the extraction folder.

If you have a project archived in a zip file, double click or right click to extract the project. The
current working folder, for example, C:\myNewProject, contains the imported project folders. If the
zip project contains referenced projects, the project imports files into two subfolders, main and refs.
The current working folder, for example, C:\myNewProject\main contains the project folders and
C:\myNewProject\refs contains the referenced project folders. To open the project, navigate into
main to locate and double-click the prj file.

See Also

Related Examples
• “Archive Projects” on page 17-35

More About
• “Sharing Projects” on page 17-31

16-24
Create a New Project Using Templates

Create a New Project Using Templates

In a project, you can use templates to create and reuse a standard project structure.

1 To browse for templates, click Simulink on the MATLAB Home tab, or on the Project tab, click
New.
2 In the Simulink start page, click a template in the list to read the description. For example, click
Simple Project.
3 The start page shows all project templates (*.sltx) on the MATLAB path. If your templates do
not appear, locate them by clicking Open. In the Open dialog box, make *.sltx files visible by
changing the file type list Model Files to All MATLAB files, and browse to your template.
4 In the start page, select a template and click Create Project.

Templates created in R2017b or later warn you if required products are missing. Click the links
to open Add-On Explorer and install required products.
5 In the Create Project dialog box, specify your project folder and edit the project name, and click
Create Project.

Use Project Templates from R2014a or Before


To use project templates created in R2014a or earlier (.zip files), upgrade them to .sltx files using
Simulink.exportToTemplate.

After you upgrade the templates to .sltx and put them on the MATLAB path, you can use the
templates from the start page.

See Also

Related Examples
• “Create a New Project from a Folder” on page 16-18
• “Create Templates for Standard Project Settings” on page 16-36
• “Create a Template from a Project Under Version Control” on page 16-37
• “Edit a Template” on page 16-37
• “Create Template from Model” on page 4-2
• “Clone Git Repository” on page 19-33

More About
• “Using Templates to Create Standard Project Settings” on page 16-36

16-25
16 Project Setup

Open Recent Projects


You can use any of these methods to open recent projects:

• On the MATLAB Home tab, click Simulink, and select your project in the recent list.

If you select a recent model that is part of a project, you can choose to also open the project.
• On the MATLAB Home tab, click the Open arrow and select your project under the Recent
Projects list.
• From the Current Folder browser, double-click the .prj file.
• In the Simulink Editor, if an open model, library, or chart belongs to a project, you can, on the
Simulation tab, select Project > View Project.

If you already have an open project, to load another project, click on the Project tab and open a
recent project with these methods:

• Click the Open arrow and select your project under the Recent list.
• Select Open > Open. Browse and select your project .prj file.

Note You can have one project open at a time, to avoid conflicts. If you open another project, any
currently open project closes.

When you open a project, you are prompted if loaded files shadow your project model files. To avoid
working on the wrong files, close the shadowing files. See “Manage Shadowed and Dirty Models and
Other Project Files” on page 17-8.

See Also

Related Examples
• “Work with Project Files” on page 17-7

16-26
Specify Project Details, Startup Folder, and Derived Files Folders

Specify Project Details, Startup Folder, and Derived Files


Folders
On the Project tab, in the Environment section, click Details. Use the Project Details dialog box for
the following tasks:

• Edit the project name or add a description.


• View the Project root folder. 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. To change the current working folder to your project root, click Set as Current
Folder.
• View or edit the Start up folder. By default, this is set to the project root. When you open the
project, the current working folder changes to the project root folder. You can specify a different
startup folder or click Clear.

You can also configure startup scripts that set the current folder and perform other setup tasks. If
you configure startup files to set the current folder, your startup setting takes precedence over the
startup folder at the Project Details dialog box. To set up startup files, see “Automate Startup
Tasks” on page 16-30.
• View or edit the Dependency cache file. By default, the dependency cache file is stored in the
preferences folder. You can create and specify a different cache file, for example, [project
root]/dependencycache.graphml or click Clear.
• View or edit the Generated Files folders. You can set the Simulation cache folder and Code
generation folder. For details, see “Manage Build Process Folders” (Simulink Coder).
• If you edit any project details, then click OK to save your changes.

If you are looking for source control information for your project, see instead the details button for
your source control in the Source Control section of the Project tab, e.g., SVN Details. See “Add a
Project to Source Control” on page 19-5.

See Also

Related Examples
• “Automate Startup Tasks” on page 16-30
• “Add a Project to Source Control” on page 19-5

16-27
16 Project Setup

Specify Project Path

• When you open your project, it adds the project path to the MATLAB search path before applying
startup shortcuts.
• When you close your project, it removes the project path from the MATLAB search path after
applying shutdown shortcuts.

You can add or remove folders from the project path. Add project folders to ensure dependency
analysis detects project files. On the Project tab, in the Environment section, click Project Path:

• To add a folder (without subfolders) to the project path, click Add Folder. If you want to add a
folder and its subfolders, click Add with Subfolders instead. Then use the Open dialog box to
add the new folder.
• To remove a folder from the project path, from the display list, select the folder. Then click
Remove.

In the Project > Files view, you can use the context menu to add or remove folders from the project
path. Right-click a folder and select Project Path > Add to Project Path, or Add to the Project
Path (Including Subfolders), or one of the options to remove the folder from the path.

Folders on the project path display the project path icon in the Status column.

See Also

Related Examples
• “Specify Project Details, Startup Folder, and Derived Files Folders” on page 16-27

More About
• “What Is the MATLAB Search Path?”
• “What Can You Do with Project Shortcuts?” on page 16-29

16-28
What Can You Do with Project Shortcuts?

What Can You Do with Project Shortcuts?


In a project, use shortcuts to make it easy for any project user to find and access important files and
operations. You can use shortcuts to make top models or scripts easier to find in a large project. You
can group shortcuts to organize them by type and annotate them to use meaningful names instead of
cryptic file names.

Using the Project Shortcuts tab in the toolstrip, you can execute, group, or annotate shortcuts. Run
shortcuts by clicking them in the Project Shortcuts tab or execute them manually from the context
menu.

To automate tasks, use startup and shutdown files instead. You can use startup files to help you set up
the environment for your project, and shutdown shortcuts to help you clean up the environment for
the current project when you close it.

See Also

Related Examples
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Use Shortcuts to Find and Run Frequent Tasks” on page 16-35
• “Automate Startup Tasks” on page 16-30
• “Automate Shutdown Tasks” on page 16-32
• “Specify Project Path” on page 16-28

16-29
16 Project Setup

Automate Startup Tasks


In a project, startup files help you set up the environment for your project.

Startup files are automatically run (.m and .p files), loaded (.mat files), and opened (Simulink
models) when you open the project.

Note Startup scripts can have any name. You do not need to use startup.m.

You can use a file named startup.m on the MATLAB path which runs when you start MATLAB. If
your startup.m file calls the project with currentProject, an error appears because no project is
loaded yet. To avoid the error, rename startup.m and use it as a project startup file instead.

Configure an existing file to run when you open your project.

• Right-click the file and select Run at Startup.


• Alternatively, on the Project tab, click Startup Shutdown. In the Manage Project Startup and
Shutdown dialog box, you can add and remove startup and shutdown files. If execution order is
important, change the order using the arrow buttons.

In the files view, the Status column displays an icon and tooltip indicating the file will run at startup.

Note Startup file settings are included when you commit modified files to source control. Any startup
tasks you create run for all other project users.

To stop a file running at startup, change back by right-clicking it and selecting Remove from
Startup.

On the Manage Project Startup and Shutdown dialog box, use the check boxes to specify environment
options:

• Start Simulink before this project starts–This option starts Simulink when you open the
project.
• Refresh Simulink customizations– This option runs sl_customization files on project
startup and shutdown.

When you open the project, the startup files run. Also, the current working folder changes to the
project startup folder. If you want to set the startup folder, on the Project tab, click Details and edit
the Start Up folder. See “Specify Project Details, Startup Folder, and Derived Files Folders” on page
16-27.

You can create new startup and shutdown files interactively in the project or at the command line. For
details, see addStartupFile.

See Also

Related Examples
• “Specify Project Path” on page 16-28

16-30
Automate Startup Tasks

• “Automate Shutdown Tasks” on page 16-32


• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Use Shortcuts to Find and Run Frequent Tasks” on page 16-35

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-31
16 Project Setup

Automate Shutdown Tasks


In a project, shutdown files help you clean up the environment for the current project when you close
it. Shutdown files should undo the settings applied in startup files.

Configure an existing file to run when you close your project.

1 Right-click the file and select Run at Shutdown.

The Status column displays an icon and tooltip indicating the file will run at shutdown.

Note Shutdown files are included when you commit modified files to source control. Any shutdown
files you set run for all other project users.

To stop a file running at shutdown, change it back by right-clicking it and selecting Remove from
Shutdown.

See Also

Related Examples
• “Automate Startup Tasks” on page 16-30
• “Specify Project Path” on page 16-28
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Use Shortcuts to Find and Run Frequent Tasks” on page 16-35

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-32
Create Shortcuts to Frequent Tasks

Create Shortcuts to Frequent Tasks


In this section...
“Create Shortcuts” on page 16-33
“Group Shortcuts” on page 16-33
“Annotate Shortcuts to Use Meaningful Names” on page 16-34
“Customize Shortcut Icons” on page 16-34

Create Shortcuts
In a project, create shortcuts for common project tasks and to make it easy to find and access
important files and operations. For example, find and open top models, run code (for example, to load
data), and simulate models. To run startup or shutdown code, see instead “Automate Startup Tasks”
on page 16-30.

To configure an existing project file as a shortcut, use any of the following methods:

• In the Files view, right-click the project file and select Create Shortcut. In the Create New
Shortcut dialog box, you can edit the shortcut name, choose an icon, and select a group if you
have created a shortcut group you want to use. You can change shortcut group later. Click OK.
• Click New Shortcut on the Project Shortcuts tab on the toolstrip and browse to select a file.

The shortcut appears on the Project Shortcuts tab on the toolstrip.

In the files view, the Status column displays an icon and tooltip indicating the file is a shortcut.

Note Shortcuts are included when you commit your modified files to source control, so you can share
shortcuts with other project users.

Group Shortcuts
You can group shortcuts to organize them by type. For example, you can group shortcuts for loading
data, opening models, generating code, and running tests.

You can select a shortcut group when creating shortcuts, or manage groups later on the Project
Shortcuts toolstrip tab.

Create new shortcut groups to organize your shortcuts:

• On the Project Shortcuts tab, click Organize Groups.


• Click Create, enter a name for the group and click OK.

The new shortcut group appears on the Project Shortcuts tab.

To organize your shortcuts by group, either:

• Select a group when creating a shortcut.


• In the Project files view, right-click a file and select Edit Shortcut.

16-33
16 Project Setup

• On the Project Shortcuts tab, right-click a file and select Edit Shortcut.

The shortcuts are organized by group in the Project Shortcuts toolstrip tab.

Annotate Shortcuts to Use Meaningful Names


Annotating shortcuts makes their purpose visible, without changing the file name or location of the
script or model the shortcut points to. For example, you can change a cryptic file name to a
descriptive name for the shortcut. To put shortcuts in a workflow order on the toolstrip, prefix the
shortcut names with numbers.

When creating a shortcut, edit the Name. The shortcut name does not affect the file name or
location.

Your specified shortcut name appears on the Project Shortcuts tab, to make it easier to find your
shortcuts.

Customize Shortcut Icons


You can specify an icon to use for your shortcut buttons on the Project Shortcuts tab. Icons such as
"build" can aid other project users to recognize frequent tasks.

1 When creating a shortcut, choose an icon.


2 Select an image file. Images must be exactly 16 pixels square, and a png or a gif file.

See Also

Related Examples
• “Use Shortcuts to Find and Run Frequent Tasks” on page 16-35
• “Automate Startup Tasks” on page 16-30

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-34
Use Shortcuts to Find and Run Frequent Tasks

Use Shortcuts to Find and Run Frequent Tasks


In a project, use shortcuts to make it easy for any project user to find and access important files and
operations. You can use shortcuts to make top models or scripts easier to find in a large project.
Shortcuts are available from any file view via the toolstrip.

If your project does not yet contain any shortcuts, see “Create Shortcuts to Frequent Tasks” on page
16-33.

To use shortcuts:

• In the Project Shortcuts toolstrip tab, click the shortcut. Clicking a shortcut in the toolstrip
performs the default action for the file type, for example, run .m files, load .mat files, and open
models. Hover over a shortcut to view the full path.

Choose which behavior you want when running shortcuts:

• If the script is not on the path, and you want to switch to the parent folder and run the script
without being prompted, then click the shortcut in the Project Shortcuts toolstrip tab. If you use
this option, the result of pwd in the script is the parent folder of the script.
• If you select Run in the Files view context menu, and the script is not on the path, then MATLAB
asks if you want to change folder or add the folder to the path. This is the same behavior as
running from the Current Folder browser. If you use this option, the result of pwd in the script is
the current folder when you run the script.

See Also

Related Examples
• “Create Shortcuts” on page 16-33
• “Group Shortcuts” on page 16-33
• “Annotate Shortcuts to Use Meaningful Names” on page 16-34
• “Automate Startup Tasks” on page 16-30

More About
• “What Can You Do with Project Shortcuts?” on page 16-29

16-35
16 Project Setup

Create Templates for Standard Project Settings

In this section...
“Using Templates to Create Standard Project Settings” on page 16-36
“Create a Template from the Current Project” on page 16-36
“Create a Template from a Project Under Version Control” on page 16-37
“Edit a Template” on page 16-37
“Remove a Template” on page 16-37
“Explore the Example Templates” on page 16-37

Using Templates to Create Standard Project Settings


In a project, use templates to create and reuse a standard project structure. Templates help you make
consistent projects across teams. You can 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.

You can use templates to share information and best practices. You or your colleagues can create
templates.

Create a template from a project when it is useful to reuse or share with others. You can use the
template when creating new projects.

Create a Template from the Current Project


In a project, when you create a template, it contains the structure and all the contents of the current
project, enabling you to reuse scripts and other files for your standard project setup. You can choose
whether to include the contents of referenced projects in the template.

1 Before creating the template, create a copy of the project, and edit the copy to contain only the
files you want to reuse. Use the copy as the basis for the template.

Note If the project is under version control, see instead “Create a Template from a Project
Under Version Control” on page 16-37.
2 On the Project tab, in the File section, select Share > Simulink Template.
3 On the Create Project Template dialog box, edit the name and author, select or create a group,
and add a description to help template users.
4 If you have referenced projects and want to export the referenced project files, then select the
Include referenced projects check box.
5 Click Save As. Choose a file location and click Save.

16-36
Create Templates for Standard Project Settings

Create a Template from a Project Under Version Control


1 Get a new working copy of the project. See “Clone Git Repository” on page 19-33 or “Check Out
SVN Repository” on page 19-35.
2 To avoid accidentally committing changes to your project meant only for the template, stop using
source control with this sandbox as you work on the template. In the Source Control view, under
Available Source Control Integrations, select No Source Control Integration and click
Reload.
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 Files view, right-click
unwanted files and select Remove from Project.
4 On the Project tab, in the File section, select Share > Simulink Template and use the dialog
box to name and save the file.

To verify that your template behaves as you expect, create a new project that uses your new template.
See “Create a New Project Using Templates” on page 16-25.

Edit a Template
1 Create a new project that uses the template you want to modify. See “Create a New Project Using
Templates” on page 16-25.
2 Make the changes.
3 On the Project tab, in the File section, select Share > Simulink Template.

Use the dialog box to create a new template or overwrite the existing one.

Remove a Template
To remove a template from the Simulink start page:

1 Browse to the template location specified in the template details.


2 Delete the template or move it to another location.

Explore the Example Templates


You can use the example templates as example structures for a new project.

You can explore the templates using the Simulink start page. To search for templates, use the start
page search box. See “Create a New Project Using Templates” on page 16-25 and “Create a New
Project from a Folder” on page 16-18.

See Also

Related Examples
• “Create a New Project Using Templates” on page 16-25
• “Compare Model or Project Templates” on page 21-35
• “Clone Git Repository” on page 19-33

16-37
17

Project File Management

• “Group and Sort File Views” on page 17-2


• “Search Inside Project Files and Filter File Views” on page 17-3
• “Work with Project Files” on page 17-7
• “Manage Shadowed and Dirty Models and Other Project Files” on page 17-8
• “Move, Rename, Copy, or Delete Project Files” on page 17-10
• “Back Out Changes” on page 17-15
• “Create Labels” on page 17-16
• “Add Labels to Files” on page 17-17
• “View and Edit Label Data” on page 17-18
• “Automate Project Tasks Using Scripts” on page 17-19
• “Create a Custom Task Function” on page 17-28
• “Run a Project Custom Task and Publish Report” on page 17-29
• “Sharing Projects” on page 17-31
• “Share Project by Email” on page 17-32
• “Share Project as a MATLAB Toolbox” on page 17-33
• “Share Project on GitHub” on page 17-34
• “Archive Projects” on page 17-35
• “Analyze Model Dependencies” on page 17-37
• “View Requirements Toolbox Links Associated with Model Elements” on page 17-43
• “Identify and Run Tests in MATLAB Projects” on page 17-49
17 Project File Management

Group and Sort File Views


In a project, to group and sort the views in the Files view:

• Use the List or Tree options under Layout to switch between a flat list of files and a hierarchical
tree of files.

Click the Actions button to specify display columns and sort order. For example, you can
display columns for label categories that you created and sort files by label category.

See Also

Related Examples
• “Search Inside Project Files and Filter File Views” on page 17-3

17-2
Search Inside Project Files and Filter File Views

Search Inside Project Files and Filter File Views


In this section...
“Project-Wide Search” on page 17-3
“Filter Project File Views” on page 17-5
“More Ways to Search” on page 17-6

Project-Wide Search
In a project, you can search inside all your models and supporting files. You can find matches inside
model files, MATLAB files, data dictionaries, and other project files. You search only the current
project. If you want to search referenced project files, open the referenced project.

1 On the Project tab, click the down arrow to expand the Tools gallery. Under Project Files, click
Search. Alternatively, type in the file filter box, and the project provides a link to try searching
inside files instead.

2 In the Search Inside Project Files dialog box, enter some characters to search for. Do not use
quotes around phrases, or hyphens.
3 Expand files in the list to see results inside the file. Double-click results to locate specific items,
e.g., highlight blocks in Simulink models, or highlight specific lines in MATLAB files.

17-3
17 Project File Management

4 Click Filters to refine results by file type, status, or label.

17-4
Search Inside Project Files and Filter File Views

Filter Project File Views


In a project, in the Files view and in the Custom Task dialog box, you can use the search box and
filtering tools to specify file display.

• To view files, select the Files node. When the Project (number of files) view is selected, only the
files in your project are shown. To see all the files in your sandbox, click All. This view shows all
the files that are under the project root, not just the files that are in the project.
• To search, type a search term in the search box, for example, part of a file name or a file
extension. You can use wildcards, for example, *.m, or *.m*.

Click X to clear the search.



To build a filter for the current view, click the filter button .

In the Filter Builder dialog box you can select multiple filter criteria to apply using names, file
types, project status, and labels.

The dialog box reports the resulting filter at the bottom, for example:

Filter = file type is 'Model files (*.slx, *.mdl)' AND project status
is 'In project' AND has label 'Engine Type:Diesel'

When you click Apply, the search box shows the filter that you are applying.

17-5
17 Project File Management

More Ways to Search


You can also search:

• Model contents without loading the models into memory. On the MATLAB Home tab, in the File
section, click Find Files. You can search a folder or the entire path. However, you cannot
highlight results in models from the results in the Find Files dialog box the same way you do with
project search. See “Advanced Search for Files”.
• A model hierarchy. In the Simulink Editor, on the Modeling tab, click Find. Select options to look
inside masks, links, and references. This search loads the models into memory. See Model
Explorer
• For variables, block parameter values, or search a model hierarchy and contents using more
options, using the Model Explorer. This search loads the models into memory. Use the Model
Explorer to search for variables in workspaces and data dictionaries, and variable usage in a
model. See “Edit and Manage Workspace Variables by Using Model Explorer” on page 73-129

See Also
Model Explorer

Related Examples
• “Group and Sort File Views” on page 17-2
• “Edit and Manage Workspace Variables by Using Model Explorer” on page 73-129

17-6
Work with Project Files

Work with Project Files


In a project, in the Files view, use the context 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 files.
• Add and remove files from the project.
• Add, change, and remove labels. See “Add Labels to Files” on page 17-17.
• Create entry point shortcuts (for example, code to run at startup or shutdown, open models,
simulate, or generate code). See “Create Shortcuts to Frequent Tasks” on page 16-33.
• If a source control interface is enabled, you can also:

• Refresh source control status.


• Update from source control.
• Check for modifications.
• Revert.
• Compare against revision (select a version to compare).

See “About Source Control with Projects” on page 19-2.

In the Files view, if you select, for example a model file, the bottom right-hand pane displays file
information, a model preview, and file labels.

See Also

Related Examples
• “Open Recent Projects” on page 16-26
• “Add Files to the Project” on page 16-22
• “Move, Rename, Copy, or Delete Project Files” on page 17-10
• “Back Out Changes” on page 17-15
• “Group and Sort File Views” on page 17-2
• “Search Inside Project Files and Filter File Views” on page 17-3
• “Create a Custom Task Function” on page 17-28

More About
• “What Can You Do with Project Shortcuts?” on page 16-29
• “About Source Control with Projects” on page 19-2

17-7
17 Project File Management

Manage Shadowed and Dirty Models and Other Project Files


In this section...
“Identify Shadowed Project Files When Opening a Project” on page 17-8
“Find Models and Other Project Files With Unsaved Changes” on page 17-8
“Manage Open Models and Data Dictionaries When Closing a Project” on page 17-9

Identify Shadowed Project Files When Opening a Project


If there are two model files with the same name on the MATLAB path, then the one higher on the
path is loaded, and the one lower on the path is shadowed. This shadowing applies to all models and
libraries (SLX and MDL files).

A loaded model always takes precedence over unloaded ones, regardless of its position on the
MATLAB path. Loaded models can interfere when you try to use other files of the same name,
especially when models are loaded but not visible. Simulink warns when you try to load a shadowed
model, because the other model is already loaded and can cause conflicts. The project checks for
shadowed files when you open a project.

1 When you open a project, it warns you if any models of the same names as your project models
are already loaded. This check enables you to find and avoid shadowed files before opening any
project models.

The Configuring Project Environment dialog box reports the Identify shadowed project files
check fails. Click Details.
2 In the dialog box, use the context menu to open or close individual files, or click Close All to
close all potentially shadowing files. To avoid working on the wrong files, close the loaded
models. The dialog box closes and you return to the Configuring Project Environment dialog box.
3 Inspect the other project loading tasks, then click Continue to view the project.

Tip To help avoid problems with shadowed files, turn on the Simulink preference Do not load
models that are shadowed on the MATLAB path. See “Do not load models that are shadowed on
the MATLAB path”.

When you open a project with many referenced projects, identifying shadowed files can be time-
consuming. You can turn off this check using the MATLAB project preference Detect project files
shadowed by open models.

To learn more about shadowed files, see “Shadowed Files” on page 15-3.

Find Models and Other Project Files With Unsaved Changes


You can check your project for models, data dictionaries and MATLAB files with unsaved changes. On
the Project tab, click on the down arrow to expand the Tools gallery. Under Project Checks, click
Show Unsaved Changes.

In the Unsaved Changes dialog box, you can see all dirty project models, data dictionaries, and
MATLAB files. Project only detects unsaved changes edited in the MATLAB and Simulink editors.

17-8
Manage Shadowed and Dirty Models and Other Project Files

Manually examine changes edited in other tools. If you have referenced projects, files are grouped by
project. You can save or discard all detected changes.

Manage Open Models and Data Dictionaries When Closing a Project


When you close a project, it closes any project models or data dictionaries, unless they are dirty.

When you close a project, if there are model files or data dictionaries with unsaved changes, a
message prompts you to save or discard changes. You can see all dirty files, grouped by project if you
have referenced projects. To avoid losing work, you can save or discard changes by file, by project, or
globally.

Control this behavior using the project shutdown preferences.

See Also

Related Examples
• “Do not load models that are shadowed on the MATLAB path”
• “Shadowed Files” on page 15-3

17-9
17 Project File Management

Move, Rename, Copy, or Delete Project Files


In this section...
“Move or Add Files” on page 17-10
“Automatic Updates When Renaming, Deleting, or Removing Files” on page 17-10

Move or Add Files


To move or add project files, you can drag them to the project, or use clipboard operations.

• To add files to your project, you can paste files or drag them from your operating system file
browser or the MATLAB Current Folder browser onto the Project files view in the project. When
you drag a file to the Project files view, you add the file to the project. For projects under source
control, you also add the file to source control.
• To move files within your project, cut and paste or drag files in the project.

See also “Add Files to the Project” on page 16-22.

Automatic Updates When Renaming, Deleting, or Removing Files


When you rename, delete, or remove files or folders in a project, the project checks for impact in
other project files. You can find and fix impacts such as changed library links, model references, and
model callbacks. You can avoid refactoring pain tracking down other affected files. Automatic
renaming helps to prevent errors that result from changing names or paths manually and overlooking
or mistyping one or more instances of the name.

For example:

• When renaming a library, the project offers to automatically update all library links to the
renamed library.
• When renaming a class, the project offers to automatically update all classes that inherit from it. If
you rename a .m or .mlx file, the project offers to automatically update files and callbacks that
call it. The project does not automatically update .mlx files. You need to update them manually.
• When deleting files or removing them from the project, the project prompts you if other files refer
to them. You must decide how to fix the affected files manually.
• When renaming a C file, the project prompts you to update the S-function that uses it.
• When renaming buses or bus elements using the Simulink Type Editor, the project prompts you to
update all usages in the project.

You can disable the project prompt and analysis when renaming buses or bus elements while
keeping automatic updates enabled for other files. On the MATLAB Home tab, in the
Environment section, click Preferences. Select MATLAB > Project and clear Detect project-
wide references when renaming Simulink buses and bus elements.

You can disable the automatic updates when renaming, deleting, or removing files in a project. On the
MATLAB Home tab, in the Environment section, click Preferences. Select MATLAB > Project and
clear Detect project-wide references when renaming, removing, and deleting files.

To use automatic updates:

17-10
Move, Rename, Copy, or Delete Project Files

1 Rename a model, library, or MATLAB file in a project.

The project runs a dependency analysis to look for impacts in other files.
2 In the Rename dialog box, you can examine impacted files, choose to rename and update, just
rename, or cancel renaming the file.
3 If you choose automatic updates, you can examine the results in updated files.

Automatic Renaming Using the Power Window Project

1 Open the power window example project.

openExample('simulink_automotive/PowerWindowControlProjectExample')

The project opens the top model, some scopes, and an animation window.
2 In the project, expand the model folder, and rename the slexPowerWindowControl.slx model
to slexPowerWindowControlSystem.slx.

The project runs a dependency analysis to look for impacts in other files, and then the Rename
dialog box reports impacted files.

3 In the Rename dialog box, click Show impacted files. Expand the last impacted file to view the
dependency, which is a model reference.

17-11
17 Project File Management

4 To view the dependency highlighted in the model, double-click the last Model Reference line in
the Rename dialog box. Observe the model name on the highlighted control block,
slexPowerWindowControl.

17-12
Move, Rename, Copy, or Delete Project Files

5 In the Rename dialog box, click Rename and Update.

The project updates the impact files to use the new model name in model references. When the
project can automatically rename items, it reports success with a check mark. With some
impacts, you must decide how to fix the affected files manually.

17-13
17 Project File Management

6 Examine the results by double-clicking items in the Rename dialog box. Double-click the last
Model Reference line. Check if the model name on the highlighted control block is updated to
slexPowerWindowControlSystem.

See Also

Related Examples
• “Work with Project Files” on page 17-7

17-14
Back Out Changes

Back Out Changes


Similar to many applications, the project enables you to Undo and Redo, to back out recent changes.

It is not possible to undo actions that trigger autorenaming.

If you are using source control, you can revert to particular versions of files or projects. See “Revert
Changes” on page 19-52.

See Also

Related Examples
• “Revert Changes” on page 19-52

17-15
17 Project File Management

Create Labels
In a project, use labels to organize files and communicate information to project users. You can create
these types of label categories:

• Single-valued — You can attach only one label from the category to a file.
• Multi-valued — You can attach multiple labels from the category to a file.

The Labels tree has built-in labels in the single-valued Classification category:

• You cannot rename or delete Artifact, Convenience, Derived, Design, None, Test, and Other.
• You cannot annotate built-in labels.

To create a label category:

1 In a project, right-click the Labels pane. Then select Create New Category.
2 In the Create Category dialog box, enter a name for the new category.
3 If you require a single-valued label category, select the Single Valued check box. The default is
multi-valued.
4 If you want to specify a data type for the label other than String, from the Type list, select
Double, Integer, Logical, or None.
5 Click Create.

To create a label in a category:

1 In the Labels pane, right-click the label category and select Create New Label.
2 In the Create Label dialog box, enter a name for the new label and click OK.

To rename or delete a category or label, right-click it and select Rename or Remove.

To create new labels at the command line, see “Automate Project Tasks Using Scripts” on page 17-
19.

See Also

Related Examples
• “Add Labels to Files” on page 17-17
• “View and Edit Label Data” on page 17-18

17-16
Add Labels to Files

Add Labels to Files


In a project, use labels to organize files and communicate information to project users.

To add a label to a file, use one of these methods:

• Drag the label from the Labels pane onto the file.
• In the Files view, select the file. Then, drag the label from the Labels pane into the label editor.

To add a label to multiple files, in the Files view or Dependency Analyzer graph, select the files that
require the label. Then right-click and select Add Label. Use the dialog box to specify the label.

To add labels programmatically, for example, in custom task functions, see “Automate Project Tasks
Using Scripts” on page 17-19.

Note After you add a label to a file, the label persists across file revisions.

After you add labels, you can organize files by label in the Files view and dependency graph. See
“Group and Sort File Views” on page 17-2 and “Perform an Impact Analysis” on page 18-15.

If the project is under SVN source control, adding tags to all your project files enables you to mark
versions. See “Tag and Retrieve Versions of Project Files” on page 19-37.

See Also

Related Examples
• “Create Labels” on page 17-16
• “View and Edit Label Data” on page 17-18

17-17
17 Project File Management

View and Edit Label Data


When you select a file in the project Files view, the file labels appear in the label editor view.

To change a label that belongs to a single-valued category, select the new value from the label list.

You can annotate labels from categories that you create. In the label, insert or modify text. Then, click
Apply.

See Also

Related Examples
• “Create Labels” on page 17-16
• “Add Labels to Files” on page 17-17

17-18
Automate Project Tasks Using Scripts

Automate Project Tasks Using Scripts

This example shows how to use the project API to automate project tasks manipulating files, including
working with modified files, dependencies, shortcuts, and labels.

Open Project

Open the Airframe example project.

openExample("simulink/AirframeProjectExample")

Building with 'Microsoft Visual C++ 2022 (C)'.


MEX completed successfully.

Get Project at the Command Line

Use currentProject to get a project object to manipulate the project at the command line.

proj = currentProject

proj =

Project with properties:

Name: "Airframe Example"


Description: "This is an example project...."
RootFolder: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\Airfr
TopLevel: 1
ReadOnly: 0
DefinitionFilesType: FixedPathMultiFile
SourceControlIntegration: "Git"
RepositoryLocation: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\repos
SourceControlMessages: ["Branch status: Normal" ... ] (1x3 string)
Files: [1x30 matlab.project.ProjectFile]
Shortcuts: [1x3 matlab.project.Shortcut]
Categories: [1x1 matlab.project.Category]
Dependencies: [1x1 digraph]
StartupFiles: [1x0 string]
ShutdownFiles: [1x0 string]
ProjectPath: [1x7 matlab.project.PathFolder]
ProjectReferences: [1x0 matlab.project.ProjectReference]
SimulinkCacheFolder: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\Airfr
SimulinkCodeGenFolder: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\Airfr
ProjectStartupFolder: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\Airfr
DependencyCacheFile: ""

Find Project Commands

Find out what you can do with your project.

methods(proj)

Methods for class matlab.project.Project:

17-19
17 Project File Management

addFile listModifiedFiles
addFolderIncludingChildFiles listRequiredFiles
addPath refreshSourceControl
addReference reload
addShortcut removeCategory
addShutdownFile removeFile
addStartupFile removePath
close removeReference
createCategory removeShortcut
export removeShutdownFile
findCategory removeStartupFile
findFiles runChecks
isLoaded updateDependencies
listAllProjectReferences
listImpactedFiles

Call "methods('handle')" for methods of matlab.project.Project inherited from handle.

Examine Project Files

After you get a project object, you can examine project properties such as files.
files = proj.Files

files =

1x30 ProjectFile array with properties:

Path
Revision
SourceControlStatus
Labels

Use indexing to access files in this list. The following command gets file number 10. Each file has
properties describing its path and attached labels.
proj.Files(10)

ans =

ProjectFile with properties:

Path: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframePr
Revision: "7512378c3b82a519f72204089b0ce552cfc90e1a"
SourceControlStatus: NotUnderSourceControl
Labels: [1x0 matlab.project.Label]

Examine the labels of the 10th file.


proj.Files(10).Labels

ans =

17-20
Automate Project Tasks Using Scripts

1x0 Label array with properties:

File
DataType
Data
Name
CategoryName

Get a particular file by name.

myfile = findFile(proj, 'models/AnalogControl.slx')

myfile =

ProjectFile with properties:

Path: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframePr
Revision: "7512378c3b82a519f72204089b0ce552cfc90e1a"
SourceControlStatus: Unmodified
Labels: [1x1 matlab.project.Label]

Find out what you can do with the file.

methods(myfile)

Methods for class matlab.project.ProjectFile:

addLabel findLabel removeLabel

Call "methods('handle')" for methods of matlab.project.ProjectFile inherited from handle.

Get Modified Files

Modify a project model file by adding an arbitrary block.

load_system('AnalogControl')
add_block('built-in/SubSystem', 'AnalogControl/test')
save_system('AnalogControl')

Get all the modified files in the project. Observe two modified files. Compare with the Modified Files
view in Project, where you can see a modified model file, and the corresponding project definition file.

modifiedfiles = listModifiedFiles(proj)

modifiedfiles =

1x2 ProjectFile array with properties:

Path
Revision
SourceControlStatus
Labels

17-21
17 Project File Management

Get the second modified file. Observe the file SourceControlStatus property is Modified. Similarly,
listModifiedFiles returns any files that are added, conflicted, deleted, etc., that show up in the
Modified Files view in Project.
modifiedfiles(2)

ans =

ProjectFile with properties:

Path: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframePr
Revision: ""
SourceControlStatus: Added

Refresh source control status before querying individual files. You do not need to do before using
listModifiedFiles .
refreshSourceControl(proj)

Get all the project files with a particular source control status. For example, get the files that are
Unmodified .
proj.Files(ismember([proj.Files.SourceControlStatus], matlab.sourcecontrol.Status.Unmodified))

ans =

1x21 ProjectFile array with properties:

Path
Revision
SourceControlStatus
Labels

Get File Dependencies

Update the file dependencies. The project runs a dependency analysis to update the known
dependencies between project files.
updateDependencies(proj)

Get the list of dependencies in the Airframe project. The Dependencies property contains the graph of
dependencies between project files, stored as a MATLAB digraph object.
g = proj.Dependencies

g =

digraph with properties:

Edges: [21x1 table]


Nodes: [21x1 table]

Get the files required by a model.

17-22
Automate Project Tasks Using Scripts

requiredFiles = bfsearch(g, which('AnalogControl'))

requiredFiles =

3x1 cell array

{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram

Get the top-level files of all types in the graph.

g.Nodes.Name(indegree(g)==0);

Get the top-level files that have dependencies.

g.Nodes.Name(indegree(g)==0 & outdegree(g)>0)

ans =

4x1 cell array

{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram

Find impacted (or "upstream") files by creating a transposed graph.

transposed = flipedge(g)
impacted = bfsearch(transposed, which('vertical_channel'))

transposed =

digraph with properties:

Edges: [21x1 table]


Nodes: [21x1 table]

impacted =

4x1 cell array

{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram

Find files impacted by a data dictionary.

impacted2 = bfsearch(transposed, which('buses.sldd'))

17-23
17 Project File Management

impacted2 =

11x1 cell array

{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram
{'C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfram

Get information on your files, such as the number of dependencies and orphans.
averageNumDependencies = mean(outdegree(g));
numberOfOrphans = sum(indegree(g)+outdegree(g)==0);

If you want to make changes to a model hierarchy, starting from the bottom up, find the topological
order.
ordered = g.Nodes.Name(flip(toposort(g)));

Query Shortcuts

Examine the project's Shortcuts property.


shortcuts = proj.Shortcuts

shortcuts =

1x3 Shortcut array with properties:

Name
Group
File

Examine a shortcut in the array.


shortcuts(3)

ans =

Shortcut with properties:

Name: "Rebuild Project's S-functions"


Group: "Utility"
File: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\a

Get the file path of a shortcut.

17-24
Automate Project Tasks Using Scripts

shortcuts(3).File

ans =

"C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airframe

Examine all the files in the shortcuts cell array.


{shortcuts.File}'

ans =

3x1 cell array

{["C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfra
{["C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfra
{["C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airfra

Label files

Create a new category of labels, of type char. In the Project, the new Engineers category appears in
the Labels pane.
createCategory(proj, 'Engineers', 'char')

ans =

Category with properties:

SingleValued: 0
DataType: "char"
Name: "Engineers"
LabelDefinitions: [1x0 matlab.project.LabelDefinition]

Find out what you can do with the new category.


category = findCategory(proj, 'Engineers');
methods(category)

Methods for class matlab.project.Category:

createLabel findLabel removeLabel

Call "methods('handle')" for methods of matlab.project.Category inherited from handle.

Define a new label in the new category.


createLabel(category, 'Bob');

Get a label definition.


ld = findLabel(category, 'Bob')

17-25
17 Project File Management

ld =

LabelDefinition with properties:

Name: "Bob"
CategoryName: "Engineers"

Attach a label to the retrieved file, myfile. If you select the file in Project, you can see this label in the
label editor pane.

addLabel(myfile, 'Engineers', 'Bob');

Get a particular label and attach data to it, for example, some text.

label = findLabel(myfile, 'Engineers', 'Bob');


label.Data = 'Please assess'

label =

Label with properties:

File: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectEx
DataType: "char"
Data: 'Please assess'
Name: "Bob"
CategoryName: "Engineers"

You can specify a variable for the label data, for example:

mydata = label.Data

mydata =

'Please assess'

Create a new label category with numeric data type.

createCategory(proj, 'Assessors', 'double');


category = findCategory(proj, 'Assessors');
createLabel(category, 'Sam');

Attach the new label to a specified file and assign data value 2 to the label.

myfile = proj.Files(14);
addLabel(myfile, 'Assessors', 'Sam', 2)

ans =

Label with properties:

File: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectEx
DataType: "double"

17-26
Automate Project Tasks Using Scripts

Data: 2
Name: "Sam"
CategoryName: "Assessors"

Close Project

Closing the project at the command line is the same as closing the project using the Project tool. For
example, the project runs shutdown scripts ad checks for unsaved models.

close(proj)

More Information

For more details on using the API, enter: doc currentProject.

To automate start and shutdown tasks, see “Automate Startup Tasks” on page 16-30.

See Also
currentProject | listModifiedFiles | refreshSourceControl | addLabel | createLabel

Related Examples
• “Perform an Impact Analysis” on page 18-15
• “Automate Startup Tasks” on page 16-30
• “View Modified Files” on page 19-44
• “Create Labels” on page 17-16
• “Add Labels to Files” on page 17-17
• “View and Edit Label Data” on page 17-18
• Automate Label Management in a Simulink Project

17-27
17 Project File Management

Create a Custom Task Function


In a project, you can create functions and run them on selected project files.

For example custom task functions, see “Run Custom Tasks with a Project”.

To create a custom task function:

1 On the Project tab, click the down arrow to expand the Tools gallery. Under Project Checks,
click Custom Tasks. In the Custom Task dialog box, click Manage.
2 In the Manage Custom Tasks dialog box, select Add > Add Using New Function or Add Using
Existing Function.

Either browse to an existing script, or name and save the new file on your MATLAB path. The file
is added to the project.
3 The MATLAB Editor opens the new file containing a simple example custom task function for you
to edit. Edit the function to perform the desired action on each file. The instructions guide you to
create a custom task with the correct function signature. Save the file.
4 To run your task, on the Project tab, click the down arrow to expand the Tools gallery. Under
Project Checks, click Custom Tasks. In the Custom Task dialog box, select project files to
include using the check boxes, select your custom task in the list, and click Run Task.
5 After your custom task function runs, view the results in the Custom Task Report.
6 To save the results in a file, click Publish Report.

See Also

Related Examples
• “Run a Project Custom Task and Publish Report” on page 17-29

17-28
Run a Project Custom Task and Publish Report

Run a Project Custom Task and Publish Report


1 On the Project tab, click the down arrow to expand the Tools gallery. Under Project Checks,
click Custom Tasks, and then select the check boxes of project files you want to include in the
custom task.

Tip If the function can identify the files to operate on, include all files. For example, the custom
task function saveModelFiles in the airframe project checks that the file is a Simulink model
and does nothing if it is not.

To select multiple files, Shift or Ctrl+click, and then right-click a file and select Include or
Exclude.
2 Specify the custom task function to run in the Custom task box. Enter the name, or click
Browse, or choose from a list of custom tasks.

If your project does not yet contain any custom task functions, see “Create a Custom Task
Function” on page 17-28.
3 Click Run Task.

The project displays the results.


4 To view details of results for the currently selected file, click a file and check the Results pane.

You can publish a report of your custom task results. For example, try this custom task:

1 Open an example project by entering openExample('simulink/


AirframeProjectExample').
2 On the Project tab, click the down arrow to expand the Tools gallery. Under Project Checks,
click Custom Tasks.
3 In the Custom Task dialog box, click the Custom task drop-down arrow to choose from a list of
tasks, and select Generate Bill of Materials Report.
4 Click Run Task. Results appear.

17-29
17 Project File Management

5 Click Publish Report.


6 In the file browser, specify a name and location for the report, and choose a file type from HTML
or Microsoft Word. If you have MATLAB Report Generator, you can also choose PDF.
7 View the results in the report.

The example custom task function Generate Bill of Materials Report creates a list of project
files, their source control status, revision numbers, and MD5 checksums. You can view the code
for this custom task in the file billOfMaterials.m.
8 To see the report file and add it to your project, switch to the All files view.

Tip To try example custom tasks in a project, see the example “Run Custom Tasks with a Project”.

See Also

Related Examples
• “Create a Custom Task Function” on page 17-28
• “Run Custom Tasks with a Project”
• “Perform Impact Analysis with a Project”

17-30
Sharing Projects

Sharing Projects
Projects help you collaborate. Use the Share menu to share your project in these ways:

• Archive your project in a single file.


• Share your project by email (Windows only).
• Create a template from your project.
• Package your project as a MATLAB toolbox.
• Make your project publicly available on GitHub.

You can also collaborate by using source control within projects.

See Also

Related Examples
• “Archive Projects” on page 17-35
• “Create Templates for Standard Project Settings” on page 16-36
• “Share Project by Email” on page 17-32
• “Share Project as a MATLAB Toolbox” on page 17-33
• “Share Project on GitHub” on page 17-34

More About
• “About Source Control with Projects” on page 19-2

17-31
17 Project File Management

Share Project by Email


To package and share project files on Windows, you can email your project as an archive file
attachment. For example, you can share the project with people who do not have access to the
connected source control tool.

1 With a project loaded, on the Project tab, select Share > Email.
2 (Optional) To export only the specified files, choose an Export profile. To exclude files with
particular labels, select Manage Export Profiles and create an export profile.
3 If you have referenced projects and want to export the referenced project files, then select the
Include referenced projects check box.
4 Click Attach to Email. The project opens a new email in your default email client with the
project attached as an archive .mlproj file.
5 Edit and send the email.

See Also

Related Examples
• “Create a New Project from an Archived Project” on page 16-24
• “Archive Projects” on page 17-35

More About
• “Sharing Projects” on page 17-31

17-32
Share Project as a MATLAB Toolbox

Share Project as a MATLAB Toolbox


To package and share project files, you can create a MATLAB toolbox from your project.

1 With a project loaded, on the Project tab, select Share > Toolbox.

The packager adds all project files to the toolbox and opens the Package a Toolbox dialog box.
2 The Toolbox Information fields are populated with the project name, author, and description.
Edit the information if needed.
3 If you want to include files not already included in the project files, edit the excluded files and
folders.
4 Click Package.

See Also

Related Examples
• “Create and Share Toolboxes”

More About
• “Sharing Projects” on page 17-31

17-33
17 Project File Management

Share Project on GitHub


To share your project, you can make your project publicly available on GitHub. You must first have a
GitHub account.

You can share any project. Sharing adds Git source control to the open project. If your project is
already under source control, sharing replaces the source control configuration with Git, and the
project’s remote repository is GitHub.

Note If you do not want to change your current source control in the open project, share a copy of
the project instead. To create a copy to share, see “Archive Projects” on page 17-35.

1 With a project loaded, on the Project tab, select Share > Change Share Options.
2 Add the GitHub option to your Share menu. In the Manage Sharing dialog box, select GitHub
and click Close.
3 Select Share > GitHub.
4 In the Create GitHub Repository dialog box, enter your GitHub user name and personal access
token, and edit the name for the new repository. Click Create.

A warning prompts you to confirm that you want to create a public repository and modify the
current project’s remote repository location. To continue, click Yes.
5 The Create GitHub Repository dialog box displays the URL address for your new repository. Click
the link to view the new repository on the GitHub website. The repository contains the initial
commit of your project files.
6 The source control in your current project now references the new repository on GitHub as the
remote repository. To use the project with the new repository, in the Create GitHub Repository
dialog box, click Reload Project.

In the project, you can find the URL address for your remote repository on the Project tab, under
Source Control, using the Git Details button.

If you have not already set up Git, you need some additional setup steps before you can merge
branches. You can use other Git functionality without any additional installation. See “Set Up Git
Source Control” on page 19-17.

See Also

Related Examples
• “Archive Projects” on page 17-35
• “Set Up Git Source Control” on page 19-17

More About
• “Sharing Projects” on page 17-31

17-34
Archive Projects

Archive Projects
To package and share project files, you can export all project files to an archive file. For example, you
can share an archived project with people who do not have access to the connected source control
tool.

1 With a project loaded, on the Project tab, select Share > Archive.
2 (Optional) To export only the specified files, choose an Export profile.
3 If you have referenced projects and want to export the referenced project files, then select the
Include referenced projects check box.
4 Click Save As.
5 Use the file browser to specify a file path in the File name field. By default, the file
myProjectName.mlproj is created in the current working folder. You can choose the file type
project archive (.mlproj) or zip file.

If you want to share a subset of your project files, create an export profile. An export profile allows
you to exclude or only include files with particular labels. For more information about creating labels
and adding them to project files, see “Create Labels” on page 17-16.

1 Specify an export profile. On the Project tab, select Share > Manage Export Profiles.

a Click + and specify a name for the export profile.


b In the Files pane, choose if you want to exclude or include files based on their labels from
the final project archive.

If the files you need to share are only a small subset of a large project, choose the include
option.
c In the Files pane, click + and select the labels for the files you want to exclude or include,
and then click OK.
d You can also exclude user-defined labels from the exported project. In the Labels pane, click
+ and select the custom labels you do not want to export, and then click OK.
e Click Apply and close the Manage Export Profiles dialog box.

17-35
17 Project File Management

2 When you share the project to an archive, in the Export profile list, select the name of your
export profile to export only the specified files.

Note Export profiles do not apply changes to referenced projects. When you share your project,
MATLAB exports the entire referenced projects.

Before sharing projects with other users, it can be useful to examine the required add-ons for your
project. See “Find Required Products and Add-Ons” on page 18-17.

See Also

Related Examples
• “Create a New Project from an Archived Project” on page 16-24
• “Share Subset of Project Files Using Labels”
• “Share Project by Email” on page 17-32

More About
• “Sharing Projects” on page 17-31

17-36
Analyze Model Dependencies

Analyze Model Dependencies


In this section...
“Open and Explore Dependency Graph” on page 17-37
“Model Dependency Views” on page 17-38
“Find Required Products” on page 17-40
“Export Dependency Analysis Results” on page 17-40
“Create Project from the Dependency Graph” on page 17-41

Examine models, subsystems, and libraries referenced directly or indirectly by the model using the
Dependency Analyzer. Use the dependency graph to identify all required files and products. To
package, share, or put your design under source control, create a project from your model. For more
details, see “Create Project from the Dependency Graph” on page 17-41.

Open and Explore Dependency Graph

1. Open the ModelReferenceHierarchy project and the sldemo_mdlref_depgraph model.

2. To open the model dependency graph, on the Modeling tab, click the down arrow to expand the
Design section. Under Dependencies, click Dependency Analyzer.

The Dependency Analyzer opens the dependency graph using the Model Hierarchy view by default.
To switch to the model instances view, in the Views section, click Model Instances. For more details,
see “Model Dependency Views” on page 17-38.

After you run the first dependency analysis, subsequent analyses incrementally update the results.
The Dependency Analyzer determines which files changed since the last analysis and updates the
dependency data for those files. To perform a complete analysis, in the Dependency Analyzer, select
Analyze > Reanalyze All.

To analyze the dependencies inside add-ons, select Analyze > Add-Ons. For more details about
available options, see “Analysis Scope” on page 18-2.

3. To view the dependencies laid out horizontally, in the Layout section, click Horizontal.

4. In the dependency graph, double-click a box to open the corresponding model in the Simulink®
Editor.

5. To see more information about how two files are related, select their dependency arrow. In the
Properties pane, in the Details section, you can see the full paths of the files you are examining, the
dependency type, and where the dependency is introduced.

17-37
17 Project File Management

6. To open the file and highlight where the dependency is introduced, in the Details section, click the
link under Impacted.

For example, to open the sldemo_mdlref_depgraph model and highlight where the dependency to
sldemo_mdlref_house is introduced, select the dependency arrow between
sldemo_mdlref_depgraph and sldemo_mdlref_house. In the Properties pane on the right,
under Impacted, click house.

Model Dependency Views

You can explore model dependencies using the model hierarchy or the model instances views.

Model Hierarchy View

The Model Hierarchy view shows the model, subsystem, library and data dictionary files referenced
by a top model.

• A referenced file appears only once in the view even if it is referenced more than once in the
model.
• In the following illustration, blue boxes represent model files, red boxes represent libraries, and
yellow boxes represent subsystem references. Arrows represent dependencies. For example, the
arrows in this example indicate that the aero_guidance model references two libraries:
aerospace and simulink_need_slupdate.

17-38
Analyze Model Dependencies

• An arrow from a library that points to itself indicates that the library references itself. Blocks in
the library reference other blocks in that same library. The example view shows that the libraries
aerospace and simulink_need_slupdate reference themselves.
• Dark red boxes represent protected models (.slxp files). You cannot open or edit protected
referenced models. See “Reference Protected Models from Third Parties” on page 8-18.

Model Instances View

The Model Instances view shows every reference to a model in a model reference hierarchy with
the top model at the root of the hierarchy. Boxes represent the top model and its references. See
“Model References”.

• 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. This example graph shows that the
model reference hierarchy for sldemo_mdlref_depgraph contains two references to the model
sldemo_mdlref_F2C.
• Yellow boxes represent accelerated-mode instances, red boxes represent normal-mode instances,
purple boxes represent processor-in-the-loop mode instances, and green boxes represent
software-in-the-loop mode instances. See “Choose Simulation Modes for Model Hierarchies” on
page 8-45.

The previous example graph shows that one of the references to sldemo_mdlref_F2C operates
in normal mode and the other operates in accelerated mode.
• The Dependency Analyzer detects when a simulation mode is overridden and appends
(Overridden) to the simulation mode. If a referenced model is configured to run in normal mode
and it runs in accelerator mode, its simulation mode is overridden. This occurs when another
model that runs in accelerator mode directly or indirectly references it.

17-39
17 Project File Management

Find Required Products


To find required products and add-ons for a file in your design, select a box in the dependency graph.
The Dependency Analyzer shows the list of required products by your selection in the Products
section in the Properties pane.

To find required add-ons for the whole design, click the graph background to clear all selection.
Examine the list of products in the Products section in the Properties pane.

To highlight files that use a certain product in the graph, for example Simulink, in the Products

section, in the Properties pane, point to product and click the magnifying glass icon .

To go through these files, use the arrows in the search box (e.g., Files using "productName").

To undo the highlighting, close the search box.

To investigate further, you can list the files that use a product and examine where in these files the
dependency is introduced. In the Products section, in the Properties pane, point to a product and

click the search folder icon .

Export Dependency Analysis Results


To export all the files displayed in the dependency graph, click the graph background to clear the
selection on all files. In the Dependency Analyzer toolstrip, in the Export section, click Export. Select
from the available options:

• Export to Workspace — Save file paths to a variable in the workspace.


• Generate Dependency Report — Save dependency analysis results in a printable report (HTML,
Word, or PDF).
• Package As Archive — Export files in the graph as an archive.
• Save As GraphML — Save dependency analysis results as a GraphML file.
• Save As Image — Save displayed dependency graph as an image.

17-40
Analyze Model Dependencies

You can also export a subset of files in the graph. Select the files, then click Export. The menu
displays how many files are selected. The Dependency Analyzer exports only the selected files.

Note When you use Package As Archive, the Dependency Analyzer includes the selected files and
all their dependencies in the archive.

Create Project from the Dependency Graph


To package, share, or put your design under source control, create a project from your model. You
can create a project from the model dependency graph.

To create a project from all the files displayed in the dependency graph, click the graph background.
This action clears all selected files.

1 In the Dependency Analyzer toolstrip, in the Export section, click Create Project.
2 In the Create Project window, click OK.

The Dependency Analyzer creates a project and reloads the graph.

You can also create a project from a subset of files in the graph. Select the files, then click Create
Project. The Dependency Analyzer includes the selected files and all their dependencies in the
project.

See Also

Related Examples
• “Perform Block-Level Impact Analysis Using Dependency Analyzer”
• “Visualize Model Reference Hierarchies”
• “Design a Guidance System in MATLAB and Simulink”

More About
• “Custom Libraries”

17-41
17 Project File Management

• “Model References”

17-42
View Requirements Toolbox Links Associated with Model Elements

View Requirements Toolbox Links Associated with Model


Elements

In this section...
“Highlight, Filter, and View Information for Links in a Model” on page 17-43
“Navigate to Externally Stored Requirements from a Model” on page 17-46

You can work with links that were added to the model with Requirements Toolbox when you use the
Requirements Viewer app in Simulink. For all links, you can:

• Highlight model objects with links


• View information about a link
• Filter link highlighting based on specified keywords

For links to requirements that are stored in external documents, you can also navigate to the linked
requirements.

Highlight, Filter, and View Information for Links in a Model

This example shows how to work with a Simulink model that has links using the Requirements Viewer
app. You can highlight links, view information about a link, and filter link highlighting based on
specified keywords.

Open the slvnvdemo_fuelsys_officereq model.

open_system('slvnvdemo_fuelsys_officereq')

In the Apps tab, click Requirements Viewer.

Highlight Links in a Model

To highlight model objects that have associated outgoing links, in the Requirements Viewer tab,
click Highlight Links.

Model objects that have associated outgoing links are highlighted in yellow, such as the block called
MAP sensor.

Objects that contain child objects with associated outgoing links are highlighted with an orange
outline, such as the fuel rate controller subsystem.

17-43
17 Project File Management

Model objects that do not have associated links are dimmed.

To remove highlighting, click the Highlight Links button again. When highlighting links, ensure that
you don't have any keyword filters applied because this can prevent some objects from becoming
highlighted. For more information, see Filter Highlighted Links on page 17-45.

View Information About a Link

After you've identified the model objects that have associated outgoing links, you can view
information about those links. Right-click the MAP sensor block and select Requirements > Open
Outgoing Links dialog.

17-44
View Requirements Toolbox Links Associated with Model Elements

The Outgoing Links dialog displays information about the link and its destination. In this case, the
link destination is a requirement stored in an external document. The dialog displays the:

• Link description
• Document type
• Document name and relative location
• Location identifier for link destination
• Link keywords

If you do not have Requirements Toolbox™ installed, the buttons on the Outgoing Links dialog box
are dimmed.

Filter Highlighted Links

Links in your model can have associated keywords. You can categorize a link with a keyword. For
example, the slvnvdemo_fuelsys_officereq model uses the keywords design, requirement,
and test.

In the slvnvdemo_fuelsys_officereq model, the MAP sensor block has the specified keyword
test, which was found in View Information about a Link on page 17-44. Filter the highlighted links
so that only blocks that have associated links with the keyword test are highlighted:

17-45
17 Project File Management

1 In the Requirements Viewer tab, click Link Settings.


2 In the Requirement Settings dialog, in the Filters tab, select Filter links by keywords when
highlighting and reporting requirements.
3 In the Include links with any of these keywords field, enter test.
4 Click Close.
5 In the Requirements Viewer tab, click Highlight Links.

Note that the fuel rate controller subsystem is not highlighted when the filter is applied.

You can also use the Exclude links with any of these keywords field to omit blocks from
highlighting that have associated links with the specified keyword. You can enter multiple keywords
in the Include links with any of these keywords and Exclude links with any of these keywords
fields. If you select Apply same filters to link labels, when you right-click blocks that have links but
are not highlighted, the link is greyed out and you cannot navigate to the destination.

To clear the filter, clear Filter links by keywords when highlighting and reporting
requirements, or remove all keywords from the Include links with any of these keywords and
Exclude links with any of these keywords fields.

Navigate to Externally Stored Requirements from a Model

17-46
View Requirements Toolbox Links Associated with Model Elements

This example shows how to navigate to linked requirements that are stored in an external document
from a model using the Requirements Viewer app in Simulink®. If a model object is linked to a
requirement that is stored in an external document, such as a Microsoft® Word or Microsoft Excel®
file, or an IBM® Rational® DOORS® or IBM DOORS Next project, then you can navigate to the
requirement in the external document from the associated block in Simulink.

Open the slvnvdemo_fuelsys_officereq model.

open_system('slvnvdemo_fuelsys_officereq')

The block called MAP sensor is linked to a requirement in a Microsoft Excel file. To navigate to the
requirement in the Excel file, right-click the MAP sensor block, select Requirements, and click the
link at the top of the context menu.

The associated requirement opens in Excel.

If you don't have Requirements Toolbox™ installed, then you cannot navigate to requirements that
are stored in a Requirements Toolbox requirement set.

Cleanup

Close the open models without saving changes.

17-47
17 Project File Management

bdclose all;

See Also
“Find Requirements Documents in a Project” on page 18-27

17-48
Identify and Run Tests in MATLAB Projects

Identify and Run Tests in MATLAB Projects


In this section...
“Label Test Files” on page 17-49
“Identify and Run All Tests in Project” on page 17-50
“Create Test Suite from Project Test Files” on page 17-51

MATLAB projects provide tools to improve productivity, portability, collaboration, and maintainability
of your MATLAB and Simulink code. Testing is an important aspect of software development and
maintenance. To ensure the reproducibility, reliability, and accuracy of your code, MATLAB projects
helps you identify and run tests easily.

Label Test Files


To easily identify and group tests and create test suites, label your test files. When you add test files
to a MATLAB project, the project automatically associates the Test labels with Simulink Test files
(.mldatx) and class-based MATLAB unit tests.

Label other test files manually using the Test classification label.

1 In the project Files view or in the Dependency Analyzer graph, select and right-click the files,
and then click Add Label.
2 From the list, select the Test label and click OK.

Alternatively, add the Test label programmatically using the addLabel function.

For projects under source control, the labels you add persist across file revisions.

17-49
17 Project File Management

Identify and Run All Tests in Project


In projects that have tests in different folders, you can use project filters to group and run all test files
from the project interface. Use filtering to identify and group tests in large projects.

To show only the files with the Test label in the project view, follow these steps.

1 In the project Files view, click the filter icon.


2 In the Filter Builder dialog box, select the Test label.
3 Click Apply.

17-50
Identify and Run Tests in MATLAB Projects

To run all the tests in the project, follow these steps.


1 In the project filtered Files view, select all the test files by using Ctrl+A.
2 Right-click your selection and click Run.

Alternatively, run all the tests with the Test label in the current project by using the runtests
function.

Create Test Suite from Project Test Files


If you run tests frequently by using project shortcuts or custom tasks, or if you need to run tests in
continuous integration (CI) pipelines, create a test suite and run tests programmatically.

To create a test suite from all files with the Test label in the opened project and its referenced
projects, use the testsuite function.

17-51
17 Project File Management

proj = currentProject;
suite = testsuite(proj.RootFolder,IncludingReferencedProjects=true);
results = run(suite)

results =

1×9 TestResult array with properties:

Name
Passed
Failed
Incomplete
Duration
Details

Totals:
9 Passed, 0 Failed, 0 Incomplete.
1.2533 seconds testing time.

Run Impacted Tests to Reduce Qualification Runtime

For projects with a large number of tests, running all tests is often time consuming.

To reduce qualification run time locally or in CI jobs, run only the tests that are impacted by the
changes you make to your project.
1 List modified files in the current project.
proj = currentProject;
modifiedFiles = listModifiedFiles(proj);

The listModifiedFiles function lists only local modifications. If you need the list of modified
files between revision identifiers for CI workflows, for example, when you want to run tests after
you merge your Git branch into the main branch, use these commands instead.
proj = currentProject;
[status,modifiedFiles] = system("git diff --name-only main..newBranch :!resources");
modifiedFiles = split(modifiedFiles);
modifiedFiles = modifiedFiles(1:(end-1));
2 Find all files that are impacted by the modified files in your project.
impactedFiles = listImpactedFiles(proj,modifiedFiles);

Tip

• You can use the Dependency Analyzer to interactively identify and create a test suite from the
tests you need to run to qualify your change. For more information, see “Perform Impact
Analysis with a Project”.
• To reduce qualification time on local machines and CI servers, you can also share the
dependency cache file. Using a prepopulated dependency cache file, you can perform an
incremental impact analysis and cut down the runtime of a full impact analysis. For more
information, see “Reduce Test Runtime Using Dependency Cache and Impact Analysis”.

3 Find all test files in your project.


testFiles = findFiles(proj,Label="Test");

17-52
Identify and Run Tests in MATLAB Projects

4 Find and run test files that are impacted by the modified project files.

impactedTests = intersect(testFiles,impactedFiles);
runtests(impactedTests);

Alternatively, you can create a filtered test suite based on source code dependency by using the
matlabtest.selectors.DependsOn class. For an example, see “Select Tests That Depend on
Modified Files in Project” (MATLAB Test).

See Also
Apps
Dependency Analyzer

Functions
addLabel | findFile | runtests | run (TestSuite) | testsuite | listModifiedFiles |
listImpactedFiles

More About
• “Find Project Files”
• “Add Labels to Project Files”
• “Create and Edit Projects Programmatically”
• “Create Shortcuts to Frequent Tasks”
• “Create Custom Tasks”
• “Continuous Integration Using MATLAB Projects and Jenkins”

17-53
18

Project Dependency Analysis

• “Dependency Analyzer Scope and Limitations” on page 18-2


• “Run a Dependency Analysis” on page 18-5
• “Explore the Dependency Graph, Views, and Filters” on page 18-7
• “Perform an Impact Analysis” on page 18-15
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Find Requirements Documents in a Project” on page 18-27
• “Export Dependency Analysis Results” on page 18-28
18 Project Dependency Analysis

Dependency Analyzer Scope and Limitations


Analysis Scope
The Dependency Analyzer identifies the required files and add-ons for your project or model. The
analysis covers a wide range of dependencies, including model references, subsystem references,
linked libraries, MATLAB and C/C++ code, Stateflow charts, data files, S-functions, and requirements
documents.

When the Dependency Analyzer encounters MATLAB code, such as in a model or block callback, or in
a .m file S-function, it attempts to identify the files it references. For more information, see “Analysis
Limitations” on page 18-2.

For files under the MATLAB root folder, the Dependency Analyzer only shows required products. It
does not analyze dependencies.

The Dependency Analyzer identifies dependencies inside user-defined add-ons and dependencies that
were introduced by code generation or by MATLAB code in model parameters. These options are off
by default because they can be time consuming for large designs.

To specify the scope of the analysis, in the Dependency Analyzer toolstrip, click Analyze and select
one or more of the following options:

Option Default Description


C/C++ Code On Analyze dependencies introduced by C/C++
code files.
Add-Ons Off Analyze dependencies inside add-ons.
Model Parameters Off Analyze dependencies introduced by MATLAB
code in model block parameters.
Generated Code Traceability Off Analyze dependencies introduced by code
generated from a model.

Analysis Limitations
• The Dependency Analyzer has limitations specific to MATLAB code analysis:

• The Dependency Analyzer only identifies function input arguments when they are literal
character vectors or strings:
load("mydatafile")
load mydatafile

If you define a file name as a variable and pass it to a function, the Dependency Analyzer is
unable to identify the dependency. In the following example, since the code is not executed, the
Dependency Analyzer does not have the value of str. The Dependency Analyzer might report a
missing dependency.
str = "mydatafile";
load(str);

This limitation extends to functions similar to load, such as fopen, xlsread, importdata,
dlmread, eval, or imread.

18-2
Dependency Analyzer Scope and Limitations

• The Dependency Analyzer does not always determine type automatically. Depending on the
way you call an object method, the Dependency Analyzer might confuse a method with a
function and report a missing dependency.

In MATLAB, you can call an object method in two different ways. For example, for an object p,
you can call the method addFile using the function notation:

p = currentProject;
addFile(p,"myfile");

or by using the dot notation:

p = currentProject;
p.addFile("myfile");

If you do not declare the type of p explicitly, the Dependency Analyzer might confuse a method
call that uses a function notation with a function call. The analyzer reports addFile as a
missing dependency.

To work around this limitation, use dot notation to call a method or use arguments to explicitly
declare the variable type in your function:

function myfunction(p)

arguments
p matlab.project.Project
end

addFile(p,"myfile");
end
• The Dependency Analyzer does not report a dependency to a class that is referenced using a
method call.
• When analyzing a file, the Dependency Analyzer does not consider the context in which it is called.
When a file A calls a file B, the Dependency Analyzer does not know about data used in B but
defined in A. The Dependency Analyzer reports this data as a missing file. To work around this
limitation, pass this data explicitly using function input arguments.

For example, when you analyze a Simulink subsystem that is referenced in a model that links to a
data dictionary and the subsystem uses an enumeration that you define in the data dictionary, the
analysis cannot access the enumeration and reports this data as a missing file.
• The Dependency Analyzer might not report certain blocksets required by a model.

The Dependency Analyzer is unable to detect blocksets that do not introduce dependencies on any
files, such as Fixed-Point Designer.

To include dependencies that the analysis cannot detect, add the file that introduces the
dependency to your project. To create a project from your model, see “Create a Project from a
Model” on page 16-12.
• The Dependency Analyzer might not detect required support packages. It lists required add-ons,
including apps and toolboxes.
• The Dependency Analyzer might not report dependencies for dynamic content in masked blocks.

18-3
18 Project Dependency Analysis

Based on the parameters of the masked blocks, dynamic masks can modify the masked subsystem
and change the block dependencies. If the dynamic mask is in a library, the Dependency Analyzer
is unable to detect the dynamic changes.
• The Dependency Analyzer does not support Simulink functions called from MATLAB function
blocks.
• Some MathWorks products and add-ons share code and Simulink libraries. The Dependency
Analyzer might report dependencies on all of them.

To investigate where shared code is used, in the Properties panel, in the Products section, point

to a product under Shared Functionalities Among: and click the search folder icon .
• The Dependency Analyzer analyzes project code without evaluating its content, therefore:

• The Dependency Analyzer does not add global variables in executed functions.
• The Dependency Analyzer analyzes code inside logic statements, even if it is not executed. In
the following example, the code is not executed but the Dependency Analyzer reports a missing
dependency on Simulink.

if false
load_system(vdp)
end

See Also

Related Examples
• “Run a Dependency Analysis” on page 18-5
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Perform an Impact Analysis” on page 18-15
• “Find Requirements Documents in a Project” on page 18-27

18-4
Run a Dependency Analysis

Run a Dependency Analysis

Note You can analyze only files that are in your project. If your project is new, add files to the project
before running a dependency analysis. See “Add Files to the Project” on page 16-22.

To investigate dependencies, run a dependency analysis on your project. On the Project tab, click the
down arrow to expand the Tools gallery. Under Apps, click Dependency Analyzer. Alternatively, in
the project Views pane, select Dependency Analyzer and click Analyze.

To analyze the dependencies of specific files, in the dependency graph, select the files. In the Impact
Analysis section, click All Dependencies or use the context menu and select Find All
Dependencies.

To analyze the dependencies inside add-ons, select Analyze > Add-Ons. For more details about
available options, see “Analysis Scope” on page 18-2.

You can also check dependencies directly in Project. In the Project Files view, right-click the project
files you want to analyze and select Find Dependencies.

After you run the first dependency analysis of your project, subsequent analyses incrementally update
the results. The Dependency Analyzer determines which files changed since the last analysis and
updates the dependency data for those files. However, if you update add-ons or installed products and
want to discover dependency changes in them, you must perform a complete analysis. To perform a
complete analysis, in the Dependency Analyzer, click Analyze > Reanalyze All.

Note In the Simulink Editor, if an open model, library, or chart belongs to a project, you can find file
dependencies. On the Simulation tab, select Project > Run Dependency Analysis. Simulink
analyzes the whole project and shows all dependencies for the file.

18-5
18 Project Dependency Analysis

For next steps, see:

• “Find Required Products and Add-Ons” on page 18-17


• “Find Dependencies of Selected Files” on page 18-18
• “Check Dependency Results and Resolve Problems” on page 18-21

Tip To try a dependency analysis on example files, see “Perform Impact Analysis with a Project”.

See Also

Related Examples
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Perform an Impact Analysis” on page 18-15
• “Export Dependency Analysis Results” on page 18-28
• “Find Requirements Documents in a Project” on page 18-27

18-6
Explore the Dependency Graph, Views, and Filters

Explore the Dependency Graph, Views, and Filters


If you have not yet run an analysis, on the Project tab, click the down arrow to expand the Tools
gallery. Under Apps, click Dependency Analyzer.

The dependency graph displays your project structure, dependencies, and how files relate to each
other. Each item in the graph represents a file and each arrow represents a dependency. For more
details, see “Investigate Dependency Between Two Files” on page 18-7.

By default, the dependency graph shows all files required by your project. To help you investigate
dependencies or a specific problem, you can simplify the graph using one of the following filters:

• Use the Views to color the files in the graph by type, class, source control status, and label. See
“Color Files by Type, Status, or Label” on page 18-8.
• Use the check boxes in the Legend pane to filter out a group of files.
• Use the Impact Analysis tools to simplify the graph. See “Find Dependencies of Selected Files”
on page 18-18.

Select, Pan, and Zoom


• To select an item in the graph, click it.

To select multiple files, press Shift and click the files.

To select all files of a certain type, hover the pointer over the corresponding item in the Legend
pane and click the Add to selection icon.

To clear all selection, click the graph background.

To remove all files of a certain type from the current selection, hover the pointer over the
corresponding item in the Legend pane and click the Remove from selection icon.
• To open a file, double-click it.
• To pan the dependency graph, hold the Space key, click and drag the mouse. Alternatively, press
and hold the mouse wheel and drag.

For large graphs, navigate using the Overview pane.


• To zoom in and out, in the Navigate section, click Zoom In and Zoom Out. Alternatively, use the
mouse wheel.
• To center and fit the dependency graph to view, in the Navigate section, click Fit to View.
Alternatively, press the Space bar.

Investigate Dependency Between Two Files


To see more information about how two files are related, select their dependency arrow. In the
Properties pane, in the Details section, you can see the full paths of the files you are examining, the
dependency type (such as function call, inheritance, S-function, data dictionary, model reference, and
library link), and where the dependency is introduced.

18-7
18 Project Dependency Analysis

To open the file and highlight where the dependency is introduced, in the Details section, click the
link under Impacted.

Color Files by Type, Status, or Label


Explore the different views in the Views section of the Dependency Analyzer toolstrip to explore your
project files dependencies.

• The MATLAB Files view shows only MATLAB files (such as .m, .mlx, .p, .mlapp, .fig, .mat,
and .mex) in the view and colors them by type.

18-8
Explore the Dependency Graph, Views, and Filters

• The Class Hierarchy view shows the class inheritance graph and colors the files by type (class,
enumeration class, or abstract class). If the class is not on the search path, the Dependency
Analyzer cannot determine the class type.

• The Model Hierarchy view shows the model, subsystem, library and data dictionary files
referenced by a top model. A referenced file appears only once in the view even if it is referenced
more than once in the model. For more details, see “Model Hierarchy View” on page 17-38.

18-9
18 Project Dependency Analysis

• The Model Instances view shows every instance to a model in a model reference hierarchy. A top
model is at the root of this hierarchy. If a model hierarchy references the same model more than
once, the referenced model appears multiple times in the instance view. For more details, see
“Model Instances View” on page 17-39.

18-10
Explore the Dependency Graph, Views, and Filters

• The Classification view shows all files in the graph and colors them by file label (such as test,
design, and artifact).

Use the classification view to identify which tests you need to run to validate the changes in your
design. For more information, see “Identify Tests to Run” on page 18-19.

18-11
18 Project Dependency Analysis

• The Source Control view shows all files in the graph and colors them by source control status.
This view is only enabled if your project is under source control.

Use the source control view to find modified files in your project and to examine the impact of
these changes on the rest of the project files. For more information, see “Investigate Impact of
Modified Files” on page 18-19.

18-12
Explore the Dependency Graph, Views, and Filters

• The Project Hierarchy view shows all projects in your project hierarchy in the graph and colors
them by project type, top-level or referenced project. This view is available only in MATLAB
Online.

Use the project hierarchy view to investigate how projects in your hierarchy relate to each other
and identify projects that introduce circular dependencies.

• Restore to Default clears all filters.

This is equivalent to manually removing all of the filters. Filters appear at the top of the graph. For
example, if you have the Source Control view selected, you can remove it by clicking

Apply and Clear Filters


In large projects, when investigating problems or dependencies, use the different filters to show only
the files you want to investigate:

18-13
18 Project Dependency Analysis

• To filter out a subgroup of files from the graph, such as files labeled test or modified files, use the
check boxes in the Legend pane. To remove the legend filter, click the Legend Filter

.
• To color the files in the graph by type, class, label, or source control status, use the filtered Views.
To remove the view filter, click View: viewName at the top of the graph. For example, if you have

the Source Control view selected, you can remove it by clicking .


• To show only the dependencies of a specific file, select the file and, in the Impact Analysis
section, click All Dependencies. The graph shows the selected file and all its dependencies. To
reset the graph to show all project dependencies, remove the filter at the top of the graph. For
example, if you filtered by all dependencies of NonLinearActuator.slx, to remove the filter

click .
• To clear all filters and restore the graph to show all analyzed dependencies in the project, click
Restore to Default. Alternatively, manually remove all filters at the top of the graph.

See Also

Related Examples
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Perform an Impact Analysis” on page 18-15

18-14
Perform an Impact Analysis

Perform an Impact Analysis

In this section...
“About Impact Analysis” on page 18-15
“Run a Dependency Analysis” on page 18-15
“Find Required Products and Add-Ons” on page 18-17
“Find Dependencies of Selected Files” on page 18-18

About Impact Analysis


In a project, you can use impact analysis to find out the impact of changing particular files.
Investigate dependencies visually and explore the structure of your project. Analyze selected or
modified files to find their required files and the files they affect. Impact analysis can show you how a
change affects other files before you make the change. For example, you can:

• Investigate the potential impact of a change in requirements by finding the design files linked to
the requirements document.
• Investigate change set impact by finding upstream and downstream dependencies of modified files
before committing the changes. Finding these dependencies can help you identify design and test
files that need modification, and help you find the tests you need to run.

After performing dependency analysis, you can open or label the files, export the results as
workspace variables, or reloadable files, or send files for custom task processing. Exporting the
results enables further processing or archiving of impact analysis results.

Tip For an example showing how to perform file-level impact analysis to find and run the tests
affected by modified files, see “Perform Impact Analysis with a Project”.

Run a Dependency Analysis


Before running a dependency analysis on a project, make sure that you have added all your files to
the project. For more information, see “Add Files to the Project” on page 16-22.

To start analyzing your project, on the Project tab, click the down arrow to expand the Tools gallery.
Under Apps, click Dependency Analyzer. Alternatively, in the project Views pane, select
Dependency Analyzer and click Analyze.

To analyze the dependencies of specific files, in the dependency graph, select the files. In the Impact
Analysis section, click All Dependencies or use the context menu and select Find All
Dependencies.

To analyze the dependencies inside add-ons, select Analyze > Add-Ons. For more details about
available options, see “Analysis Scope” on page 18-2.

You can also check dependencies directly in Project. In the Project Files view, right-click the project
files you want to analyze and select Find Dependencies.

18-15
18 Project Dependency Analysis

The dependency graph shows:

• Your project structure and its file dependencies, including how files such as models, libraries,
functions, data files, source files, and derived files relate to each other.
• Required products and add-ons.
• Relationships between source and derived files (such as .m and .p files, .slx and .slxp, .ssc
and .sscp, or .c and .mex files), and between C/C++ source and header files. You can see what
code is generated by each model, and find what code needs to be regenerated if you modify a
model.
• Warnings about problem files, such as missing files, files not in the project, files with unsaved
changes, and out-of-date derived files.

You can examine project dependencies and problem files using the File List. In the toolstrip, click
File List.

After you run the first dependency analysis of your project, subsequent analyses incrementally update
the results. The Dependency Analyzer determines which files changed since the last analysis and
updates the dependency data for those files. However, if you update add-ons or installed products and
want to discover dependency changes in them, you must perform a complete analysis. To perform a
complete analysis, in the Dependency Analyzer, click Analyze > Reanalyze All.

For next steps:

18-16
Perform an Impact Analysis

• “Find Required Products and Add-Ons” on page 18-17


• “Find Dependencies of Selected Files” on page 18-18
• “Check Dependency Results and Resolve Problems” on page 18-21

Tip To try a dependency analysis on example files, see “Perform Impact Analysis with a Project”.

Find Required Products and Add-Ons


After running a dependency analysis on a project, the graph shows the required add-ons for the whole
project or for selected files. You can see which products are required to use the project or find which
file is introducing a product dependency.

In the Dependency Analyzer, in the Properties pane, the Product section displays the required
products for the whole project. To view products required by a specific file, select a file by clicking
the graph.

To find which file is introducing a product dependency, point to the product name and click the

magnifying glass icon . The graph highlights the files that use the selected product.

To go through these files, use the arrows in the search box (e.g., Files using "productName").

To undo the highlighting, close the search box.

18-17
18 Project Dependency Analysis

To investigate further, you can list the files that use a product and examine where the dependency is
introduced. In the Products section, in the Properties pane, point to a product and click the search

folder icon .

If a required product is missing, the products list labels it as missing. The product is also listed in the
Problems section as productName not installed. To resolve a missing product, install the product
and rerun the dependency analysis.

Find Dependencies of Selected Files


After a dependency analysis, to find out the impact of particular files, select files in the dependency
graph use the context menu, or use controls in the legend, View and Impact Analysis sections of the
Dependency Analyzer. You can simplify the graph by investigating dependencies of particular files.

To investigate the dependencies of a file after running a dependency analysis, in the dependency
graph, select a file.

• In the Impact Analysis section, click All Dependencies. The graph shows the selected file and
all its dependencies.
• To show only files needed by the selected file to run properly, click Required.

18-18
Perform an Impact Analysis

• To show only files impacted by a potential change to the selected file, click Impacted.

Finding these dependencies can help you identify the impact of a change and identify the tests you
need to run to validate your design before committing the changes.

To investigate the dependencies of multiple files, click files while holding the Shift key. The Impact
Analysis section displays how many files are selected.

To reset the graph, click the filter at the top of the graph. For example, if you had filtered by files

impacted by f14_airframe.slx, click .

Investigate Impact of Modified Files

To examine the impact of the changes you made on the rest of the project files, perform an impact
analysis on the modified files in your project.

1 In the Views section, select the Source Control view. The graph colors the files by their source
control status. The modified files are in light blue.
2 Select all the modified files in the graph.

Alternatively, add all modified files to selection by clicking the Add to selection icon of an item
in the Legend pane.

Tip If you changed a large number of files, you can also use the file list.

In the Dependency Analyzer toolstrip, click File List. Point to Status and click the arrow to sort
the list by the source control status. Select all the modified files.

3 In the Impact Analysis section, click Impacted. Alternatively, use the context menu and select
Find Impacted.

Identify Tests to Run

To identify the tests you need to run to validate your design before committing the changes, use the
Classification view when you perform an impact analysis on the file you changed.

18-19
18 Project Dependency Analysis

1 In the Views section, select the Classification view. The graph colors the files by their project
label.
2 Select the file you changed, for example f14_airframe.slx.
3 In the Impact Analysis section, click Impacted. Alternatively, use the context menu and select
Find Impacted.

The example graph shows four tests you need to run to qualify the change made to
f14_airframe.slx.

See Also

Related Examples
• “Run a Dependency Analysis” on page 18-5
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Export Dependency Analysis Results” on page 18-28
• “Find Requirements Documents in a Project” on page 18-27
• “Automate Project Tasks Using Scripts” on page 17-19
• “Perform Impact Analysis with a Project”

18-20
Check Dependency Results and Resolve Problems

Check Dependency Results and Resolve Problems

If you have not yet run an analysis, on the Project tab, click the down arrow to expand the Tools
gallery. Under Apps, click Dependency Analyzer.

When you run a dependency analysis, the Dependency Analyzer identifies problems, such as missing
files, files not in the project, unsaved changes, and out-of-date derived files. You can examine problem
files using the dependency graph or the file list. When no file is selected, the Properties pane on the
right shows the add-ons dependencies and a list of problems for the entire project.

Problem Description Fix


Message
File not in project The file is not in the project. Right-click the problem file in the
graph and select Add to Project.

To remove a file from the problem list


without adding it to the project, right-
click the file and select Hide
Warnings.
Missing file The file is in the project but does not Create the file or recover it using
exist on disk. source control.
The file or variable cannot be found. If this status is acceptable, right-click
the file and select Hide Warnings.

Depending on the way you call an


object method, the Dependency
Analyzer might confuse a method with
a function and report a missing
dependency. See “Analysis Limitations”
on page 18-2.
Outside project The file is outside the project root If this status is acceptable, right-click
root folder. the file and select Hide Warnings.
Otherwise, move it under the project
root.

If required files are outside your


project root, you cannot add these files
to your project. This dependency might
not indicate a problem if the file is on
your path and is a utility or resource
that is not part of your project. Use
dependency analysis to ensure that you
understand the design dependencies.
In unreferenced The file is within a project that is not Add the project containing the file as a
project referenced by the current project. project reference.
Unsaved changes The file has unsaved changes in the Save the file.
MATLAB and Simulink editors.

18-21
18 Project Dependency Analysis

Problem Description Fix


Message
Derived file out of The derived file is older than the source Regenerate the derived file. If it is a .p
date file it was derived from. file, you can regenerate it automatically
by running the project checks. In
MATLAB, on the Project tab, click the
down arrow to expand the Tools
gallery. Under Project Checks, click
Check Project.

If you rename a source file, the project


detects the impact to the derived file
and prompts you to update it.
Created in a newer The file is created in a newer release If this status is acceptable, right-click
release than the one currently used. For the file and select Hide Warnings.
example, the file is a Simulink model Otherwise, open the model in the
file created in a newer Simulink release you used to create it and export
release. The Dependency Analyzer to a previous version. See “Export
warns and does not analyze the file. Model to Previous Version of Simulink”
on page 1-30.
Not a valid file The file is not a format supported by If this status is acceptable, right-click
format MathWorks products. For example, the the file and select Hide Warnings.
file has .slx extension but is not a
valid Simulink model. The Dependency
Analyzer warns and does not analyze
the file.
File with syntax The file contains a syntax error or the If this status is acceptable, right-click
error Dependency Analyzer cannot parse the the file and select Hide Warnings.
file. For example, the file is an .m file Otherwise, fix the syntax error and
that contains a syntax error. The save the file.
Dependency Analyzer warns and does
not analyze the file.

18-22
Check Dependency Results and Resolve Problems

Problem Description Fix


Message
Product not The project has a dependency on a Fix models by installing missing
installed missing product. products.

If you open a model that contains built-


in blocks or library links from missing
products, you see labels and links to
help you fix the problem.

• Blocks are labeled with missing


products (for example, SimEvents
not installed)
• Tooltips include the name of the
missing product
• Messages provide links to open Add-
On Explorer and install the missing
products

To find a link to open Add-On Explorer


and install the product:

• For built-in blocks, open the


Diagnostic Viewer, and click the link
in the warning.
• For unresolved library links, double-
click the block to view details and
click the link.

Product dependencies can occur in


many other ways, for example in
callbacks, so in this case you cannot
easily see where the missing product is
referenced. Fix models by installing
missing products.
Circular The project hierarchy contains a Break the circular dependency. For
dependency on circular dependency. example, if the reference to
ProjectName ProjectName is not needed, remove
ProjectName from the list of the top-
level project references.

If the reference to ProjectName is


needed, refactor your project hierarchy
to eliminate the circular dependency.

This warning is specific to the Project


Hierarchy view and is available only in
MATLAB Online.

18-23
18 Project Dependency Analysis

Investigate Problem Files in Dependency Graph


Use the graph to investigate problem files graphically.

1 In the Properties pane, in the Problems section, point to a problem, such as File not in

project, and click the magnifying glass icon . The graph highlights the files with this
specific problem.

To go through these files, use the arrows in the search box (e.g., Problem: File not in
project).

To undo the highlighting, close the search box.

2 To see more information about a specific problem file, select the file in the graph. In the
Properties pane, in the Problems section, you can see details including the path, type, and the
problems for this file.

Take actions to resolve the problem file. For example, if a file is File not in project, right-
click the problem file in the graph and select Add to Project. To remove the file from the
problem list without adding it to the project, right-click the file and select Hide Warnings.

18-24
Check Dependency Results and Resolve Problems

3 Investigate the next problem listed in the Problems section. Repeat the steps until you resolve
all problems.

To update the graph and the Problems list, click Analyze.

Tip For large projects, viewing the results in a list can make navigation easier.

For more ways to work with the dependency graph, see “Perform an Impact Analysis” on page 18-15.

Investigate Problem Files in File List


For large projects, use the File List to investigate your project problem files.

1 In the Dependency Analyzer toolstrip, click File List.


2 In the Properties pane, in the Problems section, point to a problem, such as File not in

project, and click the magnifying glass icon .

The File List shows only files with the specific problem.

To fix the File not in project problem, select all the files in the list. Use the context menu
and select Add to Project. To remove a file from the problem list without adding it to the
project, right-click the file and select Hide Warnings.
3 Investigate the next problem listed in the Problems section, for example Missing file. Repeat
the steps until you resolve all problems.

To update the graph and the Problems list, click Analyze.

See Also

Related Examples
• “Run a Dependency Analysis” on page 18-5

18-25
18 Project Dependency Analysis

• “Perform an Impact Analysis” on page 18-15


• “Export Dependency Analysis Results” on page 18-28

18-26
Find Requirements Documents in a Project

Find Requirements Documents in a Project


In a project, a dependency analysis finds requirements documents linked using the Requirements
Management Interface.

• You can view and navigate to and from the linked requirements documents.
• You can create or edit Requirements Management links only if you have Requirements Toolbox.

1 On the Project tab, click the down arrow to expand the Tools gallery. Under Apps, click
Dependency Analyzer.

Alternatively, in the project Views pane, select Dependency Analyzer and click the Analyze
button.
2 The dependency graph displays the structure of all analyzed dependencies in the project. Project
files that are not detectable dependencies of the analyzed files are not visible in the graph.
3 Use the dependency graph legend to locate the requirements documents in the graph. Arrows
connect requirements documents to the files with the requirement links.
4 To find the specific block containing a requirement link, select the arrow connecting
requirements documents to the files. In the Properties pane, in the Impacted column of the
table, click the file to open it and highlight the block containing the dependency.
5 To open a requirements document, double-click the document in the graph.

See Also

Related Examples
• “Run a Dependency Analysis” on page 18-5
• “Check Dependency Results and Resolve Problems” on page 18-21
• “Perform an Impact Analysis” on page 18-15
• “Export Dependency Analysis Results” on page 18-28
• “View Requirements Toolbox Links Associated with Model Elements” on page 17-43

18-27
18 Project Dependency Analysis

Export Dependency Analysis Results


You can export dependency analysis results for your project in several formats. If you have not yet
run an analysis, on the Project tab, click the down arrow to expand the Tools gallery. Under Apps,
click Dependency Analyzer.

To export all the files displayed in the dependency graph, click the graph background to clear the
selection on all files. In the Dependency Analyzer toolstrip, in the Export section, click Export. Select
from the available options:

• Save to Workspace — Save file paths to a variable in the workspace.


• Generate Dependency Report — Save dependency analysis results in a printable report (HTML,
Word, or PDF).
• Package As Archive — Export files in the graph as an archive.
• Save As GraphML — Save dependency analysis results as a GraphML file.

Tip You can open and compare different analysis results without having to repeat the analysis.

• To compare previously saved graphs, in MATLAB, in the Current Folder, right-click two
GraphML files and select Compare Selected Files/Folders.
• To open saved dependency analysis results, use the depview function, then restore the view to
default.

1 In the Command Window, type: depview("myDepResults.graphml");


2 In the Dependency Analyzer toolstrip, in the Views section, click Restore to Default.

• Save As Image — Save displayed dependency graph as an image.

To export a subset of files in the graph, select the files, then click Export.

• Use the Legend check boxes, the filtered Views, or the Impact Analysis tools to simplify the
graph.
• To select multiple files, press Shift and select the files.
• To select all files in the filtered graph, press Ctrl+A.

The menu displays how many files are selected. The Dependency Analyzer exports only the selected
files.

18-28
Export Dependency Analysis Results

Note When you use Package As Archive, the Dependency Analyzer includes the selected files and
all their dependencies in the archive.

Alternatively, you can work with the graph information programmatically. See “Automate Project
Tasks Using Scripts” on page 17-19.

Send Files to Project Tools


You can send files to other Project tools using the Project menu. The Dependency Analyzer exports
only the selected files in the current filtered view.

Select the desired files. In the Dependency Analyzer toolstrip, in the Export section, click Project.
Select from the available options:

• Show in Project — Switch to the project Files view with the files selected.
• Send to Custom Task — Run a project custom task on the selected files.

See Also

Related Examples
• “Perform an Impact Analysis” on page 18-15

18-29
19

Project Source Control

• “About Source Control with Projects” on page 19-2


• “Add a Project to Source Control” on page 19-5
• “Set Source Control Preferences” on page 19-7
• “Register Model Files with Source Control Tools” on page 19-9
• “Set Up SVN Source Control” on page 19-10
• “Set Up Git Source Control” on page 19-17
• “Add Git Submodules” on page 19-25
• “Automatically Merge Models” on page 19-27
• “Create New GitHub Repository” on page 19-29
• “Disable Source Control” on page 19-30
• “Change Source Control” on page 19-31
• “Write a Source Control Integration with the SDK” on page 19-32
• “Clone Git Repository” on page 19-33
• “Check Out SVN Repository” on page 19-35
• “Tag and Retrieve Versions of Project Files” on page 19-37
• “Refresh Status of Project Files” on page 19-38
• “Check for Modifications” on page 19-39
• “Update Revisions of Project Files” on page 19-40
• “Get SVN File Locks” on page 19-42
• “View Modified Files” on page 19-44
• “Compare Revisions” on page 19-47
• “Run Project Checks” on page 19-49
• “Commit Modified Files to Source Control” on page 19-50
• “Revert Changes” on page 19-52
• “Pull, Push, and Fetch Files with Git” on page 19-54
• “Branch and Merge Files with Git” on page 19-58
• “Resolve Conflicts” on page 19-62
• “Work with Derived Files in Projects” on page 19-66
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67
• “Continuous Integration Using MATLAB Projects and Jenkins” on page 19-72
• “Determine Order for Resolving Conflicts Using Dependency Analyzer” on page 19-76
19 Project Source Control

About Source Control with Projects


You can use a project to work with source control. You can perform operations such as update,
commit, merge changes, and view revision history directly from the project environment.

In MATLAB, projects have interfaces to:

• Git— See “Set Up Git Source Control” on page 19-17.


• Subversion (SVN) — See “Set Up SVN Source Control” on page 19-10.
• Software Development Kit (SDK) — You can use the SDK to integrate projects with third-party
source control tools. See “Write a Source Control Integration with the SDK” on page 19-32.

Tip You can check for updated source control integration downloads on the projects Web page:
https://www.mathworks.com/products/simulink/projects.html

To use source control in your project, use any of the following workflows:

• Add source control to a project. See “Add a Project to Source Control” on page 19-5.
• Retrieve files from an existing repository and create a new project. See “Clone Git Repository” on
page 19-33 or “Check Out SVN Repository” on page 19-35.
• Create a new project in a folder already under source control and click Detect. See “Create a
New Project from a Folder” on page 16-18.
• Make your project publicly available on GitHub. See “Share Project on GitHub” on page 17-34.

When your project is under source control, you can:

• “Clone Git Repository” on page 19-33 or “Check Out SVN Repository” on page 19-35
• “Compare Revisions” on page 19-47
• “Commit Modified Files to Source Control” on page 19-50

Caution Before using source control, you must register model files with your source control tools to
avoid corrupting models. See “Register Model Files with Source Control Tools” on page 19-9.

To view an example project under source control, see “Explore Project Tools with the Airframe
Project” on page 16-5.

Classic and Distributed Source Control


This diagram represents the classic source control workflow (for example, using SVN).

19-2
About Source Control with Projects

Benefits of classic source control:

• Locking and user permissions on a per-file basis (e.g., you can enforce locking of model files)
• Central server, reducing local storage needs
• Simple and easy to learn

This diagram represents the distributed source control workflow (for example, using Git).

Benefits of distributed source control:

• Offline working
• Local repository, which provides full history
• Branching
• Multiple remote repositories, enabling large-scale hierarchical access control

To choose classic or distributed source control, consider these tips.

Classic source control can be helpful if:

• You need file locks.

19-3
19 Project Source Control

• You are new to source control.

Distributed source control can be helpful if:

• You need to work offline, commit regularly, and need access to the full repository history.
• You need to branch locally.

See Also

Related Examples
• “Set Up Git Source Control” on page 19-17
• “Set Up SVN Source Control” on page 19-10
• “Add a Project to Source Control” on page 19-5
• “Clone Git Repository” on page 19-33
• “Check Out SVN Repository” on page 19-35
• “Register Model Files with Source Control Tools” on page 19-9

19-4
Add a Project to Source Control

Add a Project to Source Control


In this section...
“Add a Project to Git Source Control” on page 19-5
“Add a Project to SVN Source Control” on page 19-5

Add a Project to Git Source Control


If you want to add version control to your project files without sharing with another user, it is
quickest to create a local Git repository in your sandbox.

1 On the Project tab, in the Source Control section, click Use Source Control.
2 In the Source control Information dialog box, click Add Project to Source Control.
3 In the Add to Source Control dialog box, in the Source control tool list, select Git to use the
Git source control tool provided by the project.
4 Click Convert to finish adding the project to source control.

Git creates a local repository in your sandbox project root folder. The project runs integrity
checks.
5 Click Open Project to return to your project.

The Project node displays the source control name Git and the repository location Local
Repository: yoursandboxpath.
6 Select the Modified files view and click Commit to commit the first version of your files to the
new repository.

In the dialog box, enter a comment if you want, and click Submit.

Tip If you want to use Git and share with other users:

• To clone an existing remote Git repository, see “Clone Git Repository” on page 19-33.
• To connect an existing project to a remote repository, on the Project tab, in the Source Control
section, click Remote and specify a single remote repository for the origin branch.
• To make your project publicly available on GitHub, see “Share Project on GitHub” on page 17-34.

Add a Project to SVN Source Control

Caution Before you start, check that your sandbox folder is on a local hard disc. Using a network
folder with SVN is slow and unreliable.

This procedure adds a project to the built-in SVN integration that comes with the project. If you want
to use a different version of SVN, see “Set Up SVN Source Control” on page 19-10.

1 On the Project tab, in the Source Control section, click Use Source Control.

19-5
19 Project Source Control

2 In the Source control Information dialog box, click Add Project to Source Control.
3 In the Add to Source Control dialog box, select SVN as the Source control tool.
4 Next to Repository path, click Change.
5
In the Specify SVN Repository URL dialog box, to specify an existing repository, click the
button to browse for your repository, paste a URL into the box, or use the list to select a recent
repository.
6 Click Validate to check the path to the selected repository.

When the path is valid, you can browse the repository folders. For example, select the trunk
folder, and verify the selected URL at the bottom of the dialog box, as shown.
7 Click OK to return to the Add to Source Control dialog box.

If your repository has a file URL, a warning appears that file URLs are for single users. Click OK
to continue.
8 Click Convert to finish adding the project to source control.

The project runs integrity checks.


9 After the integrity checks run, click Open Project to return to your project.

The Project node displays details of the current source control tool and the repository location.

Caution Before using source control, you must register model files with your source control tools to
avoid corrupting models. See “Register Model Files with Subversion” on page 19-12.

See Also

Related Examples
• “Set Up Git Source Control” on page 19-17
• “Set Up SVN Source Control” on page 19-10
• “Register Model Files with Source Control Tools” on page 19-9
• “Clone Git Repository” on page 19-33
• “Check Out SVN Repository” on page 19-35
• “Get SVN File Locks” on page 19-42
• “Work with Project Files” on page 17-7
• “View Modified Files” on page 19-44
• “Commit Modified Files to Source Control” on page 19-50

More About
• “About Source Control with Projects” on page 19-2

19-6
Set Source Control Preferences

Set Source Control Preferences

MathWorks source control integration, accessible through Projects and the Current Folder browser, is
enabled by default.

To disable source control, on the Home tab, in the Environment section, click Preferences. Select
MATLAB > General > Source Control and click None.

When you disable source control, MATLAB does not destroy repository information. For example, it
does not remove the .svn folders.

Source Control Preferences in MATLAB Online


In MATLAB Online, you can use the general source control preferences to specify the default location
of new working folders and disable SVN source control.

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Source
Control. Then, set your preferences.

To set Git-specific source control preferences, see “Set Git Preferences in MATLAB Online” on page
19-7.

Preference Usage
New Working Folder When you interactively clone or check out a working copy from a
repository, by default, MATLAB Online downloads files into the currently
opened folder. To use a folder of your choice, select Use specified folder
and specify the folder by using the browser or pasting the path.
Source Control Integrations In MATLAB Online, MathWorks source control integration, accessible
through Project browser and the Current Folder browser, is enabled by
default.

To disable SVN source control, clear Enable Java source control


adapters.

When you disable source control, MATLAB Online does not destroy
repository information. For example, it does not remove the .svn folders.

Set Git Preferences in MATLAB Online

In MATLAB Online, you can use the Git source control preferences to specify your username and
email, remember credentials for the current MATLAB session, and enable SSH authentication.

On the Home tab, in the Environment section, click Preferences. Select MATLAB > Source
Control > Git. Then, set your preferences.

Preference Usage
User Specify your username and email in Name and Email. Doing so overrides
information you already specified in your global Git configuration file.

19-7
19 Project Source Control

Preference Usage
MATLAB Git integration is configured by default to Generate local
avatars using your initials. An avatar appears next to your username and
email in the Branch Manager.

If you have a globally recognized avatar, you can enable MATLAB to


Retrieve avatars from web services such as gravatar.com.

To disable the usage of avatars, select None instead.


Credentials To configure MATLAB Online to store usernames and passwords when you
use Git, select Remember credentials for the current MATLAB
session.
SSH SSH authentication is disabled by default in MATLAB Online. To enable
the use of SSH keys, select Enable SSH. Using this option requires you
to store the public and private key files on MATLAB Drive. Make sure
your Key is pass-phrase protected when you generate your SSH keys.
Specify the Public key file by using the browser or pasting the path to
your public key file. An example path is /MATLAB Drive/.ssh/
id_rsa.pub.
Specify the Private key file by using the browser or pasting the path to
your private key file. An example path is /MATLAB Drive/.ssh/id_rsa.
To enable the use of a pass-phrase and receive a prompt once per session,
select Key is pass-phrase protected.
To use multiple keys, use an SSH agent. In the SSH section, select If
running, use SSH agent instead of the specified key.

If an SSH agent is running, MATLAB Online looks for keys in the agent
before using the keys you specified in Public key file and Private key
file.
Branch Manager To control the number of commits that the Branch Manager shows,
specify the Maximum number of commits to show.

See Also

More About
• “Clone Git Repository” on page 19-33
• “Add a Project to Source Control” on page 19-5

19-8
Register Model Files with Source Control Tools

Register Model Files with Source Control Tools


If you use third-party source control tools, you must register your model file extensions (.mdl
and .slx) as binary formats. If you do not, these third-party tools can corrupt your model files when
you submit them, by changing end-of-line characters, expanding tokens, substituting keywords, or
attempting to automerge. Corruption can occur whether you use the source control tools outside of
Simulink or if you try submitting files from a project without first registering your file formats.

Also check that other file extensions are registered as binary to avoid corruption at check-in for files
such as .mat, .mlx, .mlapp, .mdlp, .slxp, .sldd, .p, MEX-files, .xlsx, .jpg, .pdf, .docx, etc.

For instructions with SVN, see “Register Model Files with Subversion” on page 19-12. You must
register model files if you use SVN, including the SVN integration provided by the project.

For instructions with Git, see “Register Binary Files with Git” on page 19-17.

See Also

Related Examples
• “Register Model Files with Subversion” on page 19-12
• “Register Binary Files with Git” on page 19-17

19-9
19 Project Source Control

Set Up SVN Source Control


In this section...
“Set Up SVN Provided with Projects” on page 19-10
“Set Up Project SVN for SVN Version Already Installed” on page 19-11
“Set Up Project SVN for SVN Version Not Yet Provided with Projects” on page 19-11
“Register Model Files with Subversion” on page 19-12
“Enforce SVN Locking Model Files Before Editing” on page 19-14
“Share a Subversion Repository” on page 19-15
“Manage SVN Externals” on page 19-15

Set Up SVN Provided with Projects


Projects provide SVN for use with Subversion (SVN) sandboxes and repositories at version 1.9. You do
not need to install SVN to use this integration because it includes an implementation of SVN.

Note This integration ignores any existing SVN installation.

The project SVN supports secure logins.

To use the version of SVN provided with the project, do one of the following:

• On the MATLAB Home tab, select New > Project > From SVN.
• Alternatively, in the start page, select Project from SVN to retrieve from source control, or when
you add a project to source control, select SVN in the Source control tool list

For instructions, see

• “Add a Project to Source Control” on page 19-5, or


• “Check Out SVN Repository” on page 19-35.

Caution Place your project sandbox folder on a local hard disc. Using a network folder with SVN is
slow and unreliable. If you use a Windows network drive, SVN move operations can result in
incorrect "not existing" status for files visible in file browsers.

When you create a new sandbox using the project SVN, the new sandbox uses the latest version of
SVN provided by the project.

When your project is under source control, you can use these project features:

• “Check Out SVN Repository” on page 19-35


• “Compare Revisions” on page 19-47
• “Commit Modified Files to Source Control” on page 19-50

You can check out from a branch, but the project SVN does not support branch merging. Use an
external tool such as TortoiseSVN to perform branch merging. You can use the project tools for

19-10
Set Up SVN Source Control

comparing and merging by configuring TortoiseSVN to generate a comparison report when you
perform a diff on model files. See “Port or Restore Model Changes in Comparison Report” on page 21-
14.

Subversion is not supported in MATLAB Online.

Set Up Project SVN for SVN Version Already Installed


If you want to use projects with an earlier SVN version you already have installed, create a new
project in a folder already under SVN source control. The project detects SVN.

For example:

1 Create the sandbox using TortoiseSVN from Windows Explorer.


2 In MATLAB, create a new project in that folder. The project detects the existing source control. If
the sandbox is version 1.6, for example, it remains a version 1.6 sandbox.

Note Before using source control, you must register model files with the tools. See “Register Model
Files with Subversion” on page 19-12.

Set Up Project SVN for SVN Version Not Yet Provided with Projects
If you need to use a later version of SVN than 1.9, you can use Command-Line SVN Integration
(compatibility mode), but you must also install a command-line SVN client.

Note Select Command-Line SVN Integration (compatibility mode) only if you need to use
a later version of SVN than 1.9. Otherwise, use SVN instead, for more features, improved
performance, and no need to install an additional command-line SVN client.

Command-line SVN integration communicates with any Subversion (SVN) client that supports the
command-line interface.

1 Install an SVN client that supports the command-line interface.

Note TortoiseSVN does not support the command-line interface unless you choose the option to
install command-line tools. Alternatively, 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, for example, both clients are SVN 1.7.

You can find Subversion clients on this Web page:

https://subversion.apache.org/packages.html
2 In a project, select Command-Line SVN Integration (compatibility mode).

With Command-Line SVN Integration (compatibility mode), if you try to rename a file in a
project and the folder name contains an @ character, an error appears because command-line SVN
treats all characters after the @ symbol as a peg revision value.

19-11
19 Project Source Control

Tip You can check for updated source control integration downloads on the projects Web page:
https://www.mathworks.com/products/simulink/projects.html

Register Model Files with Subversion


You must register model files if you use SVN, including the SVN integration provided by projects.

If you do not register your model file extension as binary, SVN might 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 SVN, register file extensions.

1 Locate your SVN config file. Look for the file in these locations:

• C:\Users\myusername\AppData\Roaming\Subversion\config or C:\Documents and


Settings\myusername\Application Data\Subversion\config on Windows
• In ~/.subversion on Linux or Mac OS X
2 If you do not find a config file, create a new one. See “Create SVN Config File” on page 19-12.
3 If you find an existing config file, you have previously installed SVN. Edit the config file. See
“Update Existing SVN Config File” on page 19-13.

Create SVN Config File

1 If you do not find an SVN config file, create a text file containing these lines:

[miscellany]
enable-auto-props = yes
[auto-props]
*.mlx = svn:mime-type=application/octet-stream
*.mat = svn:mime-type=application/octet-stream
*.fig = svn:mime-type=application/octet-stream
*.mdl = svn:mime-type=application/octet-stream
*.slx = svn:mime-type= application/octet-stream
*.mlapp = svn:mime-type= application/octet-stream
*.p = svn:mime-type=application/octet-stream
*.mdlp = svn:mime-type=application/octet-stream
*.slxp = svn:mime-type=application/octet-stream
*.sldd = svn:mime-type=application/octet-stream
*.slxc = svn:mime-type=application/octet-stream
*.mlproj = svn:mime-type=application/octet-stream
*.mldatx = svn:mime-type=application/octet-stream
*.slreqx = svn:mime-type=application/octet-stream
*.sfx = svn:mime-type=application/octet-stream
*.sltx = svn:mime-type=application/octet-stream
2 Check for other file types you use in your projects that you also need to register as binary to
avoid corruption at check-in. Check for files such as MEX-files
(.mexa64, .mexmaci64, .mexw64), .xlsx, .jpg, .pdf, .docx, etc. Add a line to the attributes
file for each file type you need. Examples:

*.mexa64 = svn:mime-type=application/octet-stream
*.mexw64 = svn:mime-type=application/octet-stream
*.mexmaci64 = svn:mime-type=application/octet-stream
*.xlsx = svn:mime-type=application/octet-stream

19-12
Set Up SVN Source Control

*.docx = svn:mime-type=application/octet-stream
*.pdf = svn:mime-type=application/octet-stream
*.jpg = svn:mime-type=application/octet-stream
*.png = svn:mime-type=application/octet-stream
3 Name the file config and save it in the appropriate location:

• C:\Users\myusername\AppData\Roaming\Subversion\config or C:\Documents and


Settings\myusername\Application Data\Subversion\config on Windows
• ~/.subversion on Linux or Mac OS X

After you create the SVN config file, SVN treats new model files as binary.

If you already have models in repositories, see “Register Models Already in Repositories” on page 19-
14.

Update Existing SVN Config File

If you find an existing config file, you have previously installed SVN. Edit the config file to register
files as binary.
1 Edit the config file in a text editor.
2 Locate the [miscellany] section, and verify the following line enables auto-props with yes:
enable-auto-props = yes

Ensure that this line is not commented (that is, that it does not start with a #). Config files can
contain example lines that are commented out. If there is a # character at the beginning of the
line, delete it.
3 Locate the [auto-props] section. Ensure that [auto-props] is not commented. If there is a #
character at the beginning, delete it.
4 Add the following lines at the end of the [auto-props] section:
*.mlx = svn:mime-type=application/octet-stream
*.mat = svn:mime-type=application/octet-stream
*.fig = svn:mime-type=application/octet-stream
*.mdl = svn:mime-type=application/octet-stream
*.slx = svn:mime-type= application/octet-stream
*.mlapp = svn:mime-type= application/octet-stream
*.p = svn:mime-type=application/octet-stream
*.mdlp = svn:mime-type=application/octet-stream
*.slxp = svn:mime-type=application/octet-stream
*.sldd = svn:mime-type=application/octet-stream
*.slxc = svn:mime-type=application/octet-stream
*.mlproj = svn:mime-type=application/octet-stream
*.mldatx = svn:mime-type=application/octet-stream
*.slreqx = svn:mime-type=application/octet-stream
*.sfx = svn:mime-type=application/octet-stream
*.sltx = svn:mime-type=application/octet-stream

These lines prevent SVN from adding annotations to MATLAB and Simulink files on conflict and
from automerging.
5 Check for other file types you use in your projects that you also need to register as binary to
avoid corruption at check-in. Check for files such as MEX-files
(.mexa64, .mexmaci64, .mexw64), .xlsx, .jpg, .pdf, .docx, etc. Add a line to the config
file for each file type you need.

19-13
19 Project Source Control

Examples:

*.mexa64 = svn:mime-type=application/octet-stream
*.mexw64 = svn:mime-type=application/octet-stream
*.mexmaci64 = svn:mime-type=application/octet-stream
*.xlsx = svn:mime-type=application/octet-stream
*.docx = svn:mime-type=application/octet-stream
*.pdf = svn:mime-type=application/octet-stream
*.jpg = svn:mime-type=application/octet-stream
*.png = svn:mime-type=application/octet-stream
6 Save the config file.

After you create or update the SVN config file, SVN treats new model files as binary.

If you already have models in repositories, register them as described next.

Register Models Already in Repositories

Caution Changing your SVN config file does not affect model files already committed to an SVN
repository. If a model is not registered as binary, use svn propset to manually register models as
binary.

To manually register a file in a repository as binary, use the following command with command-line
SVN:

svn propset svn:mime-type application/octet-stream modelfilename

If you need to install a command-line SVN client, see “Set Up Project SVN for SVN Version Not Yet
Provided with Projects” on page 19-11.

Enforce SVN Locking Model Files Before Editing


To ensure users remember to get a lock on model files before editing, you can configure SVN to make
specified file extensions read only. To locate your SVN config file, see “Register Model Files with
Subversion” on page 19-12.

After this setup, SVN sets model files to read only when you open the project, so you need to select
Source Control > Get File Lock before you can edit them. Doing so helps prevent editing of models
without getting the file lock. When the file has a lock, other users know the file is being edited, and
you can avoid merge issues.

1 To make SLX files read only, add a property to your SVN config file. Find this line in the [auto-
props] section that registers SLX files as binary:

*.slx = svn:mime-type= application/octet-stream


2 Add the needs-lock property to the end of the existing slx line, separated by a semicolon, so
the line looks like this:

*.slx = svn:mime-type=application/octet-stream;svn:needs-lock=yes

You can combine properties in any order, but multiple entries (e.g., for slx) must be on a single
line separated by semicolons.

19-14
Set Up SVN Source Control

3 Recreate the sandbox for the config to take effect.


4 You need to select Get File Lock before you can edit model files. See “Get SVN File Locks” on
page 19-42.

If you need to resolve merge issues, see “Resolve Conflicts” on page 19-62.

Share a Subversion Repository

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:

https://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.svnserve
https://svnbook.red-bean.com/en/1.7/svn-book.html#svn.serverconfig.httpd

Standard Repository Structure

Create your repository with the standard tags, trunk, and branches folders, and check out files
from trunk. The Subversion project recommends this structure. See the Web page:

https://svn.apache.org/repos/asf/subversion/trunk/doc/user/svn-best-practices.html

Note In a production environment, do not rely on remote repositories via the file system using the
file:/// protocol. The file protocol is not safe. Concurrent access might corrupt repositories.

After you create a repository with this structure, to add tags to all your project files, on the Project
tab, in the Source Control section, click Tag. See “Tag and Retrieve Versions of Project Files” on page
19-37.

Manage SVN Externals


To get files into your project from another repository or from a different part of the same repository,
use SVN externals.

1 In a project, right-click a project folder and select Source Control > Manage Externals.
2 In the Manage Externals dialog box, click Add entry. You can browse to and validate a repository
location, specify the relative reference format, specify the subfolder, choose the revision, e.g., the
HEAD node, etc.
3 After specifying the externals, click OK. The project displays the externals definition in the
Manage Externals dialog box.

Alternatively, enter or paste an svn:external definition in the Manage Externals dialog box.
The project applies an SVN version 1.6 compliant externals definition.
4 Click Set to validate and apply your changes.
5 To retrieve the external files, click Update to update the sandbox.

If two users modify the svn:external for a folder, you can get a conflict. To resolve the conflict, in
the All Files View, locate the .prej file and examine the conflict details. Open the Manage Externals
dialog box and specify the desired svn:external, mark the folder conflict resolved, and then
commit the changes.

19-15
19 Project Source Control

See Also

Related Examples
• “Check Out SVN Repository” on page 19-35
• “Get SVN File Locks” on page 19-42

More About
• “About Source Control with Projects” on page 19-2

19-16
Set Up Git Source Control

Set Up Git Source Control


You can use Git source control in MATLAB to manage your files and collaborate with others. Using
Git, you can track changes to your files and recall specific versions later. For more information, see
“Clone Git Repository” on page 19-33 and “Add a Project to Source Control” on page 19-5.

Before using Git, follow these steps to set it up for MATLAB:

• Register your binary files with Git to avoid file corruption. (Required for all systems)
• Enable support for long paths for Git on a Windows system. (Recommended for Windows Systems)
• Configure MATLAB to sign commits. (Optional)
• Configure MATLAB to use Git SSH authentication or install a Git credential helper to prevent
frequent login prompts. (Optional)
• Configure Git to use Git LFS if you are working with large files. (Optional)
• Configure external Git tools to use MATLAB for Diff and Merge. (Optional)

Starting in R2024a, MATLAB Git integration runs Git hooks with no additional setup. Supported
hooks are pre-commit, commit-msg, post-commit, prepare-commit-msg, pre-push, pre-
merge-commit, post-checkout, and post-merge.

Before R2024a, to use some Git hooks with MATLAB, install Cygwin™ and add it to the MATLAB
library path. For instructions, see “Install Cygwin (Before R2024a)” on page 19-23.

Before R2020b, a command-line Git client must be installed to use Git to merge branches in MATLAB.
For more information, see “Install Command-Line Git Client” on page 19-23.

Register Binary Files with Git


If you use third-party source control tools, you must register your MATLAB and Simulink file
extensions such as .mlx, .mat, .fig, .mlapp, .mdl, .slx, .mdlp, .slxp, .sldd, and .p as binary
formats. Also register extensions for MEX files, such as .mexa64, .mexmaci64, .mexmaca64,
and .mexw64. If you do not register the extensions, these tools can corrupt your files when you
submit them by changing end-of-line characters, expanding tokens, substituting keywords, or
attempting to automerge. Corruption can occur if you use the source control tools outside of MATLAB
or if you try submitting files from MATLAB without first registering your file formats.

Also check that other file extensions are registered as binary to avoid corruption at check-in. Check
and register file extensions such as .xlsx, .jpg, .pdf, .docx, and so on.

To register your binary file extensions with Git, add them to the .gitattributes file in your
repository. If you create a new project that uses Git source control or switch an existing project from
another source control system to Git source control, MATLAB automatically creates
a .gitattributes file and populates it with a list of common binary files to register.

If a .gitattributes file is not automatically created, you can create one that contains the list of
common binary files to register. In the MATLAB Command Window, enter:
copyfile(fullfile(matlabroot,'toolbox','shared','cmlink','git','auxiliary_files', ...
'mwgitattributes'),fullfile(pwd,'.gitattributes'))

Alternatively, create a blank .gitattributes file in your repository and populate its content.

19-17
19 Project Source Control

1 Add * text=auto to the top of the .gitattributes file.


2 For every binary file extension ext, add *.ext binary. For example, *.mlapp binary.

Enable Support for Long Paths


To enable support for long paths on a Windows system, run this command in MATLAB:

!git config --global core.longpaths true

Enable Signing Commits


To sign commits, configure Git by running these commands in MATLAB.

• Enable signing commits automatically.

!git config --global commit.gpgsign true


• Set your signing key and the key format. Supported key formats are X.509 and OpenPGP
(default). In this example, the key ID is 3AB5C344325645B2 and the key format is X.509.

!git config --global user.signingkey 3AB5C344325645B2


!git config --global gpg.format x509
• Specify the utility used to sign commits. In this example, the command configures Git to use
smimesign as a signing utility.

!git config --global gpg.x509.program smimesign

To use OpenPGP instead, run !git config --global gpg.openpgp.program gpg.

Configure MATLAB to Use Git SSH Authentication

To prevent frequent login prompts when you interact with your remote repository using HTTPS, add a
new public key and clone the repository using SSH instead. This table provides instructions on how to
configure MATLAB to use SSH authentication based on your operating system.

19-18
Set Up Git Source Control

Operating Instructions
System
Windows 1 Install a command-line Git client and make it available system-wide. To check if
Git is installed, enter the command !git in the MATLAB Command Window. If
the command does not return anything, you need to install command-line Git. For
more information, see “Install Command-Line Git Client” on page 19-23.
2 Close all MATLAB sessions.
3 Generate an SSH key using the ssh-keygen command. For example, at a
Windows command prompt, enter this command:

ssh-keygen -t ed25519 -C "[email protected]"

ssh-keygen prompts you to confirm where to save the key and asks for a
passphrase. If you do not want to type a password when you use the key, leave
the passphrase empty.

If you already have keys in the specified folder, ssh-keygen asks if you want to
override them.

Before R2021a, specify the -m PEM option to generate an SSH key in the RSA
format. Otherwise, ssh-keygen creates the SSH key using the default OpenSSH
format, which is not supported in MATLAB versions before R2021a. For example,
at a Windows command prompt, enter this command:

ssh-keygen -m PEM

If you generate an SSH key without specifying the -m PEM option, you can
convert your key to the supported RSA format using this command, where
~/.ssh/id_rsa is the name of the SSH key file.

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa


4 Place your keys in the USERPROFILE/.ssh or HOME/.ssh folder. To verify
which USERPROFILE folder MATLAB is working with, in the MATLAB Command
Window, enter:

getenv('USERPROFILE')

Before R2021a, if you created the SSH key using the -m PEM option, you can
skip step 5.
5 To make sure that MATLAB detects the SSH keys, in the MATLAB Command
Window, enter:

git = settings().matlab.sourcecontrol.git;
git.PrivateKeyFile.PersonalValue = "C:\Users\username\.ssh\id_ed25519";
git.PublicKeyFile.PersonalValue = "C:\Users\username\.ssh\id_ed25519.pub";

If you entered a passphrase when generating the SSH key, configure MATLAB to
use the passphrase and receive a prompt only once per session. To do so, use
Pageant or, in the MATLAB Command Window, enter:

git.KeyHasPassphrase.PersonalValue = true;

19-19
19 Project Source Control

Operating Instructions
System
To use multiple keys, use Pageant as the SSH agent. If Pageant is running,
MATLAB looks for keys in Pageant before using the key you define in the
settings.
6 Configure your GitHub or GitLab® account to use the SSH keys. To do so, go to
the .ssh folder and copy the contents of the .pub file. Then, go to your account
settings, and in the SSH keys section, paste the contents of the .pub file into
the Add SSH key field.

19-20
Set Up Git Source Control

Operating Instructions
System
Linux and 1 Close all MATLAB sessions.
macOS 2 Generate an SSH key using the ssh-keygen command. For example, in a
Terminal window, enter this command:

ssh-keygen -t ed25519 -C "[email protected]"

ssh-keygen prompts you to confirm where to save the key and asks for a
passphrase. If you do not want to type a password when you use the key, leave
the passphrase empty.

If you already have keys in the specified folder, ssh-keygen asks if you want to
override them.

Before R2021a, specify the -m PEM option to generate an SSH key in the RSA
format. Otherwise, ssh-keygen creates the SSH key using the default OpenSSH
format, which is not supported in MATLAB versions before R2021a. For example,
in a Terminal window, enter this command:

ssh-keygen -m PEM

If you generate an SSH key without specifying the -m PEM option, you can
convert your key to the supported RSA format using this command, where
~/.ssh/id_rsa is the name of the SSH key file.

ssh-keygen -p -m PEM -f ~/.ssh/id_rsa


3 Place your keys in the HOME/.ssh folder. To verify which HOME folder MATLAB is
working with, in the MATLAB Command Window, enter:

getenv('HOME')

Before R2021a, if you created the SSH key using the -m PEM option, you can
skip step 4.
4 To make sure that MATLAB detects the SSH keys, in the MATLAB Command
Window, enter:

git = settings().matlab.sourcecontrol.git;
git.PrivateKeyFile.PersonalValue = "~/.ssh/id_ed25519";
git.PublicKeyFile.PersonalValue = "~/.ssh/id_ed25519.pub";

If you entered a passphrase when generating the SSH key, configure MATLAB to
use the passphrase and receive a prompt only once per session. To do so, use an
SSH agent or, in the MATLAB Command Window, enter:

git.KeyHasPassphrase.PersonalValue = true;

To use multiple keys, use an SSH agent. If an SSH agent is running, MATLAB
looks for keys in the agent before using the key you define in the settings.
5 Configure your GitHub or GitLab account to use the SSH keys. To do so, go to
the .ssh folder and copy the contents of the .pub file. Then, go to your account
settings, and in the SSH keys section, paste the contents of the .pub file into
the Add SSH key field.

19-21
19 Project Source Control

Install Git Credential Helper

To configure MATLAB to remember user names and passwords when using Git, install a credential
helper. The recommended credential helper for all platforms is Git Credential Manager Core.

For example, to install Git Credential Manager Core on a Windows system, download and run the Git
for Windows installer using the instructions described in “Install Command-Line Git Client” on page
19-23. In the Choose a credential helper section of the installer, select Git Credential Manager
Core as the credential helper.

To delete saved login information for Git repositories, follow instructions based on your operating
system.

Operating System Instructions


Windows To reset the Git credentials for your repository, in the Credential
Manager, in the Windows Credentials tab, delete the entries
under Generic Credentials.
Linux and macOS To reset the Git credentials for your repository, enter:

echo "url=https://github.com/myrepo.git" | git credential reject

Disable Compression for Simulink Models (Before R2023b)


You can reduce your Git repository size by saving Simulink models without compression. Turning off
compression results in larger SLX files on disk but reduces repository size.

To use this setting with new SLX files, create your models using a model template with SLX
Compression set to none. For existing SLX files, set the compression and then save the model. For
more information, see “Set SLX Compression Level” on page 4-88.

Note Starting in R2023b, by default, Simulink applies no compression during the save operation.

Configure Git to Use Git LFS


If you are working with large files, configure Git to use Git Large File Storage (LFS) by installing
command-line Git and setting up LFS.

For example, to use Git LFS on a Windows system, download and run the Git for Windows installer
using the instructions described in “Install Command-Line Git Client” on page 19-23. In the Select
Components section of the Git for Windows installer, select the Git LFS (Large File Support) and
Associate .sh files to be run with Bash options.

MATLAB does not support Git LFS locking. In addition, MATLAB does not support LFS commands
such as git lfs track. Use !git lfs track instead.

Configure External Git Tools to use MATLAB for Diff and Merge
You can configure Git to use the MATLAB Comparison Tool for diff and merge. The MATLAB
Comparison Tool provides tools for merging MathWorks files such as live scripts, MAT, SLX, or MDL

19-22
Set Up Git Source Control

files. You can use the automerge tool with Git to automatically merge branches that contain changes
in different subsystems in the same SLX file.

For more information about how to configure External Git tools to use the MATLAB Comparison Tool,
see “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67.

Additional Setup
Install Command-Line Git Client

To use Git LFS or a credential helper, you must install a command-line Git client and make it available
system-wide. Before R2020b, a command-line Git client must be installed to use Git to merge
branches in MATLAB.

To check if Git is installed, enter the command !git in the MATLAB Command Window. If the
command does not return anything, you need to install command-line Git. This table provides
instructions on how to install command-line Git based on your operating system.

Operating System Instructions


Windows 1 Download and run the installer from https://
gitforwindows.org/.
2 In the Adjusting your PATH environment section, choose
the install option Git from the command line and also
from 3rd-party software. This option adds Git to your PATH
variable and makes it available system-wide so that MATLAB
can communicate with Git.
3 In the section for configuring the line-ending conversions,
choose the Checkout Windows-style, commit Unix-style
line endings option. The line-ending format is not enforceable
between machines and users, but you can support consistent
line endings for text files in the .gitattributes file of each
repository.
4 Restart your system for the changes to take effect.
Linux Git is available for most distributions. Install Git for your
distribution. For example, on Debian®, install Git by entering:

sudo apt-get install git


macOS On Mavericks (10.9) or above, run Git from a Terminal window. If
you do not have Git installed already, it will prompt you to install
Xcode Command Line Tools. For more information, see https://git-
scm.com/doc.

Install Cygwin (Before R2024a)

Before 2024a, to use some Git hooks with MATLAB, you must install Cygwin.

Follow these steps to install Cygwin on a Windows system and add it to the MATLAB library path and
the system path.

1 Download and run the installer from https://www.cygwin.com/.

19-23
19 Project Source Control

2 In MATLAB, open librarypath.txt.

edit(fullfile(matlabroot,"toolbox","local","librarypath.txt"))
3 Add the Cygwin bin folder location to the end of librarypath.txt, for example,
C:\cygwin64\bin.

##
## FILE: librarypath.txt
##
## Entries:
## o path_to_jnifile
## o [alpha,glnx86,sol2,unix,win32,mac]=path_to_jnifile
## o $matlabroot/path_to_jnifile
## o $jre_home/path_to_jnifile
##
$matlabroot/bin/$arch
$matlabroot/sys/jxbrowser/$arch/lib
C:\cygwin64\bin

If you do not have permission to edit the librarypath.txt file, see “Locate Native Method
Libraries”.
4 Add the Cygwin bin folder to the system path. For more information, see https://
www.mathworks.com/matlabcentral/answers/94933-how-do-i-edit-my-system-path-in-windows.
5 Restart MATLAB.

See Also
Functions
gitclone | gitrepo | gitinit

Related Examples
• “Clone Git Repository” on page 19-33
• “Add a Project to Source Control” on page 19-5
• “Branch and Merge Files with Git” on page 19-58
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

19-24
Add Git Submodules

Add Git Submodules


To reuse code from another repository, you can specify Git submodules to include in your project.

To clone an external Git repository as a submodule:

1 On the Project tab, in the Source Control section, click Submodules.


2 In the Submodules dialog box, click Add.
3 In the Add Submodule dialog box, in the Remote box, specify a repository location. Optionally,
click Validate.
4 In the Path box, specify a location for the submodule in your project and click OK. The
Submodules dialog box displays the status and details of the submodule.
5 Check the status message, and click Close to return to your project.

Tip You can use Git submodules to populate a referenced project. For more information, see
“Organize Projects into Components Using References and Git Submodules” and watch How to
Organize Large Projects into Components (3 min, 32 sec).

Update Submodules
After using Pull on the top-level project, check submodules are up to date by clicking Submodules
and then click Update. If any submodule definition have changed, then the update ensures that the
submodule folder contains the correct files. Update applies to all child submodules in the submodule
hierarchy.

Use Fetch and Merge with Submodules


When you want to manage a submodule, open the Submodules dialog box.

1 To get the latest version of a submodule, in the Submodules dialog box, click Fetch.
2 After fetching, you must merge. Check the Status message in the Submodules dialog box for
information about your current branch relative to the remote tracking branch in the repository.
When you see the message Behind, you need to merge in changes from the repository to your
local branch.
3 Click Branches and merge in the origin changes to your local branch using the Branches dialog
box. See “Pull, Fetch, and Merge” on page 19-55.

Use Push to Send Changes to the Submodule Repository


If you make changes in your submodule and want to send changes back to the repository:

1 Perform a local commit in the parent project.


2 Open the Submodules dialog box and click Push.

If you want other project users to obtain your changes in the submodule when they clone the parent
project, make sure the index and head match.

19-25
19 Project Source Control

1 In the Submodules dialog box, check the index and head values. The index points to the head
commit at the time you first cloned the submodule, or when you last committed the parent
project repository. If the index and head do not match, you must update the index.
2 To update the index, commit your changes in the parent project, and then click Push in the
Submodules dialog box. This action makes the index and head the same.

See Also
Functions
gitclone | gitrepo | gitinit

Related Examples
• How to Organize Large Projects into Components (3 min, 32 sec)
• “Branch and Merge Files with Git” on page 19-58

19-26
Automatically Merge Models

Automatically Merge Models


You can enable MATLAB Git integration to automatically merge branches in your Git repository using
the mlAutoMerge Git plugin. The plugin can automatically merge branches that contain changes in
different subsystems, Stateflow charts, and configuration sets in the same SLX file.

Tip The mlAutoMerge Git plugin automatically merges your model files and resolves conflicts when
you are working in different subsystems.

If you are not working in different subsystems, you must merge and resolve conflicts manually. For
more information, see “Resolve Conflicts in Models Using Three-Way Merge” on page 21-24.

The mlAutoMerge Git plugin automatically merges changes in a child subsystem of a modified
subsystem. If the number of ports remains unchanged, child subsystems are independent of parent
subsystems. The plugin does not report a conflict for nonfunctional changes such as window
positions, open Editor tabs, and other graphical details.

To enable automerge for models in your Git repository:

1 Run this command in MATLAB.

comparisons.ExternalSCMLink.setupGitConfig();

This command automatically populates the global .gitconfig file. An example follows.
[difftool "mlDiff"]
cmd = \"C:/Program Files/MATLAB/R2022b/bin/win64/mlDiff.exe\" $LOCAL $REMOTE
[mergetool "mlMerge"]
cmd = \"C:/Program Files/MATLAB/R2022b/bin/win64/mlMerge.exe\" $BASE $LOCAL $REMOTE $MERGED
[merge "mlAutoMerge"]
driver = \"C:/Program Files/MATLAB/R2022b/bin/win64/mlAutoMerge.bat\" %O %A %B %A

2 Configure your Git repository to use the mlAutoMerge executable file for resolving conflicted
SLX and MDL files on branch merges. Open the .gitattributes file in your repository and
add:

*.slx binary merge=mlAutoMerge


*.mdl binary merge=mlAutoMerge

19-27
19 Project Source Control

Now, when you merge branches that contain changes in non-overlapping parts of the same SLX file,
the mlAutoMerge handles the merge automatically.

You can also enable automerge for requirement files and links. Open the .gitattributes file in
your repository and add:

*.slreqx binary merge=mlAutoMerge


*.slmx binary merge=mlAutoMerge

For more details, see “Configure Git Environment to Merge Requirement and Linkset Files”
(Requirements Toolbox).

You can also customize external source control tools to use the MATLAB Comparison Tools and
automerge functionality. For more details, see “Customize External Source Control to Use MATLAB
for Diff and Merge” on page 19-67.

See Also

Related Examples
• “Port or Restore Model Changes in Comparison Report” on page 21-14
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

19-28
Create New GitHub Repository

Create New GitHub Repository


Creating a GitHub repository adds Git source control to your new or existing project. The GitHub
repository you create becomes the project remote repository. To create a GitHub repository, you must
have a GitHub account.

To create a blank project and a GitHub remote repository:

1 On the Home tab, click New > Project > From Git.
2 Select New > GitHub Repository. In the GitHub dialog box, enter your User name and
Personal access token. Fill the Repository name and Description fields and click Create.

MATLAB creates a new public GitHub repository and populates the Repository path field with
information in the https://github.com/myusername/mynewrepository format.
3 In the Sandbox field, specify the location for your sandbox. The selected folder must be empty.
Click Retrieve to create the sandbox.

To confirm the project name and creation, click OK.

After creating the GitHub repository and sandbox, add your files to the sandbox. Commit the first
version of your files to your local repository, then push all modifications to your remote GitHub
repository.

Tip If you want to create a remote GitHub repository for an existing project, share your project to
GitHub instead.

With your project loaded, on the Project tab, select Share > GitHub. For detailed instructions, see
“Share Project on GitHub” on page 17-34.

19-29
19 Project Source Control

Disable Source Control


Disabling source control is useful when you are preparing a project to create a template from it, and
you want to avoid accidentally committing unwanted changes.

1 On the Project tab, in the Source Control section, click the Details button for your source
control. For example, SVN Details or Git Details.
2 Change the selection from the current source control to No source control integration.
3 Click Reload.

Note Source control tools create files in the project folders (for example, SVN creates an .svn
folder), so you can put the project back under the same source control only by selecting your
previous source control from the list.

See Also

Related Examples
• “Change Source Control” on page 19-31
• “Create a Template from a Project Under Version Control” on page 16-37
• “Add a Project to Source Control” on page 19-5

19-30
Change Source Control

Change Source Control


Changing source control is useful when you want to create a new local repository for testing and
debugging.

1 Prepare your project by checking for any updates from the existing source control tool repository
and committing any local changes.
2 Save your project as an archive without any source control information.

On the Project tab, click Share > Archive. Click Save As and specify a file path and name in
the File name field.

By default, the archive is a .mlproj file. You can choose to archive your project as a .zip file.
Click Save to create the project archive.
3 On the Project tab, click New, and then in the start page, click Archive to create a new project
from the archived project.
4 On the Project tab, in the Source Control section, click Use Source Control.
5 Click Add Project to Source Control and then select a new source control. For details, see
“Add a Project to Source Control” on page 19-5.

Tip To avoid accidentally committing changes to the previous source control, delete the original
sandbox.

See Also

Related Examples
• “Disable Source Control” on page 19-30
• “Add a Project to Source Control” on page 19-5

19-31
19 Project Source Control

Write a Source Control Integration with the SDK

Tip You can check for updated source control integration downloads on the projects Web page:
https://www.mathworks.com/products/simulink/projects.html

The file exchange provides a Software Development Kit (SDK) that you can use to integrate projects
with third-party source control tools. See https://www.mathworks.com/matlabcentral/fileexchange/
61483-source-control-integration-software-development-kit.

The SDK provides instructions for writing an integration to a source control tool that has a published
API you can call from Java®.

You must create a .jar file that implements a collection of Java interfaces and a Java Manifest file,
that defines a set of required properties.

The SDK provides example source code, Javadoc, and files for validating, building, and testing your
source control integration. Build and test your own interfaces using the example as a guide. Then you
can use your source control integration with projects. Download the SDK and follow the instructions.

After you write a source control integration, see “Add a Project to Source Control” on page 19-5.

See Also

More About
• “About Source Control with Projects” on page 19-2

19-32
Clone Git Repository

Clone Git Repository


Create a new local copy of a project by retrieving files from Git source control.

1 On the Home tab, click New > Project > From Git. The New Project From Source Control
dialog box opens.

Alternatively, on the Simulink start page, click the Project from Git template.
2 Enter your HTTPS repository path into the Repository path field.
3 In the Sandbox field, select the working folder where you want to put the retrieved files for your
new project.
4 Click Retrieve.

If an authentication dialog box for your repository appears, enter the login information for your
Git repository account -- for instance, your GitHub user name and personal access token.

If your repository already contains a project, then the project is ready when the tool finishes
retrieving files to your selected sandbox folder.

If your sandbox does not yet contain a project, then a dialog box asks whether you want to create
a project in the folder. To create a project, specify a project name and click OK. The Welcome
screen appears to help you set up your new project. For more information about setting up a
project, see “Create a New Project from a Folder” on page 16-18.

You can now add, delete, and modify your project files. For details on how to commit and push the
modified project files, see “Commit Modified Files to Source Control” on page 19-50.

Tip Alternatively, to prevent frequent login prompts when you interact with your remote repository,
you can clone a remote repository using SSH instead of HTTPS or install a credential helper. To avoid
problems connecting using SSH, set the HOME environment variable and use it to store your SSH
keys. For more information, see “Configure MATLAB to Use Git SSH Authentication” on page 19-18
and “Install Git Credential Helper” on page 19-22.

See Also
Functions
gitrepo | gitclone | gitinit | add | rm | commit

Related Examples
• “Set Up Git Source Control” on page 19-17
• “Work with Project Files” on page 17-7
• “Refresh Status of Project Files” on page 19-38
• “Check for Modifications” on page 19-39
• “Update Revisions of Project Files” on page 19-40
• “View Modified Files” on page 19-44
• “Commit Modified Files to Source Control” on page 19-50

19-33
19 Project Source Control

More About
• “About Source Control with Projects” on page 19-2

19-34
Check Out SVN Repository

Check Out SVN Repository


Create a new local copy of a project by retrieving files from SVN source control.

1 On the MATLAB Home tab, select New > Project > From SVN.

Alternatively, on the Simulink start page, click the Project from SVN template.
2 If you know your repository location, enter it into the Repository path field and proceed to step
3.

Otherwise, to browse for and validate the repository path from which to retrieve files, click
Change.

a In the Specify SVN Repository URL dialog box, enter a URL using the list of recent

repositories or the Repository button .

Caution Use file:// URLs only for single-user repositories. For more information, see
“Share a Subversion Repository” on page 19-15.
b Click Validate to check the repository path.

If an authentication dialog box for your repository appears, enter the login information to
continue.
c If the path is invalid, check the URL against your source control repository browser.

If necessary, select a deeper folder in the repository tree. If your repository contains tagged
versions of files, then you might want to check out from trunk or from a branch folder under
tags. For more information, see “Tag and Retrieve Versions of Project Files” on page 19-
37. You can check out from a branch, but the built-in SVN integration does not support
branch merging. Use an external tool such as TortoiseSVN to perform branch merging.
d When you have finished specifying the URL path you want to retrieve, click OK.
3 In the New Project From Source Control dialog box, in the Sandbox field, select the working
folder where you want to put the retrieved files for your new project.
4 Click Retrieve.

If an authentication dialog box for your repository appears, enter the login information to
continue.

Caution Use local sandbox folders. Using a network folder with SVN slows source control
operations.

If your repository already contains a project, then the project is ready when the tool finishes
retrieving files to your selected sandbox folder.

If your sandbox does not yet contain a project, then a dialog box asks whether you want to create
a project in the folder. To create a project, specify a project name and click OK. The Welcome
screen appears to help you set up your new project. For more information about setting up a
project, see “Create a New Project from a Folder” on page 16-18.

19-35
19 Project Source Control

Note To update an existing project sandbox from source control, see “Update Revisions of Project
Files” on page 19-40.

See Also

Related Examples
• “Set Up SVN Source Control” on page 19-10
• “Get SVN File Locks” on page 19-42
• “Work with Project Files” on page 17-7
• “Tag and Retrieve Versions of Project Files” on page 19-37
• “Refresh Status of Project Files” on page 19-38
• “Check for Modifications” on page 19-39
• “Update Revisions of Project Files” on page 19-40
• “View Modified Files” on page 19-44
• “Commit Modified Files to Source Control” on page 19-50

More About
• “About Source Control with Projects” on page 19-2

19-36
Tag and Retrieve Versions of Project Files

Tag and Retrieve Versions of Project Files


With SVN, you can use tags to identify specific revisions of all project files. 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 “Standard Repository Structure” on
page 19-15.

1 On the Project tab, in the Source Control section, click Tag.


2 Specify the tag text and click OK. The tag is added to every project file.

Errors appear if you do not have a tags folder in your repository.

Note You can retrieve a tagged version of your project files from source control, but you cannot tag
them again with a new tag. You must check out from trunk to create new tags.

To retrieve the tagged version of your project files from source control:

1 On the Project tab, click New, and then in the start page, click Source Control.
2 Click Change to select the Repository path that you want to retrieve files from.

The Specify SVN Repository URL dialog box opens.

a
Select a recent repository from the Repository list, or click the Repository button to
browse for the repository location.
b Click Validate to show the repository browser.
c Expand the tags folder in the repository tree, and select the tag version you want.
d Click OK to continue and return to the new project dialog box.
3 Select the local folder to receive the tagged files. You must use an empty project folder. (If you
try to retrieve tagged files into an existing project folder, an error appears.)
4 Click Retrieve.

Alternatively, you can use labels to apply any metadata to files and manage configurations. You can
group and sort by labels, and create batch jobs to export files by label. See “Add Labels to Files” on
page 17-17.

With Git, you can switch branches. See “Branch and Merge Files with Git” on page 19-58.

See Also

Related Examples
• “Standard Repository Structure” on page 19-15
• “Add Labels to Files” on page 17-17
• “Branch and Merge Files with Git” on page 19-58

19-37
19 Project Source Control

Refresh Status of Project Files


To check for locally modified project files, on the Project tab, in the Source Control section, click
Refresh.

Refresh queries the local sandbox state and checks for changes made with another tool outside of
MATLAB.

Note For SVN, Refresh does not contact the repository. To check the repository for later revisions,
use Check for Modifications instead. To get the latest revisions, use Update instead. See “Check
for Modifications” on page 19-39 and “Update Revisions of Project Files” on page 19-40.

The buttons in the Source Control section of the Project tab apply to the whole project.

Refresh refreshes the view of the source control status for all files under projectroot. Clicking
Refresh updates the information shown in the Revision column and the source control status
column (for example, SVN, or Git columns). Hover over the icon to see the tooltip showing the source
control status of a file, e.g., Modified.

See Also

Related Examples
• “Check for Modifications” on page 19-39
• “Update Revisions of Project Files” on page 19-40
• “Revert Changes” on page 19-52

19-38
Check for Modifications

Check for Modifications


To check the status of individual files for modifications, right-click files in the project and select
Source Control > Check for Modifications. Use this to find out if the repository version has moved
ahead.

With SVN, this option contacts the repository to check for external modifications. The project
compares the revision numbers of the local file and the repository version. If the revision number in
the repository is larger than that in the local sandbox folder, then the project displays (not latest)
next to the revision number of the local file.

If your local file is not the latest version, get the latest revisions from the repository by clicking
Update. See “Update Revisions of Project Files” on page 19-40. You might need to resolve conflicts
after updating. See “Resolve Conflicts” on page 19-62 and “Compare Revisions” on page 19-47.

To check for locally modified files, use Refresh instead. See “Refresh Status of Project Files” on page
19-38.

See Also

Related Examples
• “Refresh Status of Project Files” on page 19-38
• “Update Revisions of Project Files” on page 19-40
• “Compare Revisions” on page 19-47
• “Revert Changes” on page 19-52

19-39
19 Project Source Control

Update Revisions of Project Files


In this section...
“Update Revisions with SVN” on page 19-40
“Update Revisions with Git” on page 19-40
“Update Selected Files” on page 19-41

Update Revisions with SVN


In a project, to get the latest revisions of all project files from the source control repository, click
Update in the source control section of the project tab.

Use Update to get other people’s changes from the repository and find out about any conflicts. If you
want to back out local changes, use Revert Project instead. See “Discard Local Changes” on page
19-52.

After you update, the project displays a dialog box listing all the files that have changed on disk. You
can control this behavior using the project preference Show changes on source control update.

When your project uses SVN source control, Update calls svn update to bring changes from the
repository into your working copy. If there are other people’s changes in your modified files, SVN
adds conflict markers to the file. SVN preserves your modifications.

Caution Ensure you have registered SLX files as binary with SVN before using Update. If you do
not, SVN conflict markers can corrupt your SLX file. The project warns you about this when you first
click Update to ensure you protect your model files. See “Register Model Files with Subversion” on
page 19-12.

You must resolve any conflicts before you can commit. See “Resolve Conflicts” on page 19-62.

Update Revisions with Git


If you are using Git source control, click Pull in the source control pane.

Caution Ensure you have registered SLX files as binary with Git before using Pull. If you do not,
conflict markers can corrupt your SLX file. See “Set Up Git Source Control” on page 19-17.

Pull fetches the latest changes and merges them into your current branch. If you are not sure what is
going to come in from the repository, use fetch to examine the changes first and then merge the
changes manually.

Pull might fail if you have conflicts. With a complicated change you might want to create a branch
from the origin, make some compatibility changes, then merge that branch into the main tracking
branch. For next steps, see “Pull, Push, and Fetch Files with Git” on page 19-54.

19-40
Update Revisions of Project Files

Update Selected Files


To update selected files, right-click and select the Update command for the source control system
you are using. For example, if you are using SVN, select Source Control > Update from SVN to get
fresh local copies of the selected files from the repository.

See Also

Related Examples
• “Register Model Files with Source Control Tools” on page 19-9
• “Resolve Conflicts” on page 19-62
• “Discard Local Changes” on page 19-52

19-41
19 Project Source Control

Get SVN File Locks


To ensure users remember to get a lock on model files before editing, you can configure SVN to make
model files read only. Follow the steps in “Enforce SVN Locking Model Files Before Editing” on page
19-14. After you configure SVN to make files with certain extensions read only, then users must get a
lock on these read-only files before editing.

1 In a project, in any Files view, select the files you want to check out.
2 Right-click the selected files and select Source Control > Get File Lock.

Get File Lock is for SVN. This option does not modify the file in your local sandbox. Git does not
have locks.

A lock symbol appears in the SVN source control column. Other users cannot see the lock symbol
in their sandboxes, but they cannot get a file lock or check in a change when you have the lock.
To view or break locks, click Locks on the Project tab.

Note To get a fresh local copy of the file from the repository, select Update from SVN.

In the Simulink Editor, if an open model belongs to a project under SVN, you can get a lock by
selecting File > Project > Get File Lock.

If you see an SVN message reporting a working copy locked error, remove stale locks by clicking
SVN Cleanup in the Source Control section on the Project tab. SVN uses working copy locks
internally and they are not the file locks you control using Get File Lock.

Note Starting in R2020a Update 5, SVN cleanup only removes stale locks and unfinished
transactions. It does not remove unversioned or ignored files.

You can manually remove unversioned and ignored files.

1 In the Files view, in the All tab, click the SVN header to sort files by their SVN status.
2 Select the Not Under Source Control files.
3 Right-click and select Delete.

Manage SVN Repository Locks


To manage global SVN locks for a repository, on the Project tab, in the Source Control section, click
Locks.

In the SVN Repository Locks dialog box, you can:

• View which users have locks on files.


• Right-click to break locks.
• Group locks by user or file.

19-42
Get SVN File Locks

See Also

Related Examples
• “Work with Project Files” on page 17-7
• “Enforce SVN Locking Model Files Before Editing” on page 19-14
• “View Modified Files” on page 19-44
• “Commit Modified Files to Source Control” on page 19-50

More About
• “About Source Control with Projects” on page 19-2

19-43
19 Project Source Control

View Modified Files


To review, analyze, label, and commit modified project files, use the Modified (number of files)
view. The modified files view is visible only if you are using source control with your project.

If you need to update the modified files list, click Refresh in the source control section.

Lists of modified files are sometimes called changesets. You can perform the same operations in the
Modified files view as you can in other file views. To view changes, see “Compare Revisions” on page
19-47.

Tip In the Modified files view, it can be useful to switch to the List layout.

You can identify modified or conflicted folder contents using the source control summary status. In
the Files views, folders display rolled-up source control status to help you locate changes in files,
particularly conflicted files. Pause on the source control status (for example, the SVN or Git column)
for a folder to see how many files inside are modified, conflicted, added, or deleted.

Project Definition Files


The files in the resources/project folder are project definition files generated when you first
create or make changes to your project. The project definition files enable you to add project
metadata to files without checking them out. Some examples of metadata you can change this way

19-44
View Modified Files

are shortcuts, labels, and project descriptions. Project definition files also specify the files added to
your project. These files are not part of the project.

Any changes you make to your project generate changes in the resources/project folder. These
files store the definition of your project in XML files whose format is subject to change.

You do not 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 19-62.

Starting in R2020b, the default project definition file type is Use multiple project files (fixed-path
length). To change the project definition file management from the type selected when the project
was created, use matlab.project.convertDefinitionFiles.
matlab.project.convertDefinitionFiles preserves the source control history of your project.

Warning To avoid merge issues, do not convert the definition file type more than once for a project.

For releases before R2020b, if you want to change the project definition file management from the
type selected when the project was created:

1 On the Home tab, in the Environment section, click Preferences. Select MATLAB > Project
and in the New Projects section, select one of the options under Project definition files:

• Use multiple project files - Helps to avoid file conflicts when performing merge on shared
projects
• Use multiple project files (fixed-path length) - Is better if you need to work with long
paths
• Use a single project file (not recommended for source control) - Is faster but is likely to
cause merge issues when two users submit changes in the same project to a source control
tool
2 Create a project archive file (.mlproj). For more information, see “Archive Projects” on page 17-
35 or export.
3 Create a new project from the archived project. For more information, see “Create a New Project
from an Archived Project” on page 16-24.

You can use the project preferences to change the project definition folder for new projects. Instead
of resources/project, you can choose the .SimulinkProject or _SimulinkProject folder
names adopted for releases before R2019a.

To stop managing your folder with a project and delete the resources/project folder, see
matlab.project.deleteProject.

See Also

Related Examples
• “Compare Revisions” on page 19-47
• “Run Project Checks” on page 19-49
• “Refresh Status of Project Files” on page 19-38

19-45
19 Project Source Control

• “Check for Modifications” on page 19-39


• “Resolve Conflicts” on page 19-62
• “Discard Local Changes” on page 19-52
• “Commit Modified Files to Source Control” on page 19-50

More About
• “About Source Control with Projects” on page 19-2

19-46
Compare Revisions

Compare Revisions
To review changes in modified files in a project, select the Modified (number of files) tab.

If you need to update the modified files list, click Refresh in the source control section of the Project
tab.

To review changes in modified files, right-click selected files in any view in a project and:

• Select Compare > Compare to Ancestor to run a comparison with the last checked-out version
in the sandbox (SVN) or against the local repository (Git). The Comparison Tool displays a report.
• To compare other revisions of a file, select Compare > Compare to Revision. In the Compare to
Revisions dialog box, you can view information about who previously committed the file, when
they committed it, and the log messages. To view a comparison report, select the revisions you
want to compare. You can:

• Select a revision and click Compare to Local.


• Select two revisions and click Compare Selected.
• With SVN, select a revision and you can browse the lower list of files in the change set. Right-
click a file in the list to view changes or save revisions..
• To browse the revision history of a file, select Source Control > Show Revisions. In the File
Revisions dialog box, view information about who previously committed the file, when they
committed it, and the log messages. With SVN, select a revision and you can browse the lower list
of files in the change set. Right-click a file in the list to view changes or save revisions.

19-47
19 Project Source Control

• To browse and compare files within committed SVN change sets, on the Project tab, in the Source
Control section, select Show Log. In the File Revisions dialog box, select a revision to view a list
of modified files. Right-click files in the lower list to view changes or save revisions.

Note In the Simulink Editor, if an open model, library, or chart belongs to a project under source
control, you can view changes. To do so, on the Simulation tab, select Project > Compare to
Ancestor or Compare to Revision.

When you compare to a revision or ancestor, the MATLAB Comparison Tool opens a report comparing
the modified version of the file in your sandbox with the selected revision or against its ancestor
stored in the version control tool.

Comparison type depends on the file you select. If you select a Simulink model, this command runs a
Simulink model comparison.

When reviewing changes, you can merge Simulink models from the Comparison Tool report. See
“Merge Text Files” on page 19-63 and “Merge Models” on page 19-64.

To examine the dependencies of modified files, see “Perform an Impact Analysis” on page 18-15.

See Also

Related Examples
• “Resolve Conflicts” on page 19-62
• “Run Project Checks” on page 19-49
• “Perform an Impact Analysis” on page 18-15
• “Commit Modified Files to Source Control” on page 19-50
• “Revert Changes” on page 19-52
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

More About
• “About Source Control with Projects” on page 19-2

19-48
Run Project Checks

Run Project Checks


To run the project integrity checks, on the Project tab, click the down arrow to expand the Tools
gallery. Under Project Checks, click Check Project. The checks look for missing files, files to add to
source control or retrieve from source control, and other issues.

For details on problems the checks can fix, see “Work with Derived Files in Projects” on page 19-66
and “Check Dependency Results and Resolve Problems” on page 18-21.

• Click Check Project 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.
• If you want to check for required files, click Dependency Analyzer to analyze the dependencies
of the modified files.

Use the dependency tools to analyze the structure of your project. See “Perform an Impact
Analysis” on page 18-15.

Note The files in resources/project are project definition files generated by your changes. See
“Project Definition Files” on page 19-44.

See Also

Related Examples
• “Find Models and Other Project Files With Unsaved Changes” on page 17-8
• “Commit Modified Files to Source Control” on page 19-50
• “Work with Derived Files in Projects” on page 19-66
• “Check Dependency Results and Resolve Problems” on page 18-21

More About
• “About Source Control with Projects” on page 19-2
• “Project Definition Files” on page 19-44

19-49
19 Project Source Control

Commit Modified Files to Source Control


Before you commit modified files, review changes and consider precommit actions. See “Compare
Revisions” on page 19-47 and “Run Project Checks” on page 19-49.

1 In a project, select the Modified (number of files) view.

If you need to update the modified files list, click Refresh in the source control section of the
Project tab.
2 To check in all files in the modified files list, on the Project tab, in the Source Control section,
click Commit.

If you are using SVN source control, this commits changes to your repository.

If you are using Git source control, this commits to your local repository. To commit to the remote
repository, see “Pull and Push” on page 19-54.
3 Enter comments in the dialog box if you want, and click Submit.
4 A message appears if you cannot commit because the repository has moved ahead. Before you
can commit the file, you must update its revision up to the current HEAD revision. If you are
using SVN source control, click Update. If you are using Git source control, click Pull. Resolve
any conflicts before you commit.

Note You can commit individual files using the context menu, by selecting Source Control >
Commit. However if you commit individual files, you risk not committing the related project

19-50
Commit Modified Files to Source Control

definition files that keep track of your files. Instead, use the Modified files view to see all changes,
and on the Project tab, click Commit to commit all related changes.

See Also

Related Examples
• “Refresh Status of Project Files” on page 19-38
• “View Modified Files” on page 19-44
• “Run Project Checks” on page 19-49
• “Update Revisions of Project Files” on page 19-40
• “Pull, Push, and Fetch Files with Git” on page 19-54
• “Resolve Conflicts” on page 19-62
• “Revert Changes” on page 19-52

More About
• “About Source Control with Projects” on page 19-2

19-51
19 Project Source Control

Revert Changes
In this section...
“Discard Local Changes” on page 19-52
“Revert a File to a Specified Revision” on page 19-52
“Revert the Project to a Specified Revision” on page 19-53

Discard Local Changes


With SVN, if you want to roll back local changes in a particular file, in a project, right-click the file
and select Source Control > Discard Local Changes and Release Locks to release locks and
revert to the version in the last sandbox update (that is, the last version you synchronized or
retrieved from the repository).

In the Simulink Editor, if an open model belongs to a project under source control, you can revert
changes. To do so, on the Simulation tab, select Project > Discard Local Changes and Release
Locks.

To abandon all local changes, in a project select all the files in the Modified files list, then right-click
and select Discard Local Changes and Release Locks.

With Git, right-click a file and select Source Control > Revert Local Changes. Git does not have
locks. To remove all local changes, click Branches in the Git pane and click Revert to Head.

Revert a File to a Specified Revision


1 Right-click a file and select Source Control > Revert using SVN or Source Control > Revert
using Git.
2 In the Revert Files dialog box, choose a revision to revert to. Select a revision to view information
about the change such as the author, date, log message.

With SVN, select a revision and you can browse the lower list of files in the change set. Right-
click a file in the list to view changes or save revisions.
3 Click Revert.

The project reverts the selected file.


4 If you revert a file to an earlier revision and then make changes, you cannot commit the file until
you resolve the conflict with the repository history.

With SVN, if you try to commit the file, you see a message that it is out of date. Before you can
commit the file, you must update its revision up to the current HEAD revision. click Update in
the source control section on the Project tab.

The project marks the file as conflicted because you have made changes to an earlier version of
the file than the version in the repository.
5 With either SVN or Git, to examine conflicts, right-click and select View Conflicts.

Decide how to resolve the conflict or to keep your changes to the reverted file. See “Resolve
Conflicts” on page 19-62.

19-52
Revert Changes

6 After you have resolved the conflict, mark the conflict resolved, either by using the merge tool or
manually by right-clicking the file and selecting Source Control > Mark Conflict Resolved.
7 Select the Modified (number of files) view to check changes, and on the Project tab, click
Commit.

Revert the Project to a Specified Revision


With SVN, inspect the project revision information by clicking Show Log in the in Source Control
section on the Project tab. In the Log dialog box, each revision in the list is a change set of modified
files. Select a revision to view information about the change such as the author, date, log message
and the list of modified files.

To revert the project:

1 On the Project tab, in the Source Control section, click Revert Project.
2 In the Revert Files dialog box, choose a revision to revert to.

Each revision in the list is a change set of modified files. Select a revision to view information
about the change such as the author, date, and the log message.

With SVN, select a revision and you can browse the lower list of files in the change set. Right-
click a file in the list to view changes or save revisions.
3 Click Revert.

The project displays progress messages in the SVN pane as it restores the project to the state it
was in when the selected revision was committed. Depending on the change set you selected, all
files do not necessarily have a particular revision number or matching revision numbers. For
example, if you revert a project to revision 20, all files will show their revision numbers when
revision 20 was committed (20 or lower).

With Git, you can switch branches. See “Branch and Merge Files with Git” on page 19-58.

See Also

Related Examples
• “Resolve Conflicts” on page 19-62

19-53
19 Project Source Control

Pull, Push, and Fetch Files with Git

In this section...
“Pull and Push” on page 19-54
“Pull, Fetch, and Merge” on page 19-55
“Push Empty Folders” on page 19-57
“Use Git Stashes” on page 19-57

Pull and Push


Use this workflow to work with a Git project connected to a remote repository. With Git, there is a
two-step workflow: commit local changes, and then push to the remote repository. In a project, the
only access to the remote repository is through the Pull, Push, and Fetch buttons. All other actions
use the local repository (such as Check for Modifications, Compare to Ancestor, and Commit).
This diagram represents the Git workflow.

1 To get the latest changes, on the Project tab, in the Source Control section, click Pull. Pull
fetches the latest changes and merges them into your current branch.

Note Before you can merge, you must register model files as binary to prevent Git from
inserting conflict markers. See “Register Model Files with Source Control Tools” on page 19-9.
2 To create branches to work on, on the Project tab, in the Source Control section, click Branches.
Create branches in the Branches dialog box, as described in “Branch and Merge Files with Git”
on page 19-58.
3 When you want to commit changes, select the Modified files view to view files, and on the
Project tab, click Commit. The changes are committed to your current branch in your local
repository. Check the Git pane for information about the current branch. You see the message
Ahead when you commit local changes that have moved ahead of the remote tracking branch.

19-54
Pull, Push, and Fetch Files with Git

4 To send your local commits to the remote repository, on the Project tab, in the Source Control
section, click Push.
5 A message appears if you cannot push your changes directly because the repository has moved
on. Click Fetch to fetch changes from the remote repository. Merge branches and resolve
conflicts, and then you can push your changes. See “Pull, Fetch, and Merge” on page 19-55.

Pull, Fetch, and Merge


Use Fetch to get changes and merge manually. Use Pull instead to fetch the latest changes and
merge them into your current branch.

Note Before you can merge branches, you must register model files as binary to prevent Git from
inserting conflict markers. See “Register Model Files with Source Control Tools” on page 19-9.

Pull fetches the latest changes and merges them into your current branch. If you are not sure what is
going to come in from the repository, use fetch instead to examine the changes, and then merge the
changes manually.

Pull might fail if you have conflicts. With a complicated change you might want to create a branch
from the origin, make some compatibility changes, then merge that branch into the main tracking
branch.

To fetch changes from the remote repository, click Fetch on the Project tab.

Fetch updates all of the origin branches in the local repository.

Note When you click Fetch, your sandbox files are not changed. To see others’ changes, you need to
merge in the origin changes to your local branches.

Check the Git pane for information about your current branch relative to the remote tracking branch
in the repository. When you see the message Behind, you need to merge in changes from the
repository to your local branch.

For example, if you are on the main branch and want to get changes from the main branch in the
remote repository:

1 Click Fetch.

Observe the message in the Git pane, Behind /origin/main. You need to merge in the
changes from the repository to your local branch, using Branches.

19-55
19 Project Source Control

2 Click Branches.
3 In the Branches dialog box, in the Branches list, select origin/main.

4 Click Merge. This merges the origin branch changes into the main branch in your sandbox.

5 Close the Branches dialog box. Observe the message in the Git pane now says Coincident with /
origin/main. You can now view the changes fetched and merged from the remote repository in
your local sandbox files.

When you fetch and merge, you might need to resolve conflicting changes. If the branch merge
causes a conflict that Git cannot resolve automatically, an error dialog box reports that automatic
merge failed. Resolve the conflicts before proceeding. See “Resolve Conflicts” on page 19-62.

19-56
Pull, Push, and Fetch Files with Git

Push Empty Folders


Using Git, you cannot add empty folders to source control, so you cannot select Push and then clone
an empty folder. You can create an empty folder in a project, but if you push changes and then sync a
new sandbox, then the empty folder does not appear in the new sandbox. You can instead run Check
Project which creates the empty folder for you.

Alternatively, to push empty folders to the repository for other users to sync, create a gitignore file
in the folder and then push your changes.

Use Git Stashes


Store uncommitted changes for later use by creating a Git stash. Use stashes to:

• Store modified files without committing them.


• Move changes easily to a new branch.
• Browse and examine the changes within a stash.

To create and manage stashes, on the Project tab, in the Source Control section, click Stashes. In
the Stashes dialog box:

• To create a stash containing your currently modified files, click New Stash.
• To view modified files in a stash, select the stash under Available Stashes. Right-click modified
files to view changes or save a copy.
• To apply the stash to your current branch and then delete the stash, click Pop.
• To apply the stash and keep it, click Apply.
• To delete the stash, click Drop.

See Also
Functions
gitrepo | gitclone | fetch | merge | push

Related Examples
• “Set Up Git Source Control” on page 19-17
• “Branch and Merge Files with Git” on page 19-58
• “Resolve Conflicts” on page 19-62

More About
• “About Source Control with Projects” on page 19-2

19-57
19 Project Source Control

Branch and Merge Files with Git


In this section...
“Create a Branch” on page 19-58
“Switch Branch” on page 19-59
“Compare Branches and Save Copies” on page 19-60
“Merge Branches” on page 19-60
“Revert to Head” on page 19-61
“Delete Branches” on page 19-61

Create a Branch
1 In a project using Git source control, click Branches on the Project tab. The Branches dialog box
appears, where you can view, switch, create, and merge branches.

Tip You can inspect information about each commit node. Select a node in the Branch Browser
diagram to view the author, date, commit message, and changed files.

The Branches pane in this figure shows an example branch history.

19-58
Branch and Merge Files with Git

2 Select a source for the new branch. Click a node in the Branch Browser diagram, or enter a
unique identifier in the Source text box. You can enter a tag, branch name, or a unique prefix of
the SHA1 hash (for example, 73c637 to identify a specific commit). Leave the default to create a
branch from the head of the current branch.
3 Enter a name in the Branch name text box and click Create.
4 To work on the files on your new branch, switch your project to the branch.

In the Branches drop-down list, select the branch you want to switch to and click Switch.
5 Close the Branches dialog box to return to the project and work on the files on your branch.

For next steps, see “Pull, Push, and Fetch Files with Git” on page 19-54.

Switch Branch
1 In a project, click Branches.
2 In the Branches dialog box, select the branch you want to switch to in the Branches list and
click Switch.

19-59
19 Project Source Control

3 Close the Branches dialog box to return to the project and work on the files on the selected
branch.

Compare Branches and Save Copies


From within your Git repository folder, right-click the white space of the Current Folder browser and
select Source Control > Branches.

• To examine differences in a file between the current revision and its parent, right-click a file in the
tree under Differences from parent and select Show Difference.
• To examine differences in a file between any two revisions including revisions on two different
development branches, hold the Ctrl key and select the two different revisions. Right-click a file in
the tree under Differences from selection and select Show Difference.

MATLAB opens a comparison report. You can save a copy of the selected file on either revision. Right-
click a file and select Save As to save a copy of the file on the selected revision. Select Save Original
As to save a copy of the file on the prior revision. This is useful if you want to test how the code ran in
previous revisions or on other branches.

Merge Branches
Before you can merge branches, you must register model files as binary to prevent Git from inserting
conflict markers. See “Register Model Files with Source Control Tools” on page 19-9.

Tip After you use Fetch, you must merge. See “Pull, Fetch, and Merge” on page 19-55.

To merge any branches:

1 In a project, click Branches.


2 In the Branches dialog box, from the Branches drop-down list, select a branch you want to
merge into the current branch, and click Merge.
3 Close the Branches dialog box to return to the project and work on the files on the current
branch.

If the branch merge causes a conflict that Git cannot resolve automatically, an error dialog box
reports that automatic merge failed. The Branch status in the Git pane displays MERGING. Resolve
the conflicts before proceeding.

Caution Do not move or delete files outside of MATLAB because this can cause errors on merge.

Keep Your Version

1 To keep your version of the file, right-click the file and select Mark Conflict Resolved. The
Branch status in Git pane displays MERGE_RESOLVED. The Modified Files list is empty, because
you have not changed any file contents. The local repository index version and your branch
version are identical.
2 Click Commit to commit your change that marks the conflict resolved.

19-60
Branch and Merge Files with Git

View Conflicts in Branch Versions

If you merge a branch and there is a conflict in a model file, Git marks the file as conflicted and does
not modify the contents. Right-click the file and select View Conflicts. The project opens a
comparison report showing the differences between the file on your branch and the branch you want
to merge into. Decide how to resolve the conflict. See “Resolve Conflicts” on page 19-62.

Revert to Head
To remove all local changes, in the Branches dialog box, click Revert to Head.

Delete Branches
1 In the Branches dialog box, from the Branches drop-down list, select a branch you want to
delete. You cannot delete the current branch.
2 On the far right, click the down arrow and select Delete Branch.

Caution You cannot undo deleting a branch.

See Also
Functions
gitrepo | gitclone | createBranch | switchBranch | fetch | merge | push

Related Examples
• “Set Up Git Source Control” on page 19-17
• “Pull, Push, and Fetch Files with Git” on page 19-54
• “Resolve Conflicts” on page 19-62

More About
• “About Source Control with Projects” on page 19-2

19-61
19 Project Source Control

Resolve Conflicts
In this section...
“Resolve Conflicts” on page 19-62
“Merge Text Files” on page 19-63
“Merge Models” on page 19-64
“Extract Conflict Markers” on page 19-64

Resolve Conflicts
If you and another user change the same file in different sandboxes or on different branches, a
conflict message appears when you try to commit your modified files. Extract conflict markers if
necessary, compare the differences causing the conflict, and resolve the conflict.

1 Look for conflicted files in the Modified (number of files) tab.

Identify conflicted folder contents using source control summary status. Folders display rolled-up
source control status. This makes it easier to locate changes in files, particularly conflicted files.
You can hover over the source control status for a folder to view a tooltip displaying how many
files inside are modified, conflicted, added or deleted.

Tip Use the List layout to view files without needing to expand folders.
2 Check the source control status column (Git or SVN) for files with a red warning symbol, which
indicates a conflict.

3 Right-click the conflicted file and select View Conflicts to compare versions.
4 Examine the conflict. The project opens a comparison report showing the differences between
the conflicted files.

• For SVN, the comparison shows the differences between the file and the version of the file in
conflict.
• For Git, the comparison shows the differences between the file on your branch and the branch
you want to merge into.
• For model files, see “Port or Restore Model Changes in Comparison Report” on page 21-14.

19-62
Resolve Conflicts

5 Use the comparison report to determine how to resolve the conflict.

To resolve conflicts you can:

• Use the report to merge changes between revisions.


• Decide to overwrite one set of changes with the other.
• Make changes manually from the project by editing files, changing labels, or editing the
project description.

For details on using the Comparison Tool to merge changes between revisions, see “Merge Text
Files” on page 19-63 and “Merge Models” on page 19-64.
6 When you have resolved the changes and want to commit the version in your sandbox, in a
project, right-click the file and select Source Control > Mark Conflict Resolved. You can use
the merge tool to mark the conflict resolved, or you can choose to manually mark the conflict
resolved in the project.

For Git, the Branch status in the Git pane changes from MERGING to SAFE.
7 Select the Modified (number of files) tab to check changes. On the Project tab, click Commit.

Merge Text Files


When comparing text files, you can merge changes from one file to the other. Merging changes is
useful when resolving conflicts between different versions of files.

Conflict markers appear in a text comparison report like this:

<<<<<<< .mine

If your comparison report contains conflict markers, extract them before merging, as described in
“Extract Conflict Markers” on page 19-64.

Tip You can merge only from left to right. When comparing to another version in source control, the
right file is the version in your sandbox. The left file is either a temporary copy of the previous version
or another version causing a conflict (e.g., filename_theirs). Observe the file paths of the left and
right file at the top of the comparison report. Merge differences from the left (temporary copy) file to
the right file to resolve conflicts.

1 In the Comparison Tool report, select a difference in the report and click Replace Content. The
selected difference is copied from the left file to the right file.

To undo the content replacement, click Undo.

Alternatively, use the inline Replace Content and Undo icons.

19-63
19 Project Source Control

The merged file name at the top of the report displays the dirty flag (filename.m*) to show you
that the file contains unsaved changes.
2 Click Accept & Close to save the merge changes and mark the conflicts resolved.

Merge Models
In the Comparison Tool report, you can merge changes between revisions. For details, see “Port or
Restore Model Changes in Comparison Report” on page 21-14.

After merging to resolve conflicts, the merge tool can mark the conflict resolved for you, or you can
choose to manually mark the conflict resolved. Then commit the changes, as described in “Resolve
Conflicts” on page 19-62.

Extract Conflict Markers


• “What Are Conflict Markers?” on page 19-64
• “Extract Conflict Markers” on page 19-65

What Are Conflict Markers?

Source control tools can insert conflict markers in files that you have not registered as binary (e.g.,
text files). You can use project tools to extract the conflict markers and compare the files causing the
conflict. This process helps you to decide how to resolve the conflict.

Caution Register model files with source control tools to prevent them from inserting conflict
markers and corrupting models. See “Register Model Files with Source Control Tools” on page 19-9.
If your model already contains conflict markers, the project tools can help you to resolve the conflict,
but only if you open the model from the project. Opening a model that contains conflict markers from
the Current Folder or from a file explorer can fail because Simulink does not recognize conflict
markers.

Conflict markers have the following form:

<<<<<<<["mine" file descriptor]


["mine" file content]
=======
["theirs" file content]
>>>>>>>["theirs" file descriptor]

If you try to open a file marked conflicted that contains conflict markers, the Conflict Markers Found
dialog box opens. Follow the prompts to fix the file by extracting the conflict markers. After you
extract the conflict markers, resolve the conflicts as described in “Resolve Conflicts” on page 19-62.

To view the conflict markers, in the Conflict Markers Found dialog box, click Load File. Do not try to
load model files, because Simulink does not recognize conflict markers. Instead, click Fix File to
extract the conflict markers.

By default, the project checks only conflicted files for conflict markers. You can change this
preference to check all files or no files. Click Preferences in the Project tab to change the setting.

19-64
Resolve Conflicts

Extract Conflict Markers

When you open a conflicted file or select View Conflicts, the project checks files for conflict markers
and offers to extract the conflict markers. The project checks only conflicted files for conflict markers
unless you change your preferences setting.

However, some files that are not marked conflicted can still contain conflict markers. This can happen
if you or another user marked a conflict resolved without removing the conflict markers and then
committed the file. If you see conflict markers in a file that is not marked conflicted, you can remove
the conflict markers.

1 In a project, right-click the file and select Source Control > Extract Conflict Markers to File.
2 Leave the default option to copy the “mine” revision over the conflicted file. Leave the Compare
check box selected. Click Extract.
3 Use the Comparison Tool report as usual to continue to resolve the conflict.

See Also

Related Examples
• “Register Model Files with Source Control Tools” on page 19-9
• “Port or Restore Model Changes in Comparison Report” on page 21-14

19-65
19 Project Source Control

Work with Derived Files in Projects


Best practice is to omit derived and temporary files from your project or exclude them from source
control. To check the integrity of the project, on the Project tab, click the down arrow to expand the
Tools gallery. Under Project Checks, click Check 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.

Best practice is to exclude derived files, such as .mex*, the contents of the slprj folder, sccprj
folder, or other code generation folders from source control, because they can cause problems. For
example:

• With a source control that can do file locking, you can encounter conflicts. If slprj is under
source control and you generate code, most of the files under slprj change and become locked.
Other users cannot generate code because of file permission errors. The slprj folder is also used
for simulation via code generation (for example, with model reference or Stateflow), so locking
these files can have an impact on a team. The same problems arise with binaries, such as .mex*.
• Deleting slprj is often required. However, deleting slprj causes problems such as “not a
working copy” errors if the folder is under some source control tools (for example, SVN).
• If you want to check in the generated code as an artifact of the process, 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, you can delete the temporary cache folder when you need to. See packNGo 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 many small files. This can affect performance with some source
control tools when each of those files is checked to see if it is up-to-date.

See Also
packNGo | currentProject

Related Examples
• “Add Files to the Project” on page 16-22
• “Run Project Checks” on page 19-49

19-66
Customize External Source Control to Use MATLAB for Diff and Merge

Customize External Source Control to Use MATLAB for Diff and


Merge
In this section...
“Finding the Full Paths for MATLAB Diff, Merge, and AutoMerge” on page 19-67
“Integration with Git” on page 19-68
“Integration with SVN” on page 19-69
“Integration with Other Source Control Tools” on page 19-70

You can customize external source control tools to use the MATLAB Comparison Tool for diff and
merge. To compare MATLAB files such as MLX, MAT, SLX, or MDL files from your source control tool,
configure your source control tool to open the MATLAB Comparison Tool. For a more complete list of
supported files, see visdiff. The MATLAB Comparison Tool provides tools for merging MathWorks
files and is compatible with popular software configuration management and version control systems.
You can use the automerge tool with Git to automatically merge branches that contain changes in
different subsystems in the same SLX, SLMX, SLREQX, and SLTX files.

To set up your source control tool to use MATLAB as the application for diff and merge, you must first
determine the full paths of the mlDiff, mlMerge, and mlAutoMerge executable files, and then
follow the recommended steps for the source control tool you are using.

Finding the Full Paths for MATLAB Diff, Merge, and AutoMerge
To get the required file paths and enable external source control tools to reuse open MATLAB
sessions, run this command in MATLAB:

comparisons.ExternalSCMLink.setup()

This command sets the MATLAB preference, under Comparison, called Allow external source
control tools to use open MATLAB sessions for diffs and merges.

This command also displays the file paths to copy and paste into your source control tool setup.
Example paths are:

• On Windows:

Diff: matlabroot\bin\win64\mlDiff.exe

Merge: matlabroot\bin\win64\mlMerge.exe

AutoMerge: matlabroot\bin\win64\mlAutoMerge.bat
• On Linux:

Diff: matlabroot/bin/glnxa64/mlDiff

Merge: matlabroot/bin/glnxa64/mlMerge

AutoMerge: matlabroot/bin/glnxa64/mlAutoMerge
• On Mac:

19-67
19 Project Source Control

Diff: matlabroot/bin/maci64/mlDiff

Merge: matlabroot/bin/maci64/mlMerge

AutoMerge: matlabroot/bin/maci64/mlAutoMerge

where matlabroot is replaced with the full path to your installation, for example, C:\Program
Files\MATLAB\R2020b.

Note Your diff and merge operations use open MATLAB sessions when available, and only open
MATLAB when necessary. The operations only use the specified MATLAB installation.

Integration with Git


Command Line

To configure MATLAB diff and merge tools with command-line Git:

1 Run this command in MATLAB.

comparisons.ExternalSCMLink.setupGitConfig()

This command displays the full paths of the mlDiff, mlMerge, and mlAutoMerge executable
files. It also automatically populates the global .gitconfig file. For example:
[difftool "mlDiff"]
cmd = \"C:/Program Files/MATLAB/R20xxb/bin/win64/mlDiff.exe\" $LOCAL $REMOTE
[mergetool "mlMerge"]
cmd = \"C:/Program Files/MATLAB/R20xxb/bin/win64/mlMerge.exe\" $BASE $LOCAL $REMOTE $MERGED
[merge "mlAutoMerge"]
driver = \"C:/Program Files/MATLAB/R20xb/bin/win64/mlAutoMerge.bat\" %O %A %B %A

Note You need to do step 1 only once for your Git setup.
2 Configure your repository to use the mlAutoMerge executable file. Open the .gitattributes
file in your repository and add:

*.slx binary merge=mlAutoMerge

Now, when you merge branches that contain changes in different subsystems in the same SLX
file, MATLAB handles the merge automatically.

To run the MATLAB diff and merge tools from command-line Git, use git difftool and git
mergetool:

• To compare two revisions of a model using the MATLAB diff tool, type:
git difftool -t mlDiff <revisonID1> <revisionID2> myModel.slx

If you do not provide revision IDs, git difftool compares the working copy to the repository
copy.

If you do not specify which model you want to compare, command-line Git will go through all
modified files and ask you if you want to compare them one by one.
• To resolve a merge conflict in a model using the MATLAB merge tool, type:
git mergetool -t mlMerge myModel.slx

19-68
Customize External Source Control to Use MATLAB for Diff and Merge

If you do not specify which model you want to merge, command-line Git will go through all files
and ask you if you want to merge them one by one.

SourceTree

SourceTree is an interactive GUI tool that visualizes and manages Git repositories for Windows and
Mac.

1 Configure the MATLAB diff and merge tools as SourceTree external tools:

a With SourceTree open, click Tools > Options.


b On the Diff tab, under External Diff / Merge, fill the fields with the following information:
External Diff tool: Custom
Diff Command: C:\Program Files\MATLAB\R20xxb\bin\win64\mlDiff.exe
Arguments: $LOCAL $REMOTE
Merge tool: Custom
Merge Command: C:\Program Files\MATLAB\R20xxb\bin\win64\mlMerge.exe
Arguments: $BASE $LOCAL $REMOTE $MERGED

2 Configure your repository to automerge changes in different subsystems in the same SLX file
using the mlAutoMerge executable file:

a Open the global .gitconfig file and add:


[merge "mlAutoMerge"]
driver = \"C:/Program Files/MATLAB/R20xxb/bin/win64/mlAutoMerge.bat\" %O %A %B %A

b Open the .gitattributes file in your repository and add:

*.slx binary merge=mlAutoMerge

Tip Customize the full path of the mlDiff, mlMerge, and mlAutoMerge executables to match both
the MATLAB installation and the operating system you are using. For more information, see “Finding
the Full Paths for MATLAB Diff, Merge, and AutoMerge” on page 19-67.

To use the MATLAB diff tool from within SourceTree, right-click a modified file under Unstaged files
and select External Diff.

To use the MATLAB merge tool when SourceTree detects a merge conflict, select the Uncommitted
changes branch, right-click a modified file, and select Resolve Conflicts > Launch External
Merge Tool.

Integration with SVN


TortoiseSVN

With TortoiseSVN, you can customize your diff and merge tools based on the file extension. For
example, to use MATLAB diff and merge tools for SLX files:

1 Right-click in any file explorer window and select TortoiseSVN > Settings to open TortoiseSVN
settings.
2 In the Settings sidebar, select Diff Viewer. Click Advanced to specify the diff application based
on file extensions.
3 Click Add and fill the fields with the extension and the mlDiff executable path:

19-69
19 Project Source Control

Filename, extension or mime-type: .slx


External Program: "C:\Program Files\MATLAB\R20xxb\bin\win64\mlDiff.exe" %base %mine

4 Click OK and repeat the same steps to add another file extension.
5 In the Settings sidebar, select Diff ViewerMerge Tool. Click Advanced to specify the merge
application based on file extensions.
6 Click Add and fill the fields with the extension and mlMerge executable path:
Filename, extension or mime-type: .slx
External Program: "C:\Program Files\MATLAB\R20xxb\bin\win64\mlMerge.exe" %base %mine %theirs %merged

7 Click OK and repeat the same steps to add another file extension.

You can now use the MATLAB tools for diff and merge the same way you would use the TortoiseSVN
default diff and merge applications.

Note Automerging binary files with SVN , such as SLX files, is not supported.

Integration with Other Source Control Tools


Perforce P4V

With Perforce® P4V, you can customize your diff and merge tools based on the file extension. To use
MATLAB diff and merge tools for SLX files, for example:

1 In Perforce, click Edit > Preferences.


2 In the Preferences sidebar, select Diff. Under Specify diff application by extension
(overrides default), click Add.
3 In the Add File Type dialog box, enter the following information:
Extension: .slx
Application: C:\Program Files\MATLAB\R20xxb\bin\win64\mlDiff.exe
Arguments: %1 %2
4 Click Save.
5 In the Preferences sidebar, select Merge. Under Specify merge application by extension
(overrides default), click Add.
6 In the Add File Type dialog box, enter the following information:
Extension: .slx
Application: C:\Program Files\MATLAB\R20xxb\bin\win64\mlMerge.exe
Arguments: %b %2 %1 %r
7 Click Save and repeat the steps for other file extensions.

Tip Customize the full path of the mlDiff and mlMerge executables to match both the MATLAB
installation and the operating system you are using. For more information, see “Finding the Full
Paths for MATLAB Diff, Merge, and AutoMerge” on page 19-67.

You can now use the MATLAB tools for diff and merge the same way you would use the Perforce
default diff and merge applications.

19-70
Customize External Source Control to Use MATLAB for Diff and Merge

See Also

Related Examples
• “Compare Files and Folders and Merge Files”
• “Automatically Merge Models” on page 19-27
• “Configure Git Environment to Merge Requirement and Linkset Files” (Requirements Toolbox)
• “Compare and Merge MAT-Files”
• “Port or Restore Model Changes in Comparison Report” on page 21-14

19-71
19 Project Source Control

Continuous Integration Using MATLAB Projects and Jenkins


In this section...
“Prerequisites” on page 19-72
“Set Up MATLAB Project for Continuous Integration in Jenkins” on page 19-72
“Reduce Test Runtime Using Dependency Cache and Impact Analysis” on page 19-73
“Enhance Workflow” on page 19-74

This example shows how to set up a MATLAB project for continuous integration and run a suite of
MATLAB unit tests with Jenkins.

• Configure a freestyle Jenkins project to access a MATLAB project hosted in a remote repository.
• Add a build step to the Jenkins project to run all project tests.
• Add a build step to the Jenkins project to run tests impacted by the latest change.
• Add a post-build step to archive and reuse the dependency analysis cache file to reduce test suite
runtime when qualifying a change.
• Build the project and examine the test results.

Note You can use different continuous integration (CI) platforms such as Azure® DevOps, Bamboo®,
and GitHub Actions to run MATLAB code and Simulink models as part of your automated workflow.
For a list of supported CI platforms, see “Continuous Integration with MATLAB on CI Platforms”

Prerequisites
Before you start:

1 Install Jenkins. See https://www.jenkins.io/doc/book/installing/.


2 Install the MATLAB plugin for Jenkins:

a From within Jenkins, on the Manage Jenkins page, click Manage Plugins.
b On the Available tab, search for "MATLAB".
c Download and install the plugin.

For more information, see Plugin Configuration Guide (GitHub).


3 Put your MATLAB project under Git source control and share on GitHub:

a With the project loaded, on the Project tab, select Share > GitHub.
b Enter your GitHub user name and personal access token, and edit the name for the new
repository. Click Create.

Your MATLAB project is publicly available on GitHub. You can make your repository private by
changing the settings in your GitHub account.

Set Up MATLAB Project for Continuous Integration in Jenkins


Create a new Jenkins project:

19-72
Continuous Integration Using MATLAB Projects and Jenkins

1 In the Jenkins interface, in the left pane, click New Item.


2 Enter a name for your Jenkins project, select Freestyle project, and click OK.

Configure your Jenkins project. In the left pane, click Configure.


1 In the Source Code Management section, specify the Repository URL that hosts your
MATLAB project. For example, https://github.com/username/Airframe-Example.git.
2 In the Build Triggers section, you can specify when and how frequently you want to run builds.
For example, to build your project after every GitHub push notification, select GitHub hook
trigger for GITScm polling.
3 In the Build Environment section, select Use MATLAB Version and specify the MATLAB
root, for example, C:\Program Files\MATLAB\R2022a.
4 To specify the test suite you want to run, in the Build section, select Add Build Step > Run
MATLAB Tests. To run all tests stored in a specific folder, select By folder name and specify
the test folder name. For example, tests. By default, Run MATLAB Tests runs all test files in
the MATLAB project.

Alternatively, use the Run MATLAB Command step to run all tests using the MATLAB project
label. In the Build section, select Add Build Step > Run MATLAB Command. In the
Command field, enter this script.
proj = openProject("ProjectAirframeExample.prj");
testFiles = findFiles(proj,Label="Test");
runtests(testFiles)
5 To save the Jenkins project configuration, click Save.
6 To build your project and run all tests, click Build Now. Jenkins triggers a build, assigns it a
number under Build History, and runs the build. If the build is successful, a blue circle icon
appears next to the build number. If the build fails, a red circle icon appears. For more
information, see Run MATLAB Tests on Jenkins Server (GitHub).

Reduce Test Runtime Using Dependency Cache and Impact Analysis


You can share the dependency cache file to reduce qualification time on local machines and CI
servers. Using a prepopulated dependency cache file, you can perform an incremental impact
analysis and run only the tests impacted by a change.

Set MATLAB Project Dependency Cache File

To set the project dependency cache file, in MATLAB, on the Project tab, in the Environment
section, click Details. In Dependency cache file, browse to and specify a GraphML file. If the cache
file does not exist, the project creates it for you when you run a dependency analysis.

Alternatively, you can create and set the project dependency cache programmatically.
proj = currentProject;
proj.DependencyCacheFile = "work/dependencyanalysis/projectcache.graphml";

Commit and push the change to make it available on GitHub and Jenkins. On the Project tab, in the
Source Control section, click Commit, then click Push.

Generate and Archive Dependency Cache File on Jenkins

To configure your Jenkins project to generate and archive the dependency analysis cache file, on your
Jenkins project configuration page:

19-73
19 Project Source Control

1 Add a new build step. In the Build section, select Add Build Step > Run MATLAB Command.
In the Command field, enter this script.

proj = openProject("ProjectAirframeExample.prj");
updateDependencies(proj);

This script launches MATLAB, loads your MATLAB project, runs a dependency analysis, and
caches the results in the dependency cache file.
2 In the Post-build Actions section, under Archive the artifacts, in the Files to archive field,
enter: work/dependencyanalysis/*.graphml. After the build, Jenkins copies the GraphML
file from the Jenkins workspace to the build archive location.

Share Cache for Faster Dependency Analysis on Local Machines

If you configured Jenkins to perform frequent builds, team members can sync their working copy
based on the last successful build. Team members check out the design changes from Git, retrieve the
associated dependency cache file from the build archive area, and place the GraphML file in the
specified location.

On a local machine, MATLAB projects use the prepopulated dependency cache file to run an
incremental dependency analysis. This action saves time for workflows running a dependency
analysis in the background, such as automatic renaming, sharing a project, and performing an impact
analysis.

Run Impacted Tests and Reduce Qualification Runtime on CI Servers

On a CI server, for large projects, you can use the prepopulated dependency cache to perform an
incremental impact analysis. You can configure your project build to run only impacted tests and
significantly reduce runtime when qualifying a code change.

To configure your Jenkins project to only run tests impacted by the last change, in the Build section,
select Add Build Step > Run MATLAB Command. In the Command field, enter this script.
proj = openProject("ProjectAirframeExample.prj");
[status,modifiedFiles] = system("git diff --name-only HEAD~1..HEAD :!resources");
updateDependencies(proj);
modifiedFiles = split(modifiedFiles);
modifiedFiles = modifiedFiles(1:(end-1))';
impactedFiles = listImpactedFiles(proj,modifiedFiles);
testFiles = findFiles(proj,Label="Test");
impactedTests = intersect(testFiles,impactedFiles);

runtests(impactedTests)

This script launches MATLAB, loads your MATLAB project, retrieves the list of files that changed in
the last commit, runs an impact analysis to determine the subset of tests you need to run to qualify
the change, and runs the list of impacted tests.

Enhance Workflow
You can apply several additional steps to improve the workflow and make building and qualifying the
project faster.

• Similar to the GraphML file, you also can generate and archive SLXC files to reuse and reduce
simulation time. For more information, see “Share Simulink Cache Files for Faster Simulation” on
page 8-70.

19-74
Continuous Integration Using MATLAB Projects and Jenkins

• To easily manage SLXC and GraphML files from multiple Jenkins builds, you can use a database or
a repository management tool such as JFrog Artifactory. For more information, see https://
jfrog.com/help/r/get-started-with-the-jfrog-platform/jfrog-artifactory.
• You can set up a script to automatically retrieve the associated dependency cache file and place a
copy in your working copy.

See Also

More About
• “Analyze Project Dependencies”
• “Develop and Integrate Software with Continuous Integration”
• “Continuous Integration with MATLAB on CI Platforms”

19-75
19 Project Source Control

Determine Order for Resolving Conflicts Using Dependency


Analyzer

When collaborating on a project, a branch merge can lead to conflicted files. For a smoother merge,
you can determine the optimal order in which to resolve conflicts by running a dependency analysis.
Conflicts in files that are used by other files should be resolved first. Conflicts in files that do not have
dependencies do not affect other files, so the conflict resolve order does not matter.

Note If the project dependency graph contains circular dependencies, there might not be an optimal
order in which to resolve conflicts.

You can use the Dependency Analyzer to programmatically determine the optimal order in which to
resolve conflicts. In the MATLAB Command Window, run the getProjectResolveOrder function.

function fileOrder = getProjectResolveOrder()


import matlab.sourcecontrol.Status;
p = currentProject;
conflictingFiles = p.Files([p.Files.SourceControlStatus] == Status.Conflicted);
updateDependencies(p);
graph = p.Dependencies;

if ~isdag(graph)
error("Unable to recommend an optimal resolve order. The dependency graph contains circul
end

topologicalOrder = toposort(graph);
topologicalFiles = graph.Nodes.Name(topologicalOrder);
fileIndices = ismember(topologicalFiles, [conflictingFiles.Path]);
files = flip(topologicalFiles(fileIndices));
nodependencyFiles = setdiff(cellstr([conflictingFiles.Path])',files);

19-76
Determine Order for Resolving Conflicts Using Dependency Analyzer

fileOrder = [files;nodependencyFiles];
end

getProjectResolveOrder

ans =

6×1 cell array

{'C:\workSpace\examples\airframe\src\timesthree.c' }
{'C:\workSpace\examples\airframe\lib\timesthree.tlc' }
{'C:\workSpace\examples\airframe\models\NonLinearActuator.slx'}
{'C:\workSpace\examples\airframe\models\f14_airframe.slx' }
{'C:\workSpace\examples\airframe\models\slproject_f14.slx' }
{'C:\workSpace\examples\airframe\tests\f14_airframe_test.m' }

Resolve conflicts according to the listed order. For more details, see “Resolve Conflicts” on page 19-
62.

See Also

More About
• “Set Up Git Source Control” on page 19-17
• “Branch and Merge Files with Git” on page 19-58
• “Resolve Conflicts” on page 19-62
• “Run a Dependency Analysis” on page 18-5
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

19-77
20

Project Reference

• “Componentization Using Referenced Projects” on page 20-2


• “Add or Remove a Reference to Another Project” on page 20-5
• “View, Edit, or Run Referenced Project Files” on page 20-6
• “Extract a Folder to Create a Referenced Project” on page 20-7
• “Manage Referenced Project Changes Using Checkpoints” on page 20-9
20 Project Reference

Componentization Using Referenced Projects

For a large modeling project, organizing the project into components facilitates:

• Component reuse
• Modular, team-based development
• Unit testing
• Independent release of components

Projects supports large-scale project componentization by allowing you to reference other projects
from a parent project. A collection of parent and referenced projects constitutes a project reference
hierarchy. Project referencing provides these benefits:

• A parent project has access to a referenced project’s project paths, entry-point shortcuts, and
source control information. For example, from a parent project, you can display the hierarchy of
referenced projects. You can select a referenced project and then view, edit, and run files that
belong to the referenced project.
• Through a referenced project, your team can develop a component independent of other
components.
• In a referenced project, you can test the component separately.
• In a parent project, you can set a checkpoint and then compare the referenced project against the
checkpoint to detect any changes.

This project hierarchy illustrates the use of parent and referenced projects as components of a large
project.

20-2
Componentization Using Referenced Projects

Through the Transistor Development project, a team independently creates and tests a library of
blocks. The team makes the library available to other developers by exporting release versions, for
example, version 2.3.

Through the Radio Development project, another team develops and tests the Radio system. This
team requires:

• Version 2.3 of the Transistor component. The team sets up the Radio Development project to
reference the Transistor Release V2.3 project.
• Tools to plot signals, for example, MATLAB files that are not distributed to customers. The team
sets up the Radio Development project to reference the Plotting Tools Development project.

When the Radio system is ready for customers, the team exports a release version, for example,
version 4.1.

See Also

Related Examples
• How to Organize Large Projects into Components (3 min, 32 sec)
• “Organize Large Modeling Projects” on page 16-2
• “Component-Based Modeling Guidelines” on page 23-2
• “Add or Remove a Reference to Another Project” on page 20-5
• “View, Edit, or Run Referenced Project Files” on page 20-6

20-3
20 Project Reference

• “Extract a Folder to Create a Referenced Project” on page 20-7


• “Manage Referenced Project Changes Using Checkpoints” on page 20-9
• “Organize Projects into Components Using References and Git Submodules”

20-4
Add or Remove a Reference to Another Project

Add or Remove a Reference to Another Project


Add new components to your project by referencing other projects. The addition of referenced
projects creates a project hierarchy. When the Project loads a referenced project in a project
hierarchy, it:

• Adds project paths from the referenced project to the MATLAB search path.
• Runs startup shortcuts from the referenced project.

To reference a project:

1
On the Project tab, in the Environment section, click .
2 In the Add Reference dialog box, specify settings:

• Referenced project location –– Click Browse and navigate to the project folder. Then, in
the project folder, select the required project (.prj) file.
• Reference type –– If your project hierarchy has a well-defined root relative to your project
root, for example, a folder under source control, click Relative. If the project you want to
reference is in a location accessible to your computers, for example, a network drive, click
Absolute.
• Set a checkpoint to detect future changes –– To create a checkpoint, select the check box.
To detect changes, you can compare the referenced project against this checkpoint.
3 Click Add. The Project creates a References view that displays the referenced project.

You can reference multiple projects in a hierarchical manner. In the References view, the Project
displays the project reference hierarchy as a tree.

To view summary information about a referenced project, in the References tree, select the project.

To view files that belong to the referenced project, click .

To remove a referenced project from your project hierarchy, in the References tree, right-click the
referenced project and select Remove Reference.

See Also

Related Examples
• “Componentization Using Referenced Projects” on page 20-2
• “View, Edit, or Run Referenced Project Files” on page 20-6
• “Extract a Folder to Create a Referenced Project” on page 20-7
• “Organize Projects into Components Using References and Git Submodules”

20-5
20 Project Reference

View, Edit, or Run Referenced Project Files


In a project that references other projects, use the References view to see, modify, or run files that
belong to the referenced projects.

1 In a Project, select the References view.


2 In the References tree, select the required project reference.
3
Click . The Project displays files and folders from the referenced project.

4 Right-click a file, and then, from the context menu, select the required action.

See Also

Related Examples
• “Create Shortcuts to Frequent Tasks” on page 16-33
• “Componentization Using Referenced Projects” on page 20-2
• “Add or Remove a Reference to Another Project” on page 20-5
• “Extract a Folder to Create a Referenced Project” on page 20-7
• “Organize Projects into Components Using References and Git Submodules”

20-6
Extract a Folder to Create a Referenced Project

Extract a Folder to Create a Referenced Project

In a Project, you can partition a large project into components through the use of project references.

Consider the Airframe example project. Suppose you create a folder Trial and carry out
development work within the folder. You produce:

• Shortcuts to a Simulink library, a MATLAB file, and a Readme document


• Design and source code folders
• Data files

For easier management, you want to convert the Trial folder into a separate component. In
addition, you want access to the folder contents, for example, shortcuts to key files. To fulfill these
requirements, extract the folder from the project and convert the folder into a referenced project.
1 In the Files view, right-click the Trial folder and select Extract to Referenced Project.
2 In the Extract Folder to New Project dialog box, specify these options:

• New Project Name — For example, DataLogging.


• New Project Location – For example, C:\Work\DataLogging.
• Reference type – The default is Relative reference. Use the default if you specify the
new project location with reference to the current project root. If you specify the full path for
the new location, which is, for example, on a network drive, select Absolute reference.
3 Click More Options. If you want to disable any of the default content migration actions, clear
the corresponding check box.
4 Click Extract.
5 In the two Warning dialog boxes that open, click OK.

The folder Trial and its contents are removed from the project. On the Project Shortcuts tab, the
Referenced Projects section displays a new DataLogging button.

20-7
20 Project Reference

See Also

Related Examples
• “Componentization Using Referenced Projects” on page 20-2
• “Add or Remove a Reference to Another Project” on page 20-5
• “View, Edit, or Run Referenced Project Files” on page 20-6
• “Organize Projects into Components Using References and Git Submodules”

20-8
Manage Referenced Project Changes Using Checkpoints

Manage Referenced Project Changes Using Checkpoints


In a Project, you can create a checkpoint for a referenced project. You can then compare the
referenced project against the checkpoint to detect changes.

1 In the project that contains the referenced project, select the References view.
2 In the References tree, select the referenced project. If a checkpoint does not exist for the
project, in the Details view, the Checkpoint field displays None.

3
To create a checkpoint, in the Checkpoint section, click . In the Details view, the
Checkpoint field displays the timestamp of the check point.

In future, to detect changes in the referenced project, in the Checkpoint section, click . The
Difference to Checkpoint dialog box shows files that have changed on disk since you created the
checkpoint.

To remove the checkpoint, in the Checkpoint section, click .

See Also

Related Examples
• “Componentization Using Referenced Projects” on page 20-2
• “Organize Projects into Components Using References and Git Submodules”

20-9
21

Compare Simulink Models

• “Review Changes in Simulink Models” on page 21-2


• “Select Models to Compare” on page 21-4
• “Understand Simulink Model Comparison Changes” on page 21-7
• “Port or Restore Model Changes in Comparison Report” on page 21-14
• “Resolve Conflicts in Models Under Source Control” on page 21-17
• “Make Changes and Merge Git Local Branch” on page 21-18
• “Identify Order of Resolving Conflicts in Changeset” on page 21-22
• “Resolve Conflicts in Models Using Three-Way Merge” on page 21-24
• “Export, Print, and Save Model Comparison Results” on page 21-33
• “Compare Model or Project Templates” on page 21-35
• “Set Up Simulink Diff and Merge in CI/CD Pipeline” on page 21-36
• “Attach Model Comparison Report to GitHub Pull Requests” on page 21-38
21 Compare Simulink Models

Review Changes in Simulink Models

Use the Comparison Tool to review and merge differences between two model files on disk or
between different revisions of the same file.

In a collaborative environment, you typically compare models:

• When you require a peer review of your changes


• Before you share or submit a version of your code to source control
• When you want to pinpoint when an issue was introduced
• When you want to examine your own local changes in detail

Using the Comparison Tool, you can:

• Compare and review changes in SLX and MDL model files from any version of Simulink. If needed,
the Comparison Tool resaves the models in the current release using the SLX format before
opening the comparison report.
• Visualize and highlight changes in the Simulink Editor.
• Export the comparison results to send for peer review.
• Use merge mode to port or restore changes in different models.

The Comparison report shows only portions of the files that differ.

Follow these steps to understand changes in your model, export comparison results for peer review,
and merge differences, if required:

1 “Select Models to Compare” on page 21-4


2 “Understand Simulink Model Comparison Changes” on page 21-7
3 “Export, Print, and Save Model Comparison Results” on page 21-33
4 “Port or Restore Model Changes in Comparison Report” on page 21-14

Comparison Tool Usage Tips and Limitations


Compare Models with Identical Names

When you compare model files that have identical names, the Comparison Tool creates a read-only
copy of one model named modelname_TEMPORARY_COPY before performing a comparison. The
temporary copy is read-only to prevent making changes that can be lost.

If one of the models with identical names is open when you perform a comparison, the Comparison
Tool asks you to save and close the model to avoid shadowing issues. For more information about
shadowed files, see “Shadowed Files” on page 15-3.

To automatically close models of the same name when you compare them, disable the prompt by
using these commands.

opt = slxmlcomp.options;
opt.setCloseSameNameModel(true);

21-2
Review Changes in Simulink Models

MATLAB stores this preference across sessions. To be prompted about closing identically-named
models, set the setCloseSameNameModel property to false.

Compare Model Hierarchies

The Comparison Tool performs a comparison on the currently selected models only. The comparison
report does not include changes to referenced models or linked libraries.

If you are comparing models that contain referenced models with the same name, check that your
referenced models are not on the MATLAB path before you generate the report. Keeping referenced
models with the same name on the path might result in shadowing issues and display different
comparison results.

More About Model Shadowing Impact

Simulink records information in the top-level model about the interface between the top-level model
and children models. This interface information in the top-level model enables incremental loading
and diagnostic checks without any need to load children models.

• If you are using referenced models, when you load a top-level model, Simulink refreshes the
interface information for its referenced models if the child models are on the path. The interface
information results in new entries in the comparison report. To avoid these interface changes in
the comparison report, make sure your referenced models are not on your path before you
generate the report.
• If you are using library links only, Simulink does not update the cached interface information when
comparing models. The MATLAB path does not affect the comparison report results.
• If you are using both referenced models and library links, Simulink updates the information when
displaying the model. To avoid interface changes in the comparison report, make sure that the
referenced models and associated libraries are temporarily removed from the path.

See Also
visdiff | Comparison Tool

21-3
21 Compare Simulink Models

Select Models to Compare


Use the Comparison Tool to review and merge differences between two model files on disk or
between different revisions of the same file.

For information about opening the Comparison Tool from the files, project and branches browsers,
see “Open the Comparison Tool”.

Tip If you are using source control outside of MATLAB, you can customize external source control
tools to use MATLAB comparison and merge tools.

For instructions, see “Customize External Source Control to Use MATLAB for Diff and Merge” on
page 19-67.

Compare Two Models on Disk

You assign a new hire a task to improve the readability of the mysimple_stats_block1.slx model.
You share the model in an email attachment.

After finishing the task, the new hire shares the improved model mysimple_stats_block2.slx.

To compare the models on disk, use one of these methods.

• On the Home tab, in the File section, click Compare. Specify the models you want to compare by
using the browser or pasting the path to the model files.

• In the Current Folder browser, select the two model files. Right-click and select Compare
Selected Files/Folders.

21-4
Select Models to Compare

• In the Command Window, enter this command.

visdiff("mysimple_stats_block1.slx","mysimple_stats_block2.slx");

Compare Model to Revision

You assign a new hire a task to improve the readability of the mysimple_stats_block.slx model.
The model is under Git™ source control.

After finishing the task, the new hire commits the changes to the repository.

To compare the two different model revisions, in the Current Folder browser, select the model file.
Right-click and select Source Control > Compare to Revision.

Select the two revisions from the commit history and click Compare Selected.

See Also
visdiff | Comparison Tool

Related Examples
• “Compare and Merge Simulink Models Containing Stateflow”

More About
• “Understand Simulink Model Comparison Changes” on page 21-7

21-5
21 Compare Simulink Models

• “Port or Restore Model Changes in Comparison Report” on page 21-14


• “Export, Print, and Save Model Comparison Results” on page 21-33
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67
• “Source Control in Projects”
• “Compare Revisions” on page 19-47

21-6
Understand Simulink Model Comparison Changes

Understand Simulink Model Comparison Changes


Go through the comparison report to explore the differences in your Simulink model files. If you have
not yet run a comparison analysis, see “Select Models to Compare” on page 21-4.

The comparison report displays only differences in models. To step through the differences, use the
Next and Previous buttons in the Navigate section of Comparison toolstrip. Alternatively, use the
up and down arrows on your keyboard to navigate the report.

1 The Comparison Tool shows the first change when the report opens. The selected item appears in
a box. If the selected item has a match, the box appears in both the left and right trees.

In this example report, the tool expands the Constant node and selects the modified Value,
colored in purple.

By default, selecting an item in the model comparison report opens the original model and
highlights the corresponding change item in the editor. If you select a Configuration Parameter
item, the tool also opens the corresponding pane in the Configuration Parameters dialog box. For
more information, see “Open and Highlight Changes in Simulink Editor” on page 21-9.
2 To investigate the next change in the report, click Next.

21-7
21 Compare Simulink Models

In this example report, the tool expands the MATLAB Function node and selects the added
description, colored in blue.

3 Investigate the next change. If additional comparisons are available for particular nodes, you see
a Compare button to open a comparison report for the selected change.

In this example report, you can compare the MATLAB Function block scripts in a new report.
For more information about how to open sub-comparison reports, see “Open Child Comparison
Reports for Selected Nodes” on page 21-9.

4 After stepping through all changes, the tool disables the Next button.

If you click an item in the report, the Next and Previous buttons step through changes from the
point you selected.

Tip Use one of these methods to simplify the report and focus on critical changes.

• For complex changes, use the model highlight capabilities to show and highlight model changes in
the Simulink Editor. Highlighting changes helps you identify important differences quickly and
simplifies the interpretation process. For more information, see “Open and Highlight Changes in
Simulink Editor” on page 21-9.
• For large model comparison reports, use filtering to reduce the report size and focus on critical
changes in the report. By default, the report hides all nonfunctional changes. For information on
how to create custom filters and apply built-in filters, see “Simplify Comparison Report Using
Filters” on page 21-10.

21-8
Understand Simulink Model Comparison Changes

Open Child Comparison Reports for Selected Nodes

When additional comparisons are available for particular items in the report, the Comparison Tool
displays a Compare button to run a new comparison analysis for the selected node. Additional
comparisons include comparison for variables in the Model Workspace, for modified long strings or
scripts, for changes in MATLAB Function blocks, truth tables, and action tables.

In this example report, the tool detects changes in the MATLAB Function block and offers additional
comparison. To compare the MATLAB Function blocks in a new report, click the Compare button
displayed at the end of the MATLAB Function block node.

Open and Highlight Changes in Simulink Editor


To quickly identify changes in your Simulink models, enable highlighting in the Comparison Tool. In
the Comparison toolstrip, to always highlight changes in the Simulink Editor, enable Always
Highlight.

When you select an item in the report, the Comparison Tool opens the models in the editor and
highlights changes in yellow. If you select a configuration parameter item, the tool also displays the
corresponding pane in the Configuration Parameters dialog box.

21-9
21 Compare Simulink Models

Alternatively, you can highlight changes only when needed. In the Comparison toolstrip, clear
Always Highlight and click Highlight Now to highlight the selection in the Simulink Editor.

By default, the Comparison Tool opens the two models you compare to the right of the comparison
report, with the model in the left side of the report on top and the model in the right side of the
report below. If you move or resize the models, the tool remembers your window positions for
subsequent model highlighting operations.

To remember Simulink, Stateflow, and truth table window positions across MATLAB sessions, enter
this command.

slxmlcomp.storeWindowPositions

To restore window positions to the defaults, enter:

slxmlcomp.clearWindowPositions

Simplify Comparison Report Using Filters


To simplify the comparison report and focus on critical changes, use filters. You can filter based on
specific block types, specific changes, or other criteria, such as nonfunctional changes.

The comparison tool offers built-in filters for nonfunctional changes, block defaults, and signal lines
changes. By default, the report hides all nonfunctional and block defaults changes. For more
information on built-in filters, see Comparison Tool.

You can also create and export custom filters to share with others.

21-10
Understand Simulink Model Comparison Changes

In this example, suppose you want to only inspect changes to Constant blocks.

1 In the Comparison toolstrip, click New Filter.


2 In the Name field box, enter Constant Block.
3 In the Rules section, populate the table with these values.

In the Select column, select Block. In the Parameter Name column, select BlockType. In the
Parameter Value column, select Constant. Then, click OK.

Note When you click the down arrows next to Parameter Name and Parameter Value, the
Comparison Tool proposes options from the items available in the report.

The tool stores custom filters in your MATLAB Preferences.

For examples on how to create custom filters to filter out annotation changes, Inport and Outport
block changes, or sample time parameter changes, see Comparison Tool.
4 To see only changes to Constant blocks, in the toolstrip, in the Filter section, click Show, and
then select the Constant Block filter.

21-11
21 Compare Simulink Models

To show all changes in the report, use one of these methods:

• Hide nothing – Click Hide and disable all filters in the gallery.
• Show everything – Create a custom filter named everything. In the New Filter dialog box, delete
the contents of the first column so it shows Any. Then, remove the rest of the row under
Parameter Name. Click Show and enable the everything filter.

You can export your custom filters to share with others.

1 Expand the Filters gallery and click Export.


2 In the Export Filters dialog box, select the filters you want to export and click OK.

3 Specify a name and click Save.


4 Share the exported filters file.

Another user can import the filters by expanding the Filters gallery and clicking Import.

See Also
visdiff | Comparison Tool

Related Examples
• “Compare and Merge Simulink Models Containing Stateflow”

21-12
Understand Simulink Model Comparison Changes

More About
• “Export, Print, and Save Model Comparison Results” on page 21-33
• “Port or Restore Model Changes in Comparison Report” on page 21-14
• “Compare Revisions” on page 19-47
• “Source Control in Projects”
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-13
21 Compare Simulink Models

Port or Restore Model Changes in Comparison Report


In the comparison report, you can use merge mode to port changes between models on disk or
restore changes between model revisions. If you have not yet run a comparison analysis, see “Select
Models to Compare” on page 21-4.

The Merge Mode button in the Comparison Tool enables you to port or restore individual changes
between Simulink models using two-way merge. For example, you can restore individual parameters,
blocks, or entire subsystems. For deleted and inserted subsystems, to ensure the integrity of the
models, the Comparison Tool only allows you to restore the entire subsystem.

Tip Merge blocks before lines, and merge states and junctions before merging transitions. See
“Recommended Merge Order in Models” on page 21-16.

To port or restore changes in models:

1 In the Comparison toolstrip, click Merge Mode. The Comparison Tool expands the first change
and opens a Target pane at the bottom of the report.

If you enabled Always Highlight, the Comparison Tool also opens a temporary model called
targetFile*.
2 Use the buttons in the row of the Target pane to select the differences you want to keep in the
target file.

In this example report, suppose you want to restore the Value of the Constant block to the one
in the Left model. In the Target pane, click the left button in the Value row.

21-14
Port or Restore Model Changes in Comparison Report

3 Click Next to navigate to the next difference.

If your models contain MATLAB Function blocks, the Comparison Tool enables you to port or restore
changes in individual lines in MATLAB Function blocks code.

1 With merge mode enabled, in the comparison report of the parent models, in the targetFile*,
use the buttons in the MATLAB Function block to select the line of codes you want to keep in the
target file.

In this example report, suppose you want to keep the description in the Right MATLAB Function
block model. In the Target pane, click the right buttons in the MATLAB Function code rows.

2 When you finish porting or restoring changes, save your choices in the temporary targetFile*
over the right model using the Save File button.

If you wish to cancel all operations instead, click Close Merge without saving the file.
3 Inspect your changes in the Simulink Editor. If necessary, connect any lines that the software did
not connect automatically. The comparison report does not update to show any changes that you
make in the editor.

Tip If you are using source control outside of MATLAB, you can customize external source control
tools to use MATLAB Comparison and Merge tools.

For instructions, see “Customize External Source Control to Use MATLAB for Diff and Merge” on
page 19-67.

21-15
21 Compare Simulink Models

Recommended Merge Order in Models


• In the Simulink part of the report, merge items in the models in this order. In the target file:

1 Delete the lines you do not want to keep.


2 Delete the blocks, states, and junctions you do not want to keep.
3 Add the blocks, states, and junctions you want to keep.
4 Add the lines you want to keep.
5 Select the parameters you want to keep.

For an example showing how to merge a change involving multiple nodes, see “Compare and
Merge Simulink Models Containing Stateflow”.
• Not all parameters can be merged. In this case, the Comparison Tool shows only one button in the
target pane indicating the version that is in the target model.

See Also
visdiff | Comparison Tool

Related Examples
• “Compare and Merge Simulink Models Containing Stateflow”

See Also

Related Examples
• “Understand Simulink Model Comparison Changes” on page 21-7
• “Export, Print, and Save Model Comparison Results” on page 21-33
• “Source Control in Projects”
• “Compare Revisions” on page 19-47
• “Resolve Conflicts” on page 19-62
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-16
Resolve Conflicts in Models Under Source Control

Resolve Conflicts in Models Under Source Control


Conflicts in Simulink model files can occur when multiple team members work simultaneously on the
same model and when keeping both changes in the merged model is not possible. The user must
make a decision on which change they want to keep by resolving the conflict in the model file. For
example, a conflict occurs when two users change the value of a parameter in two different Git
branches. Another example is when one user modifies the structure of the model, by deleting a block,
and another user on a different Git branch modifies the same block. A conflict occurs in the model
file, and the user must make a manual change to fix the merge.

Development practices and model architecture can greatly affect how often model file conflicts occur.
Follow these best practices to minimize model conflicts.

• Use version control systems, such as Git to help you manage changes and resolve conflicts.
• Pull changes frequently to stay up-to-date with the latest changes, minimize the occurrence of
conflicts, and make them easier to resolve.
• Communicate effectively with your team and understands the scope of their changes to avoid, if
possible, two developers working on the same model file.
• Break up large changes into smaller ones.
• Componentize your model and use subsystems. For more information, see “Subsystems”.
• Set up Git to automatically merge changes in different subsystems, Stateflow charts, and
configuration sets in the same SLX file. For more information, see “Automatically Merge Models”
on page 19-27.

Follow these steps to resolve conflicts in an example collaborative workflow:

1 “Make Changes and Merge Git Local Branch” on page 21-18


2 “Identify Order of Resolving Conflicts in Changeset” on page 21-22
3 “Resolve Conflicts in Models Using Three-Way Merge” on page 21-24

You can use the files provided at any of these steps to follow the instructions in the example.

See Also
Three-Way Merge Tool

Related Examples
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

More About
• “Source Control in Projects”
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-17
21 Compare Simulink Models

Make Changes and Merge Git Local Branch

You are collaborating on models that are under Git™ source control. You work on some changes in
your local branch taskBranch. When you attempt to merge your branch into the main branch,
merge conflicts occur in two model files.

1. Open the example to download the supporting files.

2. Switch from the main branch to the taskBranch branch. In the Current Folder browser, right-
click and select Source Control > Branches. In the Branch Browser, select taskBranch, and
then click Switch.

Alternatively, in the Command Window, enter these commands.


repo = gitrepo;
switchBranch(repo,"taskBranch");

3. Make these changes to the sldemo_mdlref_counter and sldemo_mdlref_basic models and


save the models.

21-18
Make Changes and Merge Git Local Branch

• In the sldemo_mdlref_basic model, in the Constant block C5, set the Constant value to 110.
• In the sldemo_mdlref_counter model, change the Scope block name from ScopeA to Scope
and in the Switch block Switch, set the Threshold to 0.25

Alternatively, in the Command Window, enter these commands.

topMdl = "sldemo_mdlref_basic";
refMdl = "sldemo_mdlref_counter";

load_system(refMdl);
load_system(topMdl);
modelNames=[refMdl,topMdl];

refBlockPath = append(refMdl,"/Switch");
set_param(refBlockPath,"Threshold","0.25");
refScopePath = append(refMdl,"/ScopeA");
set_param(refScopePath,"Name","Scope");
cstBlockPath = append(topMdl,"/C5");
set_param(cstBlockPath,"Value","110");

save_system(refMdl)
save_system(topMdl)

close_system(modelNames,0)

4. Commit your changes. In the Current Folder browser, right-click and select Source Control >
View and Commit Changes.... Enter a commit message and click Commit.

Alternatively, in the Command Window, enter these commands.

commit(repo,Message = "Set Fixed step size to 0.003 and set InputSignalHandling and OutputSignalH

5. Merge the branch taskBranch into the main branch. In the Current Folder browser, right-click
and select Source Control > Branches. In the Branch Browser, select main and click Merge.

21-19
21 Compare Simulink Models

Alternatively, in the Command Window, enter these commands.

try
merge(repo,mainBranch)
catch
% The merge function throws an expected error because this branch merge
% results in a conflict.
% Unable to merge main into taskBranch.

% Caused by:
% Conflicted files:
% sldemo_mdlref_basic.slx
% sldemo_mdlref_counter.slx
end

The branch merge results in conflicts in both model files. See the next steps to resolve the conflicts.

21-20
Make Changes and Merge Git Local Branch

See Also
Three-Way Merge Tool

Related Examples
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

More About
• “Source Control in Projects”
• “Resolve Conflicts in Models Under Source Control” on page 21-17
• “Identify Order of Resolving Conflicts in Changeset” on page 21-22
• “Resolve Conflicts in Models Using Three-Way Merge” on page 21-24
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-21
21 Compare Simulink Models

Identify Order of Resolving Conflicts in Changeset

This example shows how to determine the optimal order, if it exists, when you resolve conflicts in a
changeset that contains multiple conflicted files.

Open the example to download the supporting files. The repository has two conflicted model files. To
make the changes that caused the conflicts yourself instead, see “Make Changes and Merge Git Local
Branch” on page 21-18.

In a repository, whether a folder or a MATLAB® project, a branch merge can lead to conflicted files.

For a smoother merge, determine the optimal order in which to resolve conflicts by running a
dependency analysis. Conflicts in files that are used by other files should be resolved first. Conflicts in
files that do not have dependencies do not affect other files, so the conflict resolve order does not
matter. To determine the optimal order to resolve conflicted files, provide the repository path that
contains conflicts to run the getResolveOrderInFolder utility function that this example provides.

repoFolderPath = gitrepo("models").WorkingFolder;
filesResolveOrder = getResolveOrderInFolder(repoFolderPath)

filesResolveOrder =

2×1 string array

"C:\Users\username\Documents\MATLAB\Examples\IdentifyOrderOfResolvingConflictsInChangesetExam
"C:\Users\username\Documents\MATLAB\Examples\IdentifyOrderOfResolvingConflictsInChangesetExam

In this example repository, resolve the conflicts in the sldemo_mdlref_counter.slx model before
you resolve the conflicts in the sldemo_mdlref_basic.slx model. The dependency graph shows
that sldemo_mdlref_counter.slx is used by sldemo_mdlref_basic.slx. For information on
how to run a dependency analysis interactively, see Dependency Analyzer.

21-22
Identify Order of Resolving Conflicts in Changeset

See Also
Three-Way Merge Tool

Related Examples
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

More About
• “Source Control in Projects”
• “Resolve Conflicts in Models Under Source Control” on page 21-17
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-23
21 Compare Simulink Models

Resolve Conflicts in Models Using Three-Way Merge


You attempt to merge the changes on your Git™ branch into the main branch. Conflicts occur.

Open Three-Way Merge Tool

Open the example to download the supporting files.

The repository has two conflicted model files. To make the changes that cause the conflicts yourself
instead, see “Make Changes and Merge Git Local Branch” on page 21-18. If you have not yet
determined the order in which you should resolve conflicted files, see “Identify Order of Resolving
Conflicts in Changeset” on page 21-22.

To investigate and resolve conflicts using the Three-Way Merge Tool, in the Current Folder browser,
right-click the models that have conflicts and select Source Control > View Conflicts.

21-24
Resolve Conflicts in Models Using Three-Way Merge

Resolve the conflicts in the sldemo_mdlref_counter.slx model before you resolve the conflicts in
the sldemo_mdlref_basic.slx model.

Resolve Conflicts in Changeset


The Three-Way Merge Tool opens three panes at the top that display the changes you made (Mine
pane), the changes your colleague made (Theirs pane), and the common ancestor version (Base
pane). Below, the tool automatically resolves differences when possible and opens a Target pane. The
Target pane contains a copy of the Mine changes and automatic merges. Review the automerge
choices, edit if desired, and decide how to resolve any remaining conflicts.

In this example, to resolve conflicts in your model files, resolve conflicts in the
sldemo_mdlref_counter.slx model before you resolve the conflicts in the
sldemo_mdlref_basic.slx model.

Resolve Conflicts in sldemo_mdlref_counter

To resolve conflicts in the sldemo_mdlref_counter.slx model:

1 Examine the Three-Way Merge report for the sldemo_mdlref_counter.slx model.

• The summary table in the right bottom corner shows that three items in the report require
your attention, two conflicts and one manual merge. The table also shows that no changes are
filtered out that require your attention.
• In the report, the tool colors conflicted items in red. For more information about colors and
conflict classification in the report, see Three-Way Merge Tool.

21-25
21 Compare Simulink Models

2 Examine and resolve the first item that requires your attention. Click Next to navigate to the first
item.

a The tool selects the Name row under PortProperties. In the Target pane, the tool marks

the item as requiring a manual merge . This action means that the tool cannot perform
the change, and you must make the change in the Simulink Editor. For more information
about conflict classification, see Three-Way Merge Tool.

In this example, the report shows that your colleague changed the port name to previous,
which conflicts with the name you added, previous_output.
b The tool displays two models to the right of the report and highlights the differences in the
Simulink Editor. In this example, the tool highlights the Previous Output block in yellow.

By default, the tool opens the Theirs model on top and the Target model below. To configure
the tool to open different models to the right of the report, in the toolstrip, in Highlight
section, select one of the available configurations for Top Model and Bottom Model.

21-26
Resolve Conflicts in Models Using Three-Way Merge

c In the Simulink Editor, in the targetFile, change the name of the port from previous to
previous_output, then save the model.
d After you resolve the conflict using the Simulink Editor, in the Target pane, select the check

option to mark the item as resolved.


3 Examine and resolve the next item that requires your attention. Click Next to navigate to the
next item. Alternatively, select the next item in the report.

Tip Merge blocks before lines, and merge states and junctions before merging transitions. The
merge tool then attempts to connect all lines to blocks. See “Recommended Merge Order in
Models” on page 21-16.

21-27
21 Compare Simulink Models

a The tool selects the Name row under Scope. In the Target pane, the tool marks the item as
a conflict . This means that the tool can perform the change. The tool provides option

buttons next to the item.

In this example, the report shows that your colleague changed the scope name to Scope A,
which conflicts with the name you added, Scope.
b The tool displays two models to the right of the report and highlights the differences in the
Simulink Editor. In this example, the tool highlights the scope block in red with yellow
around the edges.

c Suppose you want to keep your change. In the Target pane, select the option button in the
Mine column.

The tool automatically marks the item as resolved by switching the conflict icon to a green
tick icon. The tool also colors the line in blue to indicate that the targetFile now contains
the Mine change.

21-28
Resolve Conflicts in Models Using Three-Way Merge

4 Examine and resolve the next item that requires your attention. Click Next to navigate to the
next item.

a The tool selects the Threshold row under Switch. In the Target pane, the tool marks the
item as a conflict . This action means that the tool can perform the change. The tool
provides option buttons next to the item.

In this example, the report shows that your colleague changed the switch Threshold value
to 0.4, a value that contradicts with your change.
b The tool displays two models to the right of the report and highlights the differences in the
Simulink Editor. In this example, the tool highlights the switch block in red with yellow
around the edges.

21-29
21 Compare Simulink Models

c Suppose you want to restore the value in the Base file. In the Target pane, select the option
button in the Base column.

The tool automatically marks the item as resolved by switching the conflict icon to a green
tick icon. The tool also colors the line in orange to indicate that the targetFile now contains
the Base change.

5 Examine the summary table. The table now shows that you resolved all the items that require
attention.

6 To save the target file with all your merges and mark the conflicted file as resolved in the source
control tool, click Accept and Close.

Resolve Conflicts in sldemo_mdlref_basic

To resolve conflicts in the sldemo_mdlref_basic.slx model:

1 Examine the Three-Way Merge report for the sldemo_mdlref_basic.slx model. The summary
table in the right bottom corner shows that one conflict in the report requires your attention.
2 Examine and resolve the conflict. Click Next to navigate to the item that requires your attention.

a The tool selects the Value row under C5. In the Target pane, the tool marks the item as a
conflict . This action means that the tool can perform the change. The tool provides option
buttons next to the item.

21-30
Resolve Conflicts in Models Using Three-Way Merge

In this example, the report shows that your colleague changed the Constant block Value to
90, a value that contradicts with your change.
b The tool displays two models to the right of the report and highlights the differences in the
Simulink Editor. In this example, the tool highlights the constant block in red with yellow
around the edges.

c Suppose you want to keep your change. In the Target pane, select the option button in the
Mine column.

The tool automatically marks the item as resolved by switching the conflict icon to a green
tick icon. The tool also colors the line in blue to indicate that the targetFile now contains
the Base change.
3 Examine the summary table. The table now shows that you resolved all the items that require
attention.
4 To save the target file with all your merges and mark the conflicted file resolved in the source
control tool, click Accept and Close.

21-31
21 Compare Simulink Models

Perform Last Checks

When you resolve the conflicts in both model files, the Git status now shows as Modified.

Before you commit the resolved model files to source control, perform a final review by comparing
the merge changes against the current branch. You should always qualify merged models by verifying
simulation results or running tests.

For an example on resolving conflicts using three-way merge in a MATLAB projects under source
control, see “Resolve Conflicts in Project Using Simulink Three-Way Merge”.

If you are using source control outside of MATLAB, you can customize external source control tools to
use MATLAB comparison and merge tools. For instructions, see “Customize External Source Control
to Use MATLAB for Diff and Merge” on page 19-67.

See Also
Three-Way Merge Tool

Related Examples
• “Resolve Conflicts in Project Using Simulink Three-Way Merge”

More About
• “Source Control in Projects”
• “Resolve Conflicts in Models Under Source Control” on page 21-17
• “Identify Order of Resolving Conflicts in Changeset” on page 21-22
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-32
Export, Print, and Save Model Comparison Results

Export, Print, and Save Model Comparison Results


You can save model comparison results as reports or workspace variables. If you have not yet run a
comparison analysis, see “Select Models to Compare” on page 21-4.

To save your comparison results in a report, in the Comparison toolstrip, select Publish and choose
the report format: HTML, Word, or PDF.

Alternatively, you can publish a comparison report to a file using the visdiff function.

If you apply filters to the comparison results, the saved report contains only filtered results.

The report also shows side by side screenshots of the modified models. Starting in R2023a, you can
disable screenshots in comparison reports. Before you publish the comparison results, in the
Command Window, enter these commands.

s = settings().comparisons.slx.DisplayReportScreenshots;
s.TemporaryValue = false;

To export the comparison results to the MATLAB base workspace, in the Comparison toolstrip,
select Publish > Workspace Variable and specify the variable name.

Saving the model comparison results as a workspace variable creates an xmlcomp.Edits object in
the workspace. The xmlcomp.Edits object contains information about the comparison, including file
names, filters applied, and hierarchical nodes that differ between the two files.

To create an xmlcomp.Edits object at the command line without opening the Comparison Tool,
enter this command.

edits = slxmlcomp.compare(modelname_A,modelname_B)

More About xmlcomp.Edits Properties

Property of xmlcomp.Edits Description


Filters Array of filters — Every filter has two properties,
Name and Value.
LeftFileName File name of left model.
LeftRoot xmlcomp.Node object that represents the root of
the left tree.
RightFileName File name of right model.
RightRoot xmlcomp.Node object that represents the root of
the right tree.
TimeSaved Time when results are exported to the
workspace.
Version MathWorks release-specific version number of
xmlcomp.Edits object.

Property of xmlcomp.Node Description


Children Array of xmlcomp.Node references to child
nodes, if any.

21-33
21 Compare Simulink Models

Property of xmlcomp.Node Description


Edited Boolean — If Edited = true, then the node is
either inserted, deleted, or part of a modified
matched pair.
Name Name of node.
Parameters Array of parameters — Every parameters has two
properties, Name and Value.
Parent xmlcomp.Node reference to parent node, if any.
Partner If matched, Partner is an xmlcomp.Node
reference to the matched partner node in the
other tree. Otherwise, Partner is empty [].

See Also
visdiff | Comparison Tool

Related Examples
• “Compare and Merge Simulink Models Containing Stateflow”

More About
• “Understand Simulink Model Comparison Changes” on page 21-7
• “Port or Restore Model Changes in Comparison Report” on page 21-14
• “Compare Revisions” on page 19-47
• “Source Control in Projects”
• “Customize External Source Control to Use MATLAB for Diff and Merge” on page 19-67

21-34
Compare Model or Project Templates

Compare Model or Project Templates

You can compare Simulink templates (SLTX files) using the Comparison Tool. In the Current Folder
browser, select the template files. Right-click and select Compare Selected Files/Folders.

• When you compare two model template files, the comparison report shows differences in template
properties. From the comparison report, you can also open a new report to compare the Simulink
models.

• To view differences in the parameters, such as the description or modified date, click
Template Properties.
• To open a Simulink model comparison report where you can investigate changes in models,
next to Model, click Compare.
• When you compare two project template files, the comparison report shows differences in
template properties and project metadata. From the comparison report, you can open a new
report to investigate the project file and folder differences.

• To view differences in the parameters, such as the description or modified date, click
Template Properties.
• To view metadata differences such as label changes, expand the Project Metadata node.
• To open a folder comparison where you can investigate what changed in the project root folder,
next to Project Files, click Compare.

See Also

Related Examples
• “Review Changes in Simulink Models” on page 21-2
• “Compare Folders and Zip Files”
• “Create Templates for Standard Project Settings” on page 16-36
• “Create Template from Model” on page 4-2

21-35
21 Compare Simulink Models

Set Up Simulink Diff and Merge in CI/CD Pipeline


You can use Simulink diff and merge in a continuous integration/continuous deployment (CI/CD)
pipeline to track, review, and validate changes to your models.

This diagram illustrates a typical collaboration workflow. A developer makes changes locally and
prequalifies the changes. To make the changes available to other contributors, the developer creates
a merge request and sends the changes for review. Typically, a merge request is configured to trigger
several validation steps including running tests and checking for conflicts in files. The developer
addresses the feedback from reviewers, fixes test failures, if any, and resolves flagged conflicts before
finalizing the merge request.

This general outline describes how to incorporate Simulink comparison and merge tools in your
CI/CD pipeline.

1 Use a version control system such as Git to track your work. Commit your source files, including
your Simulink models, to allow tracking changes over time.
2 Set up a CI pipeline using a CI/CD platform or tool such as GitHub, GitLab, or Jenkins to run
MATLAB code and Simulink models as part of your automated tasks. For more information about
available integrations, see “Continuous Integration with MATLAB on CI Platforms”.
3 Configure your pipeline to automatically trigger Simulink comparison regularly or for specific
events. For example, you can configure your pipeline to automatically perform a comparison and
generate diff reports on every merge or pull request. You can follow this pseudo-code in your
pipeline.

for every SLX or MDL model in the changeset do


if ancestor exists do
get ancestor of model
diff model to ancestor
generate and save diff report
if diff filters available do
specify which filter to apply in the report
end_if
end_if
end_for

21-36
Set Up Simulink Diff and Merge in CI/CD Pipeline

For an example that provides MATLAB scripts and YAML files to generate diff reports and attach
them to a GitHub pull request, see “Attach Model Comparison Report to GitHub Pull Requests”
on page 21-38 and watch Simulink Model Comparison for GitHub Pull Requests (4min 46sec).
4 Configure your pipeline to automerge models when possible. Enabling Simulink automerge
ensures smoother branch merges.

If your files are under Git source control, you can use the mlAutoMerge Git plugin to
automatically merge branches that contain changes in different subsystems, Stateflow charts,
and configuration sets in the same SLX file. For more information, see “Automatically Merge
Models” on page 19-27.

Tip If you are not working in different subsystems, conflicts may occur. If a merge request flags
merge conflicts, you must resolve the conflicts locally using the Three-Way Merge Tool. For an
example on how to resolve conflicts, see “Resolve Conflicts in Models Using Three-Way Merge”
on page 21-24.

For best practices on how to minimize the occurrence of conflicts in models, see “Resolve
Conflicts in Models Under Source Control” on page 21-17.
5 Store the comparison report in a location that can be easily accessed and reviewed as part of the
CI/CD pipeline. You can automate this process by adding a step in your pipeline to attach the diff
reports. For example, you can attach the comparison report to the merge or pull request. For
more information, see “Attach Model Comparison Report to GitHub Pull Requests” on page 21-
38.
6 Implement the feedback from reviewers, validate your changes, and verify the results of any
checks your pipeline is running. For example, you typically configure a merge request to trigger
several validation steps, including running tests and checking for conflicted files. If a merge
request flags any test failures or merge conflicts, you must fix the test failures and resolve the
conflicts locally using the Three-Way Merge Tool. When you submit your fixes, the checks in your
merge request run again. When all results are clean, the merge request can be accepted.

See Also
visdiff | Comparison Tool | Three-Way Merge Tool

More About
• “Attach Model Comparison Report to GitHub Pull Requests” on page 21-38
• “Automatically Merge Models” on page 19-27
• “Resolve Conflicts in Models Using Three-Way Merge” on page 21-24
• “Continuous Integration with MATLAB on CI Platforms”

21-37
21 Compare Simulink Models

Attach Model Comparison Report to GitHub Pull Requests


In this section...
“Prerequisites” on page 21-38
“Attach Diff Reports Using GitHub Actions” on page 21-38
“Notes” on page 21-39

Automate the generation of Simulink model diffs for GitHub pull requests and push events using
GitHub Actions. Automatically attach the comparison reports to the pull request or push event for
easy viewing outside of MATLAB and Simulink. Watch Simulink Model Comparison for GitHub Pull
Requests (4min 46sec).

Prerequisites
1 Download the MATLAB code and YAML files from https://github.com/mathworks/Simulink-Model-
Comparison-for-GitHub-Pull-Requests.
2 Ensure that GitHub Actions is enabled for your repository.
3 The actions, defined in the Diff_runTests_push.yml and
Diff_runTests_pullrequest.yml files, use a self-hosted runner. Using a self-hosted runner
enables you to keep your repository private. To add a self-hosted runner to your repository, follow
the instructions at https://docs.github.com/en/actions/hosting-your-own-runners.
4 Ensure that you have MATLAB and Simulink installed on the self-hosted runner you are using.

Alternatively, if you prefer to use a GitHub-hosted runner, use the actions defined in the
githubrunner_push.yml and githubrunner_pullrequest.yml files instead.

Attach Diff Reports Using GitHub Actions


GitHub Actions allows you to automate workflows that you define in YAML files. This example shows
how to set up the workflows to be triggered on push and pull request to the main branch on GitHub.
These workflows use the MATLAB code files to:

1 Get the list of modified model files and their ancestors using Git commands.
2 Compare every modified model to its ancestor and publish an HTML comparison report using
visdiff. To peer review changes, use the DOCX file format instead of HTML when publishing
the reports. Using DOCX files allows reviewers to leave detailed comments on different blocks or
parameters.
3 Upload all model comparison reports to the job when it is complete.
4 Run all the project tests.

To set up the workflows on GitHub:

1 Add the MATLAB code files to your repository. Select Add file > Upload and upload the files.
Then, click Commit Changes.
2 Create the new workflows:

a On the Actions tab, click set up a workflow yourself.

21-38
Attach Model Comparison Report to GitHub Pull Requests

GitHub stores all workflows in the .github/workflows folder. If it does not exist already,
GitHub automatically creates the .github/workflows folder in your repository.
b Copy the content of one of the YAML files you downloaded, for example,
Diff_runTests_pullrequest.yml, and paste it in the Edit new file field.
c Rename the file and click Start commit > Commit new file.
d Repeat the steps for the second YAML file you downloaded.

Alternatively, if you already have a .github/workflows folder in your repository, upload the
YAML files to .github/workflows and commit the changes.

Now, when you push your commits to the main branch or create a pull request to merge a
development branch with main, it triggers the workflows you set up. When the job is successful,
contributors and reviewers can access the model comparison reports in the Artifacts section of each
job.

Notes
• Including screenshots in the comparison report requires your runner to have a display. On Linux
operating systems, if your runner does not have a display, you can use one of the following
workarounds in your YAML files:

• Start a display server before the "Compare Models to Ancestors" step. For an example, see the
"Start Display Server" step in the githubrunner_pullrequest.yml file.
• Use xvfb-run to run commands on a display server that implements the X11 display server
protocol.
• Starting in R2022b, you can use the Comparison Tool to generate comparison reports with no
screenshots when running jobs on a no-display machine.

See Also

Related Examples
• Simulink Model Comparison for GitHub Pull Requests (4min 46sec)
• Use MATLAB with GitHub Actions
• “Review Changes in Simulink Models” on page 21-2

21-39
22

Design Evolution Management

• “Get Started with Design Evolution Manager” on page 22-2


• “About Design Evolutions” on page 22-4
• “Manage Evolutions and Evolution Trees” on page 22-6
• “Inspect Properties, Compare, and Merge Evolutions” on page 22-11
• “Use Design Evolution Manager with the Fixed-Point Tool” on page 22-13
22 Design Evolution Management

Get Started with Design Evolution Manager


Projects help you organize your work for large modeling projects. You can manage all the files you
need in one place, including all MATLAB and Simulink files, and any other file types you need, such as
data, requirements, reports, spreadsheets, tests, or generated files.

Design Evolution Manager helps you to manage different versions of a project. Evolutions capture the
state of a project at key stages in your design process. Evolutions are organized within an evolution
tree hierarchy. The relationships between evolutions and the metadata you associate with different
components of an evolution tree help you model your design process, test alternative solutions, and
understand the rationale of certain design decisions.

Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.

Key Terms and Concepts


• An evolution is a snapshot of the files in a project. Evolutions are stored separately within the
project by the Design Evolution Manager app.
• An evolution tree is a collection of related evolutions, organized in a tree structure. A child
evolution is created from a parent evolution.
• The baseline evolution is the reference point for the evolution tree. When you create a new
evolution tree, the Design Evolution Manager app creates a baseline evolution that captures a
snapshot of the original state of your project.
• The current files indicator marks the evolution whose files are currently open in the project.

You can get the version of files from any evolution in the tree to put them into the current project.
• The record indicator marks the active evolution tree and the active evolution in this tree. The
active evolution automatically records changes you make to files in the current project.

Non-active evolution trees can be viewed and their metadata updated, but do not record changes
to project files.

You can lock an evolution to prevent changes to project files from being recorded to the
evolution. Metadata, such as the name of the evolution and notes, can still be edited.

If you lock the active evolution, it will no longer record changes. You can either create a new
active evolution or the Design Evolution Manager app will automatically create one for you when
you make a change in the project.

Example Evolution Tree


This is an example of a small evolution tree. The tree starts with a project captured in the Baseline
evolution. Evolution 1 and Evolution 2 capture two alternative solutions based on the Baseline
evolution. Evolution 3 is the active evolution. Evolution 3 captures further improvements on Evolution
2.

The Design Evolution Manager app allows you to capture notes for the evolution tree, for each
evolution within the tree, and for each connector between two evolutions. At any time, you can select

22-2
Get Started with Design Evolution Manager

an evolution to see the files and notes captured in that evolution. As you work, you can compare files
from any two evolutions in the evolution tree.

See Also
“About Design Evolutions” on page 22-4 | “Manage Evolutions and Evolution Trees” on page 22-6
| “Inspect Properties, Compare, and Merge Evolutions” on page 22-11

Related Examples
• “Use Design Evolution Manager with the Fixed-Point Tool” on page 22-13

22-3
22 Design Evolution Management

About Design Evolutions


Design evolutions help you model and analyze your engineering process. A design evolution is a
snapshot of all files included in a project. When developing a new design or troubleshooting an
existing design, you may add or remove files from the design, or create different versions of files in
your design. By creating evolutions at key stages in your design process, you can manage and
compare different versions of a design during the course of your work. The relationships between
evolutions and the metadata associated with evolutions help you to understand the big-picture
trajectory of your design process, including why certain design decisions were made.

Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.

Evolutions and Evolution Trees


Evolutions are alternative versions of project files that you have stored, similar to a revision control
submission. An evolution is a snapshot of a particular version of your files contained in a project.
Each evolution you create has metadata associated with it where you can add additional descriptive
information about the version of the design that is captured in the evolution. An evolution tree is a
visual representation of a collection of related but different versions of your design stored as
evolutions.

This figure shows an example of a small evolution tree. An evolution tree has two important elements:

• Evolution nodes, visualized as boxes in the evolution tree.


• Connectors between evolution nodes, visualized as arrows between evolutions. Connectors
contain information about the changes between the design versions.

22-4
About Design Evolutions

Evolutions have parent-child relationships in the evolution tree. The first evolution you create is the
Baseline evolution, which is the reference point for the evolution tree. The Baseline evolution is
parent to all following evolutions. Each subsequent evolution you create is a child of the previous
evolution. A child evolution represents a change or set of changes made to the design since its parent
evolution was saved. The connectors between evolutions contain metadata about the changes that
have occurred between the parent evolution and the child evolution. You can create branches in your
evolution tree by having multiple child evolutions under a single parent evolution.

The shape of the evolution tree visually maps to your design process. Your evolution tree may be
linear, indicating that each evolution is a continuation of the same design path. Or, your evolution tree
may branch if you explore multiple design directions within one evolution tree. You can use evolutions
and branches in the evolution tree to explore different design ideas, perform trade studies, or
troubleshoot an existing design. Evolutions can be used to record successful design directions and
also to keep a record of unsuccessful design ideas. At any point, you can trace back through your
evolution tree to understand why particular changes were made to the design.

See Also
“Manage Evolutions and Evolution Trees” on page 22-6 | “Inspect Properties, Compare, and Merge
Evolutions” on page 22-11

Related Examples
• “Use Design Evolution Manager with the Fixed-Point Tool” on page 22-13

22-5
22 Design Evolution Management

Manage Evolutions and Evolution Trees


The files you want to organize and analyze with evolutions must be contained in a single project. For
more information about creating a project, see “Create a New Project from a Folder” on page 16-18.

To open the Design Evolution Manager, first open the project containing your files. If the project
contains existing evolution trees, the project opens the version of files from the last previous active
evolution. To open the app, from the Projects tab, under Tools, click the Design Evolution Manager

icon .

Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.

Create Evolution Tree


When you open the Design Evolution Manager for the first time, or when you click the New Tree
button in the Design Evolution Manager toolstrip, the Create New Evolution Tree dialog box guides
you through the process of creating a new evolution tree. Select the project containing your design
files and give the evolution tree a name. Optionally, add notes about the evolution tree.

The app creates a new evolution tree containing the Baseline evolution. The Baseline evolution
contains a copy of all files in the project in their current state. The current files indicator shows
that the version of files captured in the Baseline evolution are open in the project.

22-6
Manage Evolutions and Evolution Trees

The evolution tree you create is saved as part of the project. All of your design files must be contained
within a single project.

A project can contain multiple evolution trees. Use the Change Tree and Delete Tree buttons to
manage evolution trees in your project. You can also right-click the canvas of the evolution tree to
access these options.

22-7
22 Design Evolution Management

Create Evolution

By default, the Baseline evolution is locked , meaning that this evolution will not record changes
to files in the current project. This setting preserves the state of the Baseline evolution at the time
it was created. Because the Baseline evolution is locked, when you make changes to project files,
the Design Evolution Manager automatically creates a new child evolution to record your changes as
you work. Alternatively, you can click Create Evolution to create a new child evolution.

After the new evolution is created, the current files indicator moves to the new evolution to indicate
that these are the version of files currently open in the project. The record indicator marks the
active evolution. Any changes you make to project files are recorded to the active evolution.

Lock Evolution

When you have finished making changes in an evolution, you can lock the evolution to prevent the
evolution from recording further changes you make to project files. If you continue making changes
after locking an evolution, the Design Evolution Manager automatically creates a new child evolution
to record your changes. Parent evolutions are always locked.

Get Evolution
At any point in the design process, you can return to a previous version of your design that was saved
in an evolution. Select the evolution to which you want to return, then click Get Evolution. The
Design Evolution Manager gets that version of the design files into the project. The evolution tree
indicates this action visually by moving the current files indicator to the selected evolution. You can
then continue working with this previous version of the design files. If the evolution you get is
unlocked, it becomes the active evolution. If the evolution you get is locked, the app will create a
child active evolution when you start making changes to files in the project.

When you get an evolution, the app restores the previous saved state of the project files including any
added or removed files. For example, assume you have an evolution tree where Evolution 1
contains the file foo.m, but in your active evolution you delete this file from disk and remove it from
the project. If you get Evolution 1, the app restores the file foo.m to the disk and re-adds the file
to the project.

22-8
Manage Evolutions and Evolution Trees

Delete Evolutions
To delete an evolution, first select the evolution, then click Delete Evolution. The app deletes the
evolution. If the deleted evolution had one child node, the child is reparented to the next-higher
evolution in the tree. You cannot delete a parent evolution that has multiple child evolutions.

To delete a branch of the evolution tree, select the parent evolution and click Delete Branch. The
app deletes the selected parent evolution and all child evolutions.

Make Tree Active


You can have multiple evolution trees in a project hierarchy. Use the Tree Browser to navigate and
view different trees saved in the project hierarchy. The record indicator marks the active tree,
which contains the active evolution. To make a tree active, select the tree and click Make Tree
Active.

Managing Changes Made Outside the App

When you make changes to project files with the Design Evolution Manager app open, your changes
are automatically recorded to the active evolution. If you make changes to project files when the
Design Evolution Manager app is closed, the app does not actively record these changes. The next
time you open the Design Evolution Manager, you must tell the app how to handle these changes.

After reopening the Design Evolution Manager and selecting an evolution tree, the Unsaved Project
Changes dialog box presents options for recording unsaved changes in an evolution:

• Update — Update the selected evolution with the changes made to project files when the app was
closed. You can only update unlocked evolutions.
• Create Child — Create a child evolution under the selected evolution to record the changes made
to project files when the app was closed. You can create a child evolution under any evolution in
the evolution tree.
• Cancel — Changes you made to project files when the Design Evolution Manager was closed are
not recorded by the app.

22-9
22 Design Evolution Management

See Also
“About Design Evolutions” on page 22-4 | “Inspect Properties, Compare, and Merge Evolutions” on
page 22-11

Related Examples
• “Use Design Evolution Manager with the Fixed-Point Tool” on page 22-13

22-10
Inspect Properties, Compare, and Merge Evolutions

Inspect Properties, Compare, and Merge Evolutions


Use the Property Inspector pane of the Design Evolution Manager to inspect properties of the
evolution tree, evolutions, and the connectors between evolutions and to compare evolutions.

Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.

Inspect Properties of Evolution Tree, Evolutions, and Connectors


Select an evolution to display properties of the evolution.

Use the Property Inspector pane to:

• Rename the evolution


• View the files that are stored in the evolution
• Enter notes about the evolution

Select the evolution tree canvas to display properties of the evolution tree. Use the Property
Inspector pane to:

• Rename the evolution tree


• Enter notes about the evolution tree

Select a connector between evolutions to display what has changed between the parent and child
evolution. Use the Property Inspector pane to:

• Enter notes
• View files that have been added, deleted, or changed between the parent and child evolution

22-11
22 Design Evolution Management

Compare and Merge Evolutions


You can launch the Simulink Model Comparison Tool directly from the Design Evolution Manager to
compare changes between evolutions.

To compare two evolutions, select an evolution of interest. In the File Explorer section of the
Property Inspector pane, select an evolution to compare to. The Property Inspector displays a list
of files that have been added, deleted, or changed between the two evolutions. Select one or more
files to compare, then click Compare Files to launch the Comparison Tool. You can compare any two
files in different evolutions, even if the files have different names.

When you compare the active evolution to another evolution in the evolution tree, you can use the
Comparison Tool to merge differences from an evolution into the active evolution.

See Also
“About Design Evolutions” on page 22-4 | “Manage Evolutions and Evolution Trees” on page 22-6

Related Examples
• “Use Design Evolution Manager with the Fixed-Point Tool” on page 22-13

22-12
Use Design Evolution Manager with the Fixed-Point Tool

Use Design Evolution Manager with the Fixed-Point Tool

Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license. This example also requires a Fixed-Point Designer license.

Use Design Evolution Manager with Fixed-Point Tool

This example shows how to use the Design Evolution Manager to manage different design versions
while using the Fixed-Point Tool and the Lookup Table Optimizer to convert a floating-point model to
use fixed-point data types. While this example demonstrates the fixed-point conversion use case, you
can use the Design Evolution Manager to organize and analyze any work in which you create
different versions of files in your design.

In this example, the Fixed-Point Tool creates many versions of a design, including:

• The original floating-point model


• The model prepared for fixed-point conversion
• Various fixed-point versions of the model

Managing, analyzing, and moving between these different versions of a design can be challenging.
The Design Evolution Manager helps you to organize different versions of the same design,
understand the relationships between different versions, compare different versions, and store and
review notes and data about the versions.

This example shows how to:

1 Convert your model files into a project.


2 Create an evolution tree to visually organize the different versions of your design that you store
in evolutions.
3 Create a baseline evolution to store a snapshot of the initial state of the files in the project.
4 Convert the model to use fixed-point data types. Create evolutions to store snapshots of the
design and notes you take at key points in the design process.
5 Compare evolutions and review your notes to understand changes that were made to the model,
then choose which version of the design best meets your requirements.
6 Generate a report that summarizes the evolution tree.

Set Up Example Files

To use the Design Evolution Manager, all of your design files must be contained in a single project.

Create and open a working copy of the project example files. The MATLAB® software copies the files
to an example folder so that you can edit them.

setupDEMExample

The setupExample helper function creates and opens a project called DEM_FPT_Example, which
contains a controller_subsystem model to convert to fixed point and a controller_harness
model for testing.

22-13
22 Design Evolution Management

Create New Evolution Tree

An evolution tree is a visual representation of a collection of related but different versions of your
files, stored as evolutions. Create a new evolution tree to keep track of different design versions
created during conversion to fixed point.

1. On the Project tab, in the Tools section, click the button arrow, then click the Design Evolution
Manager icon .

2. In the Create New Evolution Tree dialog box, under Evolution Tree Name, enter Convert
Controller to Fixed Point. You can enter optional notes under Evolution Tree Notes.

3. Click Create to continue.

The Design Evolution Manager creates a new evolution tree. The Tree Browser pane shows the
Convert Controller to Fixed Point evolution tree in the current project. The record icon
shows that this evolution tree is active.

The evolution tree contains the Baseline evolution, which is a copy of all files in the project in their
current state. The current files indicator shows that the Baseline evolution is the version of files
that are currently open in the project. The Baseline evolution is locked by default to prevent
changes you make to project files from being recorded to this evolution. When you start making
changes to project files, the Design Evolution Manager automatically creates a new child evolution
under the Baseline evolution to record your changes as you work.

22-14
Use Design Evolution Manager with the Fixed-Point Tool

Prepare for Fixed-Point Conversion

The first step in the fixed-point conversion process is to use the Fixed-Point Tool to prepare the
controller_subsystem model for conversion to fixed point. The preparation step creates a new
version of the model files that you may want to reference and return to later.

1. From the project, open the controller_harness model.

2. Open the Fixed-Point Tool. On the Simulink® Apps tab, under Code Generation, click the Fixed-
Point Tool icon.

3. In the tool, select New > Optimized Fixed-Point Conversion.

4. Under System Under Design (SUD), select controller_subsystem as the system to convert to
fixed point.

5. In the toolstrip, click Prepare.

6. When the preparation checks are complete, save the changes to the controller_subsystem and
controller_harness models.

22-15
22 Design Evolution Management

Create Evolution

Use the Design Evolution Manager to check the state of your design and save the prepared model in
a new evolution.

The shape of the evolution tree has changed. Because the Baseline evolution is locked, the Design
Evolution Manager automatically created the Untitled evolution as a child of the Baseline
evolution to record the changes made to project files in the previous step.

1. In the Property Inspector pane, name the new evolution Prepared.

2. On the evolution tree, select the connector between the Baseline evolution and the Prepared
evolution. In the Property Inspector pane, the File Explorer shows that the
controller_subsystem.slx and controller_harness.slx model files have changed.

3. In the Notes field for the connector, add a note that these file changes are the result of running the
preparation step in the Fixed-Point Tool.

22-16
Use Design Evolution Manager with the Fixed-Point Tool

Inspect Changes Between Evolutions

Use the Comparison Tool to compare the version of the files stored in the Baseline evolution to the
version of the files stored in the Prepared evolution.

1. Select the connector between the Baseline and Prepared evolutions.

2. On the Property Inspector pane, in the File Explorer section, select the
controller_subsystem.slx file. Click Compare Files.

22-17
22 Design Evolution Management

The Comparison tool launches. The version of the model stored in the Baseline evolution is shown
in orange, and the version of the model stored in the Prepared evolution is shown in blue. The
comparison shows that the Exp block, which is not supported for fixed-point conversion, was
automatically isolated during the prepare step in the Fixed-Point Tool.

22-18
Use Design Evolution Manager with the Fixed-Point Tool

3. In the Design Evolution Manager, select the Prepared evolution. In the Property Inspector pane,
add a note indicating that the Exp block has been isolated and needs to be replaced later.

4. Now that the system is prepared for fixed-point conversion and the changes have been verified,
lock the evolution to prevent any further changes from being recorded to the Prepared evolution. In
the tree, select the Prepared evolution, then click Lock Evolution in the toolstrip.

Convert to Fixed-Point and Store in Evolution

Use the Fixed-Point Tool to convert the controller model to fixed point. Use the Design Evolution
Manager to track your work.

1. In the Fixed-Point Tool, from the Workflow Browser pane, select the Setup window.

2. Under Signal Tolerances, set Relative Tolerance for the Sum:1 and Sum1:1 signals to 0.15.

3. Click Optimize Data Types.

The Fixed-Point Tool determines optimized fixed-point data types for the controller_subsystem
based on the specified tolerances. The best solution found has a cost of 416. This solution is
automatically applied to the controller_subsystem model.

4. To open the Simulation Data Inspector, click Compare. Visually confirm that the solution meets the
specified tolerances for the logged signals.

5. Save the changes to the model.

22-19
22 Design Evolution Management

6. In the Design Evolution Manager, these changes were automatically recorded to the new
Untitled evolution, which is a child of the Prepared evolution.

7. Name the new evolution Converted 15%.

8. Add a note to the evolution that the total cost of this design is 416.

Add Conversion Script to the Evolution

In addition to storing the fixed-point version of the model in an evolution, you can also add a copy of
the script used to convert the model to fixed point to the Converted 15% evolution you just created.

1. Export the fixed-point conversion script. In the Fixed-Point Tool, click Export Script.

The Fixed-Point Tool exports fxpOptimizationScript.m to the base workspace.

2. Add the fixed-point conversion script to the project. In MATLAB, in the Current Project pane,
right-click fxpOptimizationScript.m and select Add to Project.

4. Confirm that the file was added to the evolution. Select the connector between the Prepared
evolution and the Converted 15% evolution.

In the Property Inspector pane, the File Explorer shows that the fxpOptimizationScript.m file
was added and that the controller_harness.slx and controller_subsystem.slx model files
were changed between the Prepared and Converted 15% evolutions.

5. Lock the Converted 15% evolution.

22-20
Use Design Evolution Manager with the Fixed-Point Tool

Create Branch in Evolution Tree to Explore Different Fixed-Point Types

Next, try the optimized fixed-point conversion workflow with a larger tolerance. Use the version of
the files saved in the Prepared evolution to start from the version of the model files already
prepared for fixed-point conversion. Then, run the optimization process again and track your work in
a new branch in the evolution tree.

1. Return to the floating-point version of the design after it was prepared for fixed-point conversion.
In the Design Evolution Manager, select the Prepared evolution. Click Get Evolution.

The dialog box indicates that the fixed point conversion script, which was not present in the
Prepared evolution, will be removed from the active project area.

2. Click OK to continue.

The files in the project are now the version of the design files as they previously were after you
prepared them with the Fixed-Point Tool. The shape of the evolution tree has changed, showing that
the next evolution created will be a child of the Prepared evolution.

3. Use the Fixed-Point Tool to convert the controller_subsystem to fixed point as before. This
time, set the Relative Tolerance for both of the logged signals to 0.20.

Because you loaded the version of the model files from the Prepared evolution, you do not need to
run the prepare step in the Fixed-Point Tool again.

4. Click Optimize Data Types to run the conversion.

The best solution found has a total cost of 392.

5. Save the changes to the model.

6. Save this version of the design in a new evolution named Converted 20%.

7. Export the fixed-point conversion script and add it to the evolution you just created.

8. Lock the Converted 20% evolution.

9. Add a note to the Converted 20% evolution that the total cost of this version of the design is 392.

22-21
22 Design Evolution Management

Compare Alternate Versions of Design

The final step of fixed-point conversion is to replace the Exp block with a lookup table approximation.
The fixed-point versions of the design stored in the Converted 15% and Converted 20% evolutions
both produced acceptable results, with the logged signals meeting all specified tolerances. You can
review your notes to confirm that the costs of these designs are 392 and 416, respectively. Because
the Converted 20% version of the design has a lower cost, choose this branch of the evolution tree
to continue your design work.

Replace Unsupported Block with Lookup Table and Save in Evolution

From the Converted 20% version of the design, replace the Exp block with a lookup table
approximation.

1. Get the Converted 20% evolution into your active project area and open the
controller_harness model.

2. In the model, navigate to the blue exponential subsystem under controller_harness > Model
(controller_subsystem) > Exp. Select the Exp block that was isolated in the preparation stage of
fixed-point conversion.

22-22
Use Design Evolution Manager with the Fixed-Point Tool

3. Open the Lookup Table Optimizer. On the Simulink Apps tab, under Code Generation, click the
app icon.

4. In the Lookup Table Optimizer, select Simulink block or subsystem. Click Next.

5. Confirm that the Simulink block path is controller_subsystem/Exp/ReplicaOfSource. Click


Collect Current Values from Model, then click Next.

6. Click Optimize, then click Next.

7. Click Replace Original Function.

The Exp block is replaced with a lookup table approximation.

8. Save the changes to the model.

9. In the Design Evolution Manager, a new Untitled evolution was created as a child of the
Converted 20% evolution to record the changes made since the Converted 20% evolution was
locked. Name this new evolution Exponent Replaced.

10. Select the connector between the Converted 20% evolution and the Exponent Replaced
evolution. Add a note that the action taken between these evolutions was to use the Lookup Table
Optimizer to replace the Exp block with an optimized lookup table approximation.

22-23
22 Design Evolution Management

22-24
Use Design Evolution Manager with the Fixed-Point Tool

Review Design Process and Generate Report

The Design Evolution Manager shows the complete design process used in this example. Design
decisions are represented visually by the evolution tree. You can select individual evolutions or
connectors to review changes made during the design process and any notes you recorded.

To generate a pdf report that summarizes the evolution tree, click Generate Report . Enter a title
for the report and a name for the pdf file to be generated, then click Generate.

Generate Report

Close Project

Close the project. On the Project tab, in the Close section, click Close Project.

proj = currentProject;
close(proj);

See Also
Apps
Lookup Table Optimizer

Tools
Fixed-Point Tool

Related Examples
• “About Design Evolutions” on page 22-4
• “Convert Floating-Point Model to Fixed Point” (Fixed-Point Designer)
• “Optimize the Fixed-Point Data Types of a System Using the Fixed-Point Tool” (Fixed-Point
Designer)
• “Optimize Lookup Tables for Memory-Efficiency” (Fixed-Point Designer)

22-25
23

Large-Scale Modeling

• “Component-Based Modeling Guidelines” on page 23-2


• “Explore Types of Model Components” on page 23-4
• “Compare Capabilities of Model Components” on page 23-8
• “Define Interfaces of Model Components” on page 23-24
• “Configuration Management” on page 23-28
23 Large-Scale Modeling

Component-Based Modeling Guidelines

Component-based modeling helps organizations develop Simulink models that consist of many
functional pieces. Each Simulink component you create is a piece of your design that has an interface
and facilitates assembly of a system or a larger component. Useful model components have a well-
defined scope, perform functionality defined by requirements, and form part of a larger system.

Model components can enable:

• Team-based development — Reduce file contention and elaborate components independently


through well-defined interfaces.
• Reduced design complexity — Each component solves smaller problems.
• Component reuse — Reuse algorithms and environment models within a project and across
multiple projects.
• Unit testing — Eliminate retesting for unchanged components and reduce the cost of verification.
• Performance benefits that scale — Reduce memory usage and the time required to load and
simulate models.
• Component variants — Choose among multiple implementations of a component.
• Intellectual property protection — Limit functionality and content visibility for components that
you share with third parties.

Should You Create Model Components?


Considering the work required to define and manage components, you should use component-based
modeling only when the benefits outweigh the cost.

Separating an existing Simulink model into components is analogous to taking a large piece of code
(C, Java, or MATLAB code) and breaking it down into multiple functions. The conversion can require
significant effort and extensive modifications if the design is not modular from the beginning.

Considering model scalability and potential requirements upfront makes separating a Simulink model
into components easier. Identifying components upfront can help you avoid these difficulties:

• Poor component definition — The scope of subsystems that are grown over time can fail to meet
component requirements. For example, they might contain too much or too little functionality to
be reused, to generate code that integrates with legacy functionality, or to support hardware-in-
the-loop tests.
• Merge conflicts — If additional engineers begin to work on a model that was originally designed
for development by a single engineer, they can encounter time-consuming and error-prone
merges.
• Algebraic loops — If a single engineer develops a model from the bottom up, they are likely to
group blocks into subsystems as model complexity increases. The subsystems within the model
are likely visual groupings that do not affect model execution. When you make these subsystems
atomic, or convert them to referenced models, you can introduce unwanted algebraic loops that
are difficult to diagnose and fix.

Components are also useful when a design becomes too complicated for one person to manage all of
the details. For example, a complicated model can be a model that has:

23-2
Component-Based Modeling Guidelines

• Thousands of blocks
• Hundreds of logical decisions
• Multiple variant configurations of the same functionality

Projects and source control can help you manage components. For more information, see “What Are
Projects?” on page 16-3 and “Configuration Management” on page 23-28.

Define Model Components


1. “Explore Types of Model Identify Simulink components that align with your high-level
Components” on page 23-4 modeling requirements.
2. “Compare Capabilities of Investigate which types of model components meet your low-level
Model Components” on page 23- modeling requirements.
8
3. “Define Interfaces of Model Configure design attributes at interfaces and manage data for
Components” on page 23-24 model components.

23-3
23 Large-Scale Modeling

Explore Types of Model Components


Simulink provides multiple ways for you to organize your model into components. The different types
of components target different requirements.

As you define a component, consider these potential requirements.

• File contention — You can have larger components if only one person is working on each. If you
must share components between several people, you should divide the design into smaller logical
pieces. If multiple people must edit the same file, see “Port or Restore Model Changes in
Comparison Report” on page 21-14.
• Reusability — If you expect to use a group of blocks multiple times in a model, define the group of
blocks in a reusable component. By avoiding duplication, you make maintaining the model easier.
To refactor an existing model with duplication, see “Refactor Models to Improve Component
Reuse” (Simulink Check).
• Code generation — If you must generate standalone code for a physical component, such as a
digital controller, you should have one component that represents the physical component and has
a well-defined interface.
• Verification cost — If part of a model changes frequently and has high testing costs, you should
manage this part of the model as a component in a separate file. When components are defined in
separate files, you can control and trace changes using project source control. For more
information on source control, see “Configuration Management” on page 23-28.
• Simulation speed — Using different solvers for components with different numerical properties
can increase simulation speed. Similarly, grouping blocks based on their sample rate can increase
simulation speed. For more information, see Solver Profiler and “Improve Simulation Performance
Using Performance Advisor” on page 35-2.

Modeling requirements can influence the size of your components. For example, models with fewer
than 500 blocks are easier to test than larger models. However, simulation can be faster for model
hierarchies when referenced models contain more than 500 blocks.

Simulink Components
The different types of Simulink components serve a variety of modeling requirements.

Type of Definition Source of Contents Implementation in More Information


Compon Model
ent
Subsyste A subsystem is a None — Contents Subsystem block “Group Blocks into
m unique group of must be manually Subsystems” on page
blocks with a added to each 4-20
dynamic interface subsystem
that can inherit the
properties of its
inputs and outputs.

23-4
Explore Types of Model Components

Type of Definition Source of Contents Implementation in More Information


Compon Model
ent
Linked A linked subsystem Library file (.slx Subsystem block “Linked Blocks” on
subsyste is a linked instance or .mdl) that with a library link page 45-12
m of a Subsystem block contains the parent
that is stored in a library block, or
library. If you disable prototype block
the library link, each
instance of a linked
block can be unique.
Subsyste A subsystem Subsystem file (.slx Subsystem “Create and Use
m reference is a or .mdl) that Reference block Referenced
reference reference to a contains the Subsystems in
reusable group of referenced Models” on page 4-
blocks with a subsystem 38
dynamic interface
that can inherit the
properties of its
inputs and outputs.
Model A model reference is Model file Model block “Model Reference
reference a reference to a (.slx, .mdl, Basics” on page 8-2
model with a defined or .slxp) that
interface that contains the
specifies the referenced model,
properties of its which may be a
inputs and outputs. protected model

Simulink models can use any combination of these components. For example, to minimize file
contention for a large model, you can convert subsystems to referenced subsystems and models, both
of which are saved in separate files.

When you drag a subsystem reference or model reference from a library into a model, it directly
references the subsystem file or model file that defines its contents. It has a library link only when the
parent library block has a mask applied directly to it. Typically, you should use model masks, which
are saved in the referenced file and do not require a library link.

High-Level Component Selection Guidelines


Each of the types of model components has an ideal use case:

• Subsystem — Ideal for simplifying the block diagrams of other components


• Linked subsystem — Ideal for utilities and blocksets
• Subsystem reference — Ideal for reducing file contention and merge issues
• Model reference — Ideal for code reuse, unit testing, parallel builds, and large components

The ideal use cases are a subset of the possible use cases for each type of component. For example,
you can also reduce file contention and merge issues with a model reference, and you can also unit
test a subsystem.

23-5
23 Large-Scale Modeling

Tip If you expect a subsystem to grow, make it atomic so that it functionally groups the blocks. An
atomic subsystem behaves like a single block, or atomic unit, when the parent model executes.
Atomic behavior is necessary for you to convert a subsystem to a model reference.

For an overview of when to use different componentization techniques, see Component-Based


Modeling in Simulink (4 min, 28 sec).

This flow chart provides a starting point for choosing a component type.

This table provides the information from the flow chart and elaborates on how your choice of
component type can improve performance for components that are reused multiple times in a
hierarchy and contain many blocks.

23-6
Explore Types of Model Components

Component Use Type of Component


The component will require a defined interface or standalone Consider a model reference.
behavior.
The component will contain enough blocks and be reused enough Consider a model reference.
to benefit from accelerator mode simulation of referenced models.

Whether a model hierarchy benefits from accelerator mode


simulation of referenced models depends on many factors. For
each referenced model that simulates in accelerator mode,
Simulink must build and compile a simulation target. These targets
are reused for additional instances of the referenced model, which
accelerates simulation when the model hierarchy contains many
instances of the referenced model. If the referenced model is
unchanged, you can reuse its simulation target, which is stored in
a Simulink cache file (.slxc). For more information, see “Share
Simulink Cache Files for Faster Simulation” on page 8-70.
The component will be a published utility, which rarely changes. Consider a linked subsystem.
The component will be reused or managed in a source control Consider a subsystem reference.
system and will not require a defined interface, benefit from model
reference simulation targets, or be a published utility.
The component will not be reused or managed in a source control Consider a subsystem.
system.

Modeling Requirement Considerations


Before implementing a component based on the high-level guidelines, consider additional modeling
requirements. For example, if you require physical connections at the component interface, you must
use a subsystem, linked subsystem, or referenced subsystem. If you require intellectual property
protection, you must create a protected model, which can be referenced.

To determine whether a component meets your modeling requirements, see “Compare Capabilities of
Model Components” on page 23-8.

See Also
Subsystem | Model

More About
• “Group Blocks into Subsystems” on page 4-20
• “Create and Use Referenced Subsystems in Models” on page 4-38
• “Linked Blocks” on page 45-12
• “Model Reference Basics” on page 8-2
• “Map System Architecture to Simulink Modeling Environment” (Simulink Coder)
• “Map Embedded System Architecture to Simulink Modeling Environment” (Embedded Coder)

23-7
23 Large-Scale Modeling

Compare Capabilities of Model Components


Before you implement a piece of your system using a specific type of model component, consider
whether the type of component satisfies your modeling requirements. To identify which component
types to consider based on high-level guidelines and use cases, see “Explore Types of Model
Components” on page 23-4.

Popular modeling requirements can be grouped into these categories.

• “Collaboration” on page 23-8 — Avoid merge conflicts and share files with third parties.
• “Reuse” on page 23-12 — Define a component or its data once and reuse it.
• “Performance” on page 23-14 — Simulate and build components faster.
• “Testing and Certification” on page 23-18 — Verify the behavior of components.
• “Interface Design” on page 23-20 — Specify properties of inputs and outputs.
• “Custom Behavior” on page 23-21 — Configure how components behave and when they execute.

Collaboration
Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Separ Not supported Supported Supported Supported
ate
Files You save a subsystem You save the parent You save a referenced You save a referenced
in the same file as its library block of a subsystem in a model in a separate
parent. linked block in a separate file. file.
separate file.
To create or change a Using separate files Using separate files
subsystem, you must Using separate files helps to avoid file helps to avoid file
edit the parent file, helps to avoid file contention. contention.
which can lead to file contention.
contention and merge
problems.

23-8
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Stand Not supported Not supported Not supported Supported
alone
Behav Subsystems depend Same behavior as Same behavior as You can develop a
ior on models to provide subsystems. subsystems. referenced model
a context for independently from
execution. the models that use it.

To simulate a
referenced model as a
standalone model,
open the referenced
model as the top
model in a new
window. The
referenced model
must have the data
required to execute in
a standalone context.
For example, the
referenced model
must have the
variables and data
types that define
parameters and
signals.

23-9
23 Large-Scale Modeling

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Versio Not supported Supported Supported Supported
n
Contr You cannot directly You can place library You can place You can place model
ol and place subsystems in a files in a source subsystem files in a files in a source
Config source control control system. source control control system.
uratio system. system.
n To provide individual
Mana To reduce file version control for
geme contention and use each library block,
nt separate version use subsystem
control for each references and model
subsystem, use a references in the
subsystem reference. library. When you
drag these blocks
from the library into
your model, they
reference the
subsystem file or
model file.

Forwarding tables
allow you to map old
library blocks to new
versions of the blocks.

23-10
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Intell Not supported Not supported Not supported Supported
ectual
Prope Use model references Same behavior as Same behavior as Protected models
rty instead. subsystems. subsystems. obscure model
Prote contents, which can
ction be useful when
distributing models.

Creating a protected
model requires a
Simulink Coder
license. For more
information, see
“Protect Models to
Conceal Contents”
(Simulink Coder).

Using a protected
model does not
require a Simulink
Coder license. For
more information, see
“Reference Protected
Models from Third
Parties” on page 8-18.

23-11
23 Large-Scale Modeling

Reuse
Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Comp Not supported Supported Supported Supported
onent
Reuse While you can copy a You can link to the You can reference the You can reference the
subsystem to reuse it same parent library same subsystem same model multiple
in a model, the copies block multiple times multiple times in times in multiple
are independent of in multiple models multiple models models without
each other. without creating without creating creating copies. See
copies. copies. “Model Reuse” on
page 8-11.
Managing library
links adds some
overhead, such as
managing broken,
disabled, or
parameterized links.
Share Supported Supported Supported Supported
d
Data You can share data Same behavior as Same behavior as You can share data
among instances by subsystems. subsystems. among instances of
defining the data the referenced model
outside the by creating a data
component. For store inside the
example, by using a model. See “Share
data store in a Data Among
common parent Referenced Model
subsystem. Instances” on page 8-
40.

23-12
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Instan Supported Supported Not supported Supported
ce-
Specif Subsystem copies are When you edit a When you edit an When you edit an
ic independent of each parent library block, instance of a instance of a
Param other. the changes apply to referenced referenced model, the
eter the library file and subsystem, the changes apply to the
Values propagate to all changes apply to the model file and
blocks that link to subsystem file and propagate to all other
that block. propagate to all other instances of the
instances of the referenced model.
To edit an instance of referenced
the block, you can subsystem. To specify instance-
disable the library specific parameter
link. values for referenced
models, see
You cannot disable “Parameterize
library links when the Instances of a
parent library block Reusable Referenced
has restricted write Model” on page 8-80.
access.
Varian Supported Supported Supported Supported
ts
Add subsystem Same behavior as Same behavior as Add model variants to
variants to a Variant subsystems. subsystems. a Variant Subsystem
Subsystem or Variant or Variant Model
Model block. block.

For more information, For more information,


see “Implement see “Implement
Variations in Separate Variations in Separate
Hierarchy Using Hierarchy Using
Variant Subsystems” Variant Subsystems”
on page 12-48. on page 12-48.

23-13
23 Large-Scale Modeling

Performance
Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Incre Not supported Supported Supported Supported
menta
l Loading a model loads The software The software The software
Model all subsystem incrementally loads a incrementally loads a incrementally loads a
Loadi contents that are library at the point referenced subsystem referenced model at
ng saved in the model. needed during at the point needed the point needed
editing, updating a during editing, during editing,
diagram, or updating a diagram, updating a diagram,
simulating a model. or simulating a model. or simulating a model.
Incre Not supported Not supported Not supported Supported
menta
l Subsystems compile Same behavior as Same behavior as A referenced model
Model as part of their parent subsystems. subsystems. that simulates in
Compi model. accelerator mode
lation compiles according to
the value of its
Rebuild
configuration
parameter.

Whether a model
compiles is
independent of other
models.
Build Not supported Not supported Not supported Supported
Artifa
ct Build artifacts, such Same behavior as Same behavior as Team members and
Reuse as simulation targets, subsystems. subsystems. continuous
are not generated for integration (CI)
subsystems. systems can generate
Simulink cache files
for models that you
use. These files let
you reuse build
artifacts, such as
simulation targets,
which can speed up
simulation and code
generation. For more
information, see
“Share Simulink
Cache Files for Faster
Simulation” on page
8-70.

23-14
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Reduc Not supported Not supported Not supported Supported
ed
Memo Subsystems do not Linked subsystems do Subsystem references Models referenced in
ry reduce memory usage not reduce memory do not reduce accelerator mode
Usage for simulation and usage for simulation memory usage for reduce memory usage
for code generation. and code generation. simulation and code for simulation and
Large generation. code generation
Model Simulink duplicates because Simulink
s library block Simulink duplicates incrementally loads
instances during subsystem reference compiled versions of
block update. instances during them.
block update.
Artific Supported Supported Supported Supported
ial
Algeb Subsystems that are Same behavior as Same behavior as You can try to
raic not atomic avoid subsystems. subsystems. eliminate artificial
Loop artificial algebraic algebraic loops by
Elimi loops. enabling
nation Configuration
If a subsystem is Parameters > Model
atomic, you can try to Referencing >
eliminate artificial Minimize algebraic
algebraic loops by loop occurrences.
enabling the
Subsystem block
parameter Minimize
algebraic loop
occurrences.

23-15
23 Large-Scale Modeling

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Local Not supported Not supported Not supported Supported
Solver
s Subsystems inherit Same behavior as Same behavior as You can use a local
the solver of their subsystems. subsystems. solver in a referenced
parent model. model to solve a
model reference as a
separate set of
differential equations.
The local solver can
use a different, larger
step size. The choice
of solver and solver
settings involves a
trade off between
speed and accuracy in
simulation. For more
information, see “Use
Local Solvers in
Referenced Models”
on page 27-5.

23-16
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Parall Not supported Not supported Not supported Supported
el
Builds Subsystems are built Same behavior as Same behavior as With Parallel
as part of their parent subsystems. subsystems. Computing Toolbox
model. software, you can
distribute the code
generation and
compilation for
referenced models
across a parallel pool
of MATLAB workers.

For large model


reference hierarchies,
you can increase the
speed of diagram
updates and code
generation by
building the model
reference targets in
parallel. For more
information, see
“Reduce Update Time
for Referenced
Models by Using
Parallel Builds” on
page 8-69 and
“Reduce Build Time
for Referenced
Models by Using
Parallel Builds”
(Simulink Coder).

23-17
23 Large-Scale Modeling

Testing and Certification


Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Unit Supported Supported Supported Supported
Testin
g If the context of a Same behavior as A test harness for a You can test a
subsystem changes, subsystems. referenced subsystem referenced model
such as the data type has the same behavior independently to
of an input signal, the as a test harness for a isolate behavior by
related test harness subsystem that is not simulating it as a top
must be updated. stored in a separate model.
file.
For subsystems that You can use a data-
are not atomic, the While you can create defined test harness,
test harness may use a test harness for a with MATLAB test
different block referenced vectors and direct
execution orders, due subsystem, you coverage collection.
to virtual boundaries. cannot create a test
harness for blocks For tools that support
For tools that support within a referenced authoring, managing,
authoring, managing, subsystem. and executing
and executing
systematic,
systematic,
simulation-based tests
simulation-based tests
of subsystems, see
of subsystems, see
“Create or Import
“Create or Import
Test Harnesses and
Test Harnesses and
Select Properties”
Select Properties”
(Simulink Test).
(Simulink Test).

To measure how To measure how


thoroughly model thoroughly model
components are components are
tested, see “Model tested, see “Model
Coverage” (Simulink Coverage” (Simulink
Coverage). Coverage).

SIL/PI Not supported Not supported Not supported Supported


L
Testin While you can Same behavior as Same behavior as To perform SIL/PIL
g perform SIL/PIL subsystems. subsystems. testing for a model
testing for a model reference hierarchy,
that contains see “SIL and PIL
subsystems, you Simulations”
cannot simulate a (Embedded Coder).
subsystem
independently.

23-18
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Single Supported Supported Supported Supported
-
Sourc By default, subsystem By default, subsystem Same behavior as Each referenced
ed code is not reusable. code is not reusable. subsystems. model has one set of
Code To generate reusable To generate reusable source code,
subsystem code when subsystem code when regardless of how
possible, see possible, see many times a model
“Generate Subsystem “Generate Reusable hierarchy includes the
Code as Separate Code from Library referenced model.
Function and Files” Subsystems Shared Having single-sourced
(Simulink Coder). Across Models” code can reduce the
(Simulink Coder). cost of verification.
Gener Supported Supported Supported Supported
ated
Code While you can trace Same behavior as Same behavior as You can trace the
Trace the generated code subsystems. subsystems. generated code for a
ability for a subsystem, if the referenced model
subsystem context independent of other
changes, the models, which
generated code reduces the cost of
changes. For example, verification.
a change to an input
signal data type With a Simulink Code
affects the subsystem Inspector license, you
code. can create a
traceability matrix for
each referenced
model. The
traceability matrix
provides the
traceability among
model objects,
generated code, and
model requirements.
For more information,
see “Generate
Traceability Matrices”
(Simulink Code
Inspector).

23-19
23 Large-Scale Modeling

Interface Design
Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Signal Supported Supported Supported Supported
Prope
rty You can specify signal Same behavior as Same behavior as You must specify most
Specif properties at a subsystems. subsystems. signal properties at a
icatio subsystem interface. referenced model
n at interface.
Interf For signal properties
aces that you do not Referenced models
specify, subsystems are context-
inherit the signal independent with a
properties from their defined boundary, so
context. Propagation they do not inherit
of signal properties most signal
can lead to Simulink properties.
using signal
properties that you do Referenced models
not anticipate. can inherit discrete
sample times when
the referenced model
is sample-time
independent.
Physic Supported Supported Supported Not supported
al
Conne You can specify Same behavior as Same behavior as Physical connections
ctions physical connections subsystems. subsystems. must be fully
at at a subsystem contained within a
Interf interface. referenced model.
aces They cannot cross the
model interface.

23-20
Compare Capabilities of Model Components

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
Bus Supported Supported Supported Supported
Specif
icatio You can use a Same behavior as Same behavior as You can use a
n at Simulink.Bus subsystems. subsystems. Simulink.Bus
Interf object, In Bus object, In Bus
aces Element block, or Out Element block, or Out
Bus Element block to Bus Element block to
specify the hierarchy specify the hierarchy
and properties of a and properties of a
bus that passes into bus that passes into
or out of a subsystem. or out of a referenced
model.
Subsystems do not
require the use of bus Model references do
objects for virtual not require the use of
buses. bus objects for virtual
buses when you use
In Bus Element and
Out Bus Element
blocks.

Custom Behavior
Model Subsystems Linked Subsystems Subsystem Model References
ing References
Requi
remen
t
Uniqu Not supported Not supported Not supported Supported
e
Config Subsystems use the Same behavior as Same behavior as Configuration
uratio configuration subsystems. subsystems. parameter settings
n parameter settings of can generally be
Param the model that different for a parent
eter contains them. model and its
Settin referenced models.
gs For compatibility
information, see “Set
Configuration
Parameters for Model
Hierarchies” on page
8-75.

23-21
23 Large-Scale Modeling

Model Subsystems Linked Subsystems Subsystem Model References


ing References
Requi
remen
t
State Supported Supported Supported Supported
Initial
izatio You can initialize Same behavior as Same behavior as You can initialize
n states of subsystems. subsystems. subsystems. states from the top
model using either
the structure format
or structure-with-time
format.
Condi Supported Supported Supported Supported
tional
Execu Subsystems support Same behavior as Same behavior as Referenced models
tion conditional execution. subsystems. subsystems. support conditional
For more information, execution. For more
see “Conditionally information, see
Executed Subsystems “Conditionally
Overview” on page Execute Referenced
10-3. Models” on page 8-28.
Event- Supported Supported Supported Supported
Based
Behav Subsystems support Same behavior as Same behavior as Referenced models
ior event-based behavior. subsystems. subsystems. support event-based
For more information, behavior. For more
see “Using Initialize, information, see
Reinitialize, Reset, “Using Initialize,
and Terminate Reinitialize, Reset,
Functions” on page and Terminate
10-208. Functions” on page
10-208.
Indep Supported Supported Supported Supported
enden
t You can define Same behavior as Same behavior as You can define
Functi independent functions subsystems. subsystems. independent functions
ons in subsystems. For in a referenced
more information, see model. For more
“Simulink Functions information, see
Overview” on page “Export-Function
10-142. Models Overview” on
page 10-125.

See Also

More About
• “Model Reference Requirements and Limitations” on page 8-11
• “Choose Simulation Modes for Model Hierarchies” on page 8-45

23-22
Compare Capabilities of Model Components

• “Subsystems” (Simulink Coder)


• “Generate Code for Model Reference Hierarchy” (Simulink Coder)
• “Map System Architecture to Simulink Modeling Environment” (Simulink Coder)
• “Map Embedded System Architecture to Simulink Modeling Environment” (Embedded Coder)

External Websites
• 11 Best Practices for Developing ISO 26262 Applications with Simulink

23-23
23 Large-Scale Modeling

Define Interfaces of Model Components


Defining the interface of a model component, such as a Simulink subsystem, subsystem reference, or
model reference, is a key first step before others can use it.

• Agreeing on an interface helps determine how to break down the functionality of a large system
into components.
• After you define interfaces between components, you can develop the components in parallel. If
the interface remains stable, then it is easy to integrate those components into a larger system.
• Changing the interface between components is expensive. Changing an interface requires changes
to at least two components (the source and any sinks) and to any test harnesses. It also makes all
previous versions of those components incompatible with the current and future versions.

Changing an interface is much easier if the components are stored under configuration management.
You can track configurations of compatible component versions to prevent incompatible combinations
of components.

Note This topic focuses on design interfaces for modeling and simulation. To configure an interface
for code generation and deployment, see:

• “Design Data Interface by Configuring Inport and Outport Blocks” (Simulink Coder)
• “Choose Storage Class for Controlling Data Representation in Generated Code” (Simulink Coder)
• “C Data Code Interface Configuration for Model Interface Elements” (Simulink Coder)
• “Interactively Configure C++ Interface” (Embedded Coder)
• “Programmatically Configure C++ Interface” (Embedded Coder)

Identify Component Boundaries


Base the boundaries of the components upon the boundaries of the corresponding real systems. This
guideline is especially useful when the model contains:

• Both physical (plant and environment) and control systems


• Algorithms that run at different rates
• A system that you want to reuse multiple times

If you intend to add sensors or other components as you elaborate your model, create components to
represent them. You can configure these components to pass signals straight through or perform a
unit delay or name conversion.

Simplify Interfaces with Buses


To simplify interfaces, group signals and messages into buses. Buses simplify subsystem and model
interfaces by letting you associate multiple signals or messages with one port. They reduce line
complexity and clutter in a block diagram and make it easier to change the interface incrementally.
For example, if you must add or remove elements from a component interface, modifying a bus can be
simpler than adding or removing ports. To logically group or define the properties of a portion of the
interface, use multiple bus ports.

23-24
Define Interfaces of Model Components

Buses are well suited for components that have many input and output signals and do not use all of
the available signals. Buses pass only the required data to each component from the inputs and
outputs. If you define the bus at the interface with a Simulink.Bus object, the interface requires
data for the entire bus.

To access an element from an input bus, use an In Bus Element block. To create an output bus, use
Out Bus Element blocks. For more information, see “Simplify Subsystem and Model Interfaces with
Bus Element Ports” on page 82-24.

How you implement buses at an interface depends on your requirements.

Requirement Bus Implementation


Provide name-based matching among elements at Use buses. Virtual buses meet most modeling
the interface and simplify line routing requirements. For more information, see
“Composite Interface Guidelines” on page 82-
2.
Enable robust component integration with Use In Bus Element blocks and Out Bus Element
defined interfaces blocks to define the properties of the buses at the
interface. Use a rigorous naming convention for
the buses and bus elements.

Optionally, use Simulink.Bus objects. To place


the bus objects under revision control, save them
in a data dictionary, function, script, or MAT file.
Replicate structure type in generated code Use nonvirtual buses to describe a structured
data type for an element in the interface.
Package signals or parameters into structures Import the type as a bus object and use the object
that correspond to a struct type definition that as a data type for buses and MATLAB structures.
your external C code defines To create the object, use the
Simulink.importExternalCTypes function.

Partition Interface Data


Explicitly control the scope of data for your components with global and nonglobal parameters.

• Global parameters — A common approach in the automotive world is to completely separate


parameter storage from model storage. The parameters for a model come from a database of
calibration data, and the specific calibration file used becomes part of the configuration. The
calibration data is treated as global data, and resides in the base MATLAB workspace. You can
migrate base workspace data to a data dictionary for more control.
• Nonglobal parameters — Combining components that store their own parameter data has the risk
of parameter name collisions. If you do not use a naming convention for parameters or a list of
unique parameter names and definitions, then two components may use a parameter with the
same name but with different meanings.

To store local parameter data:

• Partition data into reference dictionaries for each component.


• For referenced models, you can use model workspaces.
• Use parameter files (.m or .mat) and callbacks of the individual Simulink models (for example, the
preload function).

23-25
23 Large-Scale Modeling

You can also automatically load required data using project shortcuts.
• Use mask workspaces with or without the use of mask initialization functions.
• For subsystems, you can control the scope of data for a subsystem using the Permit hierarchical
resolution parameter of the Subsystem block.

Configure Data Interfaces


Explicitly configure design attributes of the interface, such as data type and numeric complexity, to
prevent modeling errors and make component integration easier. You can configure the interface of a
component before you develop the internal algorithm, in which case the component contains
unconnected blocks. After you create the blocks that correspond to the component interface, use:

• The Model Data Editor to configure the design attributes of the blocks.

To open the Model Data Editor, on the Modeling tab of the Simulink Toolstrip, click Model Data
Editor. On the Inports/Outports tab of the Model Data Editor, each row corresponds to an input
or output block and the columns correspond to attributes that you can set for the blocks.
• The interface display perspective to view the component interface in its entirety and trace
elements of the interface to usage points in the internal block algorithm.

To open the interface display perspective, on the Modeling tab, in the Design gallery, click
Model Interface. For more information, see “Trace Connections Using Interface Display” on page
82-103.

By default, the Change view list of the Model Data Editor is set to Design, which configures the
columns to correspond to design attributes. Use the columns to explicitly configure the design
attributes of the interface. For example, specify minimum and maximum values for each block with
the Min and Max columns.

Alternatively, you can specify a reusable set of design attributes at component interfaces instead of
individually specifying each attribute.

• Use Simulink.ValueType objects to assign or validate properties of a signal based on


application-specific value types such as wind velocity, tire pressure, or water temperature.
• Use Simulink.Bus objects to assign or validate the properties of each element of a bus.

To display the input and output blocks of the subsystems, select the Change Scope button .
Alternatively, view only the input and output blocks at the root level of the model by excluding the
blocks inside the subsystems.

See Also

More About
• “Composite Interface Guidelines” on page 82-2
• “Specify Bus Properties with Bus Objects” on page 82-65
• “Trace Connections Using Interface Display” on page 82-103
• “Partition Data for Model Reference Hierarchy Using Data Dictionaries” on page 80-29

23-26
Define Interfaces of Model Components

• “Parameter Interfaces for Reusable Components” on page 41-17


• “Determine Where to Store Variables and Objects for Simulink Models” on page 73-109

23-27
23 Large-Scale Modeling

Configuration Management

In this section...
“Manage Designs Using Source Control” on page 23-28
“Determine the Files Used by a Component” on page 23-28
“Manage Model Versions” on page 23-29
“Create Configurations” on page 23-29

Manage Designs Using Source Control


Projects can help you work with configuration management tools for team collaboration. You can use
projects to help you manage all the models and associated files for model-based design.

You can control and trace the changes in each component using project source control. Using source
control directly from a project provides these benefits:

• Engineers do not have to remember to use two separate tools, avoiding the common mistake of
beginning work in Simulink without checking out the required files first.
• You can perform analysis within MATLAB and Simulink to determine the dependencies of files
upon each other. Third-party tools are unlikely to understand such dependencies.
• You can compare revisions and use tools to merge models.

If each component is a single file, you can achieve efficient parallel development, where different
engineers can work on the different components of a larger system in parallel. Using model
components allows you to avoid or minimize time-consuming merging. One file per component is not
strictly necessary to perform configuration management, but it makes parallel development much
easier.

If you break down a model into components, it is easier to reuse those components in different
projects. If the components are kept under revision control and configuration management, then you
can reuse components in multiple projects simultaneously.

To find out about source control support, see “Source Control in Projects”.

Determine the Files Used by a Component


You can use a project to determine the set of files you must place under configuration management.
You can analyze the set of files that are required for the model to run, such as model references,
library links, block and model callbacks (preload functions, init functions, etc.), S-functions, From
Workspace blocks, etc. Any MATLAB code found is also analyzed to determine additional file
dependencies. You can use the Dependency Analyzer to report which toolboxes are required by a
model, which can be a useful artifact to store.

You can also perform a file dependency analysis of a model programmatically from MATLAB using
dependencies.fileDependencyAnalysis to get a cell array of paths to required files.

For more information, see “Dependency Analysis”.

23-28
Configuration Management

Manage Model Versions


Simulink can help you to manage multiple versions of a model.

• Use a project to manage your project files, connect to source control, review modified files, and
compare revisions. See “Project Management”.
• Simulink notifies you if a model has changed on disk when updating, simulating, editing, or saving
the model. Models can change on disk, for example, with source control operations and multiple
users. Control this notification with the Model File Change Notification preference. See “Model
File Change Notification” on page 4-86.
• As you edit a model, Simulink generates version information about the model, including a version
number, who created and last updated the model, and an optional comments history log. Simulink
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.
• Use Simulink.MDLInfo to extract information from a model file without loading the block
diagram into memory. You can use MDLInfo to query 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.

Create Configurations
You can use a project to work with the revision control parts of the workflow: retrieving files, adding
files to source control, checking out files, and committing edited files to source control.

To define configurations of files, you can label several files as a new mutually consistent
configuration. Team members can get this set of files from the revision control system.

Configurations are different from revisions. Individual components can have revisions that work
together only in particular configurations.

Tools for creating configurations in Simulink:

• Variant modeling. See “Variant Systems”.


• Project tools:

• Label — Label project files. Use labels to apply metadata to files. You can group and sort by
labels, label folders for adding to the path using shortcut functions, or create batch jobs to
export files by label, for example, to manage files with the label Diesel. You cannot retrieve
from source control by label, and labels persist across revisions.
• Revision Log — Use Revert Project to choose a revision to revert to (SVN source control only).
• Branch — Create branches of file versions, and switch to any branch in the repository (Git
source control only).
• Tag — You can tag all project files (SVN source control only) to identify a particular
configuration of a project, and retrieve tagged versions from source control. However,
continued development is limited. That is, you cannot tag again, and you must check out from
trunk to apply tags.

23-29
23 Large-Scale Modeling

• Archive — Package all project files in a zip file that you can create a project from. However,
this packaging removes all source control information, because archiving is for exporting,
sharing, and changing to another source control. You can commit the new zip file to source
control.

See Also

More About
• “What Are Projects?” on page 16-3
• “Source Control in Projects”
• “Dependency Analysis”
• “Model Comparison”
• “Project Management”
• “Component-Based Modeling Guidelines” on page 23-2
• “Define Interfaces of Model Components” on page 23-24

23-30
24

Power Window Example


24 Power Window Example

Power Window
In this section...
“Power Window Control Project” on page 24-3
“Quantitative Requirements” on page 24-8
“Implement Activity Diagram: Power Window Control” on page 24-15
“Interactive Testing” on page 24-17
“Case 1: Window Up” on page 24-19
“Case 2: Window Auto-Up” on page 24-22
“Case 3: Driver-Side Precedence” on page 24-23
“Model Coverage” on page 24-27
“Create Model Using Model-Based Design” on page 24-31
“Automatic Code Generation for Control Subsystem” on page 24-45
“References” on page 24-46

Automobiles use electronics for control operations such as:

• Opening and closing windows and sunroof


• Adjusting mirrors and headlights
• Locking and unlocking doors

These systems are subject to stringent operation constraints. Failures can cause dangerous and
possibly life-threatening situations. As a result, careful design and analysis are needed before
deployment.

This example focuses on the design of a power window system of an automobile, in particular, the
passenger-side window. A critical aspect of this system is that it cannot exert a force of more than
100 N on an object when the window closes. When the system detects such an object, it must lower
the window by about 10 cm.

As part of the design process, the example considers:

• Quantitative requirements for the window control system, such as timing and force requirements
• System requirements, captured in activity diagrams
• Data definitions for the signals used in activity diagrams

Other aspects of the design process that this example contains are:

• Managing the components of the system


• Building the model
• Validating the results of system simulation
• Generating code

MATLAB and Simulink support Model-Based Design for embedded control design, from initial
specification to code generation. The power window control project shows how you can use

24-2
Power Window

MathWorks tools and the Model-Based Design process to go from concept through implementation for
an automobile power window system. It uses projects to organize the files and other model
components.

Power Window Control Project

This example shows how to use a project to model a power window system for an automobile. The
project uses Model-Based Design and these large-scale modeling techniques.

• Model blocks to separate the hierarchy into separate models.


• Variant Subsystems blocks to model and switch between different design choices.
• Libraries to capture algorithms for reuse in variant subsystems.
• Projects to manage the files required for the system development.

Design Requirements

In this example, consider the passenger-side power window system of an automobile. This system can
never exert a force of more than 100 N on an object when closing the window.

When the model detects such an object, the model must lower the window by about 10 centimeters.

For more information on the design requirements, see “Power Window” on page 24-2.

Explore the Project

Upon visual inspection of the project, you can see features used to organize the example. These
features are used to organize the project:

• Folders
• File Classification
• Shortcuts

24-3
24 Power Window Example

Folders

The project is organized into these folders:

• configureModel - MATLAB® files that control the main system model variant configuration
• data - Images required by the project
• hmi - Files that animate the power window response
• model - Main system model, controller model, models for testing the controller, and libraries that
support these models
• task - MATLAB files that simulate the model for the different model configurations and generate
coverage reports for the controller
• utilities - MATLAB files to initialize the model, to generate spreadsheet input, to add data to
the generated spreadsheet, and manage the project environment at startup and shutdown

File Classification

Files in Projects have different classifications visible in the Labels pane. Each label describes the
specific role a file contributes to the body of the project.

• Configuration - Files that configure the project or model.


• PrjConfig - Files that configure the project by adding its files to the path at startup and
removing them at shutdown

24-4
Power Window

• DesignConfig - Files that determine which model configuration is active at a given time
• Design - Main system model and its referenced control model
• DesignSupport - Files such as libraries, data, and model simulation
• Simulation - Files that simulate the model for a specific configuration
• Test - Control coverage, the control interaction, and the test harness models
• Visualization - Files that animate the motion of the power window

Shortcuts

Project shortcuts provide quick access to project files that are used most often. Some shortcuts
contain general tasks, such as adding the project to the path at startup and removing it at shutdown.
In addition, project shortcut groups help organize the shortcuts.

• Interactive Testing - Files used for interactive testing of the controller


• Main Model - File for top-level Simulink model
• Model Coverage - Files used for model coverage of the controller
• Simulation - Files used for simulation of model variant configurations

Explore Simulink Models in Project

The Simulink models for this project are located in the model folder.

• Main System Model


• Models for Testing

Main System Model

The main system model is slexPowerWindowExample. This model consists of driver_switch and
passenger_switch subsystem blocks, which generate the inputs to the
power_window_control_system block. The power_window_control_system block validates the
states of the passenger and driver inputs. This block also determines if obstacle is blocking the path
of the window. The referenced controller produces the window motion command signals sent to the
active variant of the window system. The window_system block output is the feedback to the control
system block.

To visualize the results of simulation, the Simulation Data Inspector logs the output data and
Simulink 3D Animation™ animates the motion of the window.

Model Variants

The main system model in this project uses Variant Subsystem blocks to allow for multiple
implementations within a subsystem. You can change the active implementation programmatically
prior to simulation. The main model contains four Variant Subsystem blocks, each with variant
choices that can be programmatically modified. Those four variant subsystems are:

• slexPowerWindowExample/driver_switch
• slexPowerWindowExample/passenger_switch
• slexPowerWindowExample/window_system
• slexPowerWindowExample/power_window_control_system/detect_obstacle_endstop

24-5
24 Power Window Example

Each variant choice is associated with a variant control. The variant choice is active when its variant
control evaluates to true.

You can control the combinations of variant choices to create model variant configurations using the
files under the DesignConfig classification. Model variant configurations include:

• Power Window Controller Hybrid System Model


• Power Window Controller and Detailed Plant Model
• Power Window Controller With Data Acquisition Effects
• Power Window Controller With Controller Area Network (CAN) Communication

Power Window Controller Hybrid System Model

This model variant uses Stateflow® and Simulink to model both discrete event reactive behavior and
continuous time behavior. The models uses a low-order plant model to validate the roll-up and roll-
down behavior. You can simulate this variant configuration using the SimHybridPlantLowOrder
shortcut. This shortcut activates only the variant subsystem corresponding to this model
configuration. Since this model does not take into account power effects, the only output logged is
position. The Simulation Data Inspector displays the logged position data.

Power Window Controller and Detailed Plant Model

This model variant shows a more detailed plant model that includes power effects in the electrical
and mechanical domains. This variant validates that the force exerted by the window on a trapped
object never exceeds 100 N. This model variant requires Simscape™ Multibody™ and Simscape™
Electrical™ licenses. You can simulate this variant configuration using the
SimHybridPlantPowerEffects shortcut. Unlike the Power Window Controller Hybrid System
Model, this variant configuration takes into account the power effects. The Simulation Data Inspector
displays the logged data from armature current, position, and force exerted by the power window.

Power Window Controller With Data Acquisition Effects

This model variant shows additional effects due to implementation that affect the control. The
phenomena included are signal conditioning to measure the armature current and quantization of the
measurement. This model variant requires Simscape Multibody, Simscape Electrical, DSP System
Toolbox™, and Fixed-Point Designer™ licenses. You can simulate this variant configuration using the
SimHybridPlantPowerEffects+ControlDAQEffects shortcut. As with the Power Window
Controller and Detailed Plant Model, the Simulation Data Inspector displays the logged data from
armature current, position, and force exerted by the power window.

Power Window Controller With CAN Communication

This model variant shows the use of a CAN to communicate the commands to control window
movement. The switches that may be located in the center console of the vehicle and that produce
the commands are included in this model variant. This model variant requires Simscape Multibody,
Simscape Electrical, DSP System Toolbox, and Fixed-Point Designer licenses. You can simulate this
variant configuration on a machine running windows OS using the SimCANCommunication shortcut.

Models for Testing

To test the state machine that controls the power window, you can run the project shortcuts for
testing. Model shortcuts for testing the controller include:

24-6
Power Window

• InteractiveExample
• CoverageExample
• IncreaseCoverageExample

InteractiveExample

This model shortcut opens the model slexPowerWindowCntlInteract. This model contains the
power window controller, which is a state machine. This model also contains inputs to the controller
that are selected with manual switch blocks.

The power window controller has four external inputs:

Passenger Input input consists of a vector with three elements:

• neutral: Passenger control switch is not depressed.


• up: Passenger control switch generates the up signal.
• down: Passenger control switch generates the down signal.

Driver Input input consists of a vector with three elements:

• neutral: Driver control switch is not depressed.


• up: Driver control switch generates the up signal.
• down: Driver control switch generates the down signal.

Window Frame Endstops input consists of a vector with two elements:

• 0: Window moves freely between top or bottom.


• 1: Window is stuck at the top or bottom because of physical limitations.

Obstacle Present input consists of a vector with two elements:

• 0: window moves freely between top or bottom


• 1: window has obstacle within its frame

You can interactively test the controller by simulating the model and selecting the desired
combination of inputs via the manual switch blocks. After selecting inputs, you can verify the internal
controller state and controller output against the desired result for the specific set of inputs.

CoverageExample

This model shortcut opens the model slexPowerWindowCntlCoverage. The model contains a state
machine power window controller with Repeating Sequence block inputs.

You can use the Simulink Coverage Model Coverage tool to validate the discrete event control of the
window. The Model Coverage tool determines the extent to which a model test case exercises the
conditional branches of the controller. The tool evaluates whether all transitions in the discrete event
control are taken given the test case. The tool also evaluates whether all clauses in a condition that
enables a particular transition have become true. One transition may be enabled by multiple clauses,
for example, the transition from emergency back to neutral occurs when either 100 ticks have
occurred or when the endstop is reached.

IncreaseCoverageExample

24-7
24 Power Window Example

This model shortcut opens the model slexPowerWindowCntlCoverageIncrease. This model


contains the power window controller that is a state machine. This model also contains a From
Spreadsheet block that provides multiple sets of inputs to the controller. These input sets combine
with the one from the CoverageExample model to exercise more of the logic in the power window
controller:

• Logged: Logged from the CoverageExample.


• LoggedObstacleOffEndStopOn: Logged from the CoverageExample with ability to hit
endstop.
• LoggedObstacleOnEndStopOff: Logged from the CoverageExample with obstacle in window.
• LoggedObstacleOnEndStopOn: Logged from the CoverageExample with obstacle in window
and ability to hit endstop.
• DriverLoggedPassengerNeutral: Logged from the CoverageExample for only the driver.
Passenger takes no action.
• DriverDownPassengerNeutral: Driver lowering window. Passenger takes no action.
• DriverUpPassengerNeutral: Driver raising window. Passenger takes no action.
• DriverAutoDownPassengerNeutral: Driver lowering window for 1 second (auto-down).
Passenger takes no action.
• DriverAutoUpPassengerNeutral: Driver raising window for 1 second (auto-up). Passenger
takes no action.
• PassengerAutoDownDriverNeutral: Passenger lowering window for 1 second (auto-down).
Driver takes no action.
• PassengerAutoUpDriverNeutral: Passenger raising window for 1 second (auto-up). Driver
takes no action.

The model coverage shortcut GenerateIncreasedCoverage uses the multiple input sets with the
Simulink Coverage Model Coverage tool to validate the discrete event control of the window and
generate a coverage report for the multiple input sets.

Quantitative Requirements
Quantitative requirements for the control are:

• The window must fully open and fully close within 4 s.


• If the up is issued for between 200 ms and 1 s, the window must fully open. If the down command
is issued for between 200 ms and 1 s, the window must fully close.
• The window must start moving 200 ms after the command is issued.
• The force to detect when an object is present is less than 100 N.
• When closing the window, if an object is in the way, stop closing the window and lower the window
by approximately 10 cm.

Capturing Requirements in Activity and Context Diagrams

Activity diagrams help you graphically capture the specification and understand how the system
operates. A hierarchical structure helps with analyzing even large systems. At the top level, a context
diagram describes the system environment and its interaction with the system under study in terms
of data exchange and control operations. Then you can decompose the system into an activity
diagram with processes and control specifications (CSPEC).

24-8
Power Window

The processes guide the hierarchical decomposition. You specify each process using another activity
diagram or a primitive specification (PSPEC). You can specify a PSPEC in a number of
representations with a formal semantic, such as a Simulink block diagram. In addition, context
diagrams graphically capture the context of system operation. Use the data definitions for the
specifications.

Context Diagram: Power Window System

The figure represents the context diagram of a power window system. The square boxes capture the
environment, in this case, the driver, passenger, and window. Both the driver and passenger can send
commands to the window to move it up and down. The controller infers the correct command to send
to the window actuator (e.g., the driver command has priority over the passenger command). In
addition, diagram monitors the state of the window system to establish when the window is fully
opened and closed and to detect if there is an object between the window and frame.

The circle (also known as a bubble) represents the power window controller. The circle is the
graphical notation for a process. Processes capture the transformation of input data into output data.
Primitive process might also generate. CSPECs typically consist of combinational or sequential logic
to infer output control signals from input control.

For implementation in the Simulink environment, see “Implement Context Diagram: Power Window
System” on page 24-31.

24-9
24 Power Window Example

Power Window System Data Definitions

Signal Information Type Continuous/ Data Type Values


Discrete
DRIVER_COMMAND Data Discrete Aggregate Neutral, up,
down
PASSENGER_COMMAND Data Discrete Aggregate Neutral, up,
down
WINDOW_POSITION Data Continuous Real 0 to 0.4 m
MOVE_UP Control Discrete Boolean 'True', 'False'
MOVE_DOWN Control Discrete Boolean 'True', 'False'

Activity Diagram: Power Window Control

The power window control consists of three processes and a CSPEC. Two processes validate the
driver and passenger input to ensure that their input is meaningful given the state of the system. For
example, if the window is completely opened, the MOVE DOWN command does not make sense. The
remaining process detects if the window is completely opened or completely closed and if an object is
present. The CSPEC takes the control signals and infers whether to move the window up or down
(e.g., if an object is present, the window moves down for about one second or until it reaches an
endstop).

24-10
Power Window

Power Window Control Data Definitions

Signal Information Type Continuous/ Data Type Values


Discrete
DRIVER_COMMAND Data Discrete Aggregate Neutral, up,
down
PASSENGER_COMMAND Data Discrete Aggregate Neutral, up,
down
WINDOW_POSITION Data Continuous Real 0 to 0.4 m
MOVE_UP Control Discrete Boolean 'True', 'False'
MOVE_DOWN Control Discrete Boolean 'True', 'False'

Activity Diagram: Validate Driver

Each process in the VALIDATE DRIVER activity chart is primitive and specified by the following
PSPEC. In the MAKE EXCLUSIVE PSPEC, for safety reasons the DOWN command takes precedence
over the UP command.

24-11
24 Power Window Example

PSPEC 1.1.1: CHECK DOWN


CHECKED_DOWN = DOWN and not RESET

PSPEC 1.1.2: CHECK UP


CHECKED_UP = UP and not RESET

PSPEC 1.1.3: MAKE EXCLUSIVE


VALIDATED_DOWN = CHECKED_DOWN
VALIDATED_UP = CHECKED_UP and not CHECKED_DOWN
VALIDATED_NEUTRAL = (NEUTRAL and not (CHECKED_UP and not CHECKED_DOWN))
or not (CHECKED_UP or CHECKED_DOWN)

Validate Driver Data Definitions

Signal Information Type Continuous/ Data Type Values


Discrete
DRIVER_COMMAND Data Discrete Aggregate Neutral, up,
down
PASSENGER_COMMAND Data Discrete Aggregate Neutral, up,
down
WINDOW_POSITION Data Continuous Real 0 to 0.4 m
MOVE_UP Control Discrete Boolean 'True', 'False'
MOVE_DOWN Control Discrete Boolean 'True', 'False'

24-12
Power Window

Activity Diagram: Validate Passenger

The internals of the VALIDATE PASSENGER process are the same as the VALIDATE DRIVER process.
The only difference is the different input and output.

PSPEC 1.2.1: CHECK DOWN


CHECKED_DOWN = DOWN and not RESET

PSPEC 1.2.2: CHECK UP


CHECKED_UP = UP and not RESET

PSPEC 1.2.3: MAKE EXCLUSIVE


VALIDATED_DOWN = CHECKED_DOWN
VALIDATED_UP = CHECKED_UP and not CHECKED_DOWN
VALIDATED_NEUTRAL = (NEUTRAL and not (CHECKED_UP and not CHECKED_DOWN))
or not (CHECKED_UP or CHECKED_DOWN)

For implementation in the Simulink environment, see “Activity Diagram: Validate Passenger” on page
24-13.

24-13
24 Power Window Example

Validate Passenger Data Definitions

Signal Information Type Continuous/ Data Type Values


Discrete
NEUTRAL Data Discrete Boolean 'True', 'False'
UP Data Discrete Boolean 'True', 'False'
DOWN Data Discrete Boolean 'True', 'False'
CHECKED_UP Data Discrete Boolean 'True', 'False'
CHECKED_DOWN Data Discrete Boolean 'True', 'False'

Activity Diagram: Detect Obstacle Endstop

The third process in the POWER WINDOW CONTROL activity diagram detects the presence of an
obstacle or when the window reaches its top or bottom (ENDSTOP). The detection mechanism is based
on the armature current of the window actuator. During normal operation, this current is within
certain bounds. When the window reaches its top or bottom, the electromotor draws a large current
(more than 15 A or less than –15 A) to try and sustain its angular velocity. Similarly, during normal
operation the current is about 2 A or –2 A (depending on whether the window is opening or closing).
When there is an object, there is a slight deviation from this value. To keep the window force on the
object less than 100 N, the control switches to its emergency operation when it detects a current that
is less than –2.5 A. This operations is necessary only when the window is rolling up, which
corresponds to a negative current in the particular wiring of this model. The DETECT OBSTACLE
ENDSTOP activity diagram embodies this functionality.

24-14
Power Window

CSPEC 1.3: DETECT OBSTACLE ENDSTOP


RESET = OBSTACLE or ENDSTOP

PSPEC 1.3.1: DETECT ENDSTOP


ENDSTOP = WINDOW_POSITION > ENDSTOP_MAX

PSPEC 1.3.2: DETECT OBSTACLE


OBSTACLE = (WINDOW_POSITION > OBSTACLE_MAX) and MOVE_UP for 500 ms

For implementation in the Simulink environment, see “Activity Diagram: Detect Obstacle Endstop” on
page 24-14.

Detect Obstacle Endstop Data Definitions

Signal Information Continuous/ Data Type Values


Type Discrete
ENDSTOP_MIN Data Constant Real 0.0 m
ENDSTOP_MAX Data Constant Real 0.4 m
OBSTACLE_MAX Data Constant Real 0.3 m

Implement Activity Diagram: Power Window Control


This topic describes the high-level discrete-event control specification for a power window control.

24-15
24 Power Window Example

You can model the discrete-event control of the window with a Stateflow chart. A Stateflow chart is a
finite state machine with hierarchy and parallelism. This state machine contains the basic states of
the power window system: up, auto-up, down, auto-down, rest, and emergency. It models the state
transitions and accounts for the precedence of driver commands over the passenger commands. It
also includes emergency behavior that activates when the software detects an object between the
window and the frame while moving up.

The initial Simulink model for the power window control, slexPowerWindowControl, is a discrete-
event controller that runs at a given sample rate.

In this implementation, open the power window control subsystem and observe that the Stateflow
chart with the discrete-event control forms the CSPEC, represented by the tilted thick bar in the
bottom right corner. The detect_obstacle_endstop subsystem encapsulate the threshold detection
mechanisms.

The discrete-event control is a Stateflow model that extends the state transition diagram notion with
hierarchy and parallelism. State changes because of passenger commands are encapsulated in a
super state that does not correspond to an active driver command.

Consider the control of the passenger window. The passenger or driver can move this window up and
down.

This state machine contains the basic states of the power window system: up, auto-up, down, auto-
down, rest, and emergency.

24-16
Power Window

Interactive Testing
Control Input

The slexPowerWindowCntlInteract model includes this control input as switches. Double-click


these switches to manually operate them.

24-17
24 Power Window Example

Test the state machine that controls a power window by running the input test vectors and checking
that it reaches the desired internal state and generates output. The power window has the following
external inputs:

• Passenger input
• Driver input
• Window up or down
• Obstacle in window

Each input consists of a vector with these inputs.

Passenger Input

Element Description
neutral Passenger control switch is not depressed.
up Passenger control switch generates the up signal.
down Passenger control switch generates the down
signal.

24-18
Power Window

Driver Input

Element Description
neutral Driver control switch is not depressed.
up Driver control switch generates the up signal.
down Driver control switch generates the down signal.

Window Up or Down

Element Description
0 Window moves freely between top or bottom.
1 Window is stuck at the top or bottom because of
physical limitations.

Obstacle in Window

Element Description
0 Window moves freely between top or bottom.
1 Window has obstacle in the frame.

Generate the passenger and driver input signals by mapping the up and down signals according to
this table:

Inputs Outputs
up down up down neutral
0 0 0 0 1
0 1 0 1 0
1 0 1 0 0
1 1 0 0 1

The inputs explicitly generate the neutral event from the up and down events, generated by
pressing a power window control switch. The inputs are entered as a truth table in the passenger
neutral, up, down map and the driver neutral, up, down map.

Case 1: Window Up
To observe the state machine behavior:

1 Open the slexPowerWindowCntlInteract model.


2 Run the simulation and then double-click the passenger up switch.

24-19
24 Power Window Example

If you press the physical window switch for more than one second, the window moves up until
the up switch is released (or the top of the window frame is reached and the endstop event is
generated).
3 Double-click the selected passenger up switch to release it.

24-20
Power Window

4 Simulate the model.

Setting the endstop switch generates the endstop event.

24-21
24 Power Window Example

Case 2: Window Auto-Up


If you press the physical passenger window up switch for a short period of time (less than a second),
the software activates auto-up behavior and the window continues to move up.

1 Press the physical passenger window up switch for a short period of time (less than a second).

Ultimately, the window reaches the top of the frame and the software generates the endstop
event. This event moves the state machine back to its neutral state.

24-22
Power Window

2 Simulate the model.

Case 3: Driver-Side Precedence


The driver switch for the passenger window takes precedence over the driver commands. To observe
the state machine behavior in this case:

1 Run the simulation, and then move the system to the passenger up state by double-clicking the
passenger window up switch.

24-23
24 Power Window Example

2 Double-click the driver down switch.

24-24
Power Window

3 Simulate the model.


4 Notice how the state machine moves to the driver control part to generate the window down
output instead of the window up output.
5 Double-click the driver control to driver up. Double-click the driver down switch.

The driver window up state is reached, which generates the window up output again, i.e.,
windowUp = 1.

24-25
24 Power Window Example

6 To observe state behavior when an object is between the window and the frame, double-click the
obstacle switch.

24-26
Power Window

7 Simulate the model.

On the next sample time, the state machine moves to its emergencyDown state to lower the
window a few inches. How far the software lowers the window depends on how long the state
machine is in the emergencyDown state. This behavior is part of the next analysis phase.

If a driver or passenger window switch is still active, the state machine moves into the up or
down states upon the next sample time after leaving the emergency state. If the obstacle switch
is also still active, the software again activates the emergency state at the next sample time.

Model Coverage
Validation of the Control Subsystem

Validate the discrete-event control of the window using the model coverage tool. This tool helps you
determine the extent to which a model test case exercises the conditional branches of the controller.
It helps evaluate whether all transitions in the discrete-event control are taken, given the test case,
and whether all clauses in a condition that enables a particular transition have become true. Multiple
clauses can enable one transition, e.g., the transition from emergency back to neutral occurs when
either 100 ticks have occurred or if the endstop is reached.

24-27
24 Power Window Example

To achieve full coverage, each clause evaluates to true and false for the test cases used. The
percentage of transitions that a test case exercises is called its model coverage. Model coverage is a
measure of how thoroughly a test exercises a model.

Using Simulink Coverage software, you can apply the following test to the power window controller.

Position Step
0 1 2 3 4 5 6
Passenger up 0 0 0 0 0 0 0
Passenger down 0 0 0 1 0 1 1
Driver up 0 0 1 0 1 0 1
Driver down 0 1 0 0 1 1 0

With this test, all switches are inactive at time 0. At regular 1 s steps, the state of one or more
switches changes. For example, after 1 s, the driver down switch becomes active. To automatically
run these input vectors, replace the manual switches by prescribed sequences of input. To see the
preconstructed model:

1 Open the slexPowerWindowCntlCoverage model.

2 Simulate the model to generate the Simulink Coverage coverage report.

24-28
Power Window

For the slexPowerWindowCntlCoverage model, the report reveals that this test handles 100% of
the decision outcomes from the driver neutral, up, down map block. However, the test achieves only
50% coverage for the passenger neutral, up, down map block. This coverage means the overall
coverage for slexPowerWindowCntlCoverage is 45% while the overall coverage for the
slexPowerWindowControl model is 42%. A few of the contributing factors for the coverage levels
are:

• Passenger up block does not change.


• Endstop and obstacle blocks do not change.

Increase Model Coverage

To increase total coverage to 100%, you need to take into account all possible combinations of driver,
passenger, obstacle, and endstop settings. When you are satisfied with the control behavior, you can
create the power window system. For more information, see “Create Model Using Model-Based
Design” on page 24-31.

This example increases the model coverage for the validation of the discrete-event control of the
window. To start, the example uses inputs from slexPowerWindowCntlCoverage as a baseline for
the model coverage. Next, to further exercise the discrete-event control of the window, it creates
more input sets. The spreadsheet file, inputCntlCoverageIncrease.xlsx, contains these input
sets using one input set per sheet.

In the example, the slexPowerWindowSpreadsheetGeneration utility function, which creates a


spreadsheet template from the controller model, slexPowerWindowControl, creates the
inputCntlCoverageIncrease.xlsx. In inputCntlCoverageIncrease.xlsx, the function uses
the block names in the controller model as signal names.
slexPowerWindowSpreadsheetGeneration defines the sheet names. The
slexWindowSpreadsheetAddInput utility function populates
inputCntlCoverageIncrease.xlsx with signal data.

The sheet names of these input sets and their descriptions are:

Sheet Name Description


Logged Inputs logged from slexPowerWindowCntlCoverage
LoggedObstacleOffEndStopOn Inputs logged from slexPowerWindowCntlCoverage with
ability to hit endstop
LoggedObstacleOnEndStopOff Inputs logged from slexPowerWindowCntlCoverage with
obstacle in window
LoggedObstacleOnEndStopOn Inputs logged from slexPowerWindowCntlCoverage with
obstacle in window and ability to hit endstop
DriverLoggedPassengerNeutral Inputs logged from slexPowerWindowCntlCoverage for
driver only and passenger takes no action
DriverDownPassengerNeutral Driver is putting down window and passenger takes no action
DriverUpPassengerNeutral Driver is putting up window and passenger takes no action
DriverAutoDownPassengerNeutral Driver is putting down window for one second (auto-down) and
passenger takes no action
DriverAutoUpPassengerNeutral Driver is putting up window for one second (auto-up) and
passenger takes no action

24-29
24 Power Window Example

Sheet Name Description


PassengerAutoDownDriverNeutral Passenger is putting down window for one second (auto-down)
and driver takes no action
PassengerAutoUpDriverNeutral Passenger is putting up window for one second (auto-up) and
driver takes no action

To automatically run these input vectors, replace the inputs to the discrete-event control with the
From Spreadsheet block using the file, inputCntlCoverageIncrease.xlsx. This file contains the
multiple input sets. To see the preconstructed model:

1 Open the slexPowerWindowCntlCoverageIncrease model.

2 To generate the Simulink Coverage coverage report for multiple input set, double click the Run
Coverage subsystem in the model.

For the slexPowerWindowCntlCoverageIncrease model, the report reveals that using


multiple input sets has successfully raised the overall coverage for the
slexPowerWindowControl model from 42% to 78%. Coverage levels are less than 100%
because of missing input sets for:

24-30
Power Window

• Passenger up state
• Driver up and down states
• Passenger automatic down and automatic up states

Create Model Using Model-Based Design


Implement Context Diagram: Power Window System

For requirements presented as a context diagram, see “Context Diagram: Power Window System” on
page 24-9.

Create a Simulink model to resemble the context diagram.

1 Place the plant behavior into one subsystem.


2 Create two subsystems that contain the driver and passenger switches.
3 Add a control mechanism to conveniently switch between the presence and absence of the object.
4 Put the control in one subsystem.
5 Connect the new subsystems.
6 To see an implementation of this model, open the slexPowerWindowExample model.

You can use the power window control activity diagram (“Activity Diagram: Power Window Control”
on page 24-10) to decompose the power window controller of the context diagram into parts. This
diagram shows the input and output signals present in the context diagram for easier tracing to their
origins.

Implement Power Window Control System

To satisfy full requirements, the power window control must work with the validation of the driver
and passenger inputs and detect the endstop.

24-31
24 Power Window Example

For requirements presented as an activity diagram, see “Activity Diagram: Power Window Control” on
page 24-10.

Double-click the slexPowerWindowExample/power_window_control_system block to open the


following subsystem:

Implement Activity Diagram: Validate

For requirements presented as activity diagrams, see “Activity Diagram: Validate Driver” on page 24-
11 and “Activity Diagram: Validate Passenger” on page 24-13.

The activity diagram adds data validation functionality for the driver and passenger commands to
ensure correct operation. For example, when the window reaches the top, the software blocks the up
command. The implementation decomposes each validation process in new subsystems. Consider the
validation of the driver commands (validation of the passenger commands is similar). Check if the
model can execute the up or down commands, according to the following:

• The model allows the down command only when the window is not completely opened.
• The model allows the up command only when the window is not completely closed and no object is
detected.

The third activity diagram process checks that the software sends only one of the three commands
(neutral, up, down) to the controller. In an actual implementation, both up and down can be
simultaneously true (for example, because of switch bouncing effects).

From the power_window_control_system subsystem, this is the validate_driver_state subsystem:

24-32
Power Window

From the power_window_control_system subsystem, this is the validate_passenger_state subsystem:

Implement Activity Diagram: Detect Obstacle Endstop

For requirements presented as an activity diagram, see “Activity Diagram: Detect Obstacle Endstop”
on page 24-14.

In the slexPowerWindowExample model, the power_window_control_system/


detect_obstacle_endstop block implements this activity diagram in the continuous variant of the
Variant Subsystem block. During design iterations, you can add additional variants.

Double-click the slexPowerWindowExample model power_window_control_system/


detect_obstacle_endstop/Continuous/verify_position block.

24-33
24 Power Window Example

Hybrid Dynamic System: Combine Discrete-Event Control and Continuous Plant

After you have designed and verified the discrete-event control, integrate it with the continuous-time
plant behavior. This step is the first iteration of the design with the simplest version of the plant.

In the project, navigate to Files and click Project. In the configureModel folder, run the
slexPowerWindowContinuous utility to open and initialize the model.

The window_system block uses the Variant Subsystem block to allow for varying levels of fidelity in
the plant modeling. Double-click the window_system/Continuous/2nd_order_window_system block to
see the continuous variant.

24-34
Power Window

The plant is modeled as a second-order differential equation with step-wise changes in its input:

• When the Stateflow chart generates windowUp, the input is 1.


• When the Stateflow chart generates windowDown, the input is –1.
• Otherwise, the input is 0.

This phase allows analysis of the interaction between the discrete-event state behavior, its sample
rate, and the continuous behavior of the window movement. There are threshold values to generate
the window frame top and bottom:

• endStop
• Event when an obstacle is present, that is, obstacle
• Other events

Double-click the slexPowerWindowExample model power_window_control_system/


detect_obstacle_endstop/Continuous/verify_position block to see the continuous variant.

When you run the slexPowerWindowContinuous configureModel utility, the model uses the
continuous time solver ode23 (Bogacki-Shampine).

A structure analysis of a system results in:

24-35
24 Power Window Example

• A functional decomposition of the system


• Data definitions with the specifics of the system signals
• Timing constraints

A structure analysis can also include the implementation architecture (outside the scope of this
discussion).

The implementation also adds a control mechanism to conveniently switch between the presence and
absence of the object.
Expected Controller Response

To view the window movement, in Project Shortcuts, double-click SimHybridPlantLowOrder.


Alternatively, you can run the task slexPowerWindowContinuousSim.

24-36
Power Window

The position scope shows the expected result from the controller. After 30 cm, the model generates
the obstacle event and the Stateflow chart moves into its emergencyDown state. In this state,
windowDown is output until the window lowers by about 10 cm. Because the passenger window up
switch is still on, the window starts moving up again and this process repeats. Stop the simulation
and open the position scope to observe the oscillating process. In case of an emergency, the discrete-
event control rolls down the window approximately 10 cm.

Detailed Modeling of Power Effects

After an initial analysis of the discrete-event control and continuous dynamics, you can use a detailed
plant model to evaluate performance in a more realistic situation. It is best to design models at such a
level of detail in the power domain, in other words, as energy flows. Several domain-specific
MathWorks blocksets can help with this.

To take into account energy flows, add a more detailed variant consisting of power electronics and a
multibody system to the window_system variant subsystem.

To open the model and explore the more detailed plant variant, in the project, run configureModel
slexPowerWindowPowerEffects.

Double-click the slexPowerWindowExample model window_system/Power Effects - Visualization/


detailed_window_system block.

Power Electronics Subsystem

The model must amplify the control signals generated by the discrete-event controller to be powerful
enough to drive the DC motor that moves the window.

The amplification modules model this behavior. They show that a switch either connects the DC motor
to the battery voltage or ground. By connecting the battery in reverse, the system generates a
negative voltage and the window can move up, down, or remain still. The window is always driven at
maximum power. In other words, no DC motor controller applies a prescribed velocity.

To see the implementation, double-click the slexPowerWindowExample model window_system/


Power Effects - Visualization/detailed_window_system/amplification_up block.

24-37
24 Power Window Example

Multibody System

This implementation models the window using Simscape Multibody blocks.

To see the actuator implementation, double-click the slexPowerWindowExample model


window_system/Power Effects - Visualization/detailed_window_system/actuator block.

To see the window implementation, double-click the slexPowerWindowExample model


window_system/Power Effects - Visualization/detailed_window_system/plant block.

24-38
Power Window

This implementation uses Simscape Multibody blocks for bodies, joints, and actuators. The window
model consists of:

• A worm gear
• A lever to move the window holder in the vertical direction

The figure shows how the mechanical parts move.

Iterate on the Design

An important effect of the more detailed implementation is that there is no window position
measurement available. Instead, the model measures the DC motor current and uses it to detect the
endstops and to see if an obstacle is present. The next stage of the system design analyzes the control
to make sure that it does not cause excessive force when an obstacle is present.

In the original system, the design removes the obstacle and endstop detection based on the window
position and replaces it with a current-based implementation. It also connects the process to the
controller and position and force measurements. To reflect the different signals used, you must
modify the data definition. In addition, observe that, because of power effects, the units are now
amps.

PSPEC 1.3.1: DETECT ENDSTOP


ENDSTOP = ARMATURE_CURRENT > ENDSTOP_MAX

PSPEC 1.3.2: DETECT OBSTACLE


OBSTACLE = (ARMATURE_CURRENT > OBSTACLE_MAX) and MOVE_UP for 500 ms

PSPEC 1.3.3: ABSOLUTE VALUE


ABSOLUTE_ARMATURE_CURRENT = abs(ARMATURE_CURRENT)

This table lists the additional signal for the Context Diagram: Power Window System data definitions.

Context Diagram: Power Window System Data Definition Changes

Signal Information Continuous/ Data Type Values


Type Discrete
ARMATURE_CURRENT Data Continuous Real –20 to 20 A

24-39
24 Power Window Example

This table lists the changed signals for the Activity Diagram: Detect Obstacle Endstop data
definitions.

Activity Diagram: Detect Obstacle Endstop Data Definition Changes

Signal Information Continuous/ Data Type Values


Type Constant
ABSOLUTE_ARMATURE_‐ Data Continuous Real 0 to 20 A
CURRENT
ENDSTOP_MAX Data Constant Real 15 A
OBSTACLE_MAX Data Constant Real 2.5 A

To see the window subsystem, double-click the slexPowerWindowExample model window_system/


Power Effects - Visualization/detailed_window_system/plant/window block.

The implementation uses a lookup table and adds noise to allow evaluation of the control robustness.
To see the implementation of the friction subsystem, double-click the slexPowerWindowExample
model window_system/Power Effects - Visualization/detailed_window_system/plant/window/friction
block.

24-40
Power Window

Control Law Evaluation

The idealized continuous plant allows access to the window position for endStop and obstacle
event generation. In the more realistic implementation, the model must generate these events from
accessible physical variables. For power window systems, this physical variable is typically the
armature current, Ia, of the DC motor that drives the worm gear.

When the window is moving, this current has an approximate value of 2 A. When you switch the
window on, the model draws a transient current that can reach a value of approximately 10 A. When
the current exceeds 15 A, the model activates endstop detection. The model draws this current when
the angular velocity of the motor is kept at almost 0 despite a positive or negative input voltage.

Detecting the presence of an object is more difficult in this setup. Because safety concerns restrict
the window force to no more than 100 N, an armature current much less than 10 A should detect an
object. However, this behavior conflicts with the transient values achieved during normal operation.

Implement a control law that disables object detection during achieved transient values. Now, when
the system detects an armature current more than 2 A, it considers an object to be present and
enters the emergencyDown state of the discrete-event control. Open the force scope window
(measurements are in newtons) to check that the force exerted remains less than 100 N when an
object is present and the window reverses its velocity.

24-41
24 Power Window Example

In reality, far more sophisticated control laws are possible and implemented. For example, you can
implement neural-network-based learning feedforward control techniques to emulate the friction
characteristic of each individual vehicle and changes over time.

Visualization of the System in Motion

If you have Simulink 3D Animation™ software installed, you can view the geometrics of the system in
motion via a virtual reality world. If the VR Sink block is not yet open, in the
slexPowerWindowExample/window_world/Simulink_3D_Animation View model, double-click
the VR Sink block.

To simulate the model with a stiff solver:

1 In a project, run the task, slexPowerWindowPowerEffectsSim. This batch job sets the solver
to ode23tb (stiff/TR-BDF2).
2 In the slexPowerWindowExample model passenger_switch/Normal block, set the passenger up
switch to on.
3 In the slexPowerWindowExample model driver_switch/Normal block, set the driver up switch
to off.
4 Simulate the model.
5 Between 10 ms and 1 s in simulation time, switch off the slexPowerWindowExample/
passenger_switch/Normal block passenger up switch to initiate the auto-up behavior.

24-42
Power Window

6 Observe how the window holder starts to move vertically to close the window. When the model
encounters the object, it rolls the window down.
7 Double-click the slexPowerWindowExample model passenger_switch/Normal block driver down
switch to roll down the window completely and then simulate the model. In this block, at less
than one second simulation time, switch off the driver down switch to initiate the auto-down
behavior.

8 When the window reaches the bottom of the frame, stop the simulation.
9 Look at the position measurement (in meters) and at the armature current (Ia) measurement (in
amps).

Note The absolute value of the armature current transient during normal behavior does not
exceed 10 A. The model detects the obstacle when the absolute value of the armature current
required to move the window up exceeds 2.5 A (in fact, it is less than –2.5 A). During normal
operation, this is about 2 A. You might have to zoom into the scope to see this measurement. The
model detects the window endstop when the absolute value of the armature current exceeds 15
A.

24-43
24 Power Window Example

Variation in the armature current during normal operation is due to friction that is included by
sensing joint velocities and positions and applying window specific coefficients.

Realistic Armature Measurement

The armature current as used in the power window control is an ideal value that is accessible
because of the use of an actuator model. In a more realistic situation, data acquisition components
must measure this current value.

To include data acquisition components, add the more realistic measurement variant to the
window_system variant subsystem. This realistic measurement variant contains a signal conditioning
block in which the current is derived based on a voltage measurement.

To open a model and configure the realistic measurement, in the project, run the configureModel task
slexPowerWindowRealisticArmature.

To view the contents of the Realistic Armature - Communications Protocol block, double-click the
SlexPowerWindowExample model window_system/Realistic Armature - Communications Protocol/
detailed_window_system_with_DAQ.

The measurement voltage is within the range of an analog-to-digital converter (ADC) that discretizes
based on a given number of bits. You must scale the resulting value based on the value of the resistor
and the range of the ADC.

Include these operations as fixed-point computations. To achieve the necessary resolution with the
given range, 16 bits are required instead of 8.

Study the same scenario:


1 In the slexPowerWindowExample/passenger_switch/Normal block, set the passenger up switch.
2 Run the simulation.
3 After some time, in the slexPowerWindowExample/passenger_switch/Normal block, switch off the
passenger up switch.
4 When the window has been rolled down, click the slexPowerWindowExample/passenger_switch/
Normal block driver down switch.

24-44
Power Window

5 After some time, switch off the slexPowerWindowExample/passenger_switch/Normal block driver


down switch.
6 When the window reaches the bottom of the frame, stop the simulation.
7 Zoom into the armature_current scope window and notice the discretized appearance.

Communication Protocols

Similar to the power window output control, hardware must generate the input events. In this case,
the hardware is the window control switches in the door and center control panels. Local processors
generate these events and then communicate them to the window controller via a CAN bus.

To include these events, add a variant containing input from a CAN bus and switch components that
generate the events delivered on the CAN bus to the driver switch and passenger switch variant
subsystems. To open the model and configure the CAN communication protocols, run the
configureModel task, slexPowerWindowCommunicationProtocolSim.

To see the implementation of the switch subsystem, double-click the slexPowerWindowExample/


driver_switch/Communication Protocol/driver window control switch block.

Observe a structure that is very similar to the window control system. This structure contains a:

• Plant model that represents the control switch


• Data acquisition subsystem that includes, among other things, signal conditioning components
• Control module to map the commands from the physical switch to logical commands
• CAN module to post the events to the vehicle data bus

You can add communication effects, such as other systems using the CAN bus, and more realism
similar to the described phases. Each phase allows analysis of the discrete-event controller in an
increasingly realistic situation. When you have enough detail, you can automatically generate
controller code for any specific target platform.

Automatic Code Generation for Control Subsystem


You can generate code for the designed control model, slexPowerWindowExample.

24-45
24 Power Window Example

1 Display the sample rates of the controller. In the Simulink Editor, on the Debug tab, select
Information Overlays > Sample Time > Colors. Observe that the controller runs at a uniform
sample rate.

2 Right-click the power_window_control_system block and select C/C++ Code > Build This
Subsystem.

References
Mosterman, Pieter J., Janos Sztipanovits, and Sebastian Engell, “Computer-Automated Multiparadigm
Modeling in Control Systems Technology,” IEEE Transactions on Control Systems Technology, Vol. 12,
Number 2, 2004, pp. 223–234.

24-46
Power Window

See Also

Related Examples
• “Power Window Control Project”

More About
• “Project Management”

24-47
25

Schedule Editor

• “What are Partitions?” on page 25-2


• “Create Partitions” on page 25-4
• “Using the Schedule Editor” on page 25-11
• “Schedule the Partitions” on page 25-15
• “Generate Code from a Partitioned Model” on page 25-22
• “Export-Function Conversion” on page 25-26
• “Create and Analyze Random Schedules for a Model Using the Schedule Editor API”
on page 25-27
• “Events in Schedule Editor” on page 25-33
25 Schedule Editor

What are Partitions?


Partitions are components of a model that execute independently as atomic tasks. In multi-tasking
models, partitions are created from model components. Periodic partitions are scheduled as a
function of sample times in a model. In export-function models, the root function-call inputs are
defined as partitions. These partitions have a schedule associated with it, which tells order in which
the partitions execute.

With partitions, you can separate parts of the model which you can explicitly control. You can think of
periodic partitions as components that run at specific rates in a model. Aperiodic partitions are
components that run at specified hit times. The schedule of these partitions have an impact on
simulation and code generation.

The Schedule Editor enables you to partition the model and interact with those partitions. The
Schedule Editor shows partitions, the connections between them, and the ordering of the partitions

There are three types of partitions:

Types of Partitions Image Description


Implicit Automatically created by Simulink.
Blocks running at the base rate show up
as an implicit partition.
Periodic User-defined partitions from the atomic
subsystems and/or Model blocks. Periodic
partitions can also be defined by export-
functions. These partitions execute based
on their sample time and thus their
execution is periodic.
Aperiodic Aperiodic partitions are partitions which
have no constraints and can be made to
execute at any time. Specify the hit
times in the Property Inspector of the
Schedule Editor, at which you want to
run the aperiodic partition. You can also
use events in the Schedule Editor to
schedule execution of the aperiodic
partitions.

The blocks running at the base rate in the model is shown as an implicit partition in the Schedule
Editor. The base rate is the fastest discrete rate in the model. D1 denotes the base rate. D1
annotation also appears in the Timing Legend.

The default partitions that are already present in the model are also implicit partitions.

The partition colors match their rate.

25-2
What are Partitions?

See Also

More About
• “Create Partitions” on page 25-4
• “Using the Schedule Editor” on page 25-11
• “Using the Schedule Editor” on page 25-11
• Schedule Editor

25-3
25 Schedule Editor

Create Partitions

Partitioning a Model
Partitions are components of a model that execute independently as atomic tasks. In multi-tasking
models, partitions are created from model components. Periodic partitions are scheduled as a
function of sample times in a model. In export-function models, the root function-call inputs are
defined as partitions. These partitions have a schedule associated with them, which tells what order
the partitions execute.

With partitions, you can separate parts of the model which you can explicitly control. You can think of
periodic partitions as components that run at specific rates in a model. Aperiodic partitions are
components that run at specified hit times or specified events. The schedule of these partitions have
an impact on simulation and code generation.

The Schedule Editor enables you to partition the model and interact with those partitions. The
Schedule Editor shows partitions, the connections between them, and the order of the partitions.

There are three types of partitions:

Types of Partitions Image Description


Implicit Automatically created by Simulink.
Blocks running at the base rate show up
as an implicit partition.
Periodic User-defined partitions from the atomic
subsystems and/or Model blocks. Periodic
partitions can also be defined by export-
functions. These partitions execute based
on their sample time and thus their
execution is periodic.
Aperiodic Aperiodic partitions are partitions which
have no constraints and can be made to
execute at any time. Specify the hit
times in the Property Inspector of the
Schedule Editor, at which you want to
run the aperiodic partition. You can also
use events in the Schedule Editor to
schedule execution of the aperiodic
partitions.

The blocks running at the base rate in the model is shown as an implicit partition in the Schedule
Editor. The base rate is the fastest discrete rate in the model. D1 denotes the base rate. D1
annotation also appears in the Timing Legend. The D1 partition or implicit partition always remains
the first discrete partition in the order.

The default partitions that are already present in the model are also implicit partitions.

The partition colors match their rate.

25-4
Create Partitions

Create Partitions from a Rate-Based Model


Partitioning is enabled only on multitasking, fixed-step and variable-step solver models. To choose
multitasking execution mode, in Solver selection on the Solver pane, select the Type to be Fixed-
step or Variable-step. Select the Treat each discrete rate as a separate task check box on the
Solver pane of the Configuration Parameters dialog box. For more information on multitasking
execution mode, see “Time-Based Scheduling and Code Generation” (Embedded Coder).

As a best practice, enable the Automatically handle rate transition for data transfer setting in
the Solver pane. When you check Automatically handle rate transition for data transfer,
Simulink inserts Rate Transition blocks between blocks when rate transitions are detected. Simulink
handles rate transitions for asynchronous and periodic tasks. Simulink adds the hidden blocks
configured to ensure data integrity and determinism for data transfers. When you check Treat each
discrete rate as a separate task, Simulink selects multitasking execution for models operating at
different rates. It also specifies that groups of blocks with the same execution priority are processed
through each stage of simulation (for example, calculating output and updating states) based on task
priority.

To see default partitions in the Schedule Editor, open the Schedule Editor. On the Modeling tab, click

Schedule Editor. Update the diagram by clicking the icon on the toolstrip. The default
partitions in the model are called implicit partitions. You can also create partitions in the model
through an atomic subsystem or a model block.

Create Partitions Using Manage Partitions

In the Schedule Editor, use the Manage Partitions panel to create partitions. To open the Manage

Partitions panel, click Manage Partitions, on the Schedule Editor toolstrip. The changes
made in Manage Partitions are applied to the model to create partitions after updating the diagram.
Manage Partitions shows the model hierarchy with the Subsystem blocks and Model blocks which
can be explicitly partitioned.

To create partitions from Subsystem blocks, select the subsystems and click the . To create
partitions from Model blocks, select the Model blocks and click . Enter partition names in the
column Partition Name, and sample times in the column Sample Time. Repeat the steps for all the
subsystems and Model blocks in the model that you want to partition. Update the diagram to see the
created partitions in the Schedule Editor. The partitions appear in the graph with their deduced data
dependencies and order.

25-5
25 Schedule Editor

Note Creating partitions using the Manage Partitions panel makes changes to the subsystem or
model block parameters.

The following example shows how to configure a model for partitioning and create partitions by using
Manage Partitions panel in the Schedule Editor.
1 Open the “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')
sldemo_fuelsys
2 Open the Schedule Editor.

Open the Schedule Editor On the Modeling tab, click Schedule Editor. To see the default
partitions, click Update Diagram in the Schedule Editor. Two implicit partitions, created
automatically by Simulink, are seen in the Schedule Editor.
3 Create partitions.

Open the Manage Partitions panel. In the panel, expand the fuel_rate_control subsystem.
Select the airflow_calc subsystem and click . To change the default partition name and
sample time, click the default name and sample time.

25-6
Create Partitions

To create a partition for the fuel_calc subsystem, select the fuel_calc subsystem and click
.

The Manage Partitions panel gives you the default partition names and sample times.

Update the diagram to see the newly created partitions.

Create Partitions from Atomic Subsystem Blocks

You can partition an atomic subsystem. An atomic subsystem is treated by Simulink as a unit when
determining the execution order of block methods(partitioning is enabled only on multitasking, fixed-
step and variable-step solver models). To create partitions from an atomic subsystem block, go to the
Block Parameters dialog box. Select Periodic partition from the Schedule as drop-down. Give
the partition a name and a discrete sample time and click OK. This creates an explicit partition for
this block. To see this partition in the Schedule Editor, update the diagram. The partition appears in
the graph and in the Order with the connections based on the signals in the model.

Create Partitions from Model Blocks

To create partitions from a Model block, in the Model events simulation, select Schedule rates
and Schedule Editor from the Schedule rates with drop-down. When you enable partitioning

25-7
25 Schedule Editor

from a referenced model, partitions are created from all the Model blocks present in the referenced
model. These partitions are scoped by the model block name. To see this partition in the Schedule
Editor, update the diagram. The partitions appear in the graph and in the Order column with the
connections based on the design of your model.

Export-Function Partitions
In export-function models, partitions are created from the function calls present in the model. To
create partitions from the function calls in the export-function models, reference the export-function
model in a top model. Schedule the Model block using the Schedule Editor through the block
parameters. Partitions are then created from the function calls and their order is determined by the
Schedule Editor.

1 Create an export-function model.


2 Add a Model block that references the export-function model.
3 Set the parameter to partition the export-function model.

Referencing an export-function model from a Model block allows you to partition the function calls
without changing the model itself. Simulink functions in an export-functions model cannot be
scheduled, and do not appear as partitions in the Schedule Editor.

25-8
Create Partitions

1 Add a Model block to a new Simulink model. In the Model name box, enter the name of an
export-function model. For example, use the export-function model created in “Create Export-
Function Model” on page 10-98.
2 To enable the use of the Schedule Editor, configure the model to be multitasking. Open the Model
Configuration Parameters. In Solver selection on the Solver pane, set the Type to Fixed-step.
Check the Treat each discrete rate as a separate task and Automatically handle rate
transition for data transfer parameters. Click OK. The model is enabled for partitioning.

Note Do not convert a subsystem into a model because it automatically creates Inport blocks.

3 Add Outport blocks to the output_100ms and output_10ms ports for saving simulation data to
MATLAB. For this example, in the export-function model, set the sample time of both the function
calls to -1.
4 Add a Sine Wave block to provide data input. Set Amplitude to 2 and Sample time to 0.01.
5 To partition the function calls of the export-function model, in the Block Parameters dialog box
for the Model block, select Schedule Editor option from the Schedule Rates with drop-down
menu.
6 Open the Schedule Editor and update the diagram to see the function calls as partitions.

25-9
25 Schedule Editor

See Also
Schedule Editor

More About
• “Schedule the Partitions” on page 25-15
• “Generate Code from a Partitioned Model” on page 25-22

25-10
Using the Schedule Editor

Using the Schedule Editor


The Schedule Editor is a scheduling tool that represents the components in the model known as
partitions, the data connections between them, and the order of those partitions.

Partitions are the components of the model that execute independently as tasks. The data connections
between the partitions show the flow of the data between those partitions. The scheduling of these
partitions is based on the rates and the events in the model. This schedule is shown in the Order
table in the Schedule Editor.

Using the Schedule Editor you can:

• Create partitions and specify their order


• Edit and analyze the schedule of the executable partitions without disturbing the structure of the
model.
• Visualize how Simulink executes partitions

Changes made in the Schedule Editor affect both, simulation and code generation.

Using the Schedule Editor


The Schedule Editor consists of two parts representing two different views of partitions in the model.

• A graph that shows the partitions and the data connections between them.

• A table that shows the order in which the partitions execute.

Note Aperiodic partitions are listed in the order of their priority.

25-11
25 Schedule Editor

Changing one of the views impacts the other.

To use the Schedule Editor, on the Modeling tab, click Schedule Editor. If the model is already

partitioned, you can open the Schedule Editor by clicking the badge, , which appears above the
blocks. To see the default partitions present in the model in the Schedule Editor, update the diagram

with icon, on the toolstrip or by selecting Ctrl+D. As you create partitions in the model and
update the diagram, partitions appear in the Schedule Editor.

To check how the partitions map to the model, right-click the partitions and select Show Source. The
Simulink model window appears with every block corresponding to the partition highlighted.

Order

The Order pane shows the order in which the partitions execute. To change the order, you can drag
and drop the partitions. You can also use the Up and Down arrows on the toolstrip. Partitions are
sorted based on their rates. You can only reorder the partitions with the same rate. Clicking a
partition in the Order, highlights the corresponding partition in the graph. On changing the order,
the connections that are affected by this specified change get highlighted.

Note Aperiodic partitions are listed in the order of their priority.

25-12
Using the Schedule Editor

Connections

Connections between the partitions show data dependencies. You can right-click the connections
between the partitions to change the constraints on data connections. The different types of
connections illustrate how the partitions behave with each other.

The types of connections are:

• Dependency – Indicates that the source always runs before the destination. The dependency
connection is a solid line.

• Delay – Indicates that the destination runs before the source. When the destination runs before
the source, a scheduling delay is introduced. The delay connection is a dashed line.

You can put these types of constraints on connections:

• Allow Delay – Inserts a delay when required. When you specify this constraint for a connection,
Simulink inserts a delay for that connection only when necessary. The unlock icon on the
connections signifies an allowed delay. When you select this constraint on a connection, Simulink
prefers these connections to be turned into a delay if necessary over other connections.

This constraint is displayed as one of these options.

• Prevent Delay – Prevents delay from being inserted in the connection. When you specify this
constraint for a connection, Simulink ensures that the connection always remains as a
dependency. The lock icon on the connection indicates that the connection is locked to be a
dependency and is not changed to a delay.

25-13
25 Schedule Editor

See Also
Schedule Editor

More About
• “Create Partitions” on page 25-4
• “Schedule the Partitions” on page 25-15
• “Generate Code from a Partitioned Model” on page 25-22

25-14
Schedule the Partitions

Schedule the Partitions


These two examples walk through the workflow of partitioning a model, scheduling the partitions and
analyzing the simulations before and after editing the schedule of the partitions.

Schedule an Export-Function Model Using the Schedule Editor

This example shows how to view and edit the order of function-calls in an export-function model using
the Schedule Editor. As in all export-function models, the desired functionality is modeled as function-
call subsystems. These function-call subsystems define the partitions that are scheduled by the
Schedule Editor.

With the Schedule Editor, you can easily view and edit the schedule of the function-calls. The
behavior of the system depends on the order of these partitions. In this example, we change the order
and observe its effects on the behavior of the system by simulating the model. To see the impact of
editing the schedule on the simulation, we compare the model simulations before and after
scheduling.

Create Partitions from Referenced Export-Function Model

To view and edit the schedule of the export-function model, reference the model.
open_system('ThrottlePositionControlTop.slx');

ThrottlePositionControl is the referenced export-function model. By default, each function has


an input port that can be used to trigger these functions. The Schedule Editor automatically handles
these ports. To use the Schedule Editor, set the Schedule Rates With parameter to Schedule Editor.

25-15
25 Schedule Editor

set_param('ThrottlePositionControlTop/ThrottleControl','ScheduleRatesWith','Schedule Editor');

Establish a Simulation Baseline

To observe the impact of scheduling on the model behavior, establish a baseline by simulating the
model before editing the schedule. Simulate the model.
sim('ThrottlePositionControlTop');

Open the Schedule Editor

To open the Schedule Editor, click Schedule Editor in the Design section of the Modeling tab. In
the Schedule Editor, different components of the model are represented as partitions. Update the
diagram to see the partitions. Partitions are the entry-points in the model. The Schedule Editor shows
the order and data communications of these partitions. The arrows are data connections between the
partitions that show the data flow. The dashed lines indicate that there is a delay because the source
runs after the destination. The solid lines indicate that there is no delay as the source runs before the
destination.

Edit Partition Schedule

The Order pane shows the order the partitions run in at a given time step. Assume that the order of
the partitions is in an imperfect state. In this case, to remove the delay, you want to run the
ThrottleControl.ActuatorRun5ms partition after the ThrottleControl.ControllerRun5ms
partition.

Drag ThrottleControl.ActuatorRun5ms after the ThrottleControl.ControllerRun5ms in


the Order pane. Observe that the delay between the ThrottleControl.ControllerRun5ms and
the ThrottleControl.ActuatorRun5ms partitions changes to a dependency. Observe that now

25-16
Schedule the Partitions

there is no delay between the executions of ThrottleControl.ControllerRun5ms and


ThrottleControl.ActuatorRun5ms.

Schedule the Execution of Aperiodic Partitions

The export-function model contains an unconstrained partition,


AccelerationPedalPositionSensor. Suppose you want to schedule an unconstrained partition to
simulate as if it were discrete. Schedule ThrottleControl.AppSnsrRun partition to run at
[0:0.02:100] to observe its behavior at different instances of time. Click the unconstrained partition
and enter [(1:5000)*.02] for Trigger in the Property Inspector.

Compare the Runs in Simulation Data Inspector

Now, simulate the model with the changed schedule.

Open the Simulation Data Inspector. Select the two runs and compare. You can see how changing the
schedule impacts the model behavior.

25-17
25 Schedule Editor

Copyright 2018-2022 The MathWorks, Inc.

Schedule a Rate-Based Model Using the Schedule Editor

This example shows how to partition a rate-based model using the Schedule Editor. Partitions are the
components of the model that can execute independently. In this example, we convert the subsystems
into partitions and view and edit their schedule.

With the Schedule Editor, you can easily view and edit the schedule of the partitions. The behavior of
the system depends on the order of these partitions. In this example, we observe the effects of
scheduling this model on the simulation. To see the impact of partitioning and scheduling the model,
we compare the model simulations before and after creating partitions and scheduling them.

Open the Model and Establish a Simulation Baseline

Open the model of a Throttle Position Control system and simulate it to establish a baseline for
comparison

open_system('ScheduleEditorWithSubsystemPartitions');
sim('ScheduleEditorWithSubsystemPartitions');

25-18
Schedule the Partitions

Open the Schedule Editor and Create Partitions

To open the Schedule Editor, click Schedule Editor in the Design section of the Modeling tab. Use
Manage Partitions to create partitions from the subsystems in your model. Select all the
subsystems in ThrottlePositionControl, and click the Create Partitions icon on the top of the
Manage Partitions panel. Specify the names for the partitions and their sample time. Update the
diagram to see the partitions in the Schedule Editor.

The arrows are data connections between the partitions that show the data flow. The dashed lines
always indicate that there is a delay as the source runs after the destination. The solid lines indicate
that there is no delay as the source runs before the destination.

25-19
25 Schedule Editor

Edit Partition Schedule

The Order shows the order the partitions run at a given time step. Assume that the order of the
partitions is in an imperfect state. In this case, you want to run the ActuatorRun5ms partition before
the ControllerRun5ms partition. Drag ActuatorRun5ms before the ControllerRun5ms in the
order. Observe that the dependency between the ControllerRun5ms and the ActuatorRun5ms
partitions changes to a delay.

25-20
Schedule the Partitions

Compare Runs in Simulation Data Inspector

Now, simulate the model with the changed schedule.

Open the Simulation Data Inspector. Select the two runs and compare. You can see how changing the
schedule impacts the model behavior.

See Also
Schedule Editor

More About
• “Create Partitions” on page 25-4
• “Generate Code from a Partitioned Model” on page 25-22

25-21
25 Schedule Editor

Generate Code from a Partitioned Model


Partitioning and scheduling a model has an impact on the order of the function calls in the generated
code. Using the Schedule Editor to edit the schedule of a rate-based model or a referenced export-
function model, the order of the functions in the generated code depends on the specified schedule in
the Schedule Editor. The resulting code shows every partition as an entry point. The generated code
does not include the scheduler and it must be provided by the user.

Note To use the code generation functionality, Embedded Coder and Simulink Coder are required.

To see the impact of the Schedule Editor on the generated code, use the model that is created in
“Create Rate-Based Model” on page 10-60.

1 Open the Schedule Editor from the Design section of the Modeling tab. Use the Manage
Partitions panel to create partitions for Scheduled Subsystem 1 and Scheduled Subsystem 2
with 0.01 sample time. Update the diagram.
2 Change the order of the partitions by dragging Scheduled_Subsystem_2 above
Scheduled_Subsystem_1.

25-22
Generate Code from a Partitioned Model

3 Generate code for the component model. From the Apps tab, select C/C++ Code > Build
Model.

In the generated code, the order of the functions depends on the schedule specified in the Schedule
Editor.

25-23
25 Schedule Editor

25-24
Generate Code from a Partitioned Model

Note Changing the constraints on the connections does impact the generated code. The changes
with respect to connections are useful to set preferences about delays and dependencies.

See Also
Schedule Editor

More About
• “Create Partitions” on page 25-4
• “Schedule the Partitions” on page 25-15

25-25
25 Schedule Editor

Export-Function Conversion

To use the Schedule rates with option with the Schedule Editor, the model can not be an export-
function model. To enable Schedule rates with option, convert your model to a rate-based model. To
convert your model to a rate-based model, remove the function call input ports. For more information,
see “Export-Function Models” on page 10-68.

25-26
Create and Analyze Random Schedules for a Model Using the Schedule Editor API

Create and Analyze Random Schedules for a Model Using the


Schedule Editor API

This example uses the Schedule Editor API to perform operations on the schedule. Then it uses a
function to generate random schedules and analyze them in Simulation Data Inspector

Open the Model and Get the Schedule Object

Open a model of a Throttle Position Control system and use get_param to obtain the
simulink.schedule.OrderedSchedule object. This object contains the current schedule.

model = 'ScheduleEditorAPIWithSubsystemPartitions';
open_system(model);
schedule = get_param(model, 'Schedule')

schedule =

OrderedSchedule with properties:

Order: [9x3 table]


RateSections: [3x1 simulink.schedule.RateSection]
Events: [0x1 simulink.schedule.Event]
Description: ''

25-27
25 Schedule Editor

Examine the Schedule Object

The schedule object has an Order property that contains the execution order of the partitions in the
model. The Order property displays a table that contains partition names, their index, type, and their
trigger.

schedule.Order

ans =

9x3 table

Index Type Trigger


_____ ________ _______

Cont 1 Periodic "0"


TPSSecondaryRun5ms 2 Periodic "0.005"
MonitorRun5ms 3 Periodic "0.005"
ControllerRun5ms 4 Periodic "0.005"
ActuatorRun5ms 5 Periodic "0.005"
D2 6 Periodic "0.005"
D3 7 Periodic "0.01"
APPSnsrRun 8 Periodic "0.01"
TPSPrimaryRun10ms 9 Periodic "0.01"

Use the index variable in the Order table to change the execution order of the model

schedule.Order.Index('ActuatorRun5ms') = 2;
schedule.Order

ans =

9x3 table

Index Type Trigger


_____ ________ _______

Cont 1 Periodic "0"


ActuatorRun5ms 2 Periodic "0.005"
TPSSecondaryRun5ms 3 Periodic "0.005"
MonitorRun5ms 4 Periodic "0.005"
ControllerRun5ms 5 Periodic "0.005"
D2 6 Periodic "0.005"
D3 7 Periodic "0.01"
APPSnsrRun 8 Periodic "0.01"
TPSPrimaryRun10ms 9 Periodic "0.01"

Any moves within the Order property that are made to modify the schedule should result in valid
schedule. To perform the schedule modifications and valid moves easier, each partition is grouped
with partitions of the same rate in the RateSections property. Each element of the RateSection
property contains an order table with partitions of the same rate.

schedule.RateSections(2)
schedule.RateSections(2).Order

25-28
Create and Analyze Random Schedules for a Model Using the Schedule Editor API

ans =

RateSection with properties:

Rate: "0.005"
Order: [5x3 table]

ans =

5x3 table

Index Type Trigger


_____ ________ _______

ActuatorRun5ms 2 Periodic "0.005"


TPSSecondaryRun5ms 3 Periodic "0.005"
MonitorRun5ms 4 Periodic "0.005"
ControllerRun5ms 5 Periodic "0.005"
D2 6 Periodic "0.005"

Use the index variable to move the partitions within RateSections.


schedule.RateSections(2).Order.Index('ActuatorRun5ms') = 5;
schedule.Order

ans =

9x3 table

Index Type Trigger


_____ ________ _______

Cont 1 Periodic "0"


TPSSecondaryRun5ms 2 Periodic "0.005"
MonitorRun5ms 3 Periodic "0.005"
ControllerRun5ms 4 Periodic "0.005"
ActuatorRun5ms 5 Periodic "0.005"
D2 6 Periodic "0.005"
D3 7 Periodic "0.01"
APPSnsrRun 8 Periodic "0.01"
TPSPrimaryRun10ms 9 Periodic "0.01"

Create a Function to Generate Random Schedules

In this section, we create three different functions: randomSchedule,


generateSimulationInputs and simulateRandomSchedules

randomSchedule function is used to create random schedules by using random permutations of


index modifications in the schedule object. Using the Order and the RateSections properties of
the schedule object, partitions in the schedules are moved around in different, random
combinations. With these randomly created schedules, models are simulated and compared to study
the effect of different schedules on simulation. In the function randomSchedule, the input is the
model name. Then use get_param to obtain the simulink.schedule.OrderedSchedule object of

25-29
25 Schedule Editor

the model. The schedule object and its properties are used to modify and randomize the schedules.
Create a variable firstExecutionOrder for the first rate section of the model. The
rateSections(1).ExecutionOrder = [firstExecutionOrder(1,:);
reSchedule(firstExecutionOrder(2:end,:))] line of code calls the function reSchedule
which creates random permutations of the indexes.
type randomSchedule

function schedule = randomSchedule(model)


% schedule = randomSchedule(model) Produces a
% simulink.schedule.OrderedSchedule that has a randomized permutation
% of the model's original execution order schedule

arguments
model char = bdroot
end

schedule = get_param(model, 'Schedule');

rateSections = schedule.RateSections;
firstOrder = rateSections(1).Order;

% This assumes that the slowest discrete rate is at index 1. This may
% not be the case for all models (ex. JMAAB-B).
rateSections(1).Order = [firstOrder(1,:); reSchedule(firstOrder(2:end,:))];

for i=2:length(rateSections)
rateSections(i).Order = reSchedule(rateSections(i).Order);
end

schedule.RateSections = rateSections;
end

function out = reSchedule(in)


numPartitions = height(in);
in.Index = in.Index(randperm(numPartitions));
out = in;
end

To analyze the effects of different schedules on the model, simulate the model with the different
schedules. In this function, create an array of Simulink.SimulationInput objects. Through this
array of Simulink.SimulationInput objects, you can apply the schedules to the model with the
setModelParameters method of the Simulink.SimulationInput object.
type generateSimulationInputs

function in = generateSimulationInputs(model, numSimulations)


% in = generateSimulationInputs(model, numSimulations) Generates
% numSimulations Simulink.SimulationInput objects each containing a
% different, randomized execution order schedule
arguments
model char = bdroot
numSimulations double = 10
end

in(numSimulations) = Simulink.SimulationInput();

25-30
Create and Analyze Random Schedules for a Model Using the Schedule Editor API

in = in.setModelName(model);
for idx = 1:numSimulations
in(idx) = in(idx).setModelParameter('Schedule', randomSchedule(model));
end
end

In the last function, use the array of Simulink.SimulationInput objects to run multiple
simulations. Once the simulations are complete, you can plot the output of all the simulations in
Simulation Data Inspector.
type simulateRandomSchedules

function out = simulateRandomSchedules(model, numSimulations)


% out = simulateRandomSchedules(model, numSimulations) Simulates a
% model numSimulations number of times. Each simulation has a
% randomized execution order schedule.
arguments
model char = bdroot
numSimulations double = 10
end

in = generateSimulationInputs(model, numSimulations);
out = sim(in);
plot(out);
end

Execute the Functions

Now run the above functions for the ScheduleEditorAPIWithSubsystemPartitions model.


First, use the randomSchedule function to create randomly generated schedules, then, use the
generateSimulationInputs function to generate an array of Simulink.SimulationInput
objects, and use the simulateRandomSchedule function to simulate the model with different
schedules and plot their results for comparison. Let's run simulations with 15 randomly generated
schedules.
simulateRandomSchedules(model,15)

[13-Feb-2024 16:23:50] Running simulations...


[13-Feb-2024 16:24:01] Completed 1 of 15 simulation runs
[13-Feb-2024 16:24:04] Completed 2 of 15 simulation runs
[13-Feb-2024 16:24:07] Completed 3 of 15 simulation runs
[13-Feb-2024 16:24:10] Completed 4 of 15 simulation runs
[13-Feb-2024 16:24:13] Completed 5 of 15 simulation runs
[13-Feb-2024 16:24:15] Completed 6 of 15 simulation runs
[13-Feb-2024 16:24:18] Completed 7 of 15 simulation runs
[13-Feb-2024 16:24:21] Completed 8 of 15 simulation runs
[13-Feb-2024 16:24:23] Completed 9 of 15 simulation runs
[13-Feb-2024 16:24:26] Completed 10 of 15 simulation runs
[13-Feb-2024 16:24:29] Completed 11 of 15 simulation runs
[13-Feb-2024 16:24:32] Completed 12 of 15 simulation runs
[13-Feb-2024 16:24:34] Completed 13 of 15 simulation runs
[13-Feb-2024 16:24:37] Completed 14 of 15 simulation runs
[13-Feb-2024 16:24:39] Completed 15 of 15 simulation runs

ans =

1x15 Simulink.SimulationOutput array

25-31
25 Schedule Editor

25-32
Events in Schedule Editor

Events in Schedule Editor


An event is a construct that represents an action, transition, or condition. You can broadcast events
from within a model hierarchy. The Schedule Editor allows you to create and manage partitions and
schedule the execution of your model. You can bind an event to an aperiodic partition that is
scheduled, based on priority, for execution when the event is broadcast. Events simplify system
creation and provide more flexibility during scheduling.

Events can connect blocks that detect important conditions with a partition to schedule the execution
of the partition when the conditions occurs. You can send Schedule Editor events from Stateflow
charts using the send keyword. You can also configure event triggers on the Inport or In Bus Element
block, and manage the events in the Schedule Editor.

Event Management in the Schedule Editor


Each model in a model hierarchy has its own Events panel in the Schedule Editor, that contains all
the events present in the model and the model's children. When you open the Schedule Editor and
update the diagram, all partitions and events present in the model appear in the Schedule Editor.
Through the Events panel, you can:

• Create an event.
• Delete an event.
• Rename an event.
• Get an event.
• Bind an event to a partition.
• Unbind an event from a partition.

You can create a Stateflow chart for scheduling and use the send operator to broadcast an event.
Then, in the Schedule Editor, in Events, create an event of the same name. Update the diagram to
see the broadcaster of that event which is the Stateflow chart.

25-33
25 Schedule Editor

You can also configure event triggers on the Inport or In Bus Element block that represents the port.
Then, in the Schedule Editor, specify the partition to execute in response to each event and schedule
the priority of execution. By configuring event triggers on input ports, you can model and simulate
quality of service effects. The table summarizes the event triggers you can configure on input ports.
For each input port, you can configure one event trigger for each input event.

Input Event Input Event Description Event Trigger Object


Input write Value for input port updates. simulink.event.InputWrit
e
Input write timeout Input port value does not update simulink.event.InputWrit
within a specified amount of eTimeout
time.
Input write lost Input port value update simulink.event.InputWrit
overwrites unprocessed data. eLost

The Events panel in the Schedule Editor shows you the event tree. Under every event, you can see
the broadcasters and listeners of that event.

When an event is bound to a partition, the event name appears on the left side of the partition. When
multiple events are bound to a partition, the number of bound events appears on the left side of the
partition. When multiple events are bound to a partition, in the Order table, the Trigger column
displays the number of events to which the partition is bound.

25-34
Events in Schedule Editor

Naming

Unique names are enforced for events within a model and within a model hierarchy. Within a model
hierarchy, the model name prepends the event name. For example, if the model reference named
ModelName contains an event, E1, then that event appears as ModelName.E1 in the Schedule Editor.

Scope

You can set the scope of the event in the Events panel. To set the scope of the event, right click the
event in the Events panel.

There are two options:

Global, – A global event indicates that an event is available for use anywhere in the model
hierarchy. You can use and connect the global event anywhere within the model hierarchy. A global
event is visible in the Events panel for the parent model. A global event with, the name E1, that's
present in the model named ModelName.E1, is displayed as E1 in the Events panel of the parent
model. All global events must have a unique ,name. You can use the global scope to combine multiple
instances of the same event. These multiple instances of the events can then be triggered by the
same Stateflow chart to unify scheduling.

25-35
25 Schedule Editor

Scoped, – By default, the event is scoped, indicating that the event is used within the context of
the parent model. A scoped event is visible in the Events panel for the parent model. A scoped event
with the name E1, that's present in the model named ModelName, is displayed as ModelName.E1 in
the Events panel.

Execution of Aperiodic Partitions with Events


Bind Events

An event and a partition can be bound together to indicate that the partition executes when the event
is broadcast. A partition can be bound to multiple events.

To bind multiple events to a partition, hold the Shift key and drag the event on to the partition.
Priority Based Execution

If the event-bound partition is scheduled to run before the partition driving the event, then the event-
bound partition execution preempts the execution of the partition driving the event. If the triggered
partition is scheduled to run after the partition driving the event, then the triggered partition
executes when the scheduler reaches its position in the execution order.

listenerPartition is an aperiodic partition and a listener to the event, Event1. Suppose that
Event1 comes from a Stateflow Chart present in the model and is a part of the partition called,
broadcastPartition. When broadcastPartition starts executing, Event1 occurs, which then
triggers the execution of listenerPartition.

25-36
Events in Schedule Editor

Hit Times

You can trigger an aperiodic partition at specified hit times. If a partition has hit times and gets
bound to an event, the hit times are replaced with the specified event. Likewise, if a partition is
bound to an event and hit times are added, then the bound event is removed from the partition.
Variables can also specify hit times for the aperiodic partitions. In case of ambiguous variable and
events names, events are given precedence.

Schedule Partitions with Events

This example shows how you can use events to schedule the execution of aperiodic partitions via a
Stateflow chart. You can send events from Stateflow and use those events to control the execution of
the partitions in the model by using events in Schedule Editor.

Open the Model

In this example, we simulate the digital speed control of an internal combustion engine. In this model,
the angular velocity of the engine is measured using two redundant Hall sensors, and we simulate the
failure of the Hall sensors.

The model primarily contains the following main components:

• System Inputs: Inputs and signals to exercise the system.


• Engine: Simplified representation of internal combustion engine.
• Composition: Digital controller intended to deploy on an Engine Control Unit (ECU), with a Run-
time Environment (RTE).
• Crank Dual Hall Sensor: Emulation of two redundant sensors, sensor A and sensor B.
• RTE Services: Emulation of the services provided by Engine Control Unit.

open_system("ex_engine_speed_control_system");

25-37
25 Schedule Editor

System Inputs

The system inputs for this model are designed using the Signal Editor block. The
ex_engine_speed_control_external_inputs.mat file contains the following scenario:

• The desired angular velocity is set to 2000 rpm for the entire simulation.
• At t = 01 sec, the speed controller is enabled. As a result, Hall sensor A is being used to
compute the angular velocity and the engine speed increases to 2000 rpm.
• At t = 06 sec, a failure of the first Hall sensor is injected. As a result, Hall sensor B is now
being used to compute the angular velocity, the engine speed remains at 2000 rpm.
• At t = 11 sec, a failure of the second sensor is injected. As a result, the speed controller is
disabled, the engine speed falls toward zero.
• At t = 15 sec, the failure of sensors A and B gets resolved.
• At t = 21 sec, the command to enable speed control is cycled back to zero for one second and
back to one. As a result, the engine speed increases to 2000 rpm.

Engine

The engine dynamics are represented by a Transfer Function that receives a throttle command and
converts it into torque, and a Second Order Integrator to integrate the motion.

Composition

ex_engine_speed_controller_composition implements the digital control algorithm. It


contains the following components:

• ComputeRPM_A and ComputeRPM_B: Aperiodic partitions registered as hardware interrupts.


Hall sensors A and B trigger these partitions when the engine shaft rotates by every increment
of 10 degrees.
• computeThrottle and actuatorProcessing: Periodic partitions executing at 0.001 sec.
computeThrottle interrogates the RTE at every time step.
• monitorMalfunction: Periodic partition executing at 0.01 sec. Monitors output signals of
ComputeRPM_A and ComputeRPM_B to identify potential hardware failures. If a failure is
detected, it calls a function provided by the RTE to register the failure.
• checkForRecovery: Aperiodic partition that is triggered by RTE once a failure has been
detected. Upon detection, checkForRecovery is called by the RTE at a rate of 1 sec. It calls a
function provided by the RTE if a recovery is detected.

25-38
Events in Schedule Editor

Using the Schedule Editor, the events checkForRecovery, tringCrankA, and trigCrankB are
created and bound to aperiodic partitions checkForRecovery, ComputeRPM_A, and ComputeRPM_B
respectively. These events are broadcast from the top model.

Crank Dual Hall Sensor

The Hall sensors are modeled using Hit Crossing blocks that generate a function-call every time the
engine shaft rotates by increments of 10 degrees. When the Stateflow chart gets triggered, it sends
events trigCrankA and trigCrankB, which have been bound to execute aperiodic partitions,
ComputeRPM_A and ComputeRPM_B respectively.

25-39
25 Schedule Editor

RTE Services

The RTE Services subsystem emulates functionalities available on the Run-time Environment onto
which the code generated form the digital controller is deployed. For simulation purposes, those
services are emulated using Simulink Functions.

• sendFailureStatus and recoverFailureStatus are called respectively by the


monitorMalfunctions and checkForRecovery partitions when a failure or a recovery is
detected. The global failure statuses are stored using Data Store Memory blocks for simulation
purposes.
• getFailureMode is called by the computeThrottle to verify if a failure has been detected in
one of the sensors.
• getTimeA and getTimeB simulate the RTE clock.
• Check for Recovery simulates the logic to determine when the checkForRecovery aperiodic
partition of the digital controller should be triggered. Triggering is done by broadcasting the
event checkForRecovery.

Open the Schedule Editor

To open the Schedule Editor, on the Modeling tab in the Design Section, click Schedule Editor.
Doing an Update Diagram compiles the models and shows you the existing partitions in the Schedule
Editor.

25-40
Events in Schedule Editor

Events Panel in the Schedule Editor

The events broadcast by the send keyword in Stateflow are shown in the Events panel of the
Schedule Editor, these events are bound to aperiodic partitions, so that these partitions can be
triggered from the top model. In the Events panel, you can expand each event to see the listeners

and the broadcasters of that event. The icon, indicates broadcaster of the event and the icon,

indicates the listener. In this example, the sender of the event checkForRecovery is the
Stateflow Chart in RTE Services subsystem, the sender of the events trigCrankA and
trigCrankB is the Stateflow chart in the Crank Dual Hall -> Sensor A and Sensor B.

In the Order panel, the partitions are arranged in the order of priority of execution. Since
ComputeRPM_A and ComputeRPM_B are time sensitive, their priority is the highest. Therefore, when
the events trigCranA and trigCrankB are broadcast, the corresponding partitions ComputeRPM_A
and ComputeRPM_B are executed immediately. In contrast, the aperiodic partition
checkForRecovery is less time sensitive, and is lower in the priority order. Therefore, when the
event checkForRecovery is broadcast, the execution of the corresponding partition
checkForRecovery is deferred until all the partitions with higher priority complete execution.

25-41
25 Schedule Editor

You can view this event connection in the Simulink model, this connection conveys the flow of
execution between a block broadcasting an event and another block listening to that event. To view
this connection, on the Simulink Toolstrip, on the Debug tab, select Information Overlays in the
Diagnostic section. From the drop-down menu, select Connectors in the Blocks section. Select the
Schedule Connectors option from the Connectors pane that appears on the Simulink canvas.

25-42
Events in Schedule Editor

Simulation Results

Click on View Results in Simulation Data Inspector in the model to view the results of the
simulation.

25-43
25 Schedule Editor

Test Harness Generation


You can use the Schedule Editor to generate a test harness for a model with events. Using events
with test harnesses helps you avoid complex wiring between the test sequence block and the entire
system.

The generated test harness gets its own Schedule Editor, which enables you to easily send events
through the test harness. Through the test harness scheduler, you can test the model under different
scenarios by triggering events at specific times.

The Events panel also allows you to bind existing events to other aperiodic partitions. You can do this
by dragging and dropping the event over a valid aperiodic partition, or by adding the partition

25-44
Events in Schedule Editor

directly using the dropdown. You can order the partitions that have events as their Trigger in the
Order table relative to the other partitions. You can also create events in Schedule Editor. Click the
plus icon. Double click Add Row to create a new event. You can use this event to send from Stateflow
to schedule execution of an aperiodic partition.

Limitations and Error Conditions


• Events in the Schedule Editor cannot be used in models with export-functions.
• Events do not support code generation and do not impact the generated code.

Events in the Schedule Editor use the following guidelines:

• An event cannot be sent before that event has processed.


• Duplicate event names in the parent model caused by giving two model references the same name
are not allowed.
• Infinite looping is not allowed.
• A partition cannot send an event that triggers itself.

See Also
Schedule Editor

More About
• “Create Partitions” on page 25-4
• “Generate Code from a Partitioned Model” on page 25-22

25-45
26

Software Modeling
26 Software Modeling

Software Component Modeling


In this section...
“Create Models of Software Components” on page 26-2
“Create Model of Target Environment” on page 26-6
“Test System by Simulating Composition Model” on page 26-7
“Integrate Components into Software Architectures” on page 26-7
“Design Software Architectures” on page 26-7
“Generate Code for Software Components” on page 26-8

Software modeling refers to modeling, simulating, and generating code for algorithms that run in
software frameworks. Simulink provides a range of modeling abstractions, semantics, and
configuration capabilities that help you create algorithm models that leverage the scheduling,
communication, time, memory, diagnostic, and multicore support for these frameworks. For example,
when designing a model, you can:

• Partition the design for time- and event-based scheduling.


• Design software component data interfaces.
• Represent call to target platform services such as diagnostic and memory services.
• Configure the model for concurrent execution on multicore systems.
• Create test harnesses and simulate model compositions.
• Integrate with standard middleware software, such as AUTOSAR and DDS.
• Represent complex power-cycle and mode-transition logic.

By using model reference, variant, and data management capabilities, you can design software
components for reuse within an application and across software frameworks.

When you use Simulink with Simulink code generation and verification and testing products, you can
specify, elaborate, test, and validate software components. You can:

• Model your system in Simulink.


• Simulate the system behavior in a target environment.
• Use Simulink Coder or Embedded Coder to generate code from your algorithm model for rapid
prototyping or production, respectively.
• Call generated entry-point functions for initiating function execution and controlling initialization,
resets, and shutdowns.
• Use code-sharing capabilities to deploy and integrate generated function-level source code,
shared libraries, and application executable programs.

See “Modeling Guidelines” for application-specific guidelines for model architecture, design, and
configuration.

Create Models of Software Components


When you design the functionality of each component in a composition, it is useful to distinguish
between the algorithms that are internal to the component and the interaction of the component with
target environment software. The algorithm of each software component can be implemented in a

26-2
Software Component Modeling

Simulink model, which is referenced as a Model block in the composition in Simulink or as a software
component in the composition in System Composer. The model can be used in multiple instances in
your design and used for simulation and code generation.

Within a model representing software component, you can further componentize your design. See
“Component-Based Modeling Guidelines” on page 23-2. In your componentization, you can use
subsystems to establish a hierarchical block diagram and to keep functionally related blocks together.
For more information about subsystems, see “Group Blocks into Subsystems” on page 4-20. You can
also use model references to define a set of blocks once and use it repeatedly. Using model references
instead of subsystems offers several advantages. For example, model references allow you to do
modular development, during which you can develop a referenced model independently from the
models that use it. Using model references also allows model protection, using multiple references of
the same model, and incremental Simulink loading and code generation. For more information, see
“Model Reference Basics” on page 8-2.

You can create your own custom library of blocks by using the instances of blocks from built-in
Simulink libraries or from the blocks or components you create. You can create custom blocks by
using legacy code or other custom code. See “Author Block Algorithms”. Using custom libraries is
helpful for providing frequently used and seldom changed modeling utilities and for reusing
components in a model or in multiple models. To learn more, see “Create Custom Library” on page
45-2.

26-3
26 Software Modeling

To schedule and control the execution of your software component models, you can design each
model as an export-function model or a rate-based model. For an export-function model, the code
generator produces code for independent callable functions you can integrate with target
environment software and a scheduler. See “Export-Function Models Overview” on page 10-125. With
a rate-based model, Simulink schedules function execution based on sample times. The code
generator produces a callable function for each rate represented in the model. Export-function
models provide flexible entry points and customization support, which makes them useful for
generating production code. For more information, see “Create Export-Function Model” on page 10-
98 and “Create Rate-Based Model” on page 10-60.

When you design the interfaces of your components, use In Bus Element or Inport blocks to represent
component inputs. A signal or a message arriving at an input port on a component flows out of the
associated inport in that component. Similarly, use Out Bus Element or Outport blocks to represent
component outputs.

26-4
Software Component Modeling

To reduce visual complexity in a model, you can combine signals into buses that are composite
signals. Buses contain elements that retain their separate identities, which allows you to extract them
from the composite signal. When you group signals into a bus you can decide whether they affect
simulation and code generation.

• A virtual composite signal simplifies the visual appearance of a model by combining two or more
signal lines into one line. It does not group the signals in any functional sense and, therefore, does
not affect simulation or code generation. By accessing elements directly, virtual composite signals
execute faster than nonvirtual composite signals in simulations and generated code.
• A nonvirtual composite signal visually and functionally groups signals, affecting both simulation
and code generation.

For more information, see “Explore Composite Interfaces” on page 82-5.

For models that include buses composed of many bus elements, consider using In Bus Element and
Out Bus Element blocks. These blocks reduce signal line complexity and combine the functionality of
Inport and Outport blocks with the ability to choose which elements of a bus to input and output. You
can customize data interfaces to your components by defining and using custom bus types. See
“Create Nonvirtual Buses” on page 82-35.

You can configure your components to call platform services, such data sender and receiver and timer
services, custom services, such as device drivers, and other component code, or other target
environment software, as in a distributed service architecture. Use function call subsystems and
function caller blocks together with function ports for this purpose. See “Model Client-Server
Communication Using Function Ports” on page 10-195.

You can configure your components to run as concurrent systems on multicore processor and
multiprocessor systems when they are deployed. This configuration can improve performance or
enhance scalability of an embedded system. See “Concepts in Multicore Programming” on page 14-2
and “Multicore Programming with Simulink” on page 14-8.

To represent an area of RAM used by a component model, you can use a data store. A data store is a
repository from which you can read and to which you can write data without connecting input or
output signals to the store, analogous to a global variable in a program. Use Data Store Read and
Data Store Write blocks to access data stores. See “Model Global Data by Creating Data Stores” on
page 79-10 and “Determine Where to Store Variables and Objects for Simulink Models” on page 73-
109.

26-5
26 Software Modeling

Create Model of Target Environment


Once you create models of your software components, you can test your design by creating a model
to emulate or mock the target environment in which the components will be deployed.

Use messages to model communication between Simulink components for the purpose of system
integration.

You can use message-based communication instead of signals for component communication when
modeling systems in which centralized architectures are replaced with distributed architectures. A
message is a useful modeling artifact that combines events with related data. You can send and
receive messages from the root input and output ports of a model and generate C/C++ code to
connect to a middleware or an operating system communication programming interface.

For more information, see “Simulink Messages Overview” on page 11-2.

Use Simulink functions to represent callable services such as input and output, memory, diagnostics,
and hardware peripherals. See “Simulink Functions Overview” on page 10-142.

To schedule the execution of your software components, you can use the Schedule Editor, a Stateflow
chart, or other scheduling blocks such as Function-Call Generator. See “Test Export-Function Model
Simulation Using Function-Call Generators” on page 10-105, “Test Export-Function Model Simulation
Using Stateflow Chart” on page 10-109, and “Test Export-Function Model Simulation Using Schedule
Editor” on page 10-114. For rate-based models, you can use the Simulink built-in scheduler, which

26-6
Software Component Modeling

schedules tasks based on sample time. For export-function models, you need to schedule execution
with explicit calls. See “Create Partitions” on page 25-4.

If you have both export-function and rate-based components, you can use periodic function-call event
ports for the rate-based components. You can also schedule them with the Schedule Editor.

You can use event functions to implement startup, shutdown, and mode transition behavior of your
system. See “Using Initialize, Reinitialize, Reset, and Terminate Functions” on page 10-208.

Test System by Simulating Composition Model


Once you have built a model of target environment around your software components, you can
simulate the model to test and refine your design.

You can observe how the system behaves during simulation and view and analyze resulting data by
using the Simulation Data Inspector. See “Investigate Signal Values” on page 81-9. You can also
use the Sequence Viewer to visualize the flow of messages and function calls.

You can experiment with different parameter values or variant configurations as you test your system.
See “Tune and Experiment with Block Parameter Values” on page 41-31 and “What Are Variants and
When to Use Them” on page 12-3.

If you have a Simulink Test license, you can automatically create a test harness model to test your
system.

Integrate Components into Software Architectures


Once you create models in Simulink to represent your software components, you can integrate the
components into a software architecture model in System Composer. Add software components to
your software architecture model, then link the Simulink models to those components. You can use
export-function and rate-based models. Define and create interfaces between components to build the
composition. You can then use System Composer to view, analyze, and simulate the composition to
help you further refine your design. See “Author Software Architectures” (System Composer).

Design Software Architectures


Before you design the software components themselves, designing the overall architecture of the
system in which the components operate can be useful. You can model the high-level behavior of your

26-7
26 Software Modeling

system by creating a software architecture model in System Composer. See “Design Software
Architectures” (System Composer).

Using System Composer, you can define component interfaces, author functions for your components,
analyze your design, and simulate the composition before fully implementing the functionality of your
components. See “Author and Extend Functions for Software Architectures” (System Composer).

Generate Code for Software Components


When you are ready to generate code for the software component, use Embedded Coder to prepare
the model for code generation and generate C code. The code that you generate from a model
includes entry-point functions, which are called from application code. These functions include an
initialization function, execution functions, and, optionally, terminate and reset functions. The
functions exchange data with your application code through a data interface that you control. To
customize the data interface of the generated code, use the Embedded Coder Dictionary and Code
Mappings editor. To test generated code, you can run software-in-the-loop (SIL) and processor-in-the-
loop (PIL) simulations. A SIL simulation compiles and runs the generated code on your development
computer. A PIL simulation cross-compiles source code on your development computer. The PIL
simulation then downloads and runs the object code on a target processor or an equivalent
instruction set simulator.

To get started, see “Embedded Coder Fundamentals” (Embedded Coder).

26-8
Simulating Dynamic Systems

9
27

Running Simulations

• “Simulate a Model Interactively” on page 27-2


• “Use Local Solvers in Referenced Models” on page 27-5
• “Choose a Solver” on page 27-8
• “Choose a Jacobian Method for an Implicit Solver” on page 27-13
• “Variable Step Solvers in Simulink” on page 27-18
• “Fixed Step Solvers in Simulink” on page 27-25
• “Choose a Fixed-Step Solver” on page 27-29
• “Use Model Operating Point for Faster Simulation Workflow” on page 27-42
• “Specify Initial State for Simulation” on page 27-50
• “Systematic Diagnosis of Errors and Warnings” on page 27-56
• “Suppress Diagnostic Messages Programmatically” on page 27-59
• “Customize Diagnostic Messages” on page 27-65
• “Report Diagnostic Messages Programmatically” on page 27-67
• “View and Trace Callbacks in Models” on page 27-70
27 Running Simulations

Simulate a Model Interactively

Simulation Basics

You can simulate a model in the Simulink Editor using the Run button on the toolstrip. The Run
button also appears in tools within the Simulink Editor. You can simulate from any tool that includes
the button, such as the Scope viewer.

Before you start a simulation, you can specify options like simulation start time, stop time, and the
solver for solving the model. (See “Solver Selection Criteria” on page 27-10) You specify these
options in the Configuration Parameters dialog box, which you can open by clicking Model Settings
on the Modeling tab. These settings are saved with the model in a configuration set. You can
create multiple configuration sets for each model and switch between them to see the effects of
different settings. See “Model Configuration Sets”.

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, scale 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.

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.

After you set your model configuration parameters, you can start the simulation. You can pause,
resume, and stop simulation using toolstrip controls. You can also simulate more than one model at a
time, so you can start another simulation while one is running.

During simulation, you cannot make changes to the structure of the model, such as adding or deleting
lines or blocks. However, you can make these changes while a simulation is running:

• Modify some configuration parameters, including the stop time and the maximum step size.
• Modify the parameters of a block, as long as you do not cause a change in:

• 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

27-2
Simulate a Model Interactively

You can also examine the model visually as it simulates. For example, you can click a line to see the
signal carried on that line on a Floating Scope or Display block. You can also display port values as a
model simulates. See “View Signal Values Using Port Value Labels” on page 40-8.

Run, Pause, and Stop a Simulation

To start simulating your model, click the Run button . You can pause, resume, or stop a simulation
using the corresponding controls on the toolstrip.

The model starts simulating at the specified start time and runs until the specified end time. While
the simulation is running, information at the bottom of the editor shows the percentage of simulation
completed and the current simulation time.

• If an error occurs, simulation stops and a message appears. If a warning condition occurs,
simulation completes. In both cases, click the diagnostics link at the bottom of the editor to see
the message, which helps you to locate errors.
• Pausing takes effect after the current time step finishes executing. Resuming a paused simulation
occurs at the next time step.
• If you stop a simulation, the current time step completes, and then simulation stops.
• If the model outputs to a file or to the workspace, stopping or pausing simulation writes the data.

Use Blocks to Stop or Pause a Simulation

Stop Simulation Using Stop Simulation Blocks

You can use the Stop Simulation block to stop a simulation when the input to the block is nonzero. If
the block input is a vector, any nonzero element stops the simulation.

1 Add a Stop Simulation block to 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 simulation time reaches 10.

27-3
27 Running Simulations

Pause Simulation Using Assertion Blocks

You can use an Assertion block to pause the simulation when the input signal to the block is zero. The
Assertion block uses the set_param command to pause the simulation. See “Run Simulations
Programmatically” on page 28-2 for more information on using the set_param command to
control the execution of a Simulink model.

1 Add an Assertion block to your model.


2 Connect the Assertion block to a signal whose value becomes zero at the desired pause time.
3 In the Assertion block dialog box, clear the Stop simulation when assertion fails check box.
Enter this command as the value of Simulation callback when assertion fails:

set_param(bdroot,'SimulationCommand','pause'),
disp(sprintf('\nSimulation paused.'))

This model uses an Assertion block with these settings to pause the simulation when the simulation
time reaches 5.

When the simulation pauses, a message appears that shows the time the block paused the simulation.

You can resume the simulation using Continue as you can for any paused simulation.

See Also
Blocks
Assertion | Stop Simulation

Functions
sim

More About
• “Systematic Diagnosis of Errors and Warnings” on page 27-56
• “Run Individual Simulations”
• “Solver Selection Criteria” on page 27-10

27-4
Use Local Solvers in Referenced Models

Use Local Solvers in Referenced Models


When you use referenced models to represent system components, you can configure each
referenced model to use a local solver. When you use a local solver in a referenced model, the
software solves the model reference as a separate set of differential equations using the local solver.
The referenced model can use a solver that is the same or different from the solver used in the top
model. Whether the local solver is the same or different, the local solver can use a different, smaller
or larger step size.

Using a local solver can facilitate system composition and integration. When you use local solvers,
you can solve referenced models in system-level simulations using the same solver and step size used
to design and test each model in isolation. Using local solvers can also reduce the number of
configuration adjustments you need to make to configuration parameters in referenced models while
integrating the model into a larger system.

For some systems, using a local solver can improve simulation performance by allowing you to:

• Choose a solver that is more appropriate to solve the system in the referenced model
• Use different step sizes for different components to reduce the number of redundant calculations
in systems that have a wide range of dynamics among components.

The choice of solver and solver settings involves a trade off between speed and accuracy in
simulation. When you use local solvers, you can make different choices based on the requirements for
each component.

For an example about using a local solver, see “Improve Simulation Performance by Using Local
Solvers”.

How Local Solvers Work


In a typical simulation that uses only one solver, the simulation loop executes in three phases for each
major time step: output, update, and advance. In each phase, each block in the model executes the
block method that corresponds to the phase according to the execution order.

• Output — Calculates block output values


• Update — Typically calculates discrete state values
• Advance — Calculates continuous state values and determines the next major time step based on
the solver selection, the solver parameter values, and the system dynamics

When you use a local solver, the local solver computes state values for the referenced model during
the update method for the referenced model. As part of the update method, the local solver performs
a local advance for the model reference to calculate the next local time step. Because the local solver
advance occurs before the system-level advance phase, the local solver execution gets ahead of the
execution for the top model. When the local advance phase uses values that come from the parent
model, the local solver extrapolates those values to the local time.

The top solver advance phase and the output phase for the next time step both occur between each
local advance. In the top solver advance and output phases, the top solver might use values that are
calculated by the local solver. Because the local solver is ahead of the top solver, the local solver
provides interpolated values to the top solver.

Because using a local solver involves interpolation and extrapolation, simulation results might not
match between equivalent simulations of the same model with and without the use of the local solver.

27-5
27 Running Simulations

How to Configure Local Solvers


Configure the settings for a local solver using a combination of the configuration parameters for the
referenced model and the block parameters for each Model block that references the model. The
configuration parameter values in the referenced model have the same value for every instance of
that model. You can configure the Model block parameter values differently for each model reference
instance.

Configure these options using the configuration parameters of the referenced model:

• Use local solver when referencing model — Select this parameter to use a local solver for the
model when referenced in a model hierarchy.

When you select this parameter, the Solver and Fixed-step size parameter values for the
referenced model apply to the local solver.
• Type — Select Fixed-step.

When you use a local solver, the top solver can be a variable-step or fixed-step solver, and the local
solver must be a fixed-step solver.
• Solver — Select auto to have the software choose a solver, or select a solver other than the
discrete solver, which is not supported as a local solver.
• Fixed-step size (fundamental sample time) — Specify the step size for the local solver or
specify auto to have the software determine the step size for the local solver.

The local solver step size must be an integer multiple of the step size for the parent solver.

Configure these options using the Model block parameters:

• Communication step size — The discrete rate at which the Model block executes in the parent
model
• Input signal handling — How the local solver extrapolates inputs from the parent model during
the local advance stage
• Output signal handling — How the parent solver interpolates required values from the model
reference during the parent advance phase

Additional Considerations for Local Solvers


You must determine whether a local solver provides benefit based on the dynamics and
characteristics of your system. When evaluating where a local solver might provide benefit, look for
model components that:

• Operate with time constants one or more orders of magnitude larger than other parts of the
system
• Have continuous states that are decoupled from the rest of the system

Local solvers for referenced models operate on continuous states in the referenced model. Because
using a local solver for a referenced model with only discrete states has no effect on simulation
results, local solvers are not supported for models that do not contain continuous states. When a
model contains no continuous states, the software always uses the discrete solver. The fixed-step
discrete solver is not supported as a local solver.

27-6
Use Local Solvers in Referenced Models

Model hierarchies that contain one or more referenced models configured to use a local solver do not
support:

• Multitasking execution
• Saving or restoring a model operating point
• Fast restart
• Linearization
• Code generation

Referenced models configured to use a local solver do not support:

• Fixed-step zero-crossing detection


• Software-in-the-loop (SIL) or processor-in-the-loop (PIL) simulation

Model arguments are supported for referenced models configured to use a local solver only for
normal mode simulation.

Local solvers are not supported for referenced models that directly or indirectly reference another
model that has both continuous and discrete sample times, except when the model with continuous
and discrete sample times:

• Also uses a local solver


• Directly or indirectly references another model that uses a local solver

Local solvers are not supported for models referenced by Model blocks:

• Inside for-each subsystems


• With initialize, reset, or terminate ports
• That have variable-size signals at the model interface

When the top solver or a parent solver is implicit, the Solver Jacobian Method configuration
parameter value for the top or parent model must be the default value auto or Full
perturbation.

See Also
Blocks
Model

Model Settings
Use local solver when referencing model

Related Examples
• “Improve Simulation Performance by Using Local Solvers”

27-7
27 Running Simulations

Choose a Solver
In this section...
“Automatic Solver Selection” on page 27-8
“Solver Selection Criteria” on page 27-10

To simulate a dynamic system, you compute its states at successive time steps over a specified time
span. This computation uses information provided by a model of the system. Time steps are time
intervals when the computation happens. The size of this time interval is called step size. The process
of computing the states of a model in this manner is known as solving the model. No single method of
solving a model applies to all systems. Simulink provides a set of programs called solvers. Each solver
embodies a particular approach to solving a model.

A solver applies a numerical method to solve the set of ordinary differential equations that represent
the model. Through this computation, it determines the time of the next simulation step. In the
process of solving this initial value problem, the solver also satisfies the accuracy requirements that
you specify.

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 “Compare Solvers” on page 3-6). Select solvers in
the Solver pane of model configuration parameters.

All solvers provided by MATLAB and Simulink follow a similar naming convention: ode, followed by
two or three numerals indicating the orders of the solver. Some solvers can solve stiff differential
equations and the methods used by them are expressed by the s, t, or tb suffixes.

Automatic Solver Selection


When you specify the Solver and Max step size parameters as auto, the software uses an algorithm
to select a solver and maximum step size value. For most models, the software can select an
appropriate solver and step size.

The algorithm uses several heuristics to select the solver based on model characteristics. The chart
illustrates some heuristics for the selection algorithm.

27-8
Choose a Solver

When the model contains only discrete states, the software selects the discrete solver for the
specified solver type.

• For a fixed-step solver, the software selects the discrete fixed-step solver.
• For a variable-step solver, the software selects the discrete variable-step solver.

When the model contains continuous states, the solver selection depends on the solver type and the
mathematical representation of the model.

• For a fixed-step solver for a system that can be represented using ODEs, the software selects the
ode3 solver.
• For a fixed-step solver for a model of a system that can be represented as a system of differential
algebraic equations (DAEs), the software selects the ode14x solver.
• For a variable-step solver for a system that can be represented using ODEs, the software selects
the solver based on the stiffness of the model.

• For stiff models, the software selects the ode15s solver.


• For models that are not stiff, the software selects the ode45 solver.
• For a variable-step solver for a system that can be represented using DAEs, the software selects
the ode23t solver.

The software calculates the stiffness of the model when the number of continuous states is less than
the value of the NumStatesForStiffnessChecking parameter. By default, the
NumStatesForStiffnessChecking parameter value is 1000.

When the number of continuous states in the model exceeds the value of the
NumStatesForStiffnessChecking parameter, the software considers the model as stiff without
calculating the stiffness and selects the ode15s solver.

27-9
27 Running Simulations

When the number of continuous states in the model is less than the value of the
NumStatesForStiffnessChecking parameter, the software calculates the system stiffness to
select a solver based on the value of the StiffnessThreshold parameter.

• When the calculated stiffness is less than the value of the StiffnessThreshold parameter, the
software considers the model not stiff and selects the ode45 solver.
• When the calculated stiffness is greater than the value of the StiffnessThreshold parameter,
the software considers the model stiff and selects the ode15s solver.

The default value for the NumStatesForStiffnessChecking and StiffnessThreshold


parameters is 1000. You can specify a different value for either parameter using the set_param
function.

For Simscape Electrical™ models, the software selects the solver ode23tb. Systems modeled using
Simscape Electrical can include nonlinear circuit components, such as circuit breakers and power
electronics, that require a stiff solver.

Solver Selection Criteria


The appropriate solver for simulating a model depends on these characteristics:

• System dynamics
• Solution stability
• Computation speed
• Solver robustness

As such, the numerical solvers provided by Simulink can be broadly classified by two properties.

Computation Step Size Type

• Fixed-step solvers, as the name suggests, solve the model using the same step size from the
beginning to the end of the simulation. You can specify the step size or let the solver choose it.
Generally, decreasing the step size increases the accuracy of the results and the time required to
simulate the system.
• Variable-step solvers vary the step size during the simulation. These solvers reduce the step size
to increase accuracy at certain events during the simulation of the model, such as rapid state
changes, zero-crossing events, etc. Also, they increase the step size to avoid taking unnecessary
steps when the states of a model change slowly. Computing the step size adds to the
computational overhead at each step. However, it can reduce the total number of steps, and hence
the simulation time required to maintain a specified level of accuracy for models with zero-
crossings, rapidly changing states, and other events requiring extra computation.

Model States

• Continuous solvers use numerical integration to compute continuous states of a model at the
current time step based on the states at previous time steps and the state derivatives. Continuous
solvers rely on individual blocks to compute the values of the discrete states of the model at each
time step.
• Discrete solvers are primarily used for solving purely discrete models. They compute only the next
simulation time step for a model. When they perform this computation, they rely on each block in
the model to update its individual discrete state. They do not compute continuous states.

27-10
Choose a Solver

Use an iterative approach to choose a solver for your requirements. Compare simulation results from
several solvers and select a solver that offers the best performance with minimal tradeoffs.

Select a solver for your model in these ways:

• Use auto solver. New models have their solver selection set to auto solver by default. Auto solver
recommends a fixed-step or variable-step solver for your model as well as the maximum step size.
• If you are not satisfied with the simulation results using auto solver, select a solver in the Solver
pane in the model configuration parameters.

When you build and simulate a model, you can choose the solver based on the dynamics of your
model. A variable-step solver is better suited for purely continuous models, like the dynamics of a
mass spring damper system. A fixed-step solver is recommended for a model that contains several
switches, like an inverter power system, due to the number of solver resets that would cause a
variable-step solver to behave like a fixed-step solver.

Note When you deploy a model as generated code, you can use only a fixed-step solver. If you select
a variable-step solver during simulation, use it to calculate the step size required for the fixed-step
solver that you need at deployment.

This chart provides a broad classification of solvers in the Simulink library.

27-11
27 Running Simulations

To tailor the selected solver to your model, see “Check and Improve Simulation Accuracy” on page
34-12.

Ideally, the solver you select should:

• Solve the model successfully.


• For variable-step solvers, provide a solution within the tolerance limits you specify.
• Solve the model in a reasonable duration.

A single solver might not meet all of these goals. Try simulating using different solvers before making
a selection.

The Simulink library provides several solvers, all of which can work with the algebraic loop solver.
For more information, see “How the Algebraic Loop Solver Works” on page 3-42.

Solver Type Explicit/ Discrete Continuous Variable-Order


Implicit
Fixed-Step Explicit Not Applicable “Fixed-Step Continuous Not Applicable
Explicit Solvers” on page
27-26
Implicit Not Applicable “Fixed-Step Continuous Not Applicable
Implicit Solvers” on page
27-27
Variable-Step Explicit “Variable Step Solvers in “Variable-Step Continuous “Single-Order Versus
Simulink” on page 27-18 Explicit Solvers” on page Variable-Order Continuous
27-20 Solvers” on page 3-8
Implicit “Variable-Step Continuous “Single-Order Versus
Implicit Solvers” on page Variable-Order Continuous
27-21 Solvers” on page 3-8

In the Solver pane of model configuration parameters, the Simulink library of solvers is divided into
two major types. See “Fixed-Step Versus Variable-Step Solvers” on page 3-6.

For other ways to compare solvers, see:

• “Continuous Versus Discrete Solvers” on page 3-7


• “Explicit Versus Implicit Continuous Solvers” on page 3-7
• “One-Step Versus Multistep Continuous Solvers” on page 3-8
• “Single-Order Versus Variable-Order Continuous Solvers” on page 3-8

See Also

Related Examples
• “Compare Solvers” on page 3-6
• “Solver Pane”
• “Examine Model Dynamics Using Solver Profiler” on page 36-2
• “Algebraic Loop Concepts” on page 3-39

27-12
Choose a Jacobian Method for an Implicit Solver

Choose a Jacobian Method for an Implicit Solver


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:

ẋ = f (x, t, u)
y = g(x, t, u) .

The Jacobian, J, formed from this system of equations is:

∂f ∂f
∂x ∂u A B
J= = .
∂g ∂g C D
∂x ∂u

In turn, the solver Jacobian is the submatrix, Jx.

∂f
Jx = A = .
∂x

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:

ẋ 1 = f 1(x1, x3)
ẋ 2 = f 2(x2)
ẋ 3 = f 3(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 eachxi that appears explicitly on the right-hand side of an
equation. Therefore, you obtain:

1 0 1
Jx, pattern = 0 1 0
0 1 0

The sparse perturbation and the sparse analytical methods may be able to take advantage of this
sparsity pattern to reduce the number of computations necessary and 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.

27-13
27 Running Simulations

Note If you set Automatic solver parameter selection to error in the Solver Diagnostics pane,
and you choose a different solver than that suggested by Simulink, you may receive an error.

Limitations

The solver Jacobian methods have these 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.
• 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 determine which of the remaining four methods best suits your model. This flowchart
depicts the algorithm.

27-14
Choose a Jacobian Method for an Implicit Solver

Sparse methods are beneficial for models that have a large number of states. If 50 or more states
exist in your model, auto chooses a sparse method. Unlike other implicit solvers, ode23s is a sparse
method because it generates a new Jacobian at every time step. A sparse analytical or a sparse
perturbation method is, therefore, advantageous. Selecting auto 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 solves the full set of perturbation equations and uses LAPACK for linear
algebraic operations. This method is costly from a computational standpoint, but remains a
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,

ẋ 1 = f 1(x1, x3)
ẋ 2 = f 2(x2)
ẋ 3 = f 3(x2) .

The solver Jacobian is:

27-15
27 Running Simulations

∂f1 ∂f1 ∂f1


∂x1 ∂x2 ∂x3
∂f2 ∂f2 ∂f2
Jx =
∂x1 ∂x2 ∂x3
∂f3 ∂f3 ∂f3
∂x1 ∂x2 ∂x3
f 1(x1 + Δx1, x2, x3) − f 1 f 1(x1, x2 + Δx2, x3) − f 1 f 1(x1, x2, x3 + Δx3) − f 1
Δx1 Δx2 Δx3
f 2(x1 + Δx1, x2, x3) − f 2 f 2(x1, x2 + Δx2, x3) − f 2 f 2(x1, x2, x3 + Δx3) − f 2
=
Δx1 Δx2 Δx3
f 3(x1 + Δx1, x2, x3) − f 3 f 3(x1, x2 + Δx2, x3) − f 3 f 3(x1, x2, x3 + Δx3) − f 3
Δx1 Δx2 Δ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:

f 1(x1 + Δx1, x2 + Δx2, x3) − f 1 f 1(x1, x2, x3 + Δx3) − f 1


0
Δx1 Δx3
f 2(x1 + Δx1, x2 + Δx2, x3) − f 2
Jx = 0 0
Δx2
f 3(x1 + Δx1, x2 + Δx2, x3) − f 3
0 0
Δx2

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

For details on how to access and interpret the sparsity pattern in MATLAB, see “Exploring the Solver
Jacobian Structure of a Model”.

27-16
Choose a Jacobian Method for an Implicit Solver

Code Generation Support


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. This limitation applies to rapid accelerator mode as well.

27-17
27 Running Simulations

Variable Step Solvers in Simulink


Variable-step solvers vary the step size during the simulation, reducing the step size to increase
accuracy when model states are changing rapidly and increasing the step size to avoid taking
unnecessary steps when model 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.

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 collection 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 define. If your model defines no states or
defines only discrete states, select the discrete 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.

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

Variable-Step Discrete Solver


Use the variable-step discrete solver when your model does not contain continuous states. For such
models, the variable-step discrete solver reduces its step size in order to capture model events such
as zero-crossings, and increases the step size when it is possible to improve simulation performance.

The model shown in the figure contains two discrete sine wave signals at 0.5 and 0.75 sample times.
The graphs below show the signals in the model along with the solver steps for the variable-step
discrete and the fixed-step discrete solvers respectively. You can see that the variable-step solver only

27-18
Variable Step Solvers in Simulink

takes the steps needed to record the output signal from each block. On the other hand, the fixed-step
solver will need to simulate with a fixed-step size—or fundamental sample time—of 0.25 to record all
the signals, thus taking more steps overall.

Variable-Step Continuous Solvers


Variable-step solvers 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. However, it
can reduce the total number of steps, and the simulation time required to maintain a specified level of
accuracy.

27-19
27 Running Simulations

You can further categorize the variable-step continuous solvers as one-step or multistep, single-order
or variable-order, and explicit or implicit. See “One-Step Versus Multistep Continuous Solvers” on
page 3-8 for more information.

Variable-Step Continuous Explicit Solvers


The variable-step explicit solvers are designed for nonstiff problems. Simulink provides four such
solvers:

• ode45
• ode23
• ode113
• odeN

ODE Solver One-Step Multistep Order of Method


Method Method Accuracy
ode45 X Medium Runge-Kutta, Dormand-Prince (4,5)
pair
ode23 X Low Runge-Kutta (2,3) pair of Bogacki &
Shampine

27-20
Variable Step Solvers in Simulink

ODE Solver One-Step Multistep Order of Method


Method Method Accuracy
ode113 X Variable, Low PECE Implementation of Adams-
to High Bashforth-Moulton
odeN X See Order of See Integration Technique in
Accuracy in “Fixed-Step Continuous Explicit
“Fixed-Step Solvers” on page 27-26
Continuous
Explicit
Solvers” on
page 27-26

ODE Solver When to Use


ode45 In general, the ode45 solver is the best to apply as a first try for most problems. The
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 interpolant, which allows for event
location and smoother plots.

If the ode45 is computationally slow, the problem may be stiff and thus require an
implicit solver.
ode113 For problems with stringent error tolerances or for computationally intensive problems,
the Adams-Bashforth-Moulton PECE solver can be more efficient than ode45.
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 by applying a
cubic Hermite interpolation to the values and slopes computed at the ends of a step.
odeN The odeN solver uses a nonadaptive Runge-Kutta integration whose order is
determined by the Solver order parameter. odeN uses a fixed step size determined by
the Max step size parameter, but the step size can be reduced to capture certain
solver events, such as zero-crossings and discrete sample hits.

Note Select the odeN solver when simulation speed is important, for example, when

• The model contains lots of zero-crossings and/or solver resets


• The Solver Profiler does not detect any failed steps when profiling the model

Variable-Step Continuous Implicit Solvers


If your problem is stiff, try using one of the variable-step implicit solvers:

• ode15s
• ode23s
• ode23t
• ode23tb

27-21
27 Running Simulations

ODE Solver One-Step Multistep Order of Solver Max. Order Method


Method Method Accuracy Reset
Method
ode15s X Variable, X X Numerical Differentiation
low to Formulas (NDFs)
medium
ode23s X Low Second-order, modified
Rosenbrock formula
ode23t X Low X Trapezoidal rule using
interpolant
ode23tb X Low X TR-BDF2

Solver Reset Method

For ode15s, ode23t, and ode23tb a drop-down menu for the Solver reset method appears in the
Solver details section of the 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.
Fast specifies that the solver does not recompute the Jacobian for a solver reset, whereas Robust
specifies that the solver does. Consequently, the Fast setting is computationally faster but it may use
a small step size in certain cases. To test for such cases, run the simulation with each setting and
compare the results. If there is no difference in the results, 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 orders 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 for the application of variable-step implicit solvers. For an example
comparing the behavior of these solvers, see “Explore Variable-Step Solvers with Stiff Model”.

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

27-22
Variable Step Solvers in Simulink

ODE Solver Tips on When to Use


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.

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.

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

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

27-23
27 Running Simulations

real scalar. If you specify auto (the default), Simulink initially sets the absolute tolerance for each
state based on the relative tolerance. If the relative tolerance is larger 1e-3, abstol is initialized at
1e-6. However, for reltol smaller than 1e-3, abstol for the state is initialized at reltol * 1e-3.
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, abstol initializes at 1e-6 and by the end of the simulation reaches 1e-3
also. If a state goes from 0 to 1000, then abstol changes to 1.

Now, if the state changes from 0 to 1 and reltol is set at 1e-4, then abstol initializes at 1e-7 and
by the end of the simulation reaches a value of 1e-4.

If the computed initial value for the absolute tolerance is not suitable, you can determine an
appropriate value yourself. You might have to run a simulation more than once to determine an
appropriate value for the absolute tolerance. You can also specify if the absolute tolerance should
adapt similarly to its auto setting by enabling or disabling the AutoScaleAbsTol parameter. For
more information, see Auto scale 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
• 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. You can set the block absolute tolerance to:

• auto
• –1 (same as auto)
• positive scalar
• real vector (having a dimension equal to the number of corresponding continuous states in the
block)

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 set the absolute tolerance too high, 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.

27-24
Fixed Step Solvers in Simulink

Fixed Step Solvers in Simulink

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, a smaller the step size increases the accuracy of the results but
also increases the time required to simulate the system.

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. By default, Simulink chooses the step size 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.

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.

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

Simulink provides two types of fixed-step continuous solvers — explicit and implicit.

27-25
27 Running Simulations

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. For a comparison of explicit and implicit solvers, see “Explicit Versus Implicit Continuous
Solvers” on page 3-7.

Fixed-Step Continuous Explicit 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. A fixed-step explicit solver is expressed
mathematically as:

x(n + 1) = x(n) + h ∗ Dx(n)

where

• x is the state.
• Dx is a solver-dependent function that estimates the state derivative.
• h is the step size.

27-26
Fixed Step Solvers in Simulink

• n indicates the current time step.

Simulink provides a set of fixed-step continuous explicit solvers. The solvers differ in the specific
numerical integration technique that they use to compute the state derivatives of the model. This
table lists each solver and the integration technique it uses. The table lists the solvers in the order of
the computational complexity of the integration methods they use, from the least complex (ode1) to
the most complex (ode8).

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

None of these solvers have an error control mechanism. Therefore, the accuracy and the duration of a
simulation depend 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
higher the order of the solver, the more accurate the simulation results.

If you specify a fixed-step solver type for a model, then by default, Simulink selects the
FixedStepAuto solver. Auto solver then selects an appropriate fixed-step solver that 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 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 may need to choose another solver, a different fixed step
size, or both to achieve acceptable accuracy and an acceptable simulation time.

Fixed-Step Continuous Implicit Solvers

An implicit 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, as described by the following
expression.

x(n + 1) − x(n) − h ∗ Dx(n + 1) = 0

Simulink provides two fixed-step implicit solvers: ode14x and ode1be. 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.

See Also
“Choose a Fixed-Step Solver” on page 27-29

27-27
27 Running Simulations

More About
• “Variable Step Solvers in Simulink” on page 27-18
• “Compare Solvers” on page 3-6

27-28
Choose a Fixed-Step Solver

Choose a Fixed-Step Solver


This example shows an algorithmic method of selecting an appropriate fixed-step solver for your
model. For simulation workflows in Simulink, the default setting for the Solver parameter in the
Model Configuration Parameters is auto. The heuristics used by Simulink to select a variable-step
solver is shown in the figure below.

When to Use a Fixed-Step Solver


One common case to use a fixed-step solver is for workflows where you plan to generate code from
your model and run the code on a real-time system.

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
tolerances that you specify and as such, the variable step sizes cannot be mapped to the real-time
clock of a target system.

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 is not possible or practical to
decide without trial, the combination of solver and step size that will yield acceptable results for the
continuous states in the shortest time. Determining the best solver for a particular model generally
requires experimentation.

The example model represents the flight control algorithm for the longitudinal flight of an aircraft.

27-29
27 Running Simulations

Establish Baseline Results Using a Variable-Step Solver


Before you begin simulation, determine acceptable error tolerances for your variable-step solver. The
model is currently set up with the default values of absolute and relative tolerances of 1e-6 and 1e-4
respectively.

If these values are acceptable, continue with the example. Otherwise, you can change them to your
specification using the Model Configuration Parameters.

Select a variable-step solver from the list of solvers in the Solver dropdown in the Solver pane of the
Model Configuration Parameters to simulate the model. The default setting in Simulink for the Solver
parameter is VariableStepAuto. Simulink selects a solver and the maximum step size of the
simulation based on the contents and dynamics of the model.

Simulate the model using the auto solver, or pick another solver. Additionally, enable the Save
states, Save time, and Save outputs parameters in the Data Import/Export pane of the Model
Configuration Parameters. Set the logging format for your model to Dataset to allow the Simulation
Data Inspector to log the signals.

The simulation results from this run will be designated the baseline results for this task. The model
contains 13 signals, but this example focuses on only a few signals plotted below.

27-30
Choose a Fixed-Step Solver

Profile the model using the Solver Profiler to find an appropriate step size for the candidate fixed-
step simulations of the model. See Solver Profiler for information on how to launch and use the tool.
For command-line usage, see solverprofiler.profileModel.

Note the maximum and average step sizes returned by the Solver Profiler.

solver: 'ode45'
tStart: 0
tStop: 60
absTol: 1.0000e-06
relTol: 1.0000e-04
hMax: 0.1000
hAverage: 0.0447
steps: 1342
profileTime: 0.0665
zcNumber: 0
resetNumber: 600
jacobianNumber: 0
exceptionNumber: 193

27-31
27 Running Simulations

Run Fixed-Step Simulations of the Model


Once you obtain the results of the variable-step simulation of the model, simulate it using one or more
of the fixed-step solvers. In this example, the model is simulated using all the non-stiff fixed-step
solvers: ode1, ode2, ode3, ode4, ode5, and ode8. You can also select a specific solver from the
Solver dropdown in the Model Configuration Parameters to run against the variable-step baseline.

Considerations for Selecting a Fixed Step Size

The optimal step size for a fixed-step simulation of your model strikes a balance between speed and
accuracy, given constraints such as code-generation objectives, physics or dynamics of the model, and
modeling patterns used. For example, code generation would dictate the step size must be greater
than or equal to the clock speed of the processor (the reciprocal of the CPU frequency). For pure
simulation objectives, the step size must be less than the discrete sample times specified by
individual blocks in the model. For models with periodic signals, the step size must be such that the
signal is sampled at twice its highest frequency; this is known as the Nyquist frequency.

For this specific example, set the fixed-step size of the solver to 0.1 (the maximum step size detected
by the Solver Profiler). This takes into account the discrete sample time 0.1 of the Dryden Wind-
Gust block, as well as the periodic nature of the stick movements and the aircraft response.

Make sure that the model states, outputs, and simulation time are enabled for logging and that the
logging format is set to Dataset in the Model Configuration Parameters.

Simulate the model by selecting any one or all the non-stiff fixed-step solvers from the Solver
dropdown of the Model Configuration Parameters when the solver Type is set to Fixed-step.

A Simulink.sdi.Run object is created for the fixed-step solver simulation(s) and stored in the
fsRuns struct in the base workspace.

27-32
Choose a Fixed-Step Solver

Compare Fixed-Step Simulations with the Variable-Step Baseline


Use the Simulation Data Inspector to visualize and inspect logged signals in your model. You can
also compare signals across simulations, or runs, using the Compare feature. For more information
on using the Simulation Data Inspector, see Simulation Data Inspector. For more information on
how to compare simulations using the Simulation Data Inspector, see “Compare Simulation Data” on
page 31-203.

To compare signals, switch to the Compare tab in the Simulation Data Inspector. Set the
Baseline run to the variable-step simulation and select a fixed-step simulation from the Compare to
dropdown. Set the Global Abs Tolerance, Global Rel Tolerance, and Global Time Tolerance
based on your requirements.

For this example, Global Abs Tolerance is set to 0.065, Global Rel Tolerance is set to 0.005, and
Global Time Tolerance is set to 0.1.

The comparison plots display the results for the lowest order fixed-step solver simulation where all
signals fell within tolerance, when compared to the baseline variable-step simulation. For the selected
solver, comparison results of a few of the signals are plotted below.

27-33
27 Running Simulations

27-34
Choose a Fixed-Step Solver

27-35
27 Running Simulations

27-36
Choose a Fixed-Step Solver

The lowest order with all signals within tolerance is determined to be ode4. Consider the results for
the ode1 fixed-step solver, where the comparison results showed 11 signals out of tolerance. Observe
that there are 11 signals out of tolerance when the signal comparison parameters are set as:

• Signal Abs Tolerance: 0.065


• Signal Rel Tolerance: 0.065
• Signal Time Tolerance: 0.1

27-37
27 Running Simulations

27-38
Choose a Fixed-Step Solver

27-39
27 Running Simulations

27-40
Choose a Fixed-Step Solver

27-41
27 Running Simulations

Use Model Operating Point for Faster Simulation Workflow


In this section...
“Save Model Operating Points” on page 27-43
“Restore Model Operating Points” on page 27-44
“Additional Considerations for Saving and Restoring Model Operating Points” on page 27-45

To effectively design a system, you simulate a model iteratively so you can analyze the system based
on different inputs, boundary conditions, or operating conditions. In many applications, the systems
you need to model and simulate exhibit a startup phase that involves significant dynamic behavior.
For example, the takeoff stage of flight occurs before each aircraft maneuver in a set of simulations
for a model of an airplane. When you run a set of simulations for such a system, you can reduce the
amount of time required for the set of simulations by using model operating points.

1 Simulate the startup phase once.


2 Save the final operating point at the end of the startup phase.
3 Use the model operating point at the end of the startup phase as the initial state for each
simulation.

The model operating point includes all information you need to resume a simulation, including block
states, hidden block states, and the state of the solver and the execution engine. When you resume a
simulation by using an operating point as the initial state, the simulation results match exactly the
results of an equivalent simulation that runs from the start.

When you save final states without saving the operating point, only block states that are captured by
state logging are saved. Block states alone might not be sufficient to resume the simulation. For more
information, see “Save Block States and Simulation Operating Points” on page 78-72.

The flow chart summarizes the workflow for running a set of simulations from an initial operating
point. In each simulation that starts from the initial operating point, you can modify parts of the
model, such as tunable parameters, to simulate different scenarios without having to simulate the
startup phase each time.

27-42
Use Model Operating Point for Faster Simulation Workflow

Save Model Operating Points


You can configure a model to save the final operating point using the Configuration Parameters dialog
box.
1 On the Modeling tab, under Setup, click Model Settings.
2 In the Configuration Parameters dialog box, select the Data Import/Export pane.
3 In the Data Import/Export pane, select Final states and Save final operating point.
4 Click OK.

The model operating point is always saved as a Simulink.op.ModelOperatingPoint object. By


default, simulation results are returned as a single Simulink.SimulationOutput object. The
model operating point is stored in a property of the SimulationOutput object that has the name
you specify in the Final states box in the Configuration Parameters dialog box or by using the
FinalStateName parameter.

When you simulate a model that is configured to save the final operating point, the model operating
point is saved and available in the workspace when:

27-43
27 Running Simulations

• The simulation completes.


• A block, such as the Stop block, stops the simulation.
• You stop the simulation by clicking Stop or by using the set_param function to issue the
simulation command to stop.
• You pause the simulation by clicking Pause or by using the set_param function to issue the
simulation command to pause.

To save the model operating point at any time during simulation, pause the simulation, then use the
get_param function to get the value of the CurrentOperatingPoint parameter for the model.

op = get_param(mdl,"CurrentOperatingPoint");

You can save multiple operating points from a simulation so that you can continue the simulation from
one of several operating points, depending on your requirements.

Restore Model Operating Points


To resume a simulation from a model operating point, specify the stop time for the resumed
simulation, enable initial state loading, and specify the Simulink.op.ModelOperatingPoint
object that represents the model operating point as the initial state.

1 On the Simulation tab, in the Simulate section, in the Stop time field, enter a value that is
larger than the value of the snapshotTime property of the ModelOperatingPoint object that
represents the model operating point.
2 On the Modeling tab, under Setup, click Model Settings.
3 In the Configuration Parameters dialog box, select the Data Import/Export pane.
4 In the Data Import/Export pane, select Initial state.
5 In the Initial state field, specify the name of the variable that contains the model operating
point. For example, enter xFinal if you used the default variable name to save the final
operating point.
6 Click OK.

When you specify the initial state for a simulation as a model operating point, you do not change the
start time for the simulation. The simulation from the initial operating point continues the simulation
in which the operating point was created, so both simulations have the same start time. The start
time also acts as a reference for all time and time-dependent variables. For example, the operating
point information for a block might include the number of sample time hits that occurred for that
block in simulation up to the point at which the operating point was saved.

For example, suppose you run a simulation of the startup phase for your model from 0 to 100 seconds
and save the model operating point at 100 seconds. To run a simulation from 100 seconds to 200
seconds:

1 Specify the stop time for the model as 200 seconds.


2 Specify the initial state for the simulation as the model operating point you saved at 100 seconds.
3 Leave the start time for the model as 0 seconds.

When you run the simulation, the software restores the simulation time of 100 seconds as part of
restoring the model operating point. Suppose the model operating point includes information that a
block in the model had 10 sample time hits by the time the model operating point was saved. The

27-44
Use Model Operating Point for Faster Simulation Workflow

software recognizes the first time step in the resumed simulation as the 11th sample time hit for the
block, relative to 0, and not the first hit, relative to 100.

If you save the final operating point in the simulation that ran from 100 seconds to 200 seconds, you
can continue the simulation again by using that operating point as the initial state for another
simulation. For example, you could run another simulation from 200 seconds to 250 seconds by
specifying the operating point saved at the end of the second simulation as the initial state for a third
simulation.

When the start time for a simulation that starts from an initial operating point does not match the
value of the startTime property of the ModelOperatingPoint object, the software issues a
warning and uses the startTime property value as the start time for the simulation.

Additional Considerations for Saving and Restoring Model Operating


Points

Changes that you make to your model between saving and restoring the model operating point can
affect the validity of the operating point for the simulation or the simulation results.

• When you make structural changes to the model, the operating point is no longer valid, and the
software always issues an error.
• When you make nonstructural changes, such as renaming the model or changing logging settings,
the software issues a warning by default only if the changes you made affected the interface
checksum.

Nonstructural changes to the model generally do not affect the ability to restore a model operating
point but might affect the simulation results. To specify the diagnostic behavior when nonstructural
changes affect the interface checksum, use the Operating point restore interface checksum
mismatch parameter.

By default, the software issues an error if you try to simulate a model from an operating point that
was saved in a different release. You can configure the software to issue a warning instead and
restore the block states stored in the loggedStates property of the ModelOperatingPoint object,
but the simulation results might not match the result of a simulation that runs from the start time,
without the initial operating point. For more information, see Operating point object from a
different release.

Not all blocks, features, modeling patterns, and simulation modes support saving and restoring model
operating points. In some cases, you can save and restore block states without the model operating
point to avoid limitations for model operating points. For more information, see “Save Block States
and Simulation Operating Points” on page 78-72.

27-45
27 Running Simulations

Feature or Modeling Pattern Considerations or Limitations


Simulation modes Saving and restoring model operating points is
supported for normal, accelerator, and rapid
accelerator simulations.

You cannot save an operating point from a


simulation that runs in one simulation mode and
restore that operating point in a simulation that
runs in a different simulation mode.

Additional limitations apply for rapid accelerator


simulations.
Rapid accelerator simulations Saving and restoring a model operating point in
rapid accelerator simulations has these
limitations:

• You cannot modify the operating point


information, such as block states.
• Variable-size signals are not supported.

These blocks do not support saving and restoring


the model operating point in rapid accelerator
simulations:

• From Spreadsheet blocks


• Model blocks with initialize, reset, or
terminate ports
• Model blocks configured as multiple-instance
export-function models
• Model blocks that reference models that
contain string data types
• Transport Delay and Variable Transport Delay
blocks inside for-each subsystems
• n-D Lookup Table blocks
• Data Store Memory blocks
• MATLAB System blocks
• Level-2 MATLAB S-Function blocks
• S-Function blocks with custom operating point
implementations
• S-Function blocks that use PWork vectors

27-46
Use Model Operating Point for Faster Simulation Workflow

Feature or Modeling Pattern Considerations or Limitations


Model references Saving and restoring an operating point is not
supported for model hierarchies that contain one
or more referenced models configured to use a
local solver. For more information, see “Use Local
Solvers in Referenced Models” on page 27-5.

You cannot modify operating point information,


such as block states, for blocks inside referenced
models configured to simulate in accelerator
mode.

These blocks do not support model operating


point when they are inside a referenced model
that is configured to simulate in accelerator
mode:

• Level-2 MATLAB S-Function blocks


• MATLAB System blocks
• n-D Lookup Table blocks
• S-Function blocks with custom operating point
implementations
• S-Function blocks that use PWork vectors
• To File blocks
MATLAB Function block Saving and restoring the model operating point is
generally supported for models that
containMATLAB Function blocks. However, the
use of certain constructs in the MATLAB code can
affect the support.

Saving and restoring the model operating point is


not supported for models that contain MATLAB
Function blocks with code that uses persistent
variables with handle object data types or with
values that contain one or more handle objects.
Custom C code The operating point information might be
incorrect for a block that calls custom C code that
contains static variables or has side effects, such
as writing to a file.

27-47
27 Running Simulations

Feature or Modeling Pattern Considerations or Limitations


S-functions When you write an S-function, you can specify
how the software saves and restores operating
point information for the S-function by setting the
operating point compliance.

• For Level-2 MATLAB S-functions, see “Level-2


MATLAB S-Function Compliance with Model
Operating Point”.
• For C MEX S-functions, see
ssSetOperatingPointCompliance.

The software saves S-Function block outputs as


part of the operating point even if the S-function
configures the operating point compliance to save
no operating point information. Saving and
restoring model operating points is not supported
for S-functions that produce outputs with custom
data types. For more information, see “Configure
Custom Data Types”.
Code generation You cannot save or restore model operating
points in code you generate for a model using
Simulink Coder or Embedded Coder.
Stack block Supports model operating point when the Push
full stack parameter value is anything other than
Dynamic reallocation.

Does not support model operating point when the


Push full stack parameter value is Dynamic
reallocation.
Queue block Supports model operating point when the Push
onto full register parameter value is anything
other than Dynamic reallocation.

Does not support model operating point when the


Push onto full register parameter value is
Dynamic reallocation.
Model name programmatic interface You cannot specify an operating point as the
states input when you use the model name as a
programmatic interface. For more information,
see “Use Model Name as Programmatic
Interface” on page 3-65.

See Also
Model Settings
Final states | Save final operating point | Initial state | Single simulation output | Operating
point restore interface checksum mismatch | Operating point object from a different release

27-48
Use Model Operating Point for Faster Simulation Workflow

Objects
Simulink.op.ModelOperatingPoint

Related Examples
• “Specify Initial State for Simulation” on page 27-50
• “Save Block States and Simulation Operating Points” on page 78-72

27-49
27 Running Simulations

Specify Initial State for Simulation

This example shows the difference between specifying the initial state for a simulation using final
states saved with and without the model operating point. Specifying initial states for a simulation can
save time when you run a set of simulations. For example, suppose you need to simulate several
scenarios for a system that has an initialization phase. If the initialization phase is the same for all
scenarios, you can simulate the initialization phase once, save the operating point, and use that
operating point as the initial state for all the simulations.

When you want to continue a simulation from a given state, use the model operating point. A model
operating point contains complete information about the state of the model and simulation, including
the simulation time for the snapshot and the state of the solver and execution engine. When you use a
model operating point as the initial state for a simulation, the simulation results match results from a
simulation without an initial state, and you do not need to specify the start time for the model. When
you specify initial states without the operating point, the simulation results can differ from an
equivalent simulation that does not run from an initial state.

For more information about the difference between final states with and without the operating point,
see “Save Block States and Simulation Operating Points” on page 78-72.

Open and Simulate Model

Open the model slexVariableTransportDelay, which models the relationship between the
vertical displacement of the front and rear wheels for a car. For more information about the model,
see “Simulating Systems with Variable Transport Delay Phenomena”.

modelName = "slexVariableTransportDelay";
open_system(modelName)

27-50
Specify Initial State for Simulation

This example uses a model with the Variable Transport Delay block to illustrate a key difference
between saving final states and saving final states with the operating point. Some blocks, including
the Variable Transport Delay block, use information to compute output values that is not included in
the logged block state. This information is included in the Simulink.op.ModelOperatingPoint
object created when you save final states with the final operating point for the model.

Create a Simulink.SimulationInput object to specify model parameters to use in the baseline


simulation. Configure the model to simulate from 0 to 10 seconds. Use the OutputTimes parameter
to ensure that the model computes output values for simulation times of 0, 5, and 10.

siminBaseline = Simulink.SimulationInput(modelName);
siminBaseline = setModelParameter(siminBaseline,'StartTime','0','StopTime','10',...
'OutputOption','AdditionalOutputTimes','OutputTimes','[0 5 10]');

Simulate the model to create baseline results.

baseline = sim(siminBaseline);

Specify Initial State for Simulation Using Model Operating Point

To see how the model operating point allows you to resume a simulation, simulate the model for 5
seconds and save the final operating point. Then, simulate the model again from 5 seconds to 10
seconds using the operating point as the initial state for the model.

Create a SimulationInput object to specify model parameters to use in the first simulation.
Configure the model to simulate from 0 seconds to 5 seconds, and save the final states with the final
operating point.

siminOP1 = Simulink.SimulationInput(modelName);
siminOP1 = setModelParameter(siminOP1,'StartTime','0','StopTime','5',...
'SaveFinalState','on','SaveOperatingPoint','on');

Simulate the model for the first five seconds.

op1 = sim(siminOP1);

Create a SimulationInput object to specify model parameters for the second part of the
simulation. When you use an operating point as the initial state for a simulation, do not specify the
start time for the simulation. The simulation runs from the time saved in the snapshotTime property
of the Simulink.op.ModelOperatingPoint object that contains the operating point data.

siminOP2 = Simulink.SimulationInput(modelName);
siminOP2 = setModelParameter(siminOP2,'StopTime','10');

Specify the initial states for the second portion of the simulation as the operating point saved from
the first part of the simulation. By default, the operating point is stored in a variable called xFinal
and returned as part of the single simulation output as a field in a Simulink.SimulationOutput
object.

siminOP2 = setInitialState(siminOP2,op1.xFinal);

Simulate the model from five seconds to ten seconds, using the final states without the operating
point as the initial state.

op2 = sim(siminOP2);

27-51
27 Running Simulations

Plot the results from the interrupted simulation that was resumed using the operating point alongside
the results from the baseline simulation.

Get the Simulink.SimulationData.Dataset object that contains the signal data logged from the
baseline simulation. The results are returned as a single Simulink.SimulationOutput object that
contains the Dataset object with signal logging data in the variable logsout.

baselineResults = baseline.logsout;

Combine the logged signal data from the two segments of the interrupted simulation. First, create a
copy of the logged signal data that will contain the combined simulation results.

opResults = op1.logsout;

In a for loop, access the timeseries objects that contain the time and signal data for each logged
signal, and use the append function to concatenate the data in time. The Dataset object with the
logged signal data contains a Simulink.SimulationData.Signal object for each signal. The
Values property of the Signal object is a timeseries object that contains the data. This example
uses curly braces ({}) to access the Signal objects in the Dataset objects by index.

for idx = 1:numElements(op1.logsout)


ts1 = op1.logsout{idx}.Values;
ts2 = op2.logsout{idx}.Values;
opResults{idx}.Values = append(ts1,ts2);
end

Plot the data on a 3-by-1 MATLAB® figure using a for loop to iterate through the elements of the
Dataset object. This example uses curly braces ({}) to access the elements of the Dataset objects
by index.

fig2 = figure(2);
fig2.Name = "Simulation Resumed Using Operating Point";
for idx=1:numElements(baselineResults)
ax = subplot(3,1,idx);
plot(baselineResults{idx}.Values)
hold on
plot(opResults{idx}.Values,'r--')
hold off
grid on
ax.Title.String = baselineResults{idx}.Values.Name;
end

27-52
Specify Initial State for Simulation

The results from the interrupted simulation that was resumed using the operating point match the
results from the uninterrupted simulation.

Specify Initial State for Simulation Using Final States

To see how using final states without the model operating point can affect simulation results, simulate
the model for 5 seconds and save the final states without the operating point. Then, simulate the
model again from 5 seconds to 10 seconds, using the final states as the initial state for the simulation.

Create a SimulationInput object to specify model parameters to use in the first simulation.
Configure the model to simulate from 0 seconds to 5 seconds and save the final states without the
operating point.

siminStates1 = Simulink.SimulationInput(modelName);
siminStates1 = setModelParameter(siminStates1,'StartTime','0','StopTime','5',...
'SaveFinalState','on');

Simulate the model for the first five seconds.

finalStates1 = sim(siminStates1);

Create a SimulationInput object to specify model parameters for the second part of the
simulation. Configure the model to simulate from 5 seconds to 10 seconds. When you use final states
without the operating point as the initial state for a simulation, the simulation time is not restored
from the final states data. You must specify the start time for the simulation.

27-53
27 Running Simulations

siminStates2 = Simulink.SimulationInput(modelName);
siminStates2 = setModelParameter(siminStates2,'StartTime','5','StopTime','10');

Specify the initial states for the second portion of the simulation as the final states saved from the
first part of the simulation. By default, final states are stored in a variable called xFinal and
returned as part of the single simulation output as a field in a Simulink.SimulationOutput
object.

siminStates2 = setInitialState(siminStates2,finalStates1.xFinal);

Simulate the model from five seconds to ten seconds. Use the final states without the operating point
as the initial state.

finalStates2 = sim(siminStates2);

Plot the results for all ten seconds of simulation time side by side to see how resuming the
interrupted simulation using final states affects the simulation results.

Combine the logged signal data from the two segments of the interrupted simulation. First, create a
copy of the logged signal data that will contain the combined simulation results.

finalStatesResults = finalStates1.logsout;

In a for loop, access the timeseries objects that contain the time and signal data for each logged
signal, and use the append function to concatenate the data in time. The Dataset object with the
logged signal data contains a Simulink.SimulationData.Signal object for each signal. The
Values property of the Signal object is a timeseries object that contains the data. This example
uses curly braces ({}) to access the Signal objects in the Dataset objects by index.

for idx = 1:numElements(finalStates1.logsout)


ts1 = finalStates1.logsout{idx}.Values;
ts2 = finalStates2.logsout{idx}.Values;
finalStatesResults{idx}.Values = append(ts1,ts2);
end

Plot the data on a 3-by-1 MATLAB figure using a for loop to iterate through the elements of the
Dataset object. This example uses curly braces ({}) to access the elements of the Dataset objects
by index.

fig1 = figure(1);
fig1.Name = "Simulation Resumed Using Final States Without Operating Point";
for idx=1:numElements(baselineResults)
ax = subplot(3,1,idx);
plot(baselineResults{idx}.Values)
hold on
plot(finalStatesResults{idx}.Values,'r--')
hold off
grid on
ax.Title.String = baselineResults{idx}.Values.Name;
end

27-54
Specify Initial State for Simulation

The simulation results diverge in the interrupted simulation after the simulation is resumed using the
final states without operating point information. For this model, the final states alone do not provide
enough information to continue the simulation as though it was never interrupted.

See Also
Model Settings
Initial state | Final states | Save final operating point

Objects
Simulink.op.ModelOperatingPoint | Simulink.SimulationData.Dataset

Related Examples
• “Save Block States and Simulation Operating Points” on page 78-72
• “Use Model Operating Point for Faster Simulation Workflow” on page 27-42
• “Save State Information” on page 78-79

27-55
27 Running Simulations

Systematic Diagnosis of Errors and Warnings


This example shows how to use the Diagnostic Viewer to identify and locate simulation errors and
warnings systematically.

1 Open your model.

If your model contains errors related to callback functions, the Diagnostic Viewer opens and
displays the following errors in Model Load stage.

Tip To open the Diagnostic Viewer window, in the Debug tab, click Diagnostics or click the
view errors or warnings link displayed at the bottom of the Simulink Editor window.
2 In the Simulink Editor, in the Modeling tab, select Model Settings > Model Properties, and
examine the callback error.

3 After fixing any callback errors, simulate the model to diagnose simulation errors and warnings.

Diagnostic Viewer lists errors and warnings in stages. Each stage in Diagnostic Viewer
represents a single event such as model load, update diagram, simulation, or build.

27-56
Systematic Diagnosis of Errors and Warnings

4
To address errors first, click and to filter out warning and information messages.
5 To locate the source of the error, click the hyperlink in the message. The model in the source is
highlighted. If a block has multiple ports, you can hover over each port to see the port number.

6 After fixing all errors, simulate your model again and view the Diagnostic Viewer to identify
remaining problems.

Note If an error or warning has a predefined fix, the diagnostic message pane displays a
Suggested Actions section. You can use the Fix button provided in this section to rectify the
related error or warning. For more information see, “Suggested Actions”.
7 If an object in your model generates a warning that you do not want to be notified of, sometimes,
you can suppress the warning from the specified source using the Suppress button. You can
restore the warning from that source using the Restore button. For example, if a Counter Free-
Running block generates an overflow warning that is intentional in your design, you can suppress
only overflow warnings from this particular block, without sacrificing notification of other
overflows in your model.
8 To generate code for your model, in the C Code tab, click Build.

Note If there is a failure during code generation, Diagnostic Viewer provides hyperlinks for easy
navigation to the source of the error or warning message.

27-57
27 Running Simulations

See Also

Related Examples
• “Customize Diagnostic Messages” on page 27-65
• “Report Diagnostic Messages Programmatically” on page 27-67

27-58
Suppress Diagnostic Messages Programmatically

Suppress Diagnostic Messages Programmatically

The following examples show how to manage diagnostic suppressions programmatically.

In this section...
“Suppress Diagnostic Messages Programmatically” on page 27-59
“Suppress Diagnostic Messages of a Referenced Model” on page 27-61

Note Not all diagnostic IDs can be suppressed. Only IDs that have the Suppress button in the
Diagnostic Viewer or the Suppress hyperlink in the MATLAB Command Window can be suppressed.

Suppress Diagnostic Messages Programmatically

This example shows how to access simulation metadata to manage diagnostic suppressions and to
restore diagnostic messages programmatically.

Open and Simulate the Model

The local example folder contains the getDiagnosticObjects.m, suppressor_script.m, and the
Suppressor_CLI_Demo.slx model. The getDiagnosticObjects.m function queries the
simulation metadata to access diagnostics that were thrown during simulation. The
suppressor_script.m script contains the commands for suppressing and restoring diagnostics to
the Suppressor_CLI_Demo model.

Open the model. To access Simulink.SimulationMetadata class, set the


ReturnWorkspaceOutputs parameter value to '|on|'. Simulate the model.

model = 'Suppressor_CLI_Demo';
open_system(model)
set_param(model,'ReturnWorkspaceOutputs','on');
out = sim(model);

Get Message Identifiers from Simulation Metadata

Find the names of diagnostic message identifiers using the simulation metadata stored in the
MSLDiagnostic object.

if (exist('out', 'var'))
diag_objects = getDiagnosticObjects(out);
end

Several warnings were generated during simulation, including a saturation of the Data Type
Conversion block. Query the diag_objects variable to get more information on the identifiers.

diag_objects(5)

Suppress Saturation Diagnostic on a Block

Use the Simulink.suppressDiagnostic function to suppress the saturation diagnostic on the


data type conversion block only. Simulate the model.

27-59
27 Running Simulations

Simulink.suppressDiagnostic('Suppressor_CLI_Demo/Convert/FixPt To FixPt3', ...


'SimulinkFixedPoint:util:Saturationoccurred');
set_param(model,'SimulationCommand','start');

Restore the Saturation Diagnostic

Use the Simulink.restoreDiagnostic function to restore the saturation diagnostic of the same
block.
Simulink.restoreDiagnostic('Suppressor_CLI_Demo/Convert/FixPt To FixPt3',...
'SimulinkFixedPoint:util:Saturationoccurred');
set_param(model,'SimulationCommand','start');

Suppress Multiple Diagnostics on a Source

You can suppress multiple warnings on a single source by creating a cell array of message identifiers.
Suppress the precision loss and parameter underflow warnings of the Constant block, one, in the
model.
diags = {'SimulinkFixedPoint:util:fxpParameterPrecisionLoss',...
'SimulinkFixedPoint:util:fxpParameterUnderflow'};
Simulink.suppressDiagnostic('Suppressor_CLI_Demo/one',diags);
set_param(model,'SimulationCommand','start');

Restore All Diagnostics on a Block

Restore all diagnostics on a specified block using the Simulink.restoreDiagnostic function.


Simulink.restoreDiagnostic('Suppressor_CLI_Demo/one');
set_param(model,'SimulationCommand','start');

Suppress a Diagnostic on Many Blocks

You can suppress one or more diagnostics on many blocks. For example, use the find_system
function to create a cell array of all Data Type Conversion blocks in a system, and suppress all
saturation warnings on the specified blocks.
dtc_blocks = find_system('Suppressor_CLI_Demo/Convert',...
'BlockType', 'DataTypeConversion');
Simulink.suppressDiagnostic(dtc_blocks, 'SimulinkFixedPoint:util:Saturationoccurred');
set_param(model,'SimulationCommand','start');

Restore All Diagnostics Inside a Subsystem

You can also use the Simulink.restoreDiagnostic function to restore all diagnostics inside a
specified subsystem.
Simulink.restoreDiagnostic('Suppressor_CLI_Demo/Convert',...
'FindAll', 'On');
set_param(model,'SimulationCommand','start');

Add Comments and User Information to a Suppression

A SuppressedDiagnostic object contains information on the source of the suppression and the
suppressed diagnostic message identifier. You can also include comments, and the name of the user
who last modified the suppression.
Object = Simulink.SuppressedDiagnostic('Suppressor_CLI_Demo/Convert/FixPt To FixPt1',...
'SimulinkFixedPoint:util:Saturationoccurred');

27-60
Suppress Diagnostic Messages Programmatically

Object.Comments = 'Reviewed: John Doe';


Object.LastModifiedBy = 'Joe Schmoe'
set_param(model,'SimulationCommand','start');

Get Suppression Data

To get suppression data for a certain subsystem or block, use the


Simulink.getSuppressedDiagnostics function.

Object = Simulink.getSuppressedDiagnostics('Suppressor_CLI_Demo/Convert/FixPt To FixPt1');


set_param(model,'SimulationCommand','start');

Restore All Diagnostics on a Model

When a model contains many diagnostic suppressions, and you want to restore all diagnostics to a
model, use the Simulink.getSuppressedDiagnostics function to return an array of
Simulink.SuppressedDiagnostic objects. Then use the restore method as you iterate through
the array.

Objects = Simulink.getSuppressedDiagnostics('Suppressor_CLI_Demo');
for iter = 1:numel(Objects)
restore(Objects(iter));
end
set_param(model,'SimulationCommand','start');

Suppress Diagnostic Messages of a Referenced Model


This example shows how to suppress a diagnostic when the diagnostic originates from a referenced
model. By accessing the MSLDiagnostic object of the specific instance of the warning, you can
suppress the warning only for instances when the referenced model is simulated from the specified
top model.

This example model contains two instances of the same referenced model, RefModel. The model
RefModel references yet another model, RefModel_Low. RefModel_Low contains two Gain blocks
that each produce a wrap on overflow warning during simulation. Suppress one of the four instances
of this warning in the model by accessing the MSLDiagnostic object associated with the wrap on
overflow warning produced by one of the Gain blocks in the RefModel_Low model only when it is
referenced by Ref_block1.

27-61
27 Running Simulations

27-62
Suppress Diagnostic Messages Programmatically

Open the top model. Simulate the model and store the output in a variable, out.
out = sim('TopModel');

Access the simulation metadata stored in the MSLDiagnostic object.


diag = getDiagnosticObjects(out)

diag =

1×4 MSLDiagnostic array with properties:

identifier
message
paths
cause
stack

You can view the diagnostics and their causes in the Diagnostic Viewer or at the command-line.
for i = 1 : numel(diag)
disp(diag(i));
disp(diag(i).cause{1});
end

Suppress one of the wrap on overflow warnings from RefModel_Low only when it is simulated from
TopModel/Ref_block1 by accessing the specific diagnostic. Simulate the model.
Simulink.suppressDiagnostic(diag(1));
out = sim('TopModel')

Access the simulation metadata. This simulation produced only three warnings.

27-63
27 Running Simulations

diag = getDiagnosticObjects(out)

diag =

1×3 MSLDiagnostic array with properties:

identifier
message
paths
cause
stack

Restore the diagnostic to the model.

Simulink.restoreDiagnostic(diag(1));

See Also
Simulink.getSuppressedDiagnostics | Simulink.suppressDiagnostic |
Simulink.restoreDiagnostic | restore | Simulink.SuppressedDiagnostic |
Simulink.SimulationMetadata

27-64
Customize Diagnostic Messages

Customize Diagnostic Messages

In this section...
“Display Custom Text” on page 27-65
“Create Hyperlinks to Files, Folders, or Blocks” on page 27-65
“Create Programmatic Hyperlinks” on page 27-66

The Diagnostic Viewer displays the output of MATLAB error functions executed during simulation.

You can customize simulation error messages in the following ways by using MATLAB error functions
in callbacks, S-functions, or MATLAB Function blocks.

Display Custom Text


This example shows how you can customize the MATLAB function check_signal to display the text
Signal is negative.

1 Open the MATLAB Function for editing.

2 In the MATLAB Editor, create a function to display custom text.

function y = check_signal(x)
if x < 0
error('Signal is negative');
else
y = x;
end
3 Simulate the model.

A runtime error appears and you are prompted to start the debugger. Click OK.
4 To view the following error in Diagnostic Viewer, close the debugger.

Create Hyperlinks to Files, Folders, or Blocks


To create hyperlinks to files, folders, or blocks in an error message, include the path to these items
within customized text.

27-65
27 Running Simulations

Example error message Hyperlink


error ('Error reading data from "C:/ Opens designData.data in the MATLAB Editor.
Work/designData.mat"')
error ('Could not find data in folder Opens a Command Window and sets C:\Work as
"C:/Work"') the working folder.
error ('Error evaluating parameter in Displays the block Mu in model myModel.
block "myModel/Mu"')

Create Programmatic Hyperlinks


This example shows how you can customize the MATLAB function check_signal to display a
hyperlink to the documentation for find_system.

1 Open the MATLAB Function for editing.

2 In the MATLAB Editor, create a function to display custom text.


function y = check_signal(x)
if x < 0
error('See help for <a href="matlab:doc find_system">find_system</a>');
else
y = x;
end

3 Simulate the model.

A runtime error appears and you are prompted to start the debugger. Click OK.
4 To view the following error in Diagnostic Viewer, close the debugger.

See Also

Related Examples
• “Systematic Diagnosis of Errors and Warnings” on page 27-56
• “Report Diagnostic Messages Programmatically” on page 27-67

27-66
Report Diagnostic Messages Programmatically

Report Diagnostic Messages Programmatically


The sldiagviewer functions enable you to generate, display, and log diagnostic messages in the
Diagnostic Viewer.

By using these functions, you can programmatically:

• Create new diagnostic stages.


• Report diagnostic messages in the Diagnostic Viewer.
• Log diagnostic messages in a text file.

Create Diagnostic Stages


The Diagnostic Viewer organizes and displays the error, warning, and information messages in the
“Diagnostic Message Pane” in different stages. Each stage represents a runtime operation, such as
model load, simulation, build, or diagram update. As more operations occur, new stages are created.
For cases involving multiple operations, child stages are created to form a hierarchical structure.

To initialize a stage, to log the diagnostic messages for the upcoming runtime operation, create a
stage object by using the sldiagviewer.createStage function. If you create a new stage object
without ending the current stage, the new stage is a child stage of the current stage.

To end a stage, close the stage object. If you delete a parent stage object, the parent and its child
stages close in the Diagnostic Viewer.

Create Stage to Display Diagnostic Messages

Create a stage to display diagnostic messages in the Diagnostic Viewer using


sldiagviewer.createStage.

Load the model DiagnosticDemo.

model = "DiagnosticDemo";
load_system(model);

Create a stage to display the diagnostic messages.

myStage = sldiagviewer.createStage("Analysis","ModelName",model);

After you create the stage, you can report the diagnostics of your next Simulink® operation in the
Diagnostic Viewer in the Analysis stage. For more information, see Diagnostic Viewer.

Report Diagnostic Messages


Use the sldiagviewer.reportError, sldiagviewer.reportWarning, and
sldiagviewer.reportInfo functions to report error, warning, and information messages,
respectively, in the Diagnostic Viewer.

Optionally, you can specify the name of the component or the product that generates the diagnostic
message, such as Simulink, Model Advisor, or Stateflow.

27-67
27 Running Simulations

Report Error Message

Display error messages in the Diagnostic Viewer using sldiagviewer.reportError.

Load the model DiagnosticDemo.

model = "DiagnosticDemo";
load_system(model);

Create a stage to display the diagnostic messages.

myStage = sldiagviewer.createStage("Analysis","ModelName",model);

Introduce errors inside the try block and catch the resulting errors in the catch block.

try
i = p;
catch error
end

Report the error message in the Diagnostic Viewer.

output = sldiagviewer.reportError(error)

The diagnostic window opens for the model and displays the error message in red in the Analysis
stage.

Log Diagnostic Messages in a File


Use the sldiagviewer.diary function to log diagnostic messages and build information in a text
file.

By default, sldiagviewer.diary logs the diagnostic messages in a text file diary.txt located in
the current folder using the default character encoding of your system. You can also specify a
filename to log messages and set character encoding to UTF-8. For more information, see “Log
Diagnostic Messages in Specific File” and “Specify Character Encoding of Log File”. You can also
switch the logging state to on or off in the current log file.

Toggle File Logging State

Create a log by file using sldiagviewer.diary and toggle the logging state.

Create the log file diary.txt and turn on logging.

sldiagviewer.diary

Load the model DiagnosticDemo.

model = "DiagnosticDemo";
open_system(model);

Introduce errors into the model.

set_param("DiagnosticDemo/Gain","Gain","xyz");

27-68
Report Diagnostic Messages Programmatically

Simulate the model.

set_param(model,"SimulationCommand","Start")

The errors are logged in diary.txt.

Again, introduce errors into the model.

set_param("DiagnosticDemo/Gain","Gain","abc");

Turn off logging.

sldiagviewer.diary("off")

Simulate the model.

set_param(model,"SimulationCommand","Start")

The errors are not logged in diary.txt.

See Also
Tools
Diagnostic Viewer

More About
• “Customize Diagnostic Messages” on page 27-65
• “Systematic Diagnosis of Errors and Warnings” on page 27-56

27-69
27 Running Simulations

View and Trace Callbacks in Models

You can view and trace all the callbacks executed in a model. To record all callbacks, on the Simulink
toolstrip, on the Debug tab, under Diagnostics, select Log Callbacks. To view the callback report,
go to Debug > Diagnostics > Callback Tracer.

The Callback Tracer report displays the Order, Callback Type, Object Name, Callback Code, and
Total Execution Time (s).

This is the callback tracer report for the vdp model.

27-70
View and Trace Callbacks in Models

Order: The order in which callbacks are executed. You can sort this column in ascending or
descending order.

Callback Type: Callbacks that are executed based on events, for example, PostLoadFcn,
DeleteFcn, LoadFcn, InitFcn.

Object Name: The object that triggers the callback. The objects are hyper-linked. Click the hyper-
linked object name to navigate to the object. The object is highlighted in the model, which helps you
to identify the object without having to search for it.

27-71
27 Running Simulations

Callback Code: The callback code is displayed in this column. The code is hyper-linked. Click the
code to go to the callback code editor, where you can make code changes.

Total Execution Time (s) : The total time to execute the callback code. This column is sortable,
which allows you to analyze the performance of the callback code and minimize time.

Filters
You can filter callbacks based on type:

27-72
View and Trace Callbacks in Models

• “Block Callback”
• “Model Callback”
• “Port Callback”
• Mask Initialization Callbacks
• “Initialization and Parameter Callbacks”

Stage-Specific Callbacks
The callbacks are recorded for each event, for example, Model Load, Simulation, Update
Diagram. Click the stage pane and select an event to view callbacks specific to the event. The time
stamp and the time taken for execution are recorded.

Search
Use the Search box to search for specific keywords.

Export
You can export the Callback Tracer report to a TXT or JSON file. To export the Callback Tracer report,
click Export, then select the file format.

If you export the report in JSON format, use this code to read the contents of the JSON file.

fileName = 'vdp.json';
str = fileread(fileName);
data = jsondecode(str);

Trace Callbacks Programmatically


To trace callbacks programmatically, enter set_param(0, 'CallbackTracing', 'on') in the
MATLAB Command Window.

The CallbackTracing parameter 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 enable the preference.

27-73
27 Running Simulations

See Also

Related Examples
• “Customize Model Behavior with Callbacks” on page 4-68
• “Model Callbacks” on page 4-70
• “Block Callbacks” on page 4-75
• “Port Callbacks” on page 4-81
• “Fast Restart Methodology” on page 87-10

27-74
28

Running a Simulation Programmatically


28 Running a Simulation Programmatically

Run Simulations Programmatically


To run simulations programmatically, you can write scripts or issue commands in the MATLAB
Command Window. Several interfaces provide programmatic simulation capabilities. Each interface
has different capabilities for configuring simulation behavior and interacting with the simulation as it
runs.

Programmatic Interface General Use Case


sim function Configure and run simulations.
Simulation object Configure and run simulations, tune variable and
parameter values during simulation, and write
scripts that control simulation execution.
set_param function with SimulationCommand Interact with simulation using both the MATLAB
name-value argument Command Window and the Simulink Editor.

Simulations you run programmatically using the sim function, the Simulation object, or the
set_param function run one at a time, in serial. To run parallel or batch simulations, use the parsim
function or the batchsim function.

Decide How to Run or Script Programmatic Simulations


In general, the sim function supports most requirements for running and scripting individual and
serial programmatic simulations where you do not intend to interact with the model during the
simulation.

When you want to interact with a simulation programmatically during the simulation, use a
Simulation object. Using a Simulation object, you can control the simulation execution and tune
parameter and variable values during simulation. You can write MATLAB scripts that modify
parameter or variable values based on results and values computed in the simulation.

While you can programmatically interact with simulations you run using Simulation objects, you
cannot interact with the model or simulation associated with a Simulation object using the
Simulink Editor while the simulation has a status other than inactive. Issuing simulation commands
using the set_param function allows you to interact with a model both programmatically from the
MATLAB command prompt and interactively using the Simulink Editor. Simulation commands are
supported in simulations you start by clicking Run in the Simulink Editor or by issuing the start
simulation command.

The table summarizes the functionality available for scripting programmatic simulations that use the
sim function and for those that use the Simulation object.

28-2
Run Simulations Programmatically

Action or Option sim Function Simulation object


Configure simulation without You can specify parameter and You can specify parameter and
directly modifying the model variable values to override the variable values to override the
values saved in the model using values saved in the model by
a creating the Simulation object
Simulink.SimulationInput from an existing
object, a structure, a Simulink.SimulationInput
Simulink.ConfigSet object, object or by specifying the
or name-value arguments. override values on the
Simulation object.
The override values that you
specify are applied for the The override values that you
simulation and revert once the specify are applied for the
simulation completes. simulation and revert once the
simulation completes.
Tune parameter and variable Not supported. Use the setVariable,
values during simulation setModelParameter, and
setBlockParameter functions
to tune parameter values during
simulation.
Stop simulation In the MATLAB Command Call the stop function or the
Window, press Ctrl+C. terminate function.
Pause simulation Not supported. Call the pause function.

Use the step function to specify


the amount to advance the
simulation before pausing.
Issue command in MATLAB Not supported. Supported.
Command Window
The MATLAB command prompt The MATLAB command prompt
is not available during is available while the simulation
simulation. is running, except when you
advance the simulation by
calling the step function.
View simulation results using Supported for normal and Not supported.
visualization blocks, such as the accelerator mode simulations.
Scope block
Not supported for rapid
accelerator simulations.
Port value labels Not supported. Not supported.
Step through simulation Not supported. To advance the simulation, use
the step function.

Stepping backward is not


supported.
Signal breakpoints Not supported. Not supported.

28-3
28 Running a Simulation Programmatically

Action or Option sim Function Simulation object


Pause at or after specified time Not supported. Use the step function with the
PauseTime name-value
argument.
Capture information about Specify the CaptureErrors Specify the CaptureErorrs
simulation errors in simulation name-value argument as "on". parameter as "on" using the
output instead of issuing setModelParameter.
exception
Fast restart Supported. Supported.
Simulation pacing Supported. Supported.
Simulation timeout Specify a maximum amount of Not supported.
time to allow the sim function
to run using the Timeout name-
value argument.
Query simulation status Not supported. The Status property of the
Simulation object indicates
Simulation execution blocks the the current simulation status.
MATLAB thread.
Run simulation in MATLAB Supported. Not supported.
session started using the -
nodesktop or -nodisplay
options for matlab (macOS) or
matlab (Linux).

Run and Script Simulations Using sim Function


The sim function has several syntaxes you can use to run and configure simulations
programmatically. When you want to simulate the model using the current values for all model
configuration parameter values, block parameter values, variable values, and so on, use the most
basic syntax, specifying only the name of the model as an input argument.

out = sim("ModelName");

This syntax returns a single Simulink.SimulationOutput object that contains all simulation
results, except when the Single simulation output parameter is disabled. To ensure you can write
consistent code for all simulations you run programmatically, enable the Single simulation output
parameter.

When you want to configure the simulation, for example, by specifying values for model configuration
parameter values, block parameter values, and variables values, use a
Simulink.SimulationInput object to specify the simulation configuration. This command shows
the basic syntax for using a SimulationInput object. The SimulationInput object, stored in a
variable named simin, is the only input argument. The simulation results are always returned as a
single Simulink.SimulationOutput object.

out = sim(simin);

The table summarizes the options you can configure and use cases for using each syntax.

28-4
Run Simulations Programmatically

sim Syntax Simulation Configuration Options


out = sim("ModelName"); Simulate model using current values for
configuration parameter, block parameter, and
variable values.
out = sim(simin); Specify simulation configuration using
Simulink.SimulationInput object with
override values for:

• Model configuration parameters


• Variables
• External inputs
• Initial state
• Block parameters

Use name-value arguments to configure


additional options, such as whether to:

• Run simulations using fast restart.


• Capture errors in the simulation output or
issue MATLAB exceptions.
• Open the Simulation Manager.
out = sim("ModelName",Name=Value); Use name-value arguments to configure
simulation options, such as:

• Model configuration parameters


• Simulation pacing options
• Whether to simulate using fast restart
• Whether to capture errors in the simulation
output or issue MATLAB exceptions
out = sim("ModelName",paramstruct); Specify model configuration parameter values
and simulation options using a structure with
field names that match each parameter name and
field values that specify the value to use for each
parameter.

For example, to specify the StopTime parameter


value as 20, create a structure with a field named
StopTime that has a value of "20".

paramStruct.StopTime = "20";
out = sim("ModelName",configset); Specify model configuration parameter values
using a Simulink.ConfigSet object.

Run and Script Simulations Using Simulation Objects


A Simulation object represents a simulation of a model and provides an interface to control and
interact with the simulation as it runs. The MATLAB command prompt is available while the

28-5
28 Running a Simulation Programmatically

simulation is running, unlike simulations you run using the sim function. Using the Simulation
object, you can:

• Write scripts that control and interact with simulations using logic in MATLAB code based on
simulation results you can access during run time.
• Step forward through major time steps in simulation.
• Tune parameter and variable values during simulation.
• Build apps using App Designer to control, interact with, and monitor simulations.
• Deploy simulation scripts and apps using Simulink Compiler™.

The table summarizes the Simulation object functions you can use to control the simulation
execution.

Function Description Details


initialize Initialize simulation. The MATLAB command prompt
is unavailable until initialization
is complete.
start Start simulation. If you start a simulation that is
not initialized, the start
function initializes the
simulation before starting it.
The MATLAB command prompt
is unavailable until initialization
is complete, at which point the
simulation starts and the
MATLAB command prompt
becomes available.
step Advance simulation by a You can advance the simulation
specified amount and then by a single major time step, by a
pause. specified number of major time
steps, and to or past a specified
simulation time. The simulation
pauses after advancing by the
specified amount.

The MATLAB command prompt


is unavailable while the
simulation advances.
pause Pause active simulation. The pause function sends an
immediate request to pause the
simulation. The simulation
pauses after completing
processes that must finish
without interruption.

The MATLAB command prompt


is unavailable while the
simulation pauses.

28-6
Run Simulations Programmatically

Function Description Details


resume Continue paused simulation. The MATLAB command prompt
is unavailable while resuming
the simulation and becomes
available once the simulation
starts to execute.
stop Stop active simulation before The stop function sends an
simulation stop time. immediate request to stop the
simulation. The simulation stops
after completing processes that
must finish without interruption.

When a simulation reaches the


simulation stop time, the
simulation stops on its own,
except when you advance a
normal or accelerator mode
simulation through the last time
step using the step function. In
this case, the simulation pauses
after the last time step.
terminate Terminate simulation. Simulations that do not have
fast restart enabled terminate
when they stop. Fast restart
simulations remain compiled
after stopping so that you do not
need to initialize subsequent
simulations. Simulations that
run after you termination
require initialization.

You can configure simulations by specifying the initial state, external inputs, model parameter, block
parameter, and variable values to use in the simulation. The values you specify override the values
saved in the model during simulation and revert when the simulation completes. You can also modify
the values of tunable parameter and variable values during simulation. The table summarizes the
Simulation object functions available for configuring the simulation.

Function Description Details


setInitialState Specify initial state or operating The initial state is tunable only
point for simulation. between simulations and not
during simulation.
setExternalInput Specify external input data to External input data is tunable
load using top-level input ports. only between simulations and
not during simulation.
setModelParameter Specify values for model Most configuration parameters
configuration parameters to use are tunable only between
in simulation. simulations and not during
simulation.

28-7
28 Running a Simulation Programmatically

Function Description Details


setVariable Specify variable values to use in You can configure the initial
simulation. variable values to use in the
simulation and tune variable
values during simulation.
setBlockParameter Specify block parameter values Some block parameters are
to use in simulation. tunable only between
simulations and not during
simulations.

Deployed simulations do not


support tuning block parameter
values. To tune block parameter
values in a deployed simulation,
specify the block parameter
value as a variable and then
tune the variable value instead.

Interact with Simulations by Issuing Simulation Commands


Starting a simulation by using the set_param function to issue a simulation command is equivalent
to starting a simulation from a user interface, such as by clicking Run in the Simulink Editor. The
simulation commands programmatically initiate the same actions you can initiate using a user
interface, such as the Simulink Editor. Use simulation commands as a convenience in workflows that
involve switching between the MATLAB Command Window and the Simulink Editor or another user
interface.

To issue a simulation command, specify the SimulationCommand name-value argument for the
set_param function. For example, this command issues the start simulation command for a model
named MyModel.

set_param("MyModel",SimulationCommand="start")

Because issuing the start simulation command performs the same action as starting a simulation
from a user interface, you can issue simulation commands to control and interact with simulations
that you start from a user interface or by issuing the start simulation command. Simulations that
you start by issuing the start simulation command offer the same functionality and support as
simulations you start from a user interface, including:

• Tuning parameter values during simulation using a user interface or using the set_param
function
• Viewing signal values and simulation results in the block diagram using port value labels and
visualization blocks, such as the Scope block
• Controlling simulation execution by pausing and stepping backward and forward using the Pause,
Step Forward, and Step Back buttons
• Debugging tools, such as signal breakpoints

Errors that occur as a result of issuing a simulation command or during simulations that you start by
issuing the start simulation command are reported to the Diagnostic Viewer, except for errors that
occur while executing the update simulation command.

28-8
Run Simulations Programmatically

When you issue simulation commands during simulation, the software does not execute the command
immediately. The software issues the command only after currently running processes that cannot be
interrupted have finished. For example, if you issue a simulation command while the solver is
determining the next time step, the software executes the simulation command only after the solver
finishes propagating time.

Not all actions available in the Simulink Editor have a corresponding simulation command. The table
describes each simulation command and the corresponding user interface actions and keyboard
shortcuts.

Simulation Command Description Equivalent User Keyboard Shortcut


Interface Action
Start simulation.
set_param(mdl,SimulationCommand="start") Click Run. Ctrl+T or F5
Stop simulation.
set_param(mdl,SimulationCommand="stop") Click Stop. Ctrl+Shift+T
Pause simulation.
set_param(mdl,SimulationCommand="pause") Click Pause. Ctrl+T or F5
Resume paused
set_param(mdl,SimulationCommand="continue") Click Continue. Ctrl+T or F5
simulation.
Update diagram.
set_param(mdl,SimulationCommand="update") In the Simulink Ctrl+D
Toolstrip, in the
Prepare section, click
Update Model.
Write data logging Not supported.
set_param(mdl,SimulationCommand="writedatalogs") Not supported.
variables to the
workspace.

When you start a simulation from a user interface or by issuing a simulation command, you can query
the simulation status using the get_param function. For example, this command queries the
simulation status for a model named MyModel.
simstatus = get_param("MyModel","SimulationStatus")

This table describes the simulation status that corresponds to each return value for the
SimulationStatus argument.

SimulationStatus Value Description


stopped Simulation stopped.
initializing Executing initialization phase.
running Running execution phase.
paused Paused in execution phase.
compiled Model compiled.
updating Updating diagram.
terminating Executing termination phase.
external Simulating with Simulink Coder.

See Also
Functions
sim | set_param | get_param

28-9
28 Running a Simulation Programmatically

Objects
Simulink.SimulationInput | Simulink.SimulationOutput | Simulink.ConfigSet

Related Examples
• “Get Started with Fast Restart” on page 87-7
• “Use Model Operating Point for Faster Simulation Workflow” on page 27-42

28-10
Run Parallel Simulations

Run Parallel Simulations


The parsim command allows you to run parallel (simultaneous) simulations of your model (design).
In this context, parallel runs mean multiple simulations at the same time on different workers. The
parsim function makes it easy for you to run the same model with different inputs or different
parameter settings in scenarios such as Monte Carlo analyses, parameter sweeps, model testing,
experiment design, and model optimization. Running a single simulation in parallel by decomposing
the model into smaller components and running those individual pieces simultaneously on multiple
workers is currently not supported.

You can run multiple simulations from the Simulink Editor using the Multiple Simulations panel. You
can pick a block parameter of interest from the model canvas and specify values that you want to use
for the simulations. With the Multiple Simulations panel, you can provide configurations such as Use
Parallel to run your simulations in parallel. To run the simulations that you have set up, first, select
the design study, then in the Simulink Toolstrip, on the Simulation tab, click Run All. Once the
simulations are complete, you can view and manage the results in Simulation Manager. For more
information, see “Multiple Simulations Panel: Simulate for Different Values of Stiffness for a Vehicle
Dynamics System” on page 29-26 and “Configure and Run Simulations with Multiple Simulations
Panel” on page 29-19.

To run the simulations in parallel with using the parsim function, you need a Parallel Computing
Toolbox for local workers. In addition, you can use MATLAB Parallel Server for multiple computer
clusters, clouds, and grids. In the absence of Parallel Computing Toolbox and MATLAB Parallel
Server, the parsim function runs the simulations in serial. For more information, see “Parallel
Computing Toolbox” and “MATLAB Parallel Server”.

If no parallel pool exists, the parsim function creates a pool from the default cluster profile . To use a
cluster other than the default, create a pool with that cluster profile before calling the parsim
function.

This example runs multiple simulations in parallel for a set of sweep parameters.

mdl = "sldemo_suspn_3dof";
openExample(...
"simulink_features/MultipleSimulationsWorkflowTipsExample",...
supportingFile=mdl)

Cfsweep = 2500*(0.05:0.1:0.95);
numSims = numel(Cfsweep);

simIn(1:numSims) = Simulink.SimulationInput(mdl);
for idx = 1:numSims
simIn(idx) = setBlockParameter(simIn(idx),...
(mdl + "/Road-Suspension Interaction"),...
"Cf",num2str(Cfsweep(idx)));
end

simOut = parsim(simIn);

How parsim Works


The parsim function runs simulations with different parameters and values based on the
Simulink.SimulationInput object. Each SimulationInput object specifies one simulation of

28-11
28 Running a Simulation Programmatically

the model. An array of these objects can be created for multiple simulations. For more information,
see “Running Multiple Simulations” on page 29-2.

You can use these functions and properties on the Simulink.SimulationInput object:

• setVariables - Change variables in base workspace, data dictionary, or model workspace


• setBlockParameter - Change block parameters
• setModelParameter - Change model parameters
• setPreSimFcn - Specify MATLAB functions to run before each simulation for customization and
post-processing results on the cluster
• setPostSimFcn - Specify MATLAB functions to run after each simulation for customization and
post-processing results on the cluster
• InitialState - Change the Initial State
• ExternalInput - Specify a numerical array, timeseries, or Dataset object as external inputs to
the model

This flowchart shows a general sequence of events that occur when the parsim function is executed

28-12
Run Parallel Simulations

Changes to model library blocks can be overwritten when using the parsim function. When models
are set up on new workers, model inherits properties directly from the worker library. Use the
SetUpFcn name-value argument for the parsim function to transfer the model library block changes
to the workers.

See Also
Objects
Simulink.SimulationInput

Functions
applyToModel | setBlockParameter | setModelParameter | setInitialState |
setExternalInput | setVariable | validate | setPreSimFcn | setPostSimFcn

Tools
Simulation Manager

Related Examples
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Running Multiple Simulations” on page 29-2
• “Comparison Between Multiple Simulation Workflows” on page 29-10
• “Optimize, Estimate, and Sweep Block Parameter Values” on page 41-38

28-13
28 Running a Simulation Programmatically

Using sim Function Within parfor

Note Using sim function within parfor loop is no longer recommended. For running parallel
simulations, use parsim. Please see “Run Parallel Simulations” on page 28-11.

Overview of Calling sim from Within parfor


The parfor command allows you to run parallel (simultaneous) Simulink simulations of your model
(design). In this context, parallel runs mean multiple model simulations at the same time on different
workers. Calling sim from within a parfor loop often helps for performing multiple simulation runs
of the same model for different inputs or for different parameter settings. For example, you can save
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 38-10 for details on selecting a simulation mode and “Design
Your Model for Effective Acceleration” on page 38-14 for optimizing simulation run times.) For other
simulation modes, you need to address any workspace access issues and data concurrency issues to
produce useful results. Specifically, the simulations need to create separately named output files and
workspace variables. Otherwise, each simulation overwrites the same workspace variables and files,
or can have collisions trying to write variables and files simultaneously.

For information on code regeneration and parameter handling in Rapid Accelerator mode, see
“Parameter Tuning in Rapid Accelerator Mode” on page 38-7.

Also, see parfor.

Note If you open models inside a parfor statement, close them again using bdclose all to avoid
leaving temporary files behind.

sim in parfor with Normal Mode

This code fragment shows how you can use sim and parfor in Normal mode. Save changes to your
model before simulating in parfor. The saved copy of your model is distributed to parallel workers
when simulating in parfor.
% 1) Load model and initialize the pool.
openExample('sldemo_suspn_3dof');
model = 'sldemo_suspn_3dof';
load_system(model);
parpool;

% 2) Set up the iterations that we want to compute.


Cf = evalin('base', 'Cf');
Cf_sweep = Cf*(0.05:0.1:0.95);
iterations = length(Cf_sweep);
simout(iterations) = Simulink.SimulationOutput;

% 3) Need to switch all workers to a separate tempdir in case

28-14
Using sim Function Within parfor

% any code is generated for instance for StateFlow, or any other


% file artifacts are created by the model.
spmd
% Setup tempdir and cd into it
currDir = pwd;
addpath(currDir);
tmpDir = tempname;
mkdir(tmpDir);
cd(tmpDir);
% Load the model on the worker
load_system(model);
end

% 4) Loop over the number of iterations and perform the


% computation for different parameter values.
parfor idx=1:iterations
set_param([model '/Road-Suspension Interaction'],'MaskValues',...
{'Kf',num2str(Cf_sweep(idx)),'Kr','Cr'});
simout(idx) = sim(model, 'SimulationMode', 'normal');
end

% 5) Switch all of the workers back to their original folder.


spmd
cd(currDir);
rmdir(tmpDir,'s');
rmpath(currDir);
close_system(model, 0);
end

close_system(model, 0);
delete(gcp('nocreate'));

sim in parfor with Normal Mode and MATLAB Parallel Server Software

This code fragment is identical to the one in “sim in parfor with Normal Mode” on page 28-14

. Modify it as follows for using sim and parfor in Normal mode:

• In item 1, modify the parpool command as follows to create an object and use it to call a cluster
name.

p = parpool('clusterProfile');
% 'clusterProfile' is the name of the distributed cluster
• In item 1, find files on which the model depends and attach those files to the model for distribution
to cluster workers on remote machines.

files = dependencies.fileDependencyAnalysis(modelName);
p.addAttachedFiles(files);
• If you do not have a MATLAB Parallel Server cluster, use your local cluster. For more information,
see “Discover Clusters and Use Cluster Profiles” (Parallel Computing Toolbox).

Start your cluster before running the code.

% 1) Load model and initialize the pool.


openExample('sldemo_suspn_3dof');
model = 'sldemo_suspn_3dof';
load_system(model);

28-15
28 Running a Simulation Programmatically

parpool;

% 2) Set up the iterations that we want to compute.


Cf = evalin('base', 'Cf');
Cf_sweep = Cf*(0.05:0.1:0.95);
iterations = length(Cf_sweep);
simout(iterations) = Simulink.SimulationOutput;

% 3) Need to switch all workers to a separate tempdir in case


% any code is generated for instance for StateFlow, or any other
% file artifacts are created by the model.
spmd
% Setup tempdir and cd into it
addpath(pwd);
currDir = pwd;
addpath(currDir);
tmpDir = tempname;
mkdir(tmpDir);
cd(tmpDir);
% Load the model on the worker
load_system(model);
end

% 4) Loop over the number of iterations and perform the


% computation for different parameter values.
parfor idx=1:iterations
set_param([model '/Road-Suspension Interaction'],'MaskValues',...
{'Kf',num2str(Cf_sweep(idx)),'Kr','Cr'});
simout(idx) = sim(model, 'SimulationMode', 'normal');
end

% 5) Switch all of the workers back to their original folder.


spmd
cd(currDir);
rmdir(tmpDir,'s');
rmpath(currDir);
close_system(model, 0);
end

close_system(model, 0);
delete(gcp('nocreate'));

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:

• Configure the model to run in rapid accelerator simulation mode.


• Save changes to your model before simulating in parfor. The saved copy of your model is
distributed to parallel workers when simulating in parfor.
• Ensure that the rapid accelerator target is already built and up to date.

28-16
Using sim Function Within parfor

• 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 change parameters only 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 “Determine If the Simulation Will Rebuild” on page 38-
7.

To disable the rapid accelerator target up-to-date check, use the sim function, as shown in this
sample.

parpool;
% 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));
close_system(model, 0);
end

close_system(model, 0);
delete(gcp('nocreate'));

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.

When you set RapidAcceleratorUpToDateCheck to 'off', changes that you make to block
parameter values in the model (for example, by using block dialog boxes, by using the set_param
function, or by changing the values of MATLAB variables) do not affect the simulation. Instead, use
RapidAcceleratorParameterSets to pass new parameter values directly to the simulation.

Workspace Access Issues

Workspace Access for MATLAB worker sessions

By default, to run sim in parfor, a parallel pool opens automatically, enabling the code to run in
parallel. Alternatively, you can also first open MATLAB workers using the parpool 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.

28-17
28 Running a Simulation Programmatically

Transparency Violation

When you run sim in parfor with srcWorkspace set to current, Simulink uses the parfor
workspace, which is a transparent workspace. Simulink then displays an error for transparency
violation. For more information on transparent workspaces, see “Ensure Transparency in parfor-
Loops or spmd Statements” (Parallel Computing Toolbox) .
Data Dictionary Access

When a model is linked to a data dictionary (see “What Is a Data Dictionary?” on page 80-2), to
write code in parfor that accesses a variable or object that you store in the dictionary, you must use
the functions Simulink.data.dictionary.setupWorkerCache and
Simulink.data.dictionary.cleanupWorkerCache to prevent access issues. For an example,
see “Sweep Variant Control Using Parallel Simulation” on page 28-19.

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 function to load the model and to set parameters that change
with each iteration. (Alternatively, load the model and then use the get_param and set_param
functions to get and set the parameters in the parfor loop.)
• In the parfor loop, use the MATLAB evalin and assignin functions 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 store signal
objects that use a storage class other than Auto in a model workspace. For a detailed discussion on
the model workspace, see “Model Workspaces” on page 73-138.
Specifying Parameter Values Using the sim Function

Use the sim function in the parfor loop to set parameters that change with each iteration.
%Specifying Parameter Values Using the sim Command

model = 'vdp';
load_system(model)

%Specifying parameter values.


paramName = 'StopTime';
paramValue = {'10', '20', '30', '40'};

% Run parallel simulations


parfor i=1:4
simOut{i} = sim(model, ...
paramName, paramValue{i}, ...
'SaveTime', 'on'); %#ok

28-18
Using sim Function Within parfor

end

close_system(model, 0);

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 Function

You can pass the values of model or simulation variables to the MATLAB workers by using the
assignin or evalin functions. This example illustrates how to use this technique to load variable
values into the appropriate workspace of the MATLAB workers.
parfor i = 1:4
assignin('base', 'extInp', paramValue{i})%#ok
% 'extInp' is the name of the variable in the base
% workspace which contains the External Input data
simOut{i} = sim(model, 'ExternalInput', 'extInp'); %#ok
end

Sweep Variant Control Using Parallel Simulation

To use parallel simulation to sweep a variant control (a Simulink.Parameter object whose value
influences the variant condition of a Simulink.VariantExpression object) that you store in a data
dictionary, use this code as a template. Change the names and values of the model, data dictionary,
and variant control to match your application.

To sweep block parameter values or the values of workspace variables that you use to set block
parameters, use Simulink.SimulationInput objects instead of the programmatic interface to the
data dictionary. See “Optimize, Estimate, and Sweep Block Parameter Values” on page 41-38.

You must have a Parallel Computing Toolbox license to perform parallel simulation.

% For convenience, define names of model and data dictionary


model = 'mySweepMdl';
dd = 'mySweepDD.sldd';

% Define the sweeping values for the variant control


CtrlValues = [1 2 3 4];

% Grant each worker in the parallel pool an independent data dictionary


% so they can use the data without interference
spmd
Simulink.data.dictionary.setupWorkerCache
end

% Determine the number of times to simulate


numberOfSims = length(CtrlValues);

% Prepare a nondistributed array to contain simulation output


simOut = cell(1,numberOfSims);

parfor index = 1:numberOfSims


% Create objects to interact with dictionary data
% You must create these objects for every iteration of the parfor-loop
dictObj = Simulink.data.dictionary.open(dd);
sectObj = getSection(dictObj,'Design Data');
entryObj = getEntry(sectObj,'MODE');

28-19
28 Running a Simulation Programmatically

% Suppose MODE is a Simulink.Parameter object stored in the data dictionary

% Modify the value of MODE


temp = getValue(entryObj);
temp.Value = CtrlValues(index);
setValue(entryObj,temp);

% Simulate and store simulation output in the nondistributed array


simOut{index} = sim(model);

% Each worker must discard all changes to the data dictionary and
% close the dictionary when finished with an iteration of the parfor-loop
discardChanges(dictObj);
close(dictObj);
end

% Restore default settings that were changed by the function


% Simulink.data.dictionary.setupWorkerCache
% Prior to calling cleanupWorkerCache, close the model

spmd
bdclose(model)
Simulink.data.dictionary.cleanupWorkerCache
end

Note If data dictionaries are open, you cannot use the command
Simulink.data.dictionary.cleanupWorkerCache. To identify open data dictionaries, use
Simulink.data.dictionary.getOpenDictionaryPaths.

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 might cause errors by attempting to log data to the same files during parallel simulations.
A third-party blockset or custom S-function might 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.

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. During the parallel simulation of a model that involves generating a simulation
target, such as accelerator mode simulation, the software makes concurrent attempts to access
(update) the simulation target. However, you can avoid such data concurrency issues by creating a

28-20
Using sim Function Within parfor

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 or
sldemo_autotrans). 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
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});
close_system(model,0);
cd(cwd)
rmdir(tmpdir,'s')
rmpath(cwd)
end

Note the following:

• 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.
• On Windows platforms, consider inserting the evalin('base', 'clear mex'); command
before rmdir(tmpdir, 's'). This sequence closes MEX-files first before calling rmdir to
remove tmpdir.

evalin('base', 'clear mex');


rmdir(tmpdir, 's')

Models 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

28-21
28 Running a Simulation Programmatically

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.

rtp = Simulink.BlockDiagram.buildRapidAcceleratorTarget(model);
parfor idx=1:4
sim(model, ...
'ConcurrencyResolvingToFileSuffix', num2str(idx),...
'SimulationMode', 'rapid',...
'RapidAcceleratorUpToDateCheck', 'off');
end

See Also

Related Examples
• “Model an Automatic Transmission Controller”
• “Optimize, Estimate, and Sweep Block Parameter Values” on page 41-38
• “Sweep Variant Control Using Parallel Simulation” on page 28-19

28-22
Error Handling in Simulink Using MSLException Objects

Error Handling in Simulink Using MSLException Objects

Error Reporting in Simulink Applications


Simulink allows you to report an error by throwing an exception using the MSLException object,
which is based on the MATLAB MException object. As with the MATLAB MException object, you
can use a try-catch block with a MSLException object 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.

MSLException Objects
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 MException. 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.

MSLException Object Functions


The functions for the MSLException object are identical to those of the MSLException object. For
details of these functions, see MException.

Capturing Information About the Error


This code shows the structure of the try-catch block for capturing an MSLException. 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 determine if the exception is an MSLException object, which
indicates that the exception came from Simulink specific. In other words, an MSLException is a type
of MException.

try
Perform one or more operations
catch E
if isa(E, 'MSLException')
...
end

This code example shows how to get the handles associated with an error.

errHndls = [];
try
sim('ModelName');
catch e
if isa(e,'MSLException')
errHndls = e.handles{1}
end
end

You can see the results by examining the variable e. The results look similar to this output.

28-23
28 Running a Simulation Programmatically

e =

MSLException

Properties:
handles: {[7.0010]}
identifier: 'Simulink:Parameters:BlkParamUndefined'
message: [1x87 char]
cause: {0x1 cell}
stack: [0x1 struct]

Methods, Superclasses

To identify the name of the block that threw the error, use the getfullname function. For the
present example, enter this command in the MATLAB Command Window.

getfullname(errHndls)

If a block named Mu threw an error from a model named vdp, the getfullname function returns the
path to the block named Mu.

ans =
vdp/Mu

See Also

Related Examples
• “Run Simulations Programmatically” on page 28-2
• “Running Multiple Simulations” on page 29-2

28-24
29

Multiple Simulations
29 Multiple Simulations

Running Multiple Simulations


For workflows that involve multiple parallel simulations and logging of large amounts of data, you can
use the parsim or batchsim functions, or run the simulations with the Multiple Simulations panel
in the Simulink Editor. This approach is useful in scenarios like model testing, experiment design,
Monte Carlo analysis, and model optimization.

For the command line workflow (parsim or batchsim functions), you can create simulation sets by
using an array of Simulink.SimulationInput objects to run multiple simulations. Alternatively,
you can use the Multiple Simulations panel in Simulink.

In the Multiple Simulations panel, you can create design studies to make specify values for
simulations. The panel allows you to specify values for block parameters, and variables for the
simulations.

With the Parallel Computing Toolbox, you can also use the parsim and batchsim functions, and
Multiple Simulations panel to run the simulations in parallel.

• To run multiple simulations with Simulink.SimulationInput object and parsim function, see
“Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5. To learn
more about how the parsim function runs simulations in parallel, see “Run Parallel Simulations”
on page 28-11.
• To learn about running multiple simulations in batch, see batchsim.
• To understand the differences between the command line workflows and how they work, see
“Comparison Between Multiple Simulation Workflows” on page 29-10.
• To use the graphical user interface for running multiple simulations, see “Configure and Run
Simulations with Multiple Simulations Panel” on page 29-19.
• To learn how to monitor the simulations and view the results, see “Analyze Data from Multiple
Simulations” on page 31-136.

Note When the pool is not already open and simulations are run for the first time, simulations take
an additional time to start. Subsequent parallel simulations are faster.

Multiple Simulations with Simulink Editor


The Multiple Simulations panel allows you to set up multiple simulations for different values of
block parameters and variables. You can pick a block parameter of interest from the model canvas
and specify values that you want to use for the simulations. You can also provide variables for
simulations. To run the simulations that you have set up, first, select the design study, then click Run
All button on Simulation tab on the Simulink toolstrip. To learn more, see the “Multiple Simulations
Panel: Simulate for Different Values of Stiffness for a Vehicle Dynamics System” on page 29-26
example.

Multiple Simulations with Parallel Computing Toolbox


The parsim function and the Multiple Simulations panel distributes each simulation to parallel
pool workers to decrease your overall simulation time when running in parallel. Using the parsim
function and the Multiple Simulations panel creates a parallel pool, which allows you to identify file
dependencies and manage build artifacts for simulations in accelerator and rapid accelerator mode.

29-2
Running Multiple Simulations

The batchsim function offloads the simulations to the compute cluster. The simulations are executed
on the cluster, which allows you to carry out other tasks while the batch job is processing. You can
also close the client MATLAB session and access the batch job later.

The batchsim function uses the Parallel Computing Toolbox™ license to run the simulations on
compute cluster. The batchsim function runs the simulations in serial if a parallel pool cannot be
created. Without the Parallel Computing Toolbox license, batchsim function gives an errors.

Multiple Simulations with the sim Function


In the absence of a Parallel Computing Toolbox license, the parsim function and the Multiple
Simulations panel behave like the sim command. The simulations run in serial.

Multiple Simulations with Simulink.SimulationInput Object


In command line workflows, you can make changes to your model using the
Simulink.SimulationInput object and run a simulation in parallel with those changes. Changing
the values in the Simulink.SimulationInput object, overrides the values in the model, which
allows you to modify the model without dirtying it. Through the Simulink.SimulationInput
object, you can also specify MATLAB functions to run at the start and the end of each simulation by
using the PreSimFcn and PostSimFcn functions, respectively. When you use
Simulink.SimulationInput objects, the model parameters are restored after the simulation ends.
See “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5. The
Simulink.SimulationInput object allows you to change these settings in your model:

• Initial state
• External inputs
• Model parameters
• Block parameters
• Variables

Simulation Manager to Monitor Simulations


The Simulation Manager allows you to monitor multiple parallel simulations. It shows the progress of
the runs as they are running in parallel. You can view the details of every run such as parameters,
elapsed time, and diagnostics. The Simulation Manager acts as a useful tool by giving you the option
to analyze and compare your results in the Simulation Data Inspector. You can also select a run and
apply its values to the model. For more information, see Simulation Manager.

The parsim/batchsim Function Capabilities


• Outputs errors in the simulation output object for easier debugging
• Compatible with rapid accelerator and fast restart
• Compatible with file logging (to facilitate big data)
• Compatible with MATLAB Parallel Server in addition to local parallel pools
• Capable of transferring base workspace variables to workers
• Avoids transparency errors

29-3
29 Multiple Simulations

Data Logging for Multiple Simulations


The resulting Simulink.SimulationOutput object, which contains the simulation outputs,
captures error messages and the simulation metadata. When you select the Data Import/Export >
Log Dataset data to file configuration parameter, Simulink creates a
Simulink.SimulationData.DatasetRef object for each Dataset stored in the resulting MAT
file. You can use the DatasetRef object to access the data for a Dataset element. For simulations
that are run using the Simulink.SimulationInput objects, the DatasetRef object is returned as
part of the SimulationOutput object. As a result, you have quicker access to and do not need to
create them.

Parallel simulations can produce more logged data than the MATLAB memory can hold. Consider
logging to persistent storage for parallel simulations to reduce the memory requirement. When you
select the Data Import/Export > Log Dataset data to file configuration parameter
(LoggingToFile), for parallel simulations in Simulink:

• Data is logged in Dataset format in a MAT-file


• A Simulink.SimulationData.DatasetRef object is created for each Dataset element (for
example, logsout) for each simulation

You can use DatasetRef objects to access data for a specific signal. You can create
matlab.io.datastore.SimulationDatastore objects to use for streaming logged data from
persistent storage in to a model.

See Also
Simulink.SimulationInput | applyToModel | setExternalInput | setInitialState |
setVariable | setModelParameter | setBlockParameter | validate | setPostSimFcn |
setPreSimFcn | parsim

More About
• “Run Parallel Simulations” on page 28-11
• “Multiple Simulations Panel: Simulate for Different Values of Stiffness for a Vehicle Dynamics
System” on page 29-26
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Comparison Between Multiple Simulation Workflows” on page 29-10
• “Work with Big Data for Simulations” on page 78-30

29-4
Run Parallel Simulations for a Thermal Model of a House Using parsim

Run Parallel Simulations for a Thermal Model of a House Using


parsim
This example shows how to use a Simulink.SimulationInput object to change block and model
parameters and run simulations in parallel with those changes.

The example model sldemo_househeat is a system that models the thermal characteristics of a
house, its outdoor environment, and a house heating system. This model calculates heating costs for a
generic house.

Set Point block, Thermostat subsystem, Heater subsystem, House subsystem, and Cost Calculator
component are the main components. For a detailed explanation of the model, see “Thermal Model of
a House”.

Run Multiple Parallel Simulations with Different Set Points


This model uses a Constant block to specify a temperature set point that must be maintained indoors.
The default value of set point value is 70 degrees Fahrenheit. This example shows you how to
simulate the model in parallel using different values of Set Point.

Open the example and the model


openExample('simulink_general/sldemo_househeatExample');
open_system('sldemo_househeat');

Define a set of values for Set Point.


SetPointValues = 65:2:85;
spv_length = length(SetPointValues);

29-5
29 Multiple Simulations

Using the defined values, initialize an array of Simulink.SimulationInput objects. Use these
Simulink.SimulationInput objects to specify the Set Point values. In this step, to preallocate
the array, the loop index is made to start from the largest value.

for i = spv_length:-1:1
in(i) = Simulink.SimulationInput('sldemo_househeat');
in(i) = in(i).setBlockParameter('sldemo_househeat/Set Point',...
'Value',num2str(SetPointValues(i)));
end

This example produces an array of 11 Simulink.SimulationInput objects, each corresponding to


a different value of Set Point.

Now, run these multiple simulations in parallel using the command parsim. To monitor and analyze
the runs, open the Simulation Manager by setting the ShowSimulationManager argument to on.
The ShowProgress argument when set to on shows the progress of the simulations.

out = parsim(in,'ShowSimulationManager','on','ShowProgress','on')

The output is generated as a Simulink.SimulationOutput object. To see all of the different set
point values, open the plot of the Temperatures (Indoor and Outdoor) and the Heat Cost component.
The constant block Avg Outdoor Temp specifies the average air temperature outdoors. The Daily
Temp Variation Sine Wave block generates daily temperature fluctuations of outdoor temperature.
The indoor temperature is derived from the House subsystem. The temperature outdoor varies
sinusoidally, whereas the temperature indoors is maintained within 5 degrees Fahrenheit of the set
point.

In the absence of the Parallel Computing Toolbox licenses, the parsim command behaves like the
sim command. The simulations run in serial.

View the Runs in the Simulation Manager


Setting the ShowSimulationManager argument to on enables the Simulation Manager. For more
information, see Simulation Manager.

You can view the status of all the runs and detailed information about them.

29-6
Run Parallel Simulations for a Thermal Model of a House Using parsim

The Simulation Manager enables you to view your results in the Simulation Data Inspector, which in
turn allows you to analyze and compare your data. You can view the plot of the Temperatures (Indoor
and Outdoor) and the Heat Cost in Simulation Data Inspector. Select the runs for which you want to

view the plot and click icon.

29-7
29 Multiple Simulations

You can now see the heat cost for three simulations.

Using the Simulation Manager, you can apply the parameters of any run to your model. Now, suppose

that you want to apply the parameters of Run 3 to your model. Select Run 3 and click the icon.
Your parameters are applied to the model.

See Also
Objects
Simulink.SimulationInput

Functions
applyToModel | setExternalInput | setInitialState | setVariable | setModelParameter
| setBlockParameter | validate | setPreSimFcn | setPostSimFcn | parsim

Tools
Simulation Manager

More About
• “Run Parallel Simulations” on page 28-11
• “Comparison Between Multiple Simulation Workflows” on page 29-10

29-8
Run Parallel Simulations for a Thermal Model of a House Using parsim

• “Running Multiple Simulations” on page 29-2

29-9
29 Multiple Simulations

Comparison Between Multiple Simulation Workflows


When running a set of multiple simulations, you can run them in parallel on multiple MATLAB
workers in a parallel pool. To run multiple simulations, you can use parsim, parsim with
'RunInBackground' option turned on, or batchsim.

The flow chart shows how running multiple simulations with parsim, parsim with
RunInBackground and batchsim differ.

The parsim and batchsim commands use the Parallel Computing Toolbox license to run the
simulations in parallel. parsim runs the simulations in serial if a parallel pool cannot be created or if
the Parallel Computing Toolbox license is not available. batchsim commands cannot run without
Parallel Computing Toolbox license.

29-10
Comparison Between Multiple Simulation Workflows

parsim Workflow
Using parsim command with Parallel Computing Toolbox to run multiple simulations sets up a
parallel pool automatically and runs simulations in parallel. The client is always tied to the MATLAB
workers.

Basic parsim Workflow

1 Create an array of Simulink.SimulationInput objects, in, to specify changes to the model.


2 Specify one-time setup required for running multiple simulations. You can use SetupFcn and
TransferBaseWorkspaceVariables to perform setup on the parallel workers.
3 Run parsim(in) to execute these multiple simulations in parallel. If a parallel pool does not
exist, parsim creates it. parsim uses default settings.
4 You can open Simulation Manager by setting the 'SimulationManager' argument to 'on'
with parsim, parsim(in,'SimulationManager','on'). Simulation Manager enables you to
monitor the simulations as they are running and gives you access to outputs of the simulations
when they are ready. Simulation Manager provides you with information about the simulations
running on the workers. For more information, see Simulation Manager.
5 Once all the simulations are complete, you get an array of Simulink.SimulationOutput
objects.

Limitations

• Closing the MATLAB session terminates simulations on the workers, disabling retrieval of partial
results.

parsim with RunInBackground Workflow

1 Create an array of Simulink.SimulationInput objects, in, to specify changes to the model.


2 Specify one-time setup required for running multiple simulations. You can use SetupFcn and
TransferBaseWorkspaceVariables to perform setup on the parallel workers.

29-11
29 Multiple Simulations

3 Run parsim with RunInBackground option set to 'on':


parsim(in,'RunInBackground','on'). Setting the 'RunInBackground' option to 'on'
runs the simulations asynchronously. This keeps the MATLAB command prompt available
enabling you to work on other tasks.
4 With 'RunInBackground' option set to 'on', parsim returns a
Simulink.Simulation.Future object. You can poll this object to check the status of
simulations, fetch the outputs of simulations when they are completed, or cancel simulations. For
more information, see Simulink.Simulation.Future.

Limitations

• Closing the MATLAB session terminates simulations on the workers, disabling retrieval of partial
results. If the future object is cleaned, you are subsequently unable to access the results of the
simulations.
• Using a fetchNext method loop on Future objects, along with Simulation Manager causes them
to compete for retrieval of Future objects. Use either a fetchNext method loop or Simulation
Manager to get the outputs of completed simulations.

batchsim Workflow
A batch workflow typically means submitting jobs to run simulations on MATLAB workers and
subsequently accessing the results of those simulations. When you run simulations in batches, you
offload the execution of simulations onto a compute cluster. To learn more about batch processing,
see “Simple Batch Processing” (Parallel Computing Toolbox).

1 Create an array of Simulink.SimulationInput objects, in, to specify changes to the model.


2 Specify one-time setup required for running multiple simulations. You can use SetupFcn and
TransferBaseWorkspaceVariables to perform setup on the parallel workers.
3 To run on a cluster or desktop background, call batchsim to offload the execution of simulations.
With batchsim, you can use most of the arguments that are compatible with parsim and batch
commands. For more information, see batchsim.

29-12
Comparison Between Multiple Simulation Workflows

Using batchsim, you offload simulations to a MATLAB worker. To run the batch job on multiple
workers, specify a pool size, N, that is an integer specifying the number of workers to make into a
parallel pool for the job: batchsim(in, 'Pool', N). There must be at least N+1 workers
available on the cluster. If the pool size is not specified, batchsim(in) runs the simulations on a
single worker in the cluster specified by the default cluster profile.

Note batchsim errors out when used with a pool size if Parallel Computing Toolbox license is
not available.
4 batchsim offloads simulations to the compute cluster, enabling you to carry out other tasks
while the batch job is processing, or close the client MATLAB and access the batch job later.
5 On submitting a batch job, batchsim returns a job object containing a job ID and other
information that you can use to access the batch job at a later time. Access this job again to
check the progress of simulations.

Limitations

• Because the client session is not tied to the workers, you cannot access the outputs unless the job
is finished.
• batchsim does not give you the ability to monitor simulations with Simulation Manager. For
batch jobs, you can use a batch job monitor that tells you if the job is queued, in progress, or
completed. For more information, see “Job Monitor” (Parallel Computing Toolbox)

See Also
Functions
parsim | batchsim | batch | parcluster | getSimulationJobs

Classes
Simulink.SimulationInput | Simulink.Simulation.Job | Simulink.Simulation.Future

Tools
Simulation Manager

See Also

More About
• “Running Multiple Simulations” on page 29-2
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Run Parallel Simulations” on page 28-11
• “Analyze Results Using Simulation Manager” on page 29-14
• “Batch Processing” (Parallel Computing Toolbox)

29-13
29 Multiple Simulations

Analyze Results Using Simulation Manager


The Simulation Manager allows you to monitor multiple simulations, in serial or in parallel, and their
progress. You can view the details of every run, such as parameters, elapsed time, and diagnostics.
The Simulation Manager provides the option to analyze and compare your logged signal results in the
Simulation Data Inspector. Through Simulation Manager, you can select a run and apply its values
to the model. Simulation Manager opens when you run a parsim or a sim command with
ShowSimulationManager argument set to on. For more information, see Simulation Manager.

The dimensions of the tank have an impact on the total cost of production of the product. For this
example, we observe the behavior of TotalCost for different values of the width and the height. By
analyzing the behavior of the parameters, we find the combination of A and h that results in lowest
TotalCost. To solve this design problem, we run multiple simulations (in parallel or in serial) with
different values of the parameters A and h.

This example shows how you can use the Simulation Manager to analyze the simulations and solve a
design problem using a model of a continually stirred tank reactor. The reactors are specialized tanks
that are used to mix various chemicals or compounds to create a product. The important variables
used in this model are:

• Variable A, which represents the cross-sectional area of the tank (width).


• Variable h, which represents the height.
• Variable TotalCost, which represents the cost, in dollars, to produce a tankful of product.

Simulation Manager enables you to analyze the simulations as they are running. When the
simulations are in progress, you can visualize the simulation data of the model by plotting the
simulation outputs against the input parameters. Visualizing trend of the simulations as they are
happening allows you to learn about the design space of the simulations and evaluate whether the
simulations are running as required. You can stop the simulations if the progress is not as desired
thus saving time.

Open Simulation Manager


In this example, use a set of sweep parameters provided to the model through
Simulink.SimulationInput objects and then use the parsim command to run the simulations in
parallel.

Open the model.

openExample('simulink/OpenTheModelToUseWithSimulationManagerExample');
open_system('simManagerCSTR');

Create a PostSimFcn function as follows in a MATLAB script to call later in the parameter sweep.
Name the file calculateCost.m. The PostSimFcn function calculates TotalCost from the
variables A and h, and its calculation can vary depending on the application.
function costOutput = calculateCost(out)

costOutput.yout = out.yout;

coolantOutput = out.yout.get('Coolant').Values.Data;
costCoolant = abs(mean(coolantOutput - 294))/30;
costOutput.costFromCoolant = costCoolant;

concentrationOutput = out.yout.get('Residual Concentration').Values.Data;


costConcentration = 10*std(concentrationOutput - 2);

29-14
Analyze Results Using Simulation Manager

costOutput.costFromConcentration = costConcentration;

costOutput.TotalCost = costCoolant + costConcentration;

end

Create a sample of values for parameter sweep.

rangeA = [0.1, 5];


rangeH = [0.1, 5];

rng default;

numSamples = 60;
allAValues = rangeA(1) + (rangeA(2) - rangeA(1)).*rand(numSamples, 1);
allhValues = rangeH(1) + (rangeH(2) - rangeH(1)).*rand(numSamples, 1);

Create an array of Simulink.SimulationInput objects. For this example, the TotalCost is


calculated and returned using the PostSimFcn.

in(1:numSamples) = Simulink.SimulationInput('simManagerCSTR');
in = in.setPostSimFcn(@(out)calculateCost(out));

Run the simulations in parallel and open the Simulation Manager.

for k = 1:numSamples
in(k) = in(k).setVariable('A', allAValues(k), 'Workspace', 'simManagerCSTR');
in(k) = in(k).setVariable('h', allhValues(k), 'Workspace', 'simManagerCSTR');
end

out = parsim(in, 'ShowSimulationManager', 'on');

The default view in the Simulation Manager shows a scatter plot with two parameters on its X and Y
axes. In this case, the variable A is on the X-axis and variable h is on the Y-axis. When the simulations
are running you can see dots appear on the plot, color coded according to the simulation status.
Completed simulations are marked in green, in-progress simulations are blue, and simulations with
errors are red.

The Plot Properties panel on the right enables you to edit and configure the data that plot shows. By
selecting grid for X and Y axes, the plot appears with grid lines.

If a particular parameter is a time-series, the Simulation Manager plots only the last value of the time
series.

29-15
29 Multiple Simulations

With the Simulation Manager, you can visualize the above data in a surf plot. Click the surf plot in
the Results section of the toolstrip.

Add and Configure Plots


The Results section of the Simulation Manager allows you to add multiple plots and configure them.
To add a plot, click the type of the plot in the Results section. For this example, click the surf plot in
Results section of the Simulation Manager toolstrip. Using the plot properties, change the
parameters to display on the plots. You can change properties such as the plot labels, axes labels and
you can add a colormap to denote the third parameter. You can also change the value limits of the
colormap.

With the second plot and the first plot together, you can determine the value of the variables A and h,
that gives the best TotalCost.

For the Z-axis of the surf plot, change the Data to TotalCost. By observing the surf plot, you can
find the lowest point of TotalCost. Clicking the lowest point shows the values for X-axis and Y-axis,
which is h and A, respectively.

29-16
Analyze Results Using Simulation Manager

Save and Load Simulation Manager


Save the session information, which includes simulation data all the plot configurations. To save the
session, click the Save button on the toolstrip. The session saves as a .mldatx file. To reopen the
saved session, navigate to the location where the file is saved and double-click the .mldatx file.

The Simulation Manager allows you to reuse the plot configuration when you want to run similar
simulations with different sets of values. To reuse the plot configuration, click the Reuse Window
button on the toolstrip. Selecting the Reuse Window saves the plot configurations, such as labels,
axis orientation, which parameters to display on which axis that you can reuse with the next
simulation of the same model. When you use this functionality while running simulations for different
models, the simulation errors out due to a limitation.

See Also
Simulink.SimulationInput | applyToModel | setExternalInput | setInitialState |
setVariable | setModelParameter | setBlockParameter | validate | setPostSimFcn |
setPreSimFcn | parsim

29-17
29 Multiple Simulations

More About
• “Run Parallel Simulations” on page 28-11
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Comparison Between Multiple Simulation Workflows” on page 29-10
• “Work with Big Data for Simulations” on page 78-30

29-18
Configure and Run Simulations with Multiple Simulations Panel

Configure and Run Simulations with Multiple Simulations Panel


The Multiple Simulations panel allows you to set up multiple simulations for a block parameter that
you want to vary, for example, for a parameter sweep or Monte-Carlo simulations. You can pick a
block parameter of interest from the model canvas and specify values that you want to use for the
simulations. With the Multiple Simulations panel, you can provide configurations such as Use
Parallel to run your simulations in parallel. To run the simulations that you have set up, first, select
the design study, then click Run All button on Simulation tab on the Simulink toolstrip. Once the
simulations are complete, you can view and manage the results in Simulation Manager.

To learn how to use the Multiple Simulations panel through an example, see “Multiple Simulations
Panel: Simulate for Different Values of Stiffness for a Vehicle Dynamics System” on page 29-26.

Workflow for Multiple Simulations Panel


Open the model and access the supporting files by using the following command:

openExample('simulink/RunMultipleSimulationsThroughSimulinkExample')

To configure and run multiple simulations from the Simulink Editor:

1 First, check that you have made all the desired changes to your model.
2 The Multiple Simulations panel allows you to perform similar operations as the parsim
command line API, but through the Simulink Editor. To open the Multiple Simulations panel,
navigate to the Prepare section on the Simulink toolstrip. In the Inputs & Parameter Tuning

section, click Multiple Simulations .


3 The Multiple Simulations panel appears docked on the right side of the Simulink canvas.

29-19
29 Multiple Simulations

4 In the panel, click the right most button to create a new design study. A design study is an object
that allows you to set up simulations. The name of the new design study is automatically
populated as DesignStudy. To change the name, double-click on the name and enter your
preferred name. Once you configure and enter the values for the simulations, select the design
study and click Run All on the Simulink toolstrip to run the simulations.

29-20
Configure and Run Simulations with Multiple Simulations Panel

5
Now, you can add a block parameter to the created design study. Click to add a new block
parameter to the design study. You can enter the block path or use a picker to select a block from
the model canvas, or you can enter the block parameter name. Once you have added the block
parameter, specify its values. If the block is a Signal Editor block, you can choose your
specification from the list of scenarios. By default, all scenarios will be selected.

You can also add variables for your simulations by clicking .

Parameter Combinations

For the block parameters or variables that you add, you can use parameter combinations.
Parameter combinations allow you to specify either an exhaustive combination or a sequential
combination of the parameters. By default, all parameters at the top level are combined
exhaustively.

To create an exhaustive combination, select the specified block parameters. Then, from the

parameter combinations drop down list , select Exhaustive combination. An exhaustive


combination is denoted by . An exhaustive combination creates all possible combinations from
the parameter values. For example, if there are ten values of one parameter and five values of
another, an exhaustive combination creates a total of 10x5=50 different combinations.

29-21
29 Multiple Simulations

To create a sequential combination, select the specified block parameters. Then, from the

parameter combinations drop-down list , select Sequential combination. For example, if


you have two properties that each specify ten different values, sequential combination creates
total of ten different simulations, one for each set of values. A sequential combination is denoted

by . A sequential combination combines values sequentially. The number of values specified


for each parameter must be the same. You can choose the sequence in which parameters are
combined.

You can also nest parameter combinations. Based on the parameter combination specification,
the Multiple Simulations panel shows the number of simulations that correspond to the design
study.

29-22
Configure and Run Simulations with Multiple Simulations Panel

6 In the Details: Design Study section, on the Run Options tab, you can also specify the option
to run in parallel.

7 Now that you have entered specifications, select the scenarios and the design study that you
want to run. Once you select the design study, the Run button on the Simulink toolstrip changes
to Run All. Click Run All to run the simulations.

29-23
29 Multiple Simulations

8 Once the simulations complete, you can view and manage the results in the Simulation Manager .
To open the Simulation Manager, click Open Simulation Manager on the status bar at the
bottom of the canvas.
9 Click the save button in the Multiple Simulations panel to save the design study. The design
study is saved in .mldatx format. To reuse the design study, open the Multiple Simulations
panel, click the open button, and select the design study file from the file browser.

You can also save the Simulation Manager session information, which includes simulation data
for all the plot configurations. To save the Simulation Manager session, use the save button on
the Simulation Manager toolstrip.

Video Walkthrough
The following video walks through the overview of the Multiple Simulations panel.

29-24
Configure and Run Simulations with Multiple Simulations Panel

See Also
Simulink.SimulationInput | parsim

More About
• “Run Parallel Simulations” on page 28-11
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Comparison Between Multiple Simulation Workflows” on page 29-10
• “Work with Big Data for Simulations” on page 78-30

29-25
29 Multiple Simulations

Multiple Simulations Panel: Simulate for Different Values of


Stiffness for a Vehicle Dynamics System

This example shows how to use the Multiple Simulations panel in the Simulink® Editor to run
multiple simulations with varying values of stiffness of the suspension for a road profile that has a
sinusoidal shape.

Open the Model

The model simulates the vehicle dynamics based on the road-suspension interaction for different road
profiles. The road profile data for the left and right tires is imported into the Signal Editor block as a
sinusoidal shape. The Road-Suspension Interaction subsystem calculates the suspension forces on the
vehicle at the four tire locations based on the road data and the current vehicle state. In the Body
Dynamics subsystem, these forces and the resulting pitch and roll movements are used to determine
the vehicle motion in three degrees of freedom: vertical displacement, roll, and pitch. The model is
simulated using different values of stiffness of the suspension to determine if the design meets
desired performance goals.

open_system('ex_multisim_sldemo_suspn_3dof');

Set Up Simulations

To configure and set up simulations, use the Multiple Simulations panel. To open the Multiple
Simulations panel, go to the Prepare section on the Simulink toolstrip. In the Inputs & Parameter

Tuning section, click Multiple Simulations. In the panel, click to create a new design study.

The yellow button, , creates a new session of the Multiple Simulations panel

29-26
Multiple Simulations Panel: Simulate for Different Values of Stiffness for a Vehicle Dynamics System

A new design study object is added to the panel. The name of this design study is automatically
populated. Double-click the design study to change the name. Use this design study to specify the
parameters for the simulations. In this design study, we set up the values for the variable K which
represents stiffness. By running multiple simulations, we want to see how the amplitude at which the
car oscillates is affected by different values of stiffness.

To add variable to this design study, click on the Specification tab of the Details:Design Study
section. Once you add the variable, double-click to label the variable as Suspension stiffness.
Specify the variable name as K, which is the stiffness of the suspension. Run simulations for multiple
values of the stiffness, K. Simulate for values ranging from 2e4 to 8e4, with one hundred separate
points. Add linspace(2e4,8e4,100) as the values of the variable K.

29-27
29 Multiple Simulations

Run Multiple Simulations

Now that you have set up the values for our simulations, select the design study. The Run button in

the Simulation section of the Simulink toolstrip changes to Run All, to indicate that you
have setup multiple simulations. Click the Run All button to start the simulations. You can open
Simulation Manager by clicking Open Simulation Manager on the Simulink status bar at the
bottom of the canvas.

View the Results in Simulation Manager

Inspect how the amplitude at which the car oscillates is affected by different values of stiffness. To
see the plot, in Plot Properties, select yout from the list for Data for the Y-Axis. yout represents the
resulting amplitude of oscillations. The road pattern for this simulation is a sine wave with fixed
frequency. By varying the stiffness values, you vary the natural frequency of the system. Based on the
stiffness values, you start below the natural frequency. As you increase the values of the stiffness, you
cross the natural frequency, thus entering resonance. As you increase the stiffness values above the
natural frequency, the amplitude starts to decrease again.

29-28
Multiple Simulations Panel: Simulate for Different Values of Stiffness for a Vehicle Dynamics System

By configuring and specifying values through the Multiple Simulations panel, you can easily run many
simulations with different values for parameter sweep and Monte-Carlo simulations directly through
the Simulink Editor.

Save the Design Study and the Plot

Click in the Multiple Simulations panel to save the design study that you have set up. The
design study is saved in mldatx format. To reuse the design study, open the Multiple Simulations

panel, click , and select the design study file from the file browser.

You can also save the Simulation Manager session information, which includes simulation data all the
plot configurations. The Simulation Manager allows you to reuse the plot configuration when you

want to run similar simulations with different sets of values. To reuse the plot configuration, click

29-29
29 Multiple Simulations

on the Simulation Manager toolstrip. To reopen the saved session, navigate to the location where the
file is saved and double-click the .mldatx file.

See Also
Simulink.SimulationInput | parsim | Multiple Simulations

More About
• “Run Parallel Simulations” on page 28-11
• “Run Parallel Simulations for a Thermal Model of a House Using parsim” on page 29-5
• “Comparison Between Multiple Simulation Workflows” on page 29-10
• “Configure and Run Simulations with Multiple Simulations Panel” on page 29-19
• “Work with Big Data for Simulations” on page 78-30

29-30
Control a Simulink Simulation with App Designer

Control a Simulink Simulation with App Designer

This example shows how to create an interface to control a simulation for a Simulink model. The app
demonstrates connecting UI components to model elements by creating bindings and by writing
callbacks to set model parameters.

Open the Model

This example uses a model of a mass-spring-damper. The Simulink model uses signal connections,
which define how data flows from one block to another.

open_system('ex_mass_spring_damper_appdemo')

Open and Examine the App

Open the controlSimulations.mlapp in App Designer. The app provides a user interface to
interact with the ex_mass_spring_damper_appdemo model. You can run the model, view the
elapsed time, change the model stop time, and tune a model variable from within the app.The app
contains some Simulink UI components, and some common App Designer components. You can
connect some of these components with certain variables and signals in the model. Connecting the
signals and variables in the model with the UI components allows you to visualize the signal, as well
as control the values for the simulation from your app.

open('controlSimulations.mlapp')

29-31
29 Multiple Simulations

The controlSimulations app contains the following UI components:

• Simulation Controls (Simulink section) - start, pause, and stop the simulation of the model.
• Simulation Progress (Simulink section) - monitor the progress of the simulation, as well as
simulation time, and elapsed time.
• Time Scope (Simulink section) - display time domain signals in the app. You can connect this UI
component with a logged signal in the Simulink model.
• Stop Time Edit Field (Common section) - specify simulation stop time.
• Slider (Common section) - specify a value for a tunable variable that it is connected with. You can
also specify the range of values.
• Image (Common section) - display a model image

Control Simulations Using UI Components

This example connects UI components in the app to elements of the model using these techniques:

• Connecting the time scope to the Integrator signal by creating a binding.


• Connecting the slider to the Stiffness variable by creating a binding.
• Connecting the edit field to the simulation stop time by creating a callback that updates the
StopTime model parameter of the Simulation object associated with the app.

29-32
Control a Simulink Simulation with App Designer

To learn how to bind UI components to elements, see “Connect UI Components to Simulink Model
Elements” on page 39-8.

The Stop Time Edit Field is not a Simulink UI component. It is a standard UI component that is
configured programmatically to set the StopTime model parameter. You can programmatically
configure the simulation object by using the Simulation app property. The StopTime edit field is
attached to the model parameter StopTime using a callback function. Click on the StopTime edit
field in App Designer. To see the callbacks for the StopTime component, click
StopTimeEditFieldValueChangedFcn. To examine this function, click the StopTime field and go
to Code View. In the Code View, you can see the callback function
StopTimeEditFieldValueChangedFcn.

function StopTimeEditFieldValueChanged(app, event)


value = app.StopTimeEditField.Value;
app.Simulation.setModelParameter('StopTime', num2str(value));
end

Run the App

Once your app is modified as per your needs, and the binding of the UI components and the model
elements is complete, you can run the app. Click Run on the toolstrip. Now, the app is ready to be
used.

29-33
29 Multiple Simulations

Click Run on the app. You can see the signal, Integrator for the selected value of Stiffness. Now
you can easily change the value of the variable Stiffness, and run the simulation again to observe
how the signal Integrator changes with different values of Stiffness.

29-34
Load and Save External Inputs for a Simulink Model with App Designer

Load and Save External Inputs for a Simulink Model with App
Designer

This example shows an app that provides a user interface to load inputs for simulating a model, and
then save the simulation output.

Open the Model

The example uses a model of a thermal system of a house.

open_system("ex_sldemo_househeat.slx");

Open and Examine the App

Open the tuneVariablesAndSaveOutputs.mlapp file to open the app in App Design. The app
allows you to load inputs for simulating the model.

open('tuneVariablesAndSaveOutputs.mlapp');

The app tuneVariablesAndSaveOutputs is associated with the ex_sldemo_househeat model.


To verify this association, go to the

Simulink tab on the toolstrip, in the Model section, verify the model name in the text field. You can
also open the model from App Designer by clicking Open Model.

The app tuneVariablesAndSaveOutputs provides a user interface to interact with the


ex_sldemo_househeat model. The app contains the following components:

• Simulation Controls - start, pause, and stop the simulation of the model.
• Load Input Button - browse and load a mat file with simulation inputs.
• Save Output Button - save the simulation outputs into a mat file.
• Variable Tuner - tune and list all the tunable variables in the model.
• Model Image - display model image.

29-35
29 Multiple Simulations

The Simulink UI components Load Input button, Save Output button, Simulation Controls, and
Variable Tuner are all added to the app by dragging and dropping the components from the
Simulink section of the Component Library. Simulink UI components automatically connect to the
Simulink model associated with the app.

Use the App to Run Simulations

To start using the app, click the Run button from the toolstrip.

29-36
Load and Save External Inputs for a Simulink Model with App Designer

Load Inputs

Once you have the app running, you can load different set of external inputs for the simulation. Click
Load Input button and select the daily_temp_variation.mat file to load the variables for the
simulation. You can see the file name under the Load Input button.

Interact with Tunable Variables

Click Run to start the simulation.

Save Simulation Output

Once the simulation is complete, click Save Output to save simulation outputs to a MAT file.

29-37
30

Visualizing and Comparing Simulation


Results

• “Prototype and Debug Models with Scopes” on page 30-2


• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Scope Trace Selection Panel” on page 30-11
• “Scope Triggers Panel” on page 30-12
• “Cursor Measurements Panel” on page 30-23
• “Scope Signal Statistics Panel” on page 30-25
• “Scope Bilevel Measurements Panel” on page 30-27
• “Peak Finder Measurements Panel” on page 30-36
• “Spectrum Analyzer Cursor Measurements Panel” on page 30-39
• “Spectrum Analyzer Channel Measurements Panel” on page 30-41
• “Spectrum Analyzer Distortion Measurements Panel” on page 30-43
• “Spectral Masks” on page 30-47
• “Spectrum Analyzer CCDF Measurements Panel” on page 30-49
• “Common Scope Block Tasks” on page 30-51
• “View Values of Parameters Set as Variables” on page 30-70
• “Floating Scope and Scope Viewer Tasks” on page 30-73
• “Generate Signals Without Source Blocks” on page 30-81
• “Viewers and Generators Manager” on page 30-83
• “Control Scope Blocks Programmatically” on page 30-86
• “Plot a Circle Using the XY Graph Block” on page 30-88
• “Sample Time with Scope Blocks” on page 30-92
30 Visualizing and Comparing Simulation Results

Prototype and Debug Models with Scopes


Simulink scope blocks and viewers offer a quick and lightweight way to visualize your simulation data
over time. If you are prototyping a model design, you can attach signals to a Scope block. After
simulating the model, you can use the results to validate your design. See “Scope Blocks and Scope
Viewer Overview” on page 30-6 and “Model and Validate a System”.

A Scope block or Scope viewer opens to a Scope window where you can display and evaluate
simulation data.

The toolbar contains controls for starting, stopping, and stepping forward through a simulation

. You can use these controls to debug a model by viewing signal data at each time
interval. See “How Stepping Through Simulation Works” on page 2-7.

Connect signal lines to a Scope block using multiple input ports, see “Number of input ports”.

30-2
Prototype and Debug Models with Scopes

Attach signals to a Floating Scope block or signal viewer directly from the model. See “Add Signals to
an Existing Floating Scope or Scope Viewer” on page 30-74.

Use the oscilloscope-like tools available with a scope to debug your model. Set triggers to capture
events, use interactive cursors to measure signal values at various points, and review signal statistics
such as maximum and mean values. See “Scope Triggers Panel” on page 30-12 and “Cursor
Measurements Panel” on page 30-23.

30-3
30 Visualizing and Comparing Simulation Results

Save or log signal data to the MATLAB workspace, and then plot data in a MATLAB figure widow. Use
MATLAB functions or your own scripts to analyze the data. See “Save Simulation Data from Floating
Scope” on page 30-75.

30-4
Prototype and Debug Models with Scopes

See Also
Floating Scope | Scope | Scope Viewer

Related Examples
• “Common Scope Block Tasks” on page 30-51
• “Floating Scope and Scope Viewer Tasks” on page 30-73
• “Scope Triggers Panel” on page 30-12
• “Cursor Measurements Panel” on page 30-23
• “Control Scope Blocks Programmatically” on page 30-86
• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Viewers and Generators Manager” on page 30-83

30-5
30 Visualizing and Comparing Simulation Results

Scope Blocks and Scope Viewer Overview


In this section...
“Overview of Methods” on page 30-6
“Simulink Scope Versus Floating Scope” on page 30-6
“Simulink Scope Versus DSP System Toolbox Time Scope” on page 30-8

Overview of Methods
Simulink scopes provide several methods for displaying simulation data and capturing the data for
later analysis. Symbols on your block diagram represent the various data display and data capture
methods.

For more information about these methods:

• Scope and Floating Scope blocks — Scope, Floating Scope, “Common Scope Block Tasks” on page
30-51, “Floating Scope and Scope Viewer Tasks” on page 30-73.
• Scope Viewer — “Viewers and Generators Manager” on page 30-83, “Floating Scope and Scope
Viewer Tasks” on page 30-73.
• Signal Logging — “Save Simulation Data from Floating Scope” on page 30-75.
• Signal Test Point — “Configure Signals as Test Points” on page 81-50.

Simulink Scope Versus Floating Scope


Scope blocks and Floating Scope blocks both display simulation results, but they differ in how you
attach signals and save data. Simulation behavior for a Floating Scope and a Scope Viewer is
identical, but you manage them differently in your model.

30-6
Scope Blocks and Scope Viewer Overview

Capability Simulink Scope Simulink Floating Simulink Scope


Scope Viewer
Attaching signals Connect signal lines to a Attach signals Attach signals from the
Scope block using input interactively from the Viewers and Generators
ports. model before and Manager, interactively
during a simulation. See from the toolstrip, or
“Add Signals to an using the signal line
Existing Floating Scope context menu.
or Scope Viewer” on
page 30-74 and
“Quickly Switch
Visualization of
Different Signals on a
Floating Scope” on page
30-79.
Access to signals Because signals lines Because signals are Scope viewers are
are connected to a attached without signal attached to signal lines.
Scope block, access lines, you do not have to
signals at different route lines to a FloatingYou can access most
levels of a model Scope block. signals inside the model
hierarchy using GoTo hierarchy, including
blocks. You can access most referenced models and
signals inside the model Stateflow charts. You
hierarchy, including cannot access optimized
referenced models and signals.
Stateflow charts. You
cannot access optimized
signals.
Data logging Save data to a MATLAB Save data to a MATLAB Save data to a MATLAB
variable as an array, variable as an object. variable as an object.
structure, or object.
Simulation control Run, forward, and back Run, forward, and back Run, forward, and back
toolbar buttons. toolbar buttons. toolbar buttons.
Scale axes after Toolbar buttons to scale Toolbar buttons to scale Toolbar buttons to scale
simulation X-axis and Y-axis limits X-axis and Y-axis limits. X-axis and Y-axis limits.

Axes scaling set to Axes scaling set to Axes scaling set to


Auto for the X-axis and Auto for only the Y-axis. Auto for the X-axis and
Y-axis. Y-axis.
Add to model Add block from Add block from Add using “Viewers and
Simulink sinks library. Simulink sinks library. Generators Manager”
on page 30-83.
Visual indication in Scope block connected Floating Scope block Viewer icons located
model to signals. not attached to any above signal lines for all
signal lines. attached signals.

30-7
30 Visualizing and Comparing Simulation Results

Capability Simulink Scope Simulink Floating Simulink Scope


Scope Viewer
Manage scopes No. No. Use the Viewers and
centrally Generators Manager to
add or delete viewers,
and attach or remove
signals.
Manage scopes Attach signal lines to Attach signals from the Add viewers and attach
locally Scope block in ports. Floating Scope window. additional signals within
a model hierarchy using
the context menus or
from the Scope viewer
window.
Simulink Report Yes. Yes. No.
Generator support
Connecting Constant Plots the data value at Plots all data values. Plots the data value at
block with Sample the first time step and the first time step and
time set to inf anytime you tune a anytime you tune a
(constant sample parameter. parameter.
time)

Simulink Scope Versus DSP System Toolbox Time Scope


If you have a Simulink and a DSP System Toolbox license, you can use either the Simulink Scope or
DSP System Toolbox Time Scope. Choose the scope based on your application requirements, how the
blocks work, and the default values of each block.

If you have a DSP System Toolbox license and you have been using Time Scopes, continue to do so in
your applications. Using the Time Scope block requires a DSP System Toolbox license.

Feature Scope Time Scope


Location in block library Simulink Sinks library DSP System Toolbox Sinks
library
Trigger and measurement With Simulink only: • Trigger
panels • Cursor Measurements
• Trigger
• Signal Statistics
• Cursor Measurement
• Bilevel Measurements
With DSP System Toolbox or • Peak Finder
Simscape license:

• Signal Statistics
• Bilevel Measurements
• Peak Finder

30-8
Scope Blocks and Scope Viewer Overview

Feature Scope Time Scope


Simulation mode support for • Normal • Rapid-Accelerator
block-based sample times • Accelerator • External
For block-based sample times, • Rapid-Accelerator
all the inputs of the block run at • External
the same rate.

For rapid-accelerator mode, see


“Behavior of Scopes and
Viewers with Rapid Accelerator
Mode” on page 38-16.
Simulation mode support for No. • Normal
port-based sample times • Accelerator
For port-based sample times,
the input ports can run at
different rates.
Frame processing of signals Included in Scope block with Included in Time Scope block.
DSP System Toolbox license.
Sample time propagation If the different ports have When using port-based sample
different sample rates, the times, the different ports of the
scope uses the greatest common Scope block inherit the different
divisor of the rates. rates and plots the signals
according to those rates.
Save model to previous Simulink If saving to a release before No change in features.
release R2015a, the Scope block is
converted to a scope with the
features available in that
release.

This table lists the differences in Configuration Property default values between the Scope and Time
Scope blocks.

Property Scope Default Time Scope Default


Open at start of simulation Cleared Selected
Input processing Elements as channels (sample Columns as channels (frame
based) based)
Maximize Axes Off Auto
Time Units None Metric (based on Time Span)
Time-axis labels Bottom displays only All
Show time-axis label Cleared Selected
Plot Type Auto Line
Title %<Signal Label> No title
Y label No label Amplitude

30-9
30 Visualizing and Comparing Simulation Results

See Also
Floating Scope | Scope | Scope Viewer | Time Scope

Related Examples
• “Common Scope Block Tasks” on page 30-51
• “Display Time-Domain Data” (DSP System Toolbox)
• “Configure Time Scope Block” (DSP System Toolbox)
• “Floating Scope and Scope Viewer Tasks” on page 30-73

30-10
Scope Trace Selection Panel

Scope Trace Selection Panel

When you use the scope to view multiple signals, the Trace Selection panel appears. Use this panel to
select which signal to measure. To open the Trace Selection panel:

• From the menu, select Tools > Measurements > Trace Selection.
• Open a measurement panel.

See Also
Scope | Floating Scope

Related Examples
• “Scope Triggers Panel” on page 30-12

30-11
30 Visualizing and Comparing Simulation Results

Scope Triggers Panel

In this section...
“What Is the Trigger Panel” on page 30-12
“Main Pane” on page 30-12
“Source/Type and Levels/Timing Panes” on page 30-13
“Hysteresis of Trigger Signals” on page 30-21
“Delay/Holdoff Pane” on page 30-22

What Is the Trigger Panel


The Trigger panel defines a trigger event to synchronize simulation time with input signals. You can
use trigger events to stabilize periodic signals such as a sine wave or capture non-periodic signals
such as a pulse that occurs intermittently.

To open the Trigger panel:

1 Open a Scope block window.


2
On the toolbar, click the Triggers button .
3 Run a simulation.

Triangle trigger pointers indicate the trigger time and trigger level of an event. The marker color
corresponds to the color of the source signal.

Main Pane
Mode — Specify when the display updates.

• Auto — Display data from the last trigger event. If no event occurs after one time span, display
the last available data.

30-12
Scope Triggers Panel

Normal — Display data from the last trigger event. If no event occurs, the display remains blank.
• Once — Display data from the last trigger event and freeze the display. If no event occurs, the
display remains blank. Click the Rearm button to look for the next trigger event.
• Off — Disable triggering.

Position (%) — Specify the position of the time pointer along the y-axis. You can also drag the time
pointer to the left or right to adjust its position.

Source/Type and Levels/Timing Panes


Source — Select a trigger signal. For magnitude and phase plots, select either the magnitude or the
phase.

Type — Select the type of trigger.

30-13
30 Visualizing and Comparing Simulation Results

Trigger Type Trigger Parameters


Edge — Trigger when the Polarity — Select the polarity for an edge-triggered signal.
signal crosses a threshold.
• Rising — Trigger when the signal is increasing.

• Falling — Trigger when the signal value is decreasing.

• Either — Trigger when the signal is increasing or decreasing.

Level — Enter a threshold value for an edge triggered signal. Auto level
is 50%

30-14
Scope Triggers Panel

Trigger Type Trigger Parameters


Hysteresis — Enter a value for an edge-triggered signal. See
“Hysteresis of Trigger Signals” on page 30-21
Pulse Width — Trigger Polarity — Select the polarity for a pulse width-triggered signal.
when the signal crosses a
low threshold and a high • Positive — Trigger on a positive-polarity pulse when the pulse
threshold twice within a crosses the low threshold for a second time.
specified time.

• Negative — Trigger on a negative-polarity pulse when the pulse


crosses the high threshold for a second time.
• Either — Trigger on both positive-polarity and negative-polarity
pulses.

Note A glitch-trigger is a special type of a pulse width-trigger. A glitch-


Trigger occurs for a pulse or spike whose duration is less than a
specified amount. You can implement a glitch trigger by using a pulse
width-trigger and setting the Max Width parameter to a small value.

High — Enter a high value for a pulse width-triggered signal. Auto level
is 90%.

Low — Enter a low value for a pulse width-triggered signal. Auto level
is 10%.

Min Width — Enter the minimum pulse-width for a pulse width


triggered signal. Pulse width is measured between the first and second
crossings of the middle threshold.

Max Width — Enter the maximum pulse width for a pulse width
triggered signal.

30-15
30 Visualizing and Comparing Simulation Results

Trigger Type Trigger Parameters


Transition — Trigger Polarity — Select the polarity for a transition-triggered signal.
on the rising or falling
edge of a signal that • Rise Time — Trigger on an increasing signal when the signal
crosses the high and low crosses the high threshold.
levels within a specified
time range.

• Fall Time — Trigger on a decreasing signal when the signal crosses


the low threshold.
• Either — Trigger on an increasing or decreasing signal.

High — Enter a high value for a transition-triggered signal. Auto level


is 90%.

Low — Enter a low value for a transition-triggered signal. Auto level is


10%.

Min Time — Enter a minimum time duration for a transition-triggered


signal.

Max Time — Enter a maximum time duration for a transition-triggered


signal.

30-16
Scope Triggers Panel

Trigger Type Trigger Parameters


Runt— Trigger when a Polarity — Select the polarity for a runt-triggered signal.
signal crosses a low
threshold or a high • Positive — Trigger on a positive-polarity pulse when the signal
threshold twice within a crosses the low threshold a second time, without crossing the high
specified time. threshold.

• Negative — Trigger on a negative-polarity pulse.


• Either — Trigger on both positive-polarity and negative-polarity
pulses.

High — Enter a high value for a runt-triggered signal. Auto level is


90%.

Low — Enter a low value for a runt-triggered signal. Auto level is 10%.

Min Width — Enter a minimum width for a runt-triggered signal. Pulse


width is measured between the first and second crossing of a threshold.

Max Width — Enter a maximum pulse width for a runt-triggered signal.

30-17
30 Visualizing and Comparing Simulation Results

Trigger Type Trigger Parameters


Window — Trigger when a Polarity — Select the region for a window-triggered signal.
signal stays within or
outside a region defined • Inside — Trigger when a signal leaves a region between the low and
by the high and low high levels.
thresholds for a specified
time.

• Outside — Trigger when a signal enters a region between the low


and high levels.

• Either — Trigger when a signal leaves or enters a region between


the low and high levels.

30-18
Scope Triggers Panel

Trigger Type Trigger Parameters


High — Enter a high value for a window-triggered signal. Auto level is
90%.

Low — Enter a low value for a window-trigger signal. Auto level is 10%.

Min Time — Enter the minimum time duration for a window-triggered


signal.

Max Time — Enter the maximum time duration for a window-triggered


signal.

30-19
30 Visualizing and Comparing Simulation Results

Trigger Type Trigger Parameters


Timeout — Trigger when Polarity — Select the polarity for a timeout-triggered signal.
a signal stays above or
below a threshold longer • Rising — Trigger when the signal does not cross the threshold from
than a specified time below. For example, if you set Timeout to 7.50 seconds, the scope
triggers 7.50 seconds after the signal crosses the threshold.

• Falling — Trigger when the signal does not cross the threshold
from above.
• Either — Trigger when the signal does not cross the threshold from
either direction

Level — Enter a threshold value for a timeout-triggered signal.

Hysteresis — Enter a value for a timeout-triggered signal. See


“Hysteresis of Trigger Signals” on page 30-21.

Timeout — Enter a time duration for a timeout-triggered signal.

Alternatively, a trigger event can occur when the signal stays within the
boundaries defined by the hysteresis for 7.50 seconds after the signal
crosses the threshold.

30-20
Scope Triggers Panel

Trigger Type Trigger Parameters

Hysteresis of Trigger Signals


Hysteresis (V) — Specify the hysteresis or noise reject value. This parameter is visible when you set
Type to Edge or Timeout. If the signal jitters inside this range and briefly crosses the trigger level,
the scope does not register an event. In the case of an edge trigger with rising polarity, the scope
ignores the times that a signal crosses the trigger level within the hysteresis region.

You can reduce the hysteresis region size by decreasing the hysteresis value. In this example, if you
set the hysteresis value to 0.07, the scope also considers the second rising edge to be a trigger event.

30-21
30 Visualizing and Comparing Simulation Results

Delay/Holdoff Pane
Offset the trigger position by a fixed delay, or set the minimum possible time between trigger events.

• Delay (s) — Specify the fixed delay time by which to offset the trigger position. This parameter
controls the amount of time the scope waits after a trigger event occurs before displaying a signal.
• Holdoff (s) — Specify the minimum possible time between trigger events. This amount of time is
used to suppress data acquisition after a valid trigger event has occurred. A trigger holdoff
prevents repeated occurrences of a trigger from occurring during the relevant portion of a burst.

See Also
Scope | Floating Scope

Related Examples
• “Cursor Measurements Panel” on page 30-23

30-22
Cursor Measurements Panel

Cursor Measurements Panel

The Cursor Measurements panel displays screen cursors. The panel provides two types of cursors
for measuring signals. Waveform cursors are vertical cursors that track along the signal. Screen
cursors are both horizontal and vertical cursors that you can place anywhere in the display.

Note If a data point in your signal has more than one value, the cursor measurement at that point is
undefined and no cursor value is displayed.

Display screen cursors with signal times and values. To open the Cursor measurements panel:

• From the menu, select Tools > Measurements > Cursor Measurements.

On the toolbar, click the Cursor Measurements button.

In the Settings pane, you can modify the type of screen cursors used for calculating measurements.
When more than one signal is displayed, you can assign cursors to each trace individually.

• Screen Cursors — Shows screen cursors (for spectrum and dual view only).
• Horizontal — Shows horizontal screen cursors (for spectrum and dual view only).
• Vertical — Shows vertical screen cursors (for spectrum and dual view only).
• Waveform Cursors — Shows cursors that attach to the input signals (for spectrum and dual view
only).
• Lock Cursor Spacing — Locks the frequency difference between the two cursors.
• Snap to Data — Positions the cursors on signal data points.

The Measurements pane displays time and value measurements.

30-23
30 Visualizing and Comparing Simulation Results

• 1 — View or modify the time or value at cursor number one (solid line cursor).
• 2 — View or modify the time or value at cursor number two (dashed line cursor).
• ΔT or ΔX — Shows the absolute value of the time (x-axis) difference between cursor number one
and cursor number two.
• ΔY — Shows the absolute value of the signal amplitude difference between cursor number one and
cursor number two.
• 1/ΔT or 1/ΔX — Shows the rate. The reciprocal of the absolute value of the difference in the times
(x-axis) between cursor number one and cursor number two.
• ΔY/ΔT or ΔY/ΔX — Shows the slope. The ratio of the absolute value of the difference in signal
amplitudes between cursors to the absolute value of the difference in the times (x-axis) between
cursors.

See Also
Scope | Floating Scope

Related Examples
• “Scope Triggers Panel” on page 30-12

30-24
Scope Signal Statistics Panel

Scope Signal Statistics Panel

Note The Signal Statistics panel requires a DSP System Toolbox or Simscape license.

Display signal statistics for the signal selected in the Trace Selection panel. To open the Signal
Statistics panel:

• From the menu, select Tools > Measurements > Signal Statistics.

On the toolbar, click the Signal Statistics button.

The statistics shown are:

• Max — Maximum or largest value within the displayed portion of the input signal.
• Min — Minimum or smallest value within the displayed portion of the input signal.
• Peak to Peak — Difference between the maximum and minimum values within the displayed
portion of the input signal.
• Mean — Average or mean of all the values within the displayed portion of the input signal.
• Median — Median value within the displayed portion of the input signal.
• RMS — Root mean squared of the input signal.

When you use the zoom options in the scope, the Signal Statistics measurements automatically adjust
to the time range shown in the display. In the scope toolbar, click the Zoom In or Zoom X button to
constrict the x-axis range of the display, and the statistics shown reflect this time range. For example,
you can zoom in on one pulse to make the Signal Statistics panel display information about only
that particular pulse.

The Signal Statistics measurements are valid for any units of the input signal. The letter after the
value associated with each measurement represents the appropriate International System of Units
(SI) prefix, such as m for milli-. For example, if the input signal is measured in volts, an m next to a
measurement value indicates that this value is in units of millivolts.

See Also
Scope | Floating Scope

30-25
30 Visualizing and Comparing Simulation Results

Related Examples
• “Scope Triggers Panel” on page 30-12

30-26
Scope Bilevel Measurements Panel

Scope Bilevel Measurements Panel

In this section...
“Bilevel Measurements” on page 30-27
“Settings” on page 30-27
“Transitions Pane” on page 30-30
“Overshoots / Undershoots Pane” on page 30-32
“Cycles Pane” on page 30-34

Bilevel Measurements

Note The Bilevel Measurements panel requires a DSP System Toolbox or Simscape license.

Display information about signal transitions, overshoots, undershoots, and cycles. To open the Bilevel
Measurements panel:

• From the menu, select Tools > Measurements > Bilevel Measurements.

On the toolbar, click the Bilevel Measurements button.

Settings
The Settings pane enables you to modify the properties used to calculate various measurements
involving transitions, overshoots, undershoots, and cycles. You can modify the high-state level, low-
state level, state-level tolerance, upper-reference level, mid-reference level, and lower-reference
level.

30-27
30 Visualizing and Comparing Simulation Results

• Auto State Level — When this check box is selected, the Bilevel measurements panel detects the
high- and low- state levels of a bilevel waveform. When this check box is cleared, you can enter in
values for the high- and low- state levels manually.

• High — Used to specify manually the value that denotes a positive polarity, or high-state level.

30-28
Scope Bilevel Measurements Panel

• Low — Used to specify manually the value that denotes a negative polarity, or low-state level.

• State Level Tolerance — Tolerance within which the initial and final levels of each transition
must be within their respective state levels. This value is expressed as a percentage of the
difference between the high- and low-state levels.
• Upper Ref Level — Used to compute the end of the rise-time measurement or the start of the fall
time measurement. This value is expressed as a percentage of the difference between the high-
and low-state levels.
• Mid Ref Level — Used to determine when a transition occurs. This value is expressed as a
percentage of the difference between the high- and low- state levels. In the following figure, the
mid-reference level is shown as the horizontal line, and its corresponding mid-reference level
instant is shown as the vertical line.

30-29
30 Visualizing and Comparing Simulation Results

• Lower Ref Level — Used to compute the end of the fall-time measurement or the start of the rise-
time measurement. This value is expressed as a percentage of the difference between the high-
and low-state levels.
• Settle Seek — The duration after the mid-reference level instant when each transition occurs
used for computing a valid settling time. This value is equivalent to the input parameter, D, which
you can set when you run the settlingtime function. The settling time is displayed in the
Overshoots/Undershoots pane.

Transitions Pane
Display calculated measurements associated with the input signal changing between its two possible
state level values, high and low.

A positive-going transition, or rising edge, in a bilevel waveform is a transition from the low-state
level to the high-state level. A positive-going transition has a slope value greater than zero. The
following figure shows a positive-going transition.

30-30
Scope Bilevel Measurements Panel

When there is a plus sign (+) next to a text label, the measurement is a rising edge, a transition from
a low-state level to a high-state level.

A negative-going transition, or falling edge, in a bilevel waveform is a transition from the high-state
level to the low-state level. A negative-going transition has a slope value less than zero. The following
figure shows a negative-going transition.

When there is a minus sign (–) next to a text label, the measurement is a falling edge, a transition
from a high-state level to a low-state level.

The Transition measurements assume that the amplitude of the input signal is in units of volts. For
the transition measurements to be valid, you must convert all input signals to volts.

• High — The high-amplitude state level of the input signal over the duration of the Time Span
parameter. You can set Time Span in the Main pane of the Visuals—Time Domain Properties
dialog box.
• Low — The low-amplitude state level of the input signal over the duration of the Time Span
parameter. You can set Time Span in the Main pane of the Visuals—Time Domain Properties
dialog box.
• Amplitude — Difference in amplitude between the high-state level and the low-state level.
• + Edges — Total number of positive-polarity, or rising, edges counted within the displayed portion
of the input signal.
• + Rise Time — Average amount of time required for each rising edge to cross from the lower-
reference level to the upper-reference level.
• + Slew Rate — Average slope of each rising-edge transition line within the upper- and lower-
percent reference levels in the displayed portion of the input signal. The region in which the slew
rate is calculated appears in gray in the following figure.

30-31
30 Visualizing and Comparing Simulation Results

• – Edges — Total number of negative-polarity or falling edges counted within the displayed portion
of the input signal.
• – Fall Time — Average amount of time required for each falling edge to cross from the upper-
reference level to the lower-reference level.
• – Slew Rate — Average slope of each falling edge transition line within the upper- and lower-
percent reference levels in the displayed portion of the input signal.

Overshoots / Undershoots Pane


The Overshoots/Undershoots pane displays calculated measurements involving the distortion and
damping of the input signal. Overshoot and undershoot refer to the amount that a signal respectively
exceeds and falls below its final steady-state value. Preshoot refers to the amount before a transition
that a signal varies from its initial steady-state value.

This figure shows preshoot, overshoot, and undershoot for a rising-edge transition.

30-32
Scope Bilevel Measurements Panel

The next figure shows preshoot, overshoot, and undershoot for a falling-edge transition.

• + Preshoot — Average lowest aberration in the region immediately preceding each rising
transition.
• + Overshoot — Average highest aberration in the region immediately following each rising
transition.
• + Undershoot — Average lowest aberration in the region immediately following each rising
transition.
• + Settling Time — Average time required for each rising edge to enter and remain within the
tolerance of the high-state level for the remainder of the settle-seek duration. The settling time is
the time after the mid-reference level instant when the signal crosses into and remains in the
tolerance region around the high-state level. This crossing is illustrated in the following figure.

30-33
30 Visualizing and Comparing Simulation Results

You can modify the settle-seek duration parameter in the Settings pane.
• – Preshoot — Average highest aberration in the region immediately preceding each falling
transition.
• – Overshoot — Average highest aberration in the region immediately following each falling
transition.
• – Undershoot — Average lowest aberration in the region immediately following each falling
transition.
• – Settling Time — Average time required for each falling edge to enter and remain within the
tolerance of the low-state level for the remainder of the settle-seek duration. The settling time is
the time after the mid-reference level instant when the signal crosses into and remains in the
tolerance region around the low-state level. You can modify the settle-seek duration parameter in
the Settings pane.

Cycles Pane
The Cycles pane displays calculated measurements pertaining to repetitions or trends in the
displayed portion of the input signal.

Properties to set:

• Period — Average duration between adjacent edges of identical polarity within the displayed
portion of the input signal. The Bilevel measurements panel calculates period as follows. It takes
the difference between the mid-reference level instants of the initial transition of each positive-
polarity pulse and the next positive-going transition. These mid-reference level instants appear as
red dots in the following figure.

• Frequency — Reciprocal of the average period. Whereas period is typically measured in some
metric form of seconds, or seconds per cycle, frequency is typically measured in hertz or cycles
per second.
• + Pulses — Number of positive-polarity pulses counted.
• + Width — Average duration between rising and falling edges of each positive-polarity pulse
within the displayed portion of the input signal.

30-34
Scope Bilevel Measurements Panel

• + Duty Cycle — Average ratio of pulse width to pulse period for each positive-polarity pulse
within the displayed portion of the input signal.
• – Pulses — Number of negative-polarity pulses counted.
• – Width — Average duration between rising and falling edges of each negative-polarity pulse
within the displayed portion of the input signal.
• – Duty Cycle — Average ratio of pulse width to pulse period for each negative-polarity pulse
within the displayed portion of the input signal.

When you use the zoom options in the Scope, the bilevel measurements automatically adjust to the
time range shown in the display. In the Scope toolbar, click the Zoom In or Zoom X button to
constrict the x-axis range of the display, and the statistics shown reflect this time range. For example,
you can zoom in on one rising edge to make the bilevel measurements panel display information
about only that particular rising edge. However, this feature does not apply to the High and Low
measurements.

See Also
Scope | Floating Scope

Related Examples
• “Scope Triggers Panel” on page 30-12

30-35
30 Visualizing and Comparing Simulation Results

Peak Finder Measurements Panel

Note Peak Finder measurements require a DSP System Toolbox or Simscape license.

The Peak Finder panel displays the maxima, showing the x-axis values at which they occur. Peaks
are defined as a local maximum where lower values are present on both sides of a peak. Endpoints
are not considered peaks. This panel allows you to modify the settings for peak threshold, maximum
number of peaks, and peak excursion.

• From the menu, select Tools > Measurements > Peak Finder.

On the toolbar, click the Peak Finder button.

The Settings pane enables you to modify the parameters used to calculate the peak values within the
displayed portion of the input signal. For more information on the algorithms this pane uses, see the
findpeaks function reference.

Properties to set:

• Peak Threshold — The level above which peaks are detected. This setting is equivalent to the
MINPEAKHEIGHT parameter, which you can set when you run the findpeaks function.
• Max Num of Peaks — The maximum number of peaks to show. The value you enter must be a
scalar integer from 1 through 99. This setting is equivalent to the NPEAKS parameter, which you
can set when you run the findpeaks function.
• Min Peaks Distance — The minimum number of samples between adjacent peaks. This setting is
equivalent to the MINPEAKDISTANCE parameter, which you can set when you run the findpeaks
function.
• Peak Excursion — The minimum height difference between a peak and its neighboring samples.
Peak excursion is illustrated alongside peak threshold in the following figure.

30-36
Peak Finder Measurements Panel

The peak threshold is a minimum value necessary for a sample value to be a peak. The peak
excursion is the minimum difference between a peak sample and the samples to its left and right
in the time domain. In the figure, the green vertical line illustrates the lesser of the two height
differences between the labeled peak and its neighboring samples. This height difference must be
greater than the Peak Excursion value for the labeled peak to be classified as a peak. Compare
this setting to peak threshold, which is illustrated by the red horizontal line. The amplitude must
be above this horizontal line for the labeled peak to be classified as a peak.

The peak excursion setting is equivalent to the THRESHOLD parameter, which you can set when
you run the findpeaks function.
• Label Format — The coordinates to display next to the calculated peak values on the plot. To see
peak values, you must first expand the Peaks pane and select the check boxes associated with
individual peaks of interest. By default, both x-axis and y-axis values are displayed on the plot.
Select which axes values you want to display next to each peak symbol on the display.

• X+Y — Display both x-axis and y-axis values.


• X — Display only x-axis values.
• Y — Display only y-axis values.

The Peaks pane displays the largest calculated peak values. It also shows the coordinates at which
the peaks occur, using the parameters you define in the Settings pane. You set the Max Num of
Peaks parameter to specify the number of peaks shown in the list.

The numerical values displayed in the Value column are equivalent to the pks output argument
returned when you run the findpeaks function. The numerical values displayed in the second
column are similar to the locs output argument returned when you run the findpeaks function.

The Peak Finder displays the peak values in the Peaks pane. By default, the Peak Finder panel
displays the largest calculated peak values in the Peaks pane in decreasing order of peak height.

Use the check boxes to control which peak values are shown on the display. By default, all check
boxes are cleared and the Peak Finder panel hides all the peak values. To show or hide all the peak
values on the display, use the check box in the top-left corner of the Peaks pane.

30-37
30 Visualizing and Comparing Simulation Results

The Peaks are valid for any units of the input signal. The letter after the value associated with each
measurement indicates the abbreviation for the appropriate International System of Units (SI) prefix,
such as m for milli-. For example, if the input signal is measured in volts, an m next to a measurement
value indicates that this value is in units of millivolts.

See Also
Scope | Floating Scope

Related Examples
• “Scope Triggers Panel” on page 30-12

30-38
Spectrum Analyzer Cursor Measurements Panel

Spectrum Analyzer Cursor Measurements Panel


The Cursor Measurements panel displays screen cursors. The panel provides two types of cursors
for measuring signals. Waveform cursors are vertical cursors that track along the signal. Screen
cursors are both horizontal and vertical cursors that you can place anywhere in the display.

Note If a data point in your signal has more than one value, the cursor measurement at that point is
undefined and no cursor value is displayed.

In the Scope menu, select Tools > Measurements > Cursor Measurements. Alternatively, in the

Scope toolbar, click the Cursor Measurements button.

The Cursor Measurements panel for the spectrum and dual view:

The Cursor Measurements panel for the spectrogram view. You must pause the spectrogram display
before you can use cursors.

You can use the mouse or the left and right arrow keys to move vertical or waveform cursors and the
up and down arrow keys for horizontal cursors.

In the Settings pane, you can modify the type of screen cursors used for calculating measurements.
When more than one signal is displayed, you can assign cursors to each trace individually.

30-39
30 Visualizing and Comparing Simulation Results

• Screen Cursors — Shows screen cursors (for spectrum and dual view only).
• Horizontal — Shows horizontal screen cursors (for spectrum and dual view only).
• Vertical — Shows vertical screen cursors (for spectrum and dual view only).
• Waveform Cursors — Shows cursors that attach to the input signals (for spectrum and dual view
only).
• Lock Cursor Spacing — Locks the frequency difference between the two cursors.
• Snap to Data — Positions the cursors on signal data points.

The Measurements pane displays the frequency (Hz) , time (s), and power (dBm) value
measurements. Time is displayed only in spectrogram mode. Channel Power shows the total power
between the cursors.

• 1 — Shows or enables you to modify the frequency, time (for spectrograms only), or both, at
cursor number one.
• 2 — Shows or enables you to modify the frequency, time (for spectrograms only), or both, at
cursor number two.
• Δ — Shows the absolute value of the difference in the frequency, time (for spectrograms only), or
both, and power between cursor number one and cursor number two.
• Channel Power — Shows the total power in the channel defined by the cursors.

The letter after the value associated with a measurement indicates the abbreviation for the
appropriate International System of Units (SI) prefix.

30-40
Spectrum Analyzer Channel Measurements Panel

Spectrum Analyzer Channel Measurements Panel

The Channel Measurements panel displays occupied bandwidth or adjacent channel power ratio
(ACPR) measurements.

• From the menu, select Tools > Measurements > Channel Measurements.

On the toolbar, click the Channel Measurements button.

In addition to the measurements, the Channel Measurements panel has an expandable Channel
Settings pane.

• Measurement — The type of measurement data to display. Available options are Occupied BW or
ACPR. See the “Occupied BW” (DSP System Toolbox) section for information on how Occupied BW
is calculated. ACPR is the adjacent channel power ratio, which is the ratio of the main channel
power to the adjacent channel power.

When you select Occupied BW as the Measurement, the following fields appear.

• Channel Settings — Modify the parameters for calculating the channel measurements.

Channel Settings for Occupied BW

• Select the frequency span of the channel, Span(Hz), and specify the center frequency CF
(Hz) of the channel. Alternatively, select the starting frequency, FStart(Hz), and specify the
starting frequency and ending frequency (FStop (Hz)) values of the channel.
• CF (Hz) — The center frequency of the channel.
• Occupied BW (%) — The percentage of the total integrated power of the spectrum centered
on the selected channel frequency over which to compute the occupied bandwidth.
• Channel Power — The total power in the channel.
• Occupied BW — The bandwidth containing the specified Occupied BW (%) of the total power of
the spectrum. This setting is available only if you select Occupied BW as the Measurement type.
• Frequency Error — The difference between the center of the occupied band and the center
frequency (CF) of the channel. This setting is available only if you select Occupied BW as the
Measurement type.

30-41
30 Visualizing and Comparing Simulation Results

When you select ACPR as the Measurement, the following fields appear.

• Channel Settings — Enables you to modify the parameters for calculating the channel
measurements.

Channel Settings for ACPR

• Select the frequency span of the channel, Span (Hz), and specify the center frequency CF
(Hz) of the channel. Alternatively, select the starting frequency, FStart(Hz), and specify the
starting frequency and ending frequency (FStop (Hz)) values of the channel.
• CF (Hz) — The center frequency of the channel.
• Number of Pairs — The number of pairs of adjacent channels.
• Bandwidth (Hz) — The bandwidth of the adjacent channels.
• Filter — The filter to use for both main and adjacent channels. Available filters are None,
Gaussian, and RRC (root-raised cosine).
• Channel Power — The total power in the channel.
• Offset (Hz) — The center frequency of the adjacent channel with respect to the center frequency
of the main channel. This setting is available only if you select ACPR as the Measurement type.
• Lower (dBc) — The power ratio of the lower sideband to the main channel. This setting is
available only if you select ACPR as the Measurement type.
• Upper (dBc) — The power ratio of the upper sideband to the main channel. This setting is
available only if you select ACPR as the Measurement type.

30-42
Spectrum Analyzer Distortion Measurements Panel

Spectrum Analyzer Distortion Measurements Panel

The Distortion Measurements panel displays harmonic distortion and intermodulation distortion
measurements.

• From the menu, select Tools > Measurements > Distortion Measurements.

On the toolbar, click the Distortion Measurements button.

The Distortion Measurements panel has an expandable Harmonics pane, which shows
measurement results for the specified number of harmonics.

Note For an accurate measurement, ensure that the fundamental signal (for harmonics) or primary
tones (for intermodulation) is larger than any spurious or harmonic content. To do so, you may need
to adjust the resolution bandwidth (RBW) of the spectrum analyzer. Make sure that the bandwidth is
low enough to isolate the signal and harmonics from spurious and noise content. In general, you
should set the RBW so that there is at least a 10dB separation between the peaks of the sinusoids and
the noise floor. You may also need to select a different spectral window to obtain a valid
measurement.

• Distortion — The type of distortion measurements to display. Available options are Harmonic or
Intermodulation. Select Harmonic if your system input is a single sinusoid. Select
Intermodulation if your system input is two equal amplitude sinusoids. Intermodulation can
help you determine distortion when only a small portion of the available bandwidth will be used.

When you select Harmonic as the Distortion, the following fields appear.

30-43
30 Visualizing and Comparing Simulation Results

The harmonic distortion measurement automatically locates the largest sinusoidal component
(fundamental signal frequency). It then computes the harmonic frequencies and power in each
harmonic in your signal. Any DC component is ignored. Any harmonics that are outside the spectrum
analyzer’s frequency span are not included in the measurements. Adjust your frequency span so that
it includes all the desired harmonics.

Note To view the best harmonics, make sure that your fundamental frequency is set high enough to
resolve the harmonics. However, this frequency should not be so high that aliasing occurs. For the
best display of harmonic distortion, your plot should not show skirts, which indicate frequency
leakage. Also, the noise floor should be visible.

For a better display, try a Kaiser window with a large sidelobe attenuation (e.g. between 100–300 db).

• Num. Harmonics — Number of harmonics to display, including the fundamental frequency. Valid
values of Num. Harmonics are from 2 to 99. The default value is 6.

30-44
Spectrum Analyzer Distortion Measurements Panel

• Label Harmonics — Select Label Harmonics to add numerical labels to each harmonic in the
spectrum display.
• 1 — The fundamental frequency, in hertz, and its power, in decibels of the measured power
referenced to 1 milliwatt (dBm).
• 2, 3, ... — The harmonics frequencies, in hertz, and their power in decibels relative to the carrier
(dBc). If the harmonics are at the same level or exceed the fundamental frequency, reduce the
input power.
• THD — The total harmonic distortion. This value represents the ratio of the power in the
harmonics, D, to the power in the fundamental frequency, S. If the noise power is too high in
relation to the harmonics, the THD value is not accurate. In this case, lower the resolution
bandwidth or select a different spectral window.

THD = 10 ⋅ log10(D/S)
• SNR — Signal-to-noise ratio (SNR). This value represents the ratio of power in the fundamental
frequency, S, to the power of all nonharmonic content, N, including spurious signals, in decibels
relative to the carrier (dBc).

SNR = 10 ⋅ log10(S/N)

If you see –– as the reported SNR, the total non-harmonic content of your signal is less than 30%
of the total signal.
• SINAD — Signal-to-noise-and-distortion. This value represents the ratio of the power in the
fundamental frequency, S to all other content (including noise, N, and harmonic distortion, D), in
decibels relative to the carrier (dBc).

S
SIN AD = 10 ⋅ log10
N+D
• SFDR — Spurious free dynamic range (SFDR). This value represents the ratio of the power in the
fundamental frequency, S, to power of the largest spurious signal, R, regardless of where it falls in
the frequency spectrum. The worst spurious signal may or may not be a harmonic of the original
signal. SFDR represents the smallest value of a signal that can be distinguished from a large
interfering signal. SFDR includes harmonics.

SNR = 10 ⋅ log10(S/R)

When you select Intermodulation as the Distortion, the following fields appear.

30-45
30 Visualizing and Comparing Simulation Results

The intermodulation distortion measurement automatically locates the fundamental, first-order


frequencies (F1 and F2). It then computes the frequencies of the third-order intermodulation
products (2*F1-F2 and 2*F2-F1).

• Label frequencies — Select Label frequencies to add numerical labels to the first-order
intermodulation product and third-order frequencies in the spectrum analyzer display.
• F1 — Lower fundamental first-order frequency
• F2 — Upper fundamental first-order frequency
• 2F1 - F2 — Lower intermodulation product from third-order harmonics
• 2F2 - F1 — Upper intermodulation product from third-order harmonics
• TOI — Third-order intercept point. If the noise power is too high in relation to the harmonics, the
TOI value will not be accurate. In this case, you should lower the resolution bandwidth or select a
different spectral window. If the TOI has the same amplitude as the input two-tone signal, reduce
the power of that input signal.

30-46
Spectral Masks

Spectral Masks

Add upper and lower masks to the Spectrum Analyzer to visualize spectrum limits and compare
spectrum values to specification values.

To open the Spectral Mask pane, in the toolbar, select the spectral mask button .

Set Up Spectral Masks


In the Spectrum Analyzer window:

1 In the Spectral Mask pane, select a Masks option.


2 In the Upper limits or Lower limits box, enter the mask limits as a constant scalar, an array, or
a workspace variable name.
3 (Optional) Select additional properties:

• Reference level — Set a reference level for the mask. Enter a specific value or select
Spectrum peak.
• Channel — Select a channel to use for the mask reference.
• Frequency offset — Set a frequency offset for mask.

From the command-line, to add a spectral mask to the dsp.SpectrumAnalyzer System object or
the SpectrumAnalyzerConfiguration block configuration object:

1 Create a SpectralMaskSpecfication object.


2 Set properties, such as EnabledMasks, LowerMask, or UpperMask.
3 In the dsp.SpectrumAnalyzer or SpectrumAnalyzerConfiguration object, set the
SpectralMask property equal to your SpectralMaskSpecfication object.

For example:

mask = SpectralMaskSpecification();
mask.EnabledMasks = 'Upper';
mask.UpperMask = 10;
scope = dsp.SpectrumAnalyzer();
scope.SpectralMask = mask;
scope.SpectralMask

ans =

SpectralMaskSpecification with properties:

EnabledMasks: 'Upper'
UpperMask: 10
LowerMask: -Inf
ReferenceLevel: 'Custom'
CustomReferenceLevel: 0
MaskFrequencyOffset: 0

Events for class SpectralMaskSpecification: MaskTestFailed

30-47
30 Visualizing and Comparing Simulation Results

Check Spectral Masks


You can check the status of the spectral mask in several different ways:

• In the Spectrum Analyzer window, select the spectral mask button . In the Spectral Mask
pane, the Statistics section shows statistics about how often the masks fail, which channels have
caused a failure, and which masks are currently failing.
• To get the current status of the spectral masks, call getSpectralMaskStatus.
• To perform an action every time the mask fails, use the MaskTestFailed event. To trigger a
function when the mask fails, create a listener to the MaskTestFailed event and define a
callback function to trigger. For more details about using events, see “Events”.

30-48
Spectrum Analyzer CCDF Measurements Panel

Spectrum Analyzer CCDF Measurements Panel

The CCDF Measurements panel displays complimentary cumulative distribution function


measurements. CCDF measurements in this scope show the probability of the instantaneous power of
a signal being a specified level above the average power of the signal. These measurements are
useful indicators of the dynamic range of a signal.

To compute the CCDF measurements, each input sample is quantized to 0.01 dB increments. Using a
histogram 100 dB wide (10,000 points at 0.01 dB increments), the largest peak encountered is placed
in the last bin of the histogram. If a new peak is encountered, the histogram shifts to make room for
that new peak.

To open this dialog box:

• From the menu, select Tools > Measurements > CCDF Measurements
• In the toolbar, click the CCDF Measurements button.

• Plot Gaussian reference — Show the complex white Gaussian noise reference signal on the plot.
• Probability (%) — Percentage of the signal that contains the power level above the value listed in
the dB above average column
• dB above average — Expected minimum power level at the associated Probability (%).
• Average Power — Average power level of the signal since the start of simulation or from the last
reset.

Max Power — Maximum power level of the signal since the start of simulation or from the last
reset.

30-49
30 Visualizing and Comparing Simulation Results

• PAPR — Ratio of the peak power to the average power of the signal. PAPR should be less that 100
dB to obtain accurate CCDF measurements. If PAPR is above 100 dB, only the highest 100 dB
power levels are plotted in the display and shown in the distribution table.
• Sample Count — Total number of samples used to compute the CCDF.
• Reset — Clear all current CCDF measurements and restart.

30-50
Common Scope Block Tasks

Common Scope Block Tasks


In this section...
“Connect Multiple Signals to a Scope” on page 30-51
“Save Simulation Data Using Scope Block” on page 30-53
“Pause Display While Running” on page 30-55
“Copy Scope Image” on page 30-55
“Plot an Array of Signals” on page 30-57
“Scopes in Referenced Models” on page 30-58
“Scopes Within an Enabled Subsystem” on page 30-62
“Modify x-axis of Scope” on page 30-63
“Show Signal Units on a Scope Display” on page 30-66
“Select Number of Displays and Layout” on page 30-68
“Dock and Undock Scope Window to MATLAB Desktop” on page 30-69

To visualize your simulation results over time, use a Scope block or Time Scope block

Connect Multiple Signals to a Scope


To connect multiple signals to a scope, drag additional signals to the scope block. An additional port
is created automatically.

To specify the number of input ports:


1 Open a scope window.
2 From the toolbar, select File > Number of Input Ports > More.
3 Enter the number of input ports, up to 96.

Signals from Nonvirtual Buses and Arrays of Buses

You can connect signals from nonvirtual buses and arrays of buses to a Scope block. To display the
bus signals, use normal or accelerator simulation mode. The Scope block displays each bus element

30-51
30 Visualizing and Comparing Simulation Results

signal, in the order the elements appear in the bus, from the top to the bottom. Nested bus elements
are flattened. For example, in this model the nestedBus signal has the const, subSignal, and
step signals as elements. The subSignal sub-bus has the chirp and sine signals as its bus
elements. In the Scope block, the two elements of the subSignal bus display between the const
and step signals.

30-52
Common Scope Block Tasks

Save Simulation Data Using Scope Block

This example shows how to save signals to the MATLAB Workspace using the Scope block. You can us
these steps for the Scope or Time Scope blocks. To save data from the Floating Scope or Scope
viewer, see “Save Simulation Data from Floating Scope” on page 30-75.

Using the vdp model, turn on data logging to the workspace. You can follow the commands below, or
in the Scope window, click the Configuration Properties button and navigate to the Logging tab, turn
on Log data to workspace.

open_system('vdp');
scopeConfig = get_param('vdp/Scope','ScopeConfiguration');
scopeConfig.DataLogging = true;
scopeConfig.DataLoggingSaveFormat = 'Dataset';
out = sim('vdp');

30-53
30 Visualizing and Comparing Simulation Results

In the MATLAB Command window, view the logged data from the out.ScopeData structure.

x1_data = out.ScopeData{1}.Values.Data(:,1);
x1_time = out.ScopeData{1}.Values.Time;
plot(x1_time,x1_data)

30-54
Common Scope Block Tasks

Pause Display While Running


Use the Simulink Snapshot to pause the scope display while the simulation keeps running in the
background.

1 Open a scope window and start the simulation.


2 Select Simulation > Simulink Snapshot.

The scope window status in the bottom left is Frozen, but the simulation continues to run in the
background.
3 Interact with the paused display. For example, use measurements, copy the scope image, or zoom
in or out.
4 To unfreeze the display, select Simulation > Simulink Snapshot again.

Copy Scope Image


This example uses the vdp model to demonstrate how to copy and paste a scope image.

1 Add a scope block to your model.


2 Connect signals to scope ports. See “Connect Multiple Signals to a Scope” on page 30-51. For
example, in the vdp model, connect the signals x1 and x2 to a scope.
3 Open the scope window and run the simulation.

30-55
30 Visualizing and Comparing Simulation Results

4 Select File > Copy to Clipboard.


5 Paste the image into a document.

By default, Copy to Clipboard saves a printer-friendly version of the scope with a white
background and visible lines. If you want to paste the exact scope plot displayed, select View >
Style, then select the Preserve colors for copy to clipboard check box.

30-56
Common Scope Block Tasks

Plot an Array of Signals

This example shows how the scope plots an array of signals.

In this simple model, a Sine Wave block is connected to a scope block. The Sine Wave block outputs
four signals with the amplitudes [10, 20; 30 40]. The scope displays each sine wave in the array
separately in the matrix order (1,1), (2,1), (1,2), (2,2).

30-57
30 Visualizing and Comparing Simulation Results

Scopes in Referenced Models


This example shows the behavior of scopes in referenced models. When you use a scope in a
referenced model, you see different output in the scope depending on where you started the
simulation: from the top model or the scope in the referenced model.

Note Scope windows display simulation results for the most recently opened top model. Playback
controls in scope blocks and viewers simulate the model containing that block or viewer.

This example uses the sldemo_mdlref_counter model both as a top model and as a referenced
model from the sldemo_mdlref_basic model.

Open the model:


openExample('simulink/FindMdlrefsFindReferencedModelsinModelReferenceHierarchyExample','supportin

Double-click the CounterA block. The sldemo_mdlref_counter model opens as a referenced


model, as evidenced by the breadcrumb above the canvas.

30-58
Common Scope Block Tasks

Run the simulation using the main run button, then open up the ScopeA scope. The scope visualizes
the data from the entire model.

30-59
30 Visualizing and Comparing Simulation Results

If you specifically want to visualize a referenced model in isolation, open the model as a top model. In
this example, right-click the CounterA block and select Open as Top Model. The model opens in
another window and the breadcrumb only shows the referenced model name.

30-60
Common Scope Block Tasks

When you run the simulation from either the Simulink window or the scope window, the scope
visualizes the model without any reference to another model. In this case, the model input is zero the
entire time.

30-61
30 Visualizing and Comparing Simulation Results

Scopes Within an Enabled Subsystem


When placed within an Enabled Subsystem block, scopes behave differently depending on the
simulation mode:

• Normal mode — A scope plots data when the subsystem is enabled. The display plot shows gaps
when the subsystem is disabled.

• External, Accelerator, and Rapid modes — A scope plots data when the subsystem is enabled. The
display connects the gaps with straight lines.

30-62
Common Scope Block Tasks

Modify x-axis of Scope

This example shows how to modify the x-axis values of the Scope block using the Time span and
Time display offset parameters. The Time span parameter modifies how much of the simulation
time is shown and offsets the x-axis labels. The Time display offset parameter modifies the labels
used on the x-axis.

You can also use this procedure for the Time Scope block, Floating Scope block, or Scope viewer.

Open the model and run the simulation to see the original scope output. The simulation runs for 10
time steps stepping up by 1 at each time step.

model = 'ModifyScopeXAxis';
open_system(model);
sim(model);
open_system([model,'/Scope']);

30-63
30 Visualizing and Comparing Simulation Results

Modify Time Span Shown

Modify the Time span parameter to 2. You can follow the commands below, or in the Scope window,
click the Configuration Properties button and navigate to the Time tab.

scopeConfig = get_param([model,'/Scope'],'ScopeConfiguration');
scopeConfig.TimeSpan = '2';
sim(model);
open_system([model,'/Scope']);

30-64
Common Scope Block Tasks

The x-axis of the scope now shows only the last 2 time steps and offsets the x-axis labels to show 0-2.
The bottom toolbar shows that the x-axis is offset by 8. This offset is different from the Time display
offset value.

The Time span parameter is useful if you do not want to visualize signal initialization or other start-
up tasks at the beginning of a simulation. You can still see the full simulation time span if you click
the Span x-axis button.

Offset x-axis Labels

Modify the Time display offset parameter to 5. Again, use the commands below, or in the Scope
window, click the Configuration Properties button and navigate to the Time tab.

scopeConfig.TimeDisplayOffset = '5';
sim(model);
open_system([model,'/Scope']);

30-65
30 Visualizing and Comparing Simulation Results

Now, the same time span of 2 is show in the scope, but the x-axis labels are offset by 5, starting at 5
and ending at 7. If you click the Span x-axis button, the x-axis labels still start at 5.

Show Signal Units on a Scope Display


You can specify signal units at a model component boundary (Subsystem and Model blocks) using
Inport and Outport blocks. See “Unit Specification in Simulink Models” on page 9-2. You can then
connect a Scope block to an Outport block or a signal originating from an Outport block. In this
example, the Unit property for the Out1 block was set to m/s.

Show Units on a Scope Display

1
From the Scope window toolbar, select the Configuration Properties button .
2 In the Configuration Properties: Scope dialog box, select the Display tab.
3 In the Y-label box, enter a title for the y-axis followed by (%<SignalUnits>). For example,
enter

Velocity (%<SignalUnits>)
4 Click OK or Apply.

30-66
Common Scope Block Tasks

Signal units display in the y-axis label as meters per second (m/s) and in the Cursor
Measurements panel as millimeters per second (mm/s).

From the Simulink toolstrip, you can also select Debug > Information Overlays > Units. You do
not have to enter (%<SignalUnits>) in the Y-Label property.

Show Units on a Scope Display Programmatically

1 Get the scope properties. In the Command Window, enter

load_system('my_model')
s = get_param('my_model/Scope','ScopeConfiguration');
2 Add a y-axis label to the first display.

s.ActiveDisplay = 1
s.YLabel = 'Velocity (%<SignalUnits>)';

You can also set the model parameter ShowPortUnits to 'on'. All scopes in your model, with and
without (%<SignalUnits>) in the Y-Label property, show units on the displays.

load_system('my_model')
get_param('my_model','ShowPortUnits')

ans =
off

set_param('my_model', 'ShowPortUnits','on')

ans =
on

30-67
30 Visualizing and Comparing Simulation Results

Determine Units from a Logged Data Object

When saving simulation data from a scope with the Dataset format, you can find unit information in
the DataInfo field of the timeseries object.

Note Scope support for signal units is only for the Dataset logging format and not for the legacy
logging formats Array, Structure, and Structure With Time.

1
From the Scope window toolbar, select the Configuration Properties button .
2 In the Configuration Properties window, select the Logging tab.
3 Select the Log data to workspace check box. In the text box, enter a variable name for saving
simulation data. For example, enter ScopeData.
4
From the Scope window toolbar, select the run button .
5 In the Command Window, enter

ScopeData.getElement(1).Values.DataInfo

Package: tsdata
Common Properties:
Units: m/s (Simulink.SimulationData.Unit)
Interpolation: linear (tsdata.interpolation)

Connect Signals with Different Units to a Scope

When there are multiple ports on a scope, Simulink ensures that each port receives data with only
one unit. If you try to combine signals with different units (for example by using a Bus Creator block),
Simulink returns an error.

Scopes show units depending on the number of ports and displays:

• Number of ports equal to the number of displays — One port is assigned to one display with
units for the port signal shown on the y-axis label.
• Greater than the number of displays — One port is assigned to one display, with the last
display assigned the remaining signals. Different units are shown on the last y-axis label as a
comma-separated list.

Select Number of Displays and Layout


1
From a Scope window, select the Configuration Properties button .
2 In the Configuration Properties dialog box, select the Main tab, and then select the Layout
button.
3 Select the number of displays and the layout you want.

You can select more than four displays in a row or column. Click within the layout, and then drag
your mouse pointer to expand the layout to a maximum of 16 rows by 16 columns.

30-68
Common Scope Block Tasks

4 Click to apply the selected layout to the Scope window.

Dock and Undock Scope Window to MATLAB Desktop


1 In the right corner of a Scope window, click the Dock Scope button.

The Scope window is placed above the Command Window in the MATLAB desktop.
2 Click the Show Scope Actions button, and then click Undock Scope.

See Also
Scope | Floating Scope | Scope Viewer

Related Examples
• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Floating Scope and Scope Viewer Tasks” on page 30-73

30-69
30 Visualizing and Comparing Simulation Results

View Values of Parameters Set as Variables


When you specify the value of a Simulink parameter as a variable or as an expression that contains
variables, the Block Parameters dialog box and the Property Inspector display the value of the
variable or the expression.

The text box where you enter the parameter value displays the variable or expression on the left and
the value on the right.

Note Numerical values are displayed in the shortG format. For more information about the shortG
format, see format.

With this in-place display of parameter values, you can check the value of a parameter in the same
text field where you define the parameter.

To see the value the variable or expression has during simulation, run the simulation and open the
Block Parameters dialog box or the Property Inspector. The displayed value is the value of the
variable or expression in the simulation at the time step when you open the Block Parameters dialog
box or the Property Inspector.

If the variable represents a data type that cannot be evaluated, the data type or class is displayed
instead of a value. For example, if the variable represents an object, the class is displayed.

In-Place Parameter Value Display for Different Data Types


What the text field displays depends on the data type and dimensions of the parameter value. The
table shows the display according to data type and, where relevant, dimension.

Data Type and Display Example


Dimension
1-D or 2-D matrix with Values of all elements x=[1,2;3,4];
four elements or fewer

30-70
View Values of Parameters Set as Variables

Data Type and Display Example


Dimension
Matrix with more than Dimensions and data x=[1 2 3 4 5];
two dimensions or more type
than four elements

String Value x="position";

Character vector Value x='position';

Cell array Dimensions and data x={'a','b','c'};


type

Structure Data type x.a=1;


x.b=2;
x.c=3;

Object Class Create the BasicClass from the “Design Class”


example.

Note The class is x=BasicClass;


displayed as a
hyperlink. When you
click the hyperlink, the
MATLAB File Help for
the class opens.

In-Place Parameter Value Display for Variables Defined in Multiple


Workspaces
To see how a variable is evaluated when the same variable name is used to represent different values
in different workspaces, see “Symbol Resolution Process” on page 73-151.

Turn Off In-Place Parameter Value Display


To turn the value display off, in the Simulink Toolstrip, on the Modeling tab, in the Evaluate and
Manage section, click Environment, then click Simulink Preferences. Select Editor, then clear
Show evaluated value in place.

Note Settings in the Simulink Preferences are applied to all Simulink windows and persist from one
session to the next.

30-71
30 Visualizing and Comparing Simulation Results

See Also
“Create, Edit, and Manage Workspace Variables” on page 73-124 | “Edit and Manage Workspace
Variables by Using Model Explorer” on page 73-129

30-72
Floating Scope and Scope Viewer Tasks

Floating Scope and Scope Viewer Tasks


In this section...
“Add Floating Scope Block to Model and Connect Signals” on page 30-73
“Add Scope Viewer to a Signal” on page 30-74
“Add Signals to an Existing Floating Scope or Scope Viewer” on page 30-74
“Save Simulation Data from Floating Scope” on page 30-75
“Add and Manage Viewers” on page 30-78
“Quickly Switch Visualization of Different Signals on a Floating Scope” on page 30-79

These tasks walk through frequently used Floating Scope and Scope Viewer procedures.

Add Floating Scope Block to Model and Connect Signals


To add a Floating Scope block from the Simulink block library:

1
From the Simulation tab, click Library Browser .
2 From Simulink / Sinks, drag a copy of the Floating Scope block into your model.

To connect signals to your floating scope:

1 Double-click the Floating Scope block.


2
In the scope window toolbar, click the signal selection button . You may need to select the
dropdown next to the lock button to see signal selection.

The Simulink Editor canvas grays, indicating you can interactively select signals to connect to
the scope.
3 Select the signals you want to connect to the scope. To select multiple signals, click and drag.
4 In the Connect pop-up, select the check box next to the signals you want to connect.

30-73
30 Visualizing and Comparing Simulation Results

5 For scopes with multiple displays (subplots), select the desired display from the drop-down at the
top of the Connect pop-up and connect the signals.
6 Click the X in the upper-right of the Simulink canvas.

Your signals are now connected to the floating scope. Run a simulation to see the plotted signals.

Add Scope Viewer to a Signal


1 Select a signal to view.
2 In the Simulation tab, in the Prepare gallery, select Add Viewer.
3 From the Add Viewer window, select a viewer, for example Scope.

Add Signals to an Existing Floating Scope or Scope Viewer


Connect signals to an existing Floating Scope or Scope viewer.

1
Open the scope by double-clicking a Floating Scope block or Scope viewer icon .
2
In the scope window toolbar, click the signal selection button . You may need to select the
drop-down next to the lock button to see signal selection.

The Simulink Editor canvas grays, indicating you can interactively select signals to connect to
the scope.
3 Select the signals you want to connect to the scope. To select multiple signals, click and drag.

30-74
Floating Scope and Scope Viewer Tasks

4 In the Connect pop-up, select the check box next to the signals you want to connect.

5 For scopes with multiple displays (subplots), select the desired display from the drop-down at the
top of the Connect pop-up and connect the signals.
6 Click the X in the upper-right of the Simulink canvas.

Your signals are now connected to the scope. Run a simulation to see the plotted signals.

Save Simulation Data from Floating Scope

This example shows how to save signals to the MATLAB® Workspace using a Floating Scope block.
You can follow the same procedure to save data from a Scope Viewer. To save data from a Scope or
Time Scope block, see “Save Simulation Data Using Scope Block” on page 30-53.

This example uses a modified version of the vdp model. In this example, a floating scope is connected
to the x1 and x2 signals.

Set Up Signal Logging from the Floating Scope

model = 'vdpFloatingScope';
open_system(model);

30-75
30 Visualizing and Comparing Simulation Results

1 From the Floating Scope window, select View > Configuration Properties.
2 On the Logging tab, select Log/Unlog Viewer Signals to Workspace. When you click this
button, Simulink places logging symbols on the signals connected to the Floating Scope.
3 From the Simulink Editor, on the Modeling tab, click Model Settings.
4 In the Configuration Properties window, select Data Import/Export.
5 Select the Signal logging check box. You can also set the parameter name from this window.
The default parameter name is logsout.

Use Saved Simulation Data

Run a simulation. Simulink saves data to the MATLAB Workspace in a variable out.

out = sim(model);

30-76
Floating Scope and Scope Viewer Tasks

Simulink saves all logged or saved simulation data as one structure. In out, the scope data object
logsout has one element for each logged signal.

In the MATLAB Command Window, plot the log data for x1.

x1_data = out.logsout.get('x1').Values.Data;
x1_time = out.logsout.get('x2').Values.Time;
plot(x1_time,x1_data);

30-77
30 Visualizing and Comparing Simulation Results

Add and Manage Viewers


Open the Viewers and Generators Manager. From the Simulink toolstrip Simulation tab, expand the
Prepare gallery and select Viewers Manager.

You can see any viewers or generators you added in the Viewers and Generators Manager.

30-78
Floating Scope and Scope Viewer Tasks


To add viewers or generators, click and choose a viewer. New viewers and generators are not
connected to any signals.

To connect signals, click on a viewer or generator, and click .
• To delete a viewer or generator, click .

Quickly Switch Visualization of Different Signals on a Floating Scope


1 Open a Floating Scope window.
2
On the toolbar, click the Lock button so that the icon is unlocked .
3 In the model, click a signal line to select and highlight the signal line. To select multiple signals,
hold down the Shift key while selecting signals.

After clicking on the canvas, the selected display removes connections to any previously selected
signals.
4
Run a simulation. As long as the unlock icon is showing, you can click between signals to
switch which signal appears in the Floating Scope.

See Also
Scope | Floating Scope | Scope Viewer

30-79
30 Visualizing and Comparing Simulation Results

Related Examples
• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Common Scope Block Tasks” on page 30-51

30-80
Generate Signals Without Source Blocks

Generate Signals Without Source Blocks


Signal generators create signals without adding a block to your model. Generators are added and
managed through the Viewers and Generators Manager.

Attach Signal Generator


Context Menu

1 In the Simulink Editor, right-click the input to a block.


2 From the context menu, select Create And Connect Generator > product > generator.

The name of the generator you choose appears in a box connected to the block input.

Viewers and Generators Manager

1 From the Simulation tab, open the Prepare gallery and select Viewers Manager. The Viewers
and Generators Manager panel opens to the side of the Simulink editor.
2 In the Viewers and Generators panel, select the Generators tab.
3
Click the button and select a generator.

The generator is added to the list of generators.


4
Click the generator you just added from the list and select the button.
5 The canvas grays, indicating you are now in connect mode. Click the block you want to connect
the generator to and in the pop-up, select the check box for the input port you want to attach the
generator to.
6 Close connect mode by clicking the X in the upper right corner of the canvas.

Modify Signal Generator Parameters


Context Menu

1 Right-click the generator name and select Generator Parameters. In the Generator Parameters
dialog box, enter parameters for this generator.
2 To rename a signal generator, double-click the generator label and type your new name for the
generator.

Viewers and Generators Manager

1 From the Viewers and Generators Manager panel, select the generator from the Generator tab.
2
Click and enter parameter values for this generator.
3 To rename a signal generator, double-click the generator name in the Generators list and type
your new name for the generator.

30-81
30 Visualizing and Comparing Simulation Results

Remove Signal Generator


Context Menu

1 Right-click a generator.
2 From the context menu, select Disconnect Generator.

To also delete the generator, select Disconnect and Delete Generator

Viewers and Generators Manager

1 From the Viewers and Generators Manager panel, select the generator from the Generator tab.
2
Enter connect mode by selecting the button
3 On the grayed canvas, select the generator and, in the pop-up, clear the check box next to the
port you want to disconnect.
4
To delete the generator completely, in the Viewers and Generators Manager panel, also click .

See Also
Scope Viewer

Related Examples
• “Common Scope Block Tasks” on page 30-51
• “Floating Scope and Scope Viewer Tasks” on page 30-73
• “Viewers and Generators Manager” on page 30-83

30-82
Viewers and Generators Manager

Viewers and Generators Manager

Using the Viewers and Generators Manager, you can manage viewers and generators from a central
point.

Viewers and generators are not blocks. Blocks are dragged from the Library Browser and managed
with block dialog boxes. Viewers and generators are mechanisms that create or visualize signals, but
are added and managed through the Viewers and Generators Manager.

Symbols identify a viewer attached to a signal line, and signal names identify generators.

Open the Viewers and Generators Manager


From the Simulation tab, open the Prepare gallery and select Viewers Manager. The Viewers and
Generators Manager panel opens to the side of the Simulink editor.

You can also access the Viewers and Generators Manager by right-clicking a signal or block input and
selecting Viewers and Generators Manager.

Change Parameters
1 Open the Viewers and Generators Manager.
2 In the list of Generators or Viewers, select the viewer or generator you want to modify.
3
Select the button.

• For a generator, the parameters dialog box opens for that generator type.
• For a viewer, either a parameter dialog opens or the viewer itself opens. If the viewer opens,

you can access parameters from the button.


4 Review and change parameters.

Connect Viewers and Generators


Connect signals to a new viewer or generator using the Viewers and Generators Manager.

1 Open the Viewers and Generators Manager panel.


2 Select either the Viewers or Generators tab.
3
Click .

30-83
30 Visualizing and Comparing Simulation Results

4 From the list of viewers or generators, select the viewer or generator you just added.
5
Select the button. The canvas grays, indicating you are now in connect mode.
6 For generators, click the block you want to connect the generator to and in the pop-up, select the
check box for the input port you want to attach to.

For viewers, click the signal or signals you want to visualize and in the pop-up, select the check
box next to the signals you want to connect. If you have multiple displays or specific inputs,
select the display you want to connect to from the drop down before selecting the check box.
7 Close connect mode by clicking the X in the upper right corner of the canvas.

View Test Point Data


Use a Scope viewer available from the Viewers and Generators Manager to view any signal that is
defined as a test point in a referenced model. A test point is a signal that you can always see when
using a Scope viewer in a model.

Note With some viewers (for example, To Video Display, Matrix Viewer), you cannot use the Signal
Selector to select signals with test points in referenced models.

For more information, see “Configure Signals as Test Points” on page 81-50.

Customize Viewers and Generators Manager


You can add custom signal viewers or generators so that they appear in the Viewers and Generators
Manager. This procedure adds a custom viewer named newviewer to the Viewers and Generators
Manager:

1 Create a new Simulink library by selecting Simulation > New > Library.
2 Save the library as newlib.
3 In the MATLAB Command Window, set the library type to a viewer library:

set_param('newlib','LibraryType','SSMgrViewerLibrary')

To set the library type for generators, use the type 'SSMgrGenLibrary'. For example:

set_param('newlib','LibraryType','SSMgrGenLibrary')
4 Set the display name of the library:

set_param('newlib','SSMgrDisplayString','My Custom Library')


5 Add your custom viewer or generator to the library by dragging and dropping into the Simulink
canvas.

Note If the viewer is a compound viewer, such as a subsystem with multiple blocks, make the
top-level subsystem an atomic one.
6 Set the iotype of the viewer. For example:

set_param('newlib/newviewer','iotype','viewer')

30-84
Viewers and Generators Manager

7 Save the library newlib.


8 Using the MATLAB editor, create a file named sl_customization.m. In this file, enter a
directive to incorporate the new library as a viewer library.

For example, to save newlib as a viewer library, add these lines:

function sl_customization(cm)
cm.addSigScopeMgrViewerLibrary('newlib')
%end function

To add a library as a generator library, use this syntax instead:

cm.addSigScopeMgrGeneratorLibrary('newlib')
9 Add a corresponding cm.addSigScope line for each viewer or generator library you want to
add.
10 Save the sl_customization.m file on your MATLAB path. Edit this file to add new viewer or
generator libraries.
11 To see the new custom libraries, restart MATLAB and start the Viewers and Generators Manager.

Limitations
Viewers and Generators Manager workflows do not support library models, subsystem references,
and System Composer.

See Also
Floating Scope | Scope | Scope Viewer

Related Examples
• “Common Scope Block Tasks” on page 30-51
• “Floating Scope and Scope Viewer Tasks” on page 30-73
• “Scope Blocks and Scope Viewer Overview” on page 30-6

30-85
30 Visualizing and Comparing Simulation Results

Control Scope Blocks Programmatically

This example shows how to control scopes with programming scripts.

Use Simulink Configuration Object

Use a Scope Configuration object for programmatic access to scope parameters.

• Modify the title, axis labels, and axis limits


• Turn on or off the legend or grid
• Control the number of inputs
• Change the number of displays and which display is active

Create a model and add a Scope and Time Scope block. Then, use get_param to create the Scope
Configuration object myConfiguration.
mdl = 'myModel';
new_system(mdl);
add_block('simulink/Sinks/Scope', [mdl '/myScope']);
add_block('dspsnks4/Time Scope', [mdl '/myTimeScope']);
myConfiguration = get_param([mdl '/myScope'],'ScopeConfiguration')

myConfiguration =
Scope configuration with properties:

Name: 'myScope'
Position: [360 302 560 420]
Visible: 0
OpenAtSimulationStart: 0
DisplayFullPath: 0
PreserveColorsForCopyToClipboard: 0
NumInputPorts: '1'
LayoutDimensions: [1 1]
SampleTime: '-1'
FrameBasedProcessing: 0
MaximizeAxes: 'Off'
MinimizeControls: 0
AxesScaling: 'Manual'
AxesScalingNumUpdates: '10'
TimeSpan: 'Auto'
TimeSpanOverrunAction: 'Wrap'
TimeUnits: 'none'
TimeDisplayOffset: '0'
TimeAxisLabels: 'Bottom'
ShowTimeAxisLabel: 0
ActiveDisplay: 1
Title: '%<SignalLabel>'
ShowLegend: 0
ShowGrid: 1
PlotAsMagnitudePhase: 0
YLimits: [-10 10]
YLabel: ''
DataLogging: 0
DataLoggingVariableName: 'ScopeData'
DataLoggingLimitDataPoints: 0

30-86
Control Scope Blocks Programmatically

DataLoggingMaxPoints: '5000'
DataLoggingDecimateData: 0
DataLoggingDecimation: '2'
DataLoggingSaveFormat: 'Dataset'

Set a property.

myConfiguration.DataLoggingMaxPoints ='10000';

Find the Scope and Time Scope blocks.

find_system(mdl,'LookUnderMasks','on','IncludeCommented','on', ...
'AllBlocks','on','BlockType','Scope')

ans = 2x1 cell


{'myModel/myScope' }
{'myModel/myTimeScope'}

Find only Simulink Scope blocks.

find_system(mdl,'LookUnderMasks','on','IncludeCommented','on',...
'AllBlocks','on','BlockType','Scope','DefaultConfigurationName',...
'Simulink.scopes.TimeScopeBlockCfg')

ans = 1x1 cell array


{'myModel/myScope'}

Find only the DSP Time Scope blocks.

find_system(mdl,'LookUnderMasks','on','IncludeCommented','on',...
'AllBlocks','on','BlockType','Scope','DefaultConfigurationName',...
'spbscopes.TimeScopeBlockCfg')

ans = 1x1 cell array


{'myModel/myTimeScope'}

Scope Configuration Properties

For details about the Scope Configuration object properties, see TimeScopeConfiguration.

See Also
Floating Scope | Scope | Scope Viewer

Related Examples
• “Common Scope Block Tasks” on page 30-51
• “Floating Scope and Scope Viewer Tasks” on page 30-73
• “Scope Blocks and Scope Viewer Overview” on page 30-6

30-87
30 Visualizing and Comparing Simulation Results

Plot a Circle Using the XY Graph Block

This example shows how to plot data using the XY Graph block. The XY Graph block is an alternative
configuration of the Record block that plots two input signals on an XY plot. The XY plot used by the
Record block is also available in the Simulation Data Inspector. The XY Graph block has all the
capabilities of the Record block, including the ability to log data to the workspace and a file.

The model computes x and y data to plot a circle using a third variable, θ. Using a polar coordinate
system, you can express the equation for a circle of radius a centered on the origin as:

r(θ) = a

Converting the equation to use Cartesian coordinates results in these equations for the x and y data:

x = acos(θ)

y = asin(θ)

The model computes the x and y data using Trigonometric Function blocks. The Ramp block provides
the input θ and the Constant block sets the radius of the circle. Open and simulate the model.

mdl = "XYGraphCircle";
open_system(mdl);
sim(mdl);

To view the plotted results, double-click the XY Graph block.

30-88
Plot a Circle Using the XY Graph Block

You can add subplots to the layout in the XY Graph block to view the x and y data variations against
time. For example, select Layouts. Then, under Overlays, select Bottom. To view the signals, click
Show Signals. To plot the x signal, select the left overlay, then select the check box next to the x
signal. To plot the y signal, select the right overlay, then select the y signal.

30-89
30 Visualizing and Comparing Simulation Results

You can also update the styling of the data plotted on the XY plot. For example, add a connecting line
and remove the data markers. Select the XY subplot. To add a connecting line to the plot, on the
Format tab, under Line, click Line. To remove the markers from the plot, on the Format tab, under
Markers, click Markers.

30-90
Plot a Circle Using the XY Graph Block

The XY plot supports other analysis and visualization features, including trend lines and the ability to
plot more than one series. For more information, see “Visualize Simulation Data on XY Plot” on page
31-41 and “Analyze Data Using XY Plot” on page 31-52.

See Also
Blocks
Record

Tools
Simulation Data Inspector

Related Examples
• “Visualize Simulation Data on XY Plot” on page 31-41
• “Analyze Data Using XY Plot” on page 31-52
• “Log Data to the Workspace and a File Using the Record Block” on page 78-83

30-91
30 Visualizing and Comparing Simulation Results

Sample Time with Scope Blocks

The Scope block and Time Scope block inherit and propagate sample time differently. This example
helps you understand how sample time inheritance works when using a Scope block versus a Time
Scope block. This example also shows what to do when you want to control the sample time
propagation in the model.

The Time Scope block is available with the DSP System Toolbox™.

Default Behavior with Inherited Sample Time

This model shows two sine waves connected to a Time Scope block. The same sine waves are also
connected to a Scope block. All blocks have the default inherited sample time (the Sample Time
parameter equal to -1).

When you run this model, all blocks have continuous sample time. Continuous sample time occurs
because the solver is set to variable step by default and all the blocks are set to inherited sample
time. When you compile the model, Simulink® gives you four warnings that say, " Source block
specifies that its sample time (-1) is back-inherited. You should explicitly
specify the sample time of sources. " This warning helps avoid unwanted sample time
propagation from an incorrectly configured model. To improve clarity, these warnings have been
hidden in this example.

30-92
Sample Time with Scope Blocks

30-93
30 Visualizing and Comparing Simulation Results

Default Behavior with Fixed-Step Solver and Inherited Sample Time

Change the model to discrete sample time by setting the solver to fixed step.

30-94
Sample Time with Scope Blocks

The default plot type for the Scope block is Auto, which means that the plot changes type depending
on the inputs. Because the sample time is now discrete, the Scope block shows a stair plot. The
default plot type of the Time Scope block is a Line plot, so the signal visualization does not change
when the sample time changes to discrete.

30-95
30 Visualizing and Comparing Simulation Results

One Specified Sample Time On the Model

Set the sample time of the first Sine Wave block to 0.03. Specifying one sample time changes the
sample time of the entire model, changing the sample time for the blocks connected to the Sine Wave
block and the ones not connected to the block. Simulink changes the sample rates for all the blocks in
the model because the lowest specified sample time takes precedence over a solver-determined

30-96
Sample Time with Scope Blocks

sample time. The number of warnings drops to three. To improve clarity, these warnings have been
hidden in this example.

One Scope Input with Specified Sample Time

Set the sample time of the Sine Wave2 block to 0.04. Now the Sine Wave and Sine Wave2 blocks
have specified sample times of 0.03 and 0.04 respectively. The scope blocks and Sine Wave input
blocks with inherited sample time, they inherit the sample from the Sine Wave block with the
specified sample time. Now each submodel within this model has a different sample time. All sample
times are based on the sample times specified in the Sine Wave and Sine Wave2 blocks. The number
of warnings drops to two. To improve clarity, these warnings have been hidden in this example.

30-97
30 Visualizing and Comparing Simulation Results

All Inputs with Specified Sample Time

Set the sample time of the Sine Wave1 block to 0.03, and the sample time of the Sine Wave3 block to
0.04. Now the Sine Wave and Sine Wave1 blocks have a sample time of 0.03 and the Sine Wave2
and Sine Wave3 blocks have a sample time of 0.04. There are no warnings now because you have
specified the sample times for all the source blocks.

30-98
Sample Time with Scope Blocks

Inputs with Different Sample Times

Set the sample time for the Sine Wave blocks so that the two inputs to each scope have a different
sample time. Set the sample time in the Sine Wave and Sine Wave2 blocks to 0.03, and the sample
time for the Sine Wave1 and Sine Wave3 blocks to 0.04. When you compile the model, you see that
the Time Scope and Scope behave differently. The sample time for the Simulink Scope resolves to the
fastest discrete rate (FDR). The FDR sample time is 0.01, the greatest common denominator of the
two input rates 0.03 and 0.04. This smaller sample rate means that each signal is oversampled. By
contrast, the sample time for the Time Scope resolves to multirate sample time, meaning each input
is sampled at its own sample time.

In general, the DSP System Toolbox Time Scope uses port-based sample time, which processes the
sample time for each input individually during initialization. Port-based sample time allows for
multiple sample times and sample time offsets. The Simulink Scope uses block-based sample time,
which resolves to a FDR sample time for the block as a whole during the initialization phase of the
simulation.

30-99
30 Visualizing and Comparing Simulation Results

During the simulation phase, the Scope block processes all inputs at the FDR sample rate. This
sample rate can cause oversampling of some inputs. By contrast, during simulation, the Time Scope
block processes a particular port only when a sample hit occurs for that port.

Set Sample Time on Scope Blocks

Until now, the sample times for the scopes were inherited (-1). Set the sample time on both scopes to
0.01 the FDR in the previous section. Simulink issues two warnings, one per scope block, about "
Inconsistent sample times. " There is a mismatch between the specified sample time in the
scopes and their input ports. The warning lets you know the scope decides the sample hits and not
the Simulink engine.

30-100
Sample Time with Scope Blocks

Inputs Inherit Sample Time From Scope

Set the sample time for the Sine Wave1 and Sine Wave4 blocks to inherited (-1). The scope blocks
backpropagate their sample time of 0.01 to these Sine Wave blocks. This change causes the two
inherited sample time warning messages to appear again.

30-101
30 Visualizing and Comparing Simulation Results

Avoid Backpropagation From Scope with Rate Transition Blocks

To avoid backpropagating sample time from the Scope to the blocks connected to it, either set the
sample time on the connected blocks or use rate transition blocks. To specify the sample time on the
connected blocks, set the sample time of Sine Wave1 and Sine Wave3 to 0.04 again.

To use rate transition blocks, insert a Rate Transition block before the Scope and Time Scope blocks.
When you add the rate transition blocks, the two scopes behave identically. Each source with a
specified sample time is connected to a Rate Transition block that resamples the signals at the output
port according to its own rules. A Rate Transition block also prevents propagation of sample times
from one input to another through the scope block.

In this model, each input has a specified sample time and the scope blocks have inherited sample
time.

30-102
Sample Time with Scope Blocks

30-103
30 Visualizing and Comparing Simulation Results

See Also
Scope | Time Scope

More About
• “What Is Sample Time?” on page 7-2
• “View Sample Time Information” on page 7-15
• “How Propagation Affects Inherited Sample Times” on page 7-37
• “Simulink Scope Versus DSP System Toolbox Time Scope” on page 30-8
• “About Sample Times”

30-104
31

Inspecting and Comparing Simulation


Data

• “View Simulation Data in Simulation Data Inspector” on page 31-2


• “Import Data from Workspace or File into Simulation Data Inspector” on page 31-15
• “Import Workspace Variables Using a Custom Data Reader” on page 31-21
• “Import Data Using Custom File Reader” on page 31-27
• “View and Replay Map Data” on page 31-32
• “Visualize Simulation Data on XY Plot” on page 31-41
• “Analyze Data Using XY Plot” on page 31-52
• “View Many Signals Together Using Sparklines” on page 31-60
• “View Multidimensional Signals Using the Array Plot” on page 31-68
• “Microsoft Excel Import, Export, and Logging Format” on page 31-77
• “Import Data from a CSV File into the Simulation Data Inspector” on page 31-85
• “Configure the Simulation Data Inspector” on page 31-90
• “View Streaming Data in the Simulation Data Inspector” on page 31-98
• “Control Display of Streaming Data Using Triggers” on page 31-106
• “Synchronize Cursors in the Simulation Data Inspector with an App Designer App” on page 31-113
• “Iterate Model Design Using the Simulation Data Inspector” on page 31-119
• “Access Data in MATLAB Function During Simulation” on page 31-128
• “Analyze Multidimensional Signal Data” on page 31-131
• “Analyze Data from Multiple Simulations” on page 31-136
• “Save and Share Simulation Data Inspector Data and Views” on page 31-148
• “Create Interactive Comparison Reports” on page 31-154
• “Create Plots Using the Simulation Data Inspector” on page 31-161
• “Inspect Simulation Data” on page 31-179
• “Modify Signal Properties in the Simulation Data Inspector” on page 31-193
• “Replay Data in the Simulation Data Inspector” on page 31-198
• “Compare Simulation Data” on page 31-203
• “How the Simulation Data Inspector Compares Data” on page 31-214
• “Inspect and Compare Data Programmatically” on page 31-219
• “Keyboard Shortcuts for the Simulation Data Inspector” on page 31-225
31 Inspecting and Comparing Simulation Data

View Simulation Data in Simulation Data Inspector

You can use the Simulation Data Inspector to visualize data you generate throughout the design
process, including data that you log during a simulation. You can also import test data and other
recorded data into the Simulation Data Inspector to inspect and analyze it alongside the logged
simulation data. For more information about importing data to the Simulation Data Inspector, see
“Import Data from Workspace or File into Simulation Data Inspector” on page 31-15.

Simulation data that you log in a Simulink model logs to the Simulation Data Inspector. The
Simulation Data Inspector offers several types of plots, which allow you to easily create complex
visualizations of your data. For more information, see “Create Plots Using the Simulation Data
Inspector” on page 31-161.

View Logged Data


Many types of logged data automatically stream to the Simulation Data Inspector when you simulate
a model. Data that streams to the Simulation Data Inspector is also available after simulation. Other
types of logged simulation data only appear in the Simulation Data Inspector when the simulation is
paused, stopped, or complete. To view these types of logged data, open the Configuration Parameters
dialog box and, in the Data Import/Export pane, select Record logged workspace data in
Simulation Data Inspector. For more information about logging simulation data, see “Save
Simulation Data” on page 78-2.

Type of Data That Can Be Viewed During Data That Can Be Viewed Only
Simulation Data and After Simulation After Simulation is Paused,
Stopped, or Complete
Output Output data logged using Dataset Output data logged in a format other
format than Dataset when the Record
logged workspace data in
Simulation Data Inspector
parameter is selected
Signal data Signal data logged using one of these When the Record logged workspace
techniques: data in Simulation Data Inspector
parameter is selected, signal data
• Signal logging logged using:
• A Record block
• A To File block
• A To Workspace block
• A Scope block configured to log
data to the workspace
State State data logged using Dataset State data logged in a format other
format than Dataset when the Record
logged workspace data in
Simulation Data Inspector
parameter is selected
Data store All data store data Not applicable

Note When you log states and outputs using the Structure or Array format, you must also log
time for the data to record to the Simulation Data Inspector.

31-2
View Simulation Data in Simulation Data Inspector

The Simulation Data Inspector displays available data in a table in the Inspect pane. To plot a signal,
select the check box next to the signal. You can modify the layout and add different visualizations to
analyze the simulation data.

The Simulation Data Inspector manages incoming simulation data using the archive. By default, the
previous run moves to the archive when you start a new simulation. You can plot signals from the
archive, or you can drag runs of interest back into the work area.

View Complex Data

The complexSignal model logs two complex signals. The Complex Square Wave signal is logged
using an Outport block. The Complex Sine Wave signal is logged using signal logging. Open the
model.

mdl = "complexSignal";
open_system(mdl)

31-3
31 Inspecting and Comparing Simulation Data

Simulate the model. Then, plot the simulation data in the Simulation Data Inspector.

out = sim(mdl);
Simulink.sdi.plot(out);

You can control how to visualize a complex signal using the Properties pane in the Simulation Data
Inspector. You can choose from these complex format options:

• Magnitude
• Magnitude-Phase
• Phase
• Real-Imaginary

Select the Complex Square Wave signal from the signal table. Then, in the Complex Format drop-
down menu, select Real-Imaginary. If you select Magnitude-Phase or Real-Imaginary for the
Complex Format, the Simulation Data Inspector plots both components of the signal. For signals in
Real-Imaginary format, the Line Color specifies the color of the real component of the signal, and
the imaginary component is a different shade of the Line Color.

31-4
View Simulation Data in Simulation Data Inspector

When you use signal logging to log data, you can also change the default complex format for the
signal using the Instrumentation Properties for the signal in the model. To access the
Instrumentation Properties for the Complex Sine Wave signal, right-click the logging badge for
the signal and select Properties. From the Complex Format drop-down menu, select Magnitude-
Phase.

Simulate the model again to visualize the Complex Sine Wave signal in the Simulation Data
Inspector using the Magnitude-Phase format.

out = sim(mdl);

31-5
31 Inspecting and Comparing Simulation Data

View String Data

You can log and view string data with your signal data in the Simulation Data Inspector. In the model
stringData, the value of the sine wave block controls whether the switch sends a string reading
Positive or Negative to the output. Open the model.
mdl = "stringData";
open_system(mdl)

31-6
View Simulation Data in Simulation Data Inspector

Simulate the model.

out = sim(mdl);

Open the Simulation Data Inspector.

Simulink.sdi.view

Select the Sine Wave and Switch signals from the signal table to plot the results. The string signal
is shown at the bottom of the graphical viewing area.

Select Show/hide data cursors to inspect how the string signal values correspond with the sine
signal's values.

31-7
31 Inspecting and Comparing Simulation Data

When you plot multiple string signals on a plot, the signals stack in the order they were simulated or
imported, with the most recent signal positioned at the top. For example, change the phase of the
sine wave controlling the switch. Then, simulate the model again. In the Simulation Data Inspector,
select all of the signals from both runs to visualize both simulation results on one plot. You can
change the line color to better distinguish between the two runs. The string data from the second run
is stacked on top of the string data from the first run.

31-8
View Simulation Data in Simulation Data Inspector

View Multidimensional Data

You can view and analyze multidimensional signal data in the Simulation Data Inspector. To view a
signal with multidimensional signal values, use the array plot. The model MultiDim contains six Sine
Wave blocks, each vertically displaced from the previous sine wave by one, connected to a Mux block.
Output from the Mux block is logged to the Simulation Data Inspector using an Outport block.

Simulate the model. Then, open the Simulation Data Inspector.

mdl = "MultiDim";
sim(mdl);
Simulink.sdi.view

To plot data on an array plot, click Visualizations and layouts . Then, select Array. When you plot
a signal with multidimensional sample values on an array plot, a stem plot displays the value of each
sample at a given time. The time is shown in the upper right corner of the plot. The dimensions of the
signal are displayed in parentheses next to the signal name. For example, because the
multidimensional signal MultiDimSig contains six channels, the array plot of the data has six
markers.

31-9
31 Inspecting and Comparing Simulation Data

You can also convert the representation of a multidimensional signal from a single signal with
multidimensional sample values to a set of signals with scalar sample values called channels. Once
converted to channels, you can plot the data using time plots, XY plots, maps, or sparklines. To see
the difference between plotting the multidimensional signal on an array plot, and plotting the
individual channels in a time plot, run the simulation again.

sim(mdl);

To convert the multidimensional signal in the second run to channels, click the dimensions of the
signal, shown in parenthesis, next to the signal name in the Simulation Data Inspector. Then, select
Convert to channels.

31-10
View Simulation Data in Simulation Data Inspector

In the Visualizations and layouts menu, select a 2x1 layout. In the lower subplot, plot the signal
with multidimensional sample values from the first run in an array plot. In the upper subplot, plot the
channels from the second run in a time plot. To view the values of each channel at a particular time,
add a cursor to the time plot. To add one cursor to the subplot, click the arrow next to Show/hide data

cursors . Then, choose One cursor.

Notice that the sample values in the array plot change as you drag the cursor. As you move the cursor
through time, the display of each sample value in the array plot changes to show the value of that
element at that particular time. In this case, because both runs contain the same data, the values in
the array plot match the values displayed by the cursor for each corresponding channel in the time
plot. For example, when the cursor is positioned at 3.6 seconds, the time displayed in the upper-right
corner of the array plot is also 3.6 and the value of the first sample in the array plot is equal to the
value displayed by the cursor for the MultiDimSig(1) signal in the time plot.

31-11
31 Inspecting and Comparing Simulation Data

You can also see the values in the array plot change over time by replaying the data. Click Show/hide

replay controls . Then, click Replay .

For more information about inspecting and analyzing multidimensional signal data, including frame-
based data, see “Analyze Multidimensional Signal Data” on page 31-131.

View Frame-Based Data


Some applications buffer several samples of a signal into a frame to process with a single
computation instead of processing each sample in the frame separately. When you work with frame-
based signals, you can analyze the data frame by frame, or you can remove the buffering and analyze
the signal without the frames.

Processing data in frames rather than point by point provides a performance boost needed in some
applications. When you log frame-based signals as sample-based, you can convert the frames in the
Simulation Data Inspector after simulation. For more information about viewing frame-based data in
the Simulation Data Inspector, see “View Multidimensional Signals Using the Array Plot” on page 31-
68.

31-12
View Simulation Data in Simulation Data Inspector

View Event-Based Data

You can log or import event data to the Simulation Data Inspector. In this example, the model
SimpleMessagesModel logs signal data and message data using signal logging. For more
information about the model, see “Animate and Understand Sending and Receiving Messages” on
page 11-6.

mdl = "SimpleMessagesModel";
open_system(mdl)

Simulate the model. During simulation:

• The Sine Wave block generates the sine wave signal.


• Every 0.1 seconds, the Send block converts the value of the sine wave signal to a message and
sends it to the Queue block.
• The Queue block sends messages to the Receive block.
• The Receive block generates the reconstructed sine wave signal.

out = sim(mdl);

Plot the data in the Simulation Data Inspector. The Simulation Data Inspector displays message data
as a stem plot, where the value for the stem is the sample of the sine wave that was taken as the
message payload for the given simulation time.

Simulink.sdi.plot(out);

31-13
31 Inspecting and Comparing Simulation Data

See Also
Functions
Simulink.sdi.createRun | Simulink.sdi.addToRun | Simulink.sdi.view |
Simulink.sdi.plot

See Also

More About
• Inspect Simulation Data on page 31-179
• Compare Simulation Data on page 31-203
• Share Simulation Data Inspector Data and Views on page 31-148
• Decide How to Visualize Data on page 33-2
• “Import Data from Workspace or File into Simulation Data Inspector” on page 31-15

31-14
Import Data from Workspace or File into Simulation Data Inspector

Import Data from Workspace or File into Simulation Data


Inspector

You can import data into the Simulation Data inspector from the base workspace or from a file. Using
the Simulation Data Inspector, you can view imported data on its own or alongside other simulation
data.

The Simulation Data Inspector supports all built-in data types and many data formats, such as
Dataset, timeseries, and timetable, for importing data from the workspace. Whatever the
format, sample values generally must be paired with sample times. The Simulation Data Inspector
allows up to 8000 channels per signal in a run created from imported workspace data.

You can import data from many different types of files, including:

• MAT files
• CSV files — Format data as shown in “Import Data from a CSV File into the Simulation Data
Inspector” on page 31-85.
• Microsoft Excel files — Format data as described in “Microsoft Excel Import, Export, and Logging
Format” on page 31-77.
• MDF files — MDF file import is supported for Linux and Windows operating systems. The MDF file
must have a .mdf, .mf4, or .dat file extension and contain only integer, floating-point, and string
data types in the MDF file channels.
• ULG files — Flight log data import requires a UAV Toolbox license.
• ROS Bag files — ROS Bag file import is supported for file versions 1.1 and 2.0. Bag file import
requires a ROS Toolbox license.

To import data from the workspace or from a file that is saved in a data or file format that the
Simulation Data Inspector does not support, you can write your own workspace data or file reader to
import the data using the io.reader class. You can also write a custom reader to use instead of the
built-in reader for supported file types. For examples, see:

• “Import Data Using Custom File Reader” on page 31-27


• “Import Workspace Variables Using a Custom Data Reader” on page 31-21

Import Data From Workspace

You can import time-based data from the workspace into the Simulation Data Inspector. Create
timeseries objects that contain data for a sine signal and a cosine signal. Give each timeseries
object a descriptive name.

time = 0:0.1:10;

sinVals = sin(time);
cosVals = cos(time);

sinTS = timeseries(sinVals,time,"Name","Sine");
cosTS = timeseries(cosVals,time,"Name","Cosine");

Open the Simulation Data Inspector.

31-15
31 Inspecting and Comparing Simulation Data

Simulink.sdi.view

To import data interactively, in the Simulation Data Inspector, select Import . In the Import
dialog box, you can choose to import data from the workspace or from a file. The table below the
options shows data available for import. If you do not see your workspace variable or file contents in
the table, that means the Simulation Data Inspector does not have a built-in or registered reader that
supports that data. You can select which data to import using the check boxes, and you can choose
whether to import that data into an existing run or a new run. To select all or none of the data, use
the check box next to NAME.

In the Import dialog box:

• Under Import from, select Base workspace.


• Under To, select New run.
• In the signal table, select the Sine and Cosine signals.
• Click Import.

31-16
Import Data from Workspace or File into Simulation Data Inspector

31-17
31 Inspecting and Comparing Simulation Data

When you import data into a new run, the run always appears in the work area. You can manually
move imported runs to the archive.

Select signals from the signal table to view data in the Simulation Data Inspector. To create two
vertically aligned subplots, click Visualizations and layouts . Then, under Basic layouts, select a
2x1 subplot layout. Plot the Cosine signal in the upper subplot and plot the Sine signal in the lower
subplot.

Import Data From File

The MAT-file fuelsysRunData contains signal data from one run of the sldemo_fuelsys model.
For more information about the model, see “Model Fault-Tolerant Fuel Control System”.

Open the Simulation Data Inspector.

Simulink.sdi.view

To import data from the fuelsysRunData file into the Simulation Data Inspector, click Import .
In the Import dialog box:

31-18
Import Data from Workspace or File into Simulation Data Inspector

• Under Import from, select File. Then, type the file name or navigate the file system to select the
FuelsysRunData file.
• Under To, select New run.
• In the signal table, select the checkbox next to NAME to select all the signals.
• Click Import.

In the Simulation Data Inspector, use the sparklines visualization to view the data. Click
Visualizations and layouts . Then, under Visualizations, select Sparklines. Select signals from
the signal table to view them in the sparklines plot.

31-19
31 Inspecting and Comparing Simulation Data

See Also
Functions
Simulink.sdi.createRun | Simulink.sdi.addToRun | Simulink.sdi.view

More About
• “Microsoft Excel Import, Export, and Logging Format” on page 31-77
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Import Data Using Custom File Reader” on page 31-27
• “Import Workspace Variables Using a Custom Data Reader” on page 31-21
• Compare Simulation Data on page 31-203

31-20
Import Workspace Variables Using a Custom Data Reader

Import Workspace Variables Using a Custom Data Reader

When your workspace data is in a format that built-in readers do not support, you can write a custom
data reader to import the data into the Simulation Data Inspector. This example explains the parts of
the class definition for a custom workspace reader and shows how to register the reader with the
Simulation Data Inspector. Open the SimpleStructReader.m file to view the complete class
definition.

Create Workspace Data

First, create workspace data to import into the Simulation Data Inspector using the custom reader.
Suppose you store each signal as a structure with fields for the data (d), the time values (t), and the
signal name (n).
time = 0:0.1:100;
time = time';
lineData = 1/4*time;
sineWave = sin((2*pi)/50*time);
squareWave = square((2*pi)/30*time);

mySineVar.d = sineWave;
mySineVar.t = time;
mySineVar.n = "Sine Wave";

myLineVar.d = lineData;
myLineVar.t = time;
myLineVar.n = "Line";

mySquareVar.d = squareWave;
mySquareVar.t = time;
mySquareVar.n = "Square Wave";

Write the Class Definition for a Custom Reader

Write a class definition that specifies how the custom reader extracts relevant data and metadata
from the workspace variables. Save the class definition file in a location on the MATLAB™ path.

The class definition starts by inheriting from the io.reader class, followed by property and method
definitions. The custom reader in this example defines the property ChannelIndex. You can use the
reader to import individual structures or an array of structures from the workspace. The
ChannelIndex property is used when importing an array of structures.
classdef SimpleStructReader < io.reader

properties
ChannelIndex
end

Every custom reader must define the getName, getTimeValues, and getDataValues methods.
When you write a custom reader to import data from the workspace, you must also define the
supportsVariable method. The reader in this example also defines the getChildren method to
support importing an array of structures.

The supportsVariable method checks which variables in the workspace are supported by the
reader. In this example, the supportsVariable returns true when:

31-21
31 Inspecting and Comparing Simulation Data

1 The structure contains the appropriate fields.


2 The n field of the structure contains a string or character array that represents the signal name.
3 The t field of the structure is a column vector of double data.
4 The d field contains numeric data.
5 The d field is the same size as the t field, meaning there is a sample value for each time step.
function supported = supportsVariable(~, val)
% Support structure with fields t (time), d (data), and n (name)
supported = ...
isstruct(val) && ...
isfield(val,'t') && ...
isfield(val,'d') && ...
isfield(val,'n');
if supported
for idx = 1:numel(val)
varName = val(idx).n;
time = val(idx).t;
varData = val(idx).d;

% Name must be string or character array


if ~ischar(varName) && ~isstring(varName)
supported = false;

% Time must be double column vector


elseif ~isa(time,'double') || ~iscolumn(time)
supported = false;

% Data size must match time size


else
timeSz = size(time);
dataSz = size(varData);

if ~isnumeric(varData) || ~isequal(dataSz, timeSz)


supported = false;
end
end
end
end
end

The getChildren method creates a SimpleStructReader object for each structure in an array of
structures. When the variable to import is not scalar, the getChildren method assigns a value to the
ChannelIndex property added to the class for the custom reader. The VariableValue property for
each SimpleStructReader object returned by the getChildren method is the array of structures.
Other methods use the ChannelIndex property to extract the appropriate signal name, signal data,
and time values from each object.
function childObj = getChildren(obj)
childObj = {};
if ~isscalar(obj.VariableValue) && isempty(obj.ChannelIndex)
numChannels = numel(obj.VariableValue);
childObj = cell(numChannels,1);
for idx = 1:numChannels
childObj{idx} = SimpleStructReader;
childObj{idx}.VariableName = sprintf('%s(%d)',obj.VariableName,idx);
childObj{idx}.VariableValue = obj.VariableValue;

31-22
Import Workspace Variables Using a Custom Data Reader

childObj{idx}.ChannelIndex = idx;
end
end
end

The getName method assigns the name stored in the n field of the structure to each imported signal.
When the imported variable is scalar, the method gets the name from the VariableValue property
of the SimpleStructReader object. When the imported data is an array of structures, the
appropriate structure is extracted from the VariableValue property using the ChannelIndex
property. The top-level node of the array is named Signal Array.

function retName = getName(obj)


if isscalar(obj.VariableValue)
retName = char(obj.VariableValue.n);
elseif ~isempty(obj.ChannelIndex)
varVal = obj.VariableValue(obj.ChannelIndex);
retName = char(varVal.n);
else
retName = 'Signal Array';
end
end

The getTimeVals and getDataVals methods handle scalar and nonscalar structures similar to how
the getName method does. For a scalar structure, both methods extract the appropriate field from
the VariableValue property of the SimpleStructReader object. For a nonscalar structure, both
methods access the appropriate structure in the VariableValue property using the ChannelIndex
property. Finally, for the top-level node of the array, time and data are both returned as empty.

function timeVals = getTimeValues(obj)


if isscalar(obj.VariableValue)
timeVals = obj.VariableValue.t;
elseif ~isempty(obj.ChannelIndex)
varVal = obj.VariableValue(obj.ChannelIndex);
timeVals = varVal.t;
else
timeVals = [];
end
end

function dataVals = getDataValues(obj)


if isscalar(obj.VariableValue)
dataVals = obj.VariableValue.d;
elseif ~isempty(obj.ChannelIndex)
varVal = obj.VariableValue(obj.ChannelIndex);
dataVals = varVal.d;
else
dataVals = [];
end
end

Register a Custom Reader

After you write the class definition for the custom reader, you must register the reader before you can
use it to import data into the Simulation Data Inspector. The Simulation Data Inspector does not store
registered readers between MATLAB sessions, so you need to register a custom reader at the start of
each new MATLAB session. To register the workspace data reader in this example, use the
registerWorkspaceReader method.

31-23
31 Inspecting and Comparing Simulation Data

registerWorkspaceReader(SimpleStructReader);

To confirm that the reader is registered, use the io.reader.getRegisteredWorkspaceReaders


method.

io.reader.getRegisteredWorkspaceReaders

ans =
"SimpleStructReader"

Import Workspace Data in a Custom Format

Once you register the custom workspace data reader, you can import workspace variables stored
using the custom format into the Simulation Data Inspector using the UI or the
Simulink.sdi.createRun function.

To import data using the UI, open the Simulation Data Inspector. You can use the
Simulink.sdi.view function to open the Simulation Data Inspector from the MATLAB Command

Window. Then, select Import .

The Import dialog box shows the data in the base workspace that the Simulation Data Inspector is
able to import using built-in and registered custom readers. Because the custom reader is registered,
the Line, Sine Wave, and Square Wave signals are available for import, while the lineData,
sineWave, and squareWave variables are not. Select the data you want to import and select
Import. To import all or none of the data, you can select or clear the check box next to NAME. The
data imports into a run called Imported_Data.

31-24
Import Workspace Variables Using a Custom Data Reader

To import data from the workspace programmatically, use the Simulink.sdi.createRun function.

Simulink.sdi.createRun('Custom Workspace Data Run','vars',myLineVar,mySineVar,mySquareVar);

The custom reader in this example can also import an array of structures. Importing an array of
workspace variables rather than importing them individually groups the variables together when you
import the data to an existing run. Create an array that contains the myLineVar, mySineVar, and
mySquareVar structures, and import the array using the Simulink.sdi.createRun function.

myVarArray = [myLineVar; mySineVar; mySquareVar];


Simulink.sdi.createRun('Workspace Array Run','vars',myVarArray);

31-25
31 Inspecting and Comparing Simulation Data

Inspect and Analyze Imported Data

After importing data, you can use the Simulation Data Inspector to inspect and analyze the imported
data on its own or alongside related simulation data.

See Also
Classes
io.reader

Functions
Simulink.sdi.createRun

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Import Data Using Custom File Reader” on page 31-27

31-26
Import Data Using Custom File Reader

Import Data Using Custom File Reader

When you want to visualize data stored in a data or file format the Simulation Data Inspector does not
support, you can use the io.reader class to write your own custom file reader for the Simulation
Data Inspector. This example explains the parts of a class definition for a custom file reader and
demonstrates how to register the reader with the Simulation Data Inspector. Open the
ExcelFirstColumnTimeReader.m file to view the complete class definition.

Write Class Definition for Custom Reader

Write a class definition that specifies how your custom reader extracts relevant data and metadata
from files and variables that use custom formats. Save the class definition file in a location on the
MATLAB™ path.

The custom reader in this example uses the readtable function to load data from a Microsoft
Excel™ file and uses the first column in the file as time data.

The class definition starts by inheriting from the io.reader class, followed by method definitions
that return required and relevant data and metadata.

classdef ExcelFirstColumnTimeReader < io.reader

Every custom reader must define the getName, getTimeValues, and getDataValues methods.
Additional methods are available to access certain metadata that might exist in the custom file. The
class definition for this example defines the abstract methods as well as the supportsFile and
getChildren methods.

The supportsFile method checks the file contents to make sure the file contains signal data.

function supported = supportsFile(~,filename)


try
t = readtable(filename);
supported = height(t) > 0 && numel(t.Properties.VariableNames) > 1;
catch
supported = false;
end
end

To import multiple signals from a file, treat the data as hierarchical with the file being the top node.
The reader uses the getChildren method to create an ExcelFirstColumnTimeReader object for
each signal in the file.

function childObj = getChildren(obj)


childObj = {};
if isempty(obj.VariableName)
t = readtable(obj.FileName);
vars = t.Properties.VariableNames;
vars(1) = [];
childObj = cell(size(vars));
for idx = 1:numel(vars)
childObj{idx} = ExcelFirstColumnTimeReader;
childObj{idx}.FileName = obj.FileName;
childObj{idx}.VariableName = vars{idx};
end

31-27
31 Inspecting and Comparing Simulation Data

end
end

The getTimeValues method reads the data in the file using the readtable function and returns the
data in the first column for the Simulation Data Inspector to use as time data.

function timeVals = getTimeValues(obj)


timeVals = [];
if ~isempty(obj.VariableName)
t = readtable(obj.FileName);
timeName = t.Properties.VariableNames{1};
timeVals = t.(timeName);
end
end

The getName method uses the file name as the name for the top-level node of the imported data.
Signals are named using the VariableName property for the corresponding
ExcelFirstColumnTimeReader object returned by the getChildren method.

function retName = getName(obj)


if isempty(obj.VariableName)
fullName = obj.FileName;
[filepath,name,ext] = fileparts(fullName);
retName = strcat(name,ext);
else
retName = obj.VariableName;
end
end

The getDataValues method returns the data in each column that has data besides the first as signal
data. Data for each signal is accessed using the VariableName property for the corresponding
object returned by the getChildren method.

function dataVals = getDataValues(obj)


dataVals = [];
if ~isempty(obj.VariableName)
t = readtable(obj.FileName);
dataVals = t.(obj.VariableName);
end
end

Register Custom Reader for Simulation Data Inspector

After you write the class definition file for the custom data reader, you need to register the reader
with the Simulation Data Inspector before you can use it to import data. The Simulation Data
Inspector does not store registered readers between MATLAB sessions, so you need to register a
custom reader at the start of each new MATLAB session. You can register a custom reader to read
data from the workspace or to read data from a file. To register the file reader in this example, use
the registerFileReader method.

registerFileReader(ExcelFirstColumnTimeReader,[".xlsx" ".xls"]);

To confirm that the file reader is registered, use the io.reader.getRegisteredFileReaders


method.

io.reader.getRegisteredFileReaders

31-28
Import Data Using Custom File Reader

ans =
"ExcelFirstColumnTimeReader"

Import Data from File in Custom Format

Once you register the custom file reader, you can import data from a file in a custom format using the
Simulation Data Inspector UI or using the Simulink.sdi.createRun function. This example
imports a simple data set from a file that contains four columns of data. The custom file reader in this
example always loads the first column, in this case a, as time data.

To import the data using the UI, open the Simulation Data Inspector. You can use the
Simulink.sdi.view function to open the Simulation Data Inspector from the MATLAB Command

Window. Then, click Import .

In the Import dialog, select the File option and import the data from the file into a new run. Click the
folder to browse the file system and select the file you want to import. The file for this example is
called CustomFile.xlsx.

After you select a file with an extension that corresponds to one or more registered custom readers,
an option to select the reader you want to use appears in the dialog. In this example, you can choose
between the built-in Microsoft Excel file reader or the custom reader written for this example. By
default, a custom reader is selected when one is available for the extension of the selected file.

31-29
31 Inspecting and Comparing Simulation Data

You can choose which signals you want to import from the file. Use the check box next to NAME to
select all or none of the signals. After making your selection, click Import. The data is imported to a
new run called Imported_Data.

To import data programmatically, you can use the Simulink.sdi.createRun function. The
Simulation Data Inspector has a built-in reader for Microsoft Excel files. You can specify which reader
to use to import the data in the call to the Simulink.sdi.createRun function. When you do not
specify the reader you want to use to import the data, the Simulation Data Inspector uses the first
custom reader that supports the file extension.

Simulink.sdi.createRun("Custom File Run","file","CustomFile.xlsx","ExcelFirstColumnTimeReader");

After importing your data, you can use the Simulation Data Inspector to inspect and analyze the
imported data on its own or alongside related simulation data.

31-30
Import Data Using Custom File Reader

The Simulation Data Inspector stores custom readers for the duration of a MATLAB session. To
unregister a custom reader without starting a new session, use the unregisterFileReader
method.

unregisterFileReader(ExcelFirstColumnTimeReader, [".xlsx" ".xls"])

See Also
Classes
io.reader

Functions
Simulink.sdi.createRun

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2

31-31
31 Inspecting and Comparing Simulation Data

View and Replay Map Data

This example shows how to use the map visualization in the Simulation Data Inspector to view routes
of longitude and latitude data. The map data is synchronized with signal data, which allows you to
analyze signal activity throughout the route by adding cursors and by replaying the data.

The map visualization used in this example is also available in the Record block. When you use the
map visualization in the Record block, you add the visualization and configure the appearance using
the toolstrip. You plot data on the map the same way shown in this example.

To view map data in the Simulation Data Inspector or Record block, you must have an active internet
connection.

Import Route Data into Simulation Data Inspector

If your model includes latitude and longitude signals, you can view logged data on the map during
simulation. You can also import data from the workspace or a file.

Open the Simulation Data Inspector.

Simulink.sdi.view

The data for this example is stored in the Excel™ file LoganTripGPSData.xlsx. To import the data

using the user interface, click Import .

In the Import dialog box, under Import from, select File. Then, enter LoganTripGPSData.xlsx in
the text box and click Import.

Alternatively, import the data programmatically using the Simulink.sdi.createRun function.

mapRun = Simulink.sdi.createRun("LoganTrip","file","LoganTripGPSData.xlsx");

Plot Route on Map

By default, the Simulation Data Inspector uses time plots for each subplot in the layout. To plot data
on a map, you need to add the visualization to the layout.

To add a map to your layout, click Visualizations and layouts . Then, click or drag the Map icon
from Visualizations onto the subplot.

31-32
View and Replay Map Data

To plot a route on the map, assign latitude and longitude data.

1 Select the logan_lat signal.


2 In the Connect dialog box, select Latitude and click OK.
3 Select the logan_long signal.
4 In the Connect dialog box, select Longitude and click OK.

31-33
31 Inspecting and Comparing Simulation Data

Plot Signal Data Alongside Route

Change the subplot layout in the plot area to a 2-by-1 layout so you can plot the speed data alongside

the route. Click Visualizations and Layouts . Then, under Basic Layouts, select the subplot
layout in a 2-by-1 configuration.

31-34
View and Replay Map Data

To plot the speed data on the bottom subplot, select the subplot, then select the check box next to the
speed signal in the table.

31-35
31 Inspecting and Comparing Simulation Data

Click the white circle to get more information about the Starting Position.

To get more information about the Destination, click the red marker.

31-36
View and Replay Map Data

Analyze Data Using Cursors

You can add cursors to the plots to analyze the relationship between the speed signal and the route
shown on the map. To add two cursors to the layout, click the drop-down arrow on the Show/hide

data cursors button and select Two Cursors.

When you add cursors, additional orange markers appear on the map. The Starting Position and the
Destination for the route have static markers. An additional marker corresponds to each cursor in
the time plot.

31-37
31 Inspecting and Comparing Simulation Data

In the lower subplot, move the cursor on the left. The marker on the right of the map moves as you
move the left cursor because the route starts in Boston and moves from east to west over time.

31-38
View and Replay Map Data

To remove the cursors from the plot, click Show/hide data cursors .

Replay Route and Signal Data

In the Simulation Data Inspector, you can replay data to analyze relationships among plotted signals
in your view. When you replay data in the Simulation Data Inspector, animated cursors sweep through
the plotted data from the start time to the end time. To add the replay controls to the view, click

Show/hide replay controls . Then, click Replay .

A marker on the map and a cursor on the time plot sweep synchronously across the screen. By
default, the Simulation Data Inspector replays data at one second per second, meaning that the
cursor moves through one second of data in one second of clock time. The data for this trip spans
approximately 34 minutes. You can increase the replay speed using the arrow to the right of the label
or by clicking the label and typing the desired speed. Increase the replay speed to 32x using the
arrow.

31-39
31 Inspecting and Comparing Simulation Data

See Also
Tools
Simulation Data Inspector

Blocks
Record

Functions
Simulink.sdi.createRun

Related Examples
• “Replay Data in the Simulation Data Inspector” on page 31-198

31-40
Visualize Simulation Data on XY Plot

Visualize Simulation Data on XY Plot

This example shows how to plot data on an XY plot in the Simulation Data Inspector and use the
replay controls to analyze relationships among plotted signals. You run two simulations of the model
ex_sldemo_bounce and analyze the relationship between the position and velocity for a bouncing
ball.

The XY plot used in this example is also available in the Record block and the XY Graph block. When
you use the XY plot in the Record block and the XY Graph block, you add the visualization and
configure the appearance using the toolstrip. You plot data on the XY plot the same way shown in this
example.

Simulate Model

Open the model ex_sldemo_bounce, which simulates the dynamics of a bouncing ball.

open_system("ex_sldemo_bounce")

Because the model is configured to log output data, the position and velocity signals connected to the
Outport blocks log to the workspace and the Simulation Data Inspector.

To simulate the model, click Run. Then, under Review Results, click Data Inspector to open the
Simulation Data Inspector.

Alternatively, you can simulate the model and open the Simulation Data Inspector programmatically.

out = sim("ex_sldemo_bounce");
Simulink.sdi.view

31-41
31 Inspecting and Comparing Simulation Data

Plot Data on XY Plot

By default, the Simulation Data Inspector uses time plots for each subplot in the layout. To plot the
data on an XY plot, add the visualization to the layout. Click Visualizations and layouts, then click or
click and drag the XY icon onto the subplot.

To plot the signals on the XY plot, in the signal table, select the signals you want to plot. Then, assign
the signal pairs to the x- and y-axes. For this example:

1 Select the check boxes next to the Position and Velocity signals.
2 In the XY Data dialog box, use the drop-down menus in row 1 to assign Position to the x-Axis
and Velocity to the y-Axis.
3 Click OK.

31-42
Visualize Simulation Data on XY Plot

You can also use the XY Data dialog box to:

• Swap x and y data selections using the Swap button.


• Add more pairs of x and y data using the drop-down menus in the next row.

You can modify the appearance of the XY plot using the Visualization Settings. To access the
Visualization Settings for the XY plot, click Visualization Settings.

By default, data is shown as a scatter plot. The color of the marker fill matches the y-axis signal and
the color of the marker border matches the x-axis signal color. You can select or clear Line and
Markers to display only markers, only lines, or both markers and connecting lines. The line and
marker colors can match the color of the signal that provides the x data or the signal that provides
the y data. Specified settings apply for all XY plots in the layout.

You can also change the limits of the x-axis and y-axis from the Visualization Settings. To change the
limits, first, clear Autoscale. Then, enter new values for the x and y limits. These limits apply to the
currently selected XY subplot. By default, Autoscale is selected, which performs a fit-to-view on the
XY subplot.

31-43
31 Inspecting and Comparing Simulation Data

Add Time Plots and Inspect Data

You can include multiple visualizations in a layout in the Simulation Data Inspector, Record block, or
XY Graph block. For example, change to a layout with three subplots so you can see each signal on a
time plot alongside the XY plot.

To change the subplot layout, click Visualizations and layouts. Then, in the Basic Layouts section,
select the layout with two subplots on top of a third subplot.

Plot the Position signal on the upper-right time plot, and plot the Velocity signal on the bottom
time plot. To plot a signal on a time plot, select the subplot where you want to plot the signal, then
select the check box next to the signal you want to plot.

31-44
Visualize Simulation Data on XY Plot

To inspect the data, add a cursor. In the XY plot, the vertical line of the cursor shows the x-axis value,
and the horizontal line shows the y-axis value. The time that corresponds to the point is displayed in
the upper-right of the plot.

Move the cursor in the XY plot along the plotted line. You can also move the cursor in the XY plot
using the arrow keys on your keyboard or by pausing on a point on the line and clicking the
highlighted point.

31-45
31 Inspecting and Comparing Simulation Data

When you drag the cursor in a time plot, the cursor in the XY plot moves synchronously through the
plotted data. The XY plot can only have one cursor. When you add two cursors to the layout, the XY
cursor moves with the left cursor in the time plot.

Replay Data

Now that you have a comprehensive visualization of the simulation data, replaying the data can help
you understand the relationship between the signals. When you replay data in the Simulation Data
Inspector, animated cursors sweep through the logged simulation data from the start time to the end
time. Add the replay controls to the view by clicking Show/hide replay controls.

You can control the speed of the replay and pause at any time. By default, the Simulation Data
Inspector replays data at one second per second, meaning the cursor moves through one second of
data in one second of clock time. The data in this example spans 25 seconds. Slow the replay speed
by clicking the arrow to the left of the label.

31-46
Visualize Simulation Data on XY Plot

For more information about using replay controls, see “Replay Data in the Simulation Data Inspector”
on page 31-198.

Analyze Data from Multiple Simulations

To analyze how changes in simulation parameters affect the data, you can plot multiple series on an
XY plot. Simulate the model again using a higher initial velocity for the ball.

Using the Simulink® Editor or the MATLAB™ Command Window, change the Initial value
parameter of the Initial Velocity block to 25. Then, simulate the model.
set_param("ex_sldemo_bounce/Initial Velocity",'Value','25')
sim('ex_sldemo_bounce');

The Simulation Data Inspector moves the first run to the archive and transfers the view to the new
run. To adjust the zoom level for the signals from the new run, click Fit to View.

Drag the first run from the archive into the work area. Then, use the run actions menu to copy the
plotted signal selection from the current run to the first run.

To copy the plotted signal selection from the current run, click the three dots on the right of the row
for the current run. Then, under Plotted signal selection, select Copy.

31-47
31 Inspecting and Comparing Simulation Data

To plot data from the first run, paste the plotted signal selection onto the run. Click the three dots on
the right of the row for the first run. Then, under Plotted signal selection, select Paste.

31-48
Visualize Simulation Data on XY Plot

The signals in both runs have the same names and the same signal colors. Change the colors for the
signals in the first run.

1 Click the representation of the line in the table.


2 Select a new color.
3 Click Set.

The signals in both runs also have the same name. To determine which run contains a plotted signal,
you can use the tooltip in the legend.

You can also rename the signals. For example, rename the signals in the first run to Position-1 and
Velocity - 1. To rename a signal, double-click the name in the table and enter a new name.

When you add multiple series to an XY plot, each series gets a cursor. All cursors on the XY plot move
synchronously, so all signal values displayed on the cursors correspond to the same time.

31-49
31 Inspecting and Comparing Simulation Data

You can manage the signals plotted on an XY plot using the XY Data dialog box. Right-click the XY
plot to access the subplot context menu. Then, select Show plotted signals. Using the XY Data
dialog box, you can remove an x, y data pair from the plot or modify which signals provide the x-data
and y-data for each data pair.

31-50
Visualize Simulation Data on XY Plot

See Also
Blocks
Record

Tools
Simulation Data Inspector

Related Examples
• “Analyze Data Using XY Plot” on page 31-52
• “Plot a Circle Using the XY Graph Block” on page 30-88

31-51
31 Inspecting and Comparing Simulation Data

Analyze Data Using XY Plot

This example shows how to analyze data plotted on an XY plot in the Simulation Data Inspector using
trend lines.

The XY plot used in this example is also available in the Record block and the XY Graph block. When
you use the XY plot in the Record block and the XY Graph block, you add the visualization and
configure the appearance using the toolstrip. You plot data on the XY plot the same way shown in this
example.

Import Data into Simulation Data Inspector

Open the Simulation Data Inspector.

Simulink.sdi.view

The data for this example is stored in the MAT file XYData.mat. To import the data using the UI,

click Import .

In the Import dialog box, under Import from, select File. Then, enter XYData.mat in the text box
and click Import.

Alternatively, import the data programmatically using the Simulink.sdi.createRun function.

xyRunID = Simulink.sdi.createRun("XY signals","file","XYData.mat");

Plot Data on XY Plot

By default, the Simulation Data Inspector uses time plots for each subplot in the layout. To plot the
data on an XY plot, you need to add the visualization to the layout.

To add an XY plot to your layout, click Visualizations and layouts . Then, from Visualizations,
click or click and drag the XY icon onto the subplot.

31-52
Analyze Data Using XY Plot

To plot signals on the XY plot, select signals in the table. Then, assign signal pairs to the x-Axis and
y-Axis of a row in the XY Data dialog box. By default, the first signal you click is assigned to the x-
Axis, and the second signal you click is assigned to the y-Axis of the same row. If you select more
than two signals, the software assigns the data to the next row starting with the x-Axis. You can
reassign signals using the drop-down menus.

31-53
31 Inspecting and Comparing Simulation Data

For example, select the check box next to the Heart-X signal. Then, select the check box next to the
Heart-Y signal. Because you selected the Heart-X signal first, the software assigns Heart-X to the
x-Axis and Heart-Y to the y-Axis. Click OK.

You can modify the appearance of XY plots in the layout using the Visualization Settings. To access

the visualization settings for the XY plot, click Visualization Settings .

By default, data is displayed as a scatter plot with the marker fill matching the y-axis signal color and
the marker border matching the x-axis signal color. You can select or clear Line and Markers to
display only markers, only lines, or both markers and connecting lines. The line and marker colors
can match the color for the signal that provides the x data or the color for the signal that provides the
y data. Specified settings apply for all XY plots in the layout.

You can also change the limits of the x-axis and y-axis from the Visualization Settings . To change
the limits, first, clear Autoscale. Then, enter new values for the x and y limits. These limits apply to
the currently selected XY subplot. By default, Autoscale is selected, which performs a fit-to-view on
the XY subplot.

31-54
Analyze Data Using XY Plot

Analyze XY Data Using Trend Lines

You can add a trend line to an XY plot to analyze the relationship between the x- and y-data. The
trend line is most useful when the relationship can be expressed as a function. The Heart-X and
Heart-Y data plotted in the prior section is not well-suited for analysis with trend lines because the
y-data is not well correlated with the x-data.

The example data includes x- and y-data well-suited for each type of trend line available. You can try
plotting each pair of signals to see how each trend line helps you analyze the data. For example, plot
the Poly-X and Poly-Y signals on the XY plot:

1 Clear the check boxes next to the Heart-X and Heart-Y signals in the table.
2 Select the check box next to the Poly-X. Then, select the Poly-Y signal.
3 The software automatically assigns Poly-X to the x-Axis and Poly-Y to the y-Axis of the first
row.
4 Click OK.

To add a trend line, click Visualization Settings and select Trend line. From the Type list, select
Polynomial.

31-55
31 Inspecting and Comparing Simulation Data

By default, the Simulation Data Inspector computes the polynomial trend line in the form of a third-
order polynomial. To see the equation for the trend line as well as information about how it fits the
data, pause on the trend line. The tooltip for the trendline shows:

• The names of the signals that provide the x- and y- data for the series.
• The coordinates for the trend line point closest to the pointer.
• The trend line equation and R-squared value.

31-56
Analyze Data Using XY Plot

When you use a polynomial trend line, you can specify the order of the polynomial between 2 and 6,
inclusive. For example, change the order of the polynomial trend line to 2 to see how it affects the fit
of the trend line. Open the visualization settings for the XY plot. Then, in the text box next to the
trend line type selection, enter 2.

When you use a second-order polynomial, the trend line does not fit the start of the data as well.

31-57
31 Inspecting and Comparing Simulation Data

Try other trend line options to see how they fit the Poly-X and Poly-Y data. You can add these types
of trend line to the XY plot:

• Linear: Trend line equation has the form y = mx + b.


• Logarithmic: Trend line equation has the form y = a ln x + b. The x-data must not contain 0 or
negative values.
• Polynomial: Trend line equation has the form y = b6x6 . . . + b2x2 + b1x + a, where the number of
terms is determined by the specified order.
• Exponential: Trend line equation has the form y = aebx. The y-data must not contain 0 or
negative values.
• Power: Trend line equation has the form y = axb. The x- and y-data must not contain 0 or negative
values.

Try plotting other pairs of signals in the XY plot and explore how each trend line option fits each data
set.

See Also
Blocks
Record

31-58
Analyze Data Using XY Plot

Tools
Simulation Data Inspector

Related Examples
• “Visualize Simulation Data on XY Plot” on page 31-41
• “Plot a Circle Using the XY Graph Block” on page 30-88

31-59
31 Inspecting and Comparing Simulation Data

View Many Signals Together Using Sparklines

This example shows how to use the sparklines visualization in the Simulation Data Inspector to easily
plot and view many signals at once.

The sparklines visualization used in this example is also available in the Record block. When you use
the sparklines plot in the Record block, you add the visualization and configure the appearance using
the toolstrip. You plot data on the sparklines plot the same way shown in this example.

Simulate Model

This example plots signals logged from a simulation of the model sldemo_fuelsys.

Open the model.

mdl = "sldemo_fuelsys";
open_system(mdl);

To simulate the model, click Run. Then, under Review Results, click Data Inspector to open the
Simulation Data Inspector.

Alternatively, simulate the model and open the Simulation Data Inspector programmatically.

out = sim(mdl);
Simulink.sdi.view

Plot Data on Sparklines Plot

By default, the Simulation Data Inspector uses time plots for each subplot in the layout. To plot the

data on a sparklines plot, add the visualization to the layout. Click Visualizations and layouts .
From Visualizations, click or drag the Sparklines icon onto the subplot.

31-60
View Many Signals Together Using Sparklines

31-61
31 Inspecting and Comparing Simulation Data

The Simulation Data Inspector can group logged data by domain, which indicates the type or source
of the data. To group data by domain:

Click Preferences .
2 In the Group pane, select Domain from the drop-down list.

Expand the Signals group. You can add sparklines for the signals one by one by selecting the check
box next to each signal you want to plot, or you can select a group of signals to drag onto the plot.
Each signal is shown on its own sparkline.

31-62
View Many Signals Together Using Sparklines

If you want to view more than one signal in a single sparkline, you can drag the signal line from one
sparkline onto another. The sparkline for the signal you move disappears, and both signals are shown
together on the sparkline where you drag the signal. For example, drag the ego signal into the top
sparkline.

31-63
31 Inspecting and Comparing Simulation Data

You can also reorder the sparklines by dragging the signal line and dropping it between two
sparklines where you want that signal to appear. For example, drag the ego signal out of the top
sparkline and drop it in between the first and second sparklines.

Inspect Data on Sparklines

You can add cursors to the sparklines plot to see the value for each signal at a given time. You can
also use the replay controls with sparklines to inspect how the signal values change relative to each
other over time. When you pan or zoom in a given sparkline, all other sparklines remain
synchronized.

31-64
View Many Signals Together Using Sparklines

You can modify the appearance of a sparklines plot using the Visualization Settings and the subplot

menu. To access the Visualization settings for the sparklines plot, click Visualization settings .

For example, increase the minimum height for each sparkline to 130 px. The values you specify in
the Visualization settings are specific to a single sparklines visualization and apply to all sparklines
within that sparklines plot.

With the larger minimum height, all the sparklines are not visible at once, and a scroll bar allows you
to view all the signals. To scroll down, select the scroll bar with your mouse and drag.

31-65
31 Inspecting and Comparing Simulation Data

You can modify settings that apply only to a single sparkline within the sparklines plot using the
subplot menu. For example, change the y-axis limits for the sparkline that displays the ego signal.

To open the subplot menu for the sparkline, pause on the sparkline then click the three dots that
appear.

To open the sparkline-specific visualization settings, click Sparkline settings . In the menu that
appears, change the minimum value for the y-axis to 0.

31-66
View Many Signals Together Using Sparklines

To clear the Sparkline Settings menu, click outside the menu.

View Data on a Sparklines Plot During Simulation

During simulation, plotted signals stream data to the sparklines visualization. You can control how the
signal data is displayed as well as how and when the sparklines update using the Update mode and

Time span settings in the Visualization settings . Change Update mode to Scroll and set
Time span to 100. Then, simulate the model again.

out = sim(mdl);

By default, the Simulation Data Inspector automatically moves the previous run into the archive and
plots signals from the current simulation in the place of plotted signals from the prior simulation. To
inspect a signal of interest during simulation, you can pause the drawing of a streaming signal by

clicking Hold .

Before 2023b: Click Freeze display to prevent wrapping or scrolling of the display.

Alternatively, you can use a trigger to control when the sparklines plot updates. For more
information, see “Control Display of Streaming Data Using Triggers” on page 31-106

See Also
Blocks
Record

Tools
Simulation Data Inspector

Related Examples
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Create Plots Using the Simulation Data Inspector” on page 31-161
• “Control Display of Streaming Data Using Triggers” on page 31-106

31-67
31 Inspecting and Comparing Simulation Data

View Multidimensional Signals Using the Array Plot

This example shows how to view and analyze data using an array plot in the Simulation Data
Inspector. You can use an array plot to view multidimensional signals, including variable-size signals,
that you log from simulation or import from another source into the Simulation Data Inspector. This
example plots and analyzes imported data from a system that:
1 Samples a signal contaminated with noise using an analog to digital converter.
2 Performs a discrete Fourier transform (DFT) on the sampled signal.
3 Removes the noise from the signal in the frequency domain.
4 Performs an inverse DFT on the filtered signal to return to the time domain.

The signal samples are processed using frames, which buffer several samples into an array. You can
use the array plot to view the frames of the time domain signal and to view the frequency domain
representation of the signal.

Import Data into Simulation Data Inspector

Open the Simulation Data Inspector.


Simulink.sdi.view

The data for this example is stored in the MAT file NoiseFilteringData.mat. To import the data

using the user interface, click Import .

In the Import dialog box, under Import from, select File. Then, enter NoiseFilteringData.mat
in the text box and click Import.

Alternatively, import the data programmatically using the Simulink.sdi.Run.create function.


runObj = Simulink.sdi.Run.create("Noise Filtering Data Run","file","NoiseFilteringData.mat");

Plot Data Using Array Plot

By default, the Simulation Data Inspector groups signals according to data hierarchy, and groups of
signals are collapsed. To view the signals that were imported, click the arrow next to Noise Filtering
Data. Because the signals contain multidimensional data, the dimensions of each sample are
indicated to the right of the signal name.

By default, the Simulation Data Inspector uses time plots for all subplots in the layout. Time plots do
not support displaying multidimensional data. To plot Noisy Signal, select the check box next to it.

31-68
View Multidimensional Signals Using the Array Plot

A menu appears in the plot area with actions you can perform on the multidimensional signal. To view
the signal data, select Change active subplot to array plot and click OK.

Each 64-by-1 sample of Noisy Signal is a frame of time-domain data for a sine wave contaminated
by noise. The array plot uses the row index within the sample as the x data and the sample value at
that index as the y data.

Change the subplot layout to include four subplots so you can plot the other signals. Click

Visualizations and layouts . Then, under Basic Layouts, select the four-subplot layout.

31-69
31 Inspecting and Comparing Simulation Data

You can plot the other signals the same way as the first:

1 Select the subplot where you want to plot the signal.


2 Select the check box next to the signal you want to plot.
3 Select the option to change the active subplot to an array plot.
4 Click OK.

You can also manually change the time plots to array plots then plot the signals using the check boxes
in the table.

To manually change a time plot to an array plot, click Visualizations and layouts , then click or
drag the Array icon onto a subplot.

31-70
View Multidimensional Signals Using the Array Plot

Using either strategy, plot the remaining signals so the time-domain signals are on the left and the
frequency-domain data is on the right. In the time domain, you can see the sine wave is smoother
after the frequency domain processing. In the frequency domain, you can see the peak that
corresponds to the high-frequency noise and its removal.

31-71
31 Inspecting and Comparing Simulation Data

Modify Array Plot Appearance

Using the array plot settings, you can change the plot type and control the values on the x-axis by
specifying an offset and an increment value that defines the space between values on the x-axis. For
example, change the settings for the time domain plots to better suit the plotted data.

By default, the array plot uses a stem plot type. Because the frequency domain data is discrete, a
stem plot is well-suited. The time domain data represents an analog signal that is sampled, which is
better represented as a stair plot. You can change the plot type using the subplot menu. To change
the Noisy Signal and Noise Removed Signal array plot types to stair:

1 Pause on the subplot.


2 Click the three dots that appear.
3 Expand the Plot Type list and select Stair.

31-72
View Multidimensional Signals Using the Array Plot

Next, adjust the x-axes for the time domain plots to accurately reflect the relative sample times for
each frame. Using the Visualization Settings for the array plot, change the x-axis increment to match
the sample rate of 0.005s used to generate the data. First, select the subplot you want to modify,

then click Visualization Settings and specify the X-Axis Increment as 0.005.

The x-axis labels update to indicate that each frame represents a bit more than 300ms of signal data.

31-73
31 Inspecting and Comparing Simulation Data

You can also modify the appearance of the array plot by modifying properties on the plotted signal.
Using the Properties pane, you can modify:

• The signal name, which appears in the legend.


• The line style and color.
• The format used to display complex data.

The frequency domain data is complex. By default, complex data is displayed in real-imaginary
format, and the array plot uses different shades of the same color to display the real and imaginary
components. You can control how complex data is plotted by changing the Complex Format
parameter for the signal. To change the Complex Format for the Noisy Signal DFT and Noise
Removed DFT signals to Magnitude:

1 Select the row for the signal in the table.


2 Expand the Properties pane.
3 From the Complex Format list, select Magnitude.

31-74
View Multidimensional Signals Using the Array Plot

Analyze Multidimensional Data Over Time

The array plot provides a two-dimensional representation of one sample of a multidimensional signal,
plotting the values in a column evenly spaced along the x-axis. The signals also have a time
component, and the data in each multidimensional sample can vary with time.

When a view contains visualizations that support cursors, the array plot synchronizes with the cursor
to display the sample that corresponds to the cursor position in time. You can also use the replay
controls to analyze the sample values on an array plot over time.

The array plot indicates the time that corresponds to the plotted sample in the upper-right of the plot.
By default, the array plot displays the last sample of data. When you enable the replay controls, the
array plots update to display the sample value for the first time point. To show the replay controls,

click Show/hide replay controls .

You can manually control which sample is displayed on the plots using the Step forward and Step

backward buttons or by dragging the progress indicator . To replay the data, click Replay .

31-75
31 Inspecting and Comparing Simulation Data

The replay sweeps through the sample values at a rate you can adjust using the Decrease replay
speed and Increase replay speed buttons on either side of the replay speed or specify by clicking

the replay speed and entering a new value. By default, the replay updates plots at a rate of one
second per second, meaning that the cursor moves through one second of data in one second of clock
time.

As the plots update, you can see how the sine wave shifts within each frame and how that affects the
results of the DFT.

See Also
Functions
Simulink.sdi.Run.create

Tools
Simulation Data Inspector

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2

31-76
Microsoft Excel Import, Export, and Logging Format

Microsoft Excel Import, Export, and Logging Format

Using the Simulation Data Inspector or Simulink Test, you can import data from a Microsoft Excel file
or export data to a Microsoft Excel file. You can also load data from an Excel spreadsheet into your
model using the Playback block, or log data to an Excel file using the Record block. The Simulation
Data Inspector, Simulink Test, the Playback block, and the Record block all use the same file format,
so you can use the same Microsoft Excel file with multiple applications.

Tip When the format of the data in your Excel file does not match the specification in this topic, you
can write your own file reader to import the data using the io.reader class.

Basic File Format


In the simplest format, the first row in the Excel file is a header that lists the names of the signals in
the file. The first column is time. The name for the time column must be time, and the time values
must increase monotonically. The rows below the signal names list the signal values that correspond
to each time step.

The import operation does not support time data that includes Inf or NaN values or signal data that
includes Inf values. Empty or NaN signal values imported from the Excel file render as missing data
in the Simulation Data Inspector. All built-in data types are supported.

Multiple Time Vectors


When your data includes signals with different time vectors, the file can include more than one time
vector. Every time column must be named time. Time columns specify the sample times for signals to
the right, up to the next time vector. For example, the first time column defines the time for signal1
and signal2, and the second time column defines the time steps for signal3.

31-77
31 Inspecting and Comparing Simulation Data

Signal columns must have the same number of data points as the associated time vector.

Signal Metadata
The file can include metadata for signals such as data type, units, and interpolation method. The
metadata is used to determine how to plot the data, how to apply unit and data conversions, and how
to compute comparison results. For more information about how metadata is used in comparisons,
see “How the Simulation Data Inspector Compares Data” on page 31-214.

Metadata for each signal is listed in rows between the signal names and the signal data. You can
specify any combination of metadata for each signal. Leave a blank cell for signals with less specified
metadata.

Label each piece of metadata according to this table. The table also indicates which tools and
operations support each piece of metadata. When an imported file does not specify signal metadata,
double data type, zoh (zero order hold) interpolation, and union synchronization are used.

31-78
Microsoft Excel Import, Export, and Logging Format

Property Descriptions

Signal Label Values Simulation Record Block Simulink Test


Property Data Inspector Logging and Import and
Import Simulation Export
Data Inspector
Export
Data type Type: Built-in data Supported Supported Supported
type.
Units Unit: Supported unit. Supported Supported Supported
For example,
Unit: m/s
specifies units
of meters per
second.

For a list of
supported units,
enter
showunitslis
t in the
MATLAB
Command
Window.
Interpolation Interp: linear, zoh Supported Supported Supported
method for zero order
hold, or none.
Synchronization Sync: union or Supported Not Supported Supported
method intersection
. Metadata not
included in
exported file.
Relative RelTol: Percentage, Supported Not Supported Supported
tolerance represented as
a decimal. For Metadata not
example, included in
RelTol: 0.1 exported file.
specifies a 10%
relative
tolerance.
Absolute AbsTol: Numeric value. Supported Not Supported Supported
tolerance
Metadata not
included in
exported file.
Time tolerance TimeTol: Numeric value, Supported Not Supported Supported
in seconds.
Metadata not
included in
exported file.

31-79
31 Inspecting and Comparing Simulation Data

Signal Label Values Simulation Record Block Simulink Test


Property Data Inspector Logging and Import and
Import Simulation Export
Data Inspector
Export
Leading LeadingTol: Numeric value, Supported Not Supported Supported
tolerance in seconds.
Only visible in Metadata not
Simulink Test. included in
exported file.
Lagging LaggingTol: Numeric Value, Supported Not Supported Supported
tolerance in seconds.
Only visible in Metadata not
Simulink Test. included in
exported file.
Block Path BlockPath: Path to the Supported Supported Supported
block that
generated the
signal.
Port Index PortIndex: Integer. Supported Supported Supported
Name Name: Signal name Supported Not Supported Supported

Metadata not
included in
exported file.

User-Defined Data Types


In addition to built-in data types, you can use other labels in place of the DataType: label to specify
fixed-point, enumerated, alias, and bus data types.

31-80
Microsoft Excel Import, Export, and Logging Format

Property Descriptions

Data Type Label Values Simulation Record Block Simulink Test


Data Inspector Logging and Import and
Import Simulation Export
Data Inspector
Export
Enumeration Enum: Name of the Supported Supported Supported
enumeration
class. Enumeration Enumeration Enumeration
class definition class definition class definition
must be saved must be saved must be saved
on the MATLAB on the MATLAB on the MATLAB
path. path. path.
Alias Alias: Name of a Supported Not Supported Supported
Simulink.Ali
asType object For matrix and For matrix and
in the MATLAB complex complex
workspace. signals, specify signals, specify
the alias data the alias data
type on the first type on the first
channel. channel.
Fixed-point Fixdt: • fixdt Supported Not Supported Supported
constructor.
• Name of a
Simulink.
NumericTy
pe object in
the MATLAB
workspace.
• Name of a
fixed-point
data type as
described in
“Fixed-Point
Numbers in
Simulink”
(Fixed-Point
Designer).
Bus Bus: Name of a Supported Not Supported Supported
Simulink.Bus
object in the
MATLAB
workspace.

When you specify the type using the name of a Simulink.Bus object and the object is not in the
MATLAB workspace, the data still imports from the file. However, individual signals in the bus use
data types described in the file rather than data types defined in the Simulink.Bus object.

31-81
31 Inspecting and Comparing Simulation Data

Complex, Multidimensional, and Bus Signals


You can import and export complex, multidimensional, and bus signals using an Excel file. The signal
name for a column of data indicates whether that data is part of a complex, multidimensional, or bus
signal. Excel file import and export do not support arrays of buses.

Note When you export data from a nonvirtual bus with variable-size signals to an Excel file, the
variable-size signal data is expanded to individual channels, and the hierarchical nature of the data is
lost. Data imported from this file is returned as a flat list.

Multidimensional signal names include index information in parentheses. For example, the signal
name for a column might be signal1(2,3). When you import data from a file that includes
multidimensional signal data, elements in the data not included in the file take zero sample values
with the same data type and complexity as the other elements.

Complex signal data is always in real-imaginary format. Signal names for columns containing complex
signal data include (real) and (imag) to indicate which data each column contains. When you
import data from a file that includes imaginary signal data without specifying values for the real
component of that signal, the signal values for the real component default to zero.

Multidimensional signals can contain complex data. The signal name includes the indication for the
index within the multidimensional signal and the real or imaginary tag. For example, signal1(1,3)
(real).

Dots in signal names specify the hierarchy for busses. For example:

• bus.y.a
• bus.y.b
• bus.x

Tip When the name of your signal includes characters that could make it appear as though it were
part of a matrix, complex signal, or bus, use the Name metadata option to specify the name you want
the imported signal to use in the Playback block, Simulation Data Inspector, and Simulink Test.

31-82
Microsoft Excel Import, Export, and Logging Format

Function-Call Signals
Signal data specified in columns before the first time column is imported as one or more function-call
signals. The data in the column specifies the times at which the function-call signal was enabled. The
imported signals have a value of 1 for the times specified in the column. The time values for function-
call signals must be double, scalar, and real, and must increase monotonically.

When you export data from the Simulation Data Inspector, function-call signals are formatted the
same as other signals, with a time column and a column for signal values.

Simulation Parameters
You can import data for parameter values used in simulation. In the Playback block and the
Simulation Data Inspector, the parameter values are shown as signals. Simulink Test uses imported
parameter values to specify values for those parameters in the tests it runs based on imported data.

Parameter data is specified using two or three columns. The first column specifies the parameter
names, with the cell in the header row for that column labeled Parameter:. The second column
specifies the value used for each parameter, with the cell in the header row labeled Value:.
Parameter data may also include a third column that contains the block path associated with each
parameter, with the cell in the header row labeled BlockPath:. Specify names, values, and block
paths for parameters starting in the first row that contains signal data, below the rows used to
specify signal metadata. For example, this file specifies values for two parameters, X and Y.

For more information, see “Create External Data Files to Use in Test Cases” (Simulink Test).

Multiple Runs
You can include data for multiple runs in a single file. Within a sheet, you can divide data into runs by
labeling data with a simulation number and a source type, such as Input or Output. Specify the
simulation number and source type as additional signal metadata, using the label Simulation: for
the simulation number and the label Source: for the source type. The Playback block and the
Simulation Data Inspector use the simulation number and source type only to determine which
signals belong in each run. Simulink Test uses the information to define inputs, parameters, and
acceptance criteria for tests to run based on imported data.

You do not need to specify the simulation number and output type for every signal. Signals to the
right of a signal with a simulation number and source use the same simulation number and source

31-83
31 Inspecting and Comparing Simulation Data

until the next signal with a different source or simulation number. For example, this file defines data
for two simulations and imports into four runs in the Simulation Data Inspector:

• Run 1 contains signal1 and signal2.


• Run 2 contains signal3, X, and Y.
• Run 3 contains signal4.
• Run 4 contains signal5.

You can also use sheets within the Microsoft Excel file to divide the data into runs and tests. When
you do not specify simulation number and source information, the data on each sheet is imported into
a separate run in the Simulation Data Inspector or the Playback block. When you export multiple runs
from the Simulation Data Inspector, the data for each run is saved on a separate sheet. When you
import a Microsoft Excel file that contains data on multiple sheets into Simulink Test, an iteration is
created for each sheet.

See Also
Simulink.sdi.createRun | Simulink.sdi.exportRun

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Import Data from a CSV File into the Simulation Data Inspector” on page 31-85
• “Import Data Using Custom File Reader” on page 31-27

31-84
Import Data from a CSV File into the Simulation Data Inspector

Import Data from a CSV File into the Simulation Data Inspector

To import data into the Simulation Data Inspector from a CSV file, format the data in the CSV file.
Then, you can import the data using the Simulation Data Inspector UI or the
Simulink.sdi.createRun function.

Tip When you want to import data from a CSV file where the data is formatted differently from the
specification in this topic, you can write your own file reader for the Simulation Data Inspector using
the io.reader class.

Basic File Format


In the simplest format, the first row in the CSV file is a header that lists the names of the signals in
the file. The first column is time. The name for the time column must be time, and the time values
must increase monotonically. The rows below the signal names list the signal values that correspond
to each time step.

The import operation does not support time data that includes Inf or NaN values or signal data that
includes Inf values. Empty or NaN signal values render as missing data. All built-in data types are
supported.

Multiple Time Vectors


When your data includes signals with different time vectors, the file can include more than one time
vector. Every time column must be named time. Time columns specify the sample times for signals to
the right, up to the next time vector. For example, the first time column defines the time for signal1
and signal2, and the second time column defines the time steps for signal3.

31-85
31 Inspecting and Comparing Simulation Data

Signal columns must have the same number of data points as the associated time vector.

Signal Metadata
You can specify signal metadata in the CSV file to indicate the signal data type, units, interpolation
method, block path, and port index. List metadata for each signal in rows between the signal name
and the signal data. Label metadata according to this table.

Signal Property Label Value


Data type Type: Built-in data type.
Units Unit: Supported unit. For example,
Unit: m/s specifies units of
meters per second.

For a list of supported units,


enter showunitslist in the
MATLAB Command Window.
Interpolation method Interp: linear, zoh for zero order
hold, or none.
Block Path BlockPath: Path to the block that generated
the signal.
Port Index PortIndex: Integer.

You can also import a signal with a data type defined by an enumeration class. Instead of using the
Type: label, use the Enum: label and specify the value as the name of the enumeration class. The
definition for the enumeration class must be saved on the MATLAB path.

When an imported file does not specify signal metadata, the Simulation Data Inspector assumes
double data type and linear interpolation. You can specify the interpolation method as linear, zoh
(zero-order hold), or none. If you do not specify units for the signals in your file, you can assign units
to the signals in the Simulation Data Inspector after you import the file.

You can specify any combination of metadata for each signal. Leave a blank cell for signals with less
specified metadata.

31-86
Import Data from a CSV File into the Simulation Data Inspector

Import Data from a CSV File

You can import data from a CSV file using the Simulation Data Inspector UI or using the
Simulink.sdi.createRun function.

To import data using the UI, open the Simulation Data Inspector using the Simulink.sdi.view

function or the Data Inspector button in the Simulink™ toolstrip. Then, click Import .

In the Import dialog, select the option to import data from a file and navigate in the file system to
select the file. After you select the file, data available for import shows in the table. You can choose
which signals to import and whether to import them to a new or existing run. This example imports
all available signals to a new run. To select all or none of the signals, select or clear the check box
next to NAME. After selecting the options, click the Import button.

31-87
31 Inspecting and Comparing Simulation Data

When you import data into a new run using the UI, the new run name includes the run number
followed by Imported_Data.

When you import data programmatically, you can specify the name of the imported run.

csvRunID = Simulink.sdi.createRun('CSV File Run','file','csvExampleData.csv');

See Also
Functions
Simulink.sdi.createRun

31-88
Import Data from a CSV File into the Simulation Data Inspector

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Microsoft Excel Import, Export, and Logging Format” on page 31-77
• “Import Data Using Custom File Reader” on page 31-27

31-89
31 Inspecting and Comparing Simulation Data

Configure the Simulation Data Inspector

The Simulation Data Inspector supports a wide range of use cases for analyzing and visualizing data.
You can modify preferences in the Simulation Data Inspector to match your visualization and analysis
requirements. The preferences that you specify persist between MATLAB sessions.

By specifying preferences in the Simulation Data Inspector, you can configure options such as:

• How signals and metadata are displayed.


• Which data automatically imports from parallel simulations.
• Where prior run data is retained and how much prior data to store.
• How much memory is used during save operations.
• The system of units used to display signals.

To open the Simulation Data Inspector preferences, click Preferences.

Note You can restore all preferences in the Simulation Data Inspector to default values by clicking
Restore Defaults in the Preferences menu or by using the Simulink.sdi.clearPreferences
function.

Logged Data Size and Location

By default, simulation data logs to disk with data loaded into memory on demand, and the maximum
size of logged data is constrained only by available disk space. You can use the Disk Management
settings in the Simulation Data Inspector to directly control the size and location of logged data.

The Record mode setting specifies whether logged data is retained after simulation. When you
change the Record mode setting to View during simulation only, no logged data is available in the
Simulation Data Inspector or the workspace after the simulation completes. Only use this mode when
you do not want to save logged data. The Record mode setting reverts to View and record data
each time you start MATLAB. Changing the Record mode setting can affect other applications, such
as visualization tools. For details, see “View Data Only During Simulation” on page 78-26.

To directly limit the size of logged data, you can specify a minimum amount of free disk space or a
maximum size for the logged data. By default, logged data must leave at least 100 MB of free disk
space with no maximum size limit. Specify the required disk space and maximum size in GB, and
specify 0 to apply no disk space requirement or no maximum size limit.

When you specify a minimum disk space requirement or a maximum size for logged data, you can
also specify whether to prioritize retaining data from the current simulation or data from prior
simulations when approaching the limit. By default, the Simulation Data Inspector prioritizes
retaining data for the current run by deleting data for prior runs. To prioritize retaining prior data,
change the When low on disk space setting to Keep prior runs and stop recording. You see a
warning message when prior runs are deleted and when recording is disabled. If recording is
disabled due to the size of logged data, you need to change the Record Mode back to View and

31-90
Configure the Simulation Data Inspector

record data to continue logging data, after you have freed up disk space. For more information, see
“Specify a Minimum Disk Space Requirement or Maximum Size for Logged Data” on page 78-25.

The Storage Mode setting specifies whether to log data to disk or to memory. By default, data logs to
disk. When you configure a parallel worker to log data to memory, data transfer back to the host is
not supported. Logging data to memory is not supported for rapid accelerator simulations or models
deployed using Simulink Compiler.

You can also specify the location of the temporary file that stores logged data. By default, data logs to
the temporary files directory on your computer. You may change the file location when you need to
log large amounts of data and a secondary drive provides more storage capacity. Logging data to a
network location can degrade performance.

Programmatic Use

You can programmatically configure and check each preference value.

Preference Functions
Record mode Simulink.sdi.setRecordData

Simulink.sdi.getRecordData
Required Free Space Simulink.sdi.setRequiredFreeSpace

Simulink.sdi.getRequiredFreeSpace
Max Disk Usage Simulink.sdi.setMaxDiskUsage

Simulink.sdi.getMaxDiskUsage
When low on disk space Simulink.sdi.setDeleteRunsOnLowSpace

Simulink.sdi.getDeleteRunsOnLowSpace
Storage Mode Simulink.sdi.setStorageMode

Simulink.sdi.getStorageMode
Storage Location Simulink.sdi.setStorageLocation

Simulink.sdi.getStorageLocation

Archive Behavior and Run Limit

When you run multiple simulations in a single MATLAB session, the Simulation Data Inspector retains
results from each simulation so you can analyze the results together. Use the Simulation Data
Inspector archive to manage runs in the user interface and control the number of runs the Simulation
Data Inspector retains.

You can configure a limit for the number of runs to retain in the archive and whether the Simulation
Data Inspector automatically moves prior runs into the archive.

31-91
31 Inspecting and Comparing Simulation Data

Manage Runs Using the Archive

By default, the Simulation Data Inspector automatically archives simulation runs. When you simulate
a model, the prior simulation run moves to the archive, and the Simulation Data Inspector updates
the view to show data for aligned signals in the current run.

The archive does not impose functional limitations on the runs and signals it contains. You can plot
signals from the archive, and you can use runs and signals in the archive in comparisons. You can
drag runs of interest from the archive to the work area and vice versa whether Automatically
Archive is selected or disabled.

To prevent the Simulation Data Inspector from automatically moving prior simulations runs to the
archive, clear the Automatically archive setting. With automatic archiving disabled, the Simulation
Data Inspector does not move prior runs into the Archive pane or automatically update plots to
display data from the current simulation.

Tip To manually delete the contents of the archive, click Delete archived runs .

Control Number of Runs Retained in Simulation Data Inspector

You can specify a limit for the number of runs to retain in the archive. When the number of runs in
the archive reaches the limit, the Simulation Data Inspector deletes runs in the archive on a first-in,
first-out basis.

The run limit applies only to runs in the archive. For the Simulation Data Inspector to automatically
limit the data it retains by deleting old runs, select Automatically archive and specify a size limit.

By default, the Simulation Data Inspector retains the last 20 runs moved to the archive. To remove
the limit, select No limit. To specify the maximum number of runs to store in the archive, select Last
n runs and enter the limit. A warning occurs if you specify a limit that would delete runs already in
the archive.

Programmatic Use

You can programmatically configure and check the archive behavior and run limit.

Preference Functions
Automatically archive Simulink.sdi.setAutoArchiveMode

Simulink.sdi.getAutoArchiveMode
Size Simulink.sdi.setArchiveRunLimit

Simulink.sdi.getArchiveRunLimit

Incoming Run Names and Location

You can configure how the Simulation Data Inspector handles incoming runs from import or
simulation. You can choose whether new runs are added at the top of the work area or the bottom and
specify a naming rule to use for runs created from simulation.

31-92
Configure the Simulation Data Inspector

By default, the Simulation Data Inspector adds new runs below prior runs in the work area. The
Archive settings also affect the location of runs. By default, prior runs are moved to the archive when
a new simulation run is created.

The run naming rule is used to name runs created from simulation. You can create the run naming
rule using a mix of literal text that is used in the run name as-is and one or more tokens that
represent metadata about the run. By default, the Simulation Data Inspector names runs using the
run index and model name: Run <run_index>: <model_name>.

Tip To rename an existing run, double-click the name in the work area and enter the new name, or
modify the run name in the Properties pane.

Programmatic Use

You can programmatically configure and check incoming run names and locations.

Preference Functions
Add New Runs Simulink.sdi.setAppendRunToTop

Simulink.sdi.getAppendRunToTop
Naming Rule Simulink.sdi.setRunNamingRule

Simulink.sdi.getRunNamingRule

Simulink.sdi.resetRunNamingRule

Signal Metadata to Display

You can control which signal metadata is displayed in the work area of the Inspect pane and in the
results section on the Compare pane in the Simulation Data Inspector. You specify the metadata to
display separately for each pane using the Table Columns preferences in the Inspect and Compare
sections of the Preferences dialog, respectively.

Inspect Pane

By default, the signal name and the line style and color used to plot the signal are displayed on the
Inspect pane. To display different or additional metadata in the work area on the Inspect pane,
select the check box next to each piece of metadata you want to display in the Table Columns
preference in the Inspect section. You can always view complete metadata for the selected signal in
the Inspect pane using the Properties pane.

Note Metadata displayed in the work area on Inspect pane is included when you generate a report
of plotted signals. You can also specify metadata to include in the report regardless of what is
displayed in the work area when you create the report programmatically using the
Simulink.sdi.report function.

31-93
31 Inspecting and Comparing Simulation Data

Compare Pane

By default, the Compare pane shows the signal name, the absolute and relative tolerances used in
the signal comparison, and the maximum difference from the comparison result. To display different
or additional metadata in the results on the Compare pane, select the check box next to each piece
of metadata you want to display in the Table Columns preference in the Compare section. You can
always view complete metadata for the signals compared for a selected signal result using the
Properties pane, where metadata that differs between the compared signals is highlighted. Signal
metadata displayed on the Compare pane does not affect the contents of comparison reports.

Signal Selection on the Inspect Pane

You can configure how you select signals to plot on the selected subplot in the Simulation Data
Inspector. By default, you use check boxes next to each signal to plot. You can also choose to plot
signals based on selection in the work area. Use Check Mode when creating views and visualizations
that represent findings and analysis of a data set. Use Browse Mode to quickly view and analyze
data sets with a large number of signals.

For more information about creating visualizations using Check Mode, see “Create Plots Using the
Simulation Data Inspector” on page 31-161.

For more information about using Browse Mode, see “Visualize Many Logged Signals” on page 31-
124.

Note To use Browse Mode, your layout must include only Time Plot visualizations.

How Signals Are Aligned for Comparison

When you compare runs using the Simulation Data Inspector, the comparison algorithm pairs signals
for signal comparison through a process called alignment. You can align signals between the
compared runs using one or more of the signal properties shown in the table.

Property Description
Data Source Path of the variable in the MATLAB workspace for
data imported from the workspace
Path Block path for the source of the data in its model
SID Automatically assigned Simulink identifier
Signal Name Name of the signal

You can specify the priority for each piece of metadata used for alignment. The Align By field
specifies the highest priority property used to align signals. The priority drops with each subsequent
Then By field. You must specify a primary alignment property in the Align By field, but you can
leave any number of Then By fields blank.

By default, the Simulation Data Inspector aligns signals between runs according to this flow chart.

31-94
Configure the Simulation Data Inspector

For more information about configuring comparisons in the Simulation Data Inspector, see “How the
Simulation Data Inspector Compares Data” on page 31-214.

Colors Used to Display Comparison Results

You can configure the colors used to display comparison results using the Simulation Data Inspector
preferences. You can specify whether to use the signal color from the Inspect pane or a fixed color
for the baseline and compared signals. You can also choose colors for the tolerance and the difference
signal.

By default, the Simulation Data Inspector displays comparison results using fixed colors for the
baseline and compared signals. Using a fixed color allows you to avoid the baseline signal color and
compared signal color being either the same or too similar to distinguish.

Signal Grouping

You can specify how to group signals within a run in the Simulation Data Inspector. The preferences
apply to both the Inspect and Compare panes and comparison reports. You can group signals by:

• Domain — Signal type. For example, signals created by signal logging have a domain of Signal,
while signals created from logging model outputs have a domain of Outports.
• Physical System Hierarchy — Signal Simscape physical system hierarchy. The option to group by
physical system hierarchy is available when you have a Simscape license.
• Data Hierarchy — Signal location within structured data. For example, data hierarchy grouping
reflects the hierarchy of a bus.
• Model Hierarchy — Signal location within model hierarchy. Grouping by model hierarchy can be
helpful when you log data from a model that includes model or subsystem references.

Grouping signals adds rows for the hierarchical nodes, which you can expand to show the signals
within that node. By default, the Simulation Data Inspector groups signals by domain, then by
physical system hierarchy (if you have a Simscape license), and then by data hierarchy.

To remove grouping and display a flat list of signals in each run, select None for all grouping options.

31-95
31 Inspecting and Comparing Simulation Data

Programmatic Use

To specify how to group signals programmatically, use the Simulink.sdi.setTableGrouping


function.

Data to Stream from Parallel Simulations

When you run parallel simulations using the parsim function, you can stream logged simulation data
to the Simulation Data Inspector. A dot next to the run name in the Inspect pane indicates the status
of the simulation that corresponds to the run, so you can monitor simulation progress while
visualizing the streamed data. You can control whether data streams from a parallel simulation based
on the type of worker the data comes from.

By default, the Simulation Data Inspector is configured for manual import of data from parallel
workers. You can use the Simulation Data Inspector programmatic interface to inspect the data on
the worker and decide whether to send it to the client Simulation Data Inspector for further analysis.
To manually move data from a parallel worker to the Simulation Data Inspector, use the
Simulink.sdi.sendWorkerRunToClient function.

You may want to automatically stream data from parallel simulations that run on local workers or on
local and remote workers. Streaming data from both local and remote workers may affect simulation
performance, depending on how many simulations you run and how much data you log. When you
choose to stream data from local workers or all parallel workers, all logged simulation data
automatically shows in the Simulation Data Inspector.

Programmatic Use

You can configure Simulation Data Inspector support for parallel worker data programmatically using
the Simulink.sdi.enablePCTSupport function.

Options for Saving and Loading Session Files

You can specify a maximum amount of memory to use while loading or saving a session file. By
default, the Simulation Data Inspector uses a maximum of 100 MB of memory when you load or save
a session file. You can specify a memory use limit as low as 50 MB.

To reduce the size of the saved session file, you can specify a compression option.

• None — Do not compress saved data.


• Normal — Compress the saved file as much as possible.
• Fastest — Compress the saved file less than Normal compression for faster save time.

Signal Display Units

Signals in the Simulation Data Inspector have two units properties: stored units and display units.
The stored units represent the units of the data saved to disk. The display units specify how the
Simulation Data Inspector displays the data. You can configure the Simulation Data Inspector to use a
system of units to define the display units for all signals. You can choose either the SI or US
Customary system of units, or you can display data using its stored units.

31-96
Configure the Simulation Data Inspector

When you use a system of units to define display units for signals in the Simulation Data Inspector,
the display units update for any signal with display units that are not valid for that unit system. For
example, if you select SI units, the display units for a signal may update from ft to m.

Note The system of units you choose to use in the Simulation Data Inspector does not affect the
stored units for any signal. You can convert the stored units for a signal using the convertUnits
function. Conversion may result in loss of precision.

In addition to selecting a system of units, you can specify override units so that all signals of a given
measurement type are displayed using consistent units. For example, if you want to visualize all
signals that represent weight using units of kg, specify kg as an override unit.

Tip For a list of units supported by Simulink, enter showunitslist in the MATLAB Command
Window.

You can also modify the display units for a specific signal using the Properties pane. For more
information, see “Modify Signal Properties in the Simulation Data Inspector” on page 31-193.

Programmatic Use

Configure the unit system and override units using the Simulink.sdi.setUnitSystem function.
You can check the current units preferences using the Simulink.sdi.getUnitSystem function.

See Also
Functions
Simulink.sdi.clearPreferences | Simulink.sdi.setRunNamingRule |
Simulink.sdi.setTableGrouping | Simulink.sdi.enablePCTSupport |
Simulink.sdi.setArchiveRunLimit | Simulink.sdi.setAutoArchiveMode

More About
• “Iterate Model Design Using the Simulation Data Inspector” on page 31-119
• “How the Simulation Data Inspector Compares Data” on page 31-214
• “Compare Simulation Data” on page 31-203
• “Create Plots Using the Simulation Data Inspector” on page 31-161
• “Modify Signal Properties in the Simulation Data Inspector” on page 31-193

31-97
31 Inspecting and Comparing Simulation Data

View Streaming Data in the Simulation Data Inspector


When streaming data to the Simulation Data Inspector, you can control how incoming data is
displayed by specifying the behavior of the time axis. You can set a time span, choose how plot
updates are drawn, and freeze the display to better view and analyze your streaming data. These
options are helpful when working with real-time models or infinite simulation times or when you use
simulation pacing to interact with the system. You can also use triggers to control when to draw the
plot of a streaming signal in the Simulation Data Inspector. For more information, see “Control
Display of Streaming Data Using Triggers” on page 31-106.

This example shows you how to control the time axis, display scaling, and display offset to better
visualize your streaming data.

Open and Simulate the Model

This model generates four logged signals: Sine Wave, Pulse, Sawtooth and Output. The Switch
block is configured to allow the sine signal to pass through when the output of the Pulse Generator
block is greater than zero. When the output of the Pulse Generator block is less than or equal to zero,
the Switch block allows the sawtooth signal to pass through.

The model uses simulation pacing to slow down the simulation, which allows you to interact with the
system. For more information, see Simulation Pacing Options.
1 Click Run to start a simulation.
2 When the simulation has finished, click Data Inspector to open the Simulation Data Inspector.
3 Change the plot layout to 2x1.
4 Plot the Output signal in the upper subplot.
5 Plot the Sawtooth and Sine Wave signals in the lower subplot.

By default, the Simulation Data Inspector groups signals by domain. The Signals grouping contains
all signals marked for signal logging: the output of the Pulse Generator block, the Signal Generator
block, and the Sine Wave block. The Outports grouping contains the logged model output from the
Switch block. When you plot a signal after the simulation completes, the Simulation Data Inspector
fits the view to display all the signal data.

31-98
View Streaming Data in the Simulation Data Inspector

Change Time Span


If the simulation time is finite, the Time span can be set to auto. When Time span is set to auto,
the t-axis spans the full simulation time. However, when you view the entire simulation at once, the
characteristics of the Sine Wave and Sawtooth signals are hard to see. You can view a portion of
each signal by setting the Time span. Before beginning the simulation, you can change the size of

the visible time interval by changing the Time span value. Click Visualization Settings . Then, in
Limits > Time span, enter a value. When you change the minimum or maximum time axis limit
during live streaming, the time span remains fixed. When you change the time span during live
streaming, the minimum time axis limit remains the same and the maximum time axis limit adjusts
such that t-Axis max = t-Axis min + Time span.

For example, set Time span to 150. Because the plots are linked, the t-axis has limits 0 to 150 at the
start of the simulation for both subplots. When Link plot is selected, any changes made in
Visualization Settings apply to all linked subplots. Subplots are linked by default. To unlink a subplot,
select the subplot. Then, in the Visualization Settings, clear Link plot.

31-99
31 Inspecting and Comparing Simulation Data

With the Time span set to 150, click Run to start the simulation. When the simulation starts, the
span from 0 to 150 is visible on the t-axis. After reaching 150, the t-axis shifts to show 150 to 300.

31-100
View Streaming Data in the Simulation Data Inspector

Control Plot Update Behavior


You can change the way the Simulation Data Inspector updates subplots while streaming a signal.

Click Visualization Settings . Then, you can set Axes > Update mode to Wrap or Scroll. By
default, the display updates by wrapping the plot.

In Wrap mode, the Simulation Data Inspector shows streaming data until it reaches the maximum t-
axis limit. When the data reaches this limit, the minimum and maximum t-axis limits are increased by
the Time span value.

Set Update mode to Scroll. Start a new simulation. In scroll mode, old data is moved out of view
on the left as new data is plotted on the right. In this mode, instead of jumping by 150, t-axis scrolls
with the streaming signal data.

31-101
31 Inspecting and Comparing Simulation Data

Hold Display
When you want the Simulation Data Inspector to pause the drawing of a streaming signal, you can
hold the display. Holding the display lets you inspect your signal while the simulation is running. For
example, suppose you want to measure the period of the sine wave while data is streaming. You can
hold the display and use cursors to find the difference between two peaks.

1 To improve signal visibility, set Time span to 50.


2 Start the simulation.
3
Click Hold to prevent the Simulation Data Inspector from continuing to draw the streaming
signals.

Click Freeze display to prevent wrapping or scrolling of the display.


4
Click Show/hide data cursors . Then, select Two Cursors.
5 Drag the cursors to measure the difference between two peaks in the Output or Sine Wave
signal.

31-102
View Streaming Data in the Simulation Data Inspector

When you finish measuring, click Resume to return your view to the current simulation time. If
the simulation ends while the display is held, the display jumps to the end.

Note The simulation continues to run even through it is not drawn in the Simulation Data Inspector
while the display is held. To pause the simulation, click Pause in the model.

Control Display Scaling and Display Offset


You can vertically scale and shift the display of individual signals from the Properties pane of the
Simulation Data Inspector.

• Use the Display Scaling property to vertically scale the appearance of a plotted signal. The
Simulation Data Inspector plots the signal values multiplied by the scaling value. By default,
Display Scaling is 1.
• Use the Display Offset property to vertically shift the appearance of a plotted signal. The
Simulation Data Inspector plots the summation of the offset value added to the signal values. By
default, Display Offset is 0.

31-103
31 Inspecting and Comparing Simulation Data

Note Changing the value of Display Scaling or Display Offset affects how the Simulation Data
Inspector displays a signal. Signal values are unchanged.

For example, you can change the scaling and offset values for Sine Wave and Sawtooth such that
both signals are displayed between y values of 0 and 1.

1 Select the signal Sawtooth. Then, in the Properties pane, set Display Scaling to 5 and
Display Offset to 0.5.

2 Select the signal Sine Wave. Then, in the Properties pane, set Display Scaling to 0.5 and
Display Offset to 0.5.

3
Select Fit to View in Y to adjust the view.

31-104
View Streaming Data in the Simulation Data Inspector

Notice that the cursors display the original signal values. When you set Display Scaling or Display
Offset to values other than the defaults, you change the appearance of the plot. However, cursors
display the data value of the signal, which remains unchanged.

See Also

Related Examples
• “Control Display of Streaming Data Using Triggers” on page 31-106
• “Inspect Simulation Data” on page 31-179

31-105
31 Inspecting and Comparing Simulation Data

Control Display of Streaming Data Using Triggers


A trigger is an event that determines when to draw the plot of a streaming signal. Trigger settings
specify criteria for the trigger event and where the trigger event is displayed within the updated
data. Triggers facilitate viewing and analyzing streaming data by allowing you to capture transient
changes in signals and stabilize the display of steady-state periodic signals. You can use triggers to
inspect streaming data using several tools, such as the Scope block and the Simulation Data
Inspector. This example uses the Simulation Data Inspector add, configure, and modify triggers on
signals streaming from a model simulation.

Note The following examples add a trigger to signals that are plotted in the Simulation Data
Inspector. However, you can add a trigger to a signal from the active simulation that is not plotted.

For complete descriptions of all trigger types and options, see “Scope Triggers Panel” on page 30-12.

Examine the Model

The model in this example generates two logged output signals. Both signals are created by passing
the output of a Sine Wave block through a switch. Both switches are configured to allow the sine
signal through when the control signal is greater than zero. The switch for the first output is
controlled by user input supplied using the Push Button block. The switch for the second output is
controlled by the output of a Pulse Generator block.

31-106
Control Display of Streaming Data Using Triggers

The model uses simulation pacing so the model behavior and signal display are responsive to user
interaction. Click Run to start a simulation. Then, click Data Inspector to open the Simulation Data
Inspector. In the Simulation Data Inspector, change the layout to show two subplots. Plot the User-
Controlled Output signal on the top subplot and the User Input signal on the bottom subplot.
Press and hold the Push Button block periodically throughout the simulation to pass the Sine Wave
block output to the Outport block.

Interactively Generate Trigger Events


The sine wave characteristics are difficult to see when you view the signals over the entire simulation
time. When you use a trigger to control when the plot updates, you can view the streaming data over
a smaller time range, which allows you to see the sine wave more clearly. Using the trigger ensures
that you see the signal behavior of interest in the smaller time range. In this example, you want to see
the change in the output signal when you press the Push Button block.

To trigger plot updates based on button presses, add a trigger to the User Input signal. To add a
trigger, pause on the row for the User Input signal in the Simulation Data Inspector and click the
trigger icon that appears.

31-107
31 Inspecting and Comparing Simulation Data

The default settings in the Display Trigger dialog configure an auto-leveled rising-edge trigger, with
the trigger event positioned in the middle of the displayed data. Change Mode to Normal, then clear
the Auto level check box and set the Level to 0.5. Then, click Add.

Using normal mode for the trigger means that the plot only updates when a trigger occurs. In auto
mode, the display also updates when a trigger is not detected for the duration of the time span. The
trigger level of 0.5 puts the level in the middle of the signal range.

Before simulating the model, adjust the time range displayed in the plots. In the upper right, click

Visualization Settings . Then, set Time span to 50.

Simulate the model and view the streaming signals in the Simulation Data Inspector. When you start
a new simulation, the trigger configured in the Simulation Data Inspector automatically transfers to
the corresponding signal in the current simulation. The display updates in response to the trigger

31-108
Control Display of Streaming Data Using Triggers

events you cause by pressing the Push Button block in the model. On the smaller time span, you can
see the shape of the sine wave in the output signal. The trigger position and level are marked with
green triangles. You can click and drag the trigger markers to adjust the level and position. A new
value is applied for the level or position when you let go of the marker after dragging.

Experiment with this configuration to test out different kinds of triggers and different trigger
settings. For example, try using a falling-edge trigger. You can also adjust the simulation pacing in the
model to explore how timing can affect trigger behavior. When the trigger occurs, the Simulation
Data Inspector collects all the data to display before updating the plot. If you slow the simulation
pacing closer to a rate where one simulation second takes one second of clock time, you can see the
delay between causing a trigger by pressing the Push Button block and the plot update in the
Simulation Data Inspector.

Capture Signal Transient Response


A trigger allows you to capture transient signal responses to changes in the system under test. For
example, you can use the input signal to an inverter as a trigger when you want to measure the rise
or fall time for the inverter output signal. The display updates only when the trigger occurs, so the
data is displayed long enough for you to make a measurement. When you interactively generate
trigger events, you capture the output signal transient response to the user input. Systems often do
not have user input and respond to changes in upstream signals, such as the Pulse signal that
controls the switch that generates the Pulse-Controlled Output signal.

31-109
31 Inspecting and Comparing Simulation Data

Add a trigger to the Pulse signal in the Simulation Data Inspector. Use a rising-edge trigger in
normal mode with a level of 0.5 again. Click Add Trigger in the warning dialog that appears.

Before simulating the model, update the plots so that the Pulse-Controlled Output is shown on
the top plot and the Pulse signal is shown on the bottom plot.

Simulate the model. The Simulation Data Inspector display updates are not triggered by the user
input in this simulation, so you do not need to press the Push Button block. Observe how the Pulse-
Controlled Output signal is different from the User-Controlled Output signal from the
previous simulation and how the plot updates occur in response to the periodic Pulse signal.

You can experiment in additional simulations by adjusting the pulse width or period of the Pulse
signal. You can also try out different types of triggers, such as a pulse width trigger.

Stabilize a Steady-State Periodic Signal


Using a trigger can stabilize the display of a periodic steady-state signal that you want to view and
analyze. Because the trigger event is always in the stable position in the plot, a streaming periodic
signal can appear still in the plot, rather than shifting or scrolling. When the display is stable, you can
inspect and analyze signal characteristics, such as frequency and amplitude.

31-110
Control Display of Streaming Data Using Triggers

To see how a trigger can stabilize the display of a periodic signal, trigger display updates using the
Sine Wave signal. Use the same settings to configure the rising-edge trigger in normal mode with a
level of 0.5.

Before simulation, update the plot layout to show a single plot. Plot the Sine Wave signal, and set
the Time span to 10.

Simulate the model. During simulation, you can add cursors in the Simulation Data Inspector and
measure the amplitude and period of the signal.

To contrast, remove the trigger and simulate the model again. Notice the differences in how the
display updates. Try simulating with the Update mode set to Wrap and then set to Scroll. Specify

Update mode in Visualization Settings .

See Also

More About
• “Scope Triggers Panel” on page 30-12
• “View Simulation Data in Simulation Data Inspector” on page 31-2

31-111
31 Inspecting and Comparing Simulation Data

• “Iterate Model Design Using the Simulation Data Inspector” on page 31-119

31-112
Synchronize Cursors in the Simulation Data Inspector with an App Designer App

Synchronize Cursors in the Simulation Data Inspector with an


App Designer App
You can use several functions from the Simulation Data Inspector programmatic interface to
synchronize cursors between an App Designer app and the Simulation Data Inspector. Synchronized
cursors allow you to easily analyze data plotted in the Simulation Data Inspector alongside data
displayed on a custom visualization coded in the App Designer app.

The app in this example is simple and illustrates only the core function of passing information about
cursors between the app and the Simulation Data Inspector. Cursor positions are shown on linear
gauges in the app. You can use sliders in the app to reposition the cursors on the Inspect or
Compare panes of the Simulation Data Inspector. When you move cursors in the Simulation Data
Inspector, the new cursor positions are reflected on the sliders and linear gauges.

Open and Run the Cursors App

The cursors app opens in App Designer, where you can explore and modify the layout of the user
interface and the code that specifies the function of each user interface element.
appdesigner('CursorsApp.mlapp');

To run the cursors app, click Run. A new window opens with the app user interface. To get started
using the app, click Open the Simulation Data Inspector, then click Create Data. The Create
Data button creates data for and plots two signals in the Inspect pane of the Simulation Data
Inspector.

31-113
31 Inspecting and Comparing Simulation Data

Next, add cursors. You can add cursors using the Number of Cursors control in the app or using the
Show/hide data cursors option in the Simulation Data Inspector. The slider control and gauge
display for each cursor becomes visible once the cursor is active in the Simulation Data Inspector. Try
moving the cursors using the sliders in the app and by dragging them in the Simulation Data
Inspector.

31-114
Synchronize Cursors in the Simulation Data Inspector with an App Designer App

The app also includes controls and displays for cursors on the Compare pane of the Simulation Data
Inspector. To interact with cursors on the Compare pane, start by clicking Compare Data. The
Simulation Data Inspector automatically shows the Compare pane when you compare data. Then,
add cursors to the comparison plots using the app or the Simulation Data Inspector. Try moving the
cursors in the Simulation Data Inspector and using the sliders in the app.

When you finish exploring the cursor synchronization, close the app window.

Examine the App Code


To view the code in the App Designer window, click Code View in the upper-right of the app canvas.

31-115
31 Inspecting and Comparing Simulation Data

The code view shows the code that specifies the function of the app. Code in grey areas is
automatically programmed by the App Designer when you interactively add components and specify
properties in the Design View. The code in white areas customizes the function of the app.

Custom App Properties

The cursors app adds two custom properties to the app. The callbackID property saves the ID for
the cursor callback registered with the Simulation Data Inspector so the app can unregister the
callback when you close the app. The runIDs property saves the run IDs for the runs created when
you click Create Data. The run IDs are then used to compare the runs when you click Compare
Data.

Custom OnCursorMove Method

The OnCursorMove function is the cursor callback that the app registers with the Simulation Data
Inspector when you start the app. To keep the displays in sync, the function refreshes the app
settings each time you move a cursor in the Simulation Data Inspector.

Custom refreshSettings Method

The cursors app also includes the custom method refreshSettings, which keeps the values
displayed in the app synchronized with the state of the Simulation Data Inspector. The
refreshSettings method uses the Simulink.sdi.getNumCursors function to make sure the
Number of Cursors controls display the correct number of cursors currently visible in the Inspect
and Compare panes of the Simulation Data Inspector. The refreshSettings method also controls
the visibility of the sliders and gauges using the cursor positions returned by the
Simulink.sdi.getCursorPositions function. When a cursor is outside the range of its
corresponding slider and gauge, the app hides the slider and gauge for that cursor.

31-116
Synchronize Cursors in the Simulation Data Inspector with an App Designer App

Callbacks That Handle Component Events

Each component in the app user interface has an associated function that implements the component
response to user interactions. You can add one or more callbacks for a component in the Design
View, and you write the code to define the component response in the Code View.

Method Description of Functionality


startupFcn When you open the cursors app, the app registers
a callback for cursors in the Simulation Data
Inspector and refreshes the app data. The
OnCursorMove cursor callback for both the
Inspect and Compare panes executes when you
move a cursor in the Simulation Data Inspector.
The callback IDs are saved in the callbackID
property of the app.
OpentheSimulationDataInspectorButtonPu When you click the Open the Simulation Data
shed Inspector button, the app opens the Simulation
Data Inspector and refreshes the app data.
CreateDataButtonPushed When you click the Create Data button, the app
creates a sine signal and a cosine signal and plots
the signals in the Simulation Data Inspector.
CompareDataButtonPushed When you click the Compare Data button, the
app compares the run with the sine signal and
the run with the cosine signal.
SimulationDataInspectorCursorControlUI When you close the app, the app unregisters the
FigureCloseRequest callback functions for cursors in the Simulation
Data Inspector.
NumberofCursorsDropDownValueChanged When you use one of the Number of Cursors
controls to change the number of cursors
CompNumCursorsDropDownValueChanged displayed in the Simulation Data Inspector, the
app uses the Simulink.sdi.setNumCursors
function to display the specified number of
cursors in the Simulation Data Inspector.
LeftSliderValueChanging When you adjust a cursor position using the
slider, the app uses the
RightSliderValueChanging Simulink.sdi.setCursorPositions function
to update the position of the cursor in the
CompLeftSliderValueChanging Simulation Data Inspector.
CompRightSliderValueChanging

See Also
Functions
Simulink.sdi.setCursorPositions | Simulink.sdi.getCursorPositions |
Simulink.sdi.setNumCursors | Simulink.sdi.getNumCursors |
Simulink.sdi.registerCursorCallback | Simulink.sdi.unregisterCursorCallback

31-117
31 Inspecting and Comparing Simulation Data

Related Examples
• “Create and Run a Simple App Using App Designer”
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Access Data in MATLAB Function During Simulation” on page 31-128

31-118
Iterate Model Design Using the Simulation Data Inspector

Iterate Model Design Using the Simulation Data Inspector


The Simulation Data Inspector facilitates iterative design, debugging, and optimization by providing
easy access to visualizations of logged data during simulation. Using the Simulation Data Inspector
archive, you can maintain a focused work area and control data retention for multiple simulations.
When you automatically archive simulation runs, you can create a view that is automatically applied
to subsequent simulation runs. With Browse Mode enabled, you can inspect large amounts of logged
signals on Time Plot visualizations more quickly.

View and Inspect Signals During Simulation


You can plot logged signals in the Simulation Data Inspector during simulation. Viewing signals
during a simulation can help build understanding of the model and allow you to make decisions about
model parameters without waiting for a simulation to complete.

When you plot data that is streaming from an active simulation, the Simulation Data Inspector
automatically updates the time span of the plot to match the stop time for the simulation. To view the
streaming data on a smaller time scale, change the t-Axis max value or zoom in time. To update the

t-Axis max, open the Visualization Settings . To zoom in time, select the Zoom in Time option
from the Zoom menu and click and drag in the plot area to specify the time span.

Use the Update mode setting to specify whether the Simulation Data Inspector wraps or scrolls the
plot after the streaming data reaches the maximum time you specified.

31-119
31 Inspecting and Comparing Simulation Data

To closely examine signals throughout design iteration, add data cursors to your plots. You can add a
data cursor to the plot during simulation, while a simulation is paused, or after the simulation has

finished. To add a data cursor, click the cursor button . Drag the data cursor across the plot to
inspect signal values. When you display multiple signals on a plot, the data cursor indicates the value
for each signal in a color-coded box.

Click the drop-down on the cursors button and select Two Cursors to add a second data cursor and
explore temporal characteristics of your data. You can move each cursor independently, or you can
move them together. The number between the two cursors displays the time difference between the
cursors.

31-120
Iterate Model Design Using the Simulation Data Inspector

You can type directly into the box to specify a desired cursor separation. To move the cursors
together, click and hold the middle number indicator, and drag it across the graphical viewing area to
your desired position. For more information about using data cursors, see “Inspect Simulation Data”
on page 31-179.

Automatically Transfer View to Current Simulation


By default, the Simulation Data Inspector is configured to automatically archive simulation runs and
transfer a view from the previous run to the current simulation. When you run a new simulation, the
Simulation Data Inspector moves the prior simulation run to the archive and updates the view to
show aligned signals from the current run. You can control archiving by toggling the Automatically

archive setting. Click Preferences . Then, navigate to the Storage - Archive pane.

31-121
31 Inspecting and Comparing Simulation Data

For example, open the “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')
sldemo_fuelsys

Create a view of signals from the sldemo_fuelsys model. Then, simulate the sldemo_fuelsys
model again. The signals from the previous run clear from the plots, and the Simulation Data
Inspector plots data from the current simulation as the simulation runs. The previous run also moves
into the archive, reducing clutter in the work area.

31-122
Iterate Model Design Using the Simulation Data Inspector

You can access and plot data from previous runs from within the archive, and you can drag runs of
interest into the work area from the archive.

Control Data Retention


Running many simulations with logged signals can create a lot of data, especially during iterative
design and debugging workflows. To limit the amount of disk space occupied by logged data, you can
limit the amount of data the Simulation Data Inspector stores in the archive from the Storage -

Archive pane in the Preferences menu.

31-123
31 Inspecting and Comparing Simulation Data

By default, the Simulation Data Inspector does not limit the number of runs stored in the archive. To
impose a limit, select the Last runs radio button, and specify the desired limit. When the number of
runs in the archive reaches the limit, the Simulation Data Inspector deletes the run that has been in
the archive the longest. If the archive contains more runs than the limit you specify, the Simulation
Data Inspector provides a warning before deleting your run data.

Tip When you do not want the Simulation Data Inspector to store run data, specify an archive limit of
0. With an archive limit of 0 and Automatically archive enabled, the Simulation Data Inspector
automatically transfers your configured view to the current simulation and only retains the current
simulation data.

Visualize Many Logged Signals


You can use Browse Mode to inspect many signals quickly on Time Plot visualizations. To enable

Browse Mode, click Preferences . Then, select the Browse Mode radio button from the
Inspect - Selection pane.

31-124
Iterate Model Design Using the Simulation Data Inspector

Note To use Browse Mode, all subplots, including hidden subplots, must be Time Plot
visualizations.

In Browse Mode, signals selected in the navigation pane are plotted on the active Time Plot. You
can use the arrow keys on your keyboard to change the selected signals, and you can select multiple
signals by holding the Shift or Ctrl keys. When you select a row for a run or hierarchical
organization, no signals are displayed in the graphical viewing area.

31-125
31 Inspecting and Comparing Simulation Data

You can also use plot layouts in Browse Mode to make more complex visualizations. When the
graphical viewing area contains multiple subplots, selecting new signals using the mouse or keyboard
changes only the active plot.

31-126
Iterate Model Design Using the Simulation Data Inspector

To preserve axes limits when new signals are plotted, select Do not scale axes limits when

plotting new signals from the Inspect - Selection pane of the Preferences menu .

When you finish browsing your simulation results, enable Check Mode from the Inspect - Selection

pane of the Preferences menu . For more information about creating plots with the Simulation
Data Inspector, see “Create Plots Using the Simulation Data Inspector” on page 31-161.

See Also

Related Examples
• “Access Data in MATLAB Function During Simulation” on page 31-128
• “Inspect Simulation Data” on page 31-179
• “Compare Simulation Data” on page 31-203
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Inspect and Compare Data Programmatically” on page 31-219

31-127
31 Inspecting and Comparing Simulation Data

Access Data in MATLAB Function During Simulation


You can stream signal data to a MATLAB callback function during simulation using the Data Access
functionality in the Instrumentation Properties for a signal. The function you provide receives data
in packets asynchronously throughout the simulation. The callback function executes each time it
receives new data. You can write a callback function to process signal data during simulation or to
create a custom visualization of a signal. The callback function does not affect signal values in your
model. This example illustrates the steps required to access signal data during simulation using a
simple callback function that plots the signal.

Note Data access does not support Rapid Accelerator mode, referenced models, fixed-point data, or
virtual bus signals and only supports 1-D and 2-D matrix signals.

Write Callback Function for Data Access


The data access callback function always receives signal data as the first argument. You can choose
whether to send the simulation time and a parameter. When you include all three arguments,
simulation time is the second argument. Your callback function can be specific to a single signal, or
you can use the same callback to process and visualize multiple signals. The callback function only
has access to data for a single signal at a time. This example creates a callback function that receives
signal data, time, and a parameter used to identify which signal the function is processing for a given
call.

Note The data access callback function receives nonvirtual bus data as a structure of arrays that
matches the hierarchy of the bus.

Author your callback function in an m-file with the same name as your function. For more information
about writing MATLAB functions, see “Create Functions in Files”. The example callback function uses
the optional parameter to assign a numerical identifier to each signal. The parameter is used to
create a unique figure for each signal and assign each signal a different line color. To accumulate
signal data on the plot, the callback includes hold on. For each call to the callback, the function
receives a portion of the signal data. You can use the callback to accumulate the packets if desired.

function plotSignals(y,time,sigNum)

figure(sigNum)

if isequal(sigNum,1)
marker = "ro-";
elseif isequal(sigNum,2)
marker = "go-";
else
marker = "bo-";
end

hold on;
plot(time,y,marker);

end

31-128
Access Data in MATLAB Function During Simulation

The callback function provides no return values. If you specify the function with returns, the return
data is discarded.

Tip Use assignin to access data from the callback function in the base workspace.

Save the callback function in a location on the MATLAB path. If the location where you save the
callback is not on the path, you can add it to the path. Right-click the directory containing the
callback in the Current Folder section in MATLAB and select Add to Path.

Configure Signals for Data Access

Configure signals in the slexAircraftExample model to use the callback from the previous
section.

Open the slexAircraftExample model

mdl = "slexAircraftExample";
open_system(mdl)

To access data for a signal with the data access callback, you must log the signal. To mark the
alpha, rad, q rad/sec, and Stick signals for logging, select the signals. Then, right-click the
selected signals and from the context menu, select Log Selected Signals.

Alternatively, you can use the Simulink.sdi.markSignalForStreaming function to mark the


signals for logging.

lines = get_param('slexAircraftExample','Lines');
q_handle = lines(1).Handle;
alpha_handle = lines(2).Handle;
Stick_handle = lines(6).Handle;

Simulink.sdi.markSignalForStreaming(q_handle,"on")
Simulink.sdi.markSignalForStreaming(alpha_handle,"on")
Simulink.sdi.markSignalForStreaming(Stick_handle,"on")

To configure data access for the each signal, right-click the logging badge and select Properties. In
the Instrumentation Properties dialog box, on the Data Access tab, you can specify the name of your
callback function, whether the callback function takes time as an argument, and the optional
parameter value.

In the Instrumentation Properties dialog box, on the Data Access tab:

• In the Function name text box, enter the name of the callback, plotSignals.
• Select Include simulation time.
• In the Function parameter text box, enter 1 for the q, rad/sec signal, enter 2 for the alpha,
rad signal, and enter 3 for the Stick signal.

31-129
31 Inspecting and Comparing Simulation Data

Simulate the model. The callback generates Figures 1, 2, and 3 to display the q, rad/sec,
alpha,rad, and Stick signals during simulation.

sim(mdl);

You can modify the callback function to create a custom visualization or to create a plot of processed
signal data. Errors related to the data access callback function do not interrupt simulation. The errors
surface in the Diagnostic Viewer as a warning.

See Also
Instrumentation Properties | assignin | Simulink.sdi.markSignalForStreaming

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2

31-130
Analyze Multidimensional Signal Data

Analyze Multidimensional Signal Data


When you log or import multidimensional signal data with fixed dimensions into the Simulation Data
Inspector, you can choose to view and analyze data as:

• A single signal with multidimensional sample values


• A set of signals with scalar sample values: one signal, called a channel, for each element of the
multidimensional data

Variable-sized signals are always represented as a single signal with multidimensional values.

When the multidimensional data is frame-based, you can also use the Simulation Data Inspector to
remove the buffering from each frame.

You can control how you view and analyze multidimensional signal data using the Record block or the
Simulation Data Inspector. When you change the representation of a multidimensional signal in the
Record block, the change is reflected in the Simulation Data Inspector and vice versa.

Convert Representation of Multidimensional Data


The way the Simulation Data Inspector initially represents a multidimensional signal with fixed
dimensions depends on the number of elements in each sample of the signal. By default:

• Signals with samples that contain fewer than five elements are represented as channels.
• Signals with samples that contain five or more elements are represented as a single signal with
multidimensional sample values.

Note Variable-sized signals are always represented as a single signal with multidimensional sample
values and cannot be converted.

When the default behavior for a signal with fixed dimensions does not provide the representation you
need for your analysis, you can convert the representation from a single signal to channels or from
channels to a single signal.

For example, consider this output from a model that creates two composite signals using Mux blocks:

• Large Mux contains five elements and is displayed as a single signal by default.
• Small Mux contains two elements and is displayed as two channels by default.

The run includes one row for the Large Mux signal and three rows for the Small Mux signal. By
default, the Simulation Data Inspector groups signals by data hierarchy, so one row groups the
signals for each channel in the Small Mux signal, and each channel has a row.

Dimensions are indicated as part of the signal name in the table of signals under each run.

• When a multidimensional signal is represented as a single signal with multidimensional sample


values, the signal name row indicates the dimensions.
• When a multidimensional signal is represented as channels, the grouping row indicates the
dimensions.

31-131
31 Inspecting and Comparing Simulation Data

To convert the representation of a signal with multidimensional data, you can click the dimensions
and select an option from the menu. For example, to convert the Large Mux signal to channels, click
the dimensions, 5, and select Convert to channels.

To convert the Small Mux signal to a single signal, click the dimensions, 2, for the grouping row and
select Convert to multidimensional signal.

When you convert a signal from channels to a single signal, any plotted channels are cleared from the
view because the signals for the channels no longer exist.

You can also convert the representation of multidimensional signals in the Simulation Data Inspector
programmatically using the expand and collapse functions.

31-132
Analyze Multidimensional Signal Data

Plot Multidimensional Signal Data


Most visualizations in the Simulation Data Inspector, including time plots, XY plots, maps, and
sparklines, only support plotting scalar signals. To plot data from a multidimensional signal on one of
these visualizations, convert the signal to channels. You can use the conversion menus that you
access by clicking the signal dimensions or the menu that appears on a subplot that does not support
multidimensional data when you try to plot the signal.

For example, if you try to plot the Large Mux signal on a time plot, the menu gives you the option to
change the active subplot to an array plot, which does support multidimensional data, or to convert
the representation of the signal.

To view multidimensional data, use the array plot in the Simulation Data Inspector. The array plot
supports scalar and multidimensional signals, including variable-size signals. You can add an array
plot to the subplot layout using the menu that appears when you try to plot a multidimensional signal
on a plot that only supports scalar signals or using the Visualization Gallery. For more information
about using the array plot, see “View Multidimensional Signals Using the Array Plot” on page 31-68.
The Record block does not support the array plot.

Only time plots support plotting signals programmatically. You can plot channel data on a time plot
programmatically. You cannot plot data for a signal with multidimensional sample values
programmatically. Use the expand function to convert a single multidimensional signal to channels,
which you can plot on a time plot programmatically using the plotOnSubPlot function.

31-133
31 Inspecting and Comparing Simulation Data

Compare Multidimensional Signals


By default, when you compare multidimensional signals represented as a single signal or runs that
contain multidimensional signals represented as a single signal, the Simulation Data Inspector
converts the multidimensional signal to channels and computes a comparison result for each channel.
The conversion happens for the comparison only and does not affect the way the signal is represented
on the Inspect pane. The Simulation Data Inspector does not support comparing variable-size signals
or signals with multidimensional sample values.

If you do not want to compute comparison results for the channels in multidimensional signals, you
can configure comparisons to skip multidimensional signals instead of computing the channel results.
On the Compare pane, click More, then clear Expand multidimensional channels.

You can also configure whether programmatic comparisons compute results for multidimensional
signals using the Simulink.sdi.compareRuns function with the ExpandChannels name-value
argument.

Convert Representation of Frame-Based Data


Some applications buffer several samples of a signal into a frame to process with a single
computation instead of processing each sample in the frame separately. When you work with frame-
based signals, you can analyze the data frame by frame, or you can remove the buffering and analyze
the signal without the frames.

You can remove frame buffering from signals logged to the Simulation Data Inspector using the menu
that appears when you click the dimensions next to a multidimensional signal or the menu that
appears when you try to plot multidimensional data on a plot that only supports scalar data.

For example, consider this run created by logging data for the analog to digital converter output in
the model sfcndemo_frame. The model buffers the samples into a frame and performs a discrete
Fourier transform on each frame. To remove the frame buffering in the Simulation Data Inspector,
click the dimensions for the signal, 64×2, and select Convert frames. The conversion interprets
each sample as 64 evenly spaced samples with dimensions 1-by-2. Because the unbuffered signal only
contains two elements, conversion also displays the results as separate channels with scalar sample
values.

31-134
Analyze Multidimensional Signal Data

You can also convert the frames for a frame-based signal in the Simulation Data Inspector
programmatically using the convertToFrames function. The Simulation Data Inspector does not
support converting frames for imported data.

When you log frame-based data from a model, you can control how the data is logged by specifying
the Input Processing setting for the logged signal in the model using the Instrumentation Properties
dialog box or the Simulink.sdi.setSignalInputProcessingMode function. You can configure
the input processing for the signal as frame-based or sample-based.

• Sample-based — The logged data retains the buffering, and each sample of the logged signal
represents a frame. The Simulation Data Inspector interprets the data as a multidimensional
signal, where each element of a sample represents a separate channel.
• Frame-based — Logging removes the buffering and treats each column in the samples as a
separate channel.

When you log frame-based signals as sample-based, you can still convert the frames in the Simulation
Data Inspector after simulation.

See Also
Blocks
Record

Objects
Simulink.sdi.Run | Simulink.sdi.Signal

Functions
expand | collapse | convertToFrames | Simulink.sdi.setSignalInputProcessingMode

Tools
Instrumentation Properties | Simulation Data Inspector

Related Examples
• “View Multidimensional Signals Using the Array Plot” on page 31-68

31-135
31 Inspecting and Comparing Simulation Data

Analyze Data from Multiple Simulations


You can analyze data from multiple simulations by viewing the data from each simulation using the
same visualizations and subplot layout. With the Simulation Data Inspector, you can save the subplot
layout and configuration, including the plotted signal selection, as a view in an MLDATX file that you
can load to visualize data from another simulation. When the Simulation Data Inspector contains
multiple runs, you can also copy or cut the plotted signal selection from one run and then paste it
onto another to plot data from different runs side by side or easily swap which run supplies the data
for the plots.

This example shows how to use views and the cut, copy, and paste options in the Simulation Data
Inspector to analyze data from several simulations of the model sldemo_autotrans. For information
about analyzing simulation data using comparisons, see “Compare Simulation Data” on page 31-203.

Open and Simulate the Model

Open the model sldemo_autotrans, which models a controller for an automatic transmission
system. The model uses a Signal Editor block to load external input data to model the Throttle and
Brake signals for different vehicle maneuvers. In this example, you run several simulations and
analyze the system response to different vehicle maneuvers. For more information about the model
and the system it represents, see “Model an Automatic Transmission Controller”.

open_system('sldemo_autotrans');

Simulate the model for the default input scenario, which represents a passing maneuver. On the
Simulation tab, click Run.

Create and Save Views to Analyze Simulation Results


After simulating the model, analyze the simulation results by plotting signals on multiple time plots in
the Simulation Data Inspector. For example, visualize the input signals Throttle and Brake
alongside the EngineRPM and VehicleSpeed signals to see how the driver input to the vehicle
affects the vehicle speed.

Open the Simulation Data Inspector. On the Simulation tab, under Review Results, click Data
Inspector. Then, change the subplot layout in the Simulation Data Inspector to include four subplots,

one for each signal. To change the subplot layout, click Visualizations and layouts . Then, under
Basic Layouts, select the four-subplot layout.

31-136
Analyze Data from Multiple Simulations

Plot the Throttle signal on the top-left subplot. To plot the signal, select the subplot where you
want to plot the signal, then select the check box next to the signal. Plot the Brake signal on the
subplot below the Throttle signal, then plot the EngineRPM and VehicleSpeed signals on the
remaining subplots.

31-137
31 Inspecting and Comparing Simulation Data

To facilitate building the same visualization for subsequent simulations, save the view. In the
Simulation Data Inspector, click Layout, then select Save current view. Use the dialog box to specify
a name for the view and browse to the location where you want to save the view file. Alternatively,
you can save the view programmatically using the Simulink.sdi.saveView function. This example
saves the view with the name ThrottleBrakeVehicleSpeed.

After saving the view, clear the subplots so you can visualize another set of signals. Click Clear
Subplot, then select Clear all subplots.

Build another view to analyze the relationships among the EngineRPM, OutputTorque,
TransmissionRPM, and VehicleSpeed signals.

31-138
Analyze Data from Multiple Simulations

Save the view using the Simulink.sdi.saveView function or using the Simulation Data Inspector
UI. In the Simulation Data Inspector, click Layout, then select Save current view. This example
saves the view with the name RPMTorqueVehicleSpeed.

Load a View and Plot Signals Side by Side


Simulate the model again, using input data for the hard braking vehicle maneuver. To change the
input scenario the Signal Editor block loads, double-click the ManeuversGUI block. Then, from the
Active scenario list, select the Hard_braking scenario.

By default, when you simulate the model the second time, the Simulation Data Inspector updates the
plots in the current view with data from the current simulation and moves the prior simulation run
into the archive. To better understand the vehicle maneuver, load the first view that plots the
Throttle and Brake signals using the Simulation Data Inspector or the Simulink.sdi.loadView
function. To load the view using the Simulation Data Inspector UI:

1 Click Layout, then select Open saved view.


2 In the dialog box, select ThrottleBrakeVehicleSpeed.mldatx.
3 Click Open.

To adjust the zoom level for the signals from the new run, click Fit to View or press the space bar.

31-139
31 Inspecting and Comparing Simulation Data

Analyze the differences between the passing maneuver and hard braking maneuver by plotting the
same signals from each simulation side by side. Copy the plotted signal selection for the current run
and paste it onto the prior run in the archive.

1 To open the run actions menu for the current run, click the three dots on the right of the row for
the current run. Then, under Plotted signal selection, select Copy.

31-140
Analyze Data from Multiple Simulations

2 Click the arrow to expand the archive and access the prior run.

3 To open the run actions menu for the prior run, click the three dots on the right of the row for the
prior run in the archive. Then, under Plotted signal selection, select Paste.

31-141
31 Inspecting and Comparing Simulation Data

The cut, copy, and paste options work for all visualizations that plot signal data, including XY plots
and Maps.

Note The map visualization only supports displaying one route. When you copy and paste the
plotted signals selection for a view that includes a map, the map updates to display the route from the
run where you pasted the plotted signal selection.

Analyze the differences between the passing maneuver and hard braking simulations using the
second view.

1 Load the view RPMTorqueVehicleSpeed.mldatx.

Click Layout, then select Open saved view. Select the file RPMTorqueVehicleSpeed.mldatx
and click Open.
2
Click Fit to View or press the space bar.
3 Copy the plotted signal selection from the current run.
4 Paste the plotted signal selection from the current run onto the first run.

31-142
Analyze Data from Multiple Simulations

Swap Source Run for Plotted Signals


Simulate the model again, using input data for the gradual acceleration maneuver. To change the
input scenario the Signal Editor block loads, double-click the ManeuversGUI block. Then, from the
Active scenario list, select the Gradual_Acceleration scenario.

When you simulate the model again, the plots update to display data from the current run. To analyze
the vehicle maneuver, load the first view. Click Layout, then select Open saved view and select the
ThrottleBrakeVehicleSpeed view file. To adjust the axis limits for the new run data, click Fit to
View or press the space bar.

Suppose you want to view data from all three runs together. You can copy the plotted signal selection
from the current run and paste it onto both prior runs.

1 Open the run actions menu for the current run. Then, under Plotted signal selection, select
Copy.
2 Open the run actions menu for Run 1 in the archive. Then, under Plotted signal selection,
select Paste.
3 Open the run actions menu for Run 2 in the archive. Then, under Plotted signal selection,
select Paste.

31-143
31 Inspecting and Comparing Simulation Data

Now suppose you want to analyze each vehicle maneuver on its own. Using the run actions menu, you
can easily clear signals from a specific run from the view or clear signals from all runs except a
specific run from the view. Then, you can use the cut and paste options to swap which run provides
the data for the view.

To remove signals from the passing maneuver and hard braking maneuver simulations, open the run
actions menu for the current run and select Clear plotted signals in all other runs.

31-144
Analyze Data from Multiple Simulations

Only signals from the current run remain plotted.

31-145
31 Inspecting and Comparing Simulation Data

To update the view to plot only signals from the hard braking maneuver simulation, cut the plotted
signal selection from the current run and paste it onto Run 2 in the archive.

1 Open the run actions menu for the current run. Then, under Plotted signal selection, select
Cut.
2 Open the run actions menu for Run 2. Then, under Plotted signal selection, select Paste.

To update the view to plot only signals from the passing maneuver simulation, cut the plotted signal
selection from Run 2 and paste it onto Run 1.

1 Open the run actions menu for Run 2. Then, under Plotted signal selection, select Cut.
2 Open the run actions menu for Run 1. Then, under Plotted signal selection, select Paste.

31-146
Analyze Data from Multiple Simulations

You can repeat similar steps using the other view, RPMTorqueVehicleSpeed. Load the view using
the Simulink.sdi.loadView function or by clicking Layout and then selecting Open saved view.
Then, use the run actions menu to plot signals from each run side by side or on their own.

See Also
Simulink.sdi.loadView | Simulink.sdi.saveView

Related Examples
• “Create Plots Using the Simulation Data Inspector” on page 31-161
• “Save and Share Simulation Data Inspector Data and Views” on page 31-148

31-147
31 Inspecting and Comparing Simulation Data

Save and Share Simulation Data Inspector Data and Views

After you inspect, analyze, or compare your data in the Simulation Data Inspector, you can share your
results with others. The Simulation Data Inspector provides several options for sharing and saving
your data and results depending on your needs. With the Simulation Data Inspector, you can:

• Save your data and layout modifications in a Simulation Data Inspector session.
• Share your layout modifications in a Simulation Data Inspector view.
• Share images and figures of plots you create in the Simulation Data Inspector.
• Create a Simulation Data Inspector report.
• Export data to the workspace.
• Export data to a file.

Save and Load Simulation Data Inspector Sessions


If you want to save or share data along with a configured view in the Simulation Data Inspector, save
your data and settings in a Simulation Data Inspector session. You can save sessions as MAT or
MLDATX files. The default format is MLDATX. When you save a Simulation Data Inspector session,
the session file contains:

• All runs, data, and properties from the Inspect pane, including which run is the current run and
which runs are in the archive
• Plot display selection for signals in the Inspect pane
• Subplot layout and line style and color selections
• Current signal or run comparison in the Comparison pane

Note Comparison results and global tolerances are not saved in Simulation Data Inspector sessions.

To save a Simulation Data Inspector session:

1 Pause on the save icon on the left side bar. Then, click Save As.

2 Name the file.


3 Browse to the location where you want to save the session, and click Save.

For large datasets, a status overlay in the bottom right of the graphical viewing area displays
information about the progress of the save operation and allows you to cancel the save operation.

The Save tab of the Simulation Data Inspector preferences menu on the left side bar allows you to
configure options related to save operations for MLDATX files. You can set a limit as low as 50 MB on
the amount of memory used for the save operation. You can also set Compression to one of these
options:

31-148
Save and Share Simulation Data Inspector Data and Views

• None, the default, applies no compression during the save operation.


• Normal creates the smallest file size.
• Fastest creates a smaller file size than you would get by selecting None, but provides a faster
save time than Normal.

To load a Simulation Data Inspector session, click the open icon on the left side bar. Then,
browse to select the MLDATX file you want to open, and click Open.

Alternatively, you can double-click the MLDATX file. MATLAB and the Simulation Data Inspector open
if they are not already open.

When the Simulation Data Inspector already contains runs, loading a session file opens the Open
Session dialog box. Using the Open Session dialog box, you can choose to:

• Delete existing runs from the Simulation Data Inspector and add data from the session file to the
workspace.
• Keep existing data in the Simulation Data Inspector and add data from the session file to the
archive.

In both cases, the view updates to show plotted signals from the session file. You can drag runs
between the work area and archive as desired.

When the Simulation Data Inspector does not contain runs and you open a session, the Simulation
Data Inspector puts runs in the work area and archive as specified in the file.

Share Simulation Data Inspector Views


When you have different sets of data that you want to visualize the same way, you can save a view. A
view saves the layout and appearance characteristics of the Simulation Data Inspector without saving
the data. Specifically, a view saves:

• Plot visualization type, layout, axis ranges, linking characteristics, and normalized axes
• Location of signals in the plots, including plotted signals in the archive
• Signal grouping and columns on display in the Inspect pane
• Signal color and line styling

To save a view:
1
Click Visualizations and layouts .
2 In Saved Views, click Save current view.
3 In the dialog box, specify a name for the view and browse to the location where you want to save
the MLDATX file.
4 Click Save.

To load a view:
1
Click Visualizations and layouts .

31-149
31 Inspecting and Comparing Simulation Data

2 In Saved Views, click Open saved view.


3 Browse to the view you would like to load, and click Open.

Share Simulation Data Inspector Plots


Use the snapshot feature to share the plots you generate in the Simulation Data Inspector. You can
export your plots to the clipboard to paste into a document, as an image file, or to a MATLAB figure.
You can choose to capture the entire plot area, including all subplots in the plot area, or to capture
only the selected subplot.

Click the camera icon on the toolbar to access the snapshot menu. Use the radio buttons to
select the area you want to share and how you want to share the plot. After you make your selections,
click Snapshot to export the plot.

If you create an image, select where you would like to save the image in the file browser.

You can also create snapshots of your plots in the Simulation Data Inspector programmatically using
Simulink.sdi.snapshot.

Create Simulation Data Inspector Report

To quickly generate documentation of your results, create a Simulation Data Inspector report. You
can create a report of your data in either the Inspect or the Compare pane. The report is an HTML
file that includes information about all the signals and plots in the active pane. The report includes all
signal information displayed in the signal table in the navigation pane. For more information about
configuring the table, see “Inspect Metadata” on page 31-188.

To generate a Simulation Data Inspector Report:


1

Click the create report icon on the left bar.

31-150
Save and Share Simulation Data Inspector Data and Views

• When you create a report while viewing the Inspect pane, the report includes the plots and
signals from the Inspect pane.

• When you create a report while viewing the Compare pane, the report includes the data and
plots from the Compare pane. When you generate a comparison report, you can select
Report only mismatched signals or to Report all signals. If you select Report only
mismatched signals, the report shows only signal comparisons that are not within the
specified tolerances.

2 In the File text box, specify a filename and location of where you want to save the report.
3 Under Options, you can choose whether to prevent overwriting files and whether to use
shortened block paths in the report.
4 Click Create.

The generated report automatically opens in your default browser.

31-151
31 Inspecting and Comparing Simulation Data

Export Data to Workspace or File

You can use the Simulation Data Inspector to export data to the base workspace, a MAT file, or a
Microsoft Excel file. You can export a selection of runs and signals, runs in the work area, or all runs
in the Inspect pane, including the Archive.

When you export a selection of runs and signals, make the selection of data to export before clicking

the export button .

Only the selected runs and signals are exported. In this example, only the x1 signals from Run 1 and
Run 2 are exported. The check box selections for plotting data do not affect whether a signal is
exported.

When you export a single signal to the workspace or a MAT file, the signal is exported to a
timeseries object. Data exported to the workspace or a MAT file for a run or multiple signals is
stored as a Simulink.SimulationData.Dataset object.

To export data to a file, in the Export dialog box, select File. You can specify a filename and browse to
the location where you want to save the exported file. When you export data to a MAT file, a single
exported signal is stored as a timeseries object, and runs or multiple signals are stored as a
Simulink.SimulationData.Dataset object. When you export data to a Microsoft Excel file, the
data is stored using the format described in “Microsoft Excel Import, Export, and Logging Format” on
page 31-77.

To export to a Microsoft Excel file, for File, select the XLSX extension. When you export data to a
Microsoft Excel file, you can specify additional options for the format of the data in the exported file.
If the filename you provided already exists, you can choose to overwrite the entire file or to only
overwrite sheets containing data that corresponds to the exported data. You can also choose which
metadata to include and whether signals with identical time data share a time column in the exported
file.

31-152
Save and Share Simulation Data Inspector Data and Views

Export Video Signal to MP4 File


You can export a 2-D or 3-D signal that contains RGB or monochrome video data to an MP4 file using
the Simulation Data Inspector. For example, when you log a video signal in a simulation, you can
export the data to an MP4 file and view the video using a video player. To export a video signal to an
MP4 file:

1 Select the signal you want to export.


2

Click Export in the toolbar on the left, or right-click the signal and select Export.
3 In the Export dialog box, for Export, select Selected runs and signals. For To, select File.
4 Specify a filename and the path to the location where you want to save the file.
5 From the list, select MP4 video file, then click Export.

For the option to export to an MP4 file to be available:

• You must export only one signal at a time.


• The selected signal must be 2-D or 3-D and contain RGB or monochrome video data.
• The selected signal must be represented in the Simulation Data Inspector as a single signal with
multidimensional sample values.

You may need to convert the signal representation before exporting the signal data. For more
information, see “Analyze Multidimensional Signal Data” on page 31-131.
• The data type for the signal values must be double, single, or uint8.

Exporting a video signal to an MP4 file is not supported for Linux operating systems.

See Also
Functions
Simulink.sdi.saveView

Related Examples
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Inspect Simulation Data” on page 31-179
• “Compare Simulation Data” on page 31-203

31-153
31 Inspecting and Comparing Simulation Data

Create Interactive Comparison Reports

This example shows how to create an interactive web-based comparison report to share and archive
results for comparisons you perform using the Simulation Data Inspector. The report is a self-
contained HTML file, and viewing the report only requires a web browser. You can use the report to
analyze the comparison results similarly to how you would in the Simulation Data Inspector. You can
change the layout of the report between the interactive view and a printable view.

This example shows how to create an interactive comparison report using data loaded into the
Simulation Data Inspector from a session file. For information about importing data into the
Simulation Data Inspector or logging data from a simulation, see “View Simulation Data in Simulation
Data Inspector” on page 31-2.

Load and Compare Data

Open the Simulation Data Inspector and load the session file data into the Simulation Data Inspector.

Simulink.sdi.view
Simulink.sdi.load("dataToCompare.mldatx");

The session file contains data created by simulating the model slexAircraftExample. Both
simulations use the square wave input from the Pilot block in the model. Each simulation uses a
different time constant for the input filter. The first run contains simulation results for an input filter
time constant of 0.1. The second run contains simulation results for an input filter time constant of 1.

To analyze the effect of changing the input filter time constant, compare the runs that contain the
data for each simulation.

1 In the Simulation Data Inspector, navigate to the Compare tab.


2 From the Baseline list, select Run 1: slexAircraftExample.
3 From the Compare to list, select Run 2: slexAircraftExample.
4 Click Compare.

Alternatively, you can compare the runs programmatically using the Simulink.sdi.compareRuns
function.

runIDs = Simulink.sdi.getAllRunIDs;
runID1 = runIDs(end-1);
runID2 = runIDs(end);

diffRes = Simulink.sdi.compareRuns(runID1,runID2);

Generate Interactive Comparison Report

When you generate a comparison report to save the comparison results, specify:

• The data you want to include in the report.


• The title and author for the report.
• The filename and location.
• Options for avoiding overwriting existing reports and shortening block paths. Consider shortening
block paths when you log data throughout a model hierarchy.

31-154
Create Interactive Comparison Reports

To create the report, click Report .

For this example:

1 In the File text box, enter the folder path followed by the filename
slexAircraftExample_filterComparison.html.
2 In the Title text box, enter Compare: Ts = 0.1 vs. Ts = 1.
3 Under Content, select either option. In this example, all signals in the comparison do not match,
so the contents of the report are the same for either option.
4 Click Create Report.

The generated report automatically opens in the system browser. By default, the Simulation Data
Inspector saves the report with the filename New_Report.html in a folder called sdireports in the
working directory.

Inspect Comparison Results Using Interactive Report

The interactive report information and layout is similar to what you see on the Compare pane of the
Simulation Data Inspector. In the comparisons table, you can select the signal result you want to view
in the plots.

31-155
31 Inspecting and Comparing Simulation Data

The Properties table shows the metadata for the compared signals and highlights metadata that
differs. Scroll in the Properties table to see all the metadata. When the comparison contains more
signals than fit in the results table, you can scroll in the comparison table to inspect the results for
each signal comparison and sort the signals in the table by the data in each column.

For example, to sort the results by the maximum difference, click the Max Diff column.

31-156
Create Interactive Comparison Reports

You can adjust the size of the panes in the report by dragging the borders and adjust the widths of
the columns in each table by dragging the divisions between the column headings. For example, since
the comparison table does not use all the space in the signals pane, you could make the Properties
pane larger.

31-157
31 Inspecting and Comparing Simulation Data

The information in the table indicates that the comparison results for the Stick signal are out of
tolerance with a maximum difference of 0.78. In the model, the Stick signal is the output from a
Signal Generator block, and the filter time constant should not affect the block output. Select the
Stick signal to investigate the comparison results.

31-158
Create Interactive Comparison Reports

By inspecting the plots, you can see that the differences occur at the rising and falling edges of the
square wave. The slexAircraftExample model uses a variable-step solver. The differences occur
because the new time constant value changes the system dynamics, and the solver calculates slightly
different time steps for the second simulation. The transition of the square wave is sharp, so small
timing differences can result in large differences in magnitude.

Because the differences in the Stick signal are due to modeling rather than a real change in system
dynamics, you could go back to the Simulation Data Inspector and specify a small time tolerance (for
example, 0.01) for the Stick signal so the comparison results are within tolerance. To share the
updated results, you can generate a new comparison report.

Print Comparison Report

After finalizing the analysis and presentation of the comparison results, you can print a
comprehensive view of the results using the interactive web report. To switch to the printable view,
select the Printable radio button, or press Ctrl+P to see a print preview in the browser. In the
printable view, the metadata and plots for all signals are stacked, with the summary table at the top.

See Also
Simulink.sdi.report

Related Examples
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Compare Simulation Data” on page 31-203

31-159
31 Inspecting and Comparing Simulation Data

• “Save and Share Simulation Data Inspector Data and Views” on page 31-148

31-160
Create Plots Using the Simulation Data Inspector

Create Plots Using the Simulation Data Inspector


Plots can help showcase important features or trends in your data and allow you to share your
findings with others. The Simulation Data Inspector allows you to select from a variety of
visualization types and layouts and customize plot and signal appearances to present your data most
effectively.

Add Visualizations
You can choose from several visualizations to use for your data in the Simulation Data Inspector.

Icon Visualization Name Description


Time Plot Plot your signal data as a function of time. Time
plots are the default visualization for each
subplot.

Array Plot multidimensional data including variable-


sized signals.

For an example, see “View Multidimensional


Signals Using the Array Plot” on page 31-68.
Map Plot a route using longitude and latitude data on
either a street or satellite view.

For an example, see “View and Replay Map Data”


on page 31-32.
Sparklines Plot many signals at once.

For an example, see “View Many Signals


Together Using Sparklines” on page 31-60.

XY Plot relationships between time-aligned signals.

For an example, see:

• “Visualize Simulation Data on XY Plot” on


page 31-41
• “Analyze Data Using XY Plot” on page 31-52
Text Editor Add notes, observations, and conclusion to your
data with a rich text editor.

To view available visualizations in the Simulation Data Inspector, click Visualizations and layouts

. To add a visualization, click or drag the visualization icon onto the subplot.

31-161
31 Inspecting and Comparing Simulation Data

When you have many subplots, you can open the Visualization Gallery in a separate window and
reposition it with the plot area. Click Undock Visualization Gallery , then move the Visualization
Gallery to a different location.

31-162
Create Plots Using the Simulation Data Inspector

You can also add a visualization to a subplot using the subplot menu.

1 Pause on the subplot you wish to change. The name of the visualization currently in use appears
with three dots.
2 Click the three dots.
3 Choose a visualization from the Change Visualization drop-down list.

31-163
31 Inspecting and Comparing Simulation Data

Select Plot Layout


You can select from three types of layouts in the Simulation Data Inspector.

• Basic Layouts offer templates for layouts including up to four subplots.


• Overlays have overlay subplots in two corners of a main plot.
• Grid layouts create a grid of subplots according to dimensions you specify from 1×1 to 8×8.

To change the layout, click Visualizations and layouts .

Moving Between Subplot Layouts

When you plot a signal on a subplot, the Simulation Data Inspector links the signal to the subplot,
identifying the subplot with a number. As you move between subplot layouts, the association between
the signal and subplot remains, even as the shape or visibility of the subplot may change.

Subplots of Grid layouts follow column-wise numbering, from 1 at the top left subplot to 8 in the
bottom left, to 64 at the bottom right. The number system is fixed, regardless of which subplot
configuration you select. For example, if you display four subplots in a 2×2 configuration, the bottom
right subplot of the configuration is numbered 10, not 4. The number is 10 because in the largest
possible 8×8 matrix, that subplot is numbered 10 when you count the subplots in a column-wise
manner.

Basic Layouts subplots also use the fixed 8×8 column-wise numbering as a base. For example, the
top plot in this three-subplot layout is subplot 1, and the two subplots below it are 2 and 10.

In this three-subplot layout, the index for the right subplot is 9, and the indices for the two subplots
on the left are 1 and 2.

31-164
Create Plots Using the Simulation Data Inspector

For the Overlays layouts, the index for the main plot is always 1, and the indices for the overlaid
plots are 2 and 9.

View Simulation Data Using Time Plot

This example shows how to plot time series data using the Simulation Data Inspector. Simulation data
for this example is generated from a simulation of the slexAircraftExample model that logs the
output of the Actuator Model block and the Stick, alpha, rad, and q, rad/sec signals.

Open the model, mark signals for logging, and run a simulation.

1 Open the model.


2 To log the output of the Actuator Model block and the q, rad/sec, the Stick, and the alpha,
rad signals, select the signals in the model. Then, click Log Signals.
3 Click the Data Inspector button to open the Simulation Data Inspector.
4 Click Run to simulate the model.

Add the alpha, rad signal to the time plot by selecting the check box next to the signal name or by
dragging the signal onto the plot. By default, when you add a signal to an empty time plot, the
Simulation Data Inspector performs a fit-to-view.

31-165
31 Inspecting and Comparing Simulation Data

You can view more than one signal in a single time plot by selecting multiple check boxes. Add the
Stick signal to your time plot of the

alpha, rad signal.

31-166
Create Plots Using the Simulation Data Inspector

By default, when a new signal is added to a non-empty time plot, the Simulation Data Inspector
increases the y-axis limits if the range of the new signal is outside the current view. If the new signal
is viewable in the current view, the y-axis limits do not change. You can set the axes not to scale when
adding new signals to a plot:

1 Click Preferences.
2 Click the Inspect pane.
3 In the Inspect - Selection section, select Do not scale axes limits when plotting new
signals.

31-167
31 Inspecting and Comparing Simulation Data

Add Text to Plot Layout


You can use text to make the results of your data more clear. For example, add a text editor to your
plot layout when you want to present conclusions, descriptions, or observations alongside your data.
Try adding a text editor below your time series data. First, to add a subplot below the time plot, click

Visualizations and layouts . Then, select the vertically aligned two-plot layout from Basic

Layouts. Next, click or drag the Text Editor icon from the Visualizations and layouts menu onto
the lower subplot.

The text editor includes a toolbar for rich text formatting, including:

• Bullet points
• Numbered lists

31-168
Create Plots Using the Simulation Data Inspector

• Hyperlinks
• LaTeX equations

To change the visualization, clear text, maximize the subplot, or take a snapshot:

• Use the context menu by right-clicking the text editor subplot.


• Use the subplot menu by clicking the three dots in the upper-right corner of the text editor.

31-169
31 Inspecting and Comparing Simulation Data

Add Subplots to Visualize Data


Select the plot layout that best highlights the characteristics of your data. For example, with a basic
three-plot layout, you can use the large plot to show a main result and show intermediate signals on
the smaller plots.

1
Click Visualizations and layouts . Then, from Basic Layouts, choose the layout with one
large plot on top and two smaller plots below.
2
Click or drag the Time Plot icon from Visualizations and layouts onto the lower left subplot.
3 Add the Actuator Model signal to the lower left subplot by selecting the check box next to the
signal name or by dragging the signal onto the plot.
4 Add the q, rad/sec signal to the lower right subplot.

Customize Time Plot Appearance


After you choose a plot layout, you can customize the appearance of each visualization. To view

customization options, click Visualization Settings . The menu tabs correspond to the
visualizations in your layout.

31-170
Create Plots Using the Simulation Data Inspector

You can customize the appearance of time plots in the Simulation Data Inspector, including choosing
custom colors, choosing to show or hide attributes such as the grid or legend, and specifying axes
limits. To maximize the area in the visualization available for the plot, you can move the tick marks,
tick mark labels, and legend inside the plot or hide them.

The Limits section gives you control over the limits of the t- and y-axes. You may also choose to
normalize the y-axis. Except for the t-axis limits, the settings you configure in the Limits section
apply to the active subplot. To configure t-axis limits individually for a subplot, unlink the subplot. For
more information, see “Linked Subplots” on page 31-184.

To view the bottom graphs with the same y-axes, change the y-axis limits of the left graph to match
those on the right.

1 Select the q, rad/sec plot to view its y-axis limits in the Limits tab.
2 Select the Actuator Model plot as the active plot.
3 In the Limits section, change the y-axis limits of the Actuator Model plot to match the limits
of the q, rad/sec plot.

31-171
31 Inspecting and Comparing Simulation Data

Customize Signal Appearance


The Simulation Data Inspector allows you to modify the color, style, and line width of each signal. You
can select a signal color from a palette of standard colors or specify a custom color with RGB values.

You can access the line style menu for a signal in the Simulation Data Inspector or in the Simulink
Editor:

• In the Simulation Data Inspector, click the graphic representation in the Line column of the work
area or the Line row in the Properties pane.

31-172
Create Plots Using the Simulation Data Inspector

• From the Simulink Editor, right-click the logging badge for a signal, and select Properties to open
the Instrumentation Properties for the signal. Then, click the graphic representation of the
Line.

From the Instrumentation Properties, you can also select subplots where you want to plot the
signal. Changes made through the Instrumentation Properties take effect for subsequent
simulations.

If a signal is connected to a Dashboard Scope block, you can also modify the signal line style and
color using the Block Parameters dialog box. Changes to line style and color made in the Simulink
Editor remain consistent for a signal. When you change the line style and color in the Simulation Data
Inspector, the signal line style and color do not change in the Simulink Editor.

Line style customization can help emphasize differences between signals in your plot. For example,
change the line style of the Stick signal to dashed to visually indicate that it is an ideal, rather than
simulated, signal.

1 Click the Line column for the Stick signal.


2 Select the dashed option.
3 Click Set.

You can select easily distinguishable colors for all of the signals in your plot.

31-173
31 Inspecting and Comparing Simulation Data

1 Click the Line column for the alpha, rad signal.


2 Specify the desired color. This example uses the dark blue in the standard palette.
3 Click Set.

Shade Signal Regions


You can shade an area of a time plot to draw attention to a region of interest in the plotted data. For
example, you can highlight the area around a signal transition. First, add two cursors to the plot area
by clicking the arrow next to the Show/hide cursors button and selecting Two Cursors.

Next, click the arrow again and select Cursor Options. You can specify whether to emphasize or de-
emphasize the shaded area, the area to shade relative to the cursors, and the shading color and

31-174
Create Plots Using the Simulation Data Inspector

opacity. You can specify separate color and opacity settings for the Emphasize and De-emphasize
options.

For this example, in the Shading drop-down menu, select De-emphasize. In the Shade area drop-
down menu, select Lead and lag. Close the Cursor Options menu. The gray shading obscures the
area outside of the cursors and highlights the signal region between the cursors. Move the cursors to
highlight an area of interest, like the first rising edge of the waveform.

31-175
31 Inspecting and Comparing Simulation Data

You can use the Zoom in Time option to zoom in synchronously on the region of interest. Select
Zoom in Time from the Zoom In menu.

Then, click and drag to select a time span.

31-176
Create Plots Using the Simulation Data Inspector

You can use the Snapshot menu to save snapshots of highlighted signal regions. For more
information, see “Save and Share Simulation Data Inspector Data and Views” on page 31-148.

Rename Signals
You can rename signals in the Simulation Data Inspector when a more descriptive name can help
convey information. Changing a signal name in the Simulation Data Inspector does not affect signal
names used in models. You cannot rename buses or bus elements in the Simulation Data Inspector.

To change a signal name, double-click the signal name in the work area or archive, or edit the Name
field in the Properties pane. Change the name of the Actuator Model signal to Actuator
Output.

31-177
31 Inspecting and Comparing Simulation Data

See Also
Simulink.sdi.setSubPlotLayout | Simulink.sdi.Signal | plotOnSubPlot

More About
• “Save and Share Simulation Data Inspector Data and Views” on page 31-148
• “Inspect Simulation Data” on page 31-179
• “Compare Simulation Data” on page 31-203

31-178
Inspect Simulation Data

Inspect Simulation Data


You can use the Simulation Data Inspector to view and inspect signals from simulations or imported
data. The Simulation Data Inspector provides a comprehensive view of your data by allowing you to
arrange data from multiple simulations and sources on multiple subplots. You can zoom and pan
within plots and use data cursors for close examination of signal values, and you can replay data to
analyze signal relationships.

This example shows you how to view and inspect signal data from the model slexAircraftExample
using the Simulation Data Inspector.

Configure Signals for Logging


This example uses signal logging to send data to the Simulation Data Inspector. You can also import
signal data from the base workspace or a CSV, MDF, Microsoft Excel, or MAT-file. For more
information, see “View Simulation Data in Simulation Data Inspector” on page 31-2.

Open the model slexAircraftExample, mark several signals for logging, and run a simulation.

1 Open the model.

openExample('simulink_aerospace/AircraftLongitudinalFlightControlExample')
2 To log the q, rad/sec, the Stick, and the alpha, rad signals using signal logging, select the
signals in the model. Then, click Log Signals.

The logging badge appears above each signal marked for logging.
3 Double-click the Pilot block. Set Wave form to sine. Click OK.
4 On the Simulation tab, click Data Inspector to open the Simulation Data Inspector.
5 Simulate the model. The simulation run appears in the Simulation Data Inspector.

By default, the Inspect pane lists all logged signals in rows, organized by simulation run. You can
expand or collapse any of the runs to view the signals in a run. For more information on signal
grouping, see “Configure the Simulation Data Inspector” on page 31-90.

View Signals
To select signals you want to plot, use the check boxes next to the signals in the table. Select the
check boxes next to the q, rad/sec, Stick, and alpha, rad signals. When the signal you want to
plot is easier to find in the model, you can click the logging badge for the signal to plot it in the
Simulation Data Inspector.

31-179
31 Inspecting and Comparing Simulation Data

You can also use Browse Mode to quickly view all the signals in a run on time plots. For more
information, see “Visualize Many Logged Signals” on page 31-124.

View Signals on Multiple Plots


You can use subplot layouts to view groups of signals on different subplots. For example, you can
arrange the same signal from different simulation runs on the same subplot or view signals that have
a similar range of values.

1 In the model, double-click the Pilot block. Set Wave form to square. Click OK.
2 Simulate the model.
3 By default, the Simulation Data Inspector automatically moves prior runs into the archive and
transfers the view to the current run. Drag Run 1 from the archive into the work area.

31-180
Inspect Simulation Data

4
Click Visualizations and layouts and select the 2×1 plot layout.
5 Click the lower subplot. In the Inspect pane, select the check boxes for the q, rad/sec, Stick,
and alpha, rad signals under Run 1.

The check boxes in the Inspect pane indicate the signals plotted in the selected subplot, outlined
in blue.

31-181
31 Inspecting and Comparing Simulation Data

You can also move signals graphically rather than using the check boxes. Drag the signal from the
Inspect pane or another subplot to the subplot where you want to plot it.

For more information on working with plots, see “Create Plots Using the Simulation Data Inspector”
on page 31-161.

Zoom, Pan, and Resize Plots


You can closely inspect signals in a larger viewing area by maximizing a subplot or expanding the
view to full screen.


— Select Maximize to expand the active subplot to occupy the entire graphical viewing area.

— Select Full Screen to view your entire layout using your whole screen. The Simulation Data
Inspector automatically collapses the navigation pane so the view of the layout is as large as
possible.

You can zoom and pan within subplots that use a time plot visualization to inspect signal values and
the relationships between signals. You can access the zoom and pan controls from the toolbar above
the plots or from the subplot menu. Each icon allows you to control aspects of the plot using your

mouse .

31-182
Inspect Simulation Data

• You can select the action for the zoom button from the drop-down list.


When you want to zoom in on a selected area in the plot, select Zoom In. While you have
Zoom In selected, the Simulation Data Inspector adapts the zoom action it performs based on
the area of the plot you select. To zoom only in the y dimension, drag vertically. When you drag
horizontally, the Simulation Data Inspector zooms only in the t dimension. You can also click
and drag to zoom in on a rectangular region.

You can click the graphical viewing area to zoom in a fixed amount on both axes. Scrolling with
the mouse wheel zooms in and out on both axes.

Select Zoom Out to zoom out a fixed amount from the center of the subplot when you
click inside the graphical viewing area. You can also use Zoom Out to undo a previous Zoom
In operation.

Select Zoom in Time to make all mouse actions zoom on the t-axis. You can click the
graphical viewing area to zoom in a fixed amount. You can click and drag the graphical viewing
area to select a portion of the plot as the limits for the t-axis. Scrolling with the mouse wheel
zooms in and out on the t-axis.

Select Zoom in Y to make all mouse actions zoom on the y-axis. You can click in the
graphical viewing area to zoom in a fixed amount. You can also click and drag to select a
portion of the plot as the limits for the y-axis. Scrolling with the mouse wheel zooms in and out
on the y-axis.

With the mouse pointer selected, you can select signals by clicking them. Pan by clicking
anywhere on the plot and dragging the mouse.

31-183
31 Inspecting and Comparing Simulation Data

• You can select the fit action to scale the axes.


Select Fit to View to scale both the y and time axes to accommodate your plotted data.

Select Fit to View in Time to scale the t-axis to fit your data.

Select Fit to View in Y to scale the y-axis to fit your data.

Linked Subplots

Subplots are linked by default. Linked plots have a synchronized response when you perform actions
that change the time axis, including:

• Any pan operation involving the t-axis


• Any zoom operation involving the t-axis
• Any fit to view operation involving the t-axis
• Any adjustment to the t-axis limits

To inspect data independently in a subplot, you can unlink the subplot.


1 Select the subplot you want to unlink.
2 Click the Visualization Settings button in the upper right of the viewing area.
3 In the Limits section, clear the Link plot option.

The broken link symbol appears on the unlinked subplot.

Inspect Simulation Data Using Cursors


In the Simulation Data Inspector, you can inspect signals using data cursors. You can use one or two
cursors to inspect your data. To add two cursors, select Two Cursors from the Show/hide data
cursors drop-down list.

31-184
Inspect Simulation Data

With two cursors, three time values are displayed: the times that corresponded to each cursor
position and the time spanned by the cursors. You can move the two cursors together by dragging the
span label between the two cursors. You can also set the span by typing the desired value into the
label field.

Practice inspecting data with cursors using one cursor.

1
Select One Cursor from the Show/hide data cursors drop-down list .

31-185
31 Inspecting and Comparing Simulation Data

2 Drag the data cursor left or right to a point of interest. You can also use the arrow keys to move
the data cursor from sample to sample.

To inspect the data at a specific point in time, click the cursor time field and enter the desired
time value, for example, 35.5.

If the signal does not have a sample at the point of interest, the Simulation Data Inspector
interpolates the value for the indicated time. An asterisk in the data cursor label indicates that

31-186
Inspect Simulation Data

the displayed value is interpolated. For information regarding interpolation methods, see
“Interpolation” on page 31-216.

3
When you have finished inspecting the data, click Show/hide data cursors to remove the
cursor from the viewing area.

Replay Data
You can replay data in the Simulation Data Inspector to inspect signal value changes and
relationships between signals. Replaying data in the Simulation Data Inspector has no effect on any
models or simulations. To replay data, first show the replay controls by clicking Show/hide replay

controls . Then, press Replay .

The Simulation Data Inspector synchronously sweeps a cursor displaying the signal value across all
subplots in the view. By default, data replays at a rate of one second per second, which means that
replaying one second of data takes one second of clock time. You can adjust the replay speed using
the arrows on either side of the label or by clicking the label to type the desired speed. You can also
pause the replay and use the step forward and step backward buttons to inspect signal values sample
by sample. For a detailed example, see “Replay Data in the Simulation Data Inspector” on page 31-
198.

31-187
31 Inspecting and Comparing Simulation Data

Inspect Metadata
The Simulation Data Inspector allows you to view signal and run metadata in the Properties pane. In
the column on the right, you can edit properties using the white box. When you view a comparison,
the Simulation Data Inspector highlights metadata differences in red.

31-188
Inspect Simulation Data

You can also view metadata for signals as a table under each run in the Inspect pane. To choose

which signal properties to display, click Preferences and click Inspect. Select the columns
you want to display from the Inspect - Columns list. Columns appear in the table in the order in
which you select them.

31-189
31 Inspecting and Comparing Simulation Data

The table describes the metadata properties.

31-190
Inspect Simulation Data

Property Descriptions

Property Name Value


Line Signal line style and color
Stored Units Signal measurement units
Data Type Signal data type
Complexity Signal type — real or complex
Complex Format Format for visualizing complex data
Sample Time Type of sampling
Model Name of the model that generated the signal
Block Name Name of the signal's source block
Block Path Path to the signal's source block
Port Index of the signal on the block's output port
Dimensions Dimensions of the matrix containing the signal
Channel Index of signal within matrix
Run Name of the simulation run containing the signal
Absolute Tolerance User-specified, positive-valued absolute tolerance
for the signal
Relative Tolerance User-specified, positive-valued relative tolerance
for the signal
Override Global Tolerance User-specified property that determines whether
signal tolerances take priority over global
tolerances
Time Tolerance User-specified, positive-valued time tolerance for
the signal
Interp Method User-specified interpolation method used to plot
the signal
Sync Method User-specified synchronization method used to
coordinate signals for comparison
Time Series Root Name of the variable associated with signals
imported from the MATLAB workspace
Time Source Name of the array containing the time data for
signals imported from the MATLAB workspace
Data Source Name of the array containing the data for signals
imported from the MATLAB workspace
Description Description of signal
Display Units Units used to display signal
Domain Signal type for data created by logging simulation
data
Display Scaling Scaling used to display signal
Display Offset Offset used to display signal

31-191
31 Inspecting and Comparing Simulation Data

In the Compare pane, create a similar table of signal properties by choosing from the Compare -

Columns list in Preferences . Many parameters have a baseline signal and a comparison
signal that you can display independently. When a parameter does not specify baseline or comparison
signal, but both signals have the property, the column shows data for the baseline signal. In addition
to the parameters listed for the Inspect pane, the Compare pane has columns specific to
comparisons.

Property Name Value


Max Difference The maximum difference between the Baseline
and Compare to signals
Align By Primary signal alignment criterion specified in
the Compare - Alignment tab of the Simulation
Data Inspector Preferences menu

By default, the table displays a column for baseline name, absolute tolerance, relative tolerance,
maximum difference, and results of the comparison. For more information, see “Compare Simulation
Data” on page 31-203.

See Also

Related Examples
• “Compare Simulation Data” on page 31-203
• “Create Plots Using the Simulation Data Inspector” on page 31-161
• “Save and Share Simulation Data Inspector Data and Views” on page 31-148

31-192
Modify Signal Properties in the Simulation Data Inspector

Modify Signal Properties in the Simulation Data Inspector


You can modify signal display units, data type, and names in the Simulation Data Inspector. When you
modify the data type for a signal, the Simulation Data Inspector converts the signal values stored on
disk. Changes you make to signal properties in the Simulation Data Inspector do not affect any
models, files, or workspace variables.

You may want to save the original signal data or export modified signal data to use as simulation
input. You can export data from the Simulation Data Inspector to the workspace or a file. For more
information, see “Export Data to Workspace or File” on page 31-152.

This example uses data from a simulation of the slexAircraftExample model. To generate the data
for this example:

1 Open the model slexAircraftExample.

openExample('simulink_aerospace/AircraftLongitudinalFlightControlExample')
2 To log the q, rad/sec, the Stick, and the alpha, rad signals to the Simulation Data
Inspector, select the signals in the model. Then, right-click the selection, and select Log
Selected Signals from the context menu.
3 Double-click the Pilot block. Set Wave form to sine, and click OK.
4 Simulate the model.

Modify Signal Units


Signals in the Simulation Data Inspector have two unit properties: display units and stored units. To
analyze sets of data using consistent units, modify the display units for a signal. The Simulation Data
Inspector converts data when the stored units and display units for a signal differ such that signals
are always plotted using values that correspond to the display units. The units you specify are
properties of the signals in the Simulation Data Inspector only and do not affect the signal properties
in models. To learn how to specify units in a model, see “Unit Specification in Simulink Models” on
page 9-2.

The slexAircraftExample model does not specify units for its signals. However, some signal
names indicate the intended units.

1 In the Inspect pane, select the alpha, rad signal.


2 To view the properties for the selected signal, expand the Properties pane.
3 To specify units of radians for the signal, in the Properties pane, type rad into the white text
box next to the Display Units property.

For a list of units supported by Simulink, enter showunitslist into the MATLAB Command Window.

Now, the Simulation Data Inspector interprets the data for the alpha, rad signal as having units of
rad. When you specify display units for a signal without units, the specified units also set the value
for the stored units. Once a signal has units Simulink recognizes, you can convert the display units for
the signal to supported compatible units using the Simulation Data Inspector. When you click the
Display Units text box to modify the units, the Simulation Data Inspector provides a drop-down list
of compatible units.

31-193
31 Inspecting and Comparing Simulation Data

Change the alpha, rad signal display units to deg using the drop-down or by typing the new units
into the Display Units field. When you change the units, the Simulation Data Inspector performs the
conversion, and the plot updates to show the converted signal values.

31-194
Modify Signal Properties in the Simulation Data Inspector

You can also configure unit preferences in the Simulation Data Inspector to use units from a system of
measurement or consistent units for a measurement type, such as length, for all logged and imported
data. For more information, see “Signal Display Units” on page 31-96.

Note You can convert the stored units for a signal using the convertUnits function. Unit
conversion does not support undo and may result in loss of precision.

Modify Signal Data Type


You can modify the data type for a signal to analyze the effect on signal values or to create a signal to
use as simulation input. Converting the data type in the Simulation Data Inspector does not affect any
signal properties in the model. You can convert signal data types to all built-in data types. If you have
a license for Fixed-Point Designer, you can also convert to fixed-point data types. For a list of built-in
data types, see “Data Types Supported by Simulink” on page 73-4.

Note When you convert to a lower precision data type, you lose precision in the data that cannot be
recovered. You can save a copy of the data in the Simulation Data Inspector before changing signal
data types. For more information, see “Save and Share Simulation Data Inspector Data and Views” on
page 31-148.

The data type for the alpha, rad signal is double. Suppose you want to convert the data type to
single. First, select the alpha, rad signal. Then, expand the Properties pane and click the white
text field next to the Data Type property. You can type single or select it from the drop-down of
data types. The Simulation Data Inspector converts the data when you click outside the drop-down.

31-195
31 Inspecting and Comparing Simulation Data

Because the single data type has less precision than the double data type, the Simulation Data
Inspector returns a warning about irreversible precision loss. Click Continue. The plot shows no
visible difference in the signal. If you saved the data for the original signal, you can compare the
converted signal to analyze the effect of changing the data type. For more information on comparing
data in the Simulation Data Inspector, see “Compare Simulation Data” on page 31-203.

Fixed-Point Conversions

If you have a license for Fixed-Point Designer, you can convert signal data types to fixed-point data
types in the Simulation Data Inspector. Specify the data type in the Data Type property text box
using the fixdt function.

Modify Signal Names


You can modify the names of signals in the Simulation Data Inspector. Changing the name of a signal
in the Simulation Data Inspector does not affect signal names specified in the model. You can specify
a new name from the work area, the Archive, or the Properties pane. To modify the signal name,
click the signal name and type the new name. For example, change the name of the alpha, rad
signal to alpha because the Units property now has the units information.

31-196
Modify Signal Properties in the Simulation Data Inspector

When you export data from the Simulation Data Inspector after modifying the name, the exported
data uses the new name.

See Also

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Inspect Simulation Data” on page 31-179
• “Compare Simulation Data” on page 31-203
• “Create Plots Using the Simulation Data Inspector” on page 31-161

31-197
31 Inspecting and Comparing Simulation Data

Replay Data in the Simulation Data Inspector

This example shows how to replay data in the Simulation Data Inspector to inspect and build intuitive
understanding of your data. When you replay data, a cursor sweeps synchronously across all the
subplots in your view, displaying signal values. You can control the replay speed, pause to move the
cursor sample-by-sample, and zoom to inspect your data. You can replay imported data and data
logged from a simulation.

This example uses logged simulation data saved in a session. The session contains two runs of data
logged from the ex_vdp_mu model. Data from Run 1: ex_vdp_mu is plotted in the viewing area.

Load the session and open the Simulation Data Inspector to view the data.

Simulink.sdi.load('ex_vdp_mu.mldatx');
Simulink.sdi.view

Replay Data

When you replay data, the Simulation Data Inspector animates synchronized cursors to move through
a time period defined by the maximum time among the plotted signals. Replaying and pausing in the
Simulation Data Inspector has no effect on any models or simulations.

To show the replay controls in the Simulation Data Inspector, click the Show/hide replay controls

button.

Click the Replay button.

Synchronized cursors sweep across the subplots, indicating the signal value as the cursor moves in
time. By default, the Simulation Data Inspector replays data at a rate of one second per second,
meaning that the cursor moves through one second of data in the span of one second of clock time.
You can adjust the replay speed to suit the data you want to inspect. By default, the Simulation Data
Inspector replays at a speed of 1x. To change the speed, click one of the arrows on either side of the
speed label or click the label and enter your desired replay speed.

31-198
Replay Data in the Simulation Data Inspector

The Simulation Data Inspector moves the cursor based on the maximum time in the plotted signals
and the replay speed. The position of the cursor at a given time during replay does not depend on the
time values for samples in the plotted signals. When the cursor position does not correspond with a
sample in a plotted signal, the Simulation Data Inspector interpolates a value to display, using the
method defined in the Interpolation property of the signal. An asterisk at the end of the cursor value
indicates that the value is interpolated.

Inspect Data Values During Replay

To inspect sample values in your data, you can pause the replay. When the replay is paused, you can
use the Step forward and Step backward buttons to move the cursor sample-by-sample. The
cursors move to the next time point among all plotted signals. When a plotted signal does not have a
sample, the Simulation Data Inspector interpolates the value.

Pause the replay and use the Step forward and Step backward buttons to view the signal values.

31-199
31 Inspecting and Comparing Simulation Data

Zoom During Replay

You can zoom in on a region of your data during replay to inspect signal values and relationships
more closely. Viewing a portion of your signal can be particularly useful when your data spans a long
duration with a high sample rate. For example, plot the signals from Run 2: ex_vdp_mu.

The data in run 2 corresponds to a much longer simulation of the ex_vdp_mu model, where the value
of Mu changed over the course of the simulation. Viewing the entire signal at once makes analyzing
the changing characteristics of the curve difficult. Before replaying the data, change the Time span
in the Visualization settings to 100 to show the first 100 seconds. You can also collapse the
navigation pane to allow the viewing area to occupy more space. Then, replay the data.

31-200
Replay Data in the Simulation Data Inspector

When the cursor nears the end of the zoomed portion of the data, click the Fit to view button to
show the complete signal. Then, you can use the Zoom in time option to select another region of the
signal to inspect more closely during the replay.

31-201
31 Inspecting and Comparing Simulation Data

When replaying a long simulation, you can also adjust the replay speed or drag the time marker to
replay data in an area of interest.

See Also

More About
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “View Streaming Data in the Simulation Data Inspector” on page 31-98
• “Inspect Simulation Data” on page 31-179
• “Create Plots Using the Simulation Data Inspector” on page 31-161

31-202
Compare Simulation Data

Compare Simulation Data

The Simulation Data Inspector can compare the data and metadata for runs and individual signals
you import from the workspace or a file or log in a simulation. You can analyze comparison results
using tolerances, and you can configure the comparison behavior by specifying signal properties and
comparison constraints. This example uses data logged from simulations of the model
slexAircraftExample and shows how to:

• Compare signals and runs.


• Analyze comparison results using the Compare pane in the Simulation Data Inspector.
• Specify signal tolerances and global tolerances.
• Configure comparison constraints.

For more information on tolerance calculations and signal properties that affect comparisons, see
“How the Simulation Data Inspector Compares Data” on page 31-214. To compare data
programmatically, use the Simulink.sdi.compareRuns function or the
Simulink.sdi.compareSignals function.

Setup

This example continues from “Inspect Simulation Data” on page 31-179. You can also use this script
to generate the data required for the example.
load_system('slexAircraftExample')

% Configure signals to log


Simulink.sdi.markSignalForStreaming('slexAircraftExample/Pilot', 1, 'on')
Simulink.sdi.markSignalForStreaming('slexAircraftExample/Aircraft Dynamics Model', 3, 'on')
Simulink.sdi.markSignalForStreaming('slexAircraftExample/Aircraft Dynamics Model', 4, 'on')

% Change Pilot signal to sine


set_param('slexAircraftExample/Pilot', 'WaveForm', 'sine')

% Simulate model
sim('slexAircraftExample')

ans =
Simulink.SimulationOutput:
logsout: [1x1 Simulink.SimulationData.Dataset]
tout: [1235x1 double]
xout: [1x1 Simulink.SimulationData.Dataset]
yout: [1x1 Simulink.SimulationData.Dataset]

SimulationMetadata: [1x1 Simulink.SimulationMetadata]


ErrorMessage: [0x0 char]

% Change Pilot signal to square


set_param('slexAircraftExample/Pilot', 'WaveForm', 'square')

% Simulate Model
sim('slexAircraftExample')

31-203
31 Inspecting and Comparing Simulation Data

ans =
Simulink.SimulationOutput:
logsout: [1x1 Simulink.SimulationData.Dataset]
tout: [1381x1 double]
xout: [1x1 Simulink.SimulationData.Dataset]
yout: [1x1 Simulink.SimulationData.Dataset]

SimulationMetadata: [1x1 Simulink.SimulationMetadata]


ErrorMessage: [0x0 char]

Compare Signals
You can compare signals to analyze the relationship between two signals in a model. For example,
compare the Stick input signal to the output signal, alpha, rad.

1 Navigate to the Compare pane.


2 To view a list of signals available for comparison, expand the Baseline drop-down and select
Signals.

3 Select Stick (Run 1: slexAircraftExample).


4 Expand the Compare to drop-down and select alpha, rad (Run 1:
slexAircraftExample).
5 Click Compare.

Alternatively, you can select the Baseline and Compare to signals using the context menu by right-
clicking the signal in the Inspect pane.

The signals are not identical, so they do not match within the absolute, relative, and time tolerances,
all set to 0 by default.

31-204
Compare Simulation Data

Signal Time Tolerance

Looking at the top plot in the comparison view, you can see the alpha, rad signal lags the Stick
signal. For signal comparisons, the Simulation Data Inspector uses tolerance values specified for the
Baseline signal. Add a time tolerance to the Stick signal to account for the lag.

Select the Stick signal and enter 0.5 in the Time Tolerance field of the Properties pane. When
you specify a tolerance for a Baseline signal, its Override Global Tolerance field automatically
changes to yes. When you click away from the Time Tolerance field, the comparison runs again,
using the signal-level tolerance you specified. If you want to use global tolerance values for the
signal, click the Override Global Tolerance field and select no from the drop-down.

The Simulation Data Inspector draws the tolerance band around the plotted Baseline signal and
around the signed difference signal displayed in the bottom subplot. The bar along the top of the
difference plot shows regions within tolerance and out of tolerance for the comparison in green and
red.

31-205
31 Inspecting and Comparing Simulation Data

Signal Magnitude Tolerance

The time tolerance covers the phase difference between the two signals, but the comparison still
includes regions out of tolerance due to the amplitude difference. You can add a magnitude tolerance
as either an Absolute Tolerance or Relative Tolerance.

To add an absolute tolerance to the Stick signal, enter 0.05 into the Absolute Tolerance field in
the properties pane. With the combination of the absolute and time tolerances, the signal comparison
passes.

Note The Simulation Data Inspector draws the tolerance region using the most lenient interpretation
of the specified tolerances for each point. For more information on how the Simulation Data Inspector
calculates the tolerance band, see “Tolerance Specification” on page 31-216.

31-206
Compare Simulation Data

Compare Runs
You can also use the Simulation Data Inspector to compare all the signals in a run to all the signals in
another run. Run comparisons can provide useful information about the effects of changing model
parameters. For example, change the frequency cutoff of the filter for the control stick input signal.
Then, evaluate the effect on the logged signals using the Simulation Data Inspector.

1 To access the data in the model workspace, on the Modeling tab of the slexAircraftExample
model, under Design, click Model Explorer.
2 Click the arrow next to the model name and select Model Workspace.
3 Change the value of Ts from 0.1 to 1 and close the Model Explorer.
4 Simulate the model with the new filter.
5 In the Compare pane in the Simulation Data Inspector, expand the Baseline drop-down, and
select Runs.
6 From the list of runs, select Run 2: slexAircraftExample.
7 Expand the Compare to drop-down and select Run 3: slexAircraftExample.
8 Click Compare.

The Compare pane lists all signals from the compared runs and summarizes the results of the
comparison in the Results column. In this example, all three signals aligned, and none matched. You

31-207
31 Inspecting and Comparing Simulation Data

can click More to see the reason each signal comparison did not match. All three signals are out of
tolerance.

Note The Simulation Data Inspector only compares signals from the Baseline run that align with a
signal from the Compare To run. If a signal from the Baseline run does not align with a signal from
the Compare To run, the signal is listed in the Compare pane with a warning. For more
information on signal alignment, see “Signal Alignment” on page 31-214.

To plot a comparison result, select the signal you want to view in the Compare pane. For example,
select the result for the q, rad/sec signal. The top plot shows the q, rad/sec signals from the
Baseline and Compare To runs. The bottom plot shows the difference between the signals and the
calculated tolerance band.

31-208
Compare Simulation Data

Global Tolerances

To analyze the signals in the run comparison, you can specify global tolerances. To specify global
tolerances, click More. Under Global Tolerances, enter 0.75 for the time tolerance and 0.075 for
the absolute tolerance.

31-209
31 Inspecting and Comparing Simulation Data

Click the Compare button to run the comparison. The Simulation Data Inspector plots the tolerance
band around the Baseline signal and on the signed difference plot. With the new tolerance values,
the Stick and q, rad/sec signals pass the comparison.

View the alpha, rad signal to analyze the out of tolerance regions in the comparison result. Click

the arrow buttons in the toolbar to navigate through the out of tolerance regions. Two
cursors on the plot show the beginning and end of the first out of tolerance region. You can use your
keyboard arrows to explore the signal and tolerance values throughout each out of tolerance region.
To view the next out of tolerance region, click the right arrow button in the tool strip.

31-210
Compare Simulation Data

To resolve the out of tolerance regions, you can choose to modify the global tolerance values or to add
a signal-specific tolerance to the alpha, rad signal using the signal properties.

Configure Comparison Constraints


You can also apply constraints to comparisons that affect whether the result is a match or mismatch.
For example, you can specify that the time vectors for signals must match in order for the result to be
a match. To specify the constraint, click More, then select Signal time vectors must match. To run
a new comparison with this constraint, click Compare.

The comparison results show all signal results as mismatches now. The time vectors do not match for
any of the signals because they were logged from simulations of a model that uses a variable-step
solver, and the conditions changed between simulations. When the comparison result is a mismatch
due to a constraint, the Simulation Data Inspector does not compute results for that signal. When you
select a signal, the plot area shows an explanation of why the signal result is a mismatch.

31-211
31 Inspecting and Comparing Simulation Data

You can configure these comparison constraints:

• Signal data types must match


• Signal start and stop times must match
• Signal time vectors must match

When you require a match in signal metadata, specifying a constraint can return a mismatch result
more quickly because the comparison does not compute results when the specified metadata does not
match.

You can also configure a comparison to stop computing results after detecting the first mismatch
result. When you configure a comparison to stop on the first mismatch, the comparison always stops
after detecting the first mismatch in the signal metadata. You can also choose to stop the comparison
when the first mismatch result is due to an out-of-tolerance result when comparing the signal data.

The Simulation Data Inspector always aligns signals in the baseline and comparison runs and always
checks whether signal units match. When you configure a comparison to stop on the first mismatch,
signals that do not align and signals with units that do not match always cause a comparison to stop.
You can specify additional metadata for the comparison to check by selecting one or more
constraints.

31-212
Compare Simulation Data

Cancel Comparisons
The runs and signals used in this example are relatively small, and comparisons run quickly. When
you compare long signals or runs containing many signals, comparisons may take more time. The
Simulation Data Inspector displays incremental progress indicators during comparison, and the
Compare button becomes a Cancel button you can click to cancel the comparison at any point. For
hierarchical data, the Results column in the comparison view summarizes the results on each
hierarchical node.

See Also

Related Examples
• “How the Simulation Data Inspector Compares Data” on page 31-214
• “Inspect Simulation Data” on page 31-179
• “Share Simulation Data Inspector Views” on page 31-149
• “Create Plots Using the Simulation Data Inspector” on page 31-161

31-213
31 Inspecting and Comparing Simulation Data

How the Simulation Data Inspector Compares Data


You can tailor the Simulation Data Inspector comparison process to fit your requirements in multiple
ways. When comparing runs, the Simulation Data Inspector:

1 Aligns signal pairs in the Baseline and Compare To runs based on the Alignment settings.

The Simulation Data Inspector does not compare signals that it cannot align.
2 Synchronizes aligned signal pairs according to the specified Sync Method.

Values for time points added in synchronization are interpolated according to the Interpolation
Method specified for the Baseline signal.
3 Computes the difference of the signal pairs.

For all signal data types other than double, the software upcasts the data to double for
comparison.
4 Compares the difference result against specified tolerances.

When the comparison run completes, the results of the comparison are displayed in the navigation
pane.

Status Comparison Result


Difference falls within the specified tolerance.

Difference violates specified tolerance.

The signal does not align with a signal from the


Compare To run.

When you compare signals with differing time intervals, the Simulation Data Inspector compares the
signals on their overlapping interval.

Signal Alignment

In the alignment step, the Simulation Data Inspector decides which signal from the Compare To run
pairs with a given signal in the Baseline run. When you compare signals with the Simulation Data
Inspector, you complete the alignment step by selecting the Baseline and Compare To signals.

The Simulation Data Inspector aligns signals using a combination of their Data Source, Path, SID, and
Signal Name properties.

Property Description
Data Source Name of the variable in the MATLAB workspace
Path Block path for the source of the data in its model
SID Automatically assigned Simulink identifier
Signal Name Name of the signal in the model

With the default alignment settings, the Simulation Data Inspector aligns signals between runs
according to this flow chart.

31-214
How the Simulation Data Inspector Compares Data

You can specify the priority for each of the signal properties used for alignment in the Simulation
Data Inspector Preferences. The Align By field specifies the highest priority property used to align
signals. The priority drops with each subsequent Then By field. You must specify a primary
alignment property in the Align By field, but you can specify any number of the Then By fields as
None.

Synchronization

Often, signals that you want to compare don't contain the exact same set of time points. The
synchronization step in Simulation Data Inspector comparisons resolves discrepancies in signals' time
vectors. You can choose union or intersection as the synchronization method.

When you specify union synchronization, the Simulation Data Inspector builds a time vector that
includes every sample time between the two signals. For each sample time not originally present in
either signal, the Simulation Data Inspector interpolates the value. The second graph in the
illustration shows the union synchronization process, where the Simulation Data Inspector identifies
samples to add in each signal, represented by the unfilled circles. The final plot shows the signals
after the Simulation Data Inspector has interpolated values for the added time points. The Simulation
Data Inspector computes the difference using the signals in the final graph, so that the computed
difference signal contains all the data points between the signals over the intersecting time region.

When you specify intersection synchronization, the Simulation Data Inspector uses only the
sample times present in both signals in the comparison. In the second graph, the Simulation Data
Inspector identifies samples that do not have a corresponding sample for comparison, shown as
unfilled circles. The final graph shows the signals used for the comparison, without the samples
identified in the second graph.

31-215
31 Inspecting and Comparing Simulation Data

It is recommended to use union synchronization because it provides a more precise result. When you
use intersection synchronization, the comparison finishes quickly because the Simulation Data
Inspector computes the difference for fewer data points and does not interpolate. However, some
data is discarded and precision lost with intersection synchronization.

Interpolation
The interpolation property of a signal determines how the Simulation Data Inspector displays the
signal and how additional data values are computed in synchronization. When you compare two
signals, the Simulation Data Inspector uses the Interpolation Method specified for the Baseline
signal for both the Baseline and Compare To signals. You can choose to interpolate your data with a
zero-order hold (zoh) or a linear approximation. You can also specify no interpolation.

When you specify zoh or none for the Interpolation Method, the Simulation Data Inspector
replicates the data of the previous sample for interpolated sample times. When you specify linear
interpolation, the Simulation Data Inspector uses samples on either side of the interpolated point to
linearly approximate the interpolated value. Typically, discrete signals use zoh interpolation and
continuous signals use linear interpolation. You can specify the Interpolation Method for your
signals in the signal properties.

Tolerance Specification
The Simulation Data Inspector allows you to specify the scope and value of the tolerance for your
signal. You can define a tolerance band using any combination of absolute, relative, and time
tolerance values, and you can specify whether the specified tolerance applies to an individual signal
or to all the signals in a run.

31-216
How the Simulation Data Inspector Compares Data

Tolerance Scope

In the Simulation Data Inspector, you can specify the tolerance for your data globally or for an
individual signal. Global tolerance values apply to all signals in a run that do not have Override
Global Tol set to yes. You can specify global tolerance values for your data at the top of the
graphical viewing area in the Compare view. To specify signal specific tolerance values, edit the
signal properties and ensure the Override Global Tol property is set to yes.

Tolerance Computation

In the Simulation Data Inspector, you can specify a tolerance band for your run or signal using a
combination of absolute, relative, and time tolerance values. When you specify the tolerance for your
run or signal using multiple types of tolerances, each tolerance can yield a different answer for the
tolerance at each point. The Simulation Data Inspector computes the overall tolerance band by
selecting the most lenient tolerance result for each data point.

When you define your tolerance using only the absolute and relative tolerance properties, the
Simulation Data Inspector computes the tolerance for each point as a simple maximum.

tolerance = max(absoluteTolerance,relativeTolerance*abs(baselineData));

The upper boundary of the tolerance band is formed by adding tolerance to the Baseline signal.
Similarly, the Simulation Data Inspector computes the lower boundary of the tolerance band by
subtracting tolerance from the Baseline signal.

When you specify a time tolerance, the Simulation Data Inspector evaluates the time tolerance first,
over a time interval defined as [(tsamp-tol), (tsamp+tol)] for each sample. The Simulation Data
Inspector builds the lower tolerance band by selecting the minimum point on the interval for each
sample. Similarly, the maximum point on the interval defines the upper tolerance for each sample.

If you specify a tolerance band using an absolute or relative tolerance in addition to a time tolerance,
the Simulation Data Inspector applies the time tolerance first, and then applies the absolute and
relative tolerances to the maximum and minimum points selected with the time tolerance.

31-217
31 Inspecting and Comparing Simulation Data

upperTolerance = max + max(absoluteTolerance,relativeTolerance*max)

lowerTolerance = min - max(absoluteTolerance,relativeTolerance*min)

Limitations
The Simulation Data Inspector does not support comparing:

• Signals of data types int64 or uint64.


• Variable-size signals.

See Also

Related Examples
• “Compare Simulation Data” on page 31-203

31-218
Inspect and Compare Data Programmatically

Inspect and Compare Data Programmatically

You can harness the capabilities of the Simulation Data Inspector from the MATLAB command line
using the Simulation Data Inspector API.

The Simulation Data Inspector organizes data in runs and signals, assigning a unique numeric
identification to each run and signal. Some Simulation Data Inspector API functions use the run and
signal IDs to reference data, rather than accepting the run or signal itself as an input. To access the
run IDs in the workspace, you can use Simulink.sdi.getAllRunIDs or
Simulink.sdi.getRunIDByIndex. You can access signal IDs through a Simulink.sdi.Run
object using the getSignalIDByIndex method.

The Simulink.sdi.Run and Simulink.sdi.Signal classes provide access to your data and allow
you to view and modify run and signal metadata. You can modify the Simulation Data Inspector
preferences using functions like Simulink.sdi.setSubPlotLayout,
Simulink.sdi.setRunNamingRule, and Simulink.sdi.setMarkersOn. To restore the
Simulation Data Inspector's default settings, use Simulink.sdi.clearPreferences.

Create Run and View Data

Create a run, add data to it, and then view the data in the Simulation Data Inspector.

Create Data for Run

Create timeseries objects to contain data for a sine signal and a cosine signal. Give each
timeseries object a descriptive name.
time = linspace(0,20,100);

sine_vals = sin(2*pi/5*time);
sine_ts = timeseries(sine_vals,time);
sine_ts.Name = "Sine, T=5";

cos_vals = cos(2*pi/8*time);
cos_ts = timeseries(cos_vals,time);
cos_ts.Name = "Cosine, T=8";

Create Run and Add Data

Use the Simulink.sdi.view function to open the Simulation Data Inspector.


Simulink.sdi.view

To import data into the Simulation Data Inspector from the workspace, create a Simulink.sdi.Run
object using the Simulink.sdi.Run.create function. Add information about the run to its
metadata using the Name and Description properties of the Run object.
sinusoidsRun = Simulink.sdi.Run.create;
sinusoidsRun.Name = "Sinusoids";
sinusoidsRun.Description = "Sine and cosine signals with different frequencies";

Use the add function to add the data you created in the workspace to the empty run.
add(sinusoidsRun,"vars",sine_ts,cos_ts);

31-219
31 Inspecting and Comparing Simulation Data

Plot Data in Simulation Data Inspector

Use the getSignalByIndex function to access Simulink.sdi.Signal objects that contain the
signal data. You can use the Simulink.sdi.Signal object properties to specify the line style and
color for the signal and plot the signal in the Simulation Data Inspector. Specify the LineColor and
LineDashed properties for each signal.

sine_sig = getSignalByIndex(sinusoidsRun,1);
sine_sig.LineColor = [0 0 1];
sine_sig.LineDashed = "-.";

cos_sig = sinusoidsRun.getSignalByIndex(2);
cos_sig.LineColor = [1 0 0];
cos_sig.LineDashed = "--";

Use the Simulink.sdi.setSubPlotLayout function to configure a 2-by-1 subplot layout in the


Simulation Data Inspector plotting area. Then, use the plotOnSubplot function to plot the sine
signal on the top subplot and the cosine signal on the lower subplot.

Simulink.sdi.setSubPlotLayout(2,1);

plotOnSubPlot(sine_sig,1,1,true);
plotOnSubPlot(cos_sig,2,1,true);

31-220
Inspect and Compare Data Programmatically

Close Simulation Data Inspector and Save Your Data

When you finish inspecting the plotted signal data, you can close the Simulation Data Inspector and
save the session to an MLDATX file.

Simulink.sdi.close("sinusoids.mldatx")

Compare Two Signals in the Same Run

You can use the Simulation Data Inspector programmatic interface to compare signals within a single
run. This example compares the input and output signals of an aircraft longitudinal controller.

First, load the session that contains the data.

Simulink.sdi.load('AircraftExample.mldatx');

Use the Simulink.sdi.Run.getLatest function to access the latest run in the data.

aircraftRun = Simulink.sdi.Run.getLatest;

Then, you can use the Simulink.sdi.getSignalsByName function to access the Stick signal,
which represents the input to the controller, and the alpha, rad signal that represents the output.

stick = getSignalsByName(aircraftRun,'Stick');
alpha = getSignalsByName(aircraftRun,'alpha, rad');

Before you compare the signals, you can specify a tolerance value to use for the comparison.
Comparisons use tolerance values specified for the baseline signal in the comparison, so set an
absolute tolerance value of 0.1 on the Stick signal.

stick.AbsTol = 0.1;

Now, compare the signals using the Simulink.sdi.compareSignals function. The Stick signal is
the baseline, and the alpha, rad signal is the signal to compare against the baseline.

comparisonResults = Simulink.sdi.compareSignals(stick.ID,alpha.ID);
match = comparisonResults.Status

match =
ComparisonSignalStatus enumeration

OutOfTolerance

The comparison result is out of tolerance. You can use the Simulink.sdi.view function to open the
Simulation Data Inspector to view and analyze the comparison results.

Compare Runs with Global Tolerance

You can specify global tolerance values to use when comparing two simulation runs. Global tolerance
values are applied to all signals within the run. This example shows how to specify global tolerance
values for a run comparison and how to analyze and save the comparison results.

31-221
31 Inspecting and Comparing Simulation Data

First, load the session file that contains the data to compare. The session file contains data for four
simulations of an aircraft longitudinal controller. This example compares data from two runs that use
different input filter time constants.

Simulink.sdi.load('AircraftExample.mldatx');

To access the run data to compare, use the Simulink.sdi.getAllRunIDs function to get the run
IDs that correspond to the last two simulation runs.

runIDs = Simulink.sdi.getAllRunIDs;
runID1 = runIDs(end - 1);
runID2 = runIDs(end);

Use the Simulink.sdi.compareRuns function to compare the runs. Specify a global relative
tolerance value of 0.2 and a global time tolerance value of 0.5.

runResult = Simulink.sdi.compareRuns(runID1,runID2,'reltol',0.2,'timetol',0.5);

Check the Summary property of the returned Simulink.sdi.DiffRunResult object to see whether
signals were within the tolerance values or out of tolerance.

runResult.Summary

ans = struct with fields:


OutOfTolerance: 0
WithinTolerance: 3
Unaligned: 0
UnitsMismatch: 0
Empty: 0
Canceled: 0
EmptySynced: 0
DataTypeMismatch: 0
TimeMismatch: 0
StartStopMismatch: 0
Unsupported: 0

All three signal comparison results fell within the specified global tolerance.

You can save the comparison results to an MLDATX file using the saveResult function.

saveResult(runResult,'InputFilterComparison');

Analyze Simulation Data Using Signal Tolerances

You can programmatically specify signal tolerance values to use in comparisons performed using the
Simulation Data Inspector. In this example, you compare data collected by simulating a model of an
aircraft longitudinal flight control system. Each simulation uses a different value for the input filter
time constant and logs the input and output signals. You analyze the effect of the time constant
change by comparing results using the Simulation Data Inspector and signal tolerances.

First, load the session file that contains the simulation data.

Simulink.sdi.load('AircraftExample.mldatx');

31-222
Inspect and Compare Data Programmatically

The session file contains four runs. In this example, you compare data from the first two runs in the
file. Access the Simulink.sdi.Run objects for the first two runs loaded from the file.
runIDs = Simulink.sdi.getAllRunIDs;
runIDTs1 = runIDs(end-3);
runIDTs2 = runIDs(end-2);

Now, compare the two runs without specifying any tolerances.


noTolDiffResult = Simulink.sdi.compareRuns(runIDTs1,runIDTs2);

Use the getResultByIndex function to access the comparison results for the q and alpha signals.
qResult = getResultByIndex(noTolDiffResult,1);
alphaResult = getResultByIndex(noTolDiffResult,2);

Check the Status of each signal result to see whether the comparison result fell within our out of
tolerance.
qResult.Status

ans =
ComparisonSignalStatus enumeration

OutOfTolerance

alphaResult.Status

ans =
ComparisonSignalStatus enumeration

OutOfTolerance

The comparison used a value of 0 for all tolerances, so the OutOfTolerance result means the
signals are not identical.

You can further analyze the effect of the time constant by specifying tolerance values for the signals.
Specify the tolerances by setting the properties for the Simulink.sdi.Signal objects that
correspond to the signals being compared. Comparisons use tolerances specified for the baseline
signals. This example specifies a time tolerance and an absolute tolerance.

To specify a tolerance, first access the Signal objects from the baseline run.
runTs1 = Simulink.sdi.getRun(runIDTs1);
qSig = getSignalsByName(runTs1,'q, rad/sec');
alphaSig = getSignalsByName(runTs1,'alpha, rad');

Specify an absolute tolerance of 0.1 and a time tolerance of 0.6 for the q signal using the AbsTol
and TimeTol properties.
qSig.AbsTol = 0.1;
qSig.TimeTol = 0.6;

Specify an absolute tolerance of 0.2 and a time tolerance of 0.8 for the alpha signal.
alphaSig.AbsTol = 0.2;
alphaSig.TimeTol = 0.8;

31-223
31 Inspecting and Comparing Simulation Data

Compare the results again. Access the results from the comparison and check the Status property
for each signal.

tolDiffResult = Simulink.sdi.compareRuns(runIDTs1,runIDTs2);
qResult2 = getResultByIndex(tolDiffResult,1);
alphaResult2 = getResultByIndex(tolDiffResult,2);

qResult2.Status

ans =
ComparisonSignalStatus enumeration

WithinTolerance

alphaResult2.Status

ans =
ComparisonSignalStatus enumeration

WithinTolerance

See Also
Simulation Data Inspector

Related Examples
• “Compare Simulation Data” on page 31-203
• “How the Simulation Data Inspector Compares Data” on page 31-214
• “Create Plots Using the Simulation Data Inspector” on page 31-161

31-224
Keyboard Shortcuts for the Simulation Data Inspector

Keyboard Shortcuts for the Simulation Data Inspector


You can use several keyboard shortcuts to facilitate working with the Simulation Data Inspector. In
the table, where the shortcut looks like Ctrl+N, hold the Ctrl key and then press the N key to use the
shortcut.

Note On Macintosh platforms, use the command key instead of Ctrl.

General Actions
Task Shortcut
Start a new session Ctrl+N
Open a session Ctrl+O
Save a session Ctrl+S
Compare Ctrl+E
Link or unlink a subplot Ctrl+U
Delete a run or signal Delete

Plot Zooming
Task Shortcut
Zoom in time Ctrl+Shift+T
Zoom in y Ctrl+Shift+Y
Zoom in time and y Ctrl++

(Numeric keypad only)


Zoom out Ctrl+-

(Numeric keypad only)


Fit to view Space bar
Fit to time Ctrl+Alt+T
Fit to y Ctrl+Alt+Y
Cancel zoom operation or signal dragging Esc

Data Cursors
Task Shortcut
Show a data cursor Ctrl+I
Hide all data cursors Shift+Del
Move a selected data cursor to next data point Right arrow
Move a selected data cursor to previous data Left arrow
point

31-225
31 Inspecting and Comparing Simulation Data

Task Shortcut
Activate first (left) cursor Ctrl+1
Activate second (right) cursor Ctrl+2

Signal Table
Task Shortcut
Expand signal grouping Ctrl+Shift+d
Collapse signal grouping Ctrl+d

Import Dialog Box


These actions pertain to the import table.

Task Shortcut
Expand all nodes Shift+Ctrl+=
Collapse all nodes Ctrl+=
Select a node Space bar
Expand a single node Right arrow
Collapse a single node Left arrow

See Also
Simulation Data Inspector

Related Examples
• “Configure the Simulation Data Inspector” on page 31-90

31-226
32

Control Simulations with Interactive


Displays
32 Control Simulations with Interactive Displays

Tune and Visualize Your Model with Dashboard Blocks


In this section...
“Explore Connections Within the Model” on page 32-2
“Simulate Changing Model States” on page 32-3
“View Signal Data” on page 32-4
“Tune Parameters During Simulation” on page 32-5

The blocks in the Dashboard library help you control and visualize your model during simulation and
while the simulation is paused. This example uses the “Model Fault-Tolerant Fuel Control System”
example model sldemo_fuelsys to showcase the control and visualization capabilities of Dashboard
blocks. To open the model, use this command:
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')

Note Dashboard blocks in parent models cannot connect to signals and tunable parameters within
referenced models or across model reference boundaries. This limitation does not apply to subsystem
references. Dashboard blocks in referenced models and subsystem references not supported when
simulating the parent model.

Explore Connections Within the Model


The Dashboard subsystem contains blocks for controlling and visualizing signals in the Fault-Tolerant
Fuel Control System model. Explore the connections between the signals and Dashboard blocks. Click
either a signal or a Dashboard block to highlight the connections.

From the Dashboard subsystem, click the Toggle Switch in the Fuel panel. Hover the mouse over the
ellipsis above the block and then click the arrow above it to jump to the connected block or signal.

From the top level of the model, click the air_fuel_ratio signal and see the Dashboard subsystem,
Quarter Gauge, and Half Gauge highlighted.

32-2
Tune and Visualize Your Model with Dashboard Blocks

Simulate Changing Model States


In the Dashboard subsystem, switches provide control over the state of the throttle angle, engine
speed, EGO, and MAP signals. For each sensor signal, the switch toggles between normal and fail,
allowing you to simulate the system response to each single-point failure. Clicking any one of these
switches before simulation, during simulation, or while a simulation is paused changes the state in
the model.

Run the simulation and observe the control system response to each single-point failure.

1 Start the simulation.


2 As the simulation runs, click one of the switches to simulate a component failure.

Observe the changes in the fuel and air_fuel_ratio signals in the Dashboard Scope and
Gauge blocks when you flip each switch.
3 Stop the simulation when you are finished.

32-3
32 Control Simulations with Interactive Displays

View Signal Data


Dashboard blocks allow you to view signal data using gauges, lamps, and dashboard scopes. In this
example, the Dashboard blocks provide visual feedback about the fuel input and air-to-fuel ratio
during simulation, after simulation, and while a simulation is paused.

To capture different types of information and more effectively visualize a signal, connect multiple
Dashboard blocks to a single signal. For example, you can visualize the air_fuel_ratio signal
using the Gauge, Quarter Gauge, and Dashboard Scope blocks.

32-4
Tune and Visualize Your Model with Dashboard Blocks

Use the Quarter Gauge block, labeled Normal Range in the example, to see small fluctuations in the
instantaneous air_fuel_ratio signal while its value lies within the normal operational range. The
Gauge block, labeled Full Range, allows you to see the behavior of the instantaneous
air_fuel_ratio signal outside of the normal range. The Dashboard Scope block shows the
variations of the air_fuel_ratio signal over time.

Tune Parameters During Simulation


Dashboard blocks allow you to tune parameters in your model during a simulation. To explore the
tuning capability within the fuel system model, replace the engine speed Toggle Switch block with a
Knob:
1 Delete the engine speed Toggle Switch.
2 Add a Knob block from the Dashboard library.
3 Click the Connect button that appears when you pause on the Knob block. When you click the
Connect button, the Simulink Editor enters connect mode, which facilitates connecting
Dashboard blocks to signals and parameters in your model.

32-5
32 Control Simulations with Interactive Displays

4 Navigate to the top level of the model and select the Engine Speed block. The Engine Speed
block is a Constant block whose Constant value parameter you can tune with the Knob block.

When you select the Engine Speed block, the names of tunable parameters associated with the
block appear in a table.

5 Select the option button next to engine_speed in the table. Then, to exit connect mode, click
the Exit button in the upper-right of the model canvas.

Now that the Knob block is connected to the engine_speed parameter, you can set the tick interval
and range to values that make sense for the simulation. Double-click the Knob block to access the
block parameters. In this example, set Minimum to 75, Maximum to 750, and Tick Interval to 75.
Then, click OK.

Simulate the model and tune the engine_speed parameter using the Knob.

1 Start the simulation.


2 As the simulation runs, drag the pointer on the Knob to adjust the value of engine_speed.

Notice as you use the Knob to adjust the value of engine_speed, the air_fuel_ratio value
displayed on the Gauge blocks and in the Dashboard Scope block changes.
3 Stop the simulation when you have finished tuning the parameter.

See Also

Related Examples
• “Decide How to Visualize Simulation Data” on page 33-2

32-6
Connect Dashboard Blocks to Simulink Model

Connect Dashboard Blocks to Simulink Model


Create an interactive dashboard to tune the value of a variable or block parameter and monitor signal
values during simulation or while the simulation is paused. There are two types of dashboard blocks:

• Controls — Connect to block parameters or variables to tune values during simulation.


• Displays — Connect to signals to display the signal value during simulation.

You can also customize dashboard blocks to look like real system controls and displays by choosing
blocks from the Customizable Blocks library. For more information, see “Customizable Blocks”.

Dashboard blocks do not use ports to connect to model elements. Instead, use connect mode to easily
establish connections between dashboard blocks and elements in your model. Connect mode is
especially useful when you want to connect multiple dashboard blocks to your model. To connect a
single dashboard block, you can also use the connection table in the Block Parameters dialog box.

Connect Interactive Controls and Displays

The model ConnectDashboardBlocks contains a Sine Wave block and three Constant blocks. The
model also contains eight dashboard blocks that are not connected to the model yet. This example
shows how to quickly connect multiple dashboard blocks using connect mode, how to connect and
tune an interactive control and display using the Block Parameters dialog box, and how to disconnect
dashboard blocks from your model.

Connect One or More Dashboard Blocks Using Connect Mode

You can use dashboard blocks to tune and visualize your model during simulation.

• To tune the value of a variable or block parameter during simulation, you can connect a control
from the Dashboard library or Customizable Dashboard library.
• To view signal values during simulation, you can connect a display from the Dashboard library or
Customizable Dashboard library.

To quickly connect one or more dashboard blocks, enter connect mode.

For example, connect the three Slider blocks to the three Constant blocks, and connect the three
Linear Gauge blocks to the constant signals. To enter connect mode and connect the Slider blocks to
the corresponding Constant blocks:

1 Select or pause on a Slider block. For example, select the Slider block named Slider1.
2
Click the Connect button above the block.
3 Select the corresponding Constant block. For example, select the Constant block named
Constant1.
4 In the table of tunable parameters, select the parameter to tune. For example, select
Constant1:Value.

While in connect mode, you can connect the display blocks to signals in a similar way.

1 Select or pause on a Linear Gauge block. For example, select the Linear Gauge block named
Linear Gauge1.

32-7
32 Control Simulations with Interactive Displays

2
Click the Connect button above the block.
3 Select the corresponding signal. For example, select the signal named const1.
4 In the table, select the signal to display. For example, select const1.

When you are done connecting dashboard blocks to your model, to exit connect mode, click the Done

Connecting button above the last dashboard block you connected.

Connect and Tune Interactive Control

When you want to tune and connect a control dashboard block at the same time, you can use the
Block Parameters dialog box.

For example, suppose you want to use the Knob block to interactively change the amplitude of the
Sine Wave block to a value between 0 and 10. Connect the Knob block to the Amplitude parameter
of the Sine Wave block, and limit the values on the Knob block to your desired range.

32-8
Connect Dashboard Blocks to Simulink Model

1 To open the Block Parameters dialog box, double-click the Knob block. From the Block
Parameters dialog box, you can connect tunable parameters and specify the scale of the block.
2 Select the Sine Wave block.
3 In the table of available parameters to connect to, select Sine Wave:Amplitude.
4 To limit the scale of the Knob block, set Maximum to 10.

Connect and Tune Interactive Display to View Signal Values During Simulation

Similarly, you can also tune and connect a display dashboard block using the Block Parameters dialog
box.

For example, connect the Gauge block to the sineSig signal to view the values of the sine wave
during simulation. Since the possible values of the sine wave are between -10 and 10, you can scale
the Gauge block to correspond to the data.

1 To open the Block Parameters dialog box, double-click the Gauge block.
2 Select the sineSig signal.
3 In the table of available signals to connect to, select sineSig.

32-9
32 Control Simulations with Interactive Displays

4 To scale the Gauge block, set Minimum to -10 and Maximum to 10.

32-10
Connect Dashboard Blocks to Simulink Model

32-11
32 Control Simulations with Interactive Displays

Disconnect Dashboard Blocks

You can also disconnect dashboard blocks. For example, disconnect the Knob block from the Sine
Wave block.

1 Select the Knob block.


2 On the Knob tab, click Change Connection.
3 Select Disconnect.

Connect Dashboard Blocks to Matrices and Structures

This example shows how to connect a control block from the Dashboard library or the Customizable
blocks library to:

• An element of a matrix
• The field of a structure with a scalar value
• An element of a matrix that is stored in a structure

While you can pass structures from one block to another using buses, and you can connect a control
block to a field in a structure, connecting display blocks to buses is not supported.

Connect Control Block to Element of Matrix

In this example, you connect a Rocker Switch block from the Customizable blocks library to the
element in the second column of the row vector [1 2 3].

Open the model ConnectToMatrixElem.slx.

open('ConnectToMatrixElem')

The model contains a Constant block that connects to a Display block. The value of the Constant
block is the row vector [1 2 3]. The Display block shows the values of the row vector elements
during simulation.

Add a Rocker Switch block to the model using the Simulink® quick insert menu:

32-12
Connect Dashboard Blocks to Simulink Model

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Rocker Switch block, type Rocker Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:


1 Pause on the Rocker Switch block.
2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select Constant:Value.
5 To specify which element to connect to, in the text box, enter 2. Since the value of the Constant
block is a row vector, you can specify the element by entering the column number. If the value
were a column vector, you could specify the element using the row number. Alternatively, you can
specify the element using both the row and column numbers: (1,2).
6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

Run the simulation. Click the On and Off sides of the Rocker Switch block. When you click the Off
side of the switch, the value of the element in the second column of the row vector changes to 0, and
when you click the On side, the value changes to 1.

Stop the simulation.

Double-click the Constant block. Change the value of the Constant block to [1 2 3; 4 5 6].

32-13
32 Control Simulations with Interactive Displays

Connect the Rocker Switch block to the element in the second row and third column of the matrix.
1 Select the Rocker Switch block.
2 Pause on the ellipsis (...) that appears above the block.
3 In the action menu that expands, click the Connect button.
4 Click the Constant block.
5 To specify which element to connect to, in the text box, enter (2,3).
6 Press Enter.
7 Pause on the Display block.
8 Click the Done Connecting button that appears.

Run the simulation. Resize the display block to show the values of the two-by-three matrix. Click the
On and Off sides of the Rocker Switch block. Flipping the switch changes the value of the element in
the second row and third column of the matrix.

Connect Control Block to Field of Structure With Scalar Value

Suppose you have a structure that captures information about six gears in a transmission.

For each gear, the structure has these two fields:

• engaged specifies whether the driver has engaged the gear (0 for no, 1 for yes).
• fault specifies whether a fault is detected by the transmission system when the gear is engaged
(0 for no, 1 for yes).

In this example, you connect a Rocker Switch block from the Customizable blocks library to the field
in this structure that specifies whether the fourth gear is engaged.

Open the model ConnectToStructElem.slx.


open('ConnectToStructScalar')

The model uses a callback function to initialize the gear structure before the model loads. The top
level of the structure contains the names of the gears.
disp(gear)

first: [1x1 struct]


second: [1x1 struct]
third: [1x1 struct]
fourth: [1x1 struct]

32-14
Connect Dashboard Blocks to Simulink Model

fifth: [1x1 struct]


reverse: [1x1 struct]

The second level of the structure contains the fields engaged and fault.

disp(gear.fourth)

fault: 0
engaged: 0

The model contains a Constant block that connects to a To Virtual Bus block that connects to a
Display block. The value of the Constant block is the gear structure. The Display block shows the
values of the structure fields engaged and fault during simulation.

Update the diagram by pressing Ctrl+D (on macOS, press command+D).

Add a Rocker Switch block to the model using the Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Rocker Switch block, type Rocker Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:

1 Pause on the Rocker Switch block.


2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select gears(base workspace).
5 To specify which field to connect to, in the text box, enter fourth.engaged.
6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

32-15
32 Control Simulations with Interactive Displays

Run the simulation. Click the On and Off sides of the Rocker Switch block. When you click the Off
side of the switch, the value of the field labeled Fourth gear, engaged switches to 0. When you
click the On side of the switch, the value of the field labeled Fourth gear, engaged switches to 1.

32-16
Connect Dashboard Blocks to Simulink Model

Connect Control Block to Element of Matrix in Structure

Suppose you have five different laboratory stations, named A through E. During an experiment, for
each station, you record the temperature you set for the station and the average of the temperature
measured at the station over the duration of the experiment. You store the data in a structure. The
structure contains a field for each laboratory station, and each field contains a row vector that stores
the set and measured temperatures.

In this example, you connect a Knob block from the Customizable blocks library to the set
temperature of station B.

Open the model ConnectToStructMatrixElem.slx.

open('ConnectToStructMatrixElem')

The model uses a callback function to initialize the T structure before the model loads. The top level
of the structure contains the names of the laboratory stations.

disp(T)

stationA: [23 23.4000]


stationB: [19.5000 20.6000]
stationC: [23 22.2000]
stationD: [23 21.5000]
stationE: [25 24.4000]

The second level of the structure contains a row vector. The first column of the row vector specifies
the set temperature of the laboratory station. The second column specifies the measured
temperature.

disp(T.stationB)

19.5000 20.6000

The model contains a Constant block that connects to a To Virtual Bus block that connects to a
Display block. The value of the Constant block is the T structure. The Display block shows the set and
measured temperatures for each laboratory station.

Update the diagram by pressing Ctrl+D (on macOS, press command+D).

Add a Knob block to the model using the Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Knob block, type Knob.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:

1 Pause on the Rocker Switch block.


2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select T(base workspace).
5 You want to connect to the field corresponding to station B. The set temperature is specified in
the first column of the row vector stored in the field. In the text box, enter stationB(1,1).

32-17
32 Control Simulations with Interactive Displays

6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

Run the simulation. To turn the knob, click and drag the handle, or, on the scale, click the value you
want to turn the knob to. When you turn the knob, the set temperature of station B changes.

See Also

Related Examples
• “Connect Dashboard Blocks to Stateflow” (Stateflow)
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19
• “Decide How to Visualize Simulation Data” on page 33-2

32-18
Getting Started with Panels

Getting Started with Panels


A panel floats above the model canvas and follows you through the model hierarchy. Use panels to
monitor signals, tune parameters, and debug from anywhere in your model without adding collections
of dashboard blocks throughout the model.

You can use panels to model real dashboards, for example, the dashboard in your car. To model
displays and controls on the panel, such as gauges, lamps, knobs, buttons, and switches, you can
promote blocks to the panel from the Dashboard library, the Customizable Blocks library, and the
Aerospace Blockset Flight Instruments library.

Note To use panels saved in a referenced model, open the referenced model as a top model.

By default, the first panel you create in a model has a single tab. To model multiple dashboards, you
can make multiple panels or add tabs to a panel. For more information, see “Create Tabbed Panels”
on page 32-43.

When you want more of the canvas to be visible so that you can inspect or edit the model in the
canvas, you can collapse or hide a panel.

32-19
32 Control Simulations with Interactive Displays

This example shows you how to create, edit, and manage the visibility of a panel for testing a fuel
control system.

Open Example Model


Open the sldemo_fuelsys model from the “Model Fault-Tolerant Fuel Control System” example.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')

The sldemo_fuelsys model has a Dashboard subsystem that contains controls and indicators for
interactively simulating the model. Navigate inside the Dashboard subsystem.

The subsystem contains four areas: Inputs, Fault Injection, Fuel (g/s), and Air/Fuel
Ratio.

In this example, you create a panel that contains the control blocks from the Input and Fault
Injection areas.

For an example of how you can use such a panel, see “Use Panels to Monitor Signals and Control
Parameters” on page 32-37.

Create Panels
To create a new panel, do one of these:

• Directly promote a group of selected blocks to a new panel. Use this approach to create your first
panel in a model.
• Create an empty panel and populate it. The option for creating empty panels becomes available
after you create your first panel.

32-20
Getting Started with Panels

For example, create the first panel in the Dashboard subsystem by promoting the dashboard block in
the Inputs area to a new panel:

1 Select the block.


2 Pause on the ellipsis (…) that appears above the block.

Note If you select one or more blocks by dragging a selection box, the ellipsis appears at the
location where you release your pointer.
3
In the action bar that appears, click Promote to Panel .

The Toggle Switch block promotes to the panel, but the annotation Engine Speed (rad/s) does
not.

You can promote blocks to a panel only from the Dashboard library, the Customizable blocks library,
and the Aerospace Blockset Flight Instruments library. When you try to promote a selection
containing dashboard blocks and other blocks, only the dashboard blocks promote to the panel.

When you use panels, the blocks in the panel are not associated with the model in the same way as
blocks in the canvas. You cannot programmatically interact with blocks in panels using get_param,
set_param, gcb, or gcbh. Otherwise, blocks promoted to panels retain their interactive behavior.
You can connect dashboard blocks in a panel using connect mode, inspect block properties using the
Property Inspector, and modify connections during simulation. For more information about connect
mode, see “Connect Blocks Without Signal Lines” on page 1-43.

When you add your first panel to the model, in the Simulink Toolstrip, the Panels tab appears.

The Panels tab stays visible unless you save and close the model when it does not contain any panels.
If you save and close a model without panels, when you reopen the model, the Panels tab is no longer
visible. To restore the tab, promote one or more dashboard blocks to a panel.

Now that a panel exists in this model, you can create an empty panel. On the Panels tab, in the
Create section, click Add Empty Panel. An empty panel appears.

To delete the panel, select it and press Delete.

32-21
32 Control Simulations with Interactive Displays

Populate and Edit Panels


When the simulation is not running, you can edit panels and the blocks they contain.

To edit panels and their contents, you can use the options available:

• In the Simulink Toolstrip, on the Panels tab, in the Edit section


• In edit mode

To make any of these changes, enter edit mode:

• Move blocks from the panel to the canvas.


• Move blocks from one panel to another panel.
• Move blocks and annotations within a panel.
• Resize blocks in a panel.
• Annotate a panel.

To enter edit mode:

1 Click the panel.


2 Pause on the ellipsis (…) that appears.
3
In the action bar that expands, click Edit Panel .

To exit edit mode, click the canvas.

Promote Block to Existing Panel

You can promote blocks to an existing panel regardless of whether the panel already contains blocks.

For example, promote the blocks from the Fault Injection area to the panel you created in
“Create Panels” on page 32-20:

1 Enter edit mode.


2 Drag the borders of the panel outwards until all the blocks in the Fault Injection area fit
inside the panel borders.
3 Drag the panel away from the Fault Injection area so that the panel and area no longer
overlap. To drag the panel, click and hold down your pointer on the panel name or on any empty
spot inside the panel, then move the pointer.
4 Drag the blocks in the Fault Injection area into the panel.
5 To exit edit mode, click the canvas.

32-22
Getting Started with Panels

Move Block from Panel to Canvas

To move a block to the canvas, enter edit mode and drag the block from the panel to the canvas.

For example, move one of the blocks from the panel you created in “Promote Block to Existing Panel”
on page 32-22 to the canvas. To promote the block to the panel again, in edit mode, drag the block
back onto the panel. To exit edit mode, click the canvas.

Move Block from One Panel to Another Panel

To move a block from one panel to another panel, enter edit mode, then drag the block to the other
panel.

For example, move blocks from the panel you created in “Promote Block to Existing Panel” on page
32-22 into a new panel:

1 To create a blank panel, in the Simulink Toolstrip, on the Panels tab, in the Create section, click
Add Empty Panel.
2 Enter edit mode.
3 Resize the panel to be as large as the panel you created in “Promote Block to Existing Panel” on
page 32-22.
4 Move blocks from the panel you created in “Promote Block to Existing Panel” on page 32-22 to
the new panel by dragging them from one to the other.
5 Move the blocks back.

32-23
32 Control Simulations with Interactive Displays

6 To exit design mode, click the canvas.

Annotate Panels

You can add text annotations to a panel.

For example, consider the annotations in the Dashboards subsystem in the Inputs and Fault
Injection areas. Replicate these annotations in the panel you created in “Promote Block to Existing
Panel” on page 32-22:

1 Enter edit mode.


2 To add an annotation, double-click the panel where you want to add the annotation. For this
example, click in the upper left of the panel. Alternatively, create the annotation anywhere in the
panel and then drag it to the upper left of the panel.
3 Type Inputs.
4 Select the text. In the formatting menu above the text, click Bold.

5 Press Enter.
6 Add a second bold annotation with the text Fault Injection. Position it at the left edge of the
panel, above the blocks from the Fault Injection area.

7 Add the annotations for the dashboard blocks.

32-24
Getting Started with Panels

8 To exist edit mode, click the canvas.

To edit an annotation after you create it, double-click the annotation.

To delete an annotation, double-click the annotation and delete all of the text in it.

To move an annotation to a different panel, in edit mode, drag the annotation onto the other panel.

Resize Panels

To promote a block to a panel, the block must fit inside the dashed line that appears along the inside
of the panel perimeter when you enter edit mode. If your panel is too small to fit the block you want
to promote, resize the panel.

32-25
32 Control Simulations with Interactive Displays

To resize a panel and its contents together, such that the contents scale proportionally to the panel:

1 If you are in edit mode, click the canvas to exit edit mode.
2 Drag one of the corners of the panel.

When you are not in edit mode and you resize the panel, the panel maintains its aspect ratio. As you
resize the panel, the blocks in the panel scale proportionally.

For example, resize the panel you created in “Promote Block to Existing Panel” on page 32-22 with its
contents.

32-26
Getting Started with Panels

To resize a panel without resizing its contents:

1 Enter edit mode.


2 Click and drag one of the corners of the panel.

When you are in edit mode and you resize the panel, the panel does not maintain its aspect ratio. You
cannot drag a corner further inwards when doing so would cut off a block or an annotation.

For example, resize the panel you created in “Promote Block to Existing Panel” on page 32-22 without
its contents.

Rename Panels

The Simulink Editor names panels when you create them. The editor follows the naming sequence
Panel, Panel1, Panel2,Panel3, and so on. You can modify these names.

For example, rename the panel you created in “Promote Block to Existing Panel” on page 32-22 to
Inputs and Fault Injection:

1 In the Simulink Toolstrip, on the Panels tab, in the Edit section, click Rename Panel. The
Property Inspector appears with the Parameters tab open and the Name text box selected.

32-27
32 Control Simulations with Interactive Displays

2 In the Name text box, replace the selected text with Inputs and Fault Injection.

Add Background Image to Panel

You can make your panel look like a real dashboard by adding a background image.

For example, add a background image to the panel you created in “Promote Block to Existing Panel”
on page 32-22:

1 In the Simulink Toolstrip, on the Panels tab, in the Edit section, click Add Background.

Note If the panel already has a background image, click Replace Background.
2 Select an image and click Open.

32-28
Getting Started with Panels

3 To exit edit mode, click the canvas.

To delete a background image, select the panel. Then, in the Simulink Toolstrip, on the Panels tab, in
the Edit section, click Add Background > Remove Background.

Manage Panel Visibility


When you want more of the canvas to be visible so that you can inspect or edit the model in the
canvas, you can collapse or hide your panels.

When you lose track of your panels, you can gather them into the visible model window.

You can also open a panel in a new window.

Collapse Panels

When you want the panel to be readily accessible while you work in the canvas, you can collapse the
panel. Collapsed panels remain visible in the model, represented by icons.

For example, collapse and then expand the panel you created in “Promote Block to Existing Panel” on
page 32-22:

• To collapse a panel, double-click an empty area in the panel. The panel is replaced by a small blue
rectangular icon. The upper left corner of the icon is located where you clicked.

32-29
32 Control Simulations with Interactive Displays

Note You cannot collapse the panel in edit mode. Double-clicking the panel while in edit mode
creates an annotation.

• You can reposition the panel when it is collapsed.


• To restore the panel, double-click the icon. When you restore the panel, it expands downward and
to the right. The top and left edges of the restored panel line up with the top and left edges of the
panel in its collapsed state.

Open Panels in New Window

When you want the panel and the model to be in separate windows, you can open a panel in a new
window. You can minimize and restore the new window containing the panel separately from the
model window. From the panel window, you can run, pause, stop, and step through the simulation.

As an example, open the dashboard panel you created in “Promote Block to Existing Panel” on page
32-22 in a new window. Select the panel. Then, in the Simulink Toolstrip, on the Panels tab, in the
Manage section, click Open In New Window.

Alternatively, select the panel and pause on the ellipsis that appears. In the action menu that

expands, click Open in New Window .

Note If a panel contains Dashboard Scope blocks, you cannot open the panel in a new window during
simulation. To open the panel in a new window, stop the simulation.

If a panel has multiple tabs, the panel with all its tabs opens in a new window.

Minimize the model window. When you open a panel in a new window, you can interact with the panel
while the model window is minimized. If you work with multiple computer screens, the model and the
panel can be on different screens.

You can take these actions using the toolstrip in the panel window.

Action Toolstrip Buttons


Run simulation.

Pause simulation.

Stop simulation.

Step through simulation. To step back, the “Enable stepping back”


parameter must be set to on.

32-30
Getting Started with Panels

Action Toolstrip Buttons


Set simulation pacing. For more information about simulation pacing, see
Simulation Pacing Options.
Keep blocks in panel active. When a block is active, you can interact with it
without selecting it first. For example, when the Knob block is not active,
to turn the knob, you must first select the block, and then you can move
the block handle. When the Knob block is active, you can move the knob
handle without selecting the block first. You cannot select active blocks.

When a block is inactive, you can connect the block, change the element to
which the block connects, and jump to the element to which the block
connects.
Open panel in model canvas.

You can also change the simulation stop time by entering a new stop time, specified in seconds, in the
Stop Time text box.

As an example, in the panel window you opened, change the simulation stop time to 5 seconds. Then,

click Run . While the simulation is running, modify the position of one or more of the Slider
Switch blocks to simulate a failure in the system.

To have more time to operate the controls before the simulation ends without changing the stop time,

use simulation pacing. Once the simulation finishes, click Simulation Pacing . Then, select
Enable pacing to slow down simulation and move the slider to about 0.8. Run the simulation
again. The stop time is the same, but you have more time to change the position of the Slider Switch
blocks.

To return the panel to the model canvas, click Open in canvas .

To hide the panel, close the panel window. To unhide the panel, in the Simulink Toolstrip, on the
Panels tab, in the Manage section, click Manage Panels. In the Manage Panels menu that
appears at the bottom right corner of the model window, click the image of the panel.

Dock Panels

You can dock dashboard panels to the Simulink Editor. You can use the docked panel to monitor
signals and control parameters during simulation without covering the model diagram in the canvas.

As an example, dock the dashboard panel you created in “Promote Block to Existing Panel” on page
32-22.

1 Select the panel. The panel you created in “Promote Block to Existing Panel” on page 32-22 only
has one tab. To dock a panel with multiple tabs, select any tab.
2 Pause on the ellipsis (…) that appears.
3
In the action menu that expands, click Dock .

32-31
32 Control Simulations with Interactive Displays

If the model is open in multiple Simulink windows, when the panel docks in one window, it disappears
from the other windows.

By default, panels dock to the right edge of the Simulink Editor. To see where else you can dock the
panel, click the canvas. A blue outline appears around the canvas. You can move the docked panel to
the left, top, or bottom of the outlined area. To do so, drag the title bar of the docked panel over the
side of the outline to which you want to move the docked panel. When a blue area appears, drop the
panel.

As an example, move the panel you docked to the left edge of the editor.

Also by default, the docked panel is pinned open.


To minimize and unpin the docked panel, click the down arrow and select Minimize. The
docked panel disappears from view, and a tab appears at the right edge of the Simulink Editor.
The tab has the name of the docked panel. To view the docked panel, click the tab. To minimize
the docked panel again, click anywhere in the canvas.
• To restore and pin open the docked panel, click the docked panel tab. Click the down arrow and
select Restore.

32-32
Getting Started with Panels

To hide the docked panel, close the docked panel window. To unhide the docked panel, in the
Simulink Toolstrip, on the Panels tab, in the Manage section, click Manage Panels. In the Manage
Panels menu that appears at the bottom right corner of the model window, click the image of the
panel.

To select control blocks such as buttons, knobs, sliders, or switches, the control blocks must be
inactive. The same is true if you want to connect control blocks, to change the elements to which
control blocks connect, or to jump to the element to which a block connects.

Inactive means that you must select the block before you can interact with the block. For example,
when a Knob block is inactive, clicking the scale only selects the block. To move the handle, you must
click a second time. When a Knob block is active, clicking the scale moves the handle. When a block
is active, it is not possible to select or connect the block.

All control blocks are active during simulation. By default, the blocks in a docked panel are locked in
active mode, meaning they are active even when the simulation is not running. To make the blocks

inactive when the simulation is not running, click the Lock Panel button .

As an example, in the docked panel you created, make the blocks inactive by clicking the Lock Panel

button . Flip one of the slider switches in the panel. To do so, you must first select the Slider
Switch block. Then, you can click to flip the switch. Select the Lock Panel button again. Flip the
switch back. Since the block is active, you no longer need to select the Slider Switch block before you
can flip the switch.

To return the docked panel to the canvas, click Open in canvas . To open the docked panel in a

new window, click Open in new window .

You can dock multiple panels. By default, all panels dock to the right edge of the Simulink Editor, and
only one docked panel is displayed. To view a panel that is not displayed, click the corresponding tab
below the visible docked panel.

Tip When you minimize and restore multiple docked panels, multiple docked panels may be visible at
once. To view only one, drag the title bar of one docked panel to the center of a second docked panel.
When a blue area appears, release the panel. If more than two docked panels are visible at once, drag
the title bars of all other docked panels to the center of the same docked panel.

Hide Panels

When you want the panel to disappear from view completely but you do not want to delete it, you can
hide the panel.

As an example, hide and then restore the panel you created in “Promote Block to Existing Panel” on
page 32-22:

• To hide the panel, select the panel. Then, in the Simulink Toolstrip, on the Panels tab, in the
Manage section, select Manage Panels > Hide Panel.
• To restore the panel, in the Simulink Toolstrip, on the Panels tab, in the Manage section, click
Manage Panels. In the Manage Panels menu that appears at the bottom right corner of the

32-33
32 Control Simulations with Interactive Displays

model window, you can toggle the visibility of a panel on or off by clicking its image. Click the
panel image to unhide the panel.

Tip To hide or unhide all panels in the model, click the eye icon above the Manage Panels menu.

Gather Panels into Visible Section of Canvas

Since panels are positioned relative to the canvas and do not scale with zoom actions, panels may
move off the edge of the model window in part or in full. To gather all panels in your model into the
visible canvas, in the Simulink Toolstrip, on the Panels tab, in the Manage section, click Fit Panels
to View.

Note The Fit Panels to View button does not affect panels that you hide using the Manage Panels
menu or the Hide Panel button in the Simulink Toolstrip.

Fit Panels to View also scales all non-collapsed panels up as large as possible within the visible
canvas. To fit a single panel to view, you can also press the space bar.

For example, move part of the panel you created in “Promote Block to Existing Panel” on page 32-22
past the edge of the model window.

32-34
Getting Started with Panels

Then, in the Simulink Toolstrip, on the Panels tab, in the Manage section, click Fit Panels to View.
The panel moves and resizes to fit in the model window.

32-35
32 Control Simulations with Interactive Displays

Move Panel in Front of or Behind Overlapping Panels

If two or more panels overlap forming a stack of panels, you can change which one appears at the
front and back of the stack.

For example, make a copy of the panel you created in “Promote Block to Existing Panel” on page 32-
22, move one panel over the other, then switch their order in the stack:

1 If you are in edit mode, exit edit mode.


2 To create a copy, press Ctrl and drag the panel.
3 Make the panels overlap by dragging one under or over the other. They do not need to overlap
completely.
4 Select the panel in the front of the stack.
5
Click Send to Back . The panel in the front of the stack moves to the back of the stack.
6 Select the panel at the back of the stack.
7
Click Bring to Front . The panel at the back of the stack moves to the front of the stack.

See Also

Related Examples
• “Use Panels to Monitor Signals and Control Parameters” on page 32-37
• “Create Tabbed Panels” on page 32-43
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Design Custom Buttons” on page 32-121

32-36
Use Panels to Monitor Signals and Control Parameters

Use Panels to Monitor Signals and Control Parameters


A panel floats above the model canvas and follows you through the model hierarchy. Using panels,
you can monitor signals, tune parameters, and debug from anywhere in your model without adding
collections of dashboard blocks throughout the model.

You can use panels to model real dashboards, for example, the dashboard in your car. To model
displays and controls on the panel, such as gauges, lamps, knobs, buttons, and switches, you can
promote blocks to the panel from the “Dashboard” library, the “Customizable Blocks” library, and the
“Aerospace Blockset” library.

For information about how to create, populate, edit, and manage the visibility of panels, see “Getting
Started with Panels” on page 32-19.

In this example, you simulate sensor failures in a fuel control system. You use panels to control the
parameter values that activate different failure modes and to monitor the effect on fuel consumption.

Open Example Model


Open the sldemo_fuelsys model from the “Model Fault-Tolerant Fuel Control System” example.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')

The sldemo_fuelsys model has a Dashboard subsystem that contains controls and indicators for
interactively simulating the model. Navigate inside the Dashboard subsystem.

The subsystem contains four areas: Inputs, Fault Injection, Fuel (g/s), and Air/Fuel
Ratio.

This example creates and then utilizes a panel that contains the control blocks from the Fault
Injection area and a panel that contains the display blocks from the Fuel (g/s) area.

32-37
32 Control Simulations with Interactive Displays

Create Panels
If you already created a panel containing the dashboard blocks and annotations from the Fault
Injection or Fuel (g/s) areas by working through the examples in “Getting Started with Panels”
on page 32-19 or “Create Tabbed Panels” on page 32-43, skip the task for creating that panel.

To create the Fault Injection panel, promote the dashboard blocks in the Fault Injection
area to a panel:
1 Draw a selection box around the blocks. Where the selection box ends, an ellipsis appears.

2 Pause on the ellipsis.


3
In the action bar that expands, click Promote to Panel . The dashboard blocks are promoted
from the area to the panel, but the annotations are not.

Add the annotations from the Fault Injection area to the panel:

32-38
Use Panels to Monitor Signals and Control Parameters

1 Select the panel.


2 Pause on the ellipsis (…) that appears.
3
In the action bar that expands, click Edit Panel .
4 Drag the lower left corner of the panel to the left to make room for the annotations.

5 To see the annotations in the Fault Injection area, drag the panel away from the area. To
drag the panel, click and hold down your pointer on the panel name or on any empty spot inside
the panel, then move the pointer.
6 For each annotation from the Fault Injection area, double-click the panel where you want
the annotation, then type the annotation text. When you finish typing, press Enter. You can drag
the annotations to move them around the panel.
7 When you finish, click the canvas.
8 To rename the panel, in the Simulink Toolstrip, on the Panels tab, in the Edit section, click
Rename Panel. The Property Inspector appears. On the Parameters tab, in the Name text box,
type Fault Injection.

32-39
32 Control Simulations with Interactive Displays

Use the same approach to create the Fuel (g/s) panel from the dashboard blocks in the Fuel
(g/s) area.

Now you have modular panels to use while interactively simulating the sldemo_fuelsys model.

32-40
Use Panels to Monitor Signals and Control Parameters

Simulate Model
Suppose you need to understand and debug the fuel_rate_control subsystem.

Navigate to the top level of the sldemo_fuelsys model. Navigate inside the fuel_rate_control
subsystem, then navigate inside the control_logic Stateflow chart.

Start a simulation. Once the simulation starts, on the Fault Injection panel, modify the position
of one or more Slider Switch blocks to induce a failure in the system.

• Observe the changes in the Stateflow chart as the system state changes in response to one or
more failures.
• Observe the changes in fuel consumption by monitoring the panel you created from the Fuel
(g/s) area.

Tip If the simulation progresses too quickly, you can use simulation pacing to slow the progression
of simulation time relative to clock time. For more information, see Simulation Pacing Options.

32-41
32 Control Simulations with Interactive Displays

See Also
Simulation Pacing Options

Related Examples
• “Getting Started with Panels” on page 32-19
• “Create Tabbed Panels” on page 32-43
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Design Custom Buttons” on page 32-121

32-42
Create Tabbed Panels

Create Tabbed Panels


This example shows you how to create tabbed panels, how to change which tabs are attached to each
other, and how to change the order of a group of attached tabs.

You can use panels to model real dashboards, for example, the dashboard in your car. To model
displays and controls on the panel, such as gauges, lamps, knobs, buttons, and switches, you can
promote blocks to the panel from the “Dashboard” library, the “Customizable Blocks” library, and the
“Aerospace Blockset” library.

For information about how to create, populate, edit, and manage the visibility of panels, see “Getting
Started with Panels” on page 32-19.

By default, the first panel you create in a model has a single tab. To model multiple dashboards, you
can make multiple panels or add tabs to a panel.

The editing options available for a panels with a single tab are also available for panels with multiple
tabs. However, when you edit a panel with multiple tabs, the edits are only applied to the selected
tab. For example, when you enter edit mode and drag a corner of a panel, only the selected tab of
that panel is resized.

For information on how to change the name of panel tabs, see “Rename Panels” on page 32-27.

In addition to the tabs and their content, you can also customize the arrangement of panel tabs. You
can:

• Change the order of tabs in a panel.


• Detach tabs from a panel.
• Attach tabs from one panel to a different panel.
• Convert freestanding panels into tabs of another panel.

32-43
32 Control Simulations with Interactive Displays

Open Example Model


In this example, you create tabbed panels and change their arrangement. The panels you create
contain dashboard blocks for monitoring and testing a fuel control system.

Open the sldemo_fuelsys model from the “Model Fault-Tolerant Fuel Control System” example.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')

The sldemo_fuelsys model has a Dashboard subsystem that contains controls and indicators for
interactively simulating the model. Navigate inside the Dashboard subsystem.

The subsystem contains four areas: Inputs, Fault Injection, Fuel (g/s), and Air/Fuel
Ratio.

Suppose you want to use the control and display blocks in these areas to test the effect of sensor
failures on the calculated air/fuel ratio and fuel consumption of a gasoline engine. Your plan consists
of these steps:

1 Test the effect of sensor failures on the calculated air/fuel ratio.

For this task, you want a panel with two tabs:

• One tab contains the control blocks from the Fault Injection area that you can use to
activate the sensor failures during simulation.
• One tab contains the display blocks from the Air/Fuel Ratio area that you can use to
observe the effect of the failures on the air/fuel ratio.
2 Test the effect of sensor failures on the calculated fuel consumption.

For this task, you also want a panel with two tabs:

32-44
Create Tabbed Panels

• One tab contains the control blocks from the Fault Injection area.
• One tab contains the display blocks from the Fuel (g/s) area that you can use to the effect
of the failures on the fuel consumption.
3 Pass the model to a colleague who will use your findings to make design changes to the fuel
control system.

You want to hand over the model with all three panels reorganized into one panel with three tabs,
and with the tabs that contain display blocks next to each other.

This example explains the process of creating the tabbed panels in your plan.

Create Panels
Start by creating one panel that contains the blocks from the Fault Injection area and one that
contains the blocks from the Fuel (g/s) area.

If you already created a panel containing the dashboard blocks and annotations from the Fault
Injection area or the Fuel (g/s) area by working through the examples in “Getting Started with
Panels” on page 32-19 or “Use Panels to Monitor Signals and Control Parameters” on page 32-37,
skip the task for creating that panel.

To create the Fault Injection panel, promote the dashboard blocks in the Fault Injection
area to a panel:

1 Draw a selection box around the blocks. Where the selection box ends, an ellipsis appears.

2 Pause on the ellipsis.


3
In the action bar that expands, click Promote to Panel . The dashboard blocks are promoted
from the area to the panel, but the annotations are not.

32-45
32 Control Simulations with Interactive Displays

Add the annotations from the Fault Injection area to the panel:

1 Select the panel.


2 Pause on the ellipsis that appears.
3
In the action bar that expands, click Edit Panel .
4 Drag the lower left corner of the panel to the left to make room for the annotations.

5 To see the annotations in the Fault Injection area, drag the panel away from the area. To
drag the panel, click and hold down your pointer on the panel name or on any empty spot inside
the panel, then move the pointer.

32-46
Create Tabbed Panels

6 For each annotation from the Fault Injection area, double-click the panel where you want
the annotation, then type the annotation text. When you finish typing, press Enter. You can drag
the annotations to move them around the panel.
7 When you finish, click the canvas.
8 To rename the panel, in the Simulink Toolstrip, on the Panels tab, in the Edit section, click
Rename Panel. The Property Inspector appears. On the Parameters tab, in the Name text box,
type Fault Injection.

Use the same approach to create the Fuel (g/s) panel from the dashboard blocks in the Fuel
(g/s) area.

32-47
32 Control Simulations with Interactive Displays

Add Empty Tab to Panel


To create the tabbed panel for the first step in your plan, add an empty tab to the Fault Injection
panel. Then, populate the tab with the blocks from the Air/Fuel Ratio area.

To add an empty tab to a panel, select the panel. Then, in the Simulink Toolstrip, on the Panels tab,
in the Edit section, click Add Tab.

To populate the new tab using the dashboard blocks from the Air/Fuel Ratio area:

1 Select the new tab.


2 Pause on the ellipsis (…) that appears.
3
In the action bar that expands, click Edit Panel .
4 Drag the lower left corner of the panel to the left to make room for the blocks.
5 Drag the blocks from the Air/Fuel Ratio area into the new tab.
6 When you finish, click the canvas.

32-48
Create Tabbed Panels

Detach Tab from Panel


To create the tabbed panel for the second step in your plan, move the Fault Injection tab to the
Fuel (g/s) panel. Start by detaching the Fault Injection tab from the Air/Fuel Ratio tab.

To detach the tab, drag the tab name away from the panel.

32-49
32 Control Simulations with Interactive Displays

Attach Tab or Freestanding Panel to Another Panel


To attach the Fault Injection tab to the Fuel (g/s) panel, dragging the Fault Injection tab
by its name, move your pointer over the Fuel (g/s) panel name. When a plus symbol appears over
the Fuel (g/s) panel name, release your pointer.

32-50
Create Tabbed Panels

To create the tabbed panel for the third step of your plan, attach the Air/Fuel Ratio tab to the
panel with the Fault Injection tab and the Fuel (g/s) tab.

32-51
32 Control Simulations with Interactive Displays

Reorder Panel Tabs


To change the position of a tab, drag the name of the tab to a new position.

When you add a tab to a panel, the tab is always added to the right end of the tabs on that panel.

To finish the tabbed panel for the third step of your plan, reorder the panels to put the two tabs with
display blocks next to each other. The tabs with display blocks are the Air/Fuel Ratio tab and the
Fuel (g/s) tab.

32-52
Create Tabbed Panels

See Also

Related Examples
• “Getting Started with Panels” on page 32-19
• “Use Panels to Monitor Signals and Control Parameters” on page 32-37
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Design Custom Buttons” on page 32-121

32-53
32 Control Simulations with Interactive Displays

Deploy Dashboard Panel as App


With the Simulink Compiler and “MATLAB Runtime” (MATLAB Compiler), you can deploy a
dashboard panel, packaged with the model to which the panel connects, as a standalone desktop app
or a web app that runs with the MATLAB Web App Server™. You can use the app to operate the
controls and monitor the displays on the panel independent of Simulink.

The panel is visible in the app, and you can interact with the panel. From the app, you can start,
pause, and stop the simulation. The model to which the panel connects is not visible. You can only
interact with the model through the panel.

Check Deployment Limitations


These actions are not supported:

• Deployment from MATLAB Online


• Deployment from a library model
• Deployment of a panel that contains any of these blocks:

• Dashboard Scope blocks


• Callback Button blocks
• Display blocks connected to a signal that is multidimensional
• Deployment of a panel in a model that does not run in rapid accelerator mode.

To check whether the model runs in rapid accelerator mode, in the Simulink Toolstrip, on the
Simulation tab, in the Simulate section, from the drop-down list, select Rapid Accelerator.
Then, click Run. To make the panel deployable, resolve any errors the simulation throws.

Note Blocks from the Dashboard and Customizable Blocks libraries do not support streaming in
rapid accelerator mode. The blocks being marked as unsupported during this process is not an
error you need to resolve in order to make the panel deployable.

Plan Ahead to Avoid Simulation Errors


Deploying a panel creates a copy of the model that contains the panel, loads the copy, and then closes
the copy. As a result, during deployment, the copy runs any callback functions that would run if you
were to load and then close the original model. The copy running the callbacks while the original
model is open can cause the original model to throw errors when you try to simulate the model after
you deploy the panel.

For example, if the model contains a callback that clears variables from the MATLAB workspace when
the model closes, then during the deployment, when the copy of the model closes, the callback runs
and clears the variables. Since the variables are the same for both the original model and the copy, if
you then try to simulate the original model, it might throw an error because the callback cleared the
variables that the model needs to run.

If you plan to simulate the model (the model you started with, not the app) after you deploy, then
adjust the callbacks, the model, or your workflow after deployment to avoid errors during simulation.
For example, depending on the model and the callbacks, you may be able to avoid simulation errors
by closing and reopening the model after you deploy.

32-54
Deploy Dashboard Panel as App

Deploy Panel as Standalone App


If you have the Simulink Compiler and MATLAB Runtime, you can deploy a panel as a standalone app
that you run from an executable.

Deploy Panel

1 If the model that contains the panel is not open, open the model.
2 If the model is already open and has unsaved changes, save the model.
3 By default, the app deploys to the current folder. Deploying to the current folder means that the
software saves all files output during simulation to the current folder. Specifically, in the current
folder, the software creates a subfolder named after the app. The software saves all temporary
files output during deployment in the current folder, and all non-temporary files in the subfolder.
If you plan to deploy to the current folder, check that the current folder has write permissions. If
the folder does not have write permissions, navigate to a folder that has write permissions.

To change the deployment folder, in the model, select the panel. In the Property Inspector, on the
Parameters tab, expand the Deployment Settings section. In the Output Folder text box,
enter a new file location. Alternatively, click Browse and select a new file location.
4 By default, the app title is the name of the panel you deploy. To change the app title, enter a new
title in the Title text box.
5 To start the deployment, in the Simulink Toolstrip, on the Panels tab, in the Deploy section,
expand Deploy Panel and select Standalone Desktop App.
6 If the person who will run the app has internet access, then in the toolstrip of the Application
Compiler window, in the Packaging Options section, select Runtime downloaded from web
app. If not, then select Runtime included in package.
7 In the toolstrip of the Application Compiler window, click Package.
8 In the Package window that appears, select Open output folder when process completes. If
the output folder does not open automatically when the packaging process completes, click the
link to open the output folder.

Run App

Running the deployed app requires MATLAB Runtime. To install MATLAB Runtime, run the
executable located in the folder to which you deployed, in the for_redistribution folder.

32-55
32 Control Simulations with Interactive Displays

To run the app, run the executable in the for_redistribution_files_only folder (on Linux, run
the shell script, and on macOS, run the application).

Deploy Panel as Web App


If you have the Simulink Compiler and the MATLAB Web App Server, you can deploy the panel as a
web app that you run in a Chrome® browser.

Deploy App

1 If the model that contains the panel is not open, open the model.

To deploy a panel as a web app, you must deploy on the operating system that supports the
server you want to deploy to. For example, if you want to deploy to a Linux Web App server, you
must deploy on Linux.
2 If the model is already open and has unsaved changes, save the model.
3 By default, the app deploys to the current folder. Deploying to the current folder means that the
software saves all files output during simulation to the current folder. Specifically, in the current
folder, the software creates a subfolder named after the app. The software saves all temporary
files output during deployment in the current folder, and all non-temporary files in the subfolder.
If you plan to deploy to the current folder, check that the current folder has write permissions. If
the folder does not have write permissions, navigate to a folder that has write permissions.

To change the deployment folder, in the model, select the panel. In the Property Inspector, on the
Parameters tab, expand the Deployment Settings section. In the Output Folder text box,
enter a new file location. Alternatively, click Browse and select a new file location.

32-56
Deploy Dashboard Panel as App

4 By default, the app title is the name of the panel you deploy. To change the app title, enter a new
title in the Title text box.
5 To start the deployment, in the Simulink Toolstrip, on the Panels tab, in the Deploy section,
expand Deploy Panel and select Web App.
6 In the Packaging Progress window, select Open output folder upon completion.

Run App

Running the web app requires the MATLAB Web App Server. Install and start the web app server. For
information about how to complete these actions, see “Install or Uninstall MATLAB Web App Server
Product” (MATLAB Web App Server).

For information about how to run the web app, see “Run Web App” (MATLAB Web App Server). Run
the web app in a Chrome browser.

Run Simulation from Panel


You can take these actions using the toolbar in the app.

Action Toolstrip Button


Run simulation.

Pause simulation.

Stop simulation.

Set simulation pacing. For more information about simulation pacing, see
Simulation Pacing Options. Setting simulation pacing is not supported
during simulation.

See Also

Related Examples
• “Getting Started with Panels” on page 32-19
• “Use Panels to Monitor Signals and Control Parameters” on page 32-37
• “Create Tabbed Panels” on page 32-43

32-57
32 Control Simulations with Interactive Displays

Create Dashboard Panel for Climate Control System

This example shows how to create a climate control screen for an automotive infotainment system,
modeled as a dashboard panel. You can use panels to model and test the user interface of a real
system. To model displays and controls on the panel, such as gauges, lamps, knobs, buttons, and
switches, you can promote dashboard blocks to the panel. Dashboard blocks are blocks from the
Dashboard library, the Customizable Blocks library, and the Aerospace Blockset™ Flight Instruments
library.

In this example, you promote a set of blocks to a panel. You add a tab to the panel and populate the
tab. Then, you use the panel to monitor and control values in the climate control system during
simulation. Note that the climate control system model uses highly simplified heat transfer models
and serves here only to demonstrate a type of potential use case for panels. For information about the
assumptions in the model, see “Simulating Automatic Climate Control Systems”.

The climate control screen you create has these controls:

• A dial for fan speed, modeled using a Slider Switch block


• A button to turn air recirculation in the cabin on and off, modeled using a Push Button block
• Two buttons for increasing or decreasing desired cabin temperature, modeled using Callback
Button blocks
• A button for switching temperature units between Celsius and Fahrenheit, modeled using a
Callback Button block

The climate control screen has these displays:

• Cabin temperature, modeled using a Display block


• Outside temperature, modeled using a Display block
• Current date and time, modeled using a Display block
• A picture of the sun or moon to indicate time of day, modeled using a Lamp block

32-58
Create Dashboard Panel for Climate Control System

For examples on how to customize blocks from the Customizable Blocks library to look like controls
and displays in real systems, see “Control Simulations with Interactive Displays”.

To try out the finished panel without working through this example, open the
sldemo_climate_control_panel.slx model by entering this command in the MATLAB®
Command Window:

open_system('sldemo_climate_control_panel.slx')

32-59
32 Control Simulations with Interactive Displays

Promote Blocks to Panel

When you open this example, the sldemo_climate_control_dashboard_blocks.slx model


opens and shows the Dashboard Blocks subsystem. The subsystem contains a set of blocks from
the Dashboard and Customizable Blocks libraries.

The blocks are on top of an image annotation. The image annotation is the same image as the
background image for the panel.

Unlike the blocks, you cannot promote the image to a panel. Promote the blocks to a panel, then add
the background image to the panel. To promote the blocks to a panel, marquee select all the blocks
on top of the image. Where you release your cursor, an ellipsis (...) appears.

Pause on the ellipsis. In the action menu that expands, click Promote to Panel.

A message appears in the Simulink Editor to remind you that only dashboard blocks can be promoted
to a panel. The message appears because the image annotation is not promoted to the panel.

Add Panel Background Image

When you add a background image to a panel, the image resizes to fit the panel. If the panel has a
different aspect ratio than the image, the image is distorted.

32-60
Create Dashboard Panel for Climate Control System

Before you add the background image to the panel, resize the panel to be the same size as the
background image. To resize the panel:

1 Select the panel.


2 To enter panel edit mode, in the Simulink® Toolstrip, on the Panels tab, in the Edit section, click
Edit Panels.
3 Drag the edges of the panel until they align with the borders of the image annotation in the
canvas.

The last step shows how you can use image annotations to guide the process of resizing the panel.
For information about how to add image annotations to the canvas, see “Create Image Annotations”
on page 1-80.

Now, add the background image. In the toolstrip, on the Panels tab, in the Edit section, click Add
Background. In the CabinClimateControlPanel folder, select the climate-control-panel-
background.png file.

32-61
32 Control Simulations with Interactive Displays

Remove the image annotation in the canvas:

1 To exit panel edit mode, click anywhere in the canvas.


2 To access the image annotation, grab the panel name or any part of the panel where there are no
blocks and drag the panel aside so that you can see the image annotation.
3 Select the image annotation in the canvas.
4 Press Delete.

Add Tabs to Panel

Suppose that while testing the climate control screen, you want to pull up a plot of the cabin
temperature without opening extra windows or adding more blocks to the climate control screen. You
can do so by adding a tab to the panel and populating the tab with a Dashboard Scope block. Then,
you can switch between the climate control screen and the plot by clicking the corresponding panel
tabs.

To add a tab to the panel, in the toolstrip, on the Panels tab, in the Edit section, click Add Tab.

If you accidentally create too many tabs, you can delete the extra tabs. Click the tab you want to
remove and press Delete.

32-62
Create Dashboard Panel for Climate Control System

Rename Tabs

The panel now has two tabs. Give the tabs names that reflect their contents:

1 Click the left tab.


2 In the toolstrip, on the Panels tab, in the Edit section, click Rename Panel.
3 In the Property Inspector Name text box, enter Climate Control Screen.
4 Click the right tab.
5 In the Property Inspector Name text box, enter Cabin Temp.

Populate Tabs

To create the plot, exit panel edit mode by clicking anywhere on the canvas.

To add a Dashboard Scope block to the model, double-click the canvas. In the Quick Insert menu, type
dashboard scope. If needed, use your arrow keys to select the entry for the Dashboard Scope
block, then press Enter.

To promote the Dashboard Scope block to the panel tab named Cabin Temp, enter panel edit mode.
To enter panel edit mode, select the panel. Then, in the toolstrip, on the Panels tab, in the Edit
section, click Edit Panel.

Drag the Dashboard Scope block onto the panel tab named Cabin Temp.

32-63
32 Control Simulations with Interactive Displays

Increase the size of the block until it fills the panel by dragging the corners outwards.

32-64
Create Dashboard Panel for Climate Control System

Exit panel edit mode by clicking anywhere in the canvas.

Connect the Dashboard Scope block on the Cabin Temp tab to the signal the block should display
during simulation.

1 Select the Dashboard Scope block.


2 In the Simulink Toolstrip, on the Scope tab, in the Connect section, click Connect.
3 Navigate to the top level of the model.
4 Drag the panel to one side of the model window so you can see the right half of the model
diagram.
5 Click the signal line that connects to the Scope block named Thermometer Display. The signal
is in the lower right of the model diagram.
6 In the menu that appears, select the check box for the signal named Subsystem:1.
7 Click the Dashboard Scope block.
8 In the Simulink Toolstrip, on the Scope tab, in the Connect section, click Done Connecting.

The panel is complete.

32-65
32 Control Simulations with Interactive Displays

Monitor and Display Values During Simulation Using Panel

To run the simulation, in the Simulink toolstrip, on the Simulation tab, in the Simulate section, click
Run.

While the simulation is running, try using the controls on the climate control screen.
1 To set the fan speed to the second-to-highest setting, on the fan speed dial, click the second
largest circle.
2 To change the desired cabin temperature to 20 degrees Celsius, click the plus button in the
upper right corner of the panel five times.
3 To activate air recirculation in the cabin, click the cabin air recirculation button on the car
windscreen in the panel.
4 To see all the temperatures on the climate control screen in degrees Fahrenheit, click the
temperature units button in the lower left corner of the panel.

To see the effect of the controls on the cabin air temperature, after changing a control setting, click
the Cabin Temp tab.

Manage Panel Visibility

Suppose you want to take a closer look at the model in the canvas. To minimize the panel, double-
click the panel. To restore the panel, double-click the panel.

32-66
Create Dashboard Panel for Climate Control System

Suppose you want to view only the panel. You can open the panel in a new window, then minimize the
model window. You can run and stop the simulation from the panel window, and you can operate the
controls in the panel.

1 Select the panel.


2 In the toolstrip, in the Panels tab, in the Manage section, click Pop Out Panel.
3 Minimize the model window.
4 To run the simulation, click the Run button at the top of the panel window.
5 On the Climate Control Screen tab, change the setting of one of the controls. For example,
click the minus button in the upper right to decrease the desired cabin temperature.
6 To stop the simulation, click the Stop button at the top of the panel window.

Learn More About Panels

For more information about creating panels, editing panels, and managing panel visibility, see
“Getting Started with Panels” on page 32-19.

See Also

Related Examples
• “Getting Started with Panels” on page 32-19
• “Use Panels to Monitor Signals and Control Parameters” on page 32-37
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2

32-67
32 Control Simulations with Interactive Displays

Design Custom Gauges

You can design custom gauges that look like displays in a real system or animate a signal using the
Circular Gauge, Horizontal Gauge, and Vertical Gauge blocks. This example gives step-by-step
guidance to design a thermometer using the Vertical Gauge block and an ammeter using the Circular
Gauge block.

The model for this example includes several customized gauges connected to the output of a Sine
Wave block. The example gives step-by-step instructions to design the gauge blocks in the canvas of
the model. The model includes a panel that contains additional customized gauges you can explore on
your own. The example directory includes a folder with all the SVG images used to create the gauges.

Design a Thermometer Using the Vertical Gauge Block

The thermometer designed using the Vertical Gauge block uses a background image to define the
shape of the thermometer and the value bar of the Vertical Gauge block to indicate the value of the
connected signal during simulation. The Battery Level block in the panel uses a similar design
strategy.

To design a thermometer, add a Vertical Gauge block to the model using the quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Vertical Gauge block, type Vertical Gauge.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Vertical Gauge block, enter design mode:

1 In the model canvas, select the Vertical Gauge block.


2 In the Simulink® Toolstrip, click the Gauge tab.

32-68
Design Custom Gauges

3 On the Gauge tab, click Edit. A toolbar appears above the Vertical Gauge block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

Add the thermometer background image:

1 Select the Background Image component in the Design tab.


2 In the Select Image section, click the plus button.
3 Navigate inside the CustomGaugeImages folder and select the Thermometer.svg file.

32-69
32 Control Simulations with Interactive Displays

The thermometer design uses the value bar, not the needle, to indicate the value of the connected
signal. To remove the needle image, in the Design tab, select the Needle component. Then, in the
Select Image section, click the X button.

Next, adjust the scale range, color, position, and size:

1 In the Design tab, select the Scale component.


2 In the Range section, change the Maximum to 50.
3 In the Ticks section and the Labels section, change Color to black so the tick marks are more
visible on the white background.
4 Resize the scale so it fits inside the white column of the thermometer background image. You can
adjust the width and height of the scale interactively on the block or by using the Design tab.
When resizing interactively, you can maintain the aspect ratio of the scale by pressing Shift as
you drag the corners of the block. To use the Design tab, in the Size and Position section,
adjust the Width and Height.
5 Align the zero point on the scale with the top of the red area of the background image.

Finally, change the value bar width and color:

32-70
Design Custom Gauges

1 In the Design tab, select the Value Bar component.


2 In the Value Preview section, adjust the slider to preview what the value bar shows when the
input value is greater than the minimum scale value.
3 In the Value Bar section, change Color to red.
4 Widen the value bar so it fills the majority of the thermometer. You can use interactive controls
on the block or use the Design tab. In the Design tab, under Value Bar, adjust Size.
5 Decrease the value bar opacity so the labels are easier to read.

When you finish adjusting the design for the thermometer, to exit design mode, in the Property
Inspector, on the Design tab, click Edit.

You can use the finished thermometer to display a signal value. In the model, a Sine Wave block
represents the temperature.

Connect the Vertical Gauge block to the Sine Wave with Offset signal:

1 Select the Vertical Gauge block.


2 Click the Connect button that appears above the block.
3 Select the Sine Wave with Offset signal.
4 Select the Sine Wave with Offset option in the table that appears below the selected signal.
5 Click the X in the upper right corner of the Simulink window.

To see the thermometer in action, simulate the model. This model uses simulation pacing to slow
model execution so you can see the fluid move in the thermometer. For more information about
simulation pacing, see Simulation Pacing Options.

Design an Ammeter Using the Circular Gauge Block

The ammeter designed using the Circular Gauge block uses a background image to define the
appearance of the ammeter, and uses a needle image and a value bar to indicate the value of the
connected signal during simulation. The Pressure Gauge block in the panel uses a similar design
strategy.

To design an ammeter, add a Circular Gauge block to the model.

32-71
32 Control Simulations with Interactive Displays

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Circular Gauge block.


2 In the Simulink Toolstrip, click the Gauge tab.
3 On the Gauge tab, click Edit. A toolbar appears above the Circular Gauge block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the ammeter background image:

1 Select the Background Image component in the Design tab.


2 In the Select Image section, click the plus button.
3 Select the Ammeter.svg file.

Change the scale limits and color:

32-72
Design Custom Gauges

1 In the Design tab, select the Scale component.


2 In the Range section, change the Minimum to -50 and the Maximum to 50.
3 In the Ticks section and the Labels section, change the Color to black so the tick marks are
more visible on the white background.

The ammeter scale starts and ends on the horizontal crosshairs. The scale Start Angle specifies the
position for the scale minimum, and the scale Arc specifies the extent of the scale arc, both in
degrees. In the Design tab, under Range, change the Start Angle and the Arc to 180.

Adjust the scale position so the entire scale fits within the display area of the ammeter background
image, with the center of the needle positioned approximately at the center of the semicircle.

Replace the needle image:


1 In the Design tab, select the Needle component.
2 In the Select Image section, click the plus button.
3 Select the Needle.svg file.

The needle image is a straight black line. The saved image is too large for the size of the block and
oriented so that the needle does not point to the zero point on the scale. To rotate the needle image,
click the needle rotation button in the block. Then, use the needle grab handles in the block to resize
and reposition the needle so it starts at the center of the semicircle in the background image and
ends before the label for the scale minimum.

32-73
32 Control Simulations with Interactive Displays

Preview the value bar:

1 Open the Value Bar component.


2 To see how the value bar grows as the needle moves, move the slider in the Value Preview
section.

The value bar grows from the origin. By default, the origin is the minimum of the scale.

Change the origin to zero:

1 Open the Scale component.


2 In the Range section, set Origin to 0.

To see the change, open the Value Bar component, and move the slider in the Value Preview
section. The value bar grows from zero, the new origin.

32-74
Design Custom Gauges

When you finish adjusting the design for the ammeter, to exit design mode, in the Property Inspector,
on the Design tab, click Edit.

You can use the finished ammeter to display a signal value. In the model, a Sine Wave block
represents the input to the ammeter.

Connect the Circular Gauge block to the Sine Wave signal:

1 Select the Circular Gauge block.


2 Click the Connect button that appears above the block.
3 Select the Sine Wave block output signal.
4 Select the Sine Wave option in the table that appears below the selected signal.
5 Click the X in the upper right corner of the Simulink window.

To see the ammeter in action, simulate the model. This model uses simulation pacing to slow model
execution so you can see the needle move on the ammeter. For more information about simulation
pacing, see Simulation Pacing Options.

Explore More Customized Gauges

The panel in the model contains more examples of customized gauges built using the Circular Gauge,
Horizontal Gauge, and Vertical Gauge blocks. For more information on panels, see “Getting Started
with Panels” on page 32-19. To view the panel, double-click the panel icon in the model. You can drag
the panel into the canvas or resize the window to view the panel. To see how the gauges respond to
changing input values, simulate the model. The CustomGaugeImages folder includes the SVG
images used to create each gauge so you can try replicating the designs on your own.

32-75
32 Control Simulations with Interactive Displays

See Also
Blocks
Circular Gauge | Horizontal Gauge | Horizontal Slider | Knob | Vertical Gauge | Vertical Slider

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-76
Design Custom Knobs

Design Custom Knobs

This example shows how to use the customizable Knob block to design three knobs that look like
controls in real systems:

• The cabin temperature knob of a passenger car


• The volume knob of a radio
• A stove knob

Each knob consists of a stationary component, the mounting, and a movable component, which is the
handle that you turn to set the value.

The blocks in the model use PNG images to define the shapes of these components. You can find all
images used to create the knobs in the example directory.

Design Cabin Temperature Knob of Passenger Car

To design the cabin temperature knob, add a customizable Knob block to the model using the
Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Knob block, type Knob.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Knob block, enter design mode:

1 In the model canvas, select the Knob block.


2 In the Simulink Toolstrip, click the Knob tab.
3 On the Knob tab, click Edit. A toolbar appears above the Knob block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

You can design a customizable knob using the toolbar or using the Design tab of the Property
Inspector. This example uses both.

32-77
32 Control Simulations with Interactive Displays

Add the background image for the cabin temperature knob:

1 In the toolbar, click the Replace Background Image button.


2 In the CustomKnobImages folder, select the cabin-temp-knob-background.png file.

Add the handle image for the cabin temperature knob:

1 In the toolbar, click the Replace Needle Image button.


2 In the CustomKnobImages folder, select the cabin-temp-knob-handle.png file.

32-78
Design Custom Knobs

Adjust the endpoints of the scale:

1 Adjust the start offset angle. On the tick mark that constitutes the left end of the scale, click and
drag the blue marker so that the tick mark aligns with the blue end of the color bar on the
background image. By default, the blue markers snap to angles located at 15 degree intervals. To
avoid snapping to these angles, press Shift while dragging the marker.
2 Adjust the scale angle. On the tick mark that constitutes the right end of the scale, click and drag
the blue marker so that the tick mark lines up with the red end of the color bar on the
background image.

For the next two steps, return to the Property Inspector. To open the Design Tab of the Property
Inspector, click Open Design Tab in the toolbar.

Hide the scale:

1 On the Design tab, select the Scale component.


2 In the Ticks section, clear Show Ticks.
3 In the Ticks section, clear Show Span Line.

32-79
32 Control Simulations with Interactive Displays

4 In the Labels section, clear Show Labels.

The customizable Knob block has a value bar: a circular arc whose length serves as a visual
representation of the value to which the knob is set. To see the value bar:

1 On the Design tab, select the Value Bar component.


2 In Value Preview, move the Value slider and see how the value bar changes as the handle of the
knob moves.

The cabin temperature knob does not use the value bar. To hide the value bar, in the toolbar, move the
Set Opacity slider to zero.

32-80
Design Custom Knobs

When you finish adjusting the design for the cabin temperature knob, to exit design mode, on the
Design tab of the Property Inspector, click Edit.

You can use the finished cabin temperature knob to control a parameter. In the model, a Constant
block represents the cabin temperature of a passenger car, and the cabin temperature knob controls
the value of the constant.

Connect the Knob block to the Value parameter of the Constant block:
1 Select the Knob block.
2 Click the Connect button that appears above the block.
3 Select the Constant block named Const1.
4 Select the Const1:Value option in the table that appears below the selected signal.
5 Click the X in the upper right corner of the Simulink window.

To use the cabin temperature knob:


1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Knob block handle to change its value during simulation.
3 See the effect on the cabin temperature in the Dashboard Scope block.

Design Volume Knob of Radio

To design the radio volume knob, add a customizable Knob block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:
1 In the model canvas, select the Knob block.
2 In the Simulink Toolstrip, click the Knob tab.
3 On the Knob tab, click Edit. A toolbar appears above the Knob block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

32-81
32 Control Simulations with Interactive Displays

Add the background image for the volume knob:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomKnobImages folder, select the radio-knob-background.png file.

Add the handle image for the volume knob:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomKnobImages folder, select the radio-knob-handle.png file.

Change the color of the value bar:

1 On the Design tab, select the Value Bar component.


2 In the Value Preview section, move the Value slider to preview the value bar.
3 In the Value Bar section, set the Color to turquoise.

The inner and outer radius of the value bar are the same as the inner and outer radius of the tick
marks on the knob scale. Change the inner and outer radius of the value bar such that the bar covers
the dark gray swoosh on the background image:

1 On the Design tab, select the Scale component.


2 In the Range section, adjust the Inner Radius slider to make the inner radius of the value bar
smaller than that of the gray swoosh. The example uses an Inner Radius value of 0.55.
3 In the Range section, adjust the Outer Radius slider to make the outer radius of the value bar
larger than that of the gray swoosh. The example uses an Outer Radius value of 0.78.

32-82
Design Custom Knobs

The scale is hard to read because the light yellow color of the tick marks and labels blends into the
white background, and because the labels are half on and half off of the knob background. To make
the scale readable so that you can adjust the arc length of the scale, set the color of the scale to
black:

1 In the Ticks section, set the Color to black.


2 In the Labels section, set the Color to black.

In the Labels section, adjust the Label Radius slider to move the scale labels outside of the outer
radius of the knob. The example uses a Label Radius value of 0.92.

Adjust the arc length of the scale:

1 In the Range section, set the Start Angle to 270 degrees to place the start point of the scale on
the positive vertical axis. The angle is measured clockwise from the horizontal axis that bisects
the right half of the knob.
2 In the Range section, set Arc to 90 degrees to place the end point of the scale one quarter of a
full knob revolution from the start point.

32-83
32 Control Simulations with Interactive Displays

Hide the scale:

1 In the Ticks section, clear Show Ticks.


2 In the Ticks section, clear Show Span Line.
3 In the Labels section, clear Show Labels.

Add the foreground image for the volume knob:

1 On the Design tab, select the Foreground Image component.


2 In the Select Image section, click the plus button.
3 In the CustomKnobImages folder, select the radio-knob-foreground.png file.

When you finish adjusting the design for the volume knob, to exit design mode, on the Design tab,
click Edit.

You can use the finished volume knob to control a parameter. In the model, a Sine Wave block
represents a radio signal, and the volume knob controls the amplitude of the sine wave.

Connect the Knob block to the Amplitude parameter of the Sine Wave block:

1 Select the Knob block.


2 Click the Connect button that appears above the block.
3 Select the Sine Wave block.
4 Select the Sine Wave:Amplitude option in the table that appears below the selected signal.
5 Click the X in the upper right corner of the Simulink window.

To use the volume knob:

32-84
Design Custom Knobs

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Knob block handle to change its value during simulation.
3 See the effect on the radio signal in the Dashboard Scope block.

Design a Stove Knob

To design the stove knob, add a customizable Knob block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Knob block.


2 In the Simulink Toolstrip, click the Knob tab.
3 On the Knob tab, click Edit. A toolbar appears above the Knob block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the stove knob:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomKnobImages folder, select the stove-knob-background.png file.

Add the handle image for the stove knob:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomKnobImages folder, select the stove-knob-handle.png file.

32-85
32 Control Simulations with Interactive Displays

To edit the scale, make it readable by changing its color:

1 On the Design tab, select the Scale component.


2 In the Ticks section, set the Color to black.
3 In the Labels section, set the Color to black.

The range of the stove knob scale labels spans from 0 to 10. The minimum of the range is the default
value of the Knob block. In the Range section, set the Maximum to 10.

The arc length of the stove knob scale is the default value, 270 degrees. The start angle of the scale is
315 degrees, measured clockwise from the horizontal axis that bisects the right half of the knob. In
the Range section, set the Start Angle to 315.

Adjust the span line, tick marks, and labels of the scale so that they fit on the knob:

1 In the Range section, adjust the radius of the span line of the scale by moving the Outer Radius
slider. Bring the span line close to the outer radius of the knob handle. The example uses an
Outer Radius value of 0.55.
2 In the Range section, adjust the width of the tick marks of the scale by moving the Inner
Radius slider. To keep the span line at the inner radius of the scale, set an Inner Radius value
larger than that of the Outer Radius. Set the Inner Radius value such that the tick marks take
up about a third of the radial distance between the outer radius of the knob handle, and the outer
radius of the knob. The example uses an Inner Radius value of 0.63.
3 In the toolstrip, on the Format tab, under Font and Paragraph, set the font size of the labels to
10.
4 On the Design tab, select the Scale component again.
5 In the Labels section, adjust the Label Radius slider to move the scale labels such that they are
between the outer radius of the tick marks and the outer radius of the knob. The example uses a
Label Radius value of 0.7.

32-86
Design Custom Knobs

Hide the value bar:

1 On the Design tab, select the Value Bar component.


2 In the Value Bar section, set the Opacity to zero.

When you finish adjusting the design for the stove knob, to exit design mode, on the Design tab, click
Edit.

You can use the finished stove knob to control a parameter. In the model, a Constant block represents
the heat setting of a stove, and the stove knob controls the value of the constant. The product of the
heat setting and a gain represent the resulting stove temperature.

Connect the Knob block to the Value parameter of the Constant block:

1 Select the Knob block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const2.
4 Select the Const2:Value option in the table that appears below the selected signal.
5 Click the X in the upper right corner of the Simulink window.

To use the stove knob:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Knob block handle to change its value during simulation.
3 See the effect on the stove temperature in the Dashboard Scope block.

See Also
Blocks
Knob

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-87
32 Control Simulations with Interactive Displays

Design Custom Lamps

This example shows how to use the customizable Lamp block to design four lamps that look like
displays in real systems:

• A dashboard light in a passenger car


• Elevator floor indicator lights
• Two pedestrian crossing lights

Each lamp has multiple states. Each state corresponds to a value or a range of values that you
specify. The lamp enters a given state when the value of the signal to which the Lamp block connects
matches the specified value or falls within the specified range.

In each state, the lamp displays a combination of a shape layer and an icon layer. You can specify the
appearance of a state by specifying the appearance of the layers for that state.

A Lamp block can also have a background image, a foreground image, or both. These do not change
as the lamp switches states.

The blocks in the model use PNG images to define the shapes of these components. You can find all
images used to create the lamps in the example directory.

Design Dashboard Light in Passenger Car

To design the dashboard light in a passenger car, add a customizable Lamp block to the model using
the quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Rocker Switch block, type Lamp.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Lamp block, enter design mode:

1 In the model canvas, select the Lamp block.


2 In the Simulink® Toolstrip, click the Lamp tab.

32-88
Design Custom Lamps

3 On the Lamp tab, click Edit. A toolbar appears above the Lamp block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

You can design a custom lamp using the toolbar or using the Design tab of the Property Inspector.
This example uses both.

Change the background color to gray:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Background Color section, turn on Use Background Color.
3 Change the Color to gray.

Delete the foreground image:

1 On the Design tab, select the Foreground Image component.


2 In the Select Image section, click the X button.

The Lamp block for the dashboard light has three states:

32-89
32 Control Simulations with Interactive Displays

• It is in the first state when the percent fuel left in the tank is between 0 and 30.
• It is in the second state when the percent fuel left in the tank is between 30 and 100.
• It is in the default state when the block does not receive a parameter value that activates any
other of the specified states.

When the Lamp block is in the default state, the fuel icon on the car
dashboard is not lit.

Configure the appearance of the lamp for the default state:

1 On the Design tab, select the States component.


2 In the Icon section, open the drop-down menu and select Automotive.
3 Select the fuel icon.
4 In the toolbar, click the color wheel and set the color to black.

The toolbar color wheel sets the color of the shape layer of the lamp. Since the default Style setting
in the Shape and Icon Combination section is Intersect, the lamp shows only the area of the
shape layer that overlaps with the area of the icon layer. In this case, the shape layer is the circle that
is selected in the Shape section, and the icon layer is the fuel symbol that is selected in the Icon
section. Since the overlapping area is the shape of the fuel symbol, the toolbar color wheel changes
the color of that symbol.

By default, states are activated by a single parameter value. However, the fuel symbol on the
dashboard is lit when the percent fuel left is in a certain range, not when the percent fuel left is equal
to a certain value. If you enable Specify State Values as Ranges, you can specify a range of values
to activate each state.

Specify the range of parameter values that activate the second state:

1 In the Select State section, open the drop-down menu and select 1 (State 2). The number in
this drop-down menu option is the parameter value that activates the state specified in
parentheses.
2 Turn on the Specify State Values as Ranges option. Observe that the drop-down menu option
has changed from 1 (State 2) to 1 to 1 (State 2). The numbers indicate the range of
values that activate the state.
3 In the Value and Color section, enter 100 as the Maximum value of the range.
4 In the Value and Color section, enter 30 as the Minimum value of the range.

32-90
Design Custom Lamps

In the second state, the percent of fuel left in the tank is 30 to 100. The fuel icon on the car
dashboard is not lit.

Configure the appearance of the lamp for the second state:

In the toolbar, click the color wheel and set the color for the icon layer to black.

Specify the range of parameter values that activate the first state:

1 On the Design tab of the Property Inspector, select the States component.
2 In the Select State section, open the drop-down menu and select 0 to 0 (State 1).
3 In the Value and Color section, enter 30 as the Maximum value of the range.

In the first state, the percent of fuel left in the tank is 0 to 30. The fuel icon on the car dashboard is
lit.

Configure the appearance of the lamp for the first state:

In the toolbar, click the color wheel and set the color for the icon layer to yellow.

When you finish adjusting the design for the dashboard light, to exit design mode, on the Design tab,
click Edit.

You can use the finished dashboard light to display a signal value. In the model, a Ramp block
represents the percentage of fuel left in the tank of a car. The Ramp block has a slope of -10 and an
initial output of 100.

32-91
32 Control Simulations with Interactive Displays

Connect the Lamp block to the % Fuel in Tank signal:

1 Select the Lamp block.


2 Click the Connect button that appears above the block.
3 Select the signal line with the label % Fuel in Tank.
4 Select the % Fuel in Tank option in the table that appears below the selected signal line.
5 Click the X in the upper right corner of the Simulink window.

To use the dashboard light, simulate the model. This model uses simulation pacing to slow model
execution so that you can clearly see the Lamp block respond to the value of the parameter that it
connects to. For more information about simulation pacing, see Simulation Pacing Options.

Design Elevator Floor Indicator Lights

To design a simple set of elevator floor indicator lights, add a customizable Lamp block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Lamp block.


2 In the Simulink Toolstrip, click the Lamp tab.
3 On the Lamp tab, click Edit. A toolbar appears above the Lamp block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the floor indicator lights:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomLampImages folder, select the floor-indicator-background.png file.

Exit design mode by clicking Edit on the Design tab.

Resize the block in the canvas by dragging one of its corners outwards until the numbers on the
background image are large enough to read.

To continue modifying the design of the Lamp block, enter design mode. In the Property Inspector, on
the Design tab, click Edit.

32-92
Design Custom Lamps

Add the foreground image for the floor indicator lights:

1 On the Design tab, select the Foreground Image component.


2 In the Select Image section, click the plus button.
3 In the CustomLampImages folder, select the floor-indicator-foreground.png file.

Hide the foreground image so that it is not in the way when you configure the lamp appearance for
each state. On the Design tab, click the eye icon of the Foreground Image component. The eye icon
now has a slash through it, indicating that the foreground image is hidden.

Using the eye icon only hides the corresponding block component while you are in design mode. If
you exit design mode, the component will become visible again.

The Lamp block for the floor indicator lights has five states:

• It is in the first state when the elevator is on the ground floor, which corresponds to a parameter
value of 0.
• It is in the second state when the elevator is on the first floor, which corresponds to a parameter
value of 1.
• It is in the third state when the elevator is on the second floor, which corresponds to a parameter
value of 2.
• It is in the fourth state when the elevator is on the third floor, which corresponds to a parameter
value of 3.
• It is in the default state when the block does not receive a parameter value that activates any
other of the specified states.

All states of the floor indicator lights have the same setting in the Shape and Icon Combination
and Custom Icon sections. The Apply Default Settings to All States option is on. Configure the
common settings for all states simultaneously by configuring them in the default state.

Configure all states to show the icon layer on top of the shape layer of the lamp:

1 On the Design tab, select the States component.


2 In the Shape and Icon Combination section, from Style, select Simple.

32-93
32 Control Simulations with Interactive Displays

To delete the custom icon for all states, in the Custom Icon section, click the X button.

For the floor indicator lights, the opacity of the shape layer of the lamp is also the same for all states.
However, since the Apply Default Settings to All States option does not apply to the parameters in
the Value and Color section, the remaining settings must be configured individually for each state.

In the Select State section, turn off the Apply Default Settings to All States option.

In the default state, all floor indicator lights are turned off.

In the Custom Icon section, set the Opacity to 0.

For each of the four non-default states, specify the parameter value that activates the state and
configure the appearance of the lamp. In each state, the elevator reaches a different floor, and the
corresponding floor indicator light turns yellow. To turn the light yellow, cover the labeled circle of
the floor with a yellow circle.

For each non-default state:

1 In the Select State section, open the drop-down menu.


2 If the state is listed in the drop-down menu, select it. If not, click the plus button in the toolstrip
to add a new state. Then, in the Select State section of the Property Inspector, select the new
state from the drop-down menu.
3 To turn the shape layer of the light yellow, in the toolbar, click the color wheel and set the color
to yellow.

32-94
Design Custom Lamps

4 To resize the surface, click and then drag one corner until the surface is the same size as the
labeled circles on the background image. To maintain the aspect ratio of the surface, press Shift
as you drag.
5 To position the surface, drag it on top of the labeled circle of the floor that the elevator reaches in
the selected state.

To unhide the foreground image, on the Design tab, click the eye icon of the Foreground Image
component. The eye icon no longer has a slash through it, indicating that the foreground image is
visible again.

When you finish adjusting the design for the floor indicator lights, to exit design mode, on the Design
tab, click Edit.

You can use the finished floor indicator lights to display a signal value. In the model, a Signal Builder
block represents the input signal to the floor indicator light panel.

32-95
32 Control Simulations with Interactive Displays

Connect the Lamp block to the Floor signal:

1 Select the Lamp block.


2 Click the Connect button that appears above the block.
3 Select the signal line with the label Floor.
4 Select the Floor option in the table that appears below the selected signal line.
5 Click the X in the upper right corner of the Simulink window.

To use the floor indicator lights, simulate the model. This model uses simulation pacing to slow model
execution so that you can clearly see the Lamp block respond to the value of the parameter that it
connects to. For more information about simulation pacing, see Simulation Pacing Options.

Design Pedestrian Crossing Light without Background Image

To design a pedestrian crossing light, add a customizable Lamp block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Lamp block.


2 In the Simulink Toolstrip, click the Lamp tab.
3 On the Lamp tab, click Edit. A toolbar appears above the Lamp block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Delete the background image:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the X button.

Delete the foreground image:

32-96
Design Custom Lamps

1 On the Design tab, select the Foreground Image component.


2 In the Select Image section, click the X button.

Configure the states for the pedestrian crossing light. In the model, the crossing light is controlled by
the walk light timer, which counts the elapsed seconds at the crosswalk for one minute, and then
resets. Over the first half of that minute, the stop sign is on. Over the second half, the walk sign is on.
The Lamp block represents this with three states:

• It is in the first state when the value of the walk light timer signal is between 0 seconds and 30
seconds, the time range when pedestrians are not permitted to cross the street.
• It is in the second state when the value of the walk light timer signal is between 30 seconds and
60 seconds, the time range when pedestrians are permitted to cross the street.
• It is in the default state when the block does not receive a parameter value that activates any
other of the specified states.

All states of the crossing light have the same settings in the Shape and Icon Combination and Size
and Position sections. The Apply Default Settings to All States option is on. Configure the
common settings for all states simultaneously by configuring them in the default state.

Configure all states to show the icon layer on top of the shape layer of the lamp:

1 On the Design tab, select the States component.


2 In the Shape and Icon Combination section, from Style, select Simple.

To configure all states to maximize and center the icon within the area taken up by the block, in the
Size and Position section:

1 Set the X Offset to 0.


2 Set the Y Offset to 0.
3 Set the Width to 1.
4 Set the Height to 1.
5 Set the Icon Size to 1.

32-97
32 Control Simulations with Interactive Displays

For the crossing light, the opacity of the shape layer of the lamp is also the same for all states.
However, since the Apply Default Settings to All States option does not apply to the parameters in
the Value and Color section, the remaining settings must be configured individually for each state.

In the Select State section, turn off the Apply Default Settings to All States option.

In the default state, the crossing light is turned off. The Lamp block uses a custom icon to show this.

Configure the appearance of the lamp for the default state:

1 To render the shape layer of the lamp invisible, in the Value and Color section, set the set the
Opacity to 0.
2 To add the custom icon, in the Custom Icon section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-1-off.png file.

By default, states are activated by a single parameter value. However, the crosswalk light shows the
walk signal over a certain time span, not at a certain time value. If you enable Specify State Values
as Ranges, you can specify a range of values to activate each state.

Specify the range of parameter values that activate the second state:

1 In the Select State section, open the drop-down menu and select 1 (State 2). The number in
this drop-down menu option is the parameter value that activates the state specified in
parentheses.
2 Turn on the Specify State Values as Ranges option. Observe that the drop-down menu option
has changed from 1 (State 2) to 1 to 1 (State 2). The numbers indicate the range of
values that activate the state.
3 In the Value and Color section, enter 60 as the Maximum value of the range.
4 In the Value and Color section, enter 30 as the Minimum value of the range.

In the second state, the walk signal is lit. The Lamp block uses a custom icon to show the lit walk
signal.

Configure the appearance of the lamp for the second state:

1 To render the shape layer of the lamp invisible, in the Value and Color section, set the set the
Opacity to 0.
2 To add the custom icon, in the Custom Icon section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-1-walk.png file.

32-98
Design Custom Lamps

Specify the range of parameter values that activate the first state:
1 On the Design tab of the Property Inspector, select the States component.
2 In the Select State section, open the drop-down menu and select 0 to 0 (State 1).
3 In the Value and Color section, enter 30 as the Maximum value of the range.

In the first state, the stop signal is lit. The Lamp block uses a custom icon to show the lit stop signal.

Configure the appearance of the lamp for the first state:


1 To render the shape layer of the lamp invisible, in the Value and Color section, set the set the
Opacity to 0.
2 To add the custom icon, in the Custom Icon section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-1-stop.png file.

Resize the block:


1 Exit design mode by clicking Edit on the Design tab.
2 In the canvas, drag one corner of the block outwards until the block is large enough to clearly
show the crossing light symbols.

You can use the finished crossing light to display a signal value. In the model, a Signal Builder block
represents the walk light timer. The Signal Builder block is set up such that one minute at the
crosswalk corresponds to 2 seconds of simulation time. In the model, the crosswalk light therefore
switches between stop and walk every second.

Connect the Lamp block to the Walk Light Timer [s] signal:
1 Select the Lamp block.
2 Click the Connect button that appears above the block.
3 Select the signal line with the label Walk Light Timer [s].
4 Select the Walk Light Timer [s] option in the table that appears below the selected signal
line.

32-99
32 Control Simulations with Interactive Displays

5 Click the X in the upper right corner of the Simulink window.

To use the crossing light, simulate the model. This model uses simulation pacing to slow model
execution so that you can clearly see the Lamp block respond to the value of the parameter that it
connects to. For more information about simulation pacing, see Simulation Pacing Options.

Design Pedestrian Crossing Light on Panel

If you want to design two lamps that share a common background but connect to different
parameters, you can do so using panels. For more information on panels, see “Getting Started with
Panels” on page 32-19.

To design a pedestrian crossing light with two lamps using this approach, add a customizable Lamp
block to the model.

Configure this lamp to be the bottom lamp in the crossing light, which is the walk light.

If the Property Inspector is not open to the Design tab with the Edit button pressed:
1 In the model canvas, select the Lamp block.
2 In the Simulink Toolstrip, click the Lamp tab.
3 On the Lamp tab, click Edit. A toolbar appears above the Lamp block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the bottom lamp of the crossing light:
1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-2-walk-off.png file.

Delete the foreground image:


1 On the Design tab, select the Foreground Image component.
2 In the Select Image section, click the X button.

32-100
Design Custom Lamps

Configure the states for the bottom lamp of the crossing light. In model, the bottom lamp in the
crossing light is controlled by the walk light timer, which counts the elapsed seconds at the crosswalk
for one minute, and then resets. Over the first half of that minute, the stop sign is on. Over the second
half, the walk sign is on. The Lamp block represents this with three states:

• It is in the first state when the value of the walk light timer signal is between 0 seconds and 30
seconds, the time range when pedestrians are not permitted to cross the street.
• It is in the second state when the value of the walk light timer signal is between 30 seconds and
60 seconds, the time range when pedestrians are permitted to cross the street.
• It is in the default state when the block does not receive a parameter value that activates any
other of the specified states.

All states of the bottom lamp have the same settings in the Shape and Icon Combination and Size
and Position sections. The Apply Default Settings to All States option is on. Configure the
common settings for all states simultaneously by configuring them in the default state.

Configure all states to show the icon layer on top of the shape layer of the lamp:

1 On the Design tab, select the States component.


2 In the Shape and Icon Combination section, open the Style drop-down menu, and select
Simple.

To configure all states to maximize and center the icon within the area taken up by the block, in the
Size and Position section:

1 Set the X Offset to 0.


2 Set the Y Offset to 0.
3 Set the Width to 1.
4 Set the Height to 1.
5 Set the Icon Size to 1.

For the bottom lamp, the opacity of the shape layer of the lamp is also the same for all states.
However, since the Apply Default Settings to All States option does not apply to the parameters in
the Value and Color section, the remaining settings must be configured individually for each state.

In the Select State section, turn off the Apply Default Settings to All States option.

In the default state, the bottom lamp is turned off. The Lamp block uses the background image to
show the unlit walk signal.

32-101
32 Control Simulations with Interactive Displays

Configure the appearance of the lamp for the default state:


1 In the Custom Icon section, click the X button.
2 In the Value and Color section, set the Opacity to 0.

By default, states are activated by a single parameter value. However, the crosswalk light shows the
walk signal over a certain time span, not at a certain time value. If you enable Specify State Values
as Ranges, you can specify a range of values to activate each state.

Specify the range of parameter values that activate the second state:
1 In the Select State section, open the drop-down menu and select 1 (State 2). The number in
this drop-down menu option is the parameter value that activates the state specified in
parentheses.
2 Turn on the Specify State Values as Ranges option. Observe that the drop-down menu option
has changed from 1 (State 2) to 1 to 1 (State 2). The numbers indicate the range of
values that activate the state.
3 In the Value and Color section, enter 60 as the Maximum value of the range.
4 In the Value and Color section, enter 30 as the Minimum value of the range.

In the second state, the walk signal is lit. The Lamp block uses a custom icon to show the lit walk
signal.

Configure the appearance of the lamp for the second state:


1 To render the shape layer of the lamp invisible, in the Value and Color section, set the set the
Opacity to 0.
2 To add the custom icon, in the Custom Icon section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-2-walk-on.png file.

Specify the range of parameter values that activate the first state:
1 On the Design tab of the Property Inspector, select the States component.
2 In the Select State section, open the drop-down menu and select 0 to 0 (State 1).
3 In the Value and Color section, enter 30 as the Maximum value of the range.

In the first state, the walk signal is not lit. The Lamp block uses the background image to show the
unlit walk signal.

Configure the appearance of the lamp for the first state:

32-102
Design Custom Lamps

1 In the Custom Icon section, click the X button.


2 In the Custom Icon section, set the Opacity to 0.

Exit design mode by clicking Edit on the Design tab.

Resize the block in the canvas by dragging one of its corners outwards until it is large enough to
clearly show the walk symbol.

To configure the top lamp in the crossing light, copy and paste the Lamp block for the bottom lamp in
the canvas. The copy represents the top lamp in the crossing light, which is the stop light.

To modify the design of the Lamp block, enter design mode:


1 On the Modeling tab, under Design, select Property Inspector.
2 In the model canvas, select the Lamp block.
3 In the Property Inspector, select the Design tab and click Edit.

Change the background image for the top lamp of the crossing light:
1 On the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomLampImages folder, select the ped-xing-2-stop-off.png file.

Configure the states for the top lamp of the crossing light. The top lamp is lit when the bottom lamp
is off, and vice versa. In the model, the parameter value settings for the top lamp are the same as
those for the bottom lamp, and the different timing of the two lamps is achieved by connecting the
top lamp to a different timer, the stop light timer. This timer also counts the elapsed seconds at the
crosswalk for one minute, and then resets. However, the signal of the stop light timer is offset from
that of the walk light timer by 30 seconds.

32-103
32 Control Simulations with Interactive Displays

Since both the top and bottom lamps of the crossing light have the same parameter value settings,
you only need to configure the appearance of the top lamp for each state. Since the default state and
the first state only show the background image, you do not need to modify these states.

In the second state, the stop signal is lit. The Lamp block uses a custom icon to show the lit stop
signal.

Configure the appearance of the lamp for the second state:

1 To add the custom icon, in the Custom Icon section, click the plus button.
2 In the CustomLampImages folder, select the ped-xing-2-stop-on.png file.

Exit design mode by clicking Edit on the Design tab.

Select and drag the Lamp block of the top lamp, the stop signal, to be directly above the bottom lamp,
the walk signal.

Promote both of the custom Lamp blocks for the crossing light to a panel:

1 Select both Lamp blocks in the canvas.


2 To open the action menu, click the three blue dots.
3 In the action menu, click the Promote to Panel button.

32-104
Design Custom Lamps

Change the background color of the panel to black:


1 Click the panel.
2 To open the action menu, click the three blue dots.
3 In the action menu, click the Edit Panel button.
4 In the action menu, click the Change Background Image button.
5 In the CustomLampImages folder, select the ped-xing-2-panel-background.png file.
6 Click the panel. In the action menu, click the Done Editing button.

When you finish adjusting the design for the crossing light, to exit design mode, on the Design tab,
click Edit.

You can use the finished crossing light to display a signal value. In the model, two Signal Builder
blocks represents the walk light and stop light timers. The Signal Builder blocks are set up such that
one minute at the crosswalk corresponds to 2 seconds of simulation time. In the model, the crosswalk
light therefore switches between stop and walk every second.

32-105
32 Control Simulations with Interactive Displays

Connect the bottom Lamp block to the Walk Light Timer [s] signal:

1 Select the Lamp block.


2 Click the Connect button that appears above the block.
3 Select the signal line with the label Walk Light Timer [s].
4 Select the Walk Light Timer option in the table that appears below the selected signal line.
5 Click the X in the upper right corner of the Simulink window.

Connect the top Lamp block to the Stop Light Timer [s] signal:

1 Select the Lamp block.


2 Click the Connect button that appears above the block.
3 Select the signal line with the label Stop Light Timer [s].
4 Select the Stop Light Timer option in the table that appears below the selected signal line.
5 Click the X in the upper right corner of the Simulink window.

To use the Pedestrian Crossing Light 2 Lamp blocks, simulate the model. This model uses simulation
pacing to slow model execution so that you can clearly see the Lamp block respond to the value of the
parameter that it connects to. For more information about simulation pacing, see Simulation Pacing
Options.

See Also
Blocks
Lamp

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-106
Design Custom Rocker, Slider, and Toggle Switches

Design Custom Rocker, Slider, and Toggle Switches

This example shows how to use the customizable Rocker Switch, Slider Switch, and Toggle Switch
blocks to design three switches that look like controls in real systems:

• A diff lock switch to lock the differential in a passenger vehicle, modeled as a rocker switch
• An automotive gearbox modeled as a slider switch
• An electromechanical toggle switch

Every switch has multiple states. A state pairs a State Value with a customizable State Label and
block appearance. The block appearance of a state can, for example, include an image that appears
on the block between the background and foreground or a particular font color for the State Label.

You can activate a state by clicking its click area. When you activate the state, the State Value is
assigned to the Simulink® block diagram element to which the switch block is connected.

The blocks in the model use PNG images to define the appearance of states. You can find all images
used to create the switches in the example directory.

Design Diff Lock Rocker Switch

To design the diff lock switch, add a customizable Rocker Switch block to the model using the
Simulink quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Rocker Switch block, type Rocker Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Rocker Switch block, enter design mode:

1 In the model canvas, select the Rocker Switch block.


2 In the Simulink Toolstrip, click the Switch tab.
3 On the Switch tab, click Edit. A toolbar appears above the Rocker Switch block.

32-107
32 Control Simulations with Interactive Displays

4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

You can design a custom switch using the toolbar or using the Design tab of the Property
Inspector. This example uses both.

Adding state images to a customizable dashboard block changes the aspect ratio of the state images
to match the aspect ratio of the block.

Adding a background image to a customizable dashboard block changes the aspect ratio of the block
to match the aspect ratio of the background image.

To prevent state images from being distorted, before you add the state images, you can use a
transparent background image to set the aspect ratio of the block to be the same as the aspect ratio
of the state image.

Add the transparent background image for the diff lock switch:

1 On the Design tab, select the Background Image component.


2 In the Select Image section, click the plus button.
3 In the CustomRockerSliderToggleSwitchImages folder, select the diff-lock-switch-
background.png file.

32-108
Design Custom Rocker, Slider, and Toggle Switches

The Rocker Switch block for the diff lock switch has two states:

• In State 1, the car is in four-wheel drive mode. The Rocker Switch block has a State Value of 0 and
the State Label 4WD.
• In State 2, the differential is locked. The Rocker Switch block has a State Value of 1 and the State
Label Lock.

When the Rocker Switch block is in State 1, the half of the diff lock switch with the 4WD label is
pressed down.

Configure the appearance of the diff lock switch for State 1:

1 On the Design tab, select the States component. The Value of the state is 0 by default.
2 To make the state identifiable in the Select State section drop-down list, in the Label section,
enter the State Label 4WD in the Text field. When you click out of the Text field, the label appears
in the Select State section drop-down list.
3 Since the diff lock switch settings are labeled in the background image, the block labels are
redundant. In the Label section, turn off Show Label.
4 In the toolbar, click Replace State Image.
5 In the CustomRockerSliderToggleSwitchImages folder, select the diff-lock-
switch-4wd.png file.

To configure the Click Area for State 1, in the canvas, click and drag the corners of the yellow
rectangle to cover the upper half of the state image.

32-109
32 Control Simulations with Interactive Displays

When the Rocker Switch block is in State 2, the half of the diff lock switch with the LOCK label is
pressed down.

Configure the appearance of the diff lock switch for State 2:

1 In the Select State section, select On (State 2). The Value of the state is 1 by default.
2 In the Label section, enter the State Label Lock in the Text field.
3 In the Label section, turn off Show Label.
4 In the toolbar, click Replace State Image.
5 In the CustomRockerSliderToggleSwitchImages folder, select the diff-lock-switch-
lock.png file.

To configure the Click Area for State 2, in the canvas, click and drag the corners of the yellow
rectangle to cover the lower half of the state image. To avoid overlap between the click areas of the
first and second states, in the toolbar, click Show All Click Areas. You can now see the click areas of
all states while editing the click area of the active state.

32-110
Design Custom Rocker, Slider, and Toggle Switches

When you finish adjusting the design for the diff lock switch, to exit design mode, in the Property
Inspector, on the Design tab, click Edit.

You can use the finished diff lock switch to control a parameter. In the model, a Constant block
represents the mode of operation of the differential, and the Rocker Switch block controls the value
of the constant.

Connect the Rocker Switch block to the Value parameter of the Constant block:

1 Select the Rocker Switch block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const1.
4 In the table that appears below the selected signal, select Const1:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the diff lock switch:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 During simulation, click the upper or on the lower half of the background image to flip the rocker
switch.
3 See the effect on the mode of operation of the differential in the Dashboard Scope block.

32-111
32 Control Simulations with Interactive Displays

Design Gearbox Modeled as Slider Switch

To design the automotive gearbox, add a customizable Slider Switch block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:
1 In the model canvas, select the Slider Switch block.
2 In the Simulink Toolstrip, click the Switch tab.
3 On the Switch tab, click Edit. A toolbar appears above the Slider Switch block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the gearbox:


1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomRockerSliderToggleSwitchImages folder, select the gearbox-
background.png file.

The Slider Switch block for the gearbox has seven states:

• In State 1, the car is in first gear. The Slider Switch block has a State Value of 1 and the State
Label First Gear.
• In State 2, the car is in second gear. The Slider Switch block has a State Value of 2 and the State
Label Second Gear.
• In State 3, the car is in third gear. The Slider Switch block has a State Value of 3 and the State
Label Third Gear.
• In State 4, the car is in fourth gear. The Slider Switch block has a State Value of 4 and the State
Label Fourth Gear.
• In State 5, the car is in fifth gear. The Slider Switch block has a State Value of 5 and the State
Label Fifth Gear.
• In State 6, the car is in reverse. The Slider Switch block has a State Value of -1 and the State
Label Reverse.
• In State 7, the car is in neutral. The Slider Switch block has a State Value of 0 and the State Label
Neutral.

32-112
Design Custom Rocker, Slider, and Toggle Switches

When the Slider Switch block is in State 1, the gear lever is in the upper left slot of the gearbox.

Configure the appearance of the gearbox for State 1:

1 On the Design tab, select the States component.


2 The default Slider Switch block has two states. Since multiple states cannot be assigned the
same State Value, before assigning the value for State 1, check the value for State 2 by
expanding the Select State menu and selecting On (State 2).
3 The State Value of State 2, shown in the Value section, is 1, but the State Value for State 1 of the
diff lock switch is also 1. To change the State Value of State 2, in the Value section, set Value to
2.
4 To configure State 1, in the Select State menu, select Off (State 1).
5 To make the state identifiable in the Select State section drop-down list, in the Label section,
enter the State Label First Gear in the Text field. When you click out of the Text field, the
label appears in the Select State section drop-down list.
6 Since the gears are labeled on the gearstick in the background image, the block labels are
redundant. In the Label section, turn off Show Label.
7 In the toolbar, click Replace State Image.
8 In the CustomRockerSliderToggleSwitchImages folder, select the gearbox-gear-1.png
file.

To exit design mode, on the Design tab, click Edit. Resize the block in the canvas by dragging one of
its corners outwards until the numbers on the gear lever are large enough to read.

To reenter design mode, in the Property Editor, on the Design tab, click Edit.

To configure the Click Area for State 1, in the canvas, click and drag the corners of the yellow
rectangle to cover the upper left slot on the gearbox in the background image.

32-113
32 Control Simulations with Interactive Displays

To configure the other five states, for each state:


1 In the Property Inspector, on the Design tab, in the States component, in the Select State
section, expand the drop-down list. If the state number is listed, select the corresponding state. If
not, click the plus button to add a new state.
2 In the Value section, enter the State Value.
3 In the Label section, enter the State Label in the Text field.
4 If a State Label is visible in the canvas, in the Label section, turn off Show Label.
5 In the toolbar, click Replace State Image.
6 In the CustomRockerSliderToggleSwitchImages folder, select the gearbox-gear-N.png
file, where N is the number of the gear. For reverse, select the gearbox-reverse.png file, and
for neutral, select the gearbox-neutral.png file.
7 To configure the click area, in the canvas, click and drag the corners of the yellow rectangle. Use
the image as a guide to size and position the click area. To avoid overlap between the click areas
of different states, in the toolbar, click Show All Click Areas. You can now see the click areas of
all states while editing the click area of the active state.

32-114
Design Custom Rocker, Slider, and Toggle Switches

When you finish adjusting the design for the gearbox, to exit design mode, in the Property Inspector,
on the Design tab, click Edit.

You can use the finished gearbox to control a parameter. In the model, a Constant block represents
the gear of a car. The Slider Switch block controls the value of the constant.

Connect the Slider Switch block to the Value parameter of the Constant block:

1 Select the Slider Switch block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const2.
4 In the table that appears below the selected signal, select Const2:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the gearbox:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 During simulation, click the area of the background image to which you want to move the gear
lever to change gears during simulation.
3 See the effect on the gear in the Dashboard Scope block.

Design Electromechanical Toggle Switch

To design the electromechanical toggle switch, add a customizable Toggle Switch block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Toggle Switch block.


2 In the Simulink Toolstrip, click the Switch tab.

32-115
32 Control Simulations with Interactive Displays

3 On the Switch tab, click Edit. A toolbar appears above the Toggle Switch block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the electromechanical switch:


1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomRockerSliderToggleSwitchImages folder, select the toggle-
background.png file.

The Toggle Switch block for the electromechanical switch has three states:

• In State 1, the switch is on, the toggle is pointing down. The Toggle Switch block has a State Value
of -1 and the State Label On, Down.
• In State 2, the switch is off, the toggle is centered. The Toggle Switch block has a State Value of 0
and the State Label Off.
• In State 3, when the switch is on, the toggle is pointing up. The Toggle Switch block has a State
Value of 1 and the State Label On, Up.

When the Toggle Switch block is in State 1, the toggle is pointing down.

Configure the appearance of the electromechanical switch for State 1:


1 On the Design tab, select the States component.
2 In the Value section, set the Value to -1.
3 To make the state identifiable in the Select State section drop-down list, in the Label section,
enter the State Label On, Down in the Text field. When you click out of the Text field, the label
appears in the Select State section drop-down list.
4 Since the settings of the electromechanical switch are labeled in the background image, the
block labels are redundant. In the Label section, turn off Show Label.
5 In the toolbar, click Replace State Image.
6 In the CustomRockerSliderToggleSwitchImages folder, select the toggle-down.png file.

To exit design mode, on the Design tab, click Edit. Resize the block in the canvas by dragging one of
its corners outwards until the labels on the electromechanical switch are large enough to read.

32-116
Design Custom Rocker, Slider, and Toggle Switches

To reenter design mode, in the Property Editor, on the Design tab, click Edit.

To configure the Click Area for State 1, in the canvas, click and drag the corners of the yellow
rectangle to cover the electromechanical switch from the bottom to halfway between the OFF label
and the lower ON label.

When the Toggle Switch block is in State 2, the toggle is centered.

Configure the appearance of the electromechanical switch for State 2:

1 On the Design tab, select the States component.


2 In the Select State section, select On (State 2).
3 In the Value section, set the Value to 0.
4 In the Label section, enter the State Label Off in the Text field.
5 In the Label section, turn off Show Label.
6 In the toolbar, click Replace State Image.
7 In the CustomRockerSliderToggleSwitchImages folder, select the toggle-neutral.png
file.

32-117
32 Control Simulations with Interactive Displays

To configure the Click Area for State 2, in the canvas, click and drag the corners of the yellow
rectangle to cover the switch from halfway between the OFF label and the lower ON label to halfway
between the OFF label and the upper ON label. To avoid overlap between the click areas of State 1
and State 2, click Show All Click Areas. You can now see the click areas of all states while editing
the click area of the active state.

When the Toggle Switch block is in State 3, the toggle is up.

Configure the appearance of the electromechanical switch for State 3:

1 In the Property Inspector, on the Design tab, select the States component.
2 To add a new state, in the Select State section, click the plus button.
3 In the Value section, set the Value to 1.
4 In the Label section, enter the State Label On, Up in the Text field.
5 In the toolbar, click Replace State Image.
6 In the CustomRockerSliderToggleSwitchImages folder, select the toggle-up.png file.

32-118
Design Custom Rocker, Slider, and Toggle Switches

To configure the Click Area for State 3, in the canvas, click and drag the corners of the yellow
rectangle to cover the switch from the top to halfway between the OFF label and the upper ON label.

When you finish adjusting the design for the electromechanical switch, to exit design mode, in the
Property Inspector, on the Design tab, click Edit.

You can use the finished switch to control a parameter. In the model, a Constant block represents the
state of the electromechanical switch, and the Toggle Switch block controls the value of the constant.

32-119
32 Control Simulations with Interactive Displays

Connect the Toggle Switch block to the Value parameter of the Constant block:

1 Select the Toggle Switch block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const3.
4 In the table that appears below the selected signal, select Const3:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the electromechanical switch:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 During simulation, click the area of the background image to which you want to move the toggle
to turn the switch on or off.
3 See the effect on the state of the switch in the Dashboard Scope block.

See Also
Blocks
Rocker Switch | Slider Switch | Toggle Switch

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-120
Design Custom Buttons

Design Custom Buttons

This example shows how to use the customizable Push Button and Callback Button blocks to design
the button panel of an elevator, including:

• Buttons that specify the floor you want to travel to


• Buttons that open and close the elevator doors
• An alarm button

You can push these virtual buttons by clicking the Push Button and Callback Button blocks. While you
press down your pointer, the button is pushed. When you release your pointer, you release the button.

You can use callback functions to specify what you want the buttons to do:

• PressFcn functions run while the button is pushed. You can configure a PressFcn function to
run only once while the button is pushed, or you can specify a repeat interval.
• ClickFcn functions run when you release the button.

In this example, you will use ClickFcn functions to display messages about the actions of an elevator
in the MATLAB® Command Window.

You can configure a button to stay pushed when you release your pointer by making it a latched
button. Once configured, to latch the button, click it. To unlatch the button, click it again. The

32-121
32 Control Simulations with Interactive Displays

PressFcn function runs while the button is latched. The ClickFcn function runs once when you
latch the button and once when you unlatch the button.

In this example, you will configure the elevator floor buttons and the alarm button as latched buttons
because real floor and alarm buttons typically stay lit when you release them.

You can use states to specify how the appearance of the Push Button or Callback Button block
changes when you interact with a button:

• While you push the button, the block is in the Pressed state.
• When the button is latched and you are not pushing it, the block is in the Latched state.
• When a button is latched and you are pushing it, the block is in the Latched and Pressed state.
• When a block is not in any of these three states, it is in the Default state.

The states pair pointer actions with:

• A state label
• A state icon
• A state image

For the Push Button block, the Pressed, Latched, and Latched and Pressed states also pair
pointer actions with an On Value. The On Value is the same for these three states. When you enter
one of these states, the On Value is assigned to the Simulink® component to which the Push Button
block connects.

In this example, you will create buttons that control the floor an elevator travels to by assigning their
On Value to a Constant block.

Design Elevator Ground Floor Button with Push Button Block

In this example, you use the Push Button block to model the ground floor button of an elevator.

When you click the ground floor button:

• The button lights up.


• The value of a Constant block changes.
• The MATLAB Command Window displays a message that states which floor the elevator is
traveling to.

The ground floor button is modeled using the Push Button block because Push Button blocks directly
control the value of the block that they connect to. Callback Button blocks do not connect to a block
and can only control a block parameter value using callback functions.

You can use Callback functions to access a block parameter value programmatically or set a block
parameter value to a variable whose value is changed by the callback function. However, both
approaches add complexity to the model. Using a Push Button block simplifies the process of
controlling a block parameter value.

To create the ground floor button, add a customizable Push Button block to the model using the
Simulink quick insert menu:

1 To open the quick insert menu, double-click the canvas.

32-122
Design Custom Buttons

2 To search for the customizable Push Button block, type Push Button.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

When you press an elevator floor button in a real elevator, the button stays lit when you release it. To
implement this behavior on the Push Button block:

1 In the Simulink Toolstrip, on the Modeling tab, under Design, select Property Inspector.
2 In the Property Inspector, on the Parameters tab, in the Main section, for Button Type, select
Latch.

The elevator button now has four states: Default, Pressed, the Latched, and Pressed and
Latched state:

• In the Default state, the elevator floor button is not lit.


• In the other states, the elevator floor button is lit.

Each state has an image that can be used to show whether the elevator button is lit.

To modify the state images of the Push Button block, enter design mode:

1 If the Push Button block is not selected, select the block.


2 In the Simulink Toolstrip, in the Button tab, click Edit.
3 In the toolbar that appears above the block, click Open Design Tab.

Adding state images to a customizable dashboard block changes the aspect ratio of the state images
to match the aspect ratio of the block.

32-123
32 Control Simulations with Interactive Displays

Adding a background image to a customizable dashboard block changes the aspect ratio of the block
to match the aspect ratio of the background image.

To prevent state images from being distorted, before you configure the button states, you can use a
background image to set the aspect ratio of the block to be the same as the aspect ratio of the state
image.

In this model, the background image both sets the aspect ratio and shows the label of the elevator
floor button.

Add the background image for the elevator floor buttons:

1 On the Design tab, select the Background Image component.


2 In the Select Image section, click the plus button.
3 In the CustomButtonImages folder, select the elevator-button-floor-G.png file.

Note that the new background image is not visible because the default state icon and image are
covering it, but the aspect ratio of the block has changed.

Configure the appearance of the button for the Default state:

1 In the Property Inspector, on the Design tab, open the States component.
2 In the Icon section, click the X.
3 In the Image section, click the plus button.
4 In the CustomButtonImages folder, select the elevator-button-off.png file.
5 Set the X Offset and Y Offset to 0.
6 Set the Width and Height to 1.
7 Since the image already indicates which elevator button is being modeled, the button label text is
not needed. In the Label section, delete the default Text.

To configure the appearance of the button for the Pressed, Latched, and Latched and Pressed
states, for each state:

1 In the Property Inspector, on the Design tab, open the States component.
2 In the Select State section, select the state.
3 In the Icon section, click the X.
4 In the Image section, click the plus button.

32-124
Design Custom Buttons

5 In the CustomButtonImages folder, select the elevator-button-on.png file.


6 Set the X Offset to 0.
7 To make the button look like it is pushed down, set the Y Offset to 0.025.
8 Set the Width and Height to 1.
9 In the Label section, delete the default Text.
10 In the Label section, verify that the X Offset and Y Offset are set to 0. If they are not, set them
to 0.

The appearance of the ground floor button is now fully configured. To exit design mode, in the
Property Inspector, on the Design Tab, click Edit.

When the Push Button block enters a state, the On Value of the block is assigned to the Simulink
block diagram element to which the Push Button block connects.

In this example, the ground floor button controls the value of a Constant block with a scalar value
that tracks the destination of the elevator:

• When the value is 0, the elevator is not traveling to the ground floor.
• When the value is 1, the elevator is traveling to the ground floor.

To implement this behavior, set the value of the Const_scalar block to 0, and the On Value of the
ground floor button to 1:

• In the model, the value of the Const_scalar block is already set to 0.


• You can specify the On Value in the Property Inspector, on the Parameters tab, in the Main
section. For this example, the On Value is 1 by default.

To connect the ground floor button to the Const_scalar block:

1 Select the Push Button block.


2 Click the Connect button that appears above the block.
3 Select the Const_scalar block.
4 In the table that appears below the selected signal, select Const_scalar:Value.
5 Click the X in the upper right corner of the Simulink window.
6 To check the connection, select the Push Button block. If the Constant block is connected, it is
highlighted in purple.

32-125
32 Control Simulations with Interactive Displays

You can use a callback function to display in the MATLAB Command Window the floor that the
elevator is headed to when you click the ground floor button and the button lights up.

Let status_scalar be the variable that the callback function uses to track whether or not the
elevator button is lit:

• When the button is lit, the value is 1.


• When the button is not lit, the value is 0.

Note that status_scalar is different from and does not affect the On Value of the Push Button
block.

Set up a preload callback function that automatically initializes status_scalar to a value of 0 when
you open the model:

1 Right-click the Simulink canvas and select Model Properties.


2 On the Callbacks tab, in the PreLoadFcn section, enter this command and click OK:

status_scalar=0;

Run the preload callback function: save and re-open the model.

Write the callback function to display which floor the elevator is heading to when the button is
clicked:

1 In the Property Inspector, on the Parameters tab, in the Callbacks section, from the list, select
ClickFcn.
2 In the Callbacks section, enter these commands:

if(status_scalar<1)
status_scalar=1;
disp('Elevator is headed to ground floor');
else
status_scalar=0;
end

Elevator is headed to ground floor

The ground floor button is now fully configured. To test the button:

32-126
Design Custom Buttons

1 Simulate the model.


2 During simulation, click the button. When the button lights up, the MATLAB Command Window
displays the message Elevator is headed to ground floor.

Design Elevator Button Panel

In this example, you use the ground floor button from the previous section to create an elevator
button panel with eight floor buttons on it. The panel includes one ground button and buttons for
floors one to seven.

Before creating the buttons, consider how you connect the buttons with the block parameter value
that they control. When you have many elevator floor buttons, connecting each one to a separate
Constant block with a scalar Constant value adds complexity to the model structure. Instead, you can
connect all elevator buttons to a single Constant block with a Constant value that is a vector. Each
button controls one element in the vector.

In the model, the Constant block named Const_vector has a Constant value that is a vector with
eight elements, one for every floor. The value of each element is initialized to zero.

Connect the Push Button to Const_vector:

1 Select the Push Button block for the ground floor.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const_vector.
4 In the table that appears below the selected signal, select Const_vector:Value.
5 To indicate the vector element that corresponds to the ground floor, in the text box at the bottom
of the Connect dialog box, enter 1.
6 Click the X in the upper right corner of the Simulink window.

Each button needs its own callback function variable to track the button status. Let these variables all
be elements of a vector: the status_vector.

Use a preload callback function to initialize the value of the status_vector so that it is
automatically initialized to zeros(8,1) when you open the model:

32-127
32 Control Simulations with Interactive Displays

1 Right-click the Simulink canvas and select Model Properties.


2 On the Callbacks tab, in the PreLoadFcn section, enter this command and click OK:

status_vector=zeros(8,1);

Save and reopen the model.

Change the callback function of the Push Button for the ground floor to track the status of the ground
floor button with the first element of the status_vector:

floor=0;
i_floor=floor+1;
if(status_vector(i_floor)<1)
status_vector(i_floor)=1;
disp('Elevator is headed to ground floor');
else
status_vector(i_floor)=0;
end

Elevator is headed to ground floor

To create the elevator buttons for floors one through seven, for each button:

1 Copy and paste the ground floor button.


2 Select the copy.
3 To enter design mode, in the Property Inspector, on the Design tab, click Edit.
4 In the Background Image component, in the Select Image section, click the green plus button.
5 In the CustomButtonImages folder, select the elevator-button-floor-N.png file, where N
is the number of the floor. In the Property Inspector, on the Parameters tab, in the Callbacks
section, change the value of floor to N.
6 Also in the Callbacks section, change the message that is displayed when the elevator button
lights up to indicate that the elevator is traveling to floor N.
7 To exit design mode, click the X in the upper right corner of the canvas.
8 Select the Push Button block.
9 Click the Connect button that appears above the block.
10 Select the Constant block named Const_vector.
11 In the table that appears below the selected signal, select Const_vector:Value.
12 In the text box at the bottom of the Connect dialog box, enter N+1.
13 Click the X in the upper right corner of the Simulink window.

32-128
Design Custom Buttons

The elevator floor buttons are mounted to a panel on the wall. Create a Simulink panel:

1 Create a copy of the ground floor button.


2 Select the copy.
3 Click the ellipsis that appears above the block and select Promote to Panel.

Add a background image to the panel:

1 Select the panel.


2 To enter panel edit mode, click the ellipsis that appears above the panel and select Edit Panel.
3 In the action menu that appears, select Change Background Image.
4 In the CustomButtonImages folder, select the elevator-button-panel-background.png
file.
5 Resize the panel to make it large enough to fit eleven buttons in six rows and two columns by
clicking and dragging one of the panel corners. Resizing can also change the aspect ratio of the
panel. Size the panel such that the screw heads in the panel background image are circular.

32-129
32 Control Simulations with Interactive Displays

Add the other seven floor buttons to the panel: click and drag each button onto the panel to add it.

Resize and position the buttons so that the floor number plates exactly cover the empty squares on
the panel background image. To resize a button, select the block modeling that button, then click and
drag one of its corners. To position a button, select the button, then use the arrow keys to move it.

To exit panel edit mode, in the action menu above the panel, select Done Editing.

To use the buttons:

1 Simulate the model.


2 During simulation, click the buttons. When a button lights up, the MATLAB Command Window
displays the message that you entered in the callback function for that button.

32-130
Design Custom Buttons

Design Elevator Door Buttons with Callback Button Blocks

In this example, you use the Callback Button block to model the door buttons of an elevator.

When you click or press the door buttons:

1 The door buttons light up and stay lit until you release the click.
2 The MATLAB Command Window displays a message that states whether the doors are opening or
closing.

Unlike the elevator floor buttons, the door buttons are not used to control a value.

To design the button that opens the elevator door, add a customizable Callback Button block to the
model.

The door buttons only stay lit until you release the click. Whether the buttons stay in the nondefault
states when you release the click or not depends on the Button Type.

The Button Type for the door button is Momentary, meaning that the buttons revert to the default
state when you release the click.

Check the Button Type of the Callback Button block:

32-131
32 Control Simulations with Interactive Displays

1 Select the Callback Button block.


2 If the Property Inspector is not open, in the Simulink Toolstrip, on the Modeling tab, under
Design, select Property Inspector.
3 In the Main section, Button Type is set to Momentary by default.

The door button has two states, Default and Pressed:

• In the Default, the elevator door button is not lit.


• In the Pressed, the elevator door button is lit.

Each state has an image that can be used to show whether the door button is lit.

To modify the state images of the Callback Button block, enter design mode:

1 If the Callback Button block is not selected, select the block.


2 In the Simulink Toolstrip, in the Button tab, click Edit.
3 In the toolbar that appears above the block, click Open Design Tab.

Adding state images to a customizable dashboard block changes the aspect ratio of the state images
to match the aspect ratio of the block.

Adding a background image to a customizable dashboard block changes the aspect ratio of the block
to match the aspect ratio of the background image.

To prevent state images from being distorted, before you configure the button states, you can use a
background image to set the aspect ratio of the block to be the same as the aspect ratio of the state
image.

32-132
Design Custom Buttons

In this model, the background image both sets the aspect ratio and shows the label of the elevator
door button.

Add the background image for the door buttons:

1 On the Design tab, select the Background Image component.


2 In the Select Image section, click the plus button.
3 In the CustomButtonImages folder, select the elevator-button-open-door.png file.

Note that the new background image is not visible because the default state icon and image are
covering it, but the aspect ratio of the block has changed.

Configure the appearance of the button for the default state:

1 In the Property Inspector, on the Design tab, open the States component.
2 In the Icon section, click the X.
3 In the Image section, click the plus button.
4 In the CustomButtonImages folder, select the elevator-button-off.png file.
5 Set the X Offset and Y Offset to 0.
6 Set the Width and Height to 1.
7 Since the image already indicates which elevator button is being modeled, the button label text is
not needed. In the Label section, delete the default Text.

To configure the appearance of the button for the pressed state:

1 In the States Component, in the Select State section, select the type of state.
2 In the Icon section, click the X.
3 In the Image section, click the plus button.
4 In the CustomButtonImages folder, select the elevator-button-on.png file.
5 Set the X Offset to 0.
6 To make the button look like it is pushed down, set the Y Offset to 0.025.
7 Set the Width and Height to 1.
8 In the Label section, delete the default Text.
9 In the Label section, set the X Offset and Y Offset to 0.

32-133
32 Control Simulations with Interactive Displays

The appearance of the button that opens the elevator door is now fully configured. To exit design
mode, in the Property Inspector, on the Design Tab, click Edit.

You can use a callback function to display in the MATLAB Command Window that the elevator door is
opening in after you click it.

Write the callback function to display that the elevator door is opening after the button is clicked:

1 In the Property Inspector, on the Parameters tab, in the Callbacks section, from the list, select
ClickFcn.
2 In the Callbacks section, enter these:

disp('Elevator doors are opening');

Elevator doors are opening

The button that opens the elevator door is now fully configured.

To create the button that closes the elevator door:

1 Copy and paste the button that opens the elevator door.
2 Select the copy.
3 To enter design mode, in the Property Inspector, on the Design tab, click Edit.
4 In the Background Image component, in the Select Image section, click the green plus button.
5 In the CustomButtonImages folder, select the elevator-button-close-door.png file.
6 In the Property Inspector, on the Parameters tab, in the Callbacks section, change the message
that is displayed when the elevator button lights up to indicate that the doors are closing.

The buttons that open and close the elevator doors are now fully configured.

Add the door buttons to the elevator button panel:

1 Select the panel.


2 To enter panel edit mode, click the ellipsis that appears above the panel and select Edit Panel.
3 Click and drag the door buttons onto the panel.
4 Position the door buttons in a row beneath the other buttons. Leave space at the bottom for one
more button to complete the next section of the example.
5 If needed, resize the buttons to fit them on the panel. To resize a button, select the block that
models the button and then click and drag one of its corners.

32-134
Design Custom Buttons

6 To exit panel edit mode, in the action menu above the panel, select Done Editing.

To use the door buttons:


1 Simulate the model.
2 During simulation, click the buttons. When the button lights up, the MATLAB Command Window
displays a message that states whether the elevator doors are opening or closing.

Design Elevator Alarm Button with Callback Button Block

In this example, you use the Callback Button block to model the alarm button of an elevator:

32-135
32 Control Simulations with Interactive Displays

1 When you click or press the alarm button, it lights up and stays lit after you release the click.
2 When you click or press the door buttons, the MATLAB Command Window displays the message
Alarm!.

Unlike the elevator floor buttons, the alarm button is not used to control a value.

To design the alarm button, add a customizable Callback Button block to the model.

When you press the alarm button in a real elevator, the button stays lit even when you release it. To
implement this behavior on the Callback Button block:

1 Select the Callback Button block.


2 If the Property Inspector is not open, in the Simulink Toolstrip, on the Modeling tab, under
Design, select Property Inspector.
3 In the Property Inspector, on the Parameters tab, in the Main section, for Button Type, select
Latch.

The elevator button now has four states: Default, Pressed, Latched, and Pressed and
Latched.

• In the Default state, the elevator alarm button is not lit.


• In the other states, the elevator alarm button is lit.

Each state has an image that can be used to show whether the elevator button is lit.

To modify the state images of the Callback Button block, enter design mode:

1 If the Callback Button block is not selected, select the block.


2 In the Simulink Toolstrip, in the Button tab, click Edit.
3 In the toolbar that appears above the block, click Open Design Tab.

Adding state images to a customizable dashboard block changes the aspect ratio of the state images
to match the aspect ratio of the block.

Adding a background image to a customizable dashboard block changes the aspect ratio of the block
to match the aspect ratio of the background image.

To prevent state images from being distorted, before you configure the button states, you can use a
background image to set the aspect ratio of the block to be the same as the aspect ratio of the state
image.

In this model, the background image both sets the aspect ratio and shows the label of the alarm
button.

Add the background image for the alarm buttons:

1 On the Design tab, select the Background Image component.


2 In the Select Image section, click the plus button.
3 In the CustomButtonImages folder, select the elevator-button-alarm.png file.

32-136
Design Custom Buttons

Note that the new background image is not visible because the default state icon and image are
covering it, but the aspect ratio of the block has changed.

Configure the appearance of the button for the Default state:

1 In the Property Inspector, on the Design tab, open the States component.
2 In the Icon section, click the plus button.
3 In the CustomButtonImages folder, select the elevator-button-alarm-icon.png file.
4 Set the Width and Height to 1.
5 In the Image section, click the plus button.
6 In the CustomButtonImages folder, select the elevator-button-alarm-off.png file.
7 Set the X Offset and Y Offset to 0.
8 Set the Width and Height to 1.
9 Since the image already indicates which elevator button is being modeled, the button label text is
not needed. In the Label section, delete the default Text.

To configure the appearance of the button for the Pressed state:

1 In the States Component, in the Select State section, select the type of state.
2 In the Icon section, click the plus button.
3 In the CustomButtonImages folder, select the elevator-button-alarm-icon.png file.
4 Set the Width and Height to 1.
5 In the Image section, click the plus button.
6 In the CustomButtonImages folder, select the elevator-button-alarm-off.png file.
7 Set the X Offset to 0.
8 To make the button look like it is pushed down, set the Y Offset to 0.025.
9 Set the Width and Height to 1.
10 In the Label section, delete the default Text.
11 In the Label section, set the X Offset to 0.
12 To keep the state icon centered on the state image, set the Y Offset to 0.025.

32-137
32 Control Simulations with Interactive Displays

The appearance of the button that opens the elevator door is now fully configured. To exit design
mode, in the Property Inspector, on the Design Tab, click Edit.

You can use a callback function to display in the MATLAB Command Window that the elevator door is
opening when you click or press the button and the button lights up.

Let status_a be the variable that the callback function uses to track whether or not the elevator
button is lit:

• When the button is lit, the value is 1.


• When the button is not lit, the value is 0.

Set up a preload callback function that automatically initializes status_a to a value of 0 when you
open the model:
1 Right-click the Simulink canvas and select Model Properties.
2 On the Callbacks tab, in the PreLoadFcn section, enter this command and click OK:
status_a=0;

Run the preload callback function: save and reopen the model.

Write the callback function to display that the elevator door is opening when the button is clicked:
1 In the Property Inspector, on the Parameters tab, in the Callbacks section, from the list, select
ClickFcn.
2 In the Callbacks section, enter these commands:

if(status_a<1)
status_a=1;
disp('Alarm!');
else
status_a=0;
end

Alarm!

The elevator alarm button is now fully configured.

Add the alarm button to the elevator button panel:


1 Select the panel.
2 To enter panel edit mode, click the ellipsis that appears above the panel and select Edit Panel.
3 Click and drag the alarm button onto the panel.
4 Position the alarm button beneath the other buttons.
5 If needed, resize the buttons to fit them on the panel. To resize a button, select the block
modeling that button, then click and drag one of its corners.

32-138
Design Custom Buttons

6 To exit panel edit mode, in the action menu above the panel, select Done Editing.

To use the alarm button:


1 Simulate the model.
2 During simulation, click the alarm button. When the button lights up, the MATLAB Command
Window displays the message Alarm!.

See Also
Callback Button | Push Button

32-139
32 Control Simulations with Interactive Displays

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-140
Design Custom Rotary Switches

Design Custom Rotary Switches

An engine order telegraph (EOT) is a device used on ships to communicate the commanded speed and
direction of travel from the bridge to the engine room. Personnel on the bridge use the EOT to control
the velocity of the ship from outside the engine room.

This example shows how to use the customizable Rotary Switch block to design two EOTs that look
like controls in real systems:

• A traditional EOT
• A modern EOT

Each switch consists of a stationary component and a movable component. The stationary component
is the mounting, and the movable component is the handle that you turn to set the value of the
parameter that the switch controls.

The blocks in the model use PNG images to define the shapes of these components. You can find all
images used to create the switches in the example directory.

Each switch has multiple states. A state pairs a State Value with a customizable State Label, a handle
orientation, and a click area.

You can activate a state by clicking its click area or by dragging the handle and releasing it over the
click area. When you activate the state, the State Value is assigned to the Simulink® block diagram
element to which the switch block is connected.

You can specify the arc angle the handle traverses when it moves from the first state to the last state.
The state labels are evenly spaced over the arc length. The edges of the click areas bisect the angular
distance between labels.

32-141
32 Control Simulations with Interactive Displays

Design Traditional EOT

To design the traditional EOT, add a customizable Rotary Switch block to the model using the
Simulink quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Rotary Switch block, type Rotary Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Rotary Switch block, enter design mode:

1 In the model canvas, select the Rotary Switch block.


2 In the Simulink Toolstrip, click the Switch tab.
3 On the Switch tab, click Edit. A toolbar appears above the Rotary Switch block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

You can design a custom rotary switch using the toolbar or using the Design tab of the Property
Inspector. This example uses both.

32-142
Design Custom Rotary Switches

Add the background image for the traditional EOT:


1 In the toolbar, click Replace Background Image.
2 In the CustomRotarySwitchImages folder, select the eot-1-background.png file.

Resize the block to make the text on the EOT in the background image large enough to read:

32-143
32 Control Simulations with Interactive Displays

1 Make the full background image visible by deleting the handle image. On the Design tab of the
Property Inspector, click the Handle component. Then, in the Handle component, underneath
the handle image, click the X button.
2 To resize the block, exit design mode. In the Property Editor, on the Design tab, click Edit.
3 Click and drag one of the corners of the block outwards until the text on the background image is
large enough to read.

To continue modifying the design of the Rotary Switch block, enter design mode again.

Add the handle image for the traditional EOT:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomRotarySwitchImages folder, select the eot-1-handle.png file. Note that the
handle in the PNG file points to the right.

32-144
Design Custom Rotary Switches

The states of the traditional EOT Rotary Switch block have this layout:

• The background image shows nine labels spaced at 30 degree intervals. Each label corresponds to
an EOT state. The traditional EOT Rotary Switch block is split into nine corresponding state
sections, shown in yellow.
• State 1 is the FULL ahead command on the background image.
• The Arc is the arc length the rotary switch handle traverses when it moves from the first state to
the last state. For the traditional EOT Rotary Switch block, the arc length spans from the middle
of the FULL ahead section to the middle of the FULL astern section, which is an angular distance
of 240 degrees.
• The Start Angle is the angular location of the end of the arc length that is in State 1, measured
clockwise from the positive horizontal axis pointing right. For the traditional EOT Rotary Switch
block, the Start Angle is the angular location of the middle of the FULL ahead section relative to
the positive horizontal axis, which is 150 degrees.
• Since the background image already has the labels for each section marked, the Rotary Switch
block state labels are hidden.

32-145
32 Control Simulations with Interactive Displays

Implement the state layout:

1 In the Property Inspector, on the Design tab, select the Rotary Switch component.
2 In the Range section, set Arc to 240 degrees.
3 In the Range section, set Start Angle to 150 degrees.
4 To hide the Rotary Switch blocks state labels, make the label radius large enough to move the
labels out of view. In the Range section, set Label Radius to 1.

32-146
Design Custom Rotary Switches

The Rotary Switch block for the traditional EOT has nine states:

• In State 1, the bridge orders the engine to travel ahead at the full engine speed. The Rotary
Switch block has a State Value of 100 and the State Label Full Speed, Ahead.
• In State 2, the bridge orders the engine to travel ahead at 50 percent of the full engine speed. The
Rotary Switch block has a State Value of 50 and the State Label Half Speed, Ahead.
• In State 3, the bridge orders the engine to travel ahead at 25 percent of the full engine speed. The
Rotary Switch block has a State Value of 25 and the State Label Slow Speed, Ahead.
• In State 4, the bridge orders the engine to stand by. The Rotary Switch block has a State Value of
1 and the State Label Stand By.
• In State 5, the bridge orders the engine to stop, and the engine speed is 0. The Rotary Switch
block has a State Value of 0 and the State Label Stop.
• In State 6, the bridge is finished with the main engine. The Rotary Switch block has a State Value
of -1 and the State Label Finished with Engine.
• In State 7, the bridge orders the engine to travel astern at 25 percent of the full engine speed. The
Rotary Switch block has a State Value of -25 and the State Label Slow Speed, Astern.
• In State 8, the bridge orders the engine to travel astern at 50 percent of the full engine speed. The
Rotary Switch block has a State Value of -50 and the State Label Half Speed, Astern.
• In State 9, the bridge orders the engine to travel astern at the full engine speed. The Rotary
Switch block has a State Value of -100 and the State Label Full Speed, Astern.

In the Property Inspector, on the Design tab, for each state:

1 In the States component, in the Select State section, expand the drop-down list. If the state
number is listed, select the corresponding state. If not, click the plus button to add a new state.
2 In the Value section, enter the State Value.

32-147
32 Control Simulations with Interactive Displays

3 To make the state identifiable in the Select State section drop-down list, in the Label section,
enter the State Label in the Text field. When you click out of the Text field, the label appears
in the Select State section drop-down list.

Note that the handle orientation for a given state not be correct until all nine states have been added
because the Rotary Switch block does not recognize the labels on the background image. The Rotary
Switch block spaces state labels at equal angular intervals, so the angular locations to which the
handle snaps depend on the number of states. When there are nine states, the angular locations of
the Rotary Switch block state labels coincide with the angular locations of the labels on the
background image, and the handle takes on the correct orientation for all states.

When you finish adjusting the design for the traditional EOT, to exit design mode, in the Property
Inspector, on the Design tab, click Edit.

You can use the finished EOT to control a parameter. In the model, a Constant block represents the
EOT signal that is sent to the engine room. The Rotary Switch block controls the value of the
constant.

Connect the Rotary Switch block to the Value parameter of the Constant block:

1 Select the Rotary Switch block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const1.
4 In the table that appears below the selected signal, select the Const1:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the traditional EOT:

32-148
Design Custom Rotary Switches

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 During simulation, click and drag the handle. To change the State Value of the Rotary Switch
block, release the handle over any of the labels on the background image.
3 See the effect on the EOT signal in the Dashboard Scope block.

Design Modern EOT

To design the modern EOT, add a customizable Rotary Switch block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:
1 In the model canvas, select the Rotary Switch block.
2 In the Simulink Toolstrip, click the Switch tab.
3 On the Switch tab, click Edit. A toolbar appears above the Rotary Switch block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the modern EOT:


1 In the toolbar, click Replace Background Image.
2 In the CustomRotarySwitchImages folder, select the eot-2-background.png file.

Resize the block to make the text on the EOT in the background image large enough to read:
1 Make the full background image visible by deleting the handle image. On the Design tab of the
Property Inspector, click the Handle component. Then, in the Handle component, underneath
the handle image, click the X button.

32-149
32 Control Simulations with Interactive Displays

2 To resize the block, exit design mode. In the Property Editor, on the Design tab, click Edit.
3 Click and drag one of the corners of the block outwards until the text on the background image is
large enough to read.

To continue modifying the design of the Rotary Switch block, enter design mode again.

Add the handle image for the modern EOT:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomRotarySwitchImages folder, select the eot-2-handle.png file. Note that the
handle in the PNG file points to the right.
4 In the Size section, set the Width and Height to 1.

32-150
Design Custom Rotary Switches

The states of the modern EOT Rotary Switch block have this layout:

• The background image shows eleven labels spaced at 30 degree intervals. Each label corresponds
to an EOT state. The modern EOT Rotary Switch block is split into eleven corresponding state
sections, shown in yellow.
• State 1 is the FULL astern command on the background image.
• The Arc is the arc length the rotary switch handle traverses when it moves from the first state to
the last state. For the modern EOT Rotary Switch block, the arc length spans from the middle of
the FULL ahead section to the middle of the FULL astern section, which is an angular distance of
300 degrees.
• The Start Angle is the angular location of the end of the arc length that is in State 1, measured
clockwise from the positive horizontal axis pointing right. For the modern EOT Rotary Switch
block, the Start Angle is the angular location of the middle of the FULL ahead section relative to
the positive horizontal axis, which is 120 degrees.
• Since the background image already has the labels for each section marked, the Rotary Switch
block state labels are hidden.

32-151
32 Control Simulations with Interactive Displays

Arc is 300 degrees by default. Start Angle is 120 degrees by default.

To hide the Rotary Switch blocks state labels, make the label radius large enough to move the labels
out of view:

1 In the Property Inspector, on the Design tab, select the Rotary Switch component.
2 In the Range section, set Label Radius to 1.

32-152
Design Custom Rotary Switches

The Rotary Switch block for the traditional EOT has eleven states:

• In State 1, the bridge orders the engine to travel astern at the full engine speed. The Rotary
Switch block has a State Value of -100 and the State Label Full Speed, Astern.
• In State 2, the bridge orders the engine to travel astern at 50 percent of the full engine speed. The
Rotary Switch block has a State Value of -50 and the State Label Half Speed, Astern.
• In State 3, the bridge orders the engine to travel astern at 25 percent of the full engine speed. The
Rotary Switch block has a State Value of -25 and the State Label Slow Speed, Astern.
• In State 4, the bridge orders the engine to travel astern at 12.5 percent of the full engine speed.
The Rotary Switch block has a State Value of -12.5 and the State Label Dead Slow Speed,
Astern.
• In State 5, the bridge is finished with the main engine. The Rotary Switch block has a State Value
of -1 and the State Label Finished with Engine.
• In State 6, the bridge orders the engine to stop, and the engine speed is 0. The Rotary Switch
block has a State Value of 0 and the State Label Stop.
• In State 7, the bridge orders the engine to stand by. The Rotary Switch block has a State Value of
1 and the State Label Stand By.
• In State 8, the bridge orders the engine to travel ahead at 12.5 percent of the full engine speed.
The Rotary Switch block has a State Value of 12.5 and the State Label Dead Slow Speed,
Ahead.
• In State 9, the bridge orders the engine to travel ahead at 25 percent of the full engine speed. The
Rotary Switch block has a State Value of 25 and the State Label Slow Speed, Ahead.
• In State 10, the bridge orders the engine to travel ahead at 50 percent of the full engine speed.
The Rotary Switch block has a State Value of 50 and the State Label Half Speed, Ahead.
• In State 11, the bridge orders the engine to travel ahead at the full engine speed. The Rotary
Switch block has a State Value of 100 and the State Label Full Speed, Ahead.

32-153
32 Control Simulations with Interactive Displays

In the Property Inspector, on the Design tab, for each state:

1 In the States component, in the Select State section, expand the drop-down list. If the state
number is listed, select the corresponding state. If not, click the plus button to add a new state.
2 In the Value section, enter the State Value.
3 To make the state identifiable in the Select State section drop-down list, in the Label section,
enter the State Label in the Text field. When you click out of the Text field, the label appears
in the Select State section drop-down list.

Note that the handle orientation for a given state not be correct until all eleven states have been
added because the Rotary Switch block does not recognize the labels on the background image. The
Rotary Switch block spaces state labels at equal angular intervals, so the angular locations to which
the handle snaps depend on the number of states. When there are eleven states, the angular locations
of the Rotary Switch block state labels coincide with the angular locations of the labels on the
background image, and the handle takes on the correct orientation for all states.

Add the foreground image for the modern EOT:

1 On the Design tab, select the Foreground Image component.


2 In the Select Image section, click the plus button.
3 In the CustomRotarySwitchImages folder, select the eot-2-foreground.png file.

32-154
Design Custom Rotary Switches

When you finish adjusting the design for the modern EOT, to exit design mode, in the Property
Inspector, on the Design tab, click Edit.

Use the finished EOT to control a parameter. In the model, a Constant block represents the EOT
signal that is sent to the engine room, and the Rotary Switch block controls the value of the constant.

Connect the Rotary Switch block to the Value parameter of the Constant block:

1 Select the Rotary Switch block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const2.
4 In the table that appears below the selected signal, select Const2:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the modern EOT:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 During simulation, click and drag the handle. To change the State Value of the Rotary Switch
block, release the handle over any of the labels on the background image.
3 See the effect on the EOT signal in the Dashboard Scope block.

See Also
Rotary Switch

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-155
32 Control Simulations with Interactive Displays

Design Custom Sliders

This example shows how to use the Horizontal Slider block and the Vertical Slider block to design
three sliders that look like controls in real systems:

• A light dimmer switch


• A medical syringe
• A mixing desk slider

Each slider consists of a stationary component and a movable component. The stationary component
is the mounting. The movable component is the handle that you turn to set the value of the parameter
that the slider controls.

32-156
Design Custom Sliders

The blocks in the model use PNG images to define the shapes of these components. You can find all
images used to create the sliders in the example directory.

Design Light Dimmer Switch

To design the light dimmer switch, add a Vertical Slider block to the model using the quick insert
menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the customizable Vertical Slider block, type Vertical Slider.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To modify the design of the Vertical Slider block, enter design mode:

1 In the model canvas, select the Vertical Slider block.


2 In the Simulink® Toolstrip, click the Slider tab.
3 On the Slider tab, click Edit. A toolbar appears above the Vertical Slider block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab. In design mode, the
Design tab of the Property Inspector is active.

You can design a custom slider using the toolbar or using the Design tab of the Property Inspector.
This example uses both.

Add the background image for the light dimmer switch:

32-157
32 Control Simulations with Interactive Displays

1 In the toolbar, click Replace Background Image.


2 In the CustomSliderImages folder, select the light-switch-background.png file.

To make the scale easier to see, in the toolbar, click Set Color. Change the scale color to blue.

32-158
Design Custom Sliders

In the canvas, adjust the scale such that the span line exactly covers the slot in the light switch
mounting shown on the background image:

• To move the scale, click and move the bounding box of the scale.
• To resize the scale, click and drag the corners of the bounding box of the scale.

32-159
32 Control Simulations with Interactive Displays

Add the handle image for the light dimmer switch:

1 In the Property Inspector, on the Design tab, select the Handle component.
2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the light-switch-handle.png file.
4 In the Size section, set the Width and Height to 1.

32-160
Design Custom Sliders

In the canvas, move the handle to the off position on the light switch mounting shown in the
background image. The center of the handle image should be at the bottom of the slot in the light
switch mounting.

32-161
32 Control Simulations with Interactive Displays

Hide the scale ticks, span line, and labels:

1 In the Property Inspector, on the Design tab, select the Scale component.
2 In the Ticks section, turn off Show Ticks and Show Span Line.
3 In the Labels section, turn off Show Labels.

32-162
Design Custom Sliders

Hide the value bar:

1 On the Design tab, select the Value Bar component.


2 In the Value Bar section, set the Opacity to 0.

When you finish adjusting the design for the light dimmer switch, to exit design mode, in the Property
Inspector, on the Design tab, click Edit.

You can use the finished light dimmer switch to control a parameter. In the model, a Constant block
represents the light intensity, and the Vertical Slider block controls the value of the constant.

32-163
32 Control Simulations with Interactive Displays

Connect the Vertical Slider block to the Value parameter of the Constant block:

1 Select the Vertical Slider block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const1.
4 In the table that appears below the selected signal, select the Const1:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the light dimmer switch:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Vertical Slider block handle to change the value of the Constant block during
simulation.
3 See the effect on the light intensity in the Dashboard Scope block.

Design Medical Syringe

The medical syringe is made with a Horizontal Slider block that has three components:

• A background image that is blank and serves only to properly scale the other images
• A handle image that shows the handle of the syringe attached to a column of liquid
• A foreground image that shows the casing of the syringe with tick marks to indicate the level of
liquid inside

32-164
Design Custom Sliders

The visual effect that the liquid column vanishes when it passes the tip of the syringe needle is
achieved with the opacity of the foreground image.

• To show the liquid inside of the syringe, the glass cylinder is transparent in the foreground image.
• To hide the part of the handle image liquid column that has moved past the needle tip, the area
around the needle tip is opaque in the foreground image.

To design the medical syringe, add a Horizontal Slider block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:
1 In the model canvas, select the Horizontal Slider block.
2 In the Simulink Toolstrip, click the Slider tab.
3 On the Slider tab, click Edit. A toolbar appears above the Horizontal Slider block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

32-165
32 Control Simulations with Interactive Displays

Adding a handle image to a customizable dashboard block changes the aspect ratio of the handle
image to match the aspect ratio of the block.

Adding a background image to a customizable dashboard block changes the aspect ratio of the block
to match the aspect ratio of the background image.

To prevent the handle image from being distorted, before you add the handle image, you can use a
background image to set the aspect ratio of the block to be the same as the aspect ratio of the handle
image.

You can prevent the foreground image from being distorted in the same way.

Since the handle and foreground images of the syringe have the same aspect ratio, a background
image with that aspect ratio can be used to prevent both from being distorted.

Add the transparent background image for the syringe:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the medical-syringe-background.png file.

Add the foreground image for the syringe:

1 On the Design tab, select the Foreground component.


2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the medical-syringe-foreground.png file.

To exit design mode, on the Design tab, click Edit.

32-166
Design Custom Sliders

Resize the block in the canvas by dragging one of its corners outwards until the tick marks on the
syringe shown in the foreground image are clearly visible.

To continue modifying the design of the Horizontal Slider block, enter design mode. In the Property
Inspector, on the Design tab, click Edit.

Make the scale easier to see:

1 On the Design tab, select the Scale component.


2 In the Ticks section, change the Color to blue.

At this point, you cannot adjust the size or position the scale in the canvas because the foreground
image is on top of the scale.

To make the scale of the Horizontal Slider block match the scale on the foreground image, the
handles of the bounding box of the scale need to be outside of the foreground image so that you can
adjust the scale with the foreground image visible.

Hide the foreground image:

On the Design tab, click the eye icon of the Foreground Image component. The eye icon now has a
slash through it, indicating that the foreground image is hidden.

Resize the scale such that you can still grab the handles of the bounding box of the scale when the
foreground is visible again:

32-167
32 Control Simulations with Interactive Displays

1 On the Design tab, click the Scale component.


2 In the canvas, click and drag the corners of the bounding box of the scale such that the top and
bottom edges of the bounding box are outside of the white box that is the background image.

To make the foreground image visible again, on the Design tab, click the eye icon of the Foreground
Image component.

In the canvas, click and drag the corners of the bounding box of the scale such that the left edge of
the scale lines up with the leftmost tick mark on the syringe in the foreground image and the right
edge lines up with the rightmost tick mark.

In the canvas, click and drag the corners of the bounding box of the scale such that the top and
bottom edges of the bounding box line up with the top and bottom edges of the white box that is the
background image.

32-168
Design Custom Sliders

Add the handle image for the syringe:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the medical-syringe-handle.png file.
4 In the Size section, set the Width and Height to 1.

In the canvas, click and drag the edges of the bounding box of the handle image to line up the right
edge of the O-rings with the left edge of the scale. Then, line up the top and bottom edges of the
handle and foreground images.

Hide the scale ticks, span line, and labels:

32-169
32 Control Simulations with Interactive Displays

1 In the Property Inspector, on the Design Tab, select the Scale component.
2 In the Ticks section, turn off Show Ticks and Show Span Line.
3 In the Labels section, turn off Show Labels.

Hide the value bar:

1 In the Property Inspector, on the Design Tab, select the Value Bar component.
2 In the Value Bar section, set the Opacity to 0.

When you finish adjusting the design for the syringe, to exit design mode, in the Property Inspector,
on the Design tab, click Edit.

You can use the finished syringe to control a parameter. In the model, a Constant block represents the
volume of liquid dispensed, and the Horizontal Slider block controls the value of the constant.

Connect the Horizontal Slider block to the Value parameter of the Constant block:

1 Select the Vertical Slider block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const2.
4 In the table that appears below the selected signal, select Const2:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the syringe:

32-170
Design Custom Sliders

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Horizontal Slider block handle to change the value of the Constant block
during simulation.
3 See the effect on the volume of liquid dispensed in the Dashboard Scope block.

Design Mixing Desk Slider

To design the mixing desk slider, add a Vertical Slider block to the model.

If the Property Inspector is not open to the Design tab with the Edit button pressed:

1 In the model canvas, select the Vertical Slider block.


2 In the Simulink Toolstrip, click the Slider tab.
3 On the Slider tab, click Edit. A toolbar appears above the Vertical Slider block.
4 To open the Property Inspector, in the toolbar, click Open Design Tab.

Add the background image for the mixing desk slider:

1 In the Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the mixing-desk-slider-background.png file.

32-171
32 Control Simulations with Interactive Displays

To exit design mode, on the Design tab, click Edit.

Resize the block in the canvas by dragging one of its corners outwards until the text on the
background image is large enough to read.

To continue modifying the design of the Horizontal Slider block, enter design mode. In the Property
Inspector, on the Design tab, click Edit.

32-172
Design Custom Sliders

To adjust the scale, you need to be able to see all of the tick marks on the background image. To hide
the handle, on the Design tab, click the eye icon of the Handle component. The eye icon now has a
slash through it, indicating that the handle is hidden.

Make the scale easier to see:

1 On the Design tab, select the Scale component.


2 In the Ticks section, change the Color to black.
3 In the Label section, change the Color to black.

32-173
32 Control Simulations with Interactive Displays

On the Design tab, in the Handle component, in the Range section, set the Minimum to -60 and
the Maximum to 10.

In the canvas, click and drag the corners of the bounding box of the scale such that:

• The top tick mark of the scale lines up with the top tick mark in the background image.
• The bottom tick mark of the scale lines up with the bottom tick mark in the background image.
• The left edge of the scale bounding box lines up with the centerline of the slot shown in the
background image.
• The right edge of the bounding box lines up with the right edge of the mixing desk surface shown
in the background image.

32-174
Design Custom Sliders

To make the scale easier to read, adjust the height of the tick marks and the offset between the scale
labels and the tick marks:

1 On the Design tab of the Property Inspector, select the Scale component.
2 To make the tick marks easier to see, in the Ticks section, set the Minor Tick Height to 1.
3 To increase the label offset to make the negative signs in front of scale labels distinguishable
from the scale tick marks, in the Labels section, set the Label Offset to 0.15.

32-175
32 Control Simulations with Interactive Displays

To make the handle visible again, on the Design tab, click the eye icon of the Handle component.

Add the handle image for the mixing desk slider:

1 On the Design tab, select the Handle component.


2 In the Select Image section, click the plus button.
3 In the CustomSliderImages folder, select the mixing-desk-slider-handle.png file.
4 The handle image is too large to fit on the scale without covering the labels. To make the handle
fit, in the Size section, set the Width to 0.245 and Height to 0.088.

Click and drag the edges of the bounding box to position the handle such that:

32-176
Design Custom Sliders

• The white line shown on the handle image lines up with the -70 tick mark on the scale.
• The center point of the handle image is on the slot shown in the background image.

Hide the value bar:


1 In the Property Inspector, on the Design Tab, select the Value Bar component.
2 In the Value Bar section, set the Opacity to 0.

When you finish adjusting the design for the fader, to exit design mode, in the Property Inspector, on
the Design tab, click Edit.

You can use the finished fader to control a parameter. In the model, a Constant block represents the
volume of a channel, and the Vertical Slider block controls the value of the constant.

32-177
32 Control Simulations with Interactive Displays

Connect the Vertical Slider block to the Value parameter of the Constant block:

1 Select the Vertical Slider block.


2 Click the Connect button that appears above the block.
3 Select the Constant block named Const3.
4 In the table that appears below the selected signal, select Const3:Value.
5 Click the X in the upper right corner of the Simulink window.

To use the fader:

1 Simulate the model. This model uses simulation pacing to slow model execution so you can
interact with the model during simulation. For more information about simulation pacing, see
Simulation Pacing Options.
2 Click and drag the Vertical Slider block handle to change the value of the Constant block during
simulation.

32-178
Design Custom Sliders

3 See the effect on the channel volume in the Dashboard Scope block.

See Also
Blocks
Horizontal Slider | Vertical Slider

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Getting Started with Panels” on page 32-19

32-179
32 Control Simulations with Interactive Displays

Connect Interactive Controls and Displays

The model ConnectDashboardBlocks contains a Sine Wave block and three Constant blocks. The
model also contains eight dashboard blocks that are not connected to the model yet. This example
shows how to quickly connect multiple dashboard blocks using connect mode, how to connect and
tune an interactive control and display using the Block Parameters dialog box, and how to disconnect
dashboard blocks from your model.

Connect One or More Dashboard Blocks Using Connect Mode

You can use dashboard blocks to tune and visualize your model during simulation.

• To tune the value of a variable or block parameter during simulation, you can connect a control
from the Dashboard library or Customizable Dashboard library.
• To view signal values during simulation, you can connect a display from the Dashboard library or
Customizable Dashboard library.

To quickly connect one or more dashboard blocks, enter connect mode.

For example, connect the three Slider blocks to the three Constant blocks, and connect the three
Linear Gauge blocks to the constant signals. To enter connect mode and connect the Slider blocks to
the corresponding Constant blocks:

1 Select or pause on a Slider block. For example, select the Slider block named Slider1.
2
Click the Connect button above the block.
3 Select the corresponding Constant block. For example, select the Constant block named
Constant1.
4 In the table of tunable parameters, select the parameter to tune. For example, select
Constant1:Value.

While in connect mode, you can connect the display blocks to signals in a similar way.

1 Select or pause on a Linear Gauge block. For example, select the Linear Gauge block named
Linear Gauge1.
2
Click the Connect button above the block.
3 Select the corresponding signal. For example, select the signal named const1.
4 In the table, select the signal to display. For example, select const1.

When you are done connecting dashboard blocks to your model, to exit connect mode, click the Done

Connecting button above the last dashboard block you connected.

32-180
Connect Interactive Controls and Displays

Connect and Tune Interactive Control

When you want to tune and connect a control dashboard block at the same time, you can use the
Block Parameters dialog box.

For example, suppose you want to use the Knob block to interactively change the amplitude of the
Sine Wave block to a value between 0 and 10. Connect the Knob block to the Amplitude parameter
of the Sine Wave block, and limit the values on the Knob block to your desired range.

1 To open the Block Parameters dialog box, double-click the Knob block. From the Block
Parameters dialog box, you can connect tunable parameters and specify the scale of the block.
2 Select the Sine Wave block.
3 In the table of available parameters to connect to, select Sine Wave:Amplitude.
4 To limit the scale of the Knob block, set Maximum to 10.

32-181
32 Control Simulations with Interactive Displays

Connect and Tune Interactive Display to View Signal Values During Simulation

Similarly, you can also tune and connect a display dashboard block using the Block Parameters dialog
box.

For example, connect the Gauge block to the sineSig signal to view the values of the sine wave
during simulation. Since the possible values of the sine wave are between -10 and 10, you can scale
the Gauge block to correspond to the data.

1 To open the Block Parameters dialog box, double-click the Gauge block.
2 Select the sineSig signal.
3 In the table of available signals to connect to, select sineSig.
4 To scale the Gauge block, set Minimum to -10 and Maximum to 10.

32-182
Connect Interactive Controls and Displays

32-183
32 Control Simulations with Interactive Displays

Disconnect Dashboard Blocks

You can also disconnect dashboard blocks. For example, disconnect the Knob block from the Sine
Wave block.

1 Select the Knob block.


2 On the Knob tab, click Change Connection.
3 Select Disconnect.

See Also
Blocks
Knob | Gauge | Slider | Linear Gauge

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Connect Dashboard Blocks to Simulink Model” on page 32-7

32-184
Connect Dashboard Blocks to Matrices and Structures

Connect Dashboard Blocks to Matrices and Structures

This example shows how to connect a control block from the Dashboard library or the Customizable
blocks library to:

• An element of a matrix
• The field of a structure with a scalar value
• An element of a matrix that is stored in a structure

While you can pass structures from one block to another using buses, and you can connect a control
block to a field in a structure, connecting display blocks to buses is not supported.

Connect Control Block to Element of Matrix

In this example, you connect a Rocker Switch block from the Customizable blocks library to the
element in the second column of the row vector [1 2 3].

Open the model ConnectToMatrixElem.slx.

open('ConnectToMatrixElem')

The model contains a Constant block that connects to a Display block. The value of the Constant
block is the row vector [1 2 3]. The Display block shows the values of the row vector elements
during simulation.

Add a Rocker Switch block to the model using the Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Rocker Switch block, type Rocker Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:

1 Pause on the Rocker Switch block.


2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select Constant:Value.
5 To specify which element to connect to, in the text box, enter 2. Since the value of the Constant
block is a row vector, you can specify the element by entering the column number. If the value
were a column vector, you could specify the element using the row number. Alternatively, you can
specify the element using both the row and column numbers: (1,2).
6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

32-185
32 Control Simulations with Interactive Displays

Run the simulation. Click the On and Off sides of the Rocker Switch block. When you click the Off
side of the switch, the value of the element in the second column of the row vector changes to 0, and
when you click the On side, the value changes to 1.

Stop the simulation.

Double-click the Constant block. Change the value of the Constant block to [1 2 3; 4 5 6].

Connect the Rocker Switch block to the element in the second row and third column of the matrix.

1 Select the Rocker Switch block.


2 Pause on the ellipsis (...) that appears above the block.
3 In the action menu that expands, click the Connect button.
4 Click the Constant block.
5 To specify which element to connect to, in the text box, enter (2,3).
6 Press Enter.
7 Pause on the Display block.
8 Click the Done Connecting button that appears.

32-186
Connect Dashboard Blocks to Matrices and Structures

Run the simulation. Resize the display block to show the values of the two-by-three matrix. Click the
On and Off sides of the Rocker Switch block. Flipping the switch changes the value of the element in
the second row and third column of the matrix.

Connect Control Block to Field of Structure With Scalar Value

Suppose you have a structure that captures information about six gears in a transmission.

For each gear, the structure has these two fields:

• engaged specifies whether the driver has engaged the gear (0 for no, 1 for yes).
• fault specifies whether a fault is detected by the transmission system when the gear is engaged
(0 for no, 1 for yes).

In this example, you connect a Rocker Switch block from the Customizable blocks library to the field
in this structure that specifies whether the fourth gear is engaged.

Open the model ConnectToStructElem.slx.

open('ConnectToStructScalar')

The model uses a callback function to initialize the gear structure before the model loads. The top
level of the structure contains the names of the gears.

disp(gear)

first: [1x1 struct]


second: [1x1 struct]
third: [1x1 struct]
fourth: [1x1 struct]
fifth: [1x1 struct]
reverse: [1x1 struct]

The second level of the structure contains the fields engaged and fault.

disp(gear.fourth)

fault: 0
engaged: 0

The model contains a Constant block that connects to a To Virtual Bus block that connects to a
Display block. The value of the Constant block is the gear structure. The Display block shows the
values of the structure fields engaged and fault during simulation.

32-187
32 Control Simulations with Interactive Displays

Update the diagram by pressing Ctrl+D (on macOS, press command+D).

Add a Rocker Switch block to the model using the Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Rocker Switch block, type Rocker Switch.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:

1 Pause on the Rocker Switch block.


2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select gears(base workspace).
5 To specify which field to connect to, in the text box, enter fourth.engaged.
6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

Run the simulation. Click the On and Off sides of the Rocker Switch block. When you click the Off
side of the switch, the value of the field labeled Fourth gear, engaged switches to 0. When you
click the On side of the switch, the value of the field labeled Fourth gear, engaged switches to 1.

32-188
Connect Dashboard Blocks to Matrices and Structures

Connect Control Block to Element of Matrix in Structure

Suppose you have five different laboratory stations, named A through E. During an experiment, for
each station, you record the temperature you set for the station and the average of the temperature
measured at the station over the duration of the experiment. You store the data in a structure. The
structure contains a field for each laboratory station, and each field contains a row vector that stores
the set and measured temperatures.

In this example, you connect a Knob block from the Customizable blocks library to the set
temperature of station B.

Open the model ConnectToStructMatrixElem.slx.

open('ConnectToStructMatrixElem')

The model uses a callback function to initialize the T structure before the model loads. The top level
of the structure contains the names of the laboratory stations.

disp(T)

stationA: [23 23.4000]


stationB: [19.5000 20.6000]
stationC: [23 22.2000]
stationD: [23 21.5000]
stationE: [25 24.4000]

The second level of the structure contains a row vector. The first column of the row vector specifies
the set temperature of the laboratory station. The second column specifies the measured
temperature.

disp(T.stationB)

32-189
32 Control Simulations with Interactive Displays

19.5000 20.6000

The model contains a Constant block that connects to a To Virtual Bus block that connects to a
Display block. The value of the Constant block is the T structure. The Display block shows the set and
measured temperatures for each laboratory station.

Update the diagram by pressing Ctrl+D (on macOS, press command+D).

Add a Knob block to the model using the Simulink® quick insert menu:

1 To open the quick insert menu, double-click in the canvas.


2 To search for the Knob block, type Knob.
3 Select the search result with the library path Simulink/Dashboard/Customizable Blocks.

To connect the Display block:

1 Pause on the Rocker Switch block.


2 Click the Connect button that appears.
3 Click the Constant block.
4 In the table that appears, select T(base workspace).
5 You want to connect to the field corresponding to station B. The set temperature is specified in
the first column of the row vector stored in the field. In the text box, enter stationB(1,1).
6 Press Enter.
7 Pause on the Display block again.
8 Click the Done Connecting button that appears.

Run the simulation. To turn the knob, click and drag the handle, or, on the scale, click the value you
want to turn the knob to. When you turn the knob, the set temperature of station B changes.

32-190
Connect Dashboard Blocks to Matrices and Structures

See Also
Blocks
Rocker Switch | Display

Related Examples
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2
• “Connect Dashboard Blocks to Simulink Model” on page 32-7

32-191
33

Analyzing Simulation Results

• “Decide How to Visualize Simulation Data” on page 33-2


• “Linearizing Models” on page 33-9
33 Analyzing Simulation Results

Decide How to Visualize Simulation Data


Visualizing simulation data throughout the modeling process helps you understand and tune model
behavior. Simulink offers several complementary visualization tools you can use throughout the
modeling process. Some visualization tools also offer the ability to save simulation data. Learn about
each technique so you can choose the right tools to visualize your model data.

• Simulation Data Inspector — View, analyze, and compare logged data throughout the modeling
process.
• Scope block, Floating Scope block, and Scope Viewer — Debug and analyze data using a block-
based tool with capabilities similar to a bench-top oscilloscope.
• Record block — Visualize data logged to the workspace, a file, or both.
• Dashboard blocks — Build an interactive interface to tune and monitor a model.
• Port value labels — View instantaneous signal values in the block diagram.
• Custom MATLAB visualization — Write MATLAB code to visualize data.

Simulation Data Inspector


You can use the Simulation Data Inspector for most visualization tasks. The Simulation Data Inspector
integrates with data logging in your model and works well for visualizing many signals throughout a
model. Use comparisons in the Simulation Data Inspector to prototype, debug, tune, calibrate, and
test your models. The Simulation Data Inspector supports:

• Viewing signals during simulation


• Logging, importing, and exporting data
• Configurable subplot layouts and visualization settings
• Viewing data using multiple visualization options, including maps and XY plots
• Post-processing and data analysis using comparisons with tolerance values
• Saving plots and data to share or archive results

33-2
Decide How to Visualize Simulation Data

To visualize simulation data using the Simulation Data Inspector, log data in the model. When you log
signals and outputs, the logged data is automatically available in the Simulation Data Inspector
during and after simulation. In the model Configuration Parameters, select Data Import/Export >
Record logged workspace data in Simulation Data Inspector to make logged states and
Simscape data available in the Simulation Data Inspector after simulation. When you want to view
signals without logging the data, consider using a Scope block, the Floating Scope block, or a Scope
Viewer.

Open the Simulation Data Inspector from Simulation > Data Inspector or by clicking a signal
logging badge. When you open the Simulation Data Inspector by clicking the logging badge on a
signal, the signal is automatically plotted.

For more information, see Simulation Data Inspector.

Scope Blocks and the Scope Viewer


Scope blocks, Floating Scope blocks, and the Scope Viewer visualize connected signals in a similar
way as a bench-top oscilloscope. The scope blocks and Scope Viewer use the same interface to
visualize and analyze connected signals. The interface is similar to other domain-specific tools, such
as the Spectrum Analyzer and Array Plot blocks. Scope blocks are easy to add and connect in your
model, and you do not need to log data in order to view signal data.

33-3
33 Analyzing Simulation Results

Scope blocks, Floating Scope blocks, and the Scope Viewer support:

• Viewing signals during simulation, including rapid accelerator simulations


• Simple connection and accessibility for lightweight debugging
• Signal visualization without logging
• Optional signal logging
• Starting simulations from the visualization interface using playback controls
• Oscilloscope measurements, including cursors and triggers. Additional measurements are
available when you have a Simscape or DSP System Toolbox license
• Configurable plots and display
• Configurable triggers to capture events

33-4
Decide How to Visualize Simulation Data

Use the Scope block, the Floating Scope block, and the Scope Viewer for prototyping and lightweight
debugging. For example, in the early stages of model development, you can connect a Scope block to
a signal to quickly verify component behavior. By adding triggers, you can tune a specific peak or
other artifact in a signal. A Scope block may or may not be permanent in your model.

When you need to view data for signals throughout a model hierarchy, consider using the Simulation
Data Inspector, especially if you already log the signals you want to view.

For more information, see “Scope Blocks and Scope Viewer Overview” on page 30-6.

Record Block
You can use the Record block to view connected signal data that you record to the workspace, a file,
or both the workspace and a file.

The Record block supports:

• Viewing signals logged using the Record block during simulation


• Logging data to the workspace, a file, and the Simulation Data Inspector
• Streaming data to the Simulation Data Inspector during simulation
• Viewing data using multiple visualization options, including maps and XY plots
• Starting simulations while viewing data in the Record block using simulation controls, such as the
Run button

Connect signals to the Record block to log data to the workspace or a file. To view simulation data
logged using the Record block, double-click the block. You can modify the plot layout and view data

33-5
33 Analyzing Simulation Results

using several visualizations, including sparklines plots, time plots, and XY plots. Data logged to the
Record block is automatically streamed to the Simulation Data Inspector during simulation. When you
want to view signals without logging the data, consider using a Scope block, the Floating Scope
block, or a Scope Viewer.

For more information, see “Log Data to the Workspace and a File Using the Record Block” on page
78-83.

Dashboard Blocks
The Dashboard library includes control blocks you can use to tune variables and parameters in your
model and visualization blocks you can use to view signal data. Use dashboard blocks to view
instantaneous signal data and build an interactive interface for your model.

You can use dashboard block controls to modify the values of variables and tunable parameters in
your model during simulation. Visualization dashboard blocks are updated continuously throughout
simulation. When you need to debug a model that uses dashboard blocks, consider using simulation
pacing or simulation stepping to slow the simulation so you can view the instantaneous signal values.
You can also promote dashboard blocks to one or more panels so the interactive dashboard can follow
you throughout a model hierarchy as you design and debug your model. For more information, see:

• Simulation Pacing Options


• “Step Through Simulation” on page 2-2
• “Getting Started with Panels” on page 32-19

33-6
Decide How to Visualize Simulation Data

The Dashboard Scope block provides a simple view of a signal over time. You can zoom, pan, and add
cursors to a Dashboard Scope block through the context menu. For more debugging and analysis
capabilities, use a Scope block or log data to the Simulation Data Inspector.

For more information about using Dashboard blocks, see “Tune and Visualize Your Model with
Dashboard Blocks” on page 32-2.

Port Value Labels


To view signal values in the block diagram during simulation, use port value labels. Port value labels
can supplement existing visualizations, especially while prototyping and debugging models. For
example, you can view signal values on port value labels as you step through a simulation while
visualizing the temporal behavior using a Scope block. You can also use port value labels on their own
to support debugging without adding any blocks to your model or logging data.

To display a signal value, right-click the signal and select Show Port Value Label On Selected
Signal.

33-7
33 Analyzing Simulation Results

When viewing signal data using port value labels, consider using simulation pacing or stepping
through the simulation. For more information, see Simulation Pacing Options and “Step Through
Simulation” on page 2-2.

For more information, see “View Signal Values Using Port Value Labels” on page 40-8.

Custom MATLAB Visualizations


When you log simulation data to the workspace or a file, you can write MATLAB code and scripts to
create custom visualizations. You can log signals, outputs, and states in a model, and you can also
enable data logging for signals connected to Scope Viewers, Floating Scope blocks and Scope blocks.
For more information about logging data in your model, see “Save Simulation Data” on page 78-2.

Note When you post-process data using MATLAB code and scripts, you do not need to write custom
MATLAB code to visualize the data. You can import the processed data into the Simulation Data
Inspector for visualization alongside the logged data.

The visualization code you write can depend on the format of the logged data. By default, logging
uses the Dataset format and produces a single simulation output. Logged data is returned to the
workspace as a Simulink.SimulationOutput object that contains a
Simulink.SimulationData.Dataset object for each type of logging used in the simulation. Each
Dataset object contains Simulink.SimulationData.Signal objects that store the data for an
individual signal as a timeseries object. For more information, see “Data Format for Logged
Simulation Data” on page 78-12.

When you log a signal, you can visualize the signal during simulation using custom MATLAB code. For
more information, see “Access Data in MATLAB Function During Simulation” on page 31-128.

See Also
Tools
Simulation Data Inspector

Blocks
Floating Scope | Scope | Scope Viewer

Related Examples
• “Save Simulation Data” on page 78-2
• “View Simulation Data in Simulation Data Inspector” on page 31-2
• “Scope Blocks and Scope Viewer Overview” on page 30-6
• “Tune and Visualize Your Model with Dashboard Blocks” on page 32-2

33-8
Linearizing Models

Linearizing Models

The Simulink product provides the linmod, linmod2, and dlinmod functions to extract linear state-
space models from Simulink models. However, these functions provide only basic linearization
functionality. For full linearization functionality, use Simulink Control Design software. For more
information, see “Choose Linearization Tools” (Simulink Control Design).

The linmod, linmod2, and dlinmod functions 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

ẋ = 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.

To extract the linear model of this system, enter this command.

[A,B,C,D] = linmod('lmod')

A =
-2 -1 -1
1 0 0
0 1 -1
B =
1
0
0
C =
0 1 0
0 0 -1
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:

33-9
33 Analyzing Simulation Results

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

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.

See Also
Functions
linmod | dlinmod | linearize | slLinearizer

Apps
Model Linearizer

More About
• “Choose Linearization Tools” (Simulink Control Design)
• “Linearize Nonlinear Models” (Simulink Control Design)
• “Exact Linearization Algorithm” (Simulink Control Design)

33-10
34

Improving Simulation Performance and


Accuracy

• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2


• “Speed Up Simulation” on page 34-3
• “How Simulink Profiler Captures Performance Data” on page 34-5
• “Check and Improve Simulation Accuracy” on page 34-12
• “Modeling Techniques That Improve Performance” on page 34-14
• “Use Performance Advisor to Improve Simulation Efficiency” on page 34-19
• “Understanding Total Time and Self Time in Profiler Reports” on page 34-20
34 Improving Simulation Performance and Accuracy

How Optimization Techniques Improve Performance and


Accuracy
The design of a model and choice of configuration parameters can affect simulation performance and
accuracy. Solvers handle most model simulations accurately and efficiently with default parameter
values. However, some models yield better results when you adjust solver parameters. Information
about the behavior of a model can help you improve simulation performance, particularly when you
provide this information to the solver. Use optimization techniques to better understand the behavior
of your model and modify the model settings to improve performance and accuracy.

To optimize your model and achieve faster simulation automatically using Performance Advisor, see
“Automated Performance Optimization”.

To learn more about accelerator modes for faster simulation, see “Acceleration”.

See Also

Related Examples
• “Speed Up Simulation” on page 34-3
• “Check and Improve Simulation Accuracy” on page 34-12
• “How Simulink Profiler Captures Performance Data” on page 34-5

More About
• “Modeling Techniques That Improve Performance” on page 34-14

34-2
Speed Up Simulation

Speed Up Simulation
Several factors can slow simulation. Check your model for some of these conditions.

• The model includes an Interpreted MATLAB Function block. When a model includes an
Interpreted MATLAB Function block, the MATLAB execution engine is called at each time step,
drastically slowing down the simulation. Use the Math Function block whenever possible.
• Your model includes a MATLAB file S-function. MATLAB file S-functions also call the MATLAB
execution engine at each time step. Consider converting the S-function either 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 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).
• Your accuracy requirements are too high. 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
this error in Maximum order“Maximum order” in the online documentation.
• The time scale is too long. Reduce the time interval.
• Your model represents a stiff system, but you are using a nonstiff solver. Try using ode15s. For
more information, see “Stiffness of System” on page 34-16.
• Your 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 Loop Concepts” on page 3-39.

You can check the model blocks for the following conditions:

• 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.
• Your model contains a scope viewer that displays too many data points. Try adjusting the viewer
property settings that can affect performance. For more information, see Scope Viewer.
• You need to simulate your model iteratively. You change tunable parameters between iterations
but do not make structural changes to the model. Every iteration requires the model to compile
again, thus increasing overall simulation time. Use fast restart to perform iterative simulations. In
this workflow, the model compiles only once and iterative simulations are tied to a single compile
phase. See “How Fast Restart Improves Iterative Simulations” on page 87-2 for more
information.

See Also

Related Examples
• “How Simulink Profiler Captures Performance Data” on page 34-5
• “Check and Improve Simulation Accuracy” on page 34-12

34-3
34 Improving Simulation Performance and Accuracy

More About
• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2
• “Modeling Techniques That Improve Performance” on page 34-14
• “How Fast Restart Improves Iterative Simulations” on page 87-2

34-4
How Simulink Profiler Captures Performance Data

How Simulink Profiler Captures Performance Data

In this section...
“How Simulink Profiler Works” on page 34-5
“Start Profiler” on page 34-6
“Save Profiler Results” on page 34-10

How Simulink Profiler Works


The Simulink Profiler captures performance data while your model simulates. It identifies the parts of
your model that require the most time to simulate. Use the profiling information to decide where to
focus your model optimization efforts.

Note The Simulink Profiler does not support rapid accelerator simulation.

Simulink stores performance data in the simulation profile report. The data shows the time spent
executing each function in your model.

The basis for the Simulink Profiler is an execution model that this pseudocode summarizes.

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()
MinorZeroCrossings()
EndIntegrate
Set time t = tNew.
EndModelExecute
ModelTerminate
EndSim

According to this conceptual model, Simulink runs a model by invoking the following functions zero,
one, or many times, depending on the function and the model.

Function Purpose Level


sim Simulate the model. This top-level function System
invokes the other functions required to
simulate the model. The time spent in this
function is the total time required to simulate
the model.
ModelInitialize Set up the model for simulation. System

34-5
34 Improving Simulation Performance and Accuracy

Function Purpose Level


ModelExecute Execute the model by invoking the output, System
update, integrate, etc., functions for each
block at each time step from the start to the
end of simulation.
Output Compute the outputs of a block at the current Block
time step.
Update Update the state of a block at the current Block
time step.
Integrate Compute the continuous states of a block by Block
integrating the state derivatives at the
current time step.
MinorOutput Compute block output at a minor time step. Block
MinorDeriv Compute the state derivatives of a block at a Block
minor time step.
MinorZeroCrossings Compute zero-crossing values of a block at a Block
minor time step.
ModelTerminate Free memory and perform any other end-of- System
simulation cleanup.
Nonvirtual Subsystem Compute the output of a nonvirtual Block
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.

The Simulink Profiler measures the time required to execute each invocation of these functions. After
the model simulates, the Simulink Profiler generates a report that describes the amount of simulation
time spent on each function.

Start Profiler
1 Open the model.
2 In the Simulink Editor, on the Debug tab, click the Performance button arrow and select
Simulink Profiler.

34-6
How Simulink Profiler Captures Performance Data

3 Run a profiling simulation. On the Profile tab that opens, click Profile.

When simulation is complete, the Simulink Profiler generates and displays the simulation profile for
the model in a panel in the Simulink Editor.

34-7
34 Improving Simulation Performance and Accuracy

Block Hierarchy View

The block hierarchy view of the report presents the profiling information of the model in a nested tree
form. The first row of the table—which is the top of the tree—corresponds to the entire model.
Subsequent rows at the first level of nesting correspond to blocks at the root level of the model.

34-8
How Simulink Profiler Captures Performance Data

Execution Stack view

The execution stack view breaks down the profiling report by simulation phase of the model. The
main simulation phases of a model are compilation, initialization, simulation, and termination. For a
more detailed explanation of simulation phases, see “Simulation Phases in Dynamic Systems” on page
3-2.

34-9
34 Improving Simulation Performance and Accuracy

Save Profiler Results


You can save the Profiler report to a mat file. At a later time, you can import and review the report by
either loading the saved mat file to the current workspace or import it into an existing profiler
session.

To save a profiling report, select Export to MAT in the Share section of the Profile tab and
optionally specify a name for the mat file.

To view a saved report in an open profiling session in the Simulink editor, select Import from File in
the Profile tab.

To view a saved report in the command line, load the MAT-file that contains the report. The profiling
information is loaded into the current workspace as a Simulink.profiler.Data object.

See Also

Related Examples
• “Speed Up Simulation” on page 34-3
• “Check and Improve Simulation Accuracy” on page 34-12

34-10
How Simulink Profiler Captures Performance Data

• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2


• “Modeling Techniques That Improve Performance” on page 34-14

34-11
34 Improving Simulation Performance and Accuracy

Check and Improve Simulation Accuracy

Check Simulation Accuracy


1 Simulate the model over a reasonable time span.
2 Reduce either the relative tolerance to 1e-4 (the default is 1e-3) or the absolute tolerance.
3 Simulate the model again.
4 Compare the results from both simulations.

If the results are not significantly different, the solution has converged.

If the simulation misses significant behavior at the start, reduce the initial step size to ensure that the
simulation does not step over that behavior.

Unstable Simulation Results


When simulation results become unstable over time,

• The system can be unstable.


• If you are using the ode15s solver, try restricting the maximum order to 2 (the maximum order
for which the solver is A-stable). You can also try using the ode23s solver.

Inaccurate Simulation Results


If simulation results are not 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 in the Solver pane of model configuration parameters or adjust it for individual
states in the function block parameters of the Integrator block.
• If reducing the absolute tolerances does not improve simulation accuracy enough, reduce the size
of the relative tolerance parameter. This change reduces the acceptable error and forces smaller
step sizes and more steps.

Certain modeling constructs can also produce unexpected or inaccurate simulation results.

• A Source block that inherits 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 7-37).
• A Derivative block found in an algebraic loop can result in a loss in solver accuracy.

See Also

Related Examples
• “Speed Up Simulation” on page 34-3
• “How Simulink Profiler Captures Performance Data” on page 34-5

34-12
Check and Improve Simulation Accuracy

More About
• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2
• “Modeling Techniques That Improve Performance” on page 34-14

34-13
34 Improving Simulation Performance and Accuracy

Modeling Techniques That Improve Performance


In this section...
“Accelerate the Initialization Phase” on page 34-14
“Reduce Model Interactivity” on page 34-14
“Reduce Model Complexity” on page 34-15
“Choose and Configure a Solver” on page 34-16
“Save the Model Operating Point” on page 34-17

Accelerate the Initialization Phase


Speed up a simulation by accelerating the initialization phase, using these techniques.

Simplify Graphics Using Mask Editor

Complex graphics and large images take a long time to load and render. Masked blocks that contain
such images can make your model less responsive. Where possible, remove complex drawings and
images from masked blocks.

If you want to keep the image, replace it with a smaller, low-resolution version. Use mask editor and
edit the icon drawing commands to keep the image that is loaded by the call to image().

For more information on mask editor, see “Mask Editor Overview”.

Consolidate Function Calls

When you open or update a model, Simulink runs the mask initialization code. If your model contains
complicated mask initialization commands that contain many calls to set_param, consolidate
consecutive calls into a single call with multiple argument pairs. Consolidating the calls can reduce
the overhead associated with these function calls.

To learn more, see “Mask Callback Code” on page 43-12.

Load Data Using MAT file

If you use MATLAB scripts to load and initialize data, you can improve performance by loading MAT
files instead. The data in a MAT file is in binary and can be more difficult to work with than a script.
However, the load operation typically initializes data more quickly than the equivalent MATLAB
script.

For more information, see “MAT-Files for Signal Data” on page 76-4.

Reduce Model Interactivity


In general, the more interactive a model is, the longer it takes to simulate. Use these techniques to
reduce the interactivity of your model.

Disable Diagnostics

Some diagnostic features can slow simulations considerably. Consider disabling diagnostic behavior
parameters in the Diagnostics pane of the Configuration Parameters dialog box.

34-14
Modeling Techniques That Improve Performance

Note Using the Array bounds exceeded and Solver data inconsistency diagnostic parameters
can slow down simulation. For more information, see Array bounds exceeded and Solver data
inconsistency.

Disable MATLAB Debugging

After verifying that MATLAB code, such as the code for a MATLAB Function block, works correctly,
disable these diagnostic parameters in the Configuration Parameters dialog box:

• In the Diagnostics > Data Validity pane, clear Wrap on overflow.


• In the Simulation Target pane, under Advanced Parameters, clear Echo expressions without
semicolons.

Use BLAS Library Support

If your simulation involves low-level MATLAB matrix operations, use the Basic Linear Algebra
Subprograms (BLAS) libraries to make use of highly optimized external linear algebra routines.

Disable Stateflow Animations

By default, Stateflow charts highlight the current active states in a model and animate the state
transitions that take place as the model simulates. This feature is useful for debugging, but it slows
the simulation.

To accelerate simulations, either close all Stateflow charts or disable the animation. Similarly,
consider disabling animation or reducing scene fidelity when you use:

• Simulink 3D Animation
• Simscape Multibody visualization
• FlightGear
• Any other 3D animation package

To learn more, see “Speed Up Simulation” (Stateflow).

Adjust Scope Viewer Properties

If your model contains a scope viewer that displays a high rate of logging and you cannot remove the
scope, adjust the viewer properties to trade off fidelity for rendering speed.

However, when you use decimation to reduce the number of plotted data points, you can miss short
transients and other phenomena that you can see with more data points. To have more precise
control over enabling visualizations, place viewers in enabled subsystems.

For more information, see Scope Viewer.

Reduce Model Complexity


Use these techniques to improve simulation performance by simplifying a model without sacrificing
fidelity.

Replace Subsystems with Lower-Fidelity Alternatives

Replace a complex subsystem with one of these alternatives:

34-15
34 Improving Simulation Performance and Accuracy

• A linear or nonlinear dynamic model that was created from measured input-output data using the
System Identification Toolbox™.
• A high-fidelity, nonlinear statistical model that was created using the Model-Based Calibration
Toolbox™.
• A linear model that was created using Simulink Control Design.
• A lookup table. For more information, see A lookup table.

You can maintain both representations of the subsystem in a library and use variant subsystems to
manage them. Depending on the model, you can make this replacement without affecting the overall
result. For more information, see “Optimize Generated Code for Lookup Table Blocks” on page 42-
59.

Reduce Number of Blocks

When you reduce the number of blocks in your model, fewer blocks require computations during
simulation, making simulations faster. Vectorization is one way to reduce the number of blocks in a
model. For example, if your model contains several signals that undergo a similar set of
computations, try to combine them into a vector using a Vector Concatenate block. The simulation
performs a single computation for the vector instead of performing a separate computation for each
element in the vector.

Use Frame-Based Processing

In frame-based processing, Simulink processes samples in batches instead of one at a time. If a model
includes an analog-to-digital converter, for example, you can collect output samples in a buffer.
Process the buffer in a single operation, such as a fast Fourier transform. Processing data in chunks
this way reduces the number of times that the simulation needs to invoke blocks in your model.

In general, the scheduling overhead decreases as frame size increases. However, larger frames
consume more memory, and memory limitations can adversely affect the performance of complex
models. Experiment with different frame sizes to find one that maximizes the performance benefit of
frame-based processing without causing memory issues.

Choose and Configure a Solver


Simulink provides a comprehensive library of solvers, including fixed-step and variable-step solvers,
to handle stiff and nonstiff systems. Each solver determines the time of the next simulation step. A
solver applies a numerical method to solve ordinary differential equations that represent the model.

The solver you choose and the solver options you select can affect simulation speed. Select and
configure a solver that helps boost the performance of your model using these criteria. For more
information, see “Choose a Solver” on page 27-8.

Stiffness of System

A stiff system has continuous dynamics that vary slowly and quickly. Implicit solvers are particularly
useful for stiff problems. Explicit solvers are better suited for nonstiff systems. Using an explicit
solver to solve a stiff system can lead to incorrect results. If a nonstiff solver uses a very small step
size to solve a model, this is a sign that your system is stiff.

Model Step Size and Dynamics

When you are deciding between using a variable-step or fixed-step solver, keep in mind the step size
and dynamics of your model. Select a solver that uses time steps to capture only the dynamics that

34-16
Modeling Techniques That Improve Performance

are important to you. Choose a solver that performs only the calculations needed to work out the next
time step.

You use fixed-step solvers when the step size is less than or equal to the fundamental sample time of
the model. With a variable-step solver, the step size can vary because variable-step solvers
dynamically adjust the step size. As a result, the step size for some time steps is larger than the
fundamental sample time, reducing the number of steps required to complete the simulation. In
general, simulations with variable-step solvers run faster than those that run with fixed-step solvers.

Choose a fixed-step solver when the fundamental sample time of your model is equal to one of the
sample rates. Choose a variable-step solver when the fundamental sample time of your model is less
than the fastest sample rate. You can also use variable-step solvers to capture continuous dynamics.

Decrease Solver Order

When you decrease the solver order, you reduce the number of calculations that Simulink performs to
determine state outputs, which improves simulation speed. However, the results become less
accurate as the solver order decreases. Choose the lowest solver order that produces results with
acceptable accuracy.

Increase Solver Step Size or Error Tolerance

Increasing the solver step size or error tolerance usually increases simulation speed at the expense of
accuracy. Make these changes with care because they can cause Simulink to miss potentially
important dynamics during simulations.

Disable Zero-Crossing Detection

Variable-step solvers dynamically adjust the step size, increasing it when a variable changes slowly
and decreasing it when a variable changes rapidly. This behavior causes the solver to take many small
steps near a discontinuity because this is when a variable changes rapidly. Accuracy improves, but
often at the expense of long simulation times.

To avoid the small time steps and long simulations associated with these situations, Simulink uses
zero-crossing detection to locate such discontinuities accurately. For systems that exhibit frequent
fluctuations between modes of operation—a phenomenon known as chattering—this zero-crossing
detection can have the opposite effect and thus slow down simulations. In these situations, you can
disable zero-crossing detection to improve performance.

You can enable or disable zero-crossing detection for specific blocks in a model. To improve
performance, consider disabling zero-crossing detection for blocks that do not affect the accuracy of
the simulation.

For more information, see “Zero-Crossing Detection” on page 3-10.

Save the Model Operating Point


Often, you run several simulations of the same model for different inputs, boundary conditions, and
operating conditions. In some situations, these simulations share a common startup phase in which
the model transitions from the initial state to another state. For example, you can bring an electric
motor up to speed before you test various control sequences.

You can save the model operating point when the system transitions from the startup phase and use
this operating point as the initial state for future simulations. This technique does not improve

34-17
34 Improving Simulation Performance and Accuracy

simulation speed, but it can reduce total simulation time for consecutive runs because the startup
phase needs to be simulated only once. For more information, see “Use Model Operating Point for
Faster Simulation Workflow” on page 27-42

See Also

Related Examples
• “Speed Up Simulation” on page 34-3
• “How Simulink Profiler Captures Performance Data” on page 34-5

More About
• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2
• “Check and Improve Simulation Accuracy” on page 34-12

34-18
Use Performance Advisor to Improve Simulation Efficiency

Use Performance Advisor to Improve Simulation Efficiency


Use Performance Advisor to check for conditions and configuration settings that can cause inefficient
simulation performance. Performance Advisor analyzes a model and produces a report with
suboptimal conditions or settings that it finds. It suggests better model configuration settings where
appropriate, and provides mechanisms for fixing issues automatically or manually.

See Also

Related Examples
• “Performance Advisor Workflow” on page 35-2
• “Improve Simulation Performance Using Performance Advisor” on page 35-2

More About
• “Improve Simulation Performance Using Performance Advisor” on page 35-2
• “How Optimization Techniques Improve Performance and Accuracy” on page 34-2

34-19
34 Improving Simulation Performance and Accuracy

Understanding Total Time and Self Time in Profiler Reports


The Simulink Profiler displays the performance of the components of your model and their simulation
phases. Each row of the Profiler Report pane presents the following information:

• Path
• Time Plot (Dark Band = Self Time)
• Total Time (s)
• Self Time (s)
• Number of Calls

An indicator of the model's performance is the number of times a block is called in conjunction with
the time taken by each call. For a model component with any level of hierarchy, it is useful to know
how much of its total execution time is taken up by its constituent blocks vis-a-vis the time taken by
its own execution, or self-time.

Use the Total Time(s) information to identify subsystems or referenced models that are expensive to
run within the current model. As subsystems and model references typically correspond to high-level
conceptual entities such as physical models and algorithms, you can identify which component of
your model is slowing down overall performance.

34-20
Understanding Total Time and Self Time in Profiler Reports

The graphic below shows part of the Profiler Report pane for the sldemo_fuelsys_dd model.

1 To begin, recursively expand the hierarchy of the Engine Gas Dynamics subsystem. For the
Throttle subsystem, tally the total time of its constituents (from threshold=0.5 to Sonic Flow),
highlighted in red. Observe that the sum of their execution times, along with the self time for
Throttle block, is the total time of the Throttle block, shown in yellow.
2 Collapse the Throttle row of the hierarchy. Repeat the previous step for the contents of the
Throttle & Manifold subsystem–which is highlighted in yellow–and then the Engine Gas Dynamics
subsystem.

See Also
“How Simulink Profiler Captures Performance Data” on page 34-5

34-21
35

Performance Advisor

• “Improve Simulation Performance Using Performance Advisor” on page 35-2


• “Perform a Quick Scan Diagnosis” on page 35-11
• “Improve vdp Model Performance” on page 35-12
• “Use Hardware Acceleration to Speed Up Simulation for Object Detection” on page 35-16
35 Performance Advisor

Improve Simulation Performance Using Performance Advisor

In this section...
“Performance Advisor Workflow” on page 35-2
“Prepare Your Model” on page 35-3
“Create a Performance Advisor Baseline Measurement” on page 35-4
“Run Performance Advisor Checks” on page 35-5
“View and Respond to Results” on page 35-6
“View and Save Performance Advisor Reports” on page 35-8

Whatever the level of complexity of your model, you can make systematic changes that improve
simulation performance. Performance Advisor checks for configuration settings that slow down your
model simulations. It produces a report that lists the suboptimal conditions or settings it finds and
suggests better configuration settings where appropriate.

You can use the Performance Advisor to fix some of these suboptimal conditions automatically or you
can fix them manually.

Note Use Performance Advisor on top models. Performance Advisor does not traverse referenced
models or library links.

To learn about faster simulation using acceleration modes, see “Acceleration”.

Performance Advisor Workflow


When the performance of a model is slower than expected, use Performance Advisor to help identify
and resolve bottlenecks.

1 Prepare your model.


2 Create a baseline to compare measurements against.
3 Select the checks you want to run.
4 Run Performance Advisor with the selected checks and see recommended changes.
5 Make changes to the model. You can either:

• Automatically apply changes.


• Generate advice, and review and apply changes manually.
6 After applying changes, Performance Advisor performs a final validation of the model to see how
performance has improved.

• If the performance improves, the selected checks were successful. The performance check is
complete.
• If the performance is worse than the baseline, Performance Advisor reinstates the previous
settings of the model.
7 Save your model.

35-2
Improve Simulation Performance Using Performance Advisor

Caution Performance Advisor does not automatically save your model after it makes changes. When
you are satisfied with the changes to the model from Performance Advisor, save the model.

Prepare Your Model


Before running checks using Performance Advisor, complete the following steps:

• “Start Performance Advisor” on page 35-3


• “Enable Data Logging for the Model” on page 35-3
• “Select How Performance Advisor Applies Advice” on page 35-3
• “Select Validation Actions for the Advice” on page 35-4
• “Specify Runtime for Performance Advisor” on page 35-4

Start Performance Advisor

To get started with Performance Advisor:

1 Make a backup of the model.


2 Verify that the model can simulate without error.
3 Close all applications, including web browsers. Leave only the MATLAB Command Window, the
model you want to analyze, and Performance Advisor running.

Running other applications can hinder the performance of model simulation and the ability of
Performance Advisor to measure accurately.
4 Open Performance Advisor. In the Simulink Editor, on the Debug tab, click Performance.

Enable Data Logging for the Model

Make sure the model configuration parameters are set to enable data logging.

1 In the model, on the Modeling tab, click Model Settings.


2 In the Configuration Parameters dialog box, in the left pane, select Data Import/Export.
3 Set up signal logging. The model must log at least one signal for Performance Advisor to work.
For example, select the States or Output check box.
4 Click Configure Signals to Log and select the signals to log.

Note Select only the signals you are most interested in. Minimizing the number of signals to log
can help performance. Selecting too many signals can cause Performance Advisor to run for a
longer time.
5 Click OK in the Configuration Parameters dialog box.
6 Run the model once to make sure that the simulation is successful.

Select How Performance Advisor Applies Advice

Choose from these options to apply advice to the model:

• Use check parameters. Select the checks for which you want Performance Advisor to
automatically apply advice. You can review the remaining checks and apply advice manually.

35-3
35 Performance Advisor

• Automatically for all checks. Performance Advisor automatically applies advice to all selected
checks.
• Generate advice only. Review advice for each check and apply changes manually.

Select Validation Actions for the Advice

For the checks you want to run, validate an improvement in simulation time and accuracy by
comparing against a baseline measurement. Each validation action requires the model to simulate.
Use these validation options as global settings for the checks you select:

• Use check parameters. From the checks you want to run, select the ones for which you want to
validate an improvement in performance. Specify validation action for fixes using individual
settings for these checks.
• For all checks. Performance Advisor automatically validates an improvement in performance for
the checks you select.
• Do not validate. Performance Advisor does not validate an improvement in performance. Instead,
you can validate manually. When you select this option and also specify for Performance Advisor to
apply advice automatically, a warning appears before Performance Advisor applies changes
without validation.

These global settings for validation apply to all checks in the left pane except the Final Validation
check. The Final Validation check validates the overall performance improvement in a model after you
have applied changes. In case you do not want to validate changes resulting from other check results,
you can run the Final Validation check to validate model changes for simulation time and accuracy.

Specify Runtime for Performance Advisor

You can specify a Time Out value in minutes if you want to limit the runtime duration of Performance
Advisor. Use this option when running Performance Advisor on models with long simulation times.

If Performance Advisor times out before completing the checks you specify, in the left pane you can
see the checks that failed.

Create a Performance Advisor Baseline Measurement


A baseline measurement is a set of simulation measurements that Performance Advisor measures
check results against.

Note Before creating a baseline measurement, set the model configuration parameters to enable
data logging. For more information, see “Enable Data Logging for the Model” on page 35-12.

1 In the Simulink Toolstrip, on the Debug tab, click Performance.


2 In the left pane of the Performance Advisor, in the Baseline folder, select Create Baseline.
3 In the right pane, under Input Parameters, enter a value in the Stop Time field for the
baseline.

When you enter a Stop Time value in Performance Advisor, this overrides the value set in the
model. A large stop time can create a simulation that runs longer.

35-4
Improve Simulation Performance Using Performance Advisor

If you do not enter a value, Performance Advisor uses values from the model. Performance
Advisor uses values from the model that are less than 10. Performance Advisor rounds values
from the model larger than 10 to 10.
4 Select the Check to view baseline signals and set their tolerances check box to start the
Simulation Data Inspector after Performance Advisor runs a check. Using the Simulation Data
Inspector, you can compare signals and adjust tolerance levels.
5 Click Run This Check.

When a baseline has been created, a message like the following appears under Analysis:

After the baseline has been created, you can run Performance Advisor checks.

Run Performance Advisor Checks


1 After you have created a baseline measurement, select checks to run.

• In the left pane of Performance Advisor, expand a folder, such as Simulation or Simulation
Targets, to display checks related to specific tasks.
• In the folder, select the checks you want to run using the check boxes.

Tip If you are unsure of which checks apply, you can select and run all checks. After you see
the results, clear the checks you are not interested in.
2 Specify input parameters for selected checks. Use one of these methods:

• Apply global settings to all checks to take action, validate simulation time and validate
simulation accuracy.
• Alternatively, for each check, in the right pane, specify input parameters.

Input Description
Parameter
Take action automatically — Allow Performance Advisor to automatically
based on advice make the change for you.

manually — Review the change first. Then manually make the


change or accept Performance Advisor recommendations.
Validate and Select this option to have Performance Advisor rerun the
revert changes simulation and verify that the change made based on the advice
if time of improves simulation time. If the change does not improve
simulation simulation time, Performance Advisor reverts the changes.
increases

35-5
35 Performance Advisor

Input Description
Parameter
Validate and Select this option to have Performance Advisor rerun the
revert changes simulation and verify that, after the change, the model results are
if degree of still within tolerance. If the result is outside tolerance,
accuracy is Performance Advisor reverts the changes.
greater than
tolerance
Quick Select this option to have Performance Advisor use the number of
estimation of blocks of a referenced model to estimate model build time.
model build
time
3 To run a single check, click Run This Check from the settings for the check. Performance
Advisor displays the results in the right pane.

You can also select multiple checks from the left pane and click Run Selected Checks from the
right pane. Select Show report after run to display the results of the checks after they run.
4 To limit the run time of Performance Advisor, specify a Time Out value in minutes. Use this
option for models with long simulation times. The default setting for this option is 60 minutes.

Note The Time Out setting does not apply to a Quick Scan diagnosis.

Performance Advisor also generates an HTML report of the current check results and actions in a file
with a name in the form model_name\report_#.html

To view this report in a separate window, click the Report link in the right pane.

Note If you rename a system, you must restart Performance Advisor to check that system.

View and Respond to Results


After you run checks with Performance Advisor, the right pane shows the results:

35-6
Improve Simulation Performance Using Performance Advisor

To view the results of a check, in the left pane, select the check you ran. The right pane updates with
the results of the check. This pane has two sections.

The Analysis section contains:

• Information about the check


• Option to run the simulation
• Settings to take action based on advice from Performance Advisor
• Result of the check (Passed, Failed or Warning)

The Action section contains:

• A setting to manually accept all recommendations for the check


• Summary of actions taken based on the recommendations for the check

Respond to Results

Use the Take action based on advice parameter in the Analysis section to select how to respond to
changes that Performance Advisor suggests.

35-7
35 Performance Advisor

Value Response
automatically • Performance Advisor makes the change for you.
• You can evaluate the changes using the links in the summary table.
• The Modify All button in the Action section is grayed out since
Performance Advisor has already made all recommended changes for you.
manually • Performance Advisor does not make the change for you.
• The links in the summary table show recommendations.
• Use the Modify All button in the Action section to implement all
recommendations after reviewing them. Depending on how you set your
validation input parameters before you ran the check, the button label can
change to Modify All and Validate.

Review Actions

The Action section contains a summary of the actions that Performance Advisor took based on the
Input Parameters setting. If the tool also performed validation actions, this section lists the results
in a summary table. If performance has not improved, Performance Advisor reports that it reinstated
the model to the settings it had before the check ran.

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 it as failed. It also flags a check as failed if
performance did not improve and reinstates the model to the settings it had before
the check ran.

Caution Performance Advisor does not automatically save your model after it makes changes. When
you are satisfied with the changes to the model from Performance Advisor, save the model.

View and Save Performance Advisor Reports


When Performance Advisor runs checks, it generates HTML reports of the results. To view a report,
select a folder in the left pane and click the link in the Report box in the right pane.

As you run checks, Performance Advisor updates the reports with the latest information for each
check in the folder. Time stamps indicate when checks ran.

35-8
Improve Simulation Performance Using Performance Advisor

In the pane for global settings, when you select Show report after run, Performance Advisor
displays a consolidated set of check results in the report.

You can perform these actions using the Performance Advisor report:

• Use the check boxes under Filter checks to view only the checks with the status that you are
interested in viewing. For example, to see only the checks that failed or gave warnings, clear the
Passed and Not Run check boxes.
• Perform a keyword search using the search box under Filter checks.
• Use the tree of checks under Navigation to jump to the category of checks or a specific check
result that interests you.
• Expand and collapse content in the right pane of the report to view or hide check results.

Some checks have input parameters that you specify in the right pane of Performance Advisor. For
example, Identify resource intensive diagnostic settings has several input parameters. When you
run checks that have input parameters, Performance Advisor displays the values of the input
parameters in the report.

Save Performance Advisor Reports

You can archive a Performance Advisor report by saving it to a new location. Performance Advisor
does not update the saved version of a report when you run checks again. Archived reports serve as
good points of comparison when you run checks again.

1 In the left pane of the Performance Advisor window, select the folder of checks for the report you
want to save.
2 In the Report box, click Save As.

35-9
35 Performance Advisor

3 In the Save As dialog box, navigate to where you want to save the report, and click Save.
Performance Advisor saves the report to the new location.

See Also

Related Examples
• “Improve vdp Model Performance” on page 35-12
• “Perform a Quick Scan Diagnosis” on page 35-11

More About
• “Simulink Performance Advisor Checks”
• “Acceleration”

External Websites
• Improving Simulation Performance in Simulink

35-10
Perform a Quick Scan Diagnosis

Perform a Quick Scan Diagnosis


Quick Scan is a fast method to diagnose settings in a model and deliver an approximate analysis of
performance. A model can compile and simulate several times during a normal run in Performance
Advisor. Quick Scan enables you to review performance issues without compiling or changing the
model or validating any fixes. In models with long compile times, use Quick Scan to get a rapid
analysis of possible improvements.

When you perform a Quick Scan diagnosis, Performance Advisor

• Does not perform a baseline measurement.


• Does not automatically apply advice to the model.
• Does not validate any changes you make to the model.
• Does not time out if the Quick Scan diagnosis takes longer than the Time Out duration you
specify.

Run Quick Scan on a Model


1 Select checks to run.

Tip If you are unsure of which checks apply, you can select and run all checks. After you see the
results, clear the checks you are not interested in.

• In the left pane of Performance Advisor, expand a folder, such as Simulation or Simulation
Targets, to display checks related to specific tasks.
• In the folder, select the checks you want to run using the check boxes.
2 Select the Show report after run check box to display the results of the checks after they run.
3 Click Quick Scan on the right pane.

Checks in Quick Scan Mode


• “Identify resource-intensive diagnostic settings”
• “Check optimization settings”
• “Identify inefficient lookup table blocks”
• “Check MATLAB System block simulation mode”
• “Identify Interpreted MATLAB Function blocks”
• “Identify simulation target settings”
• “Check model reference rebuild setting”

See Also

Related Examples
• “Improve Simulation Performance Using Performance Advisor” on page 35-2
• “Improve vdp Model Performance” on page 35-12

35-11
35 Performance Advisor

Improve vdp Model Performance

In this section...
“Enable Data Logging for the Model” on page 35-12
“Create Baseline” on page 35-12
“Select Checks and Run” on page 35-13
“Review Results” on page 35-13
“Apply Advice and Validate Manually” on page 35-15

This example shows you how to run Performance Advisor on the vdp model, review advice, and make
changes to improve performance.

Enable Data Logging for the Model


1 In the vdp model, on the Modeling tab, click Model Settings.
2 In the Configuration Parameters dialog box, click Data Import/Export in the left pane.
3 Set up signal logging. The model must log at least one signal for Performance Advisor to work.
For example, select the States or Output check box.
4 Click Configure Signals to Log .
5 To select signals to log, select a signal in vdp. Right click and select Properties.
6 In the Signal Properties dialog box, check the Log signal data option and click OK.
7 Click OK in the Configuration Parameters dialog box.
8 Run the model once to make sure that the simulation is successful.

Create Baseline
1 Open Performance Advisor. In the Simulink Toolstrip, on the Debug tab, click Performance.
2 In the right pane, under Set Up, select a global setting for Take Action. To automatically apply
advice to the model, select automatically for all checks.
3 Select global settings to validate any improvements in simulation time and accuracy after
applying advice. To select the default setting for validation, for Validate simulation time and
Validate simulation accuracy, select use check parameters.

Note To validate any improvements automatically, change the global settings to For all
checks. However, this can increase simulation time as validating all checks requires more
simulation runs.
4 Select Show report after run. This opens an HTML report of check results.
5 In the left pane, select the Create baseline check. Clear the other checks.
6 In the Create baseline pane, set Stop Time to 10. Click Apply.
7 Click Run This Check. The right pane updates to show that the baseline was created
successfully.

35-12
Improve vdp Model Performance

Select Checks and Run

Note The global input parameters to take action and validate improvement apply to all the checks
you select.

1 In the left pane, clear the baseline check. Select these checks:

• In Simulation > Checks Occurring Before Update, select Identify resource-intensive


diagnostic settings.
• In Simulation > Checks that Require Update Diagram, select Check model reference
parallel build.
• In Simulation Targets > Check Compiler Optimization Settings, select Select compiler
optimizations on or off.
• Select Final validation.
2 For every check that you have selected in the left pane, select options in the right pane to
validate any improvements in simulation time and accuracy. Note that Take Action based on
advice is set to automatically, a result of Take Action being set to automatically for
all checks.
3 Select a value for Time Out if you want to limit the runtime duration of Performance Advisor.
4 Click Run Selected Checks.

Performance Advisor runs the checks you selected and opens an HTML report with check results.

Review Results
1 In the HTML report, filter the results to see only the checks that passed.

35-13
35 Performance Advisor

All of the selected checks passed successfully.


2 Navigate to the results for a particular check, for example Check model reference parallel
build. Use the navigation tree in the left pane or scroll to the results for this check in the right
pane.
3 Performance Advisor gives you information about this check, advice for performance
improvement, as well as a list of related model configuration parameters.

4 Filter the results to display warnings. See results for the Identify resource-intensive
diagnostic settings check.

Performance Advisor identified diagnostic settings that incur runtime overhead during
simulation. It modified values for some of these diagnostics. A table in the report shows the
diagnostics checked and whether Performance Advisor suggested a change to the value.

If the performance of the model improved, the HTML report gives you information about this
improvement. If the performance has deteriorated, Performance Advisor discards all changes and
reinstates the original settings in the model.
5 See details for the Final Validation check.

35-14
Improve vdp Model Performance

This check validates the overall performance improvement in the model. The check results show
changes in simulation time and accuracy, depending on whether performance improved or
degraded.

Apply Advice and Validate Manually


Generate advice for a check, apply it, and validate any improvements manually.

1 In the left pane, click Performance Advisor. Select these settings and click Apply:

• Set Take Action to generate advice only.


• Set Validate simulation time to use check parameters.
• Set Validate simulation accuracy to use check parameters.
2 For every check that you have selected in the left pane, select options in the right pane to
validate any improvements in simulation time and accuracy. Note that Take Action based on
advice is set to manually, a result of Take Action being set to generate advice only.
3 Select Performance Advisor in the left pane. Click Run Selected Checks in the Performance
Advisor pane.

If the performance of the model has improved, the Final Validation check results show the
overall performance improvement.
4 In the results for Identify resource-intensive diagnostic settings, Performance Advisor
suggests new values for the diagnostics it checked. Review these results to accept or reject the
values it suggests.

Alternatively, click Modify all and Validate to accept all changes and validate any improvement
in performance.

See Also

Related Examples
• “Improve Simulation Performance Using Performance Advisor” on page 35-2
• “Perform a Quick Scan Diagnosis” on page 35-11

35-15
35 Performance Advisor

Use Hardware Acceleration to Speed Up Simulation for Object


Detection

This example shows how to use hardware acceleration to speed up a Simulink® model simulation for
object detection. You can use Performance Advisor to compare simulation speeds and select an
appropriate level for hardware acceleration. Hardware acceleration is achieved by leveraging single
instruction, multiple data (SIMD) in simulation targets. All processors that support Simulink
simulation have SIMD instructions. For more information, see Hardware acceleration and “SIMD
Code Generation” (DSP System Toolbox).

Open Model

Open the object detection model. This model is an aggregate channel feature-based object detection
system, which puts bounding boxes upon the detected objects. To leverage hardware acceleration for
the model, set the simulation mode to rapid accelerator. Simulate the model. Observe that the
simulation time is 8 seconds. If you cannot find the video for Traffic Video Block when running the
simulation, click Setup Input Video in the model.

Run Performance Advisor to Select Hardware Acceleration Level

To set hardware acceleration settings, in the Simulink Toolstrip, on the Debug tab, click
Performance. In the pane on the left, expand Simulation Targets, then expand Check Hardware
Acceleration Settings and select Select hardware acceleration settings. Click Run this check.
The Result pane shows the simulation times for different hardware acceleration levels and the
hardware information of your computer. In this example, the software detects an Intel-type CPU that
supports SSE and AVX, where SSE2 is used for generic hardware acceleration and AVX2 is used for
native hardware acceleration. Click Modify all to apply the recommended hardware acceleration
level.

35-16
Use Hardware Acceleration to Speed Up Simulation for Object Detection

Alternatively, you can change the level of the hardware acceleration manually. Under the Modeling
tab, click Model Settings. On the left pane, select Simulation Target. Expand Advanced
parameters and set Hardware acceleration to

• Off
• Leverage generic hardware (Faster, no rebuild)
• Leverage native hardware (Fastest, rebuild allowed)

Improve Performance with Hardware Acceleration

These images show the aggregate channel feature-based object detection system placing bounding
boxes on the detected objects with no hardware acceleration and with hardware acceleration. The
instantaneous frames per second (FPS) data is displayed in the top left of each image. With the same
video input, the FPS with no hardware acceleration is 8.72 and the FPS with hardware acceleration is
11.90.

Performance improvement with hardware acceleration is based on execution time, which is measured
using the sim command. Without hardware acceleration, simulation execution time is 34.50 seconds.
With hardware acceleration, simulation execution time is 23.04 seconds, which is a 33.22%
improvement. Note that simulation time improvement may vary on different hardware. These
numbers and analysis were published on a Windows laptop with Intel® Core™ i7-8650U CPU @
1.90GHz 4 Cores 8 Threads processor.

35-17
35 Performance Advisor

See Also

Related Examples
• “Optimize Code for Reduction Operations by Using SIMD” (Simulink Coder)

35-18
36

Solver Profiler

• “Examine Model Dynamics Using Solver Profiler” on page 36-2


• “Zero-Crossing Events” on page 36-5
• “Solver Exception Events” on page 36-7
• “Solver Resets” on page 36-14
• “Jacobian Logging and Analysis” on page 36-21
• “Modify Solver Profiler Rules” on page 36-23
• “Customize State Ranking” on page 36-25
• “Solver Profiler Interface” on page 36-27
36 Solver Profiler

Examine Model Dynamics Using Solver Profiler


When model simulation slows down or stops responding, a close examination of the dynamics of the
model can help you identify the factors affecting the simulation.

Understanding solver behavior enables you to interpret how the model simulates and what causes the
solver to take small steps.

The Solver Profiler analyzes a model for patterns that affect its simulation. The Solver Profiler
presents graphical and statistical information about the simulation, solver settings, events, and
errors. You can use this data to identify locations in the model that caused simulation bottlenecks.

In addition, there are multiple factors that can limit the simulation speed. The Solver Profiler logs and
reports all the major events that occur when simulating a model:

• Zero-crossing events
• Solver exception events
• Solver reset events
• Jacobian computation events

Note In order to accurately profile the solver performance, the Solver Profiler may temporarily
modify some logging settings of your model. Your settings will be restored after profiling has been
completed.

These events are common and necessary for an accurate simulation. However, they do incur
computational cost and frequent occurrences can slow down or even stall the simulation.

To examine model dynamics and identify causes that affect the simulation:
1 Open the model that is simulating slowly or unsuccessfully. For example, open the
BouncingBallWithSwitch model.

2 Open the Solver Profiler by clicking the hyperlink in the lower-right corner of the Simulink
Editor.

36-2
Examine Model Dynamics Using Solver Profiler

3 The Solver Profiler provides smart logging and diagnostics of continuous model states and
Simscape states. To enable this, select the Continuous States, Zero Crossing or Simscape
States option before a run. Disable these options only if you are running out of memory. After the
run, access the States Explorer, Zero Crossing Explorer, or Simscape Explorer to examine those
states.
4 Click Run. The profiler simulates the model and starts capturing solver performance data.

When the simulation ends, the profiler displays the statistics and exceptions it captured over the
duration of the simulation.

Tip You can pause or stop the simulation at any time to view the information captured until that
point.
5 Use the profiler plot to highlight the parts of the model that caused generate the most events.
6 Click Save to capture your profiling session, or exit without saving.

36-3
36 Solver Profiler

See Also
Solver Profiler | Zero Crossing Explorer | State Explorer | solverprofiler.profileModel

36-4
Zero-Crossing Events

Zero-Crossing Events
The BouncingBallWithSwitch model simulates a ball bouncing on a hard surface.

Select the Zero Crossing option in Configure section of toolstrip, then click the Run button on the
Solver Profiler. The model simulates in 648 steps and triggers 45 zero crossing events. To highlight
the zero crossing events on the step size plot, click the Zero Crossing tab from the Diagnostics
pane and select the ex_spi_show_zc/Switch block that is causing the zero-crossing events. Notice
that the zero crossing events are displayed on the Step Size plot as yellow dots.

36-5
36 Solver Profiler

The result indicates that when the ball drops on the hard surface, it bounces 45 times before coming
to a stop. The solver resets after each bounce, increasing the computational load. Having many resets
improves accuracy at the cost of computation load. Therefore, it is important to know this tradeoff
when modeling.

If this modeling construct belonged to a larger model, the Solver Profiler would help you locate it. You
could then modify the model to improve solver performance. For example, you can decide to reduce
the accuracy of the contact dynamic by increasing the damping factor, which would reduce the
number of bounce events. Increasing the damping from 100 to 500 makes the ball bounce only 9
times, allowing the simulation to complete in only 161 steps.

You can observe more details about Zero Crossing events from Zero Crossing Explorer. To do this,
ensure Zero Crossing option from Configure is selected before profiling the model. Then click Zero
Crossing in the Explore section of the Solver Profiler toolstrip. See Zero Crossing Explorer.

See Also
Solver Profiler | solverprofiler.profileModel | “Solver Profiler Interface” on page 36-27

36-6
Solver Exception Events

Solver Exception Events

Tolerance-Exceeding Events
This example simulates two identical nonlinear spring-damping systems. The two systems have
different spring stiffness.

When you run the Solver Profiler on this model, you can see the tolerance-exceeding events in the
Solver Exception tab.

36-7
36 Solver Profiler

The result indicates that the stiffer spring causes the solver tolerance to exceed the limit. Typically,
model states that change the fastest tend to be closest to the solver tolerance limit.

The solver attempts to take the largest possible steps while optimally trading off between speed and
accuracy. Occasionally, this tradeoff causes the solver to take steps that exceed the tolerance limit
and forces it to reduce the step size. Exceeding the tolerance limit is not a poor modeling practice in
itself. This profiler statistic is not meant to help you reduce tolerance exceeding events to zero.

This statistic can help you identify parts of your model that are close to exceeding the tolerance limit.
You can identify model components that change the fastest or are the stiffest. You can decide to retain
this model dynamic in the simulation or simplify it to speed up simulation.

The tolerance-exceeding statistic can also help you identify modeling errors. If you do not expect the
highlighted states to change as fast, you can examine your model for errors. In this example, the
modeling error could be that the stiffness of the stiffer spring is specified in N/m instead of N/mm. This
error makes the spring 1000 times stiffer than expected.

Newton Iteration Failures


Newton iteration failures are specific to implicit solvers like ode15s and ode23t, and they result
from Newton iterations not converging after a few trials. Similar to tolerance-exceeding events, these
failures tend to occur when a system changes quickly.

This example simulates how the radius of a ball of flame changes when you strike a match. The ball of
flame grows rapidly until it reaches a critical size, when the amount of oxygen consumed balances the
growth in ball surface.

36-8
Solver Exception Events

When you run the Solver Profiler on this model, you can see the Newton iteration failures in the
Solver Exception tab.

The result indicates that when the combustion begins, the solver tolerance is exceeded multiple
times. When equilibrium is attained, the system appears different, and a Newton iteration failure
occurs. The Jacobian of the system is recomputed, and the solver continues to move forward.

Newton failures are not indicative of poor modeling practices. This profiler statistic is not meant to
help you reduce these failures to zero. In this example, you can reduce the solver tolerance to prevent
this failure. But the solver then takes small steps unnecessarily, which is counterproductive.
Therefore, in this example, this failure is acceptable.

36-9
36 Solver Profiler

This type of failure becomes problematic when it occurs in large numbers over a short period,
especially in Simscape models. Dense failures indicate that your model is not robust numerically. One
way to improve numerical robustness is to tighten the solver tolerance. Another way is to modify the
model to avoid rapid changes.

Infinite State and Infinite Derivative Exceptions


An infinite state exception occurs when the magnitude of a state approaches infinity. Similarly, when
the magnitude of the derivative of a state approaches infinity, an infinite derivative exception occurs.
The solver reduces the step size and makes another attempt at integration.

This example shows a set of two Integrator Limited blocks that have initial conditions slightly less
than realmax. As they integrate the Constant input of 1e305, the solver quickly reaches the infinite
state exception.

36-10
Solver Exception Events

When you run the Solver Profiler for this model, you can see that the InfiniteState5 and InfiniteState7
blocks have 188 and 152 infinite state exceptions in the Solver Exceptions tab.

Differential Algebraic Equation Failures


Most Simscape models use differential algebraic equations (DAEs), in contrast to Simulink models,
which use ordinary differential equations.

The use of DAEs adds complexity to Simscape models. Solvers like ode15s and ode23t can handle
many types of DAEs. However, when the algebraic constraints between Simscape components are
complex and changing fast, the Newton iteration process fails to resolve to those constraints.

This example simulates a pressure source that can be directed toward one of two hydraulic
chambers.

36-11
36 Solver Profiler

When you simulate this model, Simulink displays several warnings.

Typically, small models can handle such warnings and simulate to completion. However, this warning
indicates that the model is not robust numerically. Minor changes to the model, or integration into a
larger model, can result in errors.

When you run the Solver Profiler on this model, you can see the DAE failures in the Solver
Exception tab.

36-12
Solver Exception Events

In this case, the exception results from large solver tolerance. Tightening the solver tolerance forces
the solver to take smaller steps and better capture the changes in algebraic constraints.

Alternatively, this exception can be avoided by removing the algebraic constraint. In this example, the
Check Valve and the 4-Way Directional Valve are directly connected. When their pressure–flow
relationship changes rapidly, the solver is unable to capture the changes. Inserting a Hydraulic
Chamber between those two components makes them compliant. To learn more about dry nodes, see
Simscape documentation.

36-13
36 Solver Profiler

Solver Resets
The Solver Profiler logs events that cause the solver to reset its parameters because solver resets do
incur computational cost. In addition to the total number of resets, you can also see a breakdown by
type of reset event.

Note A solver reset event can have multiple causes. As a result, the number of Total solver reset
events in the Statistics pane may be less than the sum of the solver resets of each type.

Zero-Crossing
Some zero crossing events occur at discontinuities in the signal. Consider the example model of a
bouncing ball from the “Zero-Crossing Events” on page 36-5 section.

Open the model BouncingBallWithSwitch and open Solver Profiler.

The Solver Profiler records 46 solver resets, 45 of them are caused by Zero Crossing events from the
switch block. The solver resets are displayed on the Step Size plot as green dots. Compare the step-
size and the Solver Reset highlighting with the output x of the Second-Order Integrator block, which
is the height of the ball from the ground. Observe that the solver resets occur when the ball bounces
off the ground.

36-14
Solver Resets

Discrete Signal
Solver resets also occur when your model has a discrete signal driving a block with continuous states,
as seen in this example model.

The discrete Sine Wave block outputs a 1 rad/s sine wave with a discrete sample time ts = 2.

The Solver Profiler report shows that four solver resets occur due to discrete signals driving a
continuous block. These resets occur at every execution of the Sine Wave block.

36-15
36 Solver Profiler

When a discrete input to a Model block connects to the input of a block that has continuous states,
the software cannot determine with certainty the appropriate rate at which to reset the solver to
ensure simulation accuracy. The software resets the solver each time the discrete signal updates. This
solver reset rate ensures that the simulation results are accurate when the discrete signal is the
source for the input signal to the block with continuous states. When the discrete signal is not the
source for the input signal to the block with continuous states, the software can reset the solver more
frequently than necessary, which can affect simulation performance.

ZOH Signal
This type of solver reset occurs when a block output is not executed during a trial or minor time step
and gets updated only during the integration or major time step. As a result, the block output
changes discontinuously from one major time step to the other. As a result the solver resets. See
“Fixed-in-Minor-Step Sample Time” on page 7-19 sample time.

This example model shows a simple plant and controller that tracks a sinusoidal reference signal. The
source of this signal is a Sine Wave block whose sample time is specified to be fixed-in-minor-step.

36-16
Solver Resets

Observe from the results of the profiling session that there are 80 ZOH Signal solver resets in the
simulation.

Note When you select Continuous States for logging or enable the SaveStates parameter, the
derivative of a continuous block driven by a Fixed-in-Minor-Step signal is NaN.

This is because the driving “Fixed-in-Minor-Step Sample Time” on page 7-19 block updates its value
only at every major time step. The signal driven to the continuous block is therefore discontinuous
and the state is non differentiable.

The plot shows the outputs of the Sine Wave and Integrator blocks in the example model.

36-17
36 Solver Profiler

Tip Solver resets caused due to ZOH signals are serious compared to solver reset events caused by
discrete signals and can significantly slow down the simulation. This is because ZOH signal reset
events occur at every major step of the solver. Reconfigure your simulation to avoid these resets, if
needed.

Block Signal
Sometimes, the block can be configured to reset the solver when certain conditions are satisfied
during its execution. Consider the sldemo_bouncemodel of a bouncing ball which can be found in
the “Capture the Velocity of a Bouncing Ball with the Memory Block” example.

Observe from the profiling results that there are 130 solver resets triggered by a block. A solver reset
event can have multiple causes. In this case, zero crossings and block changes cause a solver reset
event.

36-18
Solver Resets

One setting that causes the Block Change solver reset event is the Reinitialize dx/dt when x
reaches saturation parameter. This setting is necessary to properly simulate the dynamics of a
bouncing ball.

36-19
36 Solver Profiler

Initial Reset
When you run a simulation, the solver needs to reset its parameters for the first time. This event is
shown as the Initial Reset event in the Solver Profiler report. It occurs once at the start of the
simulation.

Internal
There are some reset events that are internal to the Simulink engine. These reset events are
necessary for the engine to correctly configure itself for accurate simulation.

36-20
Jacobian Logging and Analysis

Jacobian Logging and Analysis


The Solver Profiler supports Jacobian logging and analysis for implicit solvers. Implicit solvers are
common for models that include physical components and systems modeled using Simscape.

Open the model PneumaticActuationCircuit.

openExample("simscape/PneumaticActuationCircuitExample")

In the Simulink Toolstrip, on the Debug tab, in the Performance section, click the Performance
button arrow, then select Solver Profiler.

To log updates to the Jacobian matrix that occur during the profiling simulation, in the Solver Profiler,
select Model Jacobian. To run the profiling simulation, click Run. When the profiling simulation
completes, the Jacobian logging results are available in the Jacobian Analysis tab. By analyzing the
results in the Jacobian Analysis tab, you can identify states in the model that likely contribute to
slow simulation.

To view the logged Jacobian data in the step size plot, in the View section, select Jacobian Update.
The Solver Profiler annotates the step size plot with a black dot for each Jacobian update that
occurred in the profiling simulation.

36-21
36 Solver Profiler

The results in the Jacobian Analysis tab shows 448 Jacobian updates in total. To highlight the block
that corresponds to a limiting state reported in the Jacobian logging results, select the row for the
limiting state in the Jacobian Analysis tab. Then, in the Solver Profiler Toolstrip, click Highlight
Block.

See Also
Tools
Solver Profiler | State Explorer | Zero Crossing Explorer | Simscape Results Explorer

Functions
solverprofiler.profileModel

Related Examples
• “Examine Model Dynamics Using Solver Profiler” on page 36-2
• “Solver Resets” on page 36-14
• “Zero-Crossing Events” on page 36-5
• “Solver Exception Events” on page 36-7

36-22
Modify Solver Profiler Rules

Modify Solver Profiler Rules


You can customize the suggestions that appear in the Solver Profiler in these ways:

• Change the thresholds of the Solver Profiler rules that detect failure patterns.
• Select which rules to apply during a profiling run.
• Author your own rule set as a MATLAB script.

Change Thresholds of Profiler Rules

Click Rule Customization in the Solver Profiler to access the rule set. You can change the
thresholds for most of these rules and also select which rules you want to apply selectively during a
simulation run.

Develop Profiler Rule Set


You can override the settings on the Rule Set dialog box by specifying a custom rule set.

Create a rule set as a MATLAB script and specify the path to the script in the Custom Rule Set
section of the Rule Set dialog box.

A simple rule set example looks as follows:

function diagnosticsString = customRule(profilerData)


if isempty(profilerData.zcEvents)
diagnosticsString{1} = 'No zero crossing event detected.';

36-23
36 Solver Profiler

else
diagnosticsString{1} = 'Zero-crossing events detected.';
end
end

The input to the function is an array of structures called profilerData. This array of structures
organizes all the information that the Solver Profiler collects during a profiling run. It contains the
following substructures.

Substructure Fields
stateInfo: Stores information on block states • name: Block name
• value: State values
• blockIdx: Block ID
blockInfo: Cross-reference of blocks and state • name: Block name
IDs • stateIdx: State ID
zcSrcInfo: Stores information on blocks • name: Block name
causing zero crossing events • blockIdx: Block ID
zcEvents: Cross-reference of the time stamps of • t: Event timestamp
zero crossing events and the corresponding state • srcIdx: Block ID
IDs
exceptionEvents: Cross-reference of exception • t: Event timestamp
event timestamps, the ID of the corresponding • stateIdx: State ID
state that caused the event, and the cause.
• cause: Cause of exception
resetTime: Stores timestamps of solver resets. None
tout: Stores simulation times. None

36-24
Customize State Ranking

Customize State Ranking

If you log continuous states in the Solver Profiler, you can open the State Explorer to investigate each
continuous state. The State Explorer ranks continuous states by the following metrics:

• State Derivative
• Newton/DAE Exception
• State Value
• Error Control Exception
• State Name
• State Chatter

In addition to these ranking metrics, you can write and upload your own algorithm to determine how
continuous states are ranked in the State Explorer.

1 Click the edit button next to the Rank States By dropdown.

2 In the Custom Algorithm dialog box that appears, click Add and upload a MATLAB script that
contains your ranking algorithm.

A simple algorithm that ranks states by value looks as follows:

36-25
36 Solver Profiler

Note The structures referenced in this example organize information that the Solver Profiler
collects during a profiling run. For more information on the structures, see “Develop Profiler Rule
Set” on page 36-23.

function [index,score] = customRank(sd,tl,tr)

% Allocate storage for index and score list


nStates = length(sd.stateInfo);
index = l:nStates;
score = zeros(nStates,l);

% Loop through each state to calculate score


for i = l:nStates
x = sd.stateInfo(i).value;
% apply time range constraints
x = x(sd.tout>=tl & sd.tout<=tr);
if max(x) > 1
score(i) = 1;
else
score(i) = 0;
end
end

% Rank the states


[score, order] = sort(score, 'descend');
index = index(order);

end

36-26
Solver Profiler Interface

Solver Profiler Interface

The Solver Profiler enables you to:

• Start a profiling session, save a session, or open a saved session.


• Customize and filter the results displayed.
• Interact with the model and trace and highlight the states that contain exceptions.
• Open Simscape Explorer, Zero Crossing Explorer, or States Explorer to analyze simulation data
further.
• Customize profiler suggestions using your own rules.

The Solver Profiler includes four panes. Use these panes to perform these functions.

• Toolstrip — Set parameters for the Solver Profiler to log and report events that occurred during
simulation.
• Step Size — Display step size over simulation time plot. You can also observe maximum step size
and events such as Zero Crossing, Solver Reset or Solver Exception from the plot.
• Statistics — Display statistical information on solver profiling including model information, step
information and event information.
• Suggestions — Provide suggestions to improve the performance of the current model. You can
also obtain detailed profiling information from other tabs such as Zero Crossing, Solver
Exception or Solver Reset.

Toolstrip
For more information on the Solver Profiler parameters, see “Parameters”.

Statistics Pane
The statistics pane displays information on model parameters, including:

36-27
36 Solver Profiler

• Model Information — Model configurations for the current simulation including Solver type,
states, time, tolerance.
• Step Information

• Average step size — A measure of how fast the solver advances. It is calculated as the total
simulation time divided by the number of steps the solver used. It is bounded by the model
configuration parameters Max step size and Min step size.
• Max step size usage — The percentage of maximum step sizes used by the solver among all
step sizes.
• Event Information

• Zero crossing — A solver-specific event that affects model dynamics. During simulation, the
solver detects zero crossing. Zero crossing detection incurs computation cost. For more
information, see “Zero-Crossing Detection” on page 3-10.
• Solver reset — An event that causes the solver to reset its parameters. Solver reset detection
incurs computation cost. The solver reset statistics are broken down into Zero Crossing,
Discrete Signal, ZOH Signal, Block Change, Initial Reset, and Internal solver reset
events. For more information, see “Solver Resets” on page 36-14
• Solver exception — An event that renders the solver unable to solve model states to meet
accuracy specifications. To solve model states accurately, the solver has to run a few adjusted
trials, which incur computation cost.

• Error control exception — An event where a solution obtained by the solver has an error
that is greater than the tolerance specification.
• Newton iteration exception — An event specific to implicit solvers. Newton iterations do
not converge after a few trials.
• Infinite state exception — An event where one or more states solved by the solver are
infinite.
• DAE newton iteration exception — An event specific to implicit solvers for Simscape
models. The Newton iteration does not converge even though the solver violates the
minimum step size constraint.

Suggestions Pane
The Suggestions pane provides suggestions if issues are detected in the model. It also provides
detailed statistic data on events such as Zero Crossing, Solver Exception or Solver Reset. Clicking on
these events in the Statistics Pane will bring relevant tabs in the Suggestion Pane to the front. The
suggestions and exceptions pane displays information on exceptions, including:

• Zero crossing — A solver-specific event that affects model dynamics. During simulation, the
solver detects zero crossing. Zero crossing detection incurs computation cost. For more
information, see “Zero-Crossing Detection” on page 3-10.

The Suggestions pane shows blocks that experience zero crossing events and number of those
events that happened during simulation. To highlight the target block in the model, select the
block from Zero Crossing table, then click Highlight Block from toolstrip.
• Solver reset — An event that causes the solver to reset its parameters. Solver reset detection
incurs computation cost. The solver reset statistics are broken down into Zero Crossing,
Discrete Signal, ZOH Signal, Block Change, Initial Reset, and Internal solver reset events.
For more information, see “Solver Resets” on page 36-14.

36-28
Solver Profiler Interface

The suggestions pane shows detailed statistic data on solver reset events and blocks that caused
the solver to reset. To highlight the target block in the model, select the block from Solver Reset
table, then click Highlight Block from toolstrip.
• Solver exception — An event that renders the solver unable to solve model states to meet
accuracy specifications. To solve model states accurately, the solver has to run a few adjusted
trials, which incur computation cost.

The suggestions pane shows detailed statistic data on solver exception events and blocks that
caused solver exceptions. To highlight the target block in the model, Select the block from Solver
Exception table, then click Highlight Block from toolstrip.

See Also

Related Examples
• “Examine Model Dynamics Using Solver Profiler” on page 36-2

36-29
37

Debug Simulations

• “Simulink Debugging Programmatic Interface” on page 37-2


• “Debug Simulation of Iterator Subsystem” on page 37-7
37 Debug Simulations

Simulink Debugging Programmatic Interface


You can use the Simulink debugging programmatic interface to run a simulation of a model one
method at a time. Blocks in Simulink are implemented as a set of methods that are called by the
solver at specific times during each time step. Using breakpoints, you can control when the
simulation pauses and examine the execution results to trace behavior in your model to specific
blocks, parameters, or connections. You can set breakpoints for specific conditions throughout the
model, such as zero crossings, or on block methods and signals.

Note To debug a simulation using the Simulink debugging programmatic interface, you must start
the simulation using the sldebug function or using the sim function with the debug name-value
argument.

The Simulink Editor offers many of the same capabilities in the programmatic interface.

Use Simulink Debugging Functions


When you programmatically debug a simulation, you start the simulation using the sldebug function.
After you call the sldebug function, the MATLAB command prompt becomes the sldebug command
prompt. Instead of >>, you see (sldebug @0): >>. To control the debugging session, enter
debugging commands in the MATLAB Command Window, at the sldebug command prompt.

For ease of use, the Simulink debugging programmatic interface accepts abbreviations for the
debugging functions. For example, to call the step function, instead of entering the command step,
you can enter the command s.

Use MATLAB Functions


You can enter any MATLAB expression at the sldebug command prompt. For example, suppose you
are paused on a breakpoint and the simulation logs the time and output of your model as tout and
yout. You can enter this command at the sldebug command prompt to create a plot.

plot(tout,yout)

Some MATLAB functions have the same name as or a similar name to a function in the Simulink
debugging programmatic interface. To view the contents of a variable or to call a function with a
name that partially or entirely matches the name of one of the Simulink debugging functions, use the
eval function. For example, suppose the workspace contains the variable s. To display the contents
of the variable instead of calling the step function, use this command.

eval('s')

Understand Block and Method IDs


Some of the debugging functions and messages use a numeric block ID or method ID to refer to a
specific block or method in the model. Block IDs and method IDs are numeric values that the
software assigns to each block and method in the simulation during run time.

The software assigns block IDs while generating the sorted order and execution list for the model
during the compilation phase of the simulation. A block ID has the form (t)s:b, where t is an

37-2
Simulink Debugging Programmatic Interface

integer that identifies the task in which the block executes, s is an integer that identifies the system
that contains the block, and b is an integer that indicates the position of the block in the execution
list for that system. For example, the block ID (0)0:1 refers to the first block in the root system of a
model. You can use the slist function to see the block ID for each nonvirtual block in the model.

Set and Manage Breakpoints


In a simulation debugging session, you can set breakpoints, or points of interest where you want to
pause the simulation to analyze the system. Using the continue function, you can run a simulation
from one breakpoint hit to the next.

Breakpoints are useful when you know that a problem or behavior you want to investigate occurs at a
certain point in your model or when a certain condition occurs. By defining an appropriate breakpoint
and running the simulation using the continue function, you can run the simulation without
interruption up to the point in the simulation you want to investigate.

Note When the simulation pauses on a breakpoint of a MATLAB S-function, to close MATLAB, you
must first end the simulation debugging session.

The table summarizes functions available for setting breakpoints programmatically.

Function Breakpoint Behavior


break Set breakpoint that pauses simulation on specified method

To clear breakpoints set using the break function, use the clear function.
bafter Set breakpoint that pauses simulation after specified method

To clear breakpoints set using the bafter function, use the clear function.
tbreak [t] Set or clear breakpoint that pauses simulation at specified simulation time step
ebreak Set or clear breakpoint that pauses simulation when recoverable solver error
occurs
nanbreak Set or clear breakpoint that pauses simulation when NaN or infinite (Inf) value
occurs
xbreak Set or clear breakpoint that pauses simulation when the solver limits the step
size for a variable-step simulation
zcbreak Set or clear breakpoint that pauses simulation when a nonsampled zero-
crossing event occurs

Display Information About the Simulation


You can use several functions to display run-time information about the simulation during a
simulation debugging session.

The table summarizes options available to display information about blocks in the model during
simulation, including the block input and output values. The level of information displayed when you
call each of these functions depends on the software configuration. To specify the level of information
to display, use the probe function.

37-3
37 Debug Simulations

Function Name Description


probe Displays data for specified block when you issue command
disp Displays data for specified block when the simulation pauses
trace Displays data for specified block each time the block executes

The table summarizes other options available for displaying run-time information about the model in
simulation.

Function Name Description


atrace Display information each time algebraic loop is
solved in simulation debugging session
states Display current values for system states
strace Display solver information in simulation
debugging session

Display Information About the Model


The table summarizes functions you can use to display information about the model.

Function Name Description


slist Display sorted list for model.

The sorted list information includes the block ID


for each block in the model.
ashow Highlight algebraic loop in model during
simulation debugging session.
bshow Highlight in block diagram the block that
corresponds to the specified block ID.
systems Display list of nonvirtual subsystems in model or
model hierarchy.
zclist Display list of blocks that detect zero crossings.
status Display list of debugging options in effect for
current simulation debugging session.

Use Simulation Debugging Commands While Debugging from Simulink


Editor
When you start a simulation debugging session using the Simulink Editor, you can issue some of the
simulation debugging commands, such as disp and probe, when the simulation is paused within a
time step. To start a simulation debugging session from the Simulink Editor, add one or more
breakpoints to your model. Then, in the Breakpoints List, check that Pause within time step is
selected.

When a debug simulation started from the Simulink Editor pauses within a time step, the sldebug
prompt replaces the MATLAB command prompt (>>) in the MATLAB Command Window.

37-4
Simulink Debugging Programmatic Interface

The table describes the programmatic simulation debugging commands that you can use while
paused within a time step in a simulation debugging sessions started from the Simulink Editor.

Category Function Name Description


Display information about model probe Display input, output, and state
data for specified block
elist Display execution order
slist Display sorted list of blocks in
model
stimes Display information about
sample times in model
systems List nonvirtual subsystems in
model or model hierarchy
states Display state values
zclist List blocks that detect zero
crossings
Highlight blocks or algebraic bshow Highlight specified block in
loops in block diagram model
ashow Identify and highlight algebraic
loops
Add or remove model-level nanbreak Set or clear breakpoint to pause
breakpoints when Inf or NaN value occurs
zcbreak Set or clear breakpoint to pause
when nonsampled zero-crossing
events occur
Add and remove trace points trace Display information about
specified block each time block
executes
atrace Display information each time
algebraic loop is solved
etrace Display information when
entering and exiting methods
strace Display solver information
untrace Remove trace point
Get information about status Display options used in current
simulation debugging session, simulation debugging session
access help, or end simulation where Display current location within
debugging session simulation loop
help Display help for Simulink
debugging programmatic
interface
stop Stop simulation debugging
session

37-5
37 Debug Simulations

See Also
sldebug

37-6
Debug Simulation of Iterator Subsystem

Debug Simulation of Iterator Subsystem


Iterator subsystems repeat the execution of the algorithm modeled inside the subsystem one or more
times within a simulation time step. To analyze or debug the algorithm inside an iterator subsystem,
you need to pause within a major time step when the iterator subsystem executes and step the model
execution by a more granular interval than major time steps.

This example shows how to analyze a simple summing algorithm implemented using a while-iterator
subsystem.

Open Example Model

The model IterateSum uses a while-iterator subsystem to implement an iterative summing


algorithm. The while-iterator subsystem has two inputs: a sine wave signal and a pulse signal. The
pulse provides the initial logical condition that determines whether the while-iterator subsystem is
enabled in each time step. A Dashboard Scope block is connected to the Iteration Number signal
to display the output of the while-iterator subsystem.

Simulate the model. You can use debugging utilities in the Simulink® Editor to analyze the algorithm
implemented in the while-iterator subsystem and understand the signal displayed in the Dashboard
Scope block.

37-7
37 Debug Simulations

Add Port Value Labels


To understand how signal values change as the simulation progresses, you can add port value labels
to signals of interest throughout your model before and during simulation. The port value label is
displayed in the model canvas, near the port that produces the signal.

To add a port value label on the Sine Wave signal:

1 Select the Sine Wave signal.


2 On the Debug tab, under Tools, in the Port Values button group, click Show port value label on

selected signal .

You can also add port value labels to multiple signals at once. To add port value labels for the Pulse
and Iteration Number signals:

1 Select the Pulse signal.


2 Press Shift and select the Iteration Number signal.
3 On the Debug tab, in the Port Values button group, click Show port value label on selected

signal .

New port value labels display no data yet until the next time the block that produces the signal
executes.

37-8
Debug Simulation of Iterator Subsystem

Set Breakpoint to Pause Within Time Step


By default, models are configured to pause within a time step as soon as the condition for a
breakpoint is met. To check whether your model is configured to pause within a time step, open the
Breakpoints List. In the Simulink Toolstrip, on the Debug tab, click Breakpoints List. Check that
Pause within time step is selected.

To pause execution within a time step so you can analyze the model by advancing the simulation one
block at a time, set a breakpoint. The simulation pauses within the time step as soon as the condition
for the breakpoint is met. For example, to pause just before the while-iterator subsystem gets
enabled, set a breakpoint on the output of the Pulse block.
1 Select the Pulse signal.
2 On the Debug tab, under Breakpoints, click Add Breakpoint.
3 In the Add Breakpoint dialog box, configure the signal breakpoint condition so the simulation
pauses when the Pulse block output value becomes greater than zero. From the drop-down list,
select > and then enter 0 in the box.

Because the while-iterator subsystem executes only when the Pulse signal value is not 0, this signal
breakpoint causes the simulation to pause before each time the while-iterator subsystem executes.

The red circle on the signal line indicates the active signal breakpoint.

Step Through Block Execution


To start analyzing the model, run a simulation. In the Simulink Toolstrip, on the Debug tab, click
Run.

When the simulation reaches a time of 0.5 seconds, the Pulse signal value becomes 1. The
simulation pauses on the breakpoint just after the Pulse block executes and updates the output value.
To indicate why and where the simulation paused, the breakpoint is annotated with a green arrow,
and the Pulse block is highlighted green.

To step the simulation execution to the next block, in the Debug tab, click Step Over. The green
highlight moves to the while-iterator subsystem, and the green arrow on the breakpoint disappears.

37-9
37 Debug Simulations

To see the number of iterations the while-iterator subsystem executes in this time step, click Step
Over again. Because the while-iterator subsystem is nonvirtual, the Step Over action steps over the
entire subsystem as a single unit. The port value label updates to show that the while-iterator
subsystem executed the algorithm 13 times for an input value of 86.6.

If you click Step Over one more time, the Outport block executes, and the Dashboard Scope block
updates to show the new value for the Iteration Number signal.

If you continue clicking Step Over, you can step through the block-by-block execution in subsequent
major time steps. The Pulse signal value stays 1 for the next several time steps.

Each time the simulation pauses on the Pulse block after you click Step Over, clicking Step Over
again causes the simulation to pause on the breakpoint. The first time the simulation pauses on the
Pulse block, the simulation pauses just before the Pulse block runs its output method. The second
time the simulation pauses on the breakpoint is because the condition is met when the Pulse block
runs its output method.

Step into While-Iterator Subsystem


To progress the simulation until the next time the while-iterator subsystem is enabled, in the Debug
tab, click Continue. If you did not continue stepping block by block until the Pulse block output value
changed to 0, continue clicking Continue until the simulation reaches a time of 1.5 seconds and
pauses on the breakpoint.

To progress the simulation to the while-iterator subsystem, click Step Over. Then, to observe the
algorithm, click Step In. The model canvas navigates inside the while-iterator subsystem. The
simulation pauses on the Display block just before it executes to update the displayed value. The
block displays 14 from the last time it executed.

37-10
Debug Simulation of Iterator Subsystem

To see the signal values as you step through the algorithm implemented in the while-iterator
subsystem, add port value labels.

1 Select everything in the block diagram by clicking in the upper left of the canvas and holding
while you drag the pointer to the lower right of the canvas or pressing Ctrl+A.
2 In the Debug tab, under Tools, in the Port Values button group, click Show port value label on

selected signal .

The port value label for the iteration number output from the While Iterator block shows
inaccessible, so that signal value is displayed using the Display block. The other port value labels
show no data yet.

Click Step Over. The Display block executes and the displayed value updates to 1 to indicate that
this is the first iteration. The simulation pauses on the Memory block, which is next in the execution
order.

37-11
37 Debug Simulations

As you click Step Over two more times, the simulation pauses on the Sum block then the Relational
Operator block. When you click Step Over again, the canvas updates to show the top level block
diagram because the while-iterator subsystem executes only once in this time step. When you click
Step Over once more, the Dashboard Scope block plots the new value for the Iteration Number
signal.

Pause on Specific Iteration


When you want to debug or analyze the algorithm inside an iterator subsystem, you can use a
breakpoint inside the while-iterator subsystem to pause simulation on a particular iteration. Setting a
breakpoint on the iteration number output from the While Iterator block is not supported. Where you
place the breakpoint and the condition for the breakpoint depends on how your algorithm uses the
iteration number.

In the example model, the algorithm computes the cumulative sum of the iteration number. To break
on a particular iteration, you can add a breakpoint to the output of the Sum block or to the output of
the Memory block. For example, suppose you want to analyze the algorithm for a time step where the
while-iterator subsystem algorithm executes more than once. In the first iteration, the output of the
Sum block becomes 1. In the second iteration, the Memory block output becomes 1. Add a signal
breakpoint to the output of the Memory block to pause simulation when the value is greater than 0.

1 To navigate inside the while-iterator subsystem, double-click the block in the model.
2 Right-click the output signal of the Memory block.
3 From the context menu, select Add Breakpoint.

By default, clicking a signal line during simulation toggles whether the signal has a port value
label. If you click the signal line to add a breakpoint and the port value label disappears, click the
signal again to add the port value label back. The port value label shows no data yet until the
block that produces the signal executes again. The software does not retain data for port value
labels when they are removed.
4 In the Add Breakpoint dialog box, configure the signal breakpoint condition so the simulation
pauses when the signal value becomes greater than 0. From the drop-down list, select > and then
enter 0 in the box.

37-12
Debug Simulation of Iterator Subsystem

To progress simulation directly to the first time the while-iterator subsystem executes more than
once, disable the breakpoint on the Pulse signal.

1 In the Debug tab, click Breakpoints List.


2 In the Breakpoints List, in the Enabled column, clear the check box for the row that corresponds
to the breakpoint on the Pulse signal.

To progress the simulation until the next time step that the while-iterator subsystem executes more
than once, in the Debug tab, click Continue. The simulation runs to a simulation time of 3.5
seconds and pauses on the breakpoint on the Memory block output signal. The port value label for
the Memory block output shows a value of 1. The other port value labels display the value from the
last time the while-iterator subsystem executed.

37-13
37 Debug Simulations

Continue clicking Step Over to step through the algorithm one block at a time. The while-iterator
subsystem continues to execute so long as the cumulative sum is less than the input value from the
Sine Wave block.

Because the simulation pauses on the breakpoint in each iteration, you can use the Continue button
to step through the simulation one iteration at a time.

On the 13th iteration, the cumulative sum becomes 91, which is greater than the input value of 86.6.
The port value label for the output of the Relational Operator block shows a value of true because
the block has not executed yet.

When you click Step Over once more, the Relational Operator block executes, and the simulation
exits the while-iterator subsystem loop. The model canvas navigates back to the top-level view of the
model. If you click Step Over once more, the Outport block executes, and the plot in the Dashboard
Scope block updates to show the value from this time step.

37-14
Debug Simulation of Iterator Subsystem

View Execution Order


To understand how the software steps from one block to the next, you can view the execution order
on the block diagram while a simulation is paused. The execution order indicates the order in which
the software executes each block during each major time step. Viewing the execution order can help
you understand the behavior of your model and the progression of the simulation as you step block by
block.

To advance the simulation to the next time step where the while-iterator subsystem executes more
than once, click Continue. The Simulink Editor navigates inside the while-iterator subsystem, and
the simulation pauses on the Memory block.

To display the execution order, on the Debug tab, in the Diagnostics section, click Information
Overlays. Then, under Blocks, click Execution Order. The Execution Order viewer opens on the
right of the Simulink Editor with the current task selected. The Execution Order viewer highlights
and annotates the model to indicate the blocks involved in the selected task and their order of
execution.

37-15
37 Debug Simulations

When you first open the Execution Order viewer, the execution order highlighting obscures the green
debugging highlight that indicates where the simulation is paused within the time step. After you
advance the simulation, the green debugging highlight overlays the execution order highlighting. For
example, click Step Over. The simulation pauses on the Sum block, and the green highlight around
the Sum block overlays the highlighting from the Execution Order viewer. The Execution Order
viewer also highlights the Sum block in the Execution Order Block List.

You can continue to step through the simulation with the execution order highlighting visible in the
block diagram, or you can clear the execution order highlighting to focus on other aspects of
debugging. To clear the execution order highlighting, in the Execution Order viewer, click Clear

Highlighting . To view the execution order again in the block diagram, in the Execution Order
viewer, select the task for which you want to view the execution order.

The execution order highlighting overlays the green debugging highlight that indicates where the
simulation is paused, even after you advance the simulation.

37-16
Debug Simulation of Iterator Subsystem

End Simulation Debugging Session


When you are done analyzing and debugging your model, you can end the simulation debugging
session in one of several ways, depending on what you plan to do next.

To continue the simulation from the current time point and retain the set of breakpoints configured in
the model, disable all breakpoints.

1 To open the Breakpoints List, on the Debug tab, click Breakpoints List.
2 In the Breakpoints List, use the check boxes in the Enable column or the Enable or disable all
breakpoints button to disable all the breakpoints.
3 To resume the simulation, click Continue.

To continue the simulation from the current time point without retaining breakpoints, remove all
breakpoints from the model.

1 To clear all breakpoints in the model, on the Debug tab, click the Add Breakpoint button arrow
and select Clear All Breakpoints.
2 To resume simulation, click Continue.

To stop the simulation at the current time point, in the Simulink Toolstrip, on the Debug tab, click
Stop.

See Also
Tools
Breakpoints List | Simulation Stepping Options

Blocks
While Iterator Subsystem | While Iterator | For Iterator Subsystem | For Iterator

Related Examples
• “Iterate Subsystem Execution with While Iterator and For Iterator Subsystems” on page 10-29

37-17
38

Accelerating Models

• “What Is Acceleration?” on page 38-2


• “How Acceleration Modes Work” on page 38-3
• “Code Regeneration in Accelerated Models” on page 38-7
• “Choosing a Simulation Mode” on page 38-10
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “Interact with the Acceleration Modes Programmatically” on page 38-22
• “Comparing Performance” on page 38-25
• “How to Improve Performance in Acceleration Modes” on page 38-30
38 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 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.

Accelerator mode works with any model, but performance decreases if a model contains blocks that
do not support acceleration. Accelerator mode supports the Simulink debugging programmatic
interface and the Simulink Profiler. These tools help with debugging and determining relative
performance of various parts of your model. For more information, see emode and “How Simulink
Profiler Captures Performance Data” on page 34-5.

Rapid accelerator mode works with only those models that contain blocks that support code
generation of a standalone executable. For this reason, rapid accelerator mode does not support
debugging options or the Simulink Profiler. However, this mode generally results in faster execution
than accelerator mode. When used with dual-core processors, 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
38-25.

To optimize your model and achieve faster simulation automatically using Performance Advisor, see
“Automated Performance Optimization”.

To employ modeling techniques that help achieve faster simulation, see “Manual Performance
Optimization”.

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “How Acceleration Modes Work” on page 38-3
• “Choosing a Simulation Mode” on page 38-10
• “Comparing Performance” on page 38-25

38-2
How Acceleration Modes Work

How Acceleration Modes Work


In this section...
“Overview” on page 38-3
“Normal Mode” on page 38-3
“Accelerator Mode” on page 38-4
“Rapid Accelerator Mode” on page 38-5

Overview
The accelerator and rapid accelerator modes use portions of the Simulink Coder product to create an
executable.

The accelerator and rapid accelerator 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. Use Simulink Coder 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.

38-3
38 Accelerating Models

Accelerator Mode
By default, accelerator mode uses Just-in-Time (JIT) acceleration to generate an execution engine in
memory instead of generating C code or MEX files. You can also have your model fall back to the
classic accelerator mode, in which Simulink generates and links code into a C-MEX S-function.

In accelerator mode, the model methods are separate from the Simulink software and are part of the
acceleration target code, which is used in later simulations.

Simulink checks that the acceleration target code is up to date before reusing it. For more
information, see “Code Regeneration in Accelerated Models” on page 38-7 .

There are two modes of operation in accelerator mode.

Just-In-Time Accelerator Mode

In this default mode, Simulink generates an execution engine in memory for the top-level model only
and not for referenced models. As a result, a C compiler is not required during simulation.

Because the acceleration target code is in memory, it is available for reuse as long as the model is
open. Simulink also serializes the acceleration target code so that the model does not need rebuilding
when it is opened.

Classic Accelerator Mode

If you want to simulate your model using the classic, C-code generating, accelerator mode, run the
following command:

set_param(0,'GlobalUseClassicAccelMode','on');

In this mode, Simulink generates and links code into a shared library, which communicates with the
Simulink software. The target code executes in the same process as MATLAB and Simulink.

38-4
How Acceleration Modes Work

Rapid Accelerator Mode


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 “External Mode Communication” (Simulink Coder)) to communicate with
Simulink.

MATLAB and Simulink run in one process, and if a second processing core is available, the
standalone executable runs there.

38-5
38 Accelerating Models

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “Choosing a Simulation Mode” on page 38-10
• “Code Regeneration in Accelerated Models” on page 38-7
• “Comparing Performance” on page 38-25

38-6
Code Regeneration in Accelerated Models

Code Regeneration in Accelerated Models

In this section...
“Determine If the Simulation Will Rebuild” on page 38-7
“Parameter Tuning in Rapid Accelerator Mode” on page 38-7

Changing the structure of your model causes 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. Changing the value of a tunable parameter does not trigger a rebuild.

Determine 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 checksum is an array of four integers computed
using an MD5 checksum algorithm based on attributes of the model and the blocks it contains.

1 Use the Simulink.BlockDiagram.getChecksum function to obtain the checksum for your


model. For example:

cs1 = Simulink.BlockDiagram.getChecksum('myModel');
2 Obtain a second checksum after you have altered your model. The code regenerates if the new
checksum does not match the previous checksum.
3 Use the information in the checksum to determine why the simulation target rebuilt.

For a detailed explanation of this procedure, see “Determine Why Simulink Accelerator Is
Regenerating Code”.

Parameter Tuning in Rapid Accelerator Mode


In model rebuilds, rapid accelerator mode handles block diagram and runtime parameters differently
from other parameters.

Tuning Block Diagram Parameters

You can change some block diagram parameters during simulation without causing a rebuild. Tune
these parameters using the set_param function or using the Model Configuration Parameters
dialog box. These block diagram parameters include:

Solver Parameters
AbsTol MaxNumMinSteps RelTol
ConsecutiveZCsStepRelTol MaxOrder StartTime
ExtrapolationOrder MaxStep StopTime
InitialStep MinStep ZCDetectionTol
MaxConsecutiveMinStep OutputTimes
MaxConsecutiveZCs Refine

38-7
38 Accelerating Models

Loading and Logging Parameters


ConsistencyChecking MinStepSizeMsg SaveTime
Decimation OutputOption StateSaveName
FinalStateName OutputSaveName TimeSaveName
LimitDataPoints SaveFinalState
LoadExternalInput SaveFormat
MaxConsecutiveZCsMsg SaveOutput
MaxDataPoints SaveState

Tuning Runtime Parameters

To tune runtime parameters for maximum acceleration in rapid accelerator mode, follow this
procedure which yields better results than using set_param for the same purpose:

1 Collect the runtime parameters in a runtime 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 function, use the
RapidAcceleratorParameterSets and RapidAcceleratorUpToDateCheck parameters.

All other parameter changes can necessitate a rebuild of the model.

Parameter Changes Passed Directly to sim Passed Graphically via Block


function Diagram or via set_param
function
Runtime Does not require rebuild Can require rebuild
Block diagram (logging Does not require rebuild Does not require rebuild
parameters)

For information about parameter tunability limitations with accelerated simulation modes, see
“Tunability Considerations and Limitations for Other Modeling Goals” on page 41-36.

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “How to Improve Performance in Acceleration Modes” on page 38-30
• “Optimize, Estimate, and Sweep Block Parameter Values” on page 41-38
• “What Is Acceleration?” on page 38-2
• “Choosing a Simulation Mode” on page 38-10
• “How Acceleration Modes Work” on page 38-3

38-8
Code Regeneration in Accelerated Models

• “Comparing Performance” on page 38-25

38-9
38 Accelerating Models

Choosing a Simulation Mode


In this section...
“Simulation Mode Tradeoffs” on page 38-10
“Comparing Modes” on page 38-11
“Decision Tree” on page 38-12

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 offers the greatest flexibility for making model adjustments and displaying results, but
it runs the slowest.

Accelerator mode lies between normal and rapid accelerator modes in performance and in interaction
with your model. Accelerator mode does not support most runtime diagnostics.

Rapid accelerator mode runs the fastest, but this mode does not support the debugging utilities or
the Simulink Profiler, and works only with those models for which C code or MEX file is available for
all of the blocks in the model.

38-10
Choosing a Simulation Mode

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 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 “Choose
Simulation Modes for Model Hierarchies” on page 8-45.

Comparing Modes
The following table compares the characteristics of normal mode, accelerator mode, and rapid
accelerator mode.

If you want to... Then use this mode...


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, stop time
without rebuilding
Change block tunable parameters such as gain

For more information on configuration set parameters which can be modified without requiring rebuild, see
“Code Regeneration in Accelerated Models” on page 38-7
Model Requirement
Accelerate your model even if C code or MEX file are not
used for all blocks
Support Interpreted MATLAB Function blocks

Support Non-Inlined MATLAB language or Fortran S-


Functions
Permit algebraic loops in your models

Use debugging options or the Simulink Profiler

Have your model include C++ code

Data Display

38-11
38 Accelerating Models

If you want to... Then use this mode...


Normal Accelerator Rapid
Accelerator
Use scopes and signal viewers See “Behavior of
Scopes and
Viewers with
Rapid
Accelerator
Mode” on page
38-16
Use scopes and signal viewers when simulating your
model programmatically

Note Scopes and viewers do not update if you run your model programmatically in rapid accelerator
mode.

Decision Tree
Use this decision tree to select between accelerator mode and rapid accelerator mode.

See “Comparing Performance” on page 38-25 to understand how effective acceleration will be in
improving the performance of your model.

38-12
Choosing a Simulation Mode

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Interact with the Acceleration Modes Programmatically” on page 38-22
• “Code Regeneration in Accelerated Models” on page 38-7
• “How Acceleration Modes Work” on page 38-3

38-13
38 Accelerating Models

Design Your Model for Effective Acceleration

In this section...
“Select Blocks for Accelerator Mode” on page 38-14
“Select Blocks for Rapid Accelerator Mode” on page 38-14
“Control S-Function Execution” on page 38-15
“Accelerator and Rapid Accelerator Mode Data Type Considerations” on page 38-15
“Behavior of Scopes and Viewers with Rapid Accelerator Mode” on page 38-16
“Factors Inhibiting Acceleration” on page 38-16

Select Blocks for Accelerator Mode


Accelerator 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, 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
• Outport (root level only)
• Scope
• To File
• To Workspace

The following blocks can cause poor simulation runtime performance when run in the default JIT
accelerator mode.

• Transport Delay
• Variable Transport Delay

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 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 Simulink Real-Time product, or those targeting
Freescale® MPC555

38-14
Design Your Model for Effective Acceleration

Control S-Function Execution

Note In the default JIT accelerator mode, inlining of user-written TLC S-Functions is not supported.
If you run a model containing TLC S-Functions in the JIT accelerator mode, there is a possibility of
the execution speed reducing. The code generation speed, however, will be high due to JIT
acceleration.

Inlining S-functions using the Target Language Compiler increases performance with the classic
accelerator mode by eliminating unnecessary calls to the Simulink API. By default, however, the
classic 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 the target, it cannot access the target I/O registers and so would fail when
attempting to do so.

To direct the classic 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);
}

Rapid accelerator mode will make use of the MEX file if the S-Function C file is not present in the
same folder.

Note To use the .c or .cpp code for your S-Function, ensure that they are in the same folder as the
S-Function MEX-file. Otherwise, you can include additional files to an S-function or bypass the path
limitation by using the rtwmakecfg.m file. For more information, see Use rtwmakecfg.m API to
Customize Generated Makefiles (Simulink Coder).

Accelerator and Rapid Accelerator Mode Data Type Considerations


• Accelerator mode supports fixed-point signals and vectors up to 128 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 ignores the Log fixed-point data as a fi object parameter for the To
Workspace block.
• Rapid accelerator mode supports bus objects as parameters.
• Accelerator mode and rapid accelerator mode store integers as compactly as possible.
• Fixed-Point Designer does not collect min, max, or overflow data in the accelerator or rapid
accelerator modes.

38-15
38 Accelerating Models

• Accelerator mode supports a limited set of runtime diagnostics, including the assertion block.
• Rapid accelerator mode supports a limited set of runtime diagnostics, including the assertion
block.

Behavior of Scopes and Viewers with Rapid Accelerator Mode


Running the simulation programmatically or interactively determines the behavior of scopes and
viewers in rapid accelerator mode.

Scope or Viewer Type Simulation Run Interactively Simulation Run


Programmatically
Simulink Scope block Same support as normal mode • Logging is supported
• Scope window is not updated
Simulink signal viewer Graphics are updated, but logging is Not supported
scopes not supported
Other signal viewer Support limited to that available in Not supported
scopes external mode
Signal logging Supported. Supported.
Visualizers with inputs Data not visualized during Data not visualized during
from logging simulation. simulation.

(Such as the Simulation


Data Inspector or Logic
Analyzer)
Stateflow charts Same support for chart animation as Not supported
normal mode

Note Although scopes and viewers do not update when you run rapid accelerator simulations
programmatically, they do update when you run the simulation interactively. “Run Acceleration Mode
from the User Interface” on page 38-19 shows how to run rapid accelerator mode from the menu.
“Interact with the Acceleration Modes Programmatically” on page 38-22 shows how to run the
simulation programmatically.

Factors Inhibiting Acceleration


• You cannot use accelerator mode 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.
• In some cases, changes associated with external or custom code do not cause accelerator or rapid
accelerator simulation results to change. These include:

• TLC code
• S-function source code, including rtwmakecfg.m files
• Integrated custom code

38-16
Design Your Model for Effective Acceleration

• S-Function Builder

In such cases, consider force regeneration of code for a top model. Alternatively, you can force
regeneration of top model code by deleting code generation folders, such as slprj or the
generated model code folder.

Note With JIT acceleration, the acceleration target code is in memory. It is therefore available for
reuse as long as the model is open, even if you delete the slprj folder.

Rapid Accelerator Mode Limitations

• Rapid accelerator mode does not support:

• Algebraic loops.
• Targets written in C++.
• Interpreted MATLAB Function blocks.
• Noninlined MATLAB language or Fortran S-functions. You must write S-functions in C or inline
them using the Target Language Compiler (TLC) or you can also use the MEX file. For more
information, see “Write Fully Inlined S-Functions” (Simulink Coder).
• Debugging utilities or Simulink Profiler.
• Run time objects for Simulink.RunTimeBlock and Simulink.BlockCompOutputPortData blocks.
• 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
• You cannot pause a simulation in rapid accelerator mode.
• In certain cases, changing block parameters can result in structural changes to your model that
change the model checksum. An example of such a change is changing the number of delays in a
DSP simulation. In these cases, you must regenerate the code for the model. See “Code
Regeneration in Accelerated Models” on page 38-7 for more information.
• For root inports, when you specify the minimum and maximum values that the block should
output, rapid accelerator mode does not recognize these limits during simulation.
• In rapid accelerator mode, To File or To Workspace blocks inside function-call subsystems do not
generate any logging files if the function-call port is connected to Ground or unconnected.
• Rapid accelerator mode does not support systems that run RHEL / CentOS 6.x or 7.x.
• In rapid accelerator mode, struct/enum redefinition occurs when model has custom code types.

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

38-17
38 Accelerating Models

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 “Construction of Generated
Identifiers” (Simulink Coder). Additional keywords that apply only to the accelerator and rapid
accelerator modes are:

muDoubleScalarAbs muDoubleScalarCos muDoubleScalarMod


muDoubleScalarAcos muDoubleScalarCosh muDoubleScalarPower
muDoubleScalarAcosh muDoubleScalarExp muDoubleScalarRound
muDoubleScalarAsin muDoubleScalarFloor muDoubleScalarSign
muDoubleScalarAsinh muDoubleScalarHypot muDoubleScalarSin
muDoubleScalarAtan muDoubleScalarLog muDoubleScalarSinh
muDoubleScalarAtan2 muDoubleScalarLog10 muDoubleScalarSqrt
muDoubleScalarAtanh muDoubleScalarMax muDoubleScalarTan
muDoubleScalarCeil muDoubleScalarMin muDoubleScalarTanh

See Also

Related Examples
• “Perform Acceleration” on page 38-19
• “How to Improve Performance in Acceleration Modes” on page 38-30
• “What Is Acceleration?” on page 38-2
• “How Acceleration Modes Work” on page 38-3
• “Choosing a Simulation Mode” on page 38-10

38-18
Perform Acceleration

Perform Acceleration
In this section...
“Customize the Build Process” on page 38-19
“Run Acceleration Mode from the User Interface” on page 38-19
“Making Run-Time Changes” on page 38-20
“Switching Solvers between Runs” on page 38-21

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 On the Modeling tab, under Setup, click Model Settings.


2 In the Configuration Parameters dialog box, from the Compiler optimization level drop-down
list, select Optimizations on (faster runs).

Code generation takes longer with this option, but the 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 Location of Generated Code

By default, accelerator mode places the generated code in a subfolder of the working folder called
slprj/accel/modelname (for example, slprj/accel/f14). To change the name of the folder into
which accelerator mode writes generated code:

1 In the Simulink Editor window, on the Modeling tab, select Environment > Simulink
Preferences.
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 on the Simulation tab, in the Simulate section, select
Accelerator or Rapid Accelerator from the drop-down list. Then start the simulation.

The following example shows how to accelerate the already opened f14 model using accelerator
mode:

1 On the Simulation tab, in the Simulate section, select Accelerator from the drop-down list.

38-19
38 Accelerating Models

2 On the Simulation tab, click Run.

The accelerator and rapid accelerator modes first check to see if code was previously compiled
for your model. If code was created previously, 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 38-7.

Accelerator mode places the generated code in a subfolder of the working folder called slprj/
accel/modelname (for example, slprj/accel/f14). If you want to change this path, see
“Changing the Location of Generated Code” on page 38-19.

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

38-20
Perform Acceleration

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.

Switching Solvers between Runs


You can switch variable-step solvers between runs and Simulink will automatically determine if a
solver change will trigger a rebuild, based on the mathematical structure of the model, such as
whether the model is an ordinary differential equation (ODE) or a differential algebraic equation
(DAE) model, if the solver needs a Jacobian, whether it handles mass matrices, or if the model
contains rate limiter blocks.

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Interact with the Acceleration Modes Programmatically” on page 38-22
• “How Acceleration Modes Work” on page 38-3
• “Code Regeneration in Accelerated Models” on page 38-7

38-21
38 Accelerating Models

Interact with the Acceleration Modes Programmatically


In this section...
“Why Interact Programmatically?” on page 38-22
“Build JIT Accelerated Execution Engine” on page 38-22
“Control Simulation” on page 38-22
“Simulate Your Model” on page 38-22
“Customize the Acceleration Build Process” on page 38-23

Why Interact Programmatically?


You can build an accelerated model, select the simulation mode, and run the simulation
programmatically. 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
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 JIT Accelerated Execution Engine


With the accelbuild command, you can build a JIT accelerated execution engine 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 programmatically 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 using accelerator mode, you would use:

set_param('myModel','SimulationMode','accelerator')

However, a preferable method is to specify the simulation mode using the sim function:
simOut = sim('myModel','SimulationMode','accelerator');

You can use bdroot 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 using rapid accelerator mode, you would use:

simOut = sim(bdroot,'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:

38-22
Interact with the Acceleration Modes Programmatically

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 function 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 38-7
for a description), the sim function 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.

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 function again to simulate 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 38-19 for details on why doing so might be advantageous.

Controlling the Build Process

Use SimCompilerOptimization to set the degree of optimization used by the compiler when
generating code for acceleration. The permitted values are on or off. The default is off.

Enter the following in the Command Window to turn on compiler optimization:

set_param('myModel','SimCompilerOptimization','on')

When SimCompilerOptimization is set to on in JIT accelerated mode, the simulation time for
some models improves, while the build time can become slower.

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 in the Command Window to turn on verbose build:

set_param('myModel','AccelVerboseBuild','on')

38-23
38 Accelerating Models

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “How Acceleration Modes Work” on page 38-3
• “Choosing a Simulation Mode” on page 38-10
• “Code Regeneration in Accelerated Models” on page 38-7

38-24
Comparing Performance

Comparing Performance

In this section...
“Performance When Target Must Be Rebuilt” on page 38-25
“Performance When Targets Are Up to Date” on page 38-26
“Analyze Performance of Simulation Modes” on page 38-26

When simulation execution time exceeds the time required for code generation, accelerator and rapid
accelerator simulation modes give speed improvement compared to normal mode. 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 these blocks
also simulate through code generation in normal mode.

Including tunable parameters in your model can also increase the simulation time.

The figure shows the relative performance of normal mode, accelerator mode, and rapid accelerator
mode simulations in general terms for a hypothetical model.

Performance When Target Must Be Rebuilt


The solid lines, labeled all targets out of date, in the figure show performance when the target code
must be rebuilt. For this hypothetical model, the time scale is on the order of minutes. However, the
time scale could be longer for more complex models.

38-25
38 Accelerating Models

Compiling a model in normal mode generally requires less time than building the accelerator target
or the rapid accelerator executable. For small simulation stop times, normal mode results in quicker
overall simulations compared to the accelerator and rapid accelerator modes.

The crossover point where accelerator mode or rapid accelerator mode results in faster overall
simulation depends on the complexity and content of your model. For example, models that contain
large numbers of blocks that use interpreted code might not run much faster in accelerator mode
than they would in normal mode unless the simulation stop time is very large. For more information,
see “Select Blocks for Accelerator Mode” on page 38-14. Similarly, models with a large number of
Stateflow charts or MATLAB Function blocks might not show much speed improvement over normal
mode unless the simulation stop time is large. You can speed up the simulation of models with
Stateflow or MATLAB Function blocks through code generation.

The figure represents a model with a large number of Stateflow charts or MATLAB Function blocks.
The curve labeled Normal would have a much smaller initial elapsed time than shown if the model
did not contain these blocks.

Performance When Targets Are Up to Date


The dashed lines, labeled all targets up to date, in the figure show that the time to determine
whether the accelerator target or the rapid accelerator executable is up to date is significantly
smaller than the time required to generate code, which is represented by the solid lines, labeled 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 once and use it to simulate your model
with a series of gain settings. This method is especially efficient for the accelerator or rapid
accelerator modes because this type of change does not result in the target code being regenerated.
The target code is generated the first time the model runs, but on subsequent runs, the software
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. Subsequent runs of your model might
simulate faster in accelerator or rapid accelerator mode when compared to normal mode, even for
small stop times.

Analyze Performance of Simulation Modes

To see the effect of using accelerator or rapid accelerator mode for simulations of your model, you
can run equivalent simulations using different simulation modes. Simulate the model in a way that
returns the results as a single Simulink.SimulationOutput object that includes simulation
metadata. That way, you can inspect the timing information captured in the simulation metadata for
each simulation to analyze the performance of each simulation mode.

This example uses Simulink.SimulationInput objects to configure model parameter values to


use for three simulations of the model sldemo_fuelsys. For more information about the model, see
“Model Fault-Tolerant Fuel Control System”.
model = "sldemo_fuelsys";

To configure the baseline simulation, create a Simulink.SimulationInput object.

38-26
Comparing Performance

simIn = Simulink.SimulationInput(model);

The SimulationInput object stores parameter values to use in the simulation. The parameter
values on the object are applied for the simulation and reverted at the end of simulation so that the
model remains unchanged.

Set the stop time to 10000. Set the simulation mode to Normal.

simIn = setModelParameter(simIn,"StopTime","10000");
simIn = setModelParameter(simIn,"SimulationMode","normal");

To capture baseline timing information, simulate the model.

simOut = sim(simIn);

The simulation returns results as a single Simulink.SimulationOutput object that contains all
logged data and simulation metadata. The metadata is stored as a Simulink.SimulationMetadata
object that contains information about the simulation, including a structure, TimingInfo, that
contains timing information.

normalMode = simOut.SimulationMetadata.TimingInfo;

From the timing information, extract the initialization time, execution time, and total elapsed time for
the simulation.

normalInit = normalMode.InitializationElapsedWallTime;
normalExec = normalMode.ExecutionElapsedWallTime;
normalTotal = normalMode.TotalElapsedWallTime;

Simulate the model again using rapid accelerator mode. The first time you simulate a model in rapid
accelerator mode, the rapid accelerator target builds during the initialization phase.

simIn = setModelParameter(simIn,"SimulationMode","rapid");
simOut = sim(simIn);

### Building the rapid accelerator target for model: sldemo_fuelsys


### Successfully built the rapid accelerator target for model: sldemo_fuelsys

Build Summary

Top model rapid accelerator targets built:

Model Action Rebuild Reason


================================================================================================
sldemo_fuelsys Code generated and compiled. Code generation information file does not exist.

1 of 1 models built (0 models already up to date)


Build duration: 0h 0m 38.279s

Access the timing information for the first rapid accelerator simulation. Then, extract the
initialization time, execution time, and total elapsed time for the simulation.

rapidAccel = simOut.SimulationMetadata.TimingInfo;
rapidBuildInit = rapidAccel.InitializationElapsedWallTime;
rapidBuildExec = rapidAccel.ExecutionElapsedWallTime;
rapidBuildTotal = rapidAccel.TotalElapsedWallTime;

38-27
38 Accelerating Models

Simulate again to see the benefit of rapid accelerator mode for a simulation that does not build the
rapid accelerator target.

simOut = sim(simIn);

Build Summary

0 of 1 models built (1 models already up to date)


Build duration: 0h 0m 2.684s

Access the timing information for the rapid accelerator simulation that ran without building the
target. Then, extract the initialization time, the execution time, and the total elapsed time for the
simulation.

rapidAccelNoRebuild = simOut.SimulationMetadata.TimingInfo;
rapidInit = rapidAccelNoRebuild.InitializationElapsedWallTime;
rapidExec = rapidAccelNoRebuild.ExecutionElapsedWallTime;
rapidTotal = rapidAccelNoRebuild.TotalElapsedWallTime;

Build a table to compare the timing for each simulation.

InitializationTime = [normalInit;rapidBuildInit;rapidInit];
ExecutionTime = [normalExec;rapidBuildExec;rapidExec];
TotalSimulationTime = [normalTotal;rapidBuildTotal;rapidTotal];

simNames = ["Normal Mode";"Rapid Accelerator";"Rapid Accelerator No Rebuild"];


timingTable = table(TotalSimulationTime,InitializationTime, ...
ExecutionTime,RowNames=simNames);

In the first rapid accelerator simulation, the initialization time increases because the rapid
accelerator target builds during the initialization phase. For this model and simulation duration, using
rapid accelerator mode reduces the execution time so much that the first rapid accelerator simulation
is still faster than using normal mode.

timingTable

timingTable=3×3 table
TotalSimulationTime InitializationTime ExecutionTime
___________________ __________________ _____________

Normal Mode 108.91 12.411 96.437


Rapid Accelerator 68.44 40.962 26.152
Rapid Accelerator No Rebuild 17.403 3.387 13.886

See Also
Simulink.SimulationInput | Simulink.SimulationOutput

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Perform Acceleration” on page 38-19
• “Interact with the Acceleration Modes Programmatically” on page 38-22
• “How to Improve Performance in Acceleration Modes” on page 38-30

38-28
Comparing Performance

• “How Acceleration Modes Work” on page 38-3


• “Choosing a Simulation Mode” on page 38-10

38-29
38 Accelerating Models

How to Improve Performance in Acceleration Modes


In this section...
“Techniques” on page 38-30
“C Compilers” on page 38-30

Techniques
To get the best performance when accelerating your models:

• Verify that the Configuration Parameters dialog box settings are as follows:

Set... To...
Solver data inconsistency none
Array bounds exceeded none
Signal storage reuse selected
• Disable Stateflow debugging and animation.
• 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. For details, see “Customize
the Build Process” on page 38-19.

C Compilers
On computers running the Microsoft Windows operating system, the accelerator and rapid
accelerator modes use the default 64-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.

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:

https://www.mathworks.com/support/compilers/current_release/

See Also

Related Examples
• “Design Your Model for Effective Acceleration” on page 38-14
• “Interact with the Acceleration Modes Programmatically” on page 38-22
• “How Acceleration Modes Work” on page 38-3
• “Choosing a Simulation Mode” on page 38-10

38-30
How to Improve Performance in Acceleration Modes

• “Comparing Performance” on page 38-25

38-31
39

Create Apps to Control Simulations


Using App Designer

• “Create App for Simulink Model” on page 39-2


• “Connect UI Components to Simulink Model Elements” on page 39-8
39 Create Apps to Control Simulations Using App Designer

Create App for Simulink Model

This example shows how to use App Designer to interactively develop an app that runs and visualizes
the results of a bouncing ball simulation without writing any code. In this example, you build the app
using these steps:

1 Create a new blank app for a Simulink® model, and associate the app with the bouncing ball
model.
2 Design the app by adding UI components and connecting them to the associated model elements.
For example, use UI components to start and stop the simulation, tune model variables, and
visualize simulation signals.
3 Run the app and interact with the simulation.

Open the example to make the bouncing ball model available in your current folder.

openExample("simulink/CreateSimpleAppForSimulinkModelExample")

Create App with Associated Model

Create a new blank app for a Simulink model. You can do this in multiple ways, depending on where
you are working:

• From Simulink — Open the bouncingBall.slx model in Simulink. In the Apps tab, select
Design App > Create App for Model.
• From App Designer — Open App Designer. On the App Designer start page, in the Simulink Apps
section, click Blank App for Simulink Model. Select the bouncingBall.slx model in the
Associate Simulink Model dialog box.

In both cases, a new app opens in App Designer and the bouncing ball model is automatically
associated with the app.

Design App

App Designer has a set of Simulink UI components that control common simulation tasks, such as
starting and stopping the simulation and showing the simulation progress. These Simulink
components are automatically connected with the associated model. You can access these
components in the Component Library, in the Simulink section.

39-2
Create App for Simulink Model

You can also use general UI components and manually connect the components to elements of your
model.

Start and Stop Simulation

Start, stop, and pause the simulation from your app by using a Simulation Controls component.
Drag the component from the Simulink section of the Component Library onto the canvas.

App Designer automatically configures the UI component to interface with the model associated with
the app.

Tune Model Variables

Provide a way to tune a model variable from the app while the simulation is running by connecting a
UI component to the variable. For this example, create a slider to tune the coefficient of restitution
variable, which represents the elasticity of the bouncing ball.

First, drag a Slider component from the Component Library onto the canvas. Configure the slider
limits and value to align with the variable. Select the slider and modify properties in the Component
Browser:

• Specify Limits as [-1 0].


• Specify Value as -0.8.

Then, connect the slider to the model variable by creating a binding. Right-click the slider and select
Add Binding. The Simulink model opens in connect mode. Click the Coefficient of Restitution block
and select the model variable from the Connect options.

39-3
39 Create Apps to Control Simulations Using App Designer

When you add a binding, the slider is connected to the variable. When the app is running, if the value
of the slider changes, the value of the model variable updates to match.

Finally, update the slider label to describe the variable it is connected to.

Visualize Simulation Signals

Visualize signals in the app while the simulation is running by using a time scope UI component. For
this example, visualize the position and velocity of the bouncing ball.

First, drag a Time Scope component from Simulink section of the Component Library onto the
canvas.

Then, connect the time scope to the Position signal by creating a binding. Right-click the time
scope and select Add Binding. The Simulink model opens in connect mode. Click the Position
signal and select the model variable from the Connect options.

Follow the same steps to connect the time scope to the Velocity signal by creating a binding.

App Designer apps support binding only to logged signals. For more information about how to log
signals, see “Save Signal Data Using Signal Logging” on page 78-42.

You can view the bindings for a component by selecting the component and opening the Bindings
pane in the Component Browser. You can also use this pane to delete or modify bindings.

39-4
Create App for Simulink Model

After you create the bindings, configure the time scope display to provide information about the
plotted signals. Select the time scope and modify properties in the Component Browser:

• Select LegendVisible.
• Specify LegendNames as Position,Velocity.
• Specify Title as Position and Velocity of Bouncing Ball.

39-5
39 Create Apps to Control Simulations Using App Designer

Run App

To run the app, click Run in the App Designer toolstrip. To start the simulation once the app is
running, click Run on the simulation controls. Tune the coefficient of restitution using the slider and
explore the result using the time scope.

39-6
Create App for Simulink Model

See Also
uitimescope | uislider | App Designer

Related Examples
• “Connect UI Components to Simulink Model Elements” on page 39-8

39-7
39 Create Apps to Control Simulations Using App Designer

Connect UI Components to Simulink Model Elements

In this section...
“Connect UI Components to Model Variables” on page 39-8
“Connect UI Components to Signals” on page 39-9
“Modify Bindings in App” on page 39-9

When you create a custom app to interface with a Simulink model, you can connect specific UI
components in the app to model elements by creating a binding. You can use connected UI
components to control and display those model elements. For an example of an app with an
associated model, see “Create App for Simulink Model” on page 39-2.

App Designer has Simulink UI components that perform specific tasks that are common to many
simulations. For example, you can use the Simulation Controls component to start, stop, and pause
a simulation from an app. When you add a Simulink UI component to your app, App Designer
automatically configures the component to interface with the model associated with the app.

To further customize your app behavior, you can use a larger set of UI components to control
elements in the model associated with your app by creating bindings. For example, you can create a
binding to use a slider to tune a model variable or a time scope to display a signal.

Connect UI Components to Model Variables


To tune model variables from your app while you run a simulation, add bindings to connect UI
components in your app to variables in your model. You can connect to variables in the model
workspace or in the base workspace. For example, you can use a slider to interactively change the
value of a model variable.

You can use UI components that allow a user to set numeric values, such as spinners, sliders, and
numeric edit fields, to tune model variables. With your app open in App Designer, select the UI
component. Add a new binding using any of these methods:

• On the App Designer canvas, right-click the UI component and select Add Binding.

In the Component Browser, select the Bindings tab and click the button.
• In the Simulink tab of the App Designer toolstrip, click the Add Binding button.

In all cases, the Simulink model opens in connect mode. Click a block that uses a variable, and select
the variable from the connection options. You can add a binding to a variable in either the base
workspace or the model workspace.

39-8
Connect UI Components to Simulink Model Elements

When you run the app and start the simulation, interactively changing the value of the UI component
updates the value of the variable to match. If the data type of the component value is different than
the data type of the variable, the binding attempts to convert the data.

Connect UI Components to Signals


To visualize signal data in your app while you run a simulation, add bindings to connect UI
components in your app to logged signals in your model. For example, you can plot signal data on a
time scope component in your app.

You can use UI components that display information, such as time scopes, gauges, and labels, to
visualize signals. With your app open in App Designer, select the UI component. Add a new binding
using any of these methods:

• On the App Designer canvas, right-click the UI component and select Add Binding.

In the Component Browser, select the Bindings tab and click the button.
• In the Simulink tab of the App Designer toolstrip, click the Add Binding button.

In all cases, the Simulink model opens in connect mode. To choose a signal, use these steps:

• Click a logged signal or a block with a logged signal output, and select the signal from the
connection options.

• Ensure that the Signal Logging check box in the Data Import/Export pane of the Model
Settings is selected.

When you run the app and start the simulation, when the signal logs data, the UI component displays
the data.

Note App Designer creates a binding between a UI component and a signal using the fully specified
block path and port index of the signal. Therefore, if the path or index changes, you must modify the
binding.

Modify Bindings in App


You can use App Designer to view existing bindings associated with a component and to replace or
delete bindings.

With your app open in App Designer, select a UI component with a binding. In the Component
Browser, select the Bindings tab. You can use the tab to:

• View the list of bindings associated with the component.

39-9
39 Create Apps to Control Simulations Using App Designer


Create a new binding by clicking the button.

Replace an existing binding by clicking and selecting Replace.

Delete a binding by clicking and selecting Delete.

You can also view the bindings associated with a component in the App Designer canvas by selecting
a component and pointing to the binding icon for the component.

See Also
Functions
bind | findbindings

Objects
Binding

Tools
App Designer

Related Examples
• “Create App for Simulink Model” on page 39-2

39-10
Managing Blocks

11
40

Working with Blocks

• “Nonvirtual and Virtual Blocks” on page 40-2


• “Specify Block Properties” on page 40-4
• “View Signal Values Using Port Value Labels” on page 40-8
• “Control and Display Execution Order” on page 40-16
• “Access Block Data During Simulation” on page 40-31
40 Working with Blocks

Nonvirtual and Virtual Blocks

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 behavior.
• Virtual blocks help organize a model graphically. While they play no active role in the simulation,
they can affect the execution order of other blocks.

Some Simulink blocks are virtual in some circumstances and nonvirtual in others. Such blocks are
called conditionally virtual blocks.

The table lists Simulink virtual and conditionally virtual 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.
In Bus Element Virtual unless input bus is nonvirtual and contains a variable-size
signal.
Inport Always virtual.

Virtual unless the block resides in a conditionally executed or atomic


subsystem and has a direct connection to an Outport block.
Mux Always virtual.
Out Bus Element Virtual unless output bus is nonvirtual.
Outport Virtual when the block resides within any subsystem (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) for fixed-size index signal.
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.

40-2
Nonvirtual and Virtual Blocks

Block Name Condition Under Which Block Is Virtual


Trigger Virtual when the output port is not present.

See Also

More About
• “Specify Block Properties” on page 40-4
• “View Signal Values Using Port Value Labels” on page 40-8
• “Control and Display Execution Order” on page 40-16
• “Access Block Data During Simulation” on page 40-31
• “Block Libraries”

40-3
40 Working with Blocks

Specify Block Properties

For each block in a model, you can set general block properties, such as:

• A description of the block


• The block execution priority
• A block annotation
• Block callback functions

To set block properties, use the Property Inspector. You can set properties in the Properties and Info
tabs of the Property Inspector when the block is selected. Alternatively, you can use the Block
Properties dialog box.

Set Block Annotation Properties


In the Property Inspector, use the Block Annotation section to display the values of selected block
parameters in an annotation. The annotation appears below the block icon.

Enter the text of the annotation in the text box. You can use a block property token in the annotation.
The value for the property replaces the token in the annotation in the model. To display a list of
tokens that you can use in an annotation, type % in the text box. The parameters that are valid for the
selected block appear. See “Common Block Properties” and “Block-Specific Parameters”.

Suppose that you specify the following annotation text and tokens for a Product block:
Multiplication = %<Multiplication>
Sample time = %<SampleTime>

In the Simulink Editor, the block displays this annotation:

You can also create block annotations programmatically. See “Create Block Annotations
Programmatically” on page 40-7.

Specify Block Callbacks


Use the Callbacks section to specify block callbacks. Callbacks are MATLAB commands that execute
when a specific model action occurs, such as when you select or delete a block. For more information
on callbacks, see “Customize Model Behavior with Callbacks” on page 4-68.

1 Select the block whose callback you want to set.


2 In Properties tab of the Property Inspector, in the Callbacks section, select the function that
you want to assign the callback to. For example, select OpenFcn to specify a behavior for double-
clicking a block.

40-4
Specify Block Properties

3 In the text box, enter the command that you want to execute when that block function occurs.

After you assign a callback to a function, the function displays an asterisk next to it in the list.
The asterisks helps you to see the functions that have callbacks assigned to them.

Note After you add an OpenFcn callback to a block, double-clicking the block does not open the
block dialog box. Also, the block parameters do not appear in the Property Inspector when the
block is selected. To set the block parameters, select Block Parameters from the block context
menu.

Set a Block Callback Programmatically

This example shows how to use the OpenFcn callback to execute MATLAB scripts when you double-
click a block. For example, in a MATLAB script you can define variables or open a plot of simulated
data.

To create a callback programmatically, select the block to which you want to add this property. Then,
at the MATLAB command prompt, enter a command in this form:
set_param(gcb,'OpenFcn','myfunction')

In this example, myfunction represents a valid MATLAB command or a MATLAB script on your
MATLAB search path.

Specify Block Execution Order, Execution Priority and Tag


In the block properties, you can specify the block execution order, execution priority and identify the
block by assigning a value to the Tag property.

• Execution Order— Specify execution order of blocks relative to other blocks. By default, blocks
execute based on priority. You can use this property to designate blocks at the root level of a
model or inside a nonvirtual subsystem to execute first or last relative to other blocks. You can set
the block execution order through Block Properties dialog. In the Block Properties dialog, from
the Execution Order list, select First or Last. For more information, see “Set Execution Order
Property for Block to Execute First”.

These blocks are not supported for Execution Order set to First or Last:

• Virtual blocks. For more information, see “Nonvirtual and Virtual Blocks” on page 40-2.
• Blocks with control ports, such as action subsystems, enabled and triggered subsystems,
function-call subsystems, and resettable subsystems. For more information, see “Conditionally
Executed Subsystems Overview” on page 10-3.
• Initialize Function, Reset Function, Reinitialize Function, and Terminate Function blocks that
execute based on custom routines.
• Data Store Memory block.

For the first or last option in the block execution order property to work:

• Only one block can be configured to execute first or last at a single level of model hierarchy.
For example, if a Data Store Read block is set to execute first at the root-level model, another
block cannot execute first at the root level of this model.
• Connect only the Inport block to the input port of a block configured to execute first. However,
there is no limitation on which block you can connect to the output port of such a block.

40-5
40 Working with Blocks

• Connect only the Outport block to the output port of a block configured to execute last.
However, there is no limitation on which block you can be connect to the input port of such a
block.
• Blocks cannot be in an algebraic loop. The algebraic loop solver must determine the execution
order based on the algebraic variables in the loop, so specifying execution order for algebraic
loops is not supported. For more information, see “How the Algebraic Loop Solver Works” on
page 3-42.
• Blocks must be inside a system that executes in a single task. For more information, see
“Control and Display Execution Order” on page 40-16.

These limitations apply to code generated from a model containing blocks set to execute first or
last. In the generated code:

• Execution order of the blocks being set to execute first or last may not be traceable due to
optimization.
• In some cases, Simulink may deem that an extra signal copy is needed before blocks set to
execute first or after blocks set to execute last. For example, the software may add a copy of
the output signal of a block set to execute last to the root Outport block after the block set to
execute last executes.
• Priority — Specify the execution priority of the block relative to other blocks. Specify a numerical
value. A smaller number indicates a higher priority. This option is available only when the
Execution Order is set to Based on priority. For more information, see “Set Priority in
Execution Order of Blocks”.
• Tag — Specify an identifier for the block. Specify text to assign to the block Tag property. Setting
this property is useful for finding the block in the model by searching or programmatically using
find_system. See “Explore Model Hierarchy”.

Note In determining execution priority, Simulink compares the Priority of blocks only to that of
other blocks in the same block diagram, even if the block diagram is a virtual subsystem, and only to
other blocks that have their Priority explicitly set.

Note Starting in R2024a, blocks with Execution Order set to First or Last is supported inside a
model that contains blocks with continuous sample time.

Use Block Description to Identify a Block


The Info tab displays information about the block type. The block author provides this description.

You can also enter a description in the Description box to provide information about the block
instance.

• If you add a description, you can set up your model display so that the description appears in a
tooltip when you hover over the block. To enable this tooltip, on the Debug tab, select
Information Overlays > Description in Tooltip .
• The Description property can help you to find a block by searching. See Simulink Editor.

40-6
Specify Block Properties

Create Block Annotations Programmatically


You can use a block AttributesFormatString parameter to display specified block parameter
values below the block. “Common Block Properties” and “Block-Specific Parameters” describe the
parameters that a block can have. Use the Simulink set_param function to set this parameter to the
attributes format that you want.

The attributes format can be any text that has embedded parameter names. An embedded parameter
name is a parameter name preceded by %< and followed by >, for example, %<priority>. Simulink
displays the attributes format text below the block icon, replacing each parameter name with the
corresponding value. You can use line-feed characters (\n) to display each parameter on a separate
line. For example, select a Gain block and enter this command at the MATLAB command prompt:

set_param(gcb,'AttributesFormatString','pri=%<priority>\ngain=%<Gain>')

The Gain block displays this block annotation:

If a parameter value is not text or an integer, N/S (for not supported) appears in place of the value. If
the parameter name is not valid, Simulink displays ??? in place of the value.

See Also

More About
• “Add Blocks to Models” on page 1-32
• “Customize Model Behavior with Callbacks” on page 4-68

40-7
40 Working with Blocks

View Signal Values Using Port Value Labels

A port value label displays the value for a signal as a label that floats over the signal line in the block
diagram, similar to a tooltip or a data tip. You can add and remove port value labels throughout your
model before and during simulation. Use port value labels along with other visualization options to
understand, analyze, and debug your model.

Port value labels access signal values by probing the data buffers used in the simulation. In some
cases, the output port that produces a signal does not correspond directly with a data buffer in the
simulation. Adding and removing port value labels in your model does not modify the model in any
way, even to make a signal value available for display. When you add a port value label to a signal
with a value the software cannot access without modifying the model, the label displays text instead
of the signal value to indicate that the signal value is not accessible from that point in the model. For
details, see “Understand Text Displayed in Port Value Labels” on page 40-12.

You can configure settings related to port value labels, including the font size and how frequently the
value updates during active simulation. Port value labels and port value label settings are not saved
as part of the model.

For more information about options for viewing data, see “Decide How to Visualize Simulation Data”
on page 33-2.

Add and Remove Port Value Labels


When the model is not running in simulation, you can add port value labels to one signal at a time, to
a selection of multiple signals, or to all signals in the current block diagram.

• Select one or more signals. Then, in the Simulink Toolstrip, on the Debug tab, in the Tools

section, in the Port Values button group, click Show port value label on selected signal .
• Select one or more signals. Then, on the Signal tab, click Output Value Labels.
• Right-click a selection of one or more signals. Then, in the context menu, select Show Port Value
Label On Selected Signal.

During simulation, by default, clicking a signal line adds or removes the port value label for that
signal line.

• If the port value label is visible, clicking the signal line removes the port value label.
• If the port value label is not visible, clicking the signal line adds the port value label.

You can control this behavior using the Value Label Display Options dialog box. To disable the single-
click option for adding and removing port value labels during simulation:

1 On the Debug tab, in the Tools section, in the Port Values button group, click the Remove all

port value labels button arrow .


2 Select Options.

40-8
View Signal Values Using Port Value Labels

3 In the Value Label Display Options dialog box, in the Display Values section, clear Enable by
default during simulation.

After you add port value labels to one or more signal lines, the labels appear on the signal lines.
When you add a port value label before simulation or while paused in simulation, the label initially
shows no data yet because the block has not executed since you added the port value label.

When you start, continue, or advance the simulation by stepping forward, the port value label
updates to display the signal value if the action caused the block that produces the signal value to
execute. For example, after clicking Step Forward, the port value label from the previous image
updates to display the signal value.

If the port value label displays another message, such as inaccessible, that port and signal in your
model might not support port value labels. For more information, see “Understand Text Displayed in
Port Value Labels” on page 40-12.

When you remove a port value label, the software does not retain the value that was displayed. If you
immediately add the port value label again, the value shows no data yet until the block that
produces the signal executes again.

To remove specific port value labels in your model:

1 Right-click a selection of one or more signals.


2 In the context menu, clear Show Port Value Label On Selected Signal.

To remove all port value labels in a model, on the Debug tab, in the Tools section, in the Port Values

button group, click Remove all port value labels .

You cannot add or remove port value labels programmatically.

These examples show how to use port value labels to analyze and debug a model:

• “Step Through Simulation” on page 2-2


• “Debug Simulation Using Signal Breakpoints” on page 2-12
• “Debug Simulation of Iterator Subsystem” on page 37-7

Configure Port Value Label Settings


You can use the Value Label Display Options dialog box to configure several options related to port
value labels, including the font size for the value display, an approximate update rate for the value
displayed, and the display format for numeric values.

40-9
40 Working with Blocks

To open the Value Label Display Options dialog box, On the Debug tab, in the Tools section, in the

Port Values button group, click the Remove all port value labels button arrow . Then, select
Options.

The settings that you configure apply for all port value labels in the model. Port value label settings
are not saved with the model. You cannot configure port value label settings programmatically.

The Approximate refresh interval setting specifies approximately how frequently the software
updates the value displayed in each port value label. Often, signal values update during simulation
more quickly than you can read them. By default, the Approximate refresh interval for a model is
one second. Instead of updating the port value label each time the output method for the source block
executes, the software updates the value approximately once per second.

Configure Port Value Labels for Buses


When you add a port value label to a signal line for a bus or a message that carries its payload as a
bus, by default, the port value label displays the names and values for all leaf elements of the bus. For
example, consider this model that creates a bus hierarchy using output signals from source blocks.

When you add a port value label to the bus main_bus, the port value label shows no data yet.

After you start, continue, or advance the simulation by stepping forward, the port value label updates
to display the names and values for all leaf elements in the bus.

40-10
View Signal Values Using Port Value Labels

You can select which bus elements to display on the port value label.

1 Click the port value label for the bus.


2 In the menu that appears, select the elements to display. Selecting a bus selects all of its
elements.

Click anywhere outside the menu to close the menu. The port value label shows only the selected
elements with the text no data yet as the value for each element. Changing the selection of bus
elements to display discards the values previously displayed in the port value label.

When you simulate the model, the port value label updates to show the values for the selected bus
elements.

40-11
40 Working with Blocks

Consider using these options when working with bus hierarchies that contain many elements:

• Search for bus elements by name using the text box at the top of the menu.
• To reduce the items displayed in the menu, select Show only selected.

Only the elements selected for display on the port value label show in the menu. To select an
additional element, search for the element by name. The search results appear in the menu, where
you can select them.
• Collapse nodes in the tree that shows the bus hierarchy.

Understand Text Displayed in Port Value Labels


Port value labels might show one of several messages in place of signal values. For example, port
value labels on some types of signals, such as function-call signals, display a message that indicates
the signal type. In other cases, a port value label might display a message when a signal value is
difficult to display in the available space or when the signal value is not accessible at that point in the
model.

This table summarizes port value label messages that indicate the signal type.

Port Value Label Signal Type


Message
action Action signals that control execution of action subsystems, such as if-
action subsystems
fcn-call Function-call signals that control function-call subsystems
ground Ground block output signal
not a data signal Signal that does not contain valid data, such as the output signal for a
block that is commented out
[m*n] Two-dimensional signal

Instead of the element values, the port value label shows the signal
dimensions.

This table summarizes port value label messages that indicate the software can access the signal
value but cannot display the value.

Port Value Label Context


Message
... The number of elements in the vector signal exceeds the maximum
number of elements to display configured in the Value Label Display
Options dialog box.

40-12
View Signal Values Using Port Value Labels

Port Value Label Context


Message
click to add signals The port value label on a bus has no elements selected for display. To
select bus elements, click the port value label.

This table summarizes port value label messages that indicate the software is unable to access the
signal value.

Message Context
no data yet Signal values are not available because the output method of the source
block has not executed since the port value label was added.

This value also appears for port value labels in model reference instances
that do not have normal mode visibility.

When you remove a port value label, the software does not retain the
value that was displayed. If you immediately add the port value label
again, the value shows this message until the block that produces the
signal executes again.
no message Insufficient simulation data available.

Try starting, continuing, or advancing the simulation.


inaccessible The software cannot access the output port value due to the structure of
the model.

Port value labels show this message for signals that share memory in
generated code when the Signal storage reuse model configuration
parameter is selected.
not used The software cannot access the output port value because the output
port value is not used in the simulation.
removed The software cannot access the output port value because the source
block was removed by block reduction. For more information, see Block
reduction.
optimized The software cannot access the signal value due to optimization.

Port value labels show this message for output signals of blocks that are:

• Optimized out of the simulation target for accelerator mode


simulations
• Optimized out of the compiled model because the Conditional input
branch execution model configuration parameter is selected
• Optimized out of the compiled model for another reason.
unavailable The software cannot access the output port value because the data is not
available.

Port value labels show this message when you step back to a simulation
time that occurred before you added the port value label.

40-13
40 Working with Blocks

When a port value label cannot access the value you want to view, sometimes you can change the
model to make the signal value available. For example, in some cases the signal value becomes
available when you:

• View the signal value using other visualization options, such as the Display block, Scope blocks,
and scope viewers.
• Mark the signal for logging.
• Designate the signal as a test point using the Signal Properties dialog box.

Additional Considerations for Using Port Value Labels


The table summarizes considerations related to using port value labels based on several workflows
and modeling patterns.

Workflow or Modeling Pattern Considerations for Using Port Value Labels


Simulation performance Selecting Show When Hovering or Toggle
When Clicked in the Value Label Display
Options dialog box can slow down simulation.
Accelerator and rapid accelerator simulations Port value labels do not show values for output
signals of blocks that are optimized out of the
simulation target for accelerator mode.

Port value labels are not supported for rapid


accelerator simulations.
Programmatic simulation Port value labels are not supported for
simulations started using the sim function.
Fixed-point data Port value labels display the converted double
value for signals with fixed-point data types.
Model references Port value labels display data for the model
reference instance with normal mode visibility.
For more information, see “Simulate Multiple
Referenced Model Instances in Normal Mode” on
page 8-59.
Subsystem input ports Blocks that represent input ports inside
subsystems are often virtual. Port value labels on
input ports inside subsystems show the output
value of the block that drives the port when the
block that represents the input port is virtual.
Variant subsystems Port value labels cannot access the data for ports
of a subsystem that is inside a variant subsystem
with no input signals.

40-14
View Signal Values Using Port Value Labels

Workflow or Modeling Pattern Considerations for Using Port Value Labels


Disabled subsystems Whether port value labels display data for output
ports of disabled conditionally-executed
subsystems depends on the Output when
disabled parameter setting for the block that
represents the conditionally-executed subsystem.

Port value labels do not display data for output


ports of enabled subsystems that are disabled.
Signal Specification block Port value labels show the output value for the
block that drives the port.
Merge block Port value labels are not supported for signals
that connect to input ports of a Merge block.
Simscape Port value labels are not supported for physical
signals.
Model configuration parameters Port value labels show only values produced
when the output method for a block executes.
When you specify a refine factor for logging, port
value labels do not show values produced to
refine the logged data. For more information, see
Refine factor.

Port value labels might not be able to access data


for some signals when you enable these
parameters:

• Block reduction
• Conditional input branch execution
• Signal storage reuse

See Also

More About
• “Decide How to Visualize Simulation Data” on page 33-2
• “Step Through Simulation” on page 2-2
• “Debug Simulation Using Signal Breakpoints” on page 2-12
• “Nonvirtual and Virtual Blocks” on page 40-2

40-15
40 Working with Blocks

Control and Display Execution Order

The execution order for a model is the order in which the software invokes the block output methods
during simulation. The software determines this order during a model update, which you can initiate
by clicking Update Model on the Modeling tab. The software also updates the model during
simulation.

You cannot set the execution order, but you can assign priorities to nonvirtual blocks to indicate their
execution order relative to other blocks in the corresponding block diagram.

Some nonvirtual blocks do not support block priorities. For example, the software ignores priorities
set on these blocks:

• Merge blocks.
• Blocks with function-call input ports, such as Function-Call Subsystem blocks and Model blocks
that reference export-function models.
• Blocks with action ports, such as If Action Subsystem and Switch Case Action Subsystem blocks.
• For Iterator blocks inside For Iterator Subsystem blocks and While Iterator blocks inside While
Iterator Subsystem blocks. For Iterator and While Iterator blocks must be the first blocks to
execute inside For Iterator Subsystem and While Iterator Subsystem blocks, respectively.

If a priority is set on these blocks, the Block priority violation configuration parameter setting
determines whether you receive a warning or error.

The software tries to honor block priority settings unless there is a conflict with data dependencies.
To confirm the results of the priorities you have set or to debug your model, display and review the
execution order of your nonvirtual blocks and subsystems.

For more information about block methods and execution, see:

• “Block Methods”
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Specify Block Execution Order, Execution Priority and Tag” on page 40-5

Execution Order viewer


On the Debug tab, select Information Overlays > Execution Order. The Execution Order viewer
opens in a pane on the right side of the Simulink Editor.

40-16
Control and Display Execution Order

The Execution Order viewer displays information based on the latest compiled execution order.

• System Index — Unique value within a model that represents the current system or nonvirtual
subsystem. For the top-level model, the system index is 0. For each nonvirtual subsystem, the
system index is a positive integer.

Blocks that are directly inside the nonvirtual subsystem have the same system index as the
subsystem. To determine whether subsystems are part of the same system within a model,
compare their system indexes.

In model reference hierarchies, the same system index may be used multiple times. It remains
unique only within each model of the hierarchy.
• Execution Order Block List — List of blocks in order of their task-based execution order. The
block list provides complete execution order information for the selected task, providing more
information than the block diagram displays. For example, the list includes hidden blocks and
blocks in subsystem block diagrams.
• Task ID — Unique identifier for each task in the current system. Each task corresponds to a
group of blocks that execute in a set order relative to each other based on their derived sample
time information. A single Task ID can contain blocks with multiple different types of sample
times. Execution order displays blocks with different types of constant sample times in separate
tasks. For example, Simulink blocks with constant sample times of [Inf 0] and [Inf Inf] are
displayed in Task 1 and Task 2, respectively. For more information about sample times, see
“Constant Sample Time” on page 7-20.

To obtain the sample time information programmatically, use get_param function.

get_param('model_name/block_name','CompiledSampleTime')

For more information, see “Block Compiled Sample Time” on page 7-25.

40-17
40 Working with Blocks

For fixed-step sizes, the Treat each discrete rate as a separate task configuration parameter
determines whether blocks with discrete rates execute in one or multiple tasks.

To update execution order information for a model that has changed since its last compile, recompile
the model. In the Execution Order viewer, click the Recompile model to update execution order

information button .

To highlight the blocks that belong to a task and display their execution order, select the task in the
Execution Order viewer. By default, the software selects the first task that corresponds to the active
block diagram.

Note Starting in R2023b, the execution order display no longer highlights signal lines and virtual
blocks for a selected task. For more information about virtual blocks see, “Nonvirtual and Virtual
Blocks” on page 40-2.

When the active block diagram does not contain any blocks that execute as part of a given task, you
cannot select the task in the Execution Order viewer. The active block diagram may contain virtual
blocks, such as Inport blocks, that are part of this task.

To hide the highlighting and execution order, click the Clear Highlighting button .

Navigation from Blocks to Tasks


To display the tasks in which a block executes, click on a block.

40-18
Control and Display Execution Order

The task numbers in the label are links that you can click to select the corresponding task in the
Execution Order viewer. When a model has many tasks, these links provide an alternative to
scrolling through the list of tasks in the Execution Order viewer.

To compare tasks among blocks, select multiple blocks.

Execution Order Notation


The block diagram displays a number at the top-right corner of each nonvirtual block. These numbers
indicate the order in which the blocks execute. The first block to execute has the lowest execution
order, which is usually 1. The displayed execution order may skip numbers, but the blocks always
execute in order of the visible numbers. Suppose a task displays execution orders 1, 2, and 4. The
block labeled 1 executes before the block labeled 2, which executes before the block labeled 4.

For example, in this model, the block execution order ranges from 1 to 12, with each nonvirtual block
receiving an execution order.

Virtual and Nonvirtual Subsystems

Virtual Subsystem blocks exist only graphically and do not execute. Consequently, they are not part of
the execution order. Creating virtual subsystems can affect the execution order of blocks when the
blocks are sorted by block path. Each block within a virtual subsystem executes as an atomic unit and
has an execution order in the context of the root-level model or, if the virtual subsystem is inside a
nonvirtual subsystem, in the context of the parent nonvirtual subsystem. For virtual subsystems,
block execution order within the subsystem is listed in curly brackets {}.

Nonvirtual Subsystem blocks exist functionally and execute as a unit. They have a single execution
order and a different system index than the root-level model or any parent nonvirtual subsystem. The

40-19
40 Working with Blocks

blocks inside a nonvirtual subsystem have their own execution orders, which are independent of the
root-level model or any parent nonvirtual subsystem.

For example, this model contains a virtual subsystem named car dynamics and an atomic,
nonvirtual subsystem named discrete cruise controller.

The virtual car dynamics subsystem shows a list of execution orders within curly brackets for the
blocks it contains. The blocks it contains execute at the same level as the Step, Sum, and Scope
blocks and the discrete cruise controller nonvirtual subsystem. The Integrator block
executes first and sends its output to the Scope block, which executes second.

The nonvirtual discrete cruise controller subsystem has a single execution order (4), which
indicates that the subsystem and the blocks within it are the fourth to execute relative to the blocks
at the same level.

40-20
Control and Display Execution Order

Note Depending on your model configuration, the software can insert hidden, nonvirtual subsystems
in your model. As a result, the visible blocks inside the hidden Subsystem block can have a system
index that is different from the current system index. For example, if you select the Conditional
input branch execution configuration parameter, the software may create hidden, nonvirtual
subsystems for optimization, which can affect the sorted execution order.

Algebraic Loops

Blocks within an algebraic loop are moved into a hidden nonvirtual subsystem. The software first
determines the execution order of the hidden subsystem within the context of the other blocks, then
determines the execution order of the blocks within the hidden subsystem. See “Algebraic Loop
Concepts” on page 3-39.

Function-Call and Action Subsystems

For function-call and action subsystems, the execution of the subsystem is controlled by the execution
of its initiator. The subsystem and its initiator therefore share an execution order.

The software ignores any block priority set on Function-Call Subsystem, If Action Subsystem, or
Switch Case Action Subsystem blocks, but you can set the block priority on the blocks that initiate
these subsystems.

At the root-level of export-function models, function-call execution orders have an F prefix.

40-21
40 Working with Blocks

For more information, see “Export-Function Models Overview” on page 10-125.

Buses and Multiple Initiators

A block has multiple execution orders when the block executes multiple times based on different
execution paths to that block. For example:

• A block connected to a bus has an execution order corresponding to each signal that the bus
contains.

• A function-call or action subsystem with multiple initiators has an execution order corresponding
to each initiator.

Determining Execution Order


Task-based sorting sets the execution order of blocks and ports based on their derived sample time
information. Task-based sorting provides an efficient and simpler process for determining the
execution order of blocks.

With task-based sorting:

40-22
Control and Display Execution Order

• Tasks are sorted individually based on sample time.


• Multiple sorted lists are generated instead of one flattened, sorted list of blocks across all tasks.
• Rate transition handling is simplified.
• False data dependency violations involving blocks in different tasks are avoided.
• Code generation results are in efficient rate groupings.
• One subsystem can belong to different sorted lists in multiple tasks.

Direct-Feedthrough Input Impact on Execution Order

To ensure that the execution order reflects data dependencies among blocks, the software 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 input. See “Algebraic Loop Concepts” on page 3-39.

Examples of blocks that have direct-feedthrough inputs include:

• Gain
• Product
• Sum

Examples of blocks without direct-feedthrough inputs include:

• Integrator
• Unit Delay
• Constant

Rules for Determining Block Execution Order

To sort blocks, the software uses these rules:

• If a block drives the direct-feedthrough input of another block, the driving block must appear in
the execution order ahead of the block that it drives.

This rule ensures that the direct-feedthrough inputs to blocks are valid when the software invokes
block output methods that require current inputs.
• If a block drives the input of another block that is not a direct-feedthrough input, there is no data
dependency between the two blocks, so their relative execution order does not matter.

This model illustrates this result.

• The Integrator block 1/s in the Car Dynamics virtual subsystem has no direct-feedthrough input.
Therefore, even though its input is connected to the Gain block 1/m, the Integrator block is sorted
before the Gain block 1/m. The output of the Integrator block drives the input of the Gain block b,
so the Integrator block is sorted before that Gain block.

40-23
40 Working with Blocks

• In the root-level model, the Step block step response drives a Sum block, so the Step block is
sorted before the Sum block. The Sum block drives the direct-feedthrough input of the discrete
cruise controller nonvirtual subsystem, so the subsystem is sorted after the Sum block.

The discrete cruise controller nonvirtual subsystem is treated as a block with a direct-
feedthrough input because its output depends on the current value of the input via the branch with
the Gain block named Kp. Inside the subsystem, all the Gain blocks, which have direct-feedthrough
inputs, run before the Sum block that they drive.

Rules for Determining Block Execution Order in Models Containing Asynchronous Tasks

In simulation, asynchronous function-call initiators have the highest priority when determining block
sorting order within a task. For more information, see “Asynchronous Sample Time” on page 7-19 and
“Rate Transitions and Asynchronous Blocks” (Simulink Coder).

To determine the block execution order in models containing asynchronous sample times, the
software uses these rules:

• If an asynchronous function-call initiator is triggered by a discrete rate shared by the


corresponding rate transition block, then in the task of the common discrete rate, the
asynchronous function-call initiator will be sorted first.

For example, in the below model, there is one asynchronous function-call initiator (an Async
Interrupt block) that is triggered by the discrete rate D1. Within the discrete task, the

40-24
Control and Display Execution Order

asynchronous function-call initiator is sorted first. The Rate Transition blocks convert between the
asynchronous rate, A1, and the discrete rate, D1.

• If a Rate Transition block is reduced to NoOp, the Rate Transition block does not execute, and its
position in the sorted order within the discrete task is transferred to the upstream or downstream
discrete block to which it is connected.

For example, in the above model, RTB2 is reduced to NoOp, so its position in the sorted order is
transferred to the downstream Gain block.
• If two asynchronous function-call initiators share a common discrete rate task, then asynchronous
function-call initiator with higher priority executes first within the discrete rate task.

For example, in the below model, two asynchronous function-call initiators (two Async Interrupt
blocks) are triggered by the same discrete rate, D1. The one with higher task priority is sorted
first.

40-25
40 Working with Blocks

• The union of asynchronous sample times is not supported by task-based sorting. All blocks
associated with the union of multiple asynchronous sample times are sorted within a single task.

For example, in the below model, two asynchronous function-call initiators (two Async Interrupt
blocks) with same Simulink task priority are triggered by the same discrete rate, D1. In this
model, a Rate Transition block RTB1_Union computes U1 = union(A4 , A5). The blocks associated
with the union is grouped in Task 0. For more information about union sample time, see “Union
Rate” on page 7-3 and asynchronous sample time, see “Asynchronous Sample Time” on page 7-19.

40-26
Control and Display Execution Order

40-27
40 Working with Blocks

Check for Execution Order Changes Involving Data Store Memory


Blocks
Model Upgrades

Using task-based sorting instead of legacy (block) sorting can change the relative execution order
involving Data Store Memory blocks. An Upgrade Advisor check detects the changes and provides an
option to keep the original execution order when upgrading your model from earlier Simulink
versions.

1 Open the Upgrade Advisor. On the Modeling tab, select Model Advisor > Upgrade Advisor.
2 Select the check box for Check relative execution orders for Data Store Read and Data
Store Write blocks.

3 Click Run This Check.


4 Review any changes in the Result table. If you want to keep the original execution order, click
Modify.

Code Generation

When a model is compiled for code generation, the relative execution order of Data Store Read and
Data Store Write blocks can differ in the generated code from the order in normal simulation mode. A
Model Advisor check detects these differences and provides an option to change the execution order
in normal simulation mode to match the order in the generated code.

1 Open the Model Advisor. On the Modeling tab, select Model Advisor > By Product >
Simulink Coder.
2 Select the check box for Check for relative execution order change for Data Store Read
and Data Store Write blocks.

40-28
Control and Display Execution Order

3 Click Run This Check.


4 Review any changes in the Result table. If there are discrepancies listed and you want to change
the execution order in normal simulation to conform with the execution order in generated code,
click Modify block priorities.

40-29
40 Working with Blocks

See Also

More About
• “Nonvirtual and Virtual Blocks” on page 40-2
• “Specify Block Properties” on page 40-4
• “Configure Model Layout” on page 1-56
• “View Signal Values Using Port Value Labels” on page 40-8
• “Access Block Data During Simulation” on page 40-31

40-30
Access Block Data During Simulation

Access Block Data During Simulation


In this section...
“About Block Run-Time Objects” on page 40-31
“Access a Run-Time Object” on page 40-31
“Listen for Method Execution Events” on page 40-31
“Synchronizing Run-Time Objects and Simulink Execution” on page 40-32

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 73-76) 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 run-time object of the block. This allows you to use
get_param to obtain a block's run-time object. For example, the following statement
rto = get_param(gcb,'RuntimeObject');

returns the run-time object of the currently selected block. Run-time object data is read-only. You
cannot use run-time objects to change a block’s parameters, input, output, and state data.

Note Virtual blocks (see “Nonvirtual and Virtual Blocks” on page 40-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 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

40-31
40 Working with Blocks

applications. For more information, see the documentation for the add_exec_event_listener
command. For an example of using method execution events, open sldemo_msfcn_lms. 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 to add a PostOutputs method execution event to the S-function's block run-time object for
example:

% Add a callback for PostOutputs event


blk = 'sldemo_msfcn_lms/LMS Adaptive';

h = add_exec_event_listener(blk, ...
'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, ei) %#ok<INUSD>


%
% Callback function for plotting the current adaptive filtering
% coefficients.

stemPlot = get_param(block.BlockHandle,'UserData');

est = block.Dwork(2).Data;
set(stemPlot(2),'YData',est);
drawnow('expose');

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.

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 (see Signal storage reuse (Simulink Coder)).

40-32
Access Block Data During Simulation

See Also

More About
• “Nonvirtual and Virtual Blocks” on page 40-2
• “Specify Block Properties” on page 40-4
• “Configure Model Layout” on page 1-56
• “View Signal Values Using Port Value Labels” on page 40-8
• “Control and Display Execution Order” on page 40-16

40-33
41

Working with Block Parameters

• “Set Block Parameter Values” on page 41-2


• “Share and Reuse Block Parameter Values by Creating Variables” on page 41-9
• “Parameter Interfaces for Reusable Components” on page 41-17
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Tune and Experiment with Block Parameter Values” on page 41-31
• “Optimize, Estimate, and Sweep Block Parameter Values” on page 41-38
• “Control Block Parameter Data Types” on page 41-44
• “Specify Minimum and Maximum Values for Block Parameters” on page 41-52
• “Switch Between Sets of Parameter Values During Simulation and Code Execution”
on page 41-56
41 Working with Block Parameters

Set Block Parameter Values


Blocks have numeric parameters that determine how they calculate output values. To control the
calculations that blocks perform, you can specify parameter values. For example, a Gain block has a
Gain parameter, and a Transfer Fcn block has multiple parameters that represent the transfer
function coefficients.

You can use numbers, variables, and expressions to set block parameter values. Choose a technique
based on your modeling goals. For example, you can:

• Share parameter values between blocks and models by creating variables.


• Control parameter characteristics such as data type and dimensions by creating parameter
objects.
• Model an algorithm as code by using mathematical expressions.

Set block parameters using the Parameters tab in the Model Data Editor (on the Modeling tab, click
Model Data Editor), the Property Inspector (on the Modeling tab, under Design, click Property
Inspector), or the block dialog box. For more information, see “Add Blocks to Models” on page 1-32.
To set block sample times, see “Specify Sample Time” on page 7-10.

Tip You can use the Model Explorer to make batch changes to many block parameter values at once.
For more information, see Model Explorer.

Programmatically Access Parameter Values


To programmatically access block parameter values, use the get_param and set_param functions.
You can use this technique to:

• Construct a model programmatically.


• Adjust parameter values during a simulation run when you simulate a model programmatically.

To sweep parameter values between simulation runs by using a script, use


Simulink.SimulationInput objects instead of get_param and set_param. See “Optimize,
Estimate, and Sweep Block Parameter Values” on page 41-38.

Suppose you create a model named myModel that contains a Constant block named My Constant.
Next, you use the block dialog box to set the Constant value parameter to 15. To programmatically
return the parameter value, use the function get_param. You specify the block path and the
equivalent programmatic parameter name, Value.

paramValue = get_param('myModel/My Constant','Value')

paramValue =

15

To programmatically change the value, for example to 25, use the function set_param. Use the
character vector '25' as the input to the function.

set_param('myModel/My Constant','Value','25')

For a list of programmatic names of block parameters, see “Block-Specific Parameters”.

41-2
Set Block Parameter Values

For more information about programmatic simulation, see “Run Simulations Programmatically” on
page 28-2.

To avoid using the get_param and set_param functions, use the name of a MATLAB variable or
Simulink.Parameter object as the parameter value, and change the value of the variable or object
at the command prompt. See “Share and Reuse Block Parameter Values by Creating Variables” on
page 41-9.

Specify Parameter Values


Goal Block Parameter Value Description
Store the parameter value in the 2.3 Literal numeric value. Specify a
model file. scalar, vector, matrix, or
[1.2 2.3 4.5; 7.9 8.7 multidimensional array. Use i to
6.5] specify complex values.

2 + 3i
• Access the parameter value myVar MATLAB variable that exists in
without having to locate or a workspace.
identify the block in the
model. For more information, see
“Share and Reuse Block
• Change the parameter value
Parameter Values by Creating
without having to modify the
Variables” on page 41-9.
model file.
• Share the parameter value
between blocks or between
models.
• Identify the parameter by a
specific name when
sweeping or tuning the
value.
• Avoid name clashes between myParam.a.SpeedVect Field of parameter structure.
workspace variables.
For more information, see
• Organize parameter values
“Organize Related Block
using hierarchies and
Parameter Definitions in
meaningful names.
Structures” on page 41-19.
• Reduce the number of
workspace variables that a
model uses.
Use a portion of a matrix or myMatrixParam(:,2) Index operation.
array variable. For example, set
the parameters of a n-D Lookup
Table block.

41-3
41 Working with Block Parameters

Goal Block Parameter Value Description


• Define parameter myParam Parameter object.
characteristics, such as data
type, complexity, units, For more information, see “Use
allowed value range, and Parameter Objects” on page 41-
dimensions, separately from 4.
the parameter value.
• Define a system constant
with custom documentation.
• Create a tunable parameter
in the generated code.
• Set the value of a variable to
a mathematical expression
involving constants and
other variables.
• Express a parameter value 5^3.2 - 1/3 Expression or custom function.
as a mathematical
relationship between known myParam * myOtherparam + For more information, see “Use
physical constants instead of sin(0.78*pi) Mathematical Expressions,
as an unidentifiable literal MATLAB Functions, and Custom
number. myFun(15.23) Functions” on page 41-5.
• Reduce block population in a
model.
• Model an obscure or trivial
calculation by using code
instead of blocks.
• Use MATLAB operators and
functions to perform
calculations.
• Write a custom MATLAB
function that calculates
parameter values.
Specify a block parameter value 15.23 Typed or untyped expression,
by using a data type other than numeric MATLAB variable, or
double. single(15.23) parameter object.

myParam For more information about


controlling parameter data
types, see “Control Block
Parameter Data Types” on page
41-44.

Use Parameter Objects

Parameter objects are Simulink.Parameter objects and objects of the subclasses that you create.
The parameter object exists in a workspace such as the base workspace or a data dictionary.

41-4
Set Block Parameter Values

You can use parameter objects to define system constants. For example, use a parameter object to
represent the radius of the Earth. Use the properties of the object to specify the physical units and to
document the purpose of the value.

Create parameter objects to prepare your model for code generation. You can configure parameter
objects to appear as tunable global variables in the generated code. You can also control the
parameter data type through the object.

To create and use parameter objects in models, see “Data Objects” on page 73-76. For information
about using variables to set block parameter values, see “Share and Reuse Block Parameter Values by
Creating Variables” on page 41-9.

Use Mathematical Expressions, MATLAB Functions, and Custom Functions

You can set a block parameter value to an expression that calls MATLAB functions and operators such
as sin and max. You can also call your own custom functions that you write on the MATLAB path.

Suppose that a section of your block algorithm uses variables to calculate a single constant number
used by the rest of the algorithm. You can perform the calculation by creating multiple blocks.

Instead, create a single Constant block that uses an expression written in MATLAB code. This
technique reduces the size of the block algorithm and improves readability.

41-5
41 Working with Block Parameters

You can model a complicated portion of an algorithm by using an expression instead of many blocks.
To operate on an existing signal, use a mathematical expression as the value of a parameter in an
algorithmic block, such as the Gain parameter of a Gain block.

With expressions, you can also call your custom functions to set block parameter values. Suppose that
you write a MATLAB function that calculates optimal P, I, and D parameters for a control algorithm by
accepting a single input number.

You can parameterize a PID Controller block by using the function to set the parameter values.

41-6
Set Block Parameter Values

To make the best use of expressions, consider these tips:

• If you use variables and parameter objects, you can explicitly model the algebraic relationships
between the real-world quantities that the variables and objects represent. Use expressions in
parameter objects as described in “Set Variable Value by Using a Mathematical Expression” on
page 41-10.

• While you edit an expression in a block parameter value, to navigate to the documentation for a
function, use the button next to the parameter value. You can also navigate to the source code
of a custom function.

Considerations for Other Modeling Goals


Choose a technique to set block parameter values based on your modeling goals.

Goal Features or Best Practice


Products
Run multiple simulations Simulink.Simulat Use variables or parameter objects to set block parameter
quickly. ionInput objects values. This technique helps you to assign meaningful names
and the sim function to the parameters and to avoid having to identify or locate the
blocks in the model. See “Optimize, Estimate, and Sweep
Block Parameter Values” on page 41-38.
Sweep parameter values Simulink Test Use variables or parameter objects to set block parameter
during testing. values. Use iterations and parameter overrides to run multiple
tests. See “Parameter Overrides” (Simulink Test) and “Test
Iterations” (Simulink Test).
Estimate and optimize Simulink Design Use variables or parameter objects to set block parameter
parameter values. Optimization™ values.

To estimate or optimize a parameter that uses a data type


other than double, use a parameter object to separate the
value from the data type.

For parameter estimation, see “Parameter Estimation”


(Simulink Design Optimization). For response optimization, see
“Optimize Model Response” (Simulink Design Optimization).

41-7
41 Working with Block Parameters

Goal Features or Best Practice


Products
Generate code from a Simulink Coder Use parameter objects to set block parameter values. This
model. Simulate an technique helps you to declare and identify tunable
external program parameters in the generated code and to control parameter
through SIL/PIL or data types. See “Create Tunable Calibration Parameter in the
External mode Generated Code” (Simulink Coder).
simulations.
When you use expressions to set block parameter values, avoid
using operators and functions that result in loss of tunability in
the generated code. See “Tunable Expression Limitations”
(Simulink Coder).

See Also
set_param

Related Examples
• “Determine Where to Store Variables and Objects for Simulink Models” on page 73-109
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Tune and Experiment with Block Parameter Values” on page 41-31
• “Block-Specific Parameters”
• “Add Blocks to Models” on page 1-32

41-8
Share and Reuse Block Parameter Values by Creating Variables

Share and Reuse Block Parameter Values by Creating Variables


To set a block parameter value, such as the Gain parameter of a Gain block, you can use numeric
variables that you create and store in workspaces such as the base workspace, a model workspace, or
a Simulink data dictionary. You can use the variable to set multiple parameter values in multiple
blocks, including blocks in different models. To change the values of the block parameters, you
change the value of the variable in the workspace.

Using a variable to set a block parameter value also enables you to:

• Change the parameter value without having to modify the model file (if you store the variable
outside the model workspace).
• Identify the parameter by a specific, meaningful name when sweeping or tuning the value.

For basic information about setting block parameter values, see “Set Block Parameter Values” on
page 41-2.

Reuse Parameter Values in Multiple Blocks and Models


You can create a numeric MATLAB variable in a workspace, such as the base workspace or a data
dictionary, and use it to specify one or more block parameter values.

If a block parameter value is set to a simple numeric expression, you can create a variable for that
expression in the Model Data Editor (on the Modeling tab, click Model Data Editor). Click in the
right side of the cell that corresponds to the value, then select Create variable. In the Create New
Data dialog box, set the name and location for the new variable, then click Create. The cell now
displays the new variable.

You can also create a variable to represent a constant that is used in multiple expressions. The
example model sldemo_fuelsys represents the fueling system of a gasoline engine. A subsystem in
the model, feedforward_fuel_rate, calculates the fuel demand of the engine by using the
constant number 14.6, which represents the ideal (stoichiometric) ratio of air to fuel that the engine
consumes. Two blocks in the subsystem use the number to set the values of parameters. In this
example, to share the number between the blocks, you create a variable named myParam.

1 Open the “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')
sldemo_fuelsys

2 In the model, on the Modeling tab, click Model Data Editor. In the Model Data Editor, inspect
the Parameters tab.
3 In the model, navigate into the subsystem.
open_system(...
'sldemo_fuelsys/fuel_rate_control/fuel_calc/feedforward_fuel_rate')

4 In the Model Data Editor, in the Filter contents box, enter 14.6.

The data table contains two rows, which correspond to the Constant value parameters of two of
the Constant blocks in the subsystem.
5 Use the Value column to replace the literal number 14.6 with myParam. Perform the
replacement for both parameters.

41-9
41 Working with Block Parameters

6 In the Filter contents box, enter myParam.


7
While editing the value of one of the parameters, click the action button and select Create.
8 In the Create New Data dialog box, set Value to 14.6 and click Create.

The variable, myParam, appears in the base workspace.

Because the variable exists in the base workspace, you can use it in multiple models. However, when
you end your MATLAB session, you lose the contents of the base workspace. Consider permanently
storing the variable in a model workspace or data dictionary.

Define a System Constant


To define a system constant, such as a variable that represents the radius of the Earth, consider
creating a Simulink.Parameter object instead of a numeric MATLAB variable. Parameter objects
allow you to specify physical units and custom documentation as well as other characteristics.

• To create and use parameter objects in models, see “Data Objects” on page 73-76.
• Typically, the value of a system constant influences the values of other parameters and signals
through mathematical relationships. To model these relationships explicitly, set the values of the
dependent data by using expressions. See “Set Variable Value by Using a Mathematical
Expression” on page 41-10.

Set Variable Value by Using a Mathematical Expression


You can set the value of a variable to an expression involving literal numbers and other variables.
With expressions, you can:

• Express the value as a relationship between known physical constants instead of as an


unidentifiable literal number.
• Explicitly model algebraic dependencies between parameter data. When you change the values of
independent data, you do not need to remember to adjust the values of dependent data.

General Technique

Convert the variable to a Simulink.Parameter object. Then, set the Value property of the object
by using an expression:

• Interactively — For example, with the Model Data Editor or the Model Explorer, precede the
expression with an equals sign, =. The figure shows how to specify the expression myVar +
myOtherVar.

41-10
Share and Reuse Block Parameter Values by Creating Variables

• Programmatically — Use the slexpr function, specifying the expression in a character vector or
string. For example, to set the value of a parameter object named myParam to the expression
myVar + myOtherVar:

myParam.Value = slexpr('myVar + myOtherVar')

Explicitly Model Algebraic Relationship Between Variables

The example sldemo_metro (see “Exploring the Solver Jacobian Structure of a Model”) models a
system of three identical, pointlike metronomes suspended from a moving platform. Blocks in the
model use these MATLAB variables from the base workspace:

• m — Mass of each metronome, initial value 0.1 kg


• r — Length of each metronome, initial value 1.0 m
• J — Moment of inertia of each metronome, initial value 0.1 kg/m2

These variables share an algebraic relationship: the moment of inertia of each metronome is equal to
the mass times the length squared. In this example, you record this relationship in the value of J.

1 Open the model.

sldemo_metro
2 Update the block diagram. A model callback creates the variables in the base workspace.
3 To prevent the callback from overwriting changes that you make to the variables, for this
example, remove the callback code.

set_param('sldemo_metro','InitFcn','')
4 In the model, on the Modeling tab, click Model Data Editor.
5 On the Model Data Editor Parameters tab, activate the Change scope button.

The blocks that use the variables are in the subsystems, so you must configure the Model Data
Editor to show data in subsystems.
6 Click the Show/refresh additional information button.

The data table contains rows that correspond to the variables in the base workspace.
7 In the Filter contents box, enter J.
8 In the data table, find the row that corresponds to J. In the Value column, set the value of the
variable to Simulink.Parameter(J).

Simulink converts J to a Simulink.Parameter object.


9 In the Value column, set the value of the parameter object to =m*r^2.
10 Optionally, simulate the model with different metronome masses and lengths. As you change the
values of m and r, you do not have to remember to correct the value of J.

Limitations and Considerations for Other Modeling Goals

• If the expression contains fixed-point data or data of an enumerated type, the expression can
operate on only one variable or object.
• You cannot set the data type (DataType property) of the parameter object that uses the
expression to auto (the default) and set the data types of parameter objects that appear in the
expression to a value other than auto. For example, in the expression J = m*r^2, you cannot set
the data type of J to auto and the data types of m and r to single.

41-11
41 Working with Block Parameters

• To retain the benefits of auto (described in “Context-Sensitive Data Typing” on page 41-44)
for the object that uses the expression, set the data types of the objects in the expression to
auto. In other words, use auto for all of the involved objects. The objects in the expression
acquire the same data type as the object that uses the expression.
• To use a value other than auto for an object that appears in the expression, set the data types
of all dependent parameter objects to a value other than auto. In other words, do not use
auto for any involved objects.

You must use the same data type for all objects used in the expression.
• If you have Simulink Coder and Embedded Coder licenses, you can generate code that initializes a
global variable by using the expression. However, the code generator can preserve the expression
only if it conforms to certain requirements. See “Expression Preservation” (Simulink Coder).

Control Scope of Parameter Values


The scope of a variable is the set of models and blocks that can use the variable. For example,
variables that you create in the base workspace have global scope because all blocks in all open
models can use the variables. Variables that you store in a model workspace have limited scope
because only the blocks in the host model can use the variables.

You cannot create two variables that have the same name in the same scope. Controlling the scope of
a variable helps you to avoid name conflicts and establish clear ownership of the variable.

The table describes the different ways that you can control the scope of a reusable parameter value.

Scope Technique
All open models Create a variable in the base workspace.
One or more targeted models Create a variable in a data dictionary. To reuse
the variable in multiple models, create a
referenced dictionary. See “What Is a Data
Dictionary?” on page 80-2
One model, including all subsystems in the model Create a variable in the model workspace. See
“Model Workspaces” on page 73-138.
Multiple blocks inside a subsystem, including Mask the subsystem and create a mask
blocks in nested subsystems parameter instead of a workspace variable.

To prevent blocks inside a subsystem from using


workspace variables, in the subsystem block
dialog box, set Permit Hierarchical Resolution
to None. This technique allows you to use the
same name to create both a variable in a
workspace and a mask parameter in the
subsystem mask. The blocks in the subsystem can
use only the mask parameter.

For information about subsystems, see


Subsystem. For information about masking, see
“Masking Fundamentals” on page 43-3.

41-12
Share and Reuse Block Parameter Values by Creating Variables

To avoid name conflicts when you have a large model with many variables in the same scope,
consider packaging the variables into a single structure. For more information, see “Organize Related
Block Parameter Definitions in Structures” on page 41-19.

For basic information about how blocks use the variable names that you specify, see “Symbol
Resolution” on page 73-151.

Permanently Store Workspace Variables


Variables that you create in the base workspace do not persist between MATLAB sessions. However,
you can store the variables in a MAT-file or script file, and load the file whenever you open the model
using a model callback. A model callback is a set of commands that Simulink executes when you
interact with a model in a particular way, such as opening the model. You can use a callback to load
variables when you open the model. Use this technique to store variables while you learn about
Simulink and experiment with models.

1 In a model that contains a Gain block, set the value of the Gain parameter to K.
2 At the command prompt, create a variable K in the base workspace.

K = 27;
3 In the Workspace browser, right-click the variable and select Save As.

To save multiple variables in one file, select all of the target variables in the Workspace browser,
and then right-click any of the selected variables.
4 In the dialog box, set Save as type to MATLAB Script. Set File name to loadvar and click
Save.

The script file loadvar.m appears in your current folder. You can open the file to view the
command that creates the variable K.
5 In the model, on the Modeling tab, select Model Settings > Model Properties.
6 In the Callbacks tab of the Model Properties dialog box, select PreLoadFcn as the callback that
you want to define. In the Model pre-load function pane, enter loadvar and click OK.
7 Save the model.

The next time that you open the model, the PreloadFcn callback loads the variable K into the base
workspace. You can also save the variable to a MAT-file, for example loadvar.mat, and set the
model callback to load loadvar.

To learn about callbacks, see “Customize Model Behavior with Callbacks” on page 4-68. To
programmatically define a callback for loading variables, see “Programmatically Store Workspace
Variables for a Model” on page 41-13.

When you save variables to a file, you must save the changes that you make to the variables during
your MATLAB session. To permanently store variables for a model, consider using a model workspace
or a data dictionary instead of a MAT-file or script file. For more information about permanently
storing variables, see “Determine Where to Store Variables and Objects for Simulink Models” on page
73-109.

Programmatically Store Workspace Variables for a Model

In the example above, you define a model callback that creates variables when you open a model. You
can programmatically save the variable and set the model callback.

41-13
41 Working with Block Parameters

1 At the command prompt, create the variable K in the base workspace.

K = 27;
2 Save the variable to a new script file named loadvar.m.

matlab.io.saveVariablesToScript('loadvar.m','K')
3 Set the model callback to load the script file.

set_param('mymodel','PreloadFcn','loadvar')
4 Save the model.

save_system('myModel')

The function matlab.io.saveVariablesToScript saves variables to a script file. To save


variables to a MAT-file, use the function save. To programmatically set model properties such as
callbacks, use the function set_param.

Manage and Edit Workspace Variables


When you use variables to set block parameter values, you store the variables in a workspace or data
dictionary. You can use the command prompt, the Model Explorer, and the Model Data Editor to
create, move, copy, and edit variables. You can also determine where a variable is used in a model,
list all of the variables that a model uses, and list all of the variables that a model does not use. For
more information, see “Create, Edit, and Manage Workspace Variables” on page 73-124.

Package Shared Breakpoint and Table Data for Lookup Tables


To share breakpoint vectors or table data between multiple n-D Lookup Table, Prelookup, and
Interpolation Using Prelookup blocks, consider storing the data in Simulink.LookupTable and
Simulink.Breakpoint objects instead of MATLAB variables or Simulink.Parameter objects.
This technique improves model readability by clearly identifying the data as parts of a lookup table
and explicitly associating breakpoint data with table data.

Store Standalone Lookup Table in Simulink.LookupTable Object

A standalone lookup table consists of a set of table data and one or more breakpoint vectors. You do
not share the table data or any of the breakpoint vectors with other lookup tables.

When you share a standalone lookup table, you use all of the table and breakpoint data together in
multiple n-D Lookup Table blocks. To store this data in a Simulink.LookupTable object:

1 Create the object in a workspace or data dictionary. For example, at the command prompt, enter:

myLUTObj = Simulink.LookupTable;
2 Use the properties of the object to store the values of the table and breakpoint data.
3 Use the properties of the object to configure a unique name for the structure type in the
generated code. In the property dialog box, under Struct Type definition, specify Name.
4 In the n-D Lookup Table blocks, set Data specification to Lookup table object.
5 To the right of Data specification, set Name to the name of the Simulink.LookupTable
object.

For ways to create and configure Simulink.LookupTable objects, see Simulink.LookupTable

41-14
Share and Reuse Block Parameter Values by Creating Variables

Store Shared Data in Simulink.LookupTable and Simulink.Breakpoint Objects

When you use Prelookup and Interpolation Using Prelookup blocks to more finely control the lookup
algorithm, you can share breakpoint vectors and sets of table data. For example, you can share a
breakpoint vector between two separate sets of table data. With this separation of the breakpoint
data from the table data, you can share individual parts of a lookup table instead of sharing the entire
lookup table.

To store breakpoint and table data:

1 Create a Simulink.LookupTable object for each unique set of table data. Create a
Simulink.Breakpoint object for each unique breakpoint vector, including breakpoint vectors
that you do not intend to share.
2 Use the properties of the objects to store the values of the table and breakpoint data.
3 Configure the Simulink.LookupTable objects to refer to the Simulink.Breakpoint objects
for breakpoint data. In the Simulink.LookupTable objects, set Specification to Reference.
Specify the names of the Simulink.Breakpoint objects.
4 In the Interpolation Using Prelookup blocks, set Specification to Lookup table object. Set
Name to the name of a Simulink.LookupTable object.

In the Prelookup blocks, set Specification to Breakpoint object. Set Name to the name of a
Simulink.Breakpoint object.

The example model fxpdemo_lookup_shared_param contains two Prelookup and two Interpolation
Using Prelookup blocks. Configure the blocks so that each combination of a Prelookup and an
Interpolation Using Prelookup block represents a unique lookup table. Share the breakpoint vector
between the two lookup tables. In this case, each lookup table has unique table data but shared
breakpoint data.

1 Open the example model.


2 In the Prelookup block dialog box, set Specification to Breakpoint object. Set Name to
sharedBkpts.
3
Click the button next to the value of the Name parameter. Select Create Variable.
4 In the Create New Data dialog box, set Value to Simulink.Breakpoint and click Create.

A Simulink.Breakpoint object appears in the base workspace.


5 In the property dialog box for sharedBkpts, specify Value as a vector such as [1 2 3 4 5 6
7 8 9 10]. Click OK.
6 In the Prelookup block dialog box, click OK.
7 In the Prelookup1 block dialog box, set Specification to Breakpoint object. Set Name to
sharedBkpts.
8 In the Interpolation Using Prelookup block dialog box, set Specification to Lookup table
object. Set Name to dataForFirstTable.
9
Click the button next to the value of the Name parameter. Select Create Variable.
10 In the Create New Data dialog box, set Value to Simulink.LookupTable and click Create.

A Simulink.LookupTable object appears in the base workspace.


11 In the property dialog box for dataForFirstTable, specify Value as a vector, such as [10 9 8
7 6 5 4 3 2 1].

41-15
41 Working with Block Parameters

12 Set Specification to Reference.


13 In the table under Specification, set Name to sharedBkpts and click OK.
14 In the Interpolation Using Prelookup block dialog box, click OK.
15 Configure the Interpolation Using Prelookup1 block to use a Simulink.LookupTable object
named dataForSecondTable. In the object property dialog box, specify Value as a vector, such
as [0 0.5 1 1.5 2 2.5 3 3.5 4 4.5]. Configure the object to refer to sharedBkpts for
the breakpoint data.

The model now represents two unique lookup tables:

• A combination of sharedBkpts and dataForFirstTable.


• A combination of sharedBkpts and dataForSecondTable.

These lookup tables share the same breakpoint data through sharedBkpts.

See Also

Related Examples
• “Create, Edit, and Manage Workspace Variables” on page 73-124
• “Data Objects” on page 73-76
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Set Block Parameter Values” on page 41-2

41-16
Parameter Interfaces for Reusable Components

Parameter Interfaces for Reusable Components


You can use subsystems, referenced models, and custom library blocks as reusable components in
other models. For guidelines to help you decide how to componentize a system, see “Explore Types of
Model Components” on page 23-4.

Typically, a reusable algorithm requires that numeric block parameters, such as the Gain parameter
of a Gain block, either:

• Use the same value in all instances of the component.


• Use a different value in each instance of the component. Each value is instance specific.

By default, if you use a literal number or expression to set the value of a block parameter, the
parameter uses the same value in all instances of the component. If you set multiple block parameter
values by using a MATLAB variable, Simulink.Parameter object, or other parameter object in a
workspace or data dictionary, these parameters also use the same value in all instances of the
component.

Referenced Models
If you use model referencing to create a reusable component, to set parameter values that are
specific to each instance, configure model arguments for the referenced model. When you instantiate
the model by adding a Model block to a different model, you set the values of the arguments in the
Model block. When you add another Model block to the same parent model or to a different model,
you can set different values for the same arguments. Optionally, if you create more than two
instances, you can set the same value for some of the instances and different values for the other
instances.

If a model has many model arguments, consider packaging the arguments into a single structure.
Instead of configuring many arguments, configure the structure as a single argument. Without
changing the mathematical functionality of the component, this technique helps you to reduce the
number of model argument values that you must set in each instance of the component.

For more information about model arguments, see “Parameterize Instances of a Reusable Referenced
Model” on page 8-80.

Subsystems
If you use subsystems or custom libraries to create reusable components, to set parameter values
that are specific to each instance, use masks, mask parameters, and parameter promotion. When you
instantiate the component in a model, you set the values of the mask parameters in the Subsystem
block. When you instantiate the component again in the same model or a different model, you can set
different values for the same mask parameters. Optionally, if you create more than two instances, you
can set the same value for some of the instances and different values for the other instances.

If the subsystem has many mask parameters, consider packaging the parameters into a single
structure. Instead of configuring many mask parameters, configure the structure as a single
parameter. Without changing the mathematical functionality of the component, this technique helps
you to reduce the number of mask parameter values that you must set in each instance of the
component.

For more information about subsystems, see Subsystem. For more information about custom block
libraries, see “Design and Create a Custom Block” on page 44-12. For more information about

41-17
41 Working with Block Parameters

masks, see “Masking Fundamentals” on page 43-3. For more information about structures, see
“Organize Related Block Parameter Definitions in Structures” on page 41-19.

See Also

Related Examples
• “Determine Where to Store Variables and Objects for Simulink Models” on page 73-109
• “Share and Reuse Block Parameter Values by Creating Variables” on page 41-9
• “Set Block Parameter Values” on page 41-2

41-18
Organize Related Block Parameter Definitions in Structures

Organize Related Block Parameter Definitions in Structures


When you use numeric MATLAB variables to set block parameter values in a model, large models can
accumulate many variables, increasing the effort of maintenance and causing the variable names to
grow in length.

Instead, you can organize these parameter values into structures. Each structure is a single variable
and each field of the structure stores a numeric parameter value. You can assign meaningful names to
the structures, substructures, and fields to indicate the purpose of each value.

Use structures to:

• Reduce the number of workspace variables that you must maintain.


• Avoid name conflicts between workspace variables.

You cannot create two variables that have the same name in the same scope, such as in the base
workspace. When you create structures, you must provide each field a name, but multiple
structures can each contain a field that uses the same name. Therefore, you can use each
structure and substructure as a namespace that prevents the field names from conflicting with
each other and with other variable names in the same scope.
• Logically group sets of block parameter values. For example, use nested structures to clearly
identify the parameter values that each subsystem or referenced model uses.

If you use mask parameters or model arguments to pass parameter values to the components of a
system, you can use structures to reduce the number of individual mask parameters or model
arguments that you must maintain. Instead of passing multiple variables, you can pass a single
structure variable.

For basic information about creating and manipulating MATLAB structures, see Structures. For basic
information about setting block parameter values in a model, see “Set Block Parameter Values” on
page 41-2.

To use structures to initialize bus signals, see “Specify Initial Conditions for Bus Elements” on page
82-72.

Create and Use Parameter Structure


This example shows how to create and use a parameter structure in a model.

The example model f14 uses multiple variables from the base workspace to set block parameter
values. For example, when you open the model, it creates the variables Zw, Mw, and Mq in the base
workspace. To organize these variables into a single structure variable:

1 At the command prompt, open the example model.

f14
2 At the command prompt, create the parameter structure myGains. Set the field values by using
the values of the target variables.

myGains.Zw = Zw;
myGains.Mw = Mw;
myGains.Mq = Mq;

41-19
41 Working with Block Parameters

3 In the Model Explorer, on the Model Hierarchy pane, click Base Workspace. In the Contents
pane, right-click the variable Mq and select Find Where Used.
4 In the Select a system dialog box, click the node f14 and click OK. Click OK when asked about
updating the diagram.
5 In the Contents pane, right-click the row corresponding to the block labeled Gain1 and select
Properties. The Gain1 block dialog box opens.
6 Change the value of the Gain parameter from Mq to myGains.Mq and click OK.
7 In the Contents pane, right-click the row corresponding to the Transfer Fcn.1 block and select
Properties.
8 Change the value of the Denominator coefficients parameter from [1,-Mq] to [1,-
myGains.Mq] and click OK.
9 In the Model Hierarchy pane, click Base Workspace. Use Find Where Used to locate the
blocks that use the variables Mw and Zw. In the block dialog boxes, replace the references to the
variable names according to the table.

Variable Name Replacement Name


Mw myGains.Mw
Zw myGains.Zw
10 Clear the old variables.

clear Zw Mw Mq

Each of the modified block parameters now uses a field of the myGains structure. The numeric value
of each structure field is equal to the value of the corresponding variable that you cleared.

You can migrate a model to use a single parameter structure instead of multiple workspace variables.

Store Data Type Information in Field Values


To use a structure or array of structures to organize parameter values that use a data type other than
double, you can explicitly specify the type when you create the structure. When you create the
structure, use typed expressions such as single(15.23) to specify the field values.

myParams.Gain = single(15.23);

If you want to change the field value later, you must remember to explicitly specify the type again. If
you do not specify the type, the field value uses the data type double instead:

myParams.Gain = 15.23;
% The field 'Gain' now uses the data type 'double' instead of 'single'.

To preserve the type specification, you can use subscripted assignment to assign a new value to the
field:

% Assign value of type 'single'.


myParams.Gain = single(15.23);

% Assign new value while retaining type 'single'.


myParams.Gain(:) = 11.79;

To match a fixed-point data type, set the field value by using an fi object.

41-20
Organize Related Block Parameter Definitions in Structures

Control Field Data Types and Characteristics by Creating Parameter


Object
A Simulink.Parameter object allows you to separate the value of a block parameter from its data
type. If you use a parameter object to store a structure or array of structures, you can create a
Simulink.Bus object to use as the data type of the entire structure.

You can use the bus object and the parameter object to explicitly control:

• The data type of each field. When you use this technique, you do not have to remember to use
typed expressions or subscripted assignment to set the field values.
• The complexity, dimensions, and units of each field.
• The minimum and maximum value of each field if the field represents a tunable parameter value.
• The shape of the entire structure. The shape of the structure is the number, names, and hierarchy
of fields.
• The tunability of the structure in the code that you generate from the model.

1 Create a parameter structure myParams.

myParams = struct(...
'SubsystemA',struct(...
'Gain',15.23,...
'Offset',89,...
'Init',0.59),...
'SubsystemB',struct(...
'Coeffs',[5.32 7.99],...
'Offset',57,...
'Init1',1.76,...
'Init2',2.76)...
);
2 Use the function Simulink.Bus.createObject to create Simulink.Bus objects that
represent the structure and substructures.

Simulink.Bus.createObject(myParams)

Because myParams contains two unique substructures, the function creates three
Simulink.Bus objects: one named slBus1 to represent the parent structure myParams, one
named SubsystemA for the substructure SubsystemA, and one named SubsystemB for the
substructure SubsystemB.
3 Rename the bus object slBus1 as myParamsType.

myParamsType = slBus1;
clear slBus1
4 Store the structure myParams in a Simulink.Parameter object.

myParams = Simulink.Parameter(myParams);

The Value property of the parameter object contains the structure.


5 Set the data type of the parameter object to the bus object myParamsType.

myParams.DataType = 'Bus: myParamsType';


6 Open the Type Editor to view the bus objects.

typeeditor

41-21
41 Working with Block Parameters

7 In the table, expand the bus object named SubsystemA. Then, set the data types according to
the figure.

8 Optionally, change the data types for the bus object named SubsystemB.

The parameter object myParams stores the parameter structure. The data type of the parameter
object is the bus object myParamsType. Prior to simulation and code generation, the parameter
object casts the field values to the data types that you specified in the bus object.

To use one of the fields to set a block parameter value, specify an expression such as
myParams.SubsystemB.Init1.

To access the field values at the command prompt, use the Value property of the parameter object.
Because the bus object controls the field data types, you do not need to use a typed expression to set
the field value.

myParams.Value.SubsystemA.Gain = 12.79;

The bus object strictly controls the field characteristics and the shape of the structure. For example,
if you set the value of the two-element field myParams.SubsystemB.Coeffs to a three-element
array, the model generates an error when you set a block parameter value. To change the dimensions
of the field, modify the element Coeffs in the bus object SubsystemB.

To manipulate bus objects after you create them, see “Create Simulink Bus Objects” on page 82-66
and “Save Simulink Bus Objects” on page 82-67.

Match Field Data Type with Signal Data Type

Suppose that you use the field myParams.SubsystemA.Gain to set the value of the Gain parameter
in a Gain block. If you want the data type of the field to match the data type of the output signal of
the block, you cannot rely on context-sensitive data typing (see “Context-Sensitive Data Typing” on
page 41-44). Consider using a Simulink.AliasType or a Simulink.NumericType object to set
the data type of the field and the signal. If you do not use a data type object, you must remember to
change the data type of the field whenever you change the data type of the signal.

1 In the MATLAB Command Window, create a Simulink.AliasType object that represents the
data type single.

myType = Simulink.AliasType;
myType.BaseType = 'single';
2 In the Gain block dialog box, on the Signal Attributes tab, set Output data type to myType.
3 In the MATLAB Command Window, open the Type Editor.

typeeditor

41-22
Organize Related Block Parameter Definitions in Structures

4 Select the bus object named SubsystemA. Then, set the data type of the element named Gain to
myType.

Now, both the output signal of the Gain block and the structure field myParams.SubsystemA.Gain
use the data type that you specify by using the BaseType property of myType.

For more information about data type objects, see Simulink.AliasType and
Simulink.NumericType.

Manage Structure Variables


To create, modify, and inspect a variable whose value is a structure, you can use the Variable Editor.
For more information, see “Modify Structure and Array Variables Interactively” on page 73-125.

Define Parameter Hierarchy by Creating Nested Structures


To further organize block parameter values, create a hierarchy of nested structures.

For example, suppose that you create subsystems named SubsystemA and SubsystemB in your
model. You use variables such as Offset_SubsystemA and Offset_SubsystemB to set block
parameter values in the subsystems.

Gain_SubsystemA = 15.23;
Offset_SubsystemA = 89;
Init_SubsystemA = 0.59;

Coeffs_SubsystemB = [5.32 7.99];


Offset_SubsystemB = 57;
Init1_SubsystemB = 1.76;
Init2_SubsystemB = 2.76;

Create a parameter structure that contains a substructure for each subsystem. Use the values of the
existing variables to set the field values.

myParams = struct(...
'SubsystemA',struct(...
'Gain',Gain_SubsystemA,...
'Offset',Offset_SubsystemA,...
'Init',Init_SubsystemA),...
'SubsystemB',struct(...
'Coeffs',Coeffs_SubsystemB,...
'Offset',Offset_SubsystemB,...
'Init1',Init1_SubsystemB,...
'Init2',Init2_SubsystemB)...
);

The single structure variable myParams contains all of the parameter information for the blocks in
the subsystems. Because each substructure acts as a namespace, you can define the Offset field
more than once.

To use the Offset field from the substructure SubsystemB as the value of a block parameter, specify
the parameter value in the block dialog box as the expression myParams.SubsystemB.Offset.

41-23
41 Working with Block Parameters

Group Multiple Parameter Structures into an Array


To organize parameter structures that have similar characteristics, you can create a single variable
whose value is an array of structures. This technique helps you to parameterize a model that contains
multiple instances of an algorithm, such as a library subsystem or a referenced model that uses
model arguments.

Suppose that you create two identical subsystems in a model.

Suppose that the blocks in each subsystem require three numeric values to set parameter values.
Create an array of two structures to store the values.

myParams(1).Gain = 15.23;
myParams(1).Offset = 89;
myParams(1).Init = 0.59;

myParams(2).Gain = 11.93;
myParams(2).Offset = 57;
myParams(2).Init = 2.76;

Each structure in the array stores the three parameter values for one of the subsystems.

To set the value of a block parameter in one of the subsystems, specify an expression that references
a field of one of the structures in the array. For example, use the expression myParams(2).Init.

Organize Parameter Values for Reusable Components and Iterative Algorithms

You can also partition an array of structures in a For Each Subsystem block. This technique helps you
to organize workspace variables when a model executes an algorithm repeatedly, for example by
iterating the algorithm over a vector signal. For an example, see “Repeat an Algorithm Using a For-
Each Subsystem” on page 10-34.

If you use model arguments to specify different parameter values across multiple instances of a
referenced model, you can use arrays of structures to organize the model argument values. In the
referenced model workspace, create a structure variable and configure the model to use the
structure as a model argument. Use the fields of the structure to set block parameter values in the
model. Then, create an array of structures in the base workspace or a data dictionary to which the
parent model or models are linked. In the parent model or models, use each of the structures in the

41-24
Organize Related Block Parameter Definitions in Structures

array as the value of the model argument in a Model block. Each structure in the array stores the
parameter values for one instance of the referenced model.

The model sldemo_mdlref_datamngt contains three instances (Model blocks) of the masked
referenced model sldemo_mdlref_counter_datamngt. The base workspace variables IC1, IC2,
Param1, and Param2 are Simulink.Parameter objects whose values are structures. The parent
model uses these variables to set the values of mask parameters on the Model blocks. Since IC1 is
structurally identical to IC2, and Param1 to Param2, you can combine these four structures into two
arrays of structures.

1 Open the example parent model.

openExample('sldemo_mdlref_datamngt')

The model creates the four Simulink.Parameter objects in the base workspace.
2 Open the example referenced model.

sldemo_mdlref_counter_datamngt

The model workspace defines two model arguments, CounterICs and CounterParams, whose
values are structures. The blocks in the model use the fields of these structures to set parameter
values.
3 In the model sldemo_mdlref_datamngt, open the Model Data Editor (on the Modeling tab,
click Model Data Editor). In the Model Data Editor, inspect the Parameters tab.
4 In the model, click one of the Model blocks.

The Model Data Editor highlights rows that correspond to two mask parameters on the selected
Model block. The block uses the mask parameters to set the values of the two model arguments
defined by the referenced model, sldemo_mdlref_counter_datamngt. Each Model block uses
a different combination of the four parameter objects from the base workspace to set the
argument values.
5 In the Model Data Editor Value column, click one of the cells to begin editing the value of the
corresponding mask parameter (for example, IC1). Next to the parameter value, click the action
button and select Open. The property dialog box for the parameter object opens.
6 In the property dialog box, next to the Value box, click the action button and select Open
Variable Editor.

The Variable Editor shows that the parameter object stores a structure. The structures in Param2
and IC2 have the same fields as the structures in Param1 and IC1 but different field values.
7 At the command prompt, combine the four parameter objects into two parameter objects whose
values are arrays of structures.

% Create a new parameter object by copying Param1.


Param = Param1.copy;

% Use the structure in Param2 as the second structure in the new object.
Param.Value(2) = Param2.Value;
% The value of Param is now an array of two structures.

% Delete the old objects Param1 and Param2.


clear Param1 Param2

% Create a new parameter object by copying IC1.


% Use the structure in IC2 as the second structure in the new object.
IC = IC1.copy;

41-25
41 Working with Block Parameters

IC.Value(2) = IC2.Value;
clear IC1 IC2
8 In the parent model, in the Model Data Editor, use the Value column to replace the values of the
mask parameters according to the table

Previous Value New Value


Param1 Param(1)
IC1 IC(1)
Param2 Param(2)
IC2 IC(2)

Each Model block sets the value of the model argument CounterICs by using one of the structures
in the array IC. Similarly, each block sets the value of CounterParams by using one of the structures
in Param.

Enforce Uniformity in an Array of Structures

All of the structures in an array of structures must have the same hierarchy of fields. Each field in the
hierarchy must have the same characteristics throughout the array. You can use a parameter object
and a bus object to enforce this uniformity among the structures.

To use a parameter object to represent an array of parameter structures, set the value of the object to
the array of structures:

% Create array of structures.


myParams(1).Gain = 15.23;
myParams(1).Offset = 89;
myParams(1).Init = 0.59;
myParams(2).Gain = 11.93;
myParams(2).Offset = 57;
myParams(2).Init = 2.76;

% Create bus object.


Simulink.Bus.createObject(myParams);
myParamsType = slBus1;
clear slBus1

% Create parameter object and set data type.


myParams = Simulink.Parameter(myParams);
myParams.DataType = 'Bus: myParamsType';

To use one of the fields to set a block parameter value, specify an expression such as
myParams(2).Offset.

To access the field values at the command prompt, use the Value property of the parameter object.

myParams.Value(2).Offset = 129;

Create a Structure of Constant-Valued Signals


You can use a structure in a Constant block to create a single bus that transmits multiple numeric
constants. For more information, see Constant. For information about buses, see “Composite
Interface Guidelines” on page 82-2.

41-26
Organize Related Block Parameter Definitions in Structures

Considerations Before Migrating to Parameter Structures


• Before you migrate a model to use parameter structures, discover all of the blocks in the target
model and in other models that use the variables that you intend to replace.

For example, suppose two blocks in a model use the workspace variable myVar. If you create a
structure myParams with a field myVar, and set the parameter value in only one of the blocks to
myParams.myVar, the other block continues to use the variable myVar. If you delete myVar, the
model generates an error because the remaining block requires the deleted variable.

To discover all of the blocks that use a variable:

1 Open all models that might use the variable. If the models are in a model reference hierarchy,
you can open only the top model.
2 In the Model Data Editor or in the Model Explorer Contents pane, right-click the variable and
select Find Where Used. The Model Explorer displays all of the blocks that use the variable.

You can discover variable usage only in models that are open. Before you migrate to parameter
structures, open all models that might use the target variables. For more information about
determining variable usage in a model, see “Finding Blocks That Use a Specific Variable” on page
73-130.

Alternatively, you can refrain from deleting myVar. However, if you change the value of the
myParams.myVar structure field, you must remember to change the value of myVar to match.
• You can combine multiple separate variables or parameter objects (such as
Simulink.Parameter) into a structure that you store in a single variable or parameter object (to
combine parameter objects, see “Combine Existing Parameter Objects into a Structure” on page
41-27). However, the resulting variable or object acts as a single entity. As a result, you cannot
apply different code generation settings, such as storage classes, to individual fields in the
structure.

Combine Existing Parameter Objects into a Structure


When you use parameter objects to set block parameter values (for example, so you can apply storage
classes), to combine the objects into a single structure:

1 Create a MATLAB structure and store it in a variable. To set the field values, use the parameter
values that each existing parameter object stores.
2 Convert the variable to a parameter object. Create and use a Simulink.Bus object as the data
type of the parameter object (see “Control Field Data Types and Characteristics by Creating
Parameter Object” on page 41-21).
3 Choose a storage class to apply to the resulting parameter object. You can choose only one
storage class, which applies to the entire structure.
4 Transfer parameter metadata, such as the Min and Max properties of the existing parameter
objects, to the corresponding properties of the Simulink.BusElement objects in the bus object.

For example, suppose you have three individual parameter objects.

coeff = Simulink.Parameter(17.5);
coeff.Min = 14.33;
coeff.DataType = 'single';
coeff.StorageClass = 'ExportedGlobal';

41-27
41 Working with Block Parameters

init = Simulink.Parameter(0.00938);
init.Min = -0.005;
init.Max = 0.103;
init.DataType = 'single';
init.StorageClass = 'Model default';

offset = Simulink.Parameter(199);
offset.DataType = 'uint8';
offset.StorageClass = 'ExportedGlobal';

1 Create a structure variable.

myParams.coeff = coeff.Value;
myParams.init = init.Value;
myParams.offset = offset.Value;
2 Convert the variable to a parameter object.

myParams = Simulink.Parameter(myParams);
3 Create a bus object and use it as the data type of the parameter object.

Simulink.Bus.createObject(myParams.Value);
paramsDT = copy(slBus1);

myParams.DataType = 'Bus: paramsDT';


4 Transfer metadata from the old parameter objects to the bus elements in the bus object.

% coeff
paramsDT.Elements(1).Min = coeff.Min;
paramsDT.Elements(1).DataType = coeff.DataType;

% init
paramsDT.Elements(2).Min = init.Min;
paramsDT.Elements(2).Max = init.Max;
paramsDT.Elements(2).DataType = init.DataType;

% offset
paramsDT.Elements(3).DataType = offset.DataType;

To help you write a script that performs this transfer operation, you can use the properties
function to find the properties that the bus elements and the old parameter objects have in
common. To list the structure fields so that you can iterate over them, use the fieldnames
function.
5 Apply a storage class to the parameter object.

myParams.StorageClass = 'ExportedGlobal';

Now, you can use the fields of myParams, instead of the old parameter objects, to set the block
parameter values.

Parameter Structures in the Generated Code


You can configure parameter structures to appear in the generated code as structures and arrays of
structures. For information about generating code with parameter structures, see “Organize Data
into Structures in Generated Code” (Simulink Coder).

41-28
Organize Related Block Parameter Definitions in Structures

Parameter Structure Limitations


• All of the structures in an array of structures must have the same hierarchy of fields. Each field in
the hierarchy must have the same characteristics throughout the array:

• Field name
• Numeric data type, such as single or int32
• Complexity
• Dimensions

Suppose that you define an array of two structures.

paramStructArray = ...
[struct('sensor1',int16(7),'sensor2',single(9.23)) ...
struct('sensor1',int32(9),'sensor2',single(11.71))];

You cannot use any of the fields in a block parameter because the field sensor1 uses a different
data type in each structure.
• Parameter structures do not support context-sensitive data typing in the generated code. If the
parameter structure is tunable in the code, the fields of the structure use the numeric data types
that you specify by using either typed expressions or a Simulink.Bus object. If you do not use
typed expressions or a Simulink.Bus object, the fields of the structure use the double data
type.
• The code generator does not preserve the tunability of a structure if the structure or any of its
substructures has a field with an empty value (set to []).

Package Shared Breakpoint and Table Data for Lookup Tables


When you share data between lookup table blocks, consider using Simulink.LookupTable and
Simulink.Breakpoint objects instead of structures to store and group the data. This technique
improves model readability by clearly identifying the data as parts of a lookup table and explicitly
associating breakpoint data with table data. See “Package Shared Breakpoint and Table Data for
Lookup Tables” on page 41-14.

Create Parameter Structure According to Structure Type from Existing


C Code
You can create a parameter structure that conforms to a struct type definition that your existing C
code defines. Use this technique to:

• Replace existing C code with a Simulink model.


• Integrate existing C code for simulation in Simulink (for example, by using the Legacy Code Tool).
For an example, see “Integrate C Function Whose Arguments Are Pointers to Structures”.
• Generate C code (Simulink Coder) that you can compile with existing C code into a single
application. For an example, see “Exchange Structured and Enumerated Data Between Generated
and External Code” (Embedded Coder).

In MATLAB, store the parameter structure in a parameter object and use a bus object as the data
type (see “Control Field Data Types and Characteristics by Creating Parameter Object” on page 41-

41-29
41 Working with Block Parameters

21). To create the bus object according to your C-code struct type, use the
Simulink.importExternalCTypes function.

See Also

Related Examples
• “Set Block Parameter Values” on page 41-2
• “Determine Where to Store Variables and Objects for Simulink Models” on page 73-109
• Structures
• “Switch Between Sets of Parameter Values During Simulation and Code Execution” on page 41-
56

41-30
Tune and Experiment with Block Parameter Values

Tune and Experiment with Block Parameter Values


As you construct a model you can experiment with block parameters, such as the coefficients of a
Transfer Fcn block, to help you decide which blocks to use. You can simulate the model with different
parameter values, and capture and observe the simulation output.

You can change the values of most numeric block parameters during a simulation. To observe the
effects, you can visualize the simulation output in real time. This technique allows you to quickly test
parameter values while you develop an algorithm. You can visually:

• Tune and optimize control parameters.


• Calibrate model parameters.
• Test control robustness under different conditions.

When you begin a simulation, Simulink first updates the model diagram. This operation can take time
for larger models. To test parameter values without repeatedly updating the model diagram, you can
tune the parameter values during a single simulation run.

Alternatively, to avoid updating the model diagram, use Fast Restart. For more information about Fast
Restart, see “Get Started with Fast Restart” on page 87-7.

If you cannot visually analyze the simulation output in real time, or if you must run many simulations,
consider using a programmatic approach to sweeping parameter values. You can capture the
simulation output data and perform analysis later. For more information, see “Optimize, Estimate, and
Sweep Block Parameter Values” on page 41-38.

For basic information about accessing and setting block parameter values, see “Set Block Parameter
Values” on page 41-2.

Iteratively Adjust Block Parameter Value Between Simulation Runs


This example shows how to prototype a model by changing block parameter values between
simulation runs. You can experiment with parameter values and observe simulation results to help
you decide which blocks to use and how to build your model.

The “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys represents the
fueling system of a gasoline engine. A subsystem in the model, feedforward_fuel_rate, calculates
the fuel demand of the engine by using the constant number 14.6, which represents the ideal
(stoichiometric) ratio of air to fuel that the engine consumes. Two blocks in the subsystem use the
number to set the values of parameters.

Suppose that you want to change the design value of the ideal air-to-fuel ratio from 14.6 to 17.5 to
observe the effect on the fuel demand. To store the design value in the model, you can modify the
value in the block dialog boxes. Alternatively, you can store the value in a variable with a meaningful
name, which allows you to reuse the value in the two blocks.

To observe the change in simulation outputs by changing the value in the block dialog boxes:

1 Open the “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')
sldemo_fuelsys
2 Set the model simulation time from 2000 to 50 for a faster simulation.

41-31
41 Working with Block Parameters

3 In the model, open the Scope block dialog box.

4 Simulate the model. Resize the window in the Scope dialog box to see all of the simulation
results.

The scope display shows that throughout the simulation, the fuel signal oscillates between
approximately 0.9 and 1.6. The air_fuel_ratio signal quickly climbs to 15 without
overshoot.
5 In the model, open the Model Data Editor. On the Modeling tab, click Model Data Editor. In
the Model Data Editor, inspect the Parameters tab.
6 In the model or at the command prompt, navigate to the target subsystem.
open_system(...
'sldemo_fuelsys/fuel_rate_control/fuel_calc/feedforward_fuel_rate')

7 In the Model Data Editor, use the Value column to change the Constant value (Value)
parameter of the Constant block labeled rich from 1/(14.6*0.8) to 1/(17.5*0.8).
8 Similarly, change the Constant value parameter of the block labeled normal from 1/14.6 to
1/17.5.
9 Simulate the model.

The scope display shows that the signals now respond differently.

To replace the literal values in the block dialog boxes with a numeric variable:

1 Use the Model Data Editor to set the value of the normal Constant block to 1/mixture.
2 Set the value of the rich block to 1/(mixture*0.8).
3
While editing the rich value, next to 1/(mixture*0.8), click the action button and select
Create.
4 In the Create New Data dialog box, set Value to 17.5 and click Create.

The numeric variable mixture appears in the base workspace with value 17.5. Between
simulation runs, you can change the value of mixture in the base workspace instead of changing
the parameter values in the block dialog boxes.

Tune Block Parameter Value During Simulation


This example shows how to observe the effect of changing a block parameter value during a
simulation. This technique allows you to avoid updating the model diagram between simulation runs
and to interactively test and debug your model.

The example model sldemo_fuelsys contains a Constant block, Throttle Command, that
represents the throttle command. To observe the effect of increasing the magnitude of the command
during simulation:

41-32
Tune and Experiment with Block Parameter Values

1 Open the “Model Fault-Tolerant Fuel Control System” example model sldemo_fuelsys.
openExample('simulink_automotive/ModelingAFaultTolerantFuelControlSystemExample')
sldemo_fuelsys
2 In the model, open the Scope block dialog box.

3 Begin a simulation.

The model is configured to simulate 2000 seconds. During the simulation, the values of the fuel
and air_fuel_ratio signals appear on the scope graph in real time.
4 In the model, when the status bar indicates approximately 1000 (1000 seconds), click the Pause
button to pause the simulation.
5 In the scope display, the fuel graph plots the simulation output prior to the pause time.
6 In the model, on the Modeling tab, click Model Data Editor.
7 In the Model Data Editor, select the Parameters tab.
8 In the model, select the Throttle Command block.
9 In the Model Data Editor, select the rep_seq_y row. Make sure that you do not select the
rep_seq_t row as well.
10 For the rep_seq_y row, change the value in the Value column from [10 20 10] to [10 30
10].
11
Click the Step Forward button to advance the simulation step by step. Click the button about
15 times or until you see a change in the fuel graph in the scope display.

The plot of the signal fuel indicates a sharp increase in fuel demand that corresponds to the
increased throttle command.
12 In the model, resume the simulation by clicking the Continue button .

The scope display shows the significant periodic increase in fuel demand, and the periodic
reduction in the air-to-fuel ratio, throughout the rest of the simulation.

During the simulation, you must update the model diagram after you change the value of a workspace
variable. To update the model diagram, on the Simulink Toolstrip, on the Modeling tab, in the
Compile section, click Update Model.

Prepare for Parameter Tuning and Experimentation


• Use workspace variables to set block parameter values.

To access the value of a block parameter, such as the Constant value parameter of a Constant
block, you must navigate to the block in the model and open the block dialog box, search for the
block by using the Model Explorer, or use the function set_param at the command prompt.

Alternatively, if you set the block parameter value by creating a workspace variable, you can
change the value of the variable by using the command prompt, the MATLAB Workspace browser,
or the Model Explorer. You can also create a variable to set the same value for multiple block
parameters. When you change the variable value, all of the target block parameters use the new

41-33
41 Working with Block Parameters

value. For more information about accessing and setting block parameter values, see “Set Block
Parameter Values” on page 41-2.
• Visualize simulation output.

To observe simulation output in real time while you tune block parameter values, you can use
blocks in a model such as the Scope block. You can also capture simulation output at the end of a
simulation run, and view the data in the Simulation Data Inspector. For more information, see
“Decide How to Visualize Simulation Data” on page 33-2.
• Specify value ranges for block parameters that you expect to tune during simulation.

If you expect another person to use your model and tune the parameter, you can control the
allowed tuning values by specifying a range. Also, it is a best practice to specify value ranges for
all fixed-point block parameters that you expect to tune. To specify block parameter value ranges,
see “Specify Minimum and Maximum Values for Block Parameters” on page 41-52.
• Control simulation duration and pace.

A simulation run can execute so quickly that you cannot tune block parameter values. Also, if you
want to change a parameter value at a specific simulation time, you must learn to control the
simulation pace. You can configure the simulation to run for a specific duration or to run forever,
and pause and advance the simulation when you want to. For more information, see “Simulate a
Model Interactively” on page 27-2 and “Run Simulations Programmatically” on page 28-2.

Interactively Tune Using Dashboard Blocks


You can tune block parameter values by adding blocks from the Dashboard library to your model.
Dashboard blocks allow you to adjust the parameter values of other blocks, and to observe simulation
output in real time, by interacting with knobs, switches, and readouts that mimic the appearance of
industrial controls. You can interact with the Dashboard blocks without having to locate the target
block parameters in the model. For more information, see “Tune and Visualize Your Model with
Dashboard Blocks” on page 32-2.

Which Block Parameters Are Tunable During Simulation?


Nontunable block parameters are parameters whose values you cannot change during simulation. For
example, you cannot tune the Sample time block parameter. If a parameter is nontunable, you
cannot change its value during simulation by changing the value in the block dialog box or by
changing the value of a workspace variable.

Nontunable block parameters include:

• Sample times.
• Parameters that control the appearance or structure of a block such as the number of inputs of a
Sum block.
• Priority, which allows you to control block execution order.
• Parameters that control the block algorithm, such as the Integrator method parameter of a
Discrete-Time Integrator block.

To determine whether a block parameter is tunable during simulation, use one of these techniques:

• Begin a simulation and open the block dialog box. If the value of the target block parameter is
gray during simulation, you cannot tune the parameter.

41-34
Tune and Experiment with Block Parameter Values

• At the command prompt, determine whether the flags read-write and read-only-if-
compiled describe the parameter.

1 Select the block in the model.


2 At the command prompt, use the function get_param to return information about the block
dialog box parameters. The function returns a structure that has a field for each parameter in
the block dialog box.

paramInfo = get_param(gcb,'DialogParameters');

Alternatively, rather than locating and selecting the block in the model, you can replace gcb
with the block path, such as 'myModel/mySubsystem/myBlock'.
3 View the information about the target block parameter. For example, to view the information
about the Sample time parameter of a block, view the value of the field SampleTime, which
is also a structure.

paramInfo.SampleTime

ans =

Prompt: 'Sample time:'


Type: 'string'
Enum: {}
Attributes: {'read-write' 'read-only-if-compiled' 'dont-eval'}
4 Inspect the structure’s Attributes field, whose value is a cell array of character vectors. If
the flag read-write appears in the cell array, you can modify the parameter value. However,
if the flag read-only-if-compiled also appears in the cell array, you cannot modify the
parameter value during simulation.

If you use masks to create custom interfaces for blocks and subsystems, you can control the tunability
of individual mask parameters. If you use model arguments to parameterize referenced models, you
can tune the value of each model argument in each Model block.

Why Did the Simulation Output Stay the Same?


If the output of your simulation does not change after you change a parameter value, use these
troubleshooting techniques:

• Locate the definition of a workspace variable.

If you use a workspace variable to set block parameter values, determine where the variable
definition resides. For example, if you define a variable myVar in a model workspace and use it to
set a block parameter value in the model, you cannot change the parameter value by changing the
value of a variable named myVar in the base workspace. You must access the variable definition in
the model workspace.

To locate the definition of a variable, while editing the value of a block parameter that uses the
variable, click the nearby action button and select Explore. A dialog box opens, such as the
Model Explorer, which displays the definition of the variable in the appropriate workspace. For
more information about how models use variables, see “Symbol Resolution” on page 73-151.
• Specify value ranges for fixed-point parameters that you want to tune during simulation.

41-35
41 Working with Block Parameters

If the block parameter you want to tune uses a fixed-point data type with best-precision scaling,
specify a minimum and maximum value for the parameter so that Simulink can calculate and apply
an appropriate scaling. If you do not specify a value range, Simulink might apply a scaling that
excludes the tuning values that you want to use. To specify value ranges, see “Specify Minimum
and Maximum Values for Block Parameters” on page 41-52.
• Update the model diagram during a simulation run. If you use a workspace variable to set the
value of one or more block parameters, after you change the value of the variable during a
simulation, you must update the model diagram.

Tunability Considerations and Limitations for Other Modeling Goals


Referenced Models

When you use Model blocks, these parameter tunability limitations apply:

• If you set the simulation mode of a Model block to an accelerated mode or if you simulate the
parent model in an accelerated mode, you cannot tune block parameters in the referenced model
during simulation. However, if the referenced model uses variables in the base workspace or a
data dictionary to set parameter values, you can tune the values of the variables.
• Suppose you use a MATLAB variable or Simulink.Parameter object in a model workspace to set
the value of a block parameter in a model. If you use a Model block to refer to this model:

• And you set the simulation mode of the Model block to an accelerated mode or simulate the
parent model in an accelerated mode, you cannot change the value of the variable or object
during the simulation.
• When you simulate the parent model in an accelerated mode, changing the value of the
variable or object between simulation runs causes Simulink to regenerate code.
• And you use additional Model blocks to refer to the model multiple times in the parent model,
you can choose a different simulation mode for each Model block. If at least one block uses
normal simulation mode and any other block uses a different simulation mode, you cannot
change the value of the variable or object during simulation. Also, when you simulate the
parent model with fast restart on, you cannot change the value of the variable or object
between fast-restart simulation runs.

As a workaround, move the variable or object to the base workspace or a data dictionary.

Accelerator and SIL/PIL Simulations

These tunability limitations apply to accelerator, rapid accelerator, SIL, and PIL simulations:

• Suppose you use a MATLAB variable or Simulink.Parameter object in a model workspace to set
the value of a block parameter in a model. If you use the sim function to simulate the model in
rapid accelerator mode and set the RapidAcceleratorUpToDateCheck pair argument to
'off', you cannot use the RapidAcceleratorParameterSets pair argument to specify
different values for the variable or object. The structure returned by
Simulink.BlockDiagram.buildRapidAcceleratorTarget does not contain information
about the variable or object.
• If a block parameter value references workspace variables, you cannot change the block
parameter value during rapid accelerator simulation, such as by using the function set_param.
Instead, you can tune the values of the referenced variables.

41-36
Tune and Experiment with Block Parameter Values

Alternatively, use parameter sets to tune runtime parameters in between rapid accelerator
simulations. For more information, see “Tuning Runtime Parameters” on page 38-8.

For more information about parameter tunability during accelerated simulations, see “Tuning
Runtime Parameters” on page 38-8 and “sim in parfor with Rapid Accelerator Mode” on page 28-16.
For more information about parameter tunability during SIL and PIL simulations, see “Tunable
Parameters and SIL/PIL” (Embedded Coder).

Fast Restart

For more information about parameter tunability when you use fast restart, see “Get Started with
Fast Restart” on page 87-7.

Code Generation and Simulation of External Programs

Parameters that are tunable during simulation can appear as nontunable inlined parameters in the
generated code. If you simulate an external program by using SIL, PIL, or External mode simulation,
parameter tunability during the simulation and between simulation runs can depend on your code
generation settings.

To control parameter tunability in the generated code, you can adjust the code generation settings for
a model by using the configuration parameter Default parameter behavior. You can also adjust
settings for individual MATLAB variables, Simulink.Parameter objects, and other parameter
objects. For more information, see “Preserve Variables in Generated Code” (Simulink Coder).

Stateflow Charts

To debug a Stateflow chart by changing data during simulation, see “Set Breakpoints to Debug
Charts” (Stateflow).

See Also
set_param

Related Examples
• “Specify Minimum and Maximum Values for Block Parameters” on page 41-52
• “Parameter Tuning in Rapid Accelerator Mode” on page 38-7
• “Create, Edit, and Manage Workspace Variables” on page 73-124
• “Switch Between Sets of Parameter Values During Simulation and Code Execution” on page 41-
56

41-37
41 Working with Block Parameters

Optimize, Estimate, and Sweep Block Parameter Values


When you sweep one or more parameters, you change their values between simulation runs, and
compare and analyze the output signal data from each run. Use parameter sweeping to tune control
parameters, estimate unknown model parameters, and test the robustness of a control algorithm by
taking into consideration uncertainty in the real-world system.

You can sweep block parameter values or the values of workspace variables that you use to set the
parameter values. Use the Parameters tab on the Model Data Editor (on the Modeling tab, click
Model Data Editor), the Property Inspector (on the Modeling tab, under Design, click Property
Inspector), the command prompt, or scripts to change parameter values between simulation runs.

If you want to repeatedly change the value of a block parameter, consider creating a variable in a
workspace. You can use the Model Explorer or programmatic commands to change the value of the
variable instead of locating or identifying the block in the model. Also, several features and products
that facilitate parameter optimization, estimation, and sweeping require that you set block parameter
values by creating workspace variables.

To learn how to manipulate parameter values during the iterative process of creating a model, see
“Tune and Experiment with Block Parameter Values” on page 41-31.

For basic information about accessing and setting block parameter values as you design a model, see
“Set Block Parameter Values” on page 41-2. For basic information about programmatically simulating
a model, such as by using a script, see “Run Simulations Programmatically” on page 28-2.

Sweep Parameter Value and Inspect Simulation Results

This example shows how to change a block parameter value between multiple programmatic
simulation runs. Use this technique to determine an optimal parameter value by comparing the
output signal data of each run.

The example model ex_sldemo_absbrake uses a Constant block to specify a slip setpoint for an
anti-lock braking system. Simulate the model with two different slip setpoint values, 0.24 and 0.25,
and compare the output wheel speed of each simulation run.

To store the setpoint value, create a variable in the base workspace. This technique enables you to
assign a meaningful name to the value.

Open the example model.

open_system('ex_sldemo_absbrake');

41-38
Optimize, Estimate, and Sweep Block Parameter Values

On the Modeling tab, click Model Data Editor.

In the Model Data Editor, select the Signals tab.

Set the Change view drop-down list to Instrumentation. The Log Data column shows that the
signals yout (which is a virtual bus) and slp are configured for logging. When you simulate the
model, you can collect and later inspect the values of these signals by using the Simulation Data
Inspector.

In the Model Data Editor, select the Parameters tab. Set Change view to Design.

In the model, select the Constant block labeled Desired relative slip. The Model Data Editor
highlights the row that corresponds to the Constant value parameter of the block.

Use the Value column to set the parameter value to relSlip.

While editing the value, next to relSlip, click the action button (with three vertical dots) and select
Create.

In the Create New Data dialog box, set Value to 0.2 and click Create. A variable, whose value is
0.2, appears in the base workspace. The model now acquires the relative slip setpoint from this
variable.

Alternatively, you can use these commands at the command prompt to create the variable and
configure the block:

relSlip = 0.2;
set_param('ex_sldemo_absbrake/Desired relative slip','Value','relSlip')

41-39
41 Working with Block Parameters

At the command prompt, create an array to store the two experimentation values for the relative slip
setpoint, 0.24 and 0.25.

relSlip_vals = [0.24 0.25];

Create a Simulink.SimulationInput object for each simulation that you want to run (in this case,
two). Store the objects in a single array variable, simIn. Use the setVariable method of each
object to identify each of the two experimentation values.

for i = 1:length(relSlip_vals)
simIn(i) = Simulink.SimulationInput('ex_sldemo_absbrake');
simIn(i) = setVariable(simIn(i),'relSlip',relSlip_vals(i));
end

Use the sim function to simulate the model. Optionally, store the output in a variable named
simOutputs.

simOutputs = sim(simIn);

[13-Feb-2024 17:40:46] Running simulations...


[13-Feb-2024 17:40:48] Completed 1 of 2 simulation runs
[13-Feb-2024 17:40:49] Completed 2 of 2 simulation runs

The model streams the logged signals, yout and slp, to the Simulation Data Inspector. You can view
the signal data in the Simulation Data Inspector.

Compare the output data of the two latest simulation runs.

runIDs = Simulink.sdi.getAllRunIDs();
runResult = Simulink.sdi.compareRuns(runIDs(end-1), runIDs(end));

Plot the difference between the values of the Ww signal (which is an element of the virtual bus signal
yout) by specifying the result index 1.

signalResult = getResultByIndex(runResult,1);
plot(signalResult.Diff);

41-40
Optimize, Estimate, and Sweep Block Parameter Values

Store Sweep Values in Simulink.SimulationInput Objects


When you write a script to run many simulations, create an array of Simulink.SimulationInput
objects (one object for each simulation that you want to run). Use the setVariable and
setBlockParameter functions of each object to identify the parameter values to use for the
corresponding simulation run. With this technique, you avoid having to use the set_param function
to modify block parameter values and assignment commands to modify workspace variable values
between simulation runs.

For more information about using Simulink.SimulationInput objects to run multiple simulations,
see sim.

Sweep Nonscalars, Structures, and Parameter Objects

If you use nonscalar variables, structure variables, or Simulink.Parameter objects to set block
parameter values, use the setVariable function of each Simulink.SimulationInput object.
Refer to the examples in the table.

Scenario Example
MATLAB variable, myArray, whose simIn = setVariable(simIn,'myArray(3)',15.23)
value is an array. You want to set the
third element in the array (assuming
one-based indexing).

41-41
41 Working with Block Parameters

Scenario Example
MATLAB variable, myStruct, that has a simIn = setVariable(simIn,'myStruct.field1',15.23)
field named field1.
Parameter object, myParam, whose simIn = setVariable(simIn,'myParam.Value',15.23)
Value property is a scalar.
Parameter object, myArrayParam, simIn = setVariable(simIn,'myArrayParam.Value(3)',15.23)
whose Value property is an array. You
want to set the third element in the
array.
Parameter object, myStructParam, simIn = setVariable(simIn,'myStructParam.Value.field1',15.23)
whose Value property is a structure.
The structure has a field named
field1.

Sweep Value of Variable in Model Workspace

If you use the model workspace to store variables, when you use the setVariable function of a
Simulink.SimulationInput object to modify the variable value, use the Workspace pair
argument to identify the containing model:

simIn = setVariable(simIn,'myVar',15.23,'Workspace','myModel')

Capture and Visualize Simulation Results


Each simulation run during a parameter sweep produces outputs, such as signal values from Outport
blocks and from logged signals.

You can capture these outputs in variables and objects for later analysis. For more information, see
“Save Simulation Data” on page 78-2.

To visualize simulation output data so you can compare the effect of each parameter value, see
“Decide How to Visualize Simulation Data” on page 33-2.

Improve Simulation Speed


To perform many simulations that each use different parameter values, you can use accelerated
simulation modes. For larger models, accelerated simulations take less time to execute than normal
simulations. If you also have Parallel Computing Toolbox, you can use the multiple cores of your
processor to simultaneously execute simulations. Use arguments of the sim and parsim functions.

To improve the simulation speed of your model by using accelerated simulations and other
techniques, see “Optimize Performance”. For examples and more information, see “Running Multiple
Simulations” on page 29-2.

Sweep Parameter Values to Test and Verify System


If you have Simulink Test, you can confirm that your model still meets requirements when you use
different parameter values. Parameter overrides and test iterations enable you to set different
parameter values for each test case. For more information, see “Parameter Overrides” (Simulink Test)
and “Test Iterations” (Simulink Test).

41-42
Optimize, Estimate, and Sweep Block Parameter Values

Estimate and Calibrate Model Parameters


If you have Simulink Design Optimization, you can estimate model parameter values so that
simulation outputs closely fit the data that you measure in the real world. Use this technique to
estimate the real-world values of parameters in a plant model, which represents the dynamics of a
real-world system, when you cannot directly measure the values. This estimation improves the
accuracy of the plant model. For more information, see “Estimate Parameters from Measured Data”
(Simulink Design Optimization).

Tune and Optimize PID and Controller Parameters


If you have Simulink Control Design, you can use PID Tuner to tune the parameters of a PID
Controller block. For more information, see “PID Controller Tuning in Simulink” (Simulink Control
Design).

If you have Simulink Design Optimization, you can optimize control parameter values so that
simulation outputs meet response requirements that you specify. For more information, see “Design
Optimization to Meet Step Response Requirements (GUI)” (Simulink Design Optimization).

See Also

Related Examples
• “Data Objects” on page 73-76
• “Specify Minimum and Maximum Values for Block Parameters” on page 41-52
• “Sweep Variant Control Using Parallel Simulation” on page 28-19
• “Switch Between Sets of Parameter Values During Simulation and Code Execution” on page 41-
56

41-43
41 Working with Block Parameters

Control Block Parameter Data Types


A block parameter, such as the Gain parameter of a Gain block, has a data type in the same way that
a signal has a data type (see “Control Data Types of Signals” on page 73-6). MATLAB variables,
Simulink.Parameter objects, and other parameter objects that you use to set block parameter
values also have data types. Control block parameter data types to:

• Accurately simulate the execution of your control algorithm on hardware.


• Generate efficient code.
• Integrate the generated code with your custom code.
• Avoid using data types that your target hardware does not support.

Reduce Maintenance Effort with Data Type Inheritance


By default, block parameters, numeric MATLAB variables that use the data type double, and
Simulink.Parameter objects acquire a data type through inherited and context-sensitive data
typing. For example, if the input and output signals of a Gain block use the data type single, the
Gain parameter typically uses the same data type. If you use a Simulink.Parameter object to set
the value of the block parameter, by default, the object uses the same data type as the parameter. You
can take advantage of this inheritance to avoid explicitly specifying data types for parameters.

Some inheritance rules choose a parameter data type other than the data type that the corresponding
signals use. For example, suppose that:

• The input and output signals of a Gain block use fixed-point data types with binary-point-only
scaling.
• On the Parameter Attributes tab, Parameter data type is set to Inherit: Inherit via
internal rule (the default).
• On the Parameter Attributes tab, you specify a minimum and maximum value for the parameter
by using Parameter minimum and Parameter maximum.

The data type setting Inherit: Inherit via internal rule can cause the block to choose a
different data type, with a different word length or scaling, than the data type that the signals use.
The minimum and maximum values that you specified for the parameter influence the scaling that the
block chooses.

When you select internal rules (Inherit: Inherit via internal rule) to enable Simulink to
choose data types, before simulating or generating code, configure the characteristics of your target
hardware. The internal rules can use these settings to choose data types that yield efficient generated
code.

Context-Sensitive Data Typing

When you use a MATLAB variable or Simulink.Parameter object to set the value of a block
parameter, you can configure the variable or parameter object to use context-sensitive data typing.
When you simulate or generate code, the variable or parameter object uses the same data type as the
block parameter. With this technique, you can match the data type of the variable or parameter object
with the data type of the block parameter. To control the data type of the block parameter and the
variable or object, you specify only the data type of the block parameter.

41-44
Control Block Parameter Data Types

To use context-sensitive data typing, set the value of a MATLAB variable to a double value. For a
Simulink.Parameter object, set the Value property by using a double value and set the
DataType property to auto (the default).

Context-Sensitive Data Typing for Structure Fields

As described in “Organize Related Block Parameter Definitions in Structures” on page 41-19, you can
organize multiple block parameter values into a structure.

The fields of parameter structures do not support context-sensitive data typing. However, to match
the data type of a field with the data type of another data item in a model, you can use a bus object
and a data type object.

1 Use a Simulink.Bus object as the data type of the structure.


2 Use a Simulink.AliasType or Simulink.NumericType object as the data type of the
element in the bus object and as the data type of the target data item.

Techniques to Explicitly Specify Parameter Data Types


Many blocks supported for discrete-time simulation and code generation (such as those in the built-in
Discrete library) enable you to explicitly specify parameter data types. For example, in an n-D
Lookup Table block dialog box, on the Data Types tab, you can specify a data type for the lookup
table data by using the Table data parameter. In a Gain block dialog box, use the Parameter
Attributes tab to set Parameter data type, which controls the data type of the Gain parameter.

Some blocks, such as those in the Continuous library, do not enable you to specify parameter data
types. These block parameters use internal rules to choose a data type. To indirectly control the data
type of such a parameter, apply the data type to a Simulink.Parameter object instead.

When you use a Simulink.Parameter object or other parameter object to set the value of a block
parameter, you can use the DataType property of the object to specify a data type.

If you use model arguments, you can specify a data type:

• For the model argument that you store in the model workspace.
• With some blocks (such as those in the Discrete library), for the block parameter that uses the
model argument.
• For the argument value that you specify in a Model block.

The default settings for these data types typically use inheritance and context-sensitive data typing.
For example, the default value of the DataType property of a Simulink.Parameter object is auto,
which causes the parameter object to acquire a data type from the block parameter or parameters
that use the object.

To explicitly specify a data type, you can use the Data Type Assistant in block dialog boxes and
property dialog boxes. For information about the Data Type Assistant, see “Specify Data Types Using
Data Type Assistant” on page 73-46.

Use the Model Data Editor for Batch Editing


Using the Model Data Editor (on the Modeling tab, click Model Data Editor), you can specify the
same data type for multiple block parameters simultaneously. On the Parameters tab, set the
Change view drop-down list to Design and specify data types by using the Data Type column.

41-45
41 Working with Block Parameters

For more information, see Model Data Editor.

Calculate Best-Precision Fixed-Point Scaling for Tunable Block


Parameters
When you apply fixed-point data types to a model, you can use the Data Type Assistant and the Fixed-
Point Tool to calculate best-precision scaling for tunable block parameters. A block parameter,
Simulink.Parameter object, or other parameter object is tunable if it appears in the generated
code as a variable stored in memory.

The chosen scaling must accommodate the range of values that you expect to assign to the
parameter. To enable the tools to calculate an appropriate scaling, specify the range information in
the block or in a parameter object. Then, use one of these techniques to calculate the scaling:

• Use the Fixed-Point Tool to autoscale the entire model or subsystem. The tool can propose and
apply fixed-point data types for data items including block parameters, Simulink.Parameter
objects, signals, and states.
• Configure individual block parameters or parameter objects to calculate their own scaling.

When you later change value ranges for parameters, this technique enables you or the model to
recalculate the scaling without having to autoscale the entire model. However, if changing the
value range of the parameter also changes the value range of an associated signal, you must
manually calculate and apply a new scaling for the signal or use the Fixed-Point Tool to autoscale
the model or subsystem.

For basic information about fixed-point data types, block parameters, and other tools and concepts,
use the information in the table.

Topic More Information


Fixed-point data types and scaling “Fixed-Point Numbers in Simulink” (Fixed-Point
Designer)
How to specify value range information for block “Specify Minimum and Maximum Values for Block
parameters and parameter objects Parameters” on page 41-52
How to use the Data Type Assistant “Specify Data Types Using Data Type Assistant”
on page 73-46
Tunability and block parameter representation in “How Generated Code Stores Internal Signal,
the generated code State, and Parameter Data” (Simulink Coder) and
“Create Tunable Calibration Parameter in the
Generated Code” (Simulink Coder)

Autoscale Entire Model by Using the Fixed-Point Tool

You can use the Fixed-Point Tool to autoscale data items in your model, including tunable parameters
and signals whose values depend on those parameters. If you use this technique:

• To configure parameters as tunable, use parameter objects (for example, Simulink.Parameter)


instead of the Model Parameter Configuration dialog box. The Fixed-Point Tool can autoscale
parameter objects, but cannot autoscale numeric variables that you select through the Model
Parameter Configuration dialog box.

41-46
Control Block Parameter Data Types

If your model already uses the Model Parameter Configuration dialog box, use the
tunablevars2parameterobjects function to create parameter objects instead.
• When you use Simulink.Parameter objects to set block parameter values, specify the value
range information in the objects instead of the blocks. The Fixed-Point Tool uses the range
information in each object to propose a data type for that object.
• To enable the tool to autoscale parameter values that you store as fields of a structure, use a
Simulink.Bus object as the data type of the entire structure. Specify the range information for
each field by using the Min and Max properties of the corresponding element in the bus object.
The tool can then apply a data type to each element by using the DataType property.

To use a bus object as the data type of a parameter structure, see “Control Field Data Types and
Characteristics by Creating Parameter Object” on page 41-21.
• Before you apply the data types that the Fixed-Point Tool proposes, clear the proposals for
parameters and parameter objects whose data types you do not want the tool to change. For
example, clear the proposals for these entities:

• Parameter objects that you import into the generated code from your own handwritten code by
applying a storage class such as ImportedExtern.
• Simulink.Parameter model arguments in a model workspace.

Alternatively, before autoscaling the model, consider replacing these parameter objects with
numeric MATLAB variables to prevent the Fixed-Point Tool from autoscaling them.

Allowing the tool to autoscale model arguments can increase the risk of unintentional data type
mismatches between the model argument values (which you specify in Model blocks in a
parent model), the model arguments in the model workspace, and the client block parameters
in the model.
• Parameter objects whose DataType property is set to auto (context-sensitive). Clear the
proposals if you want the parameter objects to continue to use context-sensitive data typing.

For more information about using the Fixed-Point Tool to autoscale Simulink.Parameter objects,
see “Autoscaling Data Objects Using the Fixed-Point Tool” (Fixed-Point Designer).

Calculate Best-Precision Scaling for Individual Parameters

You can configure a block parameter or Simulink.Parameter object to calculate its own best-
precision scaling. First, specify value range information for the target parameter or parameter object.
Then, use the Data Type Assistant or the function fixdt to apply a data type to the parameter or
object. Use these techniques when you do not want to use the Fixed-Point Tool to autoscale the
model.
Enable Block Parameter to Automatically Calculate Best-Precision Scaling

You can enable the parameters of some blocks (typically blocks in the Discrete library) to
automatically calculate best-precision fixed-point scaling. Use this technique to store the range and
data type information in the model instead of a parameter object. When you use this technique, if you
later change the range information, the block parameter automatically recalculates best-precision
scaling.

In the block dialog box, use the function fixdt to specify a fixed-point data type with unspecified
scaling. For example, use best-precision scaling for lookup table data, and store the data in a 16-bit
word:

41-47
41 Working with Block Parameters

1 On the Data Types tab of an n-D Lookup Table block, under the Minimum and Maximum
columns, specify a value range for the elements of the table data.
2 Under the Data Type column, set the table data type to fixdt(1,16).
3 If you use a tunable Simulink.Parameter object to set the value of the table data parameter,
set the DataType property of the object to auto. In the generated code, the parameter object
uses the same scaling as the block parameter.

When you simulate or generate code, the lookup table data uses a signed 16-bit fixed-point data type
whose binary-point scaling depends on the range information that you specify. The calculated scaling
allows the fixed-point type to represent values that lie within the range. If you later change the
minimum or maximum values, the block recalculates the scaling when you simulate or generate code.

Calculate Scaling for Parameter Object

If you use a Simulink.Parameter object to set the values of multiple block parameters, and if the
block parameters use different data types (including different fixed-point scaling), you cannot set the
DataType property of the object to auto (the default). Instead, you can calculate best-precision
fixed-point scaling for the parameter object by specifying range and data type information in the
object. You can also use this technique to store range and data type information in a parameter object
instead of a block dialog box. When you use this technique, if you later change the range information,
you must recalculate the best-precision scaling by using the Data Type Assistant.

Suppose that you create a parameter object to represent the value 15.25, and that the design range
of the value is between 0.00 and 32.00. To calculate best-precision scaling, use the Data Type
Assistant.

1 At the command prompt, create a parameter object in the base workspace whose value is 15.25.

myParam = Simulink.Parameter(15.25);
2 In the MATLAB Workspace browser, double-click the object myParam. The property dialog box
opens.
3 Specify range information in the object. For example, set Minimum to 0.00 and Maximum to
32.00.
4 Set Data type to fixdt(0,16,0).
5 Expand the Data Type Assistant and click Calculate Best-Precision Scaling.

The data type changes from fixdt(0,16,0) to fixdt(0,16,10).

The calculated scaling (a fraction length of 10 bits) enables the fixed-point data type to represent
parameter values that lie within the range that you specified.

If you specify range and data type information in a parameter object, consider removing the range
and data type information from the blocks that use the object. Some tools, such as the Fixed-Point
Tool, ignore the range information that you specify in the block and use only the information in the
parameter object. Removing the information from the block prevents confusion and user errors.

For example, on the Parameter Attributes tab of a Gain block dialog box, set Parameter minimum
and Parameter maximum to []. Set Parameter data type to an inherited data type such as
Inherit: Inherit from 'Gain' so that the block parameter uses the same data type as the
parameter object.

41-48
Control Block Parameter Data Types

Detect Numerical Accuracy Issues Due to Quantization and Overflow


When the data type of a block parameter, MATLAB variable, or parameter object cannot represent the
value that you specify, the data type quantizes the value, compromising numerical accuracy. For
example, the 32-bit floating-point data type single (float in C code) cannot exactly represent the
parameter value 1.73. When the real-world value of a data item lies outside the range of values that
the data type can represent, overflow can cause loss of information.

To detect these issues, use the diagnostic configuration parameters under Configuration
Parameters > Diagnostics > Data Validity > Parameters. Set the values of these diagnostic
configuration parameters to warning or error:

• Detect downcast
• Detect precision loss
• Detect underflow
• Detect overflow

Reuse Custom C Data Types for Parameter Data


In a model, you can create parameter data that conform to custom C data types, such as structures,
that your existing C code defines. Use these data to:

• Replace existing C code with a Simulink model.


• Integrate C code for simulation in Simulink (for example, by using the Legacy Code Tool).
• Prepare to generate code (Simulink Coder) that you can integrate with existing code.

Use these techniques to match your custom data types:

• For a structure type, create a Simulink.Bus object. Use the object as the data type for a
structure that you store in a Simulink.Parameter object. See “Organize Related Block
Parameter Definitions in Structures” on page 41-19.
• For an enumeration, create an enumeration class and use it as the data type for block parameters.
See “Use Enumerated Data in Simulink Models” on page 74-5.
• To match a typedef statement that represents an alias of a primitive, numeric data type, use a
Simulink.AliasType object as the data type for block parameters. See Simulink.AliasType.

To create these classes and objects, you can use the function Simulink.importExternalCTypes.

If a MATLAB Function block or Stateflow chart in your model uses an imported enumeration or
structure type, configure the model configuration parameters to include (#include) the type
definition from your external header file. See “Control Imported Bus and Enumeration Type
Definitions” on page 50-122 (for a MATLAB Function block) and “Access Custom Code Variables and
Functions in Stateflow Charts” (Stateflow) and “Integrate Custom Structures in Stateflow Charts”
(Stateflow) (for a chart).

Data Types of Mathematical Expressions


If you specify a block parameter using a mathematical expression, the block determines the final
parameter data type using a combination of MATLAB and Simulink data typing rules.

41-49
41 Working with Block Parameters

Suppose that you define two parameter objects int8Param and doubleParam, and use the objects to
specify the Constant value parameter in a Constant block.

int8Param = Simulink.Parameter(3);
int8Param.DataType = 'int8';

doubleParam = Simulink.Parameter(9.36);
doubleParam.DataType = 'double';

The Constant block determines the data type of the Constant value parameter using these steps:

1 Each parameter object casts the specified numeric value to the specified data type.

Parameter object Data type Numeric value Result


int8Param int8 3 int8(3)
doubleParam double 9.36 double(9.36)
2 The block evaluates the specified expression, int8Param * doubleParam, using MATLAB
rules.

An expression that involves a double data type and a different type returns a result of the
different type. Therefore, the result of the expression int8(3) * double(9.36) is int8(28).

If you use an expression to set the value of a parameter object (such as Simulink.Parameter),
parameter objects used in the expression follow different data typing rules. The auto setting of the
DataType property has a slightly different meaning. See “Set Variable Value by Using a
Mathematical Expression” on page 41-10.

Block Parameter Data Types in the Generated Code


For more information about controlling parameter data types in the generated code, see “Parameter
Data Types in the Generated Code” (Simulink Coder).

See Also

Related Examples
• “Set Block Parameter Values” on page 41-2
• “Specify Minimum and Maximum Values for Block Parameters” on page 41-52
• “Tune and Experiment with Block Parameter Values” on page 41-31

41-50
Control Block Parameter Data Types

• “Model Configuration Parameters: Data Validity Diagnostics”

41-51
41 Working with Block Parameters

Specify Minimum and Maximum Values for Block Parameters


You can protect your model design by preventing block parameters from using values outside of a
range. For example, if the value of a parameter that represents the angle of an aircraft aileron cannot
feasibly exceed a known magnitude, you can specify a design maximum for the parameter in the
model.

Fixed-Point Designer enables Simulink to use your range information to calculate best-precision fixed-
point scaling for:

• Tunable parameters.
• Signals, by taking into consideration the range of values that you intend to assign to tunable
parameters.

For basic information about block parameters, see “Set Block Parameter Values” on page 41-2.

Specify Parameter Value Ranges


When you specify a value range for a block parameter, typically, you can choose to store the
information in the block (the model file) or in an external variable or parameter object. Choose a
technique based on your modeling goals.

• Use other parameters of the same block, if available. For example, you can control the value range
of the Gain parameter of a Gain block by using the Parameter minimum and Parameter
maximum parameters in the Parameter Attributes tab in the block dialog box. For other blocks,
such as n-D Lookup Table and PID Controller, use the Data Types tab.

Use this technique to:

• Store the range information in the model file.


• Store the range information when you store fixed-point data type information in the block (for
example, by setting the Parameter data type parameter of a Gain block to a fixed-point type,
including best-precision scaling). This technique more clearly associates the range information
with the data type information.
• Use parameter objects (for example, Simulink.Parameter) to set the parameter value. You can
specify the range information in the object, instead of the block, by using the Min and Max
properties of the object.

Use this technique to:

• Specify range information for blocks that cannot store minimum or maximum information, for
example, many blocks in the Continuous library.
• Specify range information for a single value that you share between multiple block parameters
(see “Share and Reuse Block Parameter Values by Creating Variables” on page 41-9). Instead of
using a numeric MATLAB variable, use a parameter object so that you can specify the Min and
Max properties.
• Store the range information when you store fixed-point data type information in a parameter
object (by setting the DataType property to a fixed-point type instead of auto). This technique
more clearly associates the range information with the data type information.

If you specify the range information in a parameter object, consider removing the range
information from the block. For example, on the Parameter Attributes tab of a Gain block dialog

41-52
Specify Minimum and Maximum Values for Block Parameters

box, set Parameter minimum and Parameter maximum to []. Some tools, such as the Fixed-
Point Tool, use the range information that you specify in the block only if you do not specify the
range information in the parameter object. If you specify the range information in the parameter
object, the tools ignore the range information that you specify in the block.

For basic information about creating and using data objects, see “Data Objects” on page 73-76.

Specify Valid Range Information

Specify a minimum or maximum as an expression that evaluates to a scalar, real number with double
data type. For example, you can specify a minimum value for the Gain parameter in a Gain block by
setting Parameter minimum:

• A literal number such as 98.884. Implicitly, the data type is double.


• A numeric workspace variable (see “Share and Reuse Block Parameter Values by Creating
Variables” on page 41-9) whose data type is double. Use this technique to share a minimum or
maximum value between multiple data items.

However, you cannot use variables to set the Min or Max properties of a parameter object.

To leave the minimum or maximum of a block parameter or parameter object unspecified, use an
empty matrix [], which is the default value.

Specify Range Information for Nonscalar Parameters

If the value of a block parameter is a vector or matrix, the range information that you specify applies
to each element of the vector or matrix. If the value of any of the elements is outside the specified
range, the model generates an error.

If the value of a block parameter is a structure or a field of a structure, specify range information for
the structure fields by creating a Simulink.Parameter object whose data type is a Simulink.Bus
object. Specify the range information by using the properties of the signal elements in the bus object.
For more information, see “Control Field Data Types and Characteristics by Creating Parameter
Object” on page 41-21.

Specify Range Information for Complex-Valued Parameters

If the value of a block parameter is complex (i), the range information that you specify applies
separately to the real part and to the imaginary part of the complex number. If the value of either
part of the number is outside the range, the model generates an error.

Specify Ranges for Multiple Parameters by Using the Model Data Editor

Using the Model Data Editor (on the Modeling tab, click Model Data Editor), you can specify value
ranges for multiple block parameters and variables with a searchable, sortable table. On the
Parameters tab, set the Change view drop-down list to Design and specify values in the Min and
Max columns.

For more information, see Model Data Editor.

Restrict Allowed Values for Block Parameters


To protect your design by preventing block parameters from using values outside of a range, you can
specify the minimum and maximum information by using other parameters of the same block. If you

41-53
41 Working with Block Parameters

or your users set the value of the target parameter outside the range that you specify, the model
generates an error.

Whether a block allows you to specify a value range for a parameter, consider using a parameter
object (for example, Simulink.Parameter) to set the value of the target parameter. Use the
properties of the object to specify the range information. This technique helps you to specify range
information for a variable that you use to set multiple block parameter values.

Specify Range Information for Tunable Fixed-Point Parameters


When you use fixed-point data types in your model, you can enable Simulink to choose a best-
precision scaling for block parameters and Simulink.Parameter objects. If you intend to tune such
a parameter by changing its value during simulation or during execution of the generated code, the
fixed-point scaling chosen by Simulink must accommodate the range of values that you expect to
assign to the parameter.

Also, if you expect to change the value of a parameter, signal data types in the model must
accommodate the corresponding expanded range of possible signal values. If you use the Fixed-Point
Tool to propose and apply fixed-point data types for a model, to allow the tool to accurately autoscale
the signals, specify range information for tunable parameters.

To specify range information for tunable parameters, see “Calculate Best-Precision Fixed-Point
Scaling for Tunable Block Parameters” on page 41-46. To learn how the Fixed-Point Tool autoscales
signals by taking into account the value ranges of tunable parameters, see “Derive Ranges for
Simulink.Parameter Objects” (Fixed-Point Designer).

Unexpected Errors or Warnings for Data with Greater Precision or


Range than double
When a data item (signal or parameter) uses a data type other than double, before comparison,
Simulink casts the data item and each design limit (minimum or maximum value that you specify) to
the nondouble data type. This technique helps prevent the generation of unnecessary, misleading
errors and warnings.

However, Simulink stores design limits as double before comparison. If the data type of the data
item has higher precision than double (for example, a fixed-point data type with a 128-bit word
length and a 126-bit fraction length) or greater range than double, and double cannot exactly
represent the value of a design limit, Simulink can generate unexpected warnings and errors.

If the nondouble type has higher precision, consider rounding the design limit to the next number
furthest from zero that double can represent. For example, suppose that a signal generates an error
after you set the maximum value to 98.8847692348509014. At the command prompt, calculate the
next number furthest from zero that double can represent.

format long
98.8847692348509014 + eps(98.8847692348509014)

ans =

98.884769234850921

Use the resulting number, 98.884769234850921, to replace the maximum value.

41-54
Specify Minimum and Maximum Values for Block Parameters

Optimize Generated Code


If you have Embedded Coder, Simulink Coder can optimize the code that you generate from the model
by taking into account the minimum and maximum values that you specify for signals and
parameters. This optimization can remove algorithmic code and affect the results of some simulation
modes such as SIL or external mode. For more information, see Optimize using the specified
minimum and maximum values (Embedded Coder).

See Also

Related Examples
• “Control Block Parameter Data Types” on page 41-44
• “Tune and Experiment with Block Parameter Values” on page 41-31

41-55
41 Working with Block Parameters

Switch Between Sets of Parameter Values During Simulation


and Code Execution

To store multiple independent sets of values for the same block parameters, you can use an array of
structures. To switch between the parameter sets, create a variable that acts as an index into the
array, and change the value of the variable. You can change the value of the variable during
simulation and, if the variable is tunable, during execution of the generated code.

You can also use variant parameters (Simulink.VariantVariable) to vary the values of block
parameters in a model conditionally during simulation and code generation. For an example, see
“Create a Simple Variant Parameter Model” on page 90-5.

A better way to implement varying sets of values for a block parameter is to use Variant Parameters
(Simulink.VariantVariable). For an example that uses this workflow, see “Create a Simple
Variant Parameter Model” on page 90-5. Use variant parameter banks (Simulink.VariantBank)
to group variant parameters into a structure array in the generated code. Variant parameter banks
use pointer switching in the code to switch the set of active parameter values based on variant
conditions.

Explore Example Model

Open the example model.

open_system('sldemo_fuelsys_dd_controller')

This model represents the fueling system of a gasoline engine. The output of the model is the rate of
fuel flow to the engine.

Navigate to the switchable_compensation nested subsystem.

open_system(['sldemo_fuelsys_dd_controller/fuel_calc/',...
'switchable_compensation'])

41-56
Switch Between Sets of Parameter Values During Simulation and Code Execution

This subsystem corrects and filters noise out of the fuel rate signal. The subsystem uses different
filter coefficients based on the fueling mode, which the control logic changes based on sensor failures
in the engine. For example, the control algorithm activates the low_mode subsystem during normal
operation. It activates the rich_mode subsystem in response to sensor failure.

Open the low_mode subsystem.


open_system(['sldemo_fuelsys_dd_controller/fuel_calc/',...
'switchable_compensation/low_mode'])

The Discrete Filter block filters the fuel rate signal. In the block dialog box, the Numerator
parameter sets the numerator coefficients of the filter.

The sibling subsystem rich_mode also contains a Discrete Filter block, which uses different
coefficients.

Update the model diagram to display the signal data types. The input and output signals of the block
use the single-precision, floating-point data type single.

41-57
41 Working with Block Parameters

In the lower-left corner of the model, click the model data badge, then click the Data Dictionary
link. The data dictionary for this model, sldemo_fuelsys_dd_controller.sldd, opens in the
Model Explorer.

In the Model Explorer Model Hierarchy pane, select the Design Data node.

In the Contents pane, view the properties of the Simulink.NumericType objects, such as
s16En15. All of these objects currently represent the single-precision, floating-point data type
single. The model uses these objects to set signal data types, including the input and output signals
of the Discrete Filter blocks.

Suppose that during simulation and execution of the generated code, you want each of these
subsystems to switch between different numerator coefficients based on a variable whose value you
control.

Store Parameter Values in Array of Structures

Store the existing set of numerator coefficients in a Simulink.Parameter object whose value is a
structure. Each field of the structure stores the coefficients for one of the Discrete Filter blocks.

lowBlock = ['sldemo_fuelsys_dd_controller/fuel_calc/'...
'switchable_compensation/low_mode/Discrete Filter'];
richBlock = ['sldemo_fuelsys_dd_controller/fuel_calc/'...
'switchable_compensation/rich_mode/Discrete Filter'];
params.lowNumerator = eval(get_param(lowBlock,'Numerator'));
params.richNumerator = eval(get_param(richBlock,'Numerator'));
params = Simulink.Parameter(params);

Copy the value of params into a temporary variable. Modify the field values in this temporary
structure, and assign the modified structure as the second element of params.

temp = params.Value;
temp.lowNumerator = params.Value.lowNumerator * 2;
temp.richNumerator = params.Value.richNumerator * 2;
params.Value(2) = temp;
clear temp

The value of params is an array of two structures. Each structure stores one set of filter coefficients.

Create Variable to Switch Between Parameter Sets

Create a Simulink.Parameter object named Ctrl.

Ctrl = Simulink.Parameter(2);
Ctrl.DataType = 'uint8';

In the low_mode subsystem, in the Discrete Filter block dialog box, set the Numerator parameter to
the expression params(Ctrl).lowNumerator.

set_param(lowBlock,'Numerator','params(Ctrl).lowNumerator');

In the Discrete Filter block in the rich_mode subsystem, set the value of the Numerator parameter
to params(Ctrl).richNumerator.

set_param(richBlock,'Numerator','params(Ctrl).richNumerator');

41-58
Switch Between Sets of Parameter Values During Simulation and Code Execution

The expressions select one of the structures in params by using the variable Ctrl. The expressions
then dereference one of the fields in the structure. The field value sets the values of the numerator
coefficients.

To switch between the sets of coefficients, you change the value of Ctrl to the corresponding index
in the array of structures.

Use Bus Object as Data Type of Array of Structures

Optionally, create a Simulink.Bus object to use as the data type of the array of structures. You can:

• Control the shape of the structures.


• For each field, control characteristics such as data type and physical units.
• Control the name of the struct type in the generated code.

Use the function Simulink.Bus.createObject to create the object and rename the object as
paramsType.
Simulink.Bus.createObject(params.Value)
paramsType = slBus1;
clear slBus1

You can use the Simulink.NumericType objects from the data dictionary to control the data types
of the structure fields. In the bus object, use the name of a data type object to set the DataType
property of each element.
paramsType.Elements(1).DataType = 's16En15';
paramsType.Elements(2).DataType = 's16En7';

Use the bus object as the data type of the array of structures.
params.DataType = 'Bus: paramsType';

Use Enumerated Type for Switching Variable

Optionally, use an enumerated type as the data type of the switching variable. You can associate each
of the parameter sets with a meaningful name and restrict the allowed values of the switching
variable.

Create an enumerated type named FilterCoeffs. Create an enumeration member for each of the
structures in params. Set the underlying integer value of each enumeration member to the
corresponding index in params.
Simulink.defineIntEnumType('FilterCoeffs',{'Weak','Aggressive'},[1 2])

Use the enumerated type as the data type of the switching variable. Set the value of the variable to
Aggressive, which corresponds to the index 2.
Ctrl.Value = FilterCoeffs.Aggressive;

Add New Objects to Data Dictionary

Add the objects that you created to the data dictionary sldemo_fuelsys_dd_controller.sldd.
dictObj = Simulink.data.dictionary.open('sldemo_fuelsys_dd_controller.sldd');
sectObj = getSection(dictObj,'Design Data');
addEntry(sectObj,'Ctrl',Ctrl)

41-59
41 Working with Block Parameters

addEntry(sectObj,'params',params)
addEntry(sectObj,'paramsType',paramsType)

You can also store enumerated types in data dictionaries. However, you cannot import the
enumerated type in this case because you cannot save changes to
sldemo_fuelsys_dd_controller.sldd. For more information about storing enumerated types in
data dictionaries, see “Enumerations in Data Dictionary” on page 80-13.

Switch Between Parameter Sets During Simulation

Open the example model sldemo_fuelsys_dd, which references the controller model
sldemo_fuelsys_dd_controller.

open_system('sldemo_fuelsys_dd')

Set the simulation stop time to Inf so that you can interact with the model during simulation.

Begin a simulation run and open the Scope block dialog box. The scope shows that the fuel flow rate
(the fuel signal) oscillates with significant amplitude during normal operation of the engine.

In the Model Explorer, view the contents of the data dictionary


sldemo_fuelsys_dd_controller.sldd. Set the value of Ctrl to FilterCoeffs.Weak.

Update the sldemo_fuelsys_dd model diagram. The scope shows that the amplitude of the fuel
rate oscillations decreases due to the less aggressive filter coefficients.

Stop the simulation.

41-60
Switch Between Sets of Parameter Values During Simulation and Code Execution

Generate and Inspect Code

If you have Simulink Coder software, you can generate code that enables you to switch between the
parameter sets during code execution.

In the Model Explorer, view the contents of the data dictionary


sldemo_fuelsys_dd_controller.sldd. In the Contents pane, set Column View to Storage
Class.

Use the StorageClass column to apply the storage class ExportedGlobal to params so that the
array of structures appears as a tunable global variable in the generated code. Apply the same
storage class to Ctrl so that you can change the value of the switching variable during code
execution.

Alternatively, to configure the objects, use these commands:


tempEntryObj = getEntry(sectObj,'params');
params = getValue(tempEntryObj);
params.StorageClass = 'ExportedGlobal';
setValue(tempEntryObj,params);

tempEntryObj = getEntry(sectObj,'Ctrl');
Ctrl = getValue(tempEntryObj);
Ctrl.StorageClass = 'ExportedGlobal';
setValue(tempEntryObj,Ctrl);

Generate code from the controller model.


slbuild('sldemo_fuelsys_dd_controller')

### Starting build procedure for: sldemo_fuelsys_dd_controller


### Successful completion of code generation for: sldemo_fuelsys_dd_controller

Build Summary

Top model targets built:

Model Action Rebuild Reason


=================================================================================================
sldemo_fuelsys_dd_controller Code generated. Code generation information file does not exist.

1 of 1 models built (0 models already up to date)


Build duration: 0h 0m 49.029s

In the code generation report, view the header file sldemo_fuelsys_dd_controller_types.h.


The code defines the enumerated data type FilterCoeffs.
file = fullfile('sldemo_fuelsys_dd_controller_ert_rtw',...
'sldemo_fuelsys_dd_controller_types.h');
coder.example.extractLines(file,'#ifndef DEFINED_TYPEDEF_FOR_FilterCoeffs_',...
'/* Forward declaration for rtModel */',1,0)

#ifndef DEFINED_TYPEDEF_FOR_FilterCoeffs_
#define DEFINED_TYPEDEF_FOR_FilterCoeffs_

typedef enum {
Weak = 1, /* Default value */

41-61
41 Working with Block Parameters

Aggressive
} FilterCoeffs;

#endif

The code also defines the structure type paramsType, which corresponds to the Simulink.Bus
object. The fields use the single-precision, floating-point data type from the model.

coder.example.extractLines(file,'#ifndef DEFINED_TYPEDEF_FOR_paramsType_',...
'#ifndef DEFINED_TYPEDEF_FOR_FilterCoeffs_',1,0)

#ifndef DEFINED_TYPEDEF_FOR_paramsType_
#define DEFINED_TYPEDEF_FOR_paramsType_

typedef struct {
real32_T lowNumerator[2];
real32_T richNumerator[2];
} paramsType;

#endif

View the source file sldemo_fuelsys_dd_controller.c. The code uses the enumerated type to
define the switching variable Ctrl.

file = fullfile('sldemo_fuelsys_dd_controller_ert_rtw',...
'sldemo_fuelsys_dd_controller.c');
coder.example.extractLines(file,'FilterCoeffs Ctrl = Aggressive;',...
'/* Block signals (default storage) */',1,0)

FilterCoeffs Ctrl = Aggressive; /* Variable: Ctrl


* Referenced by:
* '<S12>/Discrete Filter'
* '<S13>/Discrete Filter'
*/

The code also defines the array of structures params.

coder.example.extractLines(file,'/* Exported block parameters */',...


'/* Variable: params',1,1)

/* Exported block parameters */


paramsType params[2] = { {
{ 8.7696F, -8.5104F },

{ 0.0F, 0.2592F }
}, { { 17.5392F, -17.0208F },

{ 0.0F, 0.5184F }
} } ; /* Variable: params

The code algorithm in the model step function uses the switching variable to index into the array of
structures.

To switch between the parameter sets stored in the array of structures, change the value of Ctrl
during code execution.

41-62
Switch Between Sets of Parameter Values During Simulation and Code Execution

Close the connections to the data dictionary. This example discards unsaved changes. To save the
changes, use the '-save' option.

Simulink.data.dictionary.closeAll('sldemo_fuelsys_dd_controller.sldd','-discard')

See Also

Related Examples
• “Tune and Experiment with Block Parameter Values” on page 41-31
• “Create Tunable Calibration Parameter in the Generated Code” (Simulink Coder)
• “Organize Related Block Parameter Definitions in Structures” on page 41-19
• “Access Structured Data Through a Pointer That External Code Defines” (Embedded Coder)

41-63
42

Working with Lookup Tables

• “About Lookup Table Blocks” on page 42-2


• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Breakpoint and Table Size Features in Lookup Tables” on page 42-8
• “Characteristics of Lookup Table Data” on page 42-12
• “Methods for Approximating Function Values” on page 42-15
• “Use the Lookup Table Editor” on page 42-19
• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23
• “Enter Breakpoints and Table Data” on page 42-35
• “Import Lookup Table Data from MATLAB” on page 42-39
• “Copy and Paste Lookup Table Data from Excel” on page 42-45
• “Import Lookup Table Data from Excel Using readtable” on page 42-47
• “Visualize Data Through Plots” on page 42-48
• “Generate Report of Lookup Table” on page 42-51
• “Register Custom Lookup Table Blocks” on page 42-52
• “Visualize Lookup Tables Visualized Through Lookup Table Control” on page 42-54
• “Create a Logarithm Lookup Table” on page 42-56
• “Prelookup and Interpolation Blocks” on page 42-58
• “Optimize Generated Code for Lookup Table Blocks” on page 42-59
• “Row-Major Algorithm in Existing Models Containing Lookup Table Blocks” on page 42-62
• “Update Lookup Table Blocks to New Versions” on page 42-63
42 Working with Lookup Tables

About Lookup Table Blocks


A lookup table is 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, where:

• An interpolation is a process for estimating values that lie between known data points.
• An extrapolation is a process for estimating values that lie beyond the range of known data points.
• A rounding is a process for approximating a value by altering its digits according to a known rule.

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 adjacent data points (xi, yi) and
(xi+1, yi+1). For example, given these two points:

• (xi, yi) is (-2, -8)


• (xi+1, yi+1) is (-1, -1)

The lookup table estimates and returns a value of -4.5.

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

See Also

More About
• “Anatomy of a Lookup Table” on page 42-4
• “Breakpoint and Table Size Features in Lookup Tables” on page 42-8

42-3
42 Working with Lookup Tables

Anatomy of a Lookup Table


The following figure illustrates the anatomy of a two-dimensional lookup table. Breakpoint vectors
and an array, referred to as table data, constitute the lookup table.

A breakpoint is a single element of a breakpoint vector. A breakpoint represents a particular input


value to which a corresponding output value in the table data is mapped. Each breakpoint 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
breakpoints to relate a table input values to the output values that it returns.

A breakpoint vector consists of input values that indexes a particular dimension of a lookup table. A
lookup table uses breakpoint vectors to relate its input values to the output values that it returns.

Table data is an array that serves as a sampled representation of a function evaluated at a lookup
table breakpoint values. A lookup table uses breakpoints to index the table data, ultimately returning
an output value.

See Also

More About
• “About Lookup Table Blocks” on page 42-2
• “Breakpoint and Table Size Features in Lookup Tables” on page 42-8

42-4
Guidelines for Choosing a Lookup Table

Guidelines for Choosing a Lookup Table


In this section...
“Data Set Dimensionality” on page 42-5
“Data Set Numeric and Data Types” on page 42-5
“Data Accuracy and Smoothness” on page 42-5
“Dynamics of Table Inputs” on page 42-5
“Efficiency of Performance” on page 42-6
“Summary of Lookup Table Block Features” on page 42-6

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.

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, cubic spline interpolation and extrapolation, or Akima
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
breakpoints. 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

42-5
42 Working with Lookup Tables

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

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 1-D Lookup 2-D Lookup Lookup n-D Lookup Direct Prelookup Interpolati
Table Table Table Table Lookup on Using
Dynamic Table (n-D) Prelookup
Interpolation Methods
Flat • • • • •
Nearest • • • •
Linear •
Linear point- • • • •
slope
Linear • • • •
Lagrange
Cubic spline • • •
Akima spline • • •
Extrapolation Methods
Clip • • • • • •
Linear • • • • • •
Cubic spline • • •
Akima spline • •

42-6
Guidelines for Choosing a Lookup Table

Feature 1-D Lookup 2-D Lookup Lookup n-D Lookup Direct Prelookup Interpolati
Table Table Table Table Lookup on Using
Dynamic Table (n-D) Prelookup
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 • • •
data
Input range • • • • • •
checking

See Also

More About
• “Anatomy of a Lookup Table” on page 42-4
• “Breakpoint and Table Size Features in Lookup Tables” on page 42-8

42-7
42 Working with Lookup Tables

Breakpoint and Table Size Features in Lookup Tables


Simulink supports multiple size related features in lookup tables. This topic summarizes these
features and describes when to use them.

Tunable Size
Lookup tables consist of breakpoint and table arrays that lookup table blocks use to look up inputs
and interpolate table data. These arrays have fixed sizes once the simulation starts. They appear as
arrays in generated C/C++ code. Tunable sizes enable you to work with a smaller range of active
breakpoints, also known as active region, within the larger fixed size of the breakpoint array. Use
tunable sizes when you need to tune or calibrate your lookup table without needing to resize the
arrays and regenerate code. With this feature, the generated C/C++ code includes a tunable size
variable, whose value you can change, between compile runs or during program execution by writing
into its memory location. As of R2022b, this feature is available only in code generation. To use the
tunable size feature, select the Support tunable size check box on the “Advanced” tab of the
Simulink.LookupTable property dialog box.

In this example, the breakpoint array of the lookup table is of size 10. N denotes the tunable size.

Symbolic Dimensions
Symbolic dimensions let you create breakpoint and table arrays using sizes represented by symbolic
values in simulation and generated C/C++ code. Symbolic dimensions allow you to easily change the
size of your lookup table data between compile runs. In generated C/C++ code, these symbolic values
appear as macros used to declare the breakpoint and table C arrays. The symbolic values represent
the larger fixed sizes of the breakpoints and table. Use the tunable size feature with symbolic
dimensions to choose a smaller active region within the symbolic size in the generated C/C++ code.
To use symbolic dimensions, see the Dimensions parameter on the “Table and Breakpoints” tab of
the Simulink.LookupTable property dialog box.

In this example, the breakpoint and table arrays of the lookup table are of size S. S is a macro that
can represent different sizes between compile runs.

42-8
Breakpoint and Table Size Features in Lookup Tables

Reusable Struct Data Types for Different Breakpoint and Table Array
Sizes
Simulink.LookupTable objects let you create struct data types with fields to represent breakpoint
and table data. Lookup table objects also provide for customization of the struct data type definition.
The reusable struct data types feature lets you use the same struct data type to represent multiple
lookup table objects, each with different lookup table array sizes.

In simulation, you can have multiple n-D Lookup Table blocks, each with objects having different table
and breakpoint sizes with the same struct data type name. You can also pass these differently sized
array objects via model arguments in a model reference hierarchy, setting up a size-independent
interface between models for your lookup table data types. In the generated C/C++ code, the struct
data type represents the breakpoint and table fields as pointer data types instead of array data types.

Without this feature, achieving the same behavior requires padding the differently sized arrays to the
maximum size of the arrays of the participating lookup table objects. Padding in this manner has
several disadvantages, such as wasted memory and slower breakpoint search speed.

Starting in R2022b, to work with different breakpoint and table array sizes, use the Allow multiple
instances of this type to have different table and breakpoint sizes check box on the “Advanced”
tab of the Simulink.LookupTable property dialog box.

As an example, the Two Lookup Table Objects with Differently Sized Arrays graphic shows two
lookup table objects, each with different breakpoint and table array sizes.

• LUT object 1 has breakpoint and table arrays of size [1x4].


• LUT object 2 has breakpoint and table arrays of size [1x6].

We would like to have the same struct data type, lookup_type, represent both objects. As presented,
the configuration issues an error during model update diagram.

42-9
42 Working with Lookup Tables

Two Lookup Table Objects with Differently Sized Arrays

To resolve the sizing discrepancy, in releases before R2022b, the workaround was to use padding to
match the array sizes of the participating lookup table objects. This approach is not optimal.

The Lookup Table Object with Padding Applied graphic shows the padding workaround.
Breakpoint and table arrays of LUT object 1 are padded to match the size of the breakpoint and table
arrays of LUT object 2. Notice how the struct data type, lookup_type, generated in the C/C++ code,
has breakpoint and table fields as arrays of size 6. With this, the struct data type can represent both
LUT object 1 and LUT object 2 using padding.

Lookup Table Object with Padding Applied

Starting in R2022b, to solve the size discrepancy, use the Allow multiple instances of this type to
have different table and breakpoint sizes check box in the Simulink.LookupTable object. This
feature allows the same struct data type to represent different breakpoint and table sizes.

42-10
Breakpoint and Table Size Features in Lookup Tables

The Lookup Table Object with Differently Sized Tables and Breakpoints Enabled graphic
shows the same lookup table object configuration, but with the Allow multiple instances of this
type to have different table and breakpoint sizes check box selected. The struct data type,
lookup_type, in the generated C/C++ code, has breakpoint and table fields as pointers instead of
arrays. As a result, the struct data type can represent LUT object 1 and LUT object 2 without
requiring any padding.

Lookup Table Object with Differently Sized Tables and Breakpoints Enabled

See Also
Simulink.LookupTable | 1-D Lookup Table | 2-D Lookup Table | n-D Lookup Table

Related Examples
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Characteristics of Lookup Table Data” on page 42-12

42-11
42 Working with Lookup Tables

Characteristics of Lookup Table Data


In this section...
“Sizes of Breakpoint Vectors and Table Data” on page 42-12
“Monotonicity of Breakpoints” on page 42-13
“Formulation of Evenly Spaced Breakpoints” on page 42-13

Sizes of Breakpoint Vectors and Table Data


The following constraints apply to the sizes of breakpoint vectors 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 vector.

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: [-3 -2 -1 0 1 2 3]
Vector of output values: [-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.

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.

42-12
Characteristics of Lookup Table Data

Monotonicity of Breakpoints
The first stage of a table lookup operation involves relating inputs to the breakpoints. The search
algorithm requires that input breakpoint sets be strictly monotonically increasing, that is, each
successive element is greater than its preceding element. For example, the vector

A = [0 0.5 1 1.9 2.1 3]

is a valid breakpoint vector as each element is larger than its predecessors.

Note Although a breakpoint vector is strictly monotonic in double format, it might not be so after
conversion to a fixed-point data type.

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- 1 + (0.02 * The lookup table uses
first_value)/spacing] [0:450]) 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 42-6.

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” (Fixed-Point Designer)
• “Identify questionable fixed-point operations” (Embedded Coder)

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.

See Also

More About
• “Anatomy of a Lookup Table” on page 42-4
• “Breakpoint and Table Size Features in Lookup Tables” on page 42-8
• “Guidelines for Choosing a Lookup Table” on page 42-5

42-13
42 Working with Lookup Tables

• “Summary of Lookup Table Block Features” on page 42-6

42-14
Methods for Approximating Function Values

Methods for Approximating Function Values


In this section...
“About Approximating Function Values” on page 42-15
“Interpolation Methods” on page 42-15
“Extrapolation Methods” on page 42-16
“Rounding Methods” on page 42-17
“Example Output for Lookup Methods” on page 42-17

About Approximating Function Values


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 vectors, the block
outputs the corresponding values. However, if the inputs fail to match index values in the breakpoint
vectors, 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 42-17.
• Nearest — Disables interpolation and returns the table value corresponding to the breakpoint
closest to the input. If the input is equidistant from two adjacent breakpoints, the breakpoint with
the higher index is chosen.
• Linear point-slope — Fits a line between the adjacent breakpoints, and returns the point on
that line corresponding to the input. This is the equation for linear point-slope, where x is the
input data, y is the output table data (xi,yi is the coordinate of the table data), and f is the fraction.
For more information on xi,yi, see “About Lookup Table Blocks” on page 42-2.

x − xi
f =
xi + 1 − xi

y = yi + f (yi + 1 − yi)
• Cubic spline — Fits a cubic spline to the adjacent breakpoints, and returns the point on that
spline corresponding to the input.
• Linear Lagrange — Fits a line between the adjacent breakpoints using first-order Lagrange
interpolation, and returns the point on that line corresponding to the input. This is the equation
for linear Lagrange, where x is the input data, y is the output table data, and f is the fraction. f is
constrained to range from 0 to less than 1 ([0,1)). For more information on x and y, see “About
Lookup Table Blocks” on page 42-2.

x − xi
f =
xi + 1 − xi

42-15
42 Working with Lookup Tables

y = (1 − f )yi + f yi + 1

If the extrapolation method is Linear, the extrapolation value is calculated based on the selected
linear interpolation method. For example, if the interpolation method is Linear Lagrange, the
extrapolation method inherits the Linear Lagrange equation to compute the extrapolated value.
• Akima spline — Fits an Akima spline to the adjacent breakpoints, and returns the point on that
spline corresponding to the input. The interpolation method works only with the Akima spline
extrapolation method. The modified Akima cubic Hermite interpolation method has these
properties:

• It produces fewer undulations than Cubic spline.


• It is more efficient for real-time applications than Cubic spline.
• Unlike Cubic spline, it does not produce overshoots.
• Unlike Cubic spline, it supports nonscalar signals.

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 smooth results. Akima spline produces the
smoothest results.

Extrapolation Methods
When an input falls outside the range of a breakpoint vector, the block extrapolates the output value
from a pair of values at the end of the breakpoint vector. 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 vector range. This does not provide protection against out-of-range values.
• Linear — If the interpolation method is Linear, this extrapolation method fits a line between the
first or last pair of breakpoints, depending on whether the input is less than the first or greater
than the last breakpoint. If the interpolation method is Cubic spline or Akima spline, this
extrapolation method fits a linear surface using the slope of the interpolation at the first or last
break point, depending on whether the input is less than the first or greater than the last
breakpoint. The extrapolation method returns the point on the generated linear surface
corresponding to the input.

If the extrapolation method is Linear, the extrapolation value is calculated based on the selected
linear interpolation method. For example, if the interpolation method is Linear Lagrange, the
extrapolation method inherits the Linear Lagrange equation to compute the extrapolated value.
• 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.

42-16
Methods for Approximating Function Values

• Akima spline — Fits an Akima 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.

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 vectors. 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 vector 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.

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

The Lookup Table Dynamic block outputs the following values when using the specified lookup
methods and inputs.

42-17
42 Working with Lookup Tables

Lookup Method Input Output Comment


Interpolation- 1.4 2.156 N/A
Extrapolation 5.2 83.59 N/A
Interpolation- 1.4 2.156 N/A
Use End Values 5.2 74.2 The block uses the value for
sinh(5.0).
Use Input Above 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).
Use Input Below 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).
Use Input Nearest 1.4 1.175 The block uses the value for
sinh(1.0).

See Also

More About
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5

42-18
Use the Lookup Table Editor

Use the Lookup Table Editor


To manage the lookup tables in your environment, use the Lookup Table Editor. Watch How to Use the
Lookup Table Editor (5min 9sec).

• Visualize and edit lookup table data in a consistent way similar to a spreadsheet editor, regardless
of the data source. A variable data source can be from the MATLAB base workspace, model
workspace, or data dictionary.
• Explore lookup tables from multiple models, subsystems, and blocks loaded in the current
MATLAB session.
• Generate reports containing lookup table data and plots.

• For 1-D data, the report generates line plots.


• For more than 1-D data, the report generates surface plots, one plot for each 2-D slice of data.
• Add custom lookup table blocks to the Lookup Table Editor, enabling you to work with them as you
do other lookup table blocks.

This graphic is a view of the Lookup Table Editor for the Throttle Estimation lookup table block in the
“Model Fault-Tolerant Fuel Control System” example sldemo_fuelsys model. For this view, the
heatmap is enabled and the mesh and contours for the data are plotted. Observe that the red dots in
the plots represent the data in the selected area of the blue rectangle in the tabular area.

42-19
42 Working with Lookup Tables

Start the Lookup Table Editor


Access the Lookup Table Editor in one of these ways:

• In Simulink Editor, on the Modeling tab, click Lookup Table Editor. From this interface, you can
open the Lookup Table Editor for Simulink, AUTOSAR Blockset, and Simscape lookup table
blocks. The Lookup Table Editor can also open for empty models. The Lookup Table Editor also
recognizes any custom lookup table blocks that you have registered.
• From the Simulink blocks 1-D Lookup Table, 2-D Lookup Table, Direct Lookup Table (n-D), n-D
Lookup Table, Interpolation Using Prelookup, and Prelookup, click the edit lookup table button.
• From the AUTOSAR Blockset blocks Curve, Curve Using Prelookup, Map, and Map Using
Prelookup, click the edit lookup table button.
• In the MATLAB Command Window, type lookupTableEditor.
• In Simulink Editor, click a Simulink or AUTOSAR Blockset lookup table block. In the Lookup
Table tab that appears, click Lookup Table Editor.

Lookup Table Editor enables you to:

• Enter the path to models and subsystems that contain lookup table blocks and the path to lookup
table blocks themselves in the lookup table path browser to see them in the list in the Lookup
Table Blocks path pane.

In the tabular area, the Lookup Table Editor contains the same lookup table spreadsheet that is
available through the Simulink.LookupTable property dialog box. See “Edit Lookup Table Data
with Lookup Table Spreadsheet” on page 42-23.

42-20
Use the Lookup Table Editor

• Generate line, plot, surface, and contour plots for the data.

• Enable heatmap overlays for data.

Edit Lookup Tables

You can edit a lookup table using:

• Lookup Table Editor — Edit one or more lookup tables without navigating to the blocks, models, or
subsystems that contain them.
• Lookup Table block dialog box — Edit lookup tables from within a lookup table block.

For more information, see “Enter Breakpoints and Table Data” on page 42-35

42-21
42 Working with Lookup Tables

Lookup Table Editor Limitations


• The Lookup Table Editor does not support lookup tables containing data specified as
Simulink.VariantVariable. When you try to open a lookup table that contains this data type,
the lookup table block returns an error in a pop-up window.
• The Lookup Table Editor overwrites expressions set in the block dialog unless they are non-
variable names or pure structure field references. For example, if an expression
myDataSet.MyLookupTable.Breakpoints is set as the parameter value, the Lookup Table
Editor updates the value of myDataSet.
• If the Lookup Table Editor has a data source that is specified more than once, for example, if the
same model workspace variable myVar is used for both breakpoints and table, the entire lookup
table is read-only.
• If the lookup table contains data passed in through a model argument, the Lookup Table Editor
treats the local model variable as the data source.
• The Lookup Table Editor supports report generation only for the n-D Lookup Table, 1-D Lookup
Table, n-D Lookup Table, Interpolation Using Prelookup, Prelookup, and Direct Lookup Table n-D
blocks.
• The Lookup Table Editor does not support runtime tunability of parameters.
• The Lookup Table Editor shows breakpoints for the Interpolation Using Prelookup block only when
the Interpolation Using Prelookup block is directly connected to one or more Prelookup blocks.

See Also
1-D Lookup Table | 2-D Lookup Table | Direct Lookup Table (n-D) | n-D Lookup Table | Interpolation
Using Prelookup | Prelookup

Related Examples
• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23

External Websites
• How to Use the Lookup Table Editor (5min 9sec)

42-22
Edit Lookup Table Data with Lookup Table Spreadsheet

Edit Lookup Table Data with Lookup Table Spreadsheet


You can use a lookup table spreadsheet to view lookup table and breakpoint data. The lookup table
spreadsheet is shared by multiple interfaces, including the Simulink.LookupTable property dialog
box and the Lookup Table Editor. This topic and its examples are presented using the
Simulink.LookupTable property dialog box. Here is lookup table data spreadsheet as seen
through the Simulink.LookupTable property dialog box. The spreadsheet is highlighted.

When the Breakpoints specification property is set to Explicit values, use the lookup table
spreadsheet at the bottom to:

• View, add, manipulate, and remove table and breakpoint data.


• Create or modify table or breakpoint data using MATLAB expressions.

Alternatively, you can copy and paste the contents of a Microsoft Excel spreadsheet or any
spreadsheet application.

42-23
42 Working with Lookup Tables

• View and edit 2-D slices of data from multiple dimensions.

42-24
Edit Lookup Table Data with Lookup Table Spreadsheet

This topic describes:

• Supported data types for the lookup table spreadsheet


• How to create, edit, and view table and breakpoint data in the tabular interface
• How to view multidimensional 2-D slices
• How the tabular interface handles data overflows
• How the tabular interface handles invalid data
• Supported keyboard shortcuts

Lookup Table Spreadsheet Data Type Support


The spreadsheet supports these data types:

• Built-in data types (int8, uint8, int16, uint16, int32, uint32, double, single, boolean)

42-25
42 Working with Lookup Tables

• Fixed-point data types


• uint64, int64
• half

It does not support other data types that Simulink supports.

Create Simulink.LookupTable Objects


To start working with a Simulink.LookupTable object, create one at the MATLAB command line:

LUTObj = Simulink.LookupTable;

How to Open the Simulink.LookupTable Object Property Dialog Box


To work with the Simulink.LookupTable object, start its property dialog box in one of these ways
from the MATLAB Command Window:

• In the workspace, double-click the Simulink.LookupTable object.


• In the Model Explorer, double-click the object in the specific workspace for the object.
• In the command line, use the open function, for example:

open LUTObj

Create Table and Breakpoint Data


Generate data and manipulate it using standard table editing actions. You can generate lookup table
data in multiple ways, such as in the workspace, from Microsoft Excel, and so forth, and copy that
data into the lookup table spreadsheet. For Simulink.LookupTable objects, you can also generate
data from within the property dialog box using MATLAB expressions.

This example describes how to create data in the MATLAB Command Window workspace and how to
set up the property dialog box lookup table spreadsheet using an example with that data.

1 To create table and breakpoint data, at the MATLAB command line, type:

LUTObj.Breakpoints(1).Value = fi(linspace(1000,5000,5),1,16,2);
LUTObj.Breakpoints(2).Value = single(linspace(1,2,5));
LUTObj.Table.Value = uint16(rand(5,5)*60*60);
2 Set up the Unit and Field name properties for the object.

LUTObj.Breakpoints(1).Unit = 'rpm';
LUTObj.Breakpoints(2).Unit = 'Nm';
LUTObj.Table.Unit = 'kg/hr';
LUTObj.Breakpoints(1).FieldName = 'Corr_Speed';
LUTObj.Breakpoints(2).FieldName = 'Prs_ratio';
LUTObj.Table.FieldName = 'Mass_Flow_Rate';
3 Open the property dialog box.

open LUTObj;

42-26
Edit Lookup Table Data with Lookup Table Spreadsheet

4 From within the tabular area, you can perform typical table edits on particular breakpoint data,
such as copying and pasting. Data that has been edited but not applied is outlined in yellow.
When you are done, click Apply. Observe that the yellow outline for the data is gone.

Tip To create this data directly in the lookup table spreadsheet:

1 Set Number of table dimensions to 2.


2 Set the first breakpoint to fi(linspace(1000,5000,5),1,16,2);.
3 Set the second breakpoint to single(linspace(1,2,5));.
4 Set Table to uint16(rand(5,5)*60*60);.

42-27
42 Working with Lookup Tables

View Multidimensional Slices of Data


The spreadsheet lets you view and edit 2-D slices of data. This example describes how to use the slice
selector to navigate through the 2-D slices of 3-D data.

To view a multidimensional slice, use the dropdown lists under the MATLAB expression parameter.
There is a dropdown list for each breakpoint. To view a two-dimensional slice, choose a combination
of the breakpoint data from the vertical and horizontal dropdown lists.

1 Change the table dimensions to 3.

2 In the tabular area at the bottom, change the horizontal breakpoint slice to BP3. Observe the
changed view of the slice of data.

Edit Table and Breakpoint Data with MATLAB Expressions


Edit table and breakpoint data using standard table editing actions, such as cutting or copying and
pasting, or directly editing table cells. You can also edit table and breakpoint data with MATLAB
expressions.

This example shows how to replace the table and breakpoint using a MATLAB expression.

42-28
Edit Lookup Table Data with Lookup Table Spreadsheet

1 In the spreadsheet, select BP3 from the horizontal dimension dropdown list.
2 In the MATLAB expression field, enter linspace(1000,9999,5).
3 Observe the changed view of the slice of data.

Edit Table and Breakpoint Data


You can perform standard table edits in the spreadsheet. This example shows how to apply the same
value to multiple cells.

Replace a column of data with the same value.

1 In the spreadsheet, select row 1, column 2 of the table data.


2 Select the entire column by dragging down the column.
3 Enter 324.
4 Press Ctrl+Enter.
5 Observe that the entire column of data is now 324.

Add a row to the table.

42-29
42 Working with Lookup Tables

1 In the spreadsheet, right-click the last row of the table and select Insert > Insert Row Below.

Delete a column in the table.

1 In the spreadsheet, right-click the last column of the table and select Delete > Delete Column.

Select and paste a region in the table.

1 In the spreadsheet, select the top-left cell of your selection and drag to the bottom-right of your
selection.

42-30
Edit Lookup Table Data with Lookup Table Spreadsheet

2 Copy the selected area with Ctrl+C.


3 Select another area of the table. Paste the selected data with Ctrl+V.

Enable Heatmap for Table Data


You can view heatmaps for your data. Right-click any cell in the table and select Heatmap On.

42-31
42 Working with Lookup Tables

Overflow Handling
The Simulink.LookupTable object property dialog box handles data overflows in the lookup table
spreadsheet by automatically changing values to ones that do not cause overflows. For example, if
you enter a value of 70000 in a cell for a data type of uint16, the property dialog box automatically
changes the value to 65535, which is the maximum number for uint16. For a list of supported
Simulink.LookupTable object property dialog box data types, see “Lookup Table Spreadsheet
Data Type Support” on page 42-25.

Data Validation
The lookup table spreadsheet performs data validation when you enter a table cell value and press
Enter. For example, if you enter NaN, Inf or -Inf as a table cell value, an error is displayed.

The MATLAB expression area also validates expressions. For example, if you enter an invalid
expression, the text box is outlined in red and displays an error message on an expected expression.
If you enter an expression for fixed-point data with a bias, the software evaluates and, as necessary,
saturates the value to the nearest available fixed-point value before displaying the corrected value in
the table.

42-32
Edit Lookup Table Data with Lookup Table Spreadsheet

Lookup Table Spreadsheet Tabular Interface Shortcuts


Table Navigation

Action Key or Keys


Move to the table cell above current active cell. Up Arrow
Move to table cell under current active cell. Down Arrow
Move to the table cell to the right of the current Right Arrow or Tab
active cell.
Move to the table cell to the left side of current Left Arrow or Tab+Shift
active cell.
Move to the first table cell in a column. Ctrl+Up Arrow
Move to the last table cell in a column. Ctrl+Down Arrow
Move to the first table cell in a row. Ctrl+Left Arrow
Move to the last table cell in a row. Ctrl+Right Arrow

Selection

Action Key or Keys


Select all. Ctrl+A
Extend selection of the table cell above. Shift+Up Arrow
Extend selection of the table cell underneath. Shift+Down Arrow
Extend selection of the table cell to the right. Shift+Right Arrow
Extend selection of the table cell to the left. Shift+Left Arrow
Select all table cells in the row to the left, Shift+Ctrl+Left Arrow
including the current cell.
Select all table cells in the row to the right, Shift+Ctrl+Right Arrow
including the current cell.
Select all cells from the column to the top of the Shift+Ctrl+Up Arrow
table, including the current cell.
Select all cells from the column to the bottom of Shift+Ctrl+Down Arrow
the table, including the current cell.

42-33
42 Working with Lookup Tables

Editor

Action Key or Keys


Open or close table cell editor. Enter
Open table cell editor. F2
Cancel editing and close table cell editor. Esc
Clear table cell. Backspace or Delete
Copy table cell content. Ctrl+C
Cut table cell content. Ctrl+X
Paste table cell content. Ctrl+V
Fill all selected table cells with edited cell value. Ctrl+Enter
Undo. Ctrl+Z
Redo. Ctrl+Y

Context Menu Navigation

Action Key or Keys


Move the selection to the next option in context Down Arrow
menu.
Move the selection to the previous option in Up Arrow
context menu.
Select option from context menu. Enter

See Also
Simulink.LookupTable

More About
• “Use the Lookup Table Editor” on page 42-19
• “Enter Breakpoints and Table Data” on page 42-35

42-34
Enter Breakpoints and Table Data

Enter Breakpoints and Table Data


In this section...
“Enter Data in Block Parameter Dialog Box” on page 42-35
“Enter Data in Lookup Table Editor” on page 42-35
“Enter Data for Multiple Lookup Tables in Lookup Table Editor” on page 42-37
“Enter Data Using Inports of Lookup Table Dynamic Block” on page 42-37

Enter Data in Block Parameter Dialog Box


This example shows how to populate a 1-D Lookup Table block using the parameter dialog box. The
lookup table in this example approximates the function y = x3 over the range [-3, 3].

1 Add a 1-D Lookup Table block to a model.


2 In the 1-D Lookup Table block dialog box, enter the table dimensions and table data:

• Set Number of table dimensions to 1.


• Set Table data to [-27 -8 -1 0 1 8 27].

Alternatively, to use an existing lookup table (Simulink.LookupTable) object, select Data


specification > Lookup table object.
3 Enter the breakpoint vector using one of two methods:

• To specify evenly spaced data points, set Breakpoint specification to Even spacing. Set
First point to -3 and Spacing to 1. The block calculates the number of evenly spaced
breakpoints based on the table data.
• To specify breakpoint data explicitly, set Breakpoint specification to Explicit values
and set Breakpoints 1 to [-3:3].

Enter Data in Lookup Table Editor


This example shows how 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 Add a 2-D Lookup Table block to a model.


2 Open the Lookup Table Editor. For example, open the block dialog and click Edit table and
breakpoints.
3 Click in the lookup table path browser. Any models that contain lookup tables appear.

42-35
42 Working with Lookup Tables

4 Select untitled and press Enter.


5 In the hierarchy pane, navigate to the 2-D Lookup Table block.

The lookup table spreadsheet appears on the right.


6 In the spreadsheet, enter the breakpoint vectors and table data in the appropriate cells. To
change data, click a cell, enter the new value, and press Enter.

• In the cells associated with the BreakpointsForDimension1, enter each of the values [0 1
2].
• In the cells associated with the BreakpointsForDimension2, 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].
7 Notice that each value you edit appears as a red dot in the plot to the right. As you click a value
in the table, the corresponding plot point is highlighted with a red dot.

8 In the Lookup Table Editor toolstrip, click Apply to update the data in the 2-D Lookup Table
block. If the parameter value in the source is specified as a variable name, the applied data
updates the variable data, but does not overwrite the string set in the block dialog.

42-36
Enter Breakpoints and Table Data

For more information on using the lookup table spreadsheet, see “Edit Lookup Table Data with
Lookup Table Spreadsheet” on page 42-23.

Enter Data for Multiple Lookup Tables in Lookup Table Editor


This example builds on the “Enter Data in Lookup Table Editor” on page 42-35 example.

1 Open another model that contains one or more lookup tables, for example,
openExample('sldemo_fuelsys').
2 In the lookup table path browser, type the name of the new model, for example,
sldemo_fuelsys.
3 Select sldemo_fuelsys, then press Enter.

The hierarchy contains two systems that contain lookup tables.


4 Navigate through the sldemo_fuelsys node and select a lookup table to edit.

Enter Data Using Inports of Lookup Table Dynamic Block


This example shows how to populate a Lookup Table Dynamic block using the inports of the block. In
this example, the lookup table approximates the function y = 3x2 over the range [0, 10].

42-37
42 Working with Lookup Tables

1 Add a Lookup Table Dynamic block to a 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 these 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 vector to the Lookup Table Dynamic block by connecting the output port of
the Constant block to the input port labeled xdat of the Lookup Table Dynamic block. This signal
is the input breakpoint vector 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 input port of the Lookup Table
Dynamic block labeled ydat. This signal is the table data for y.

See Also
Lookup Table Dynamic | n-D Lookup Table

More About
• “Use the Lookup Table Editor” on page 42-19
• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5

42-38
Import Lookup Table Data from MATLAB

Import Lookup Table Data from MATLAB


In this section...
“Import Standard Format Lookup Table Data” on page 42-39
“Propagate Standard Format Lookup Table Data” on page 42-40
“Import Nonstandard Format Lookup Table Data” on page 42-40
“Propagate Nonstandard Format Lookup Table Data” on page 42-42

You can import table and breakpoint data from variables in the MATLAB workspace by referencing
them in the Table and Breakpoints tab of the dialog box. The following examples show how to
import and export standard format and non-standard format data from the MATLAB workspace.

Import Standard Format Lookup Table Data


Suppose you specify a 3-D lookup table in your n-D Lookup Table block.

Create workspace variables to use as breakpoint and table data for the lookup table.
table3d_map = zeros(2,4,3);
table3d_map(:,:,1) = [ 1 2 3 4; 5 6 7 8];
table3d_map(:,:,2) = [ 11 12 13 14; 15 16 17 18];
table3d_map(:,:,3) = [ 111 112 113 114; 115 116 117 118];
bp3d_z =[ 0 10 20];
bp3d_x =[ 0 10 20 30];
bp3d_y =[ 400 6400];

Open the n-D Lookup Table block dialog box, and enter the following parameters in the Table and
Breakpoints tab:

• Table data: table3d_map


• Breakpoints 1: bp3d_y
• Breakpoints 2: bp3d_x
• Breakpoints 3: bp3d_z

Click Edit table and breakpoints to open the Lookup Table Editor and show the data from the
workspace variables.

42-39
42 Working with Lookup Tables

Propagate Standard Format Lookup Table Data


When you make changes to your lookup table data, consider propagating the changes back to the
MATLAB workspace variables the data was imported from using File > Update Block Data.

You can also use the Lookup Table Editor to edit the table data and breakpoint vector of
Simulink.LookupTable and the breakpoint vector of Simulink.Breakpoint objects and
propagate the changes back to the object.

Suppose you make a change to the lookup table variables imported from the MATLAB workspace
variables in “Import Standard Format Lookup Table Data” on page 42-39. For example, change the
value of the data in (1,1,1) from 1 to 33. To propagate this change back to table3d_map in the
workspace, in the Lookup Table Editor toolstrip, click Apply.

Import Nonstandard Format Lookup Table Data


Suppose you specify a 3-D lookup table in your n-D Lookup Table block. Create workspace variables
to use as breakpoint and table data for the lookup table. The variable for table data,
table3d_map_custom, is a two-dimensional matrix.
table3d_map_custom = zeros(6,4);
table3d_map_custom = [ 1 2 3 4; 5 6 7 8;
11 12 13 14; 15 16 17 18;
111 112 113 114; 115 116 117 118];
bp3d_z =[ 0 10 20];
bp3d_x =[ 0 10 20 30];
bp3d_y =[ 400 6400];

42-40
Import Lookup Table Data from MATLAB

Open the n-D Lookup Table block dialog box, and enter the following parameters in the Table and
Breakpoints tab. Transform table3d_map_custom into a three-dimensional matrix for the table data
input using the reshape command.

• Table data: reshape(table3d_map_custom,[2,4,3])


• Breakpoints 1: bp3d_y
• Breakpoints 2: bp3d_x
• Breakpoints 3: bp3d_z

Click Edit table and breakpoints to open the Lookup Table Editor and show the data from the
workspace variables.

Change 1 to 33 in the Lookup Table Editor. The Lookup Table Editor records your changes by
maintaining a copy of the table. To restore the variable values from the MATLAB workspace, in the
Lookup Table Editor toolstrip, click Reload. To update the MATLAB workspace variables with the
edited data, in the Lookup Table Editor toolstrip, click Apply. 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 “Propagate Nonstandard Format Lookup Table Data” on
page 42-42.

42-41
42 Working with Lookup Tables

Propagate Nonstandard Format Lookup Table Data


This example shows how to propagate changes from the Lookup Table Editor to workspace variables
of nonstandard format. Suppose your Simulink model from “Import Nonstandard Format Lookup
Table Data” on page 42-40 has a three-dimensional lookup table that gets its table data from the two-
dimensional workspace variable table3d_map_custom. Update the lookup table in the Lookup Table
Editor and propagate these changes back to table3d_map_custom using a customization function.

1 Create a file named sl_customization.m with these contents.


function sl_customization(cm)
cm.LookupTableEditorCustomizer.getTableConvertToCustomInfoFcnHandle{end+1} = ...
@myGetTableConvertInfoFcn;
end

In this function:

• The argument cm 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.
2 In the same file, define the myGetTableConvertInfoFcn function.
function blkInfo = myGetTableConvertInfoFcn(blk,tableStr)
blkInfo.allowTableConvertLocal = true;
blkInfo.tableWorkSpaceVarName = 'table3d_map_custom';
blkInfo.tableConvertFcnHandle = @myConvertTableFcn;
end

The myGetTableConvertInfoFcn function returns the blkInfo object containing three fields.

• allowTableConvertLocal — Allows table data conversion 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 allowTableConvertLocal is set to true, the table data for that block is converted to
the nonstandard format of the workspace variable whose name matches
tableWorkSpaceVarName. The conversion function corresponds to the handle that
tableConvertFcnHandle specifies. You can use any alphanumeric name for the conversion
function.
3 In the same file, define the myConvertTableFcn function. This function converts a three-
dimensional lookup table of size Rows * Columns * Height to a two-dimensional variable of size
(Rows*Height) * Columns.
% Converts 3-dimensional lookup table from Simulink format to
% nonstandard format used in workspace variable
function cMap = myConvertTableFcn(data)

% Determine 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);
% Transform data back to a 2-dimensional matrix
cMap = reshape(data,[numRow,numCol]);
end

42-42
Import Lookup Table Data from MATLAB

4 Put sl_customization.m on the MATLAB search path. You can have multiple files named
sl_customization.m on the search path. For more details, see “Behavior with Multiple
Customization Functions” on page 42-43.
5 Refresh Simulink customizations at the MATLAB command prompt.

sl_refresh_customizations
6 Open the Lookup Table Editor for your lookup table block and select File > Update Block Data.
Click Yes to overwrite the workspace variable table3d_map_custom.
7 Check the value of table3d_map_custom in the base workspace.

table3d_map_custom =

33 2 3 4
5 6 7 8
11 12 13 14
15 16 17 18
111 112 113 114
115 116 117 118

The change in the Lookup Table Editor has propagated to the workspace variable.

Note If you do not overwrite the workspace variable table3d_map_custom, you are prompted to
replace it with numeric data. Click Yes to replace the expression in the Table data field with numeric
data. Click No if you do not want your Lookup Table Editor changes for the table data to appear in
the block dialog box.

Behavior with Multiple Customization Functions

At the start of a MATLAB session, Simulink loads each sl_customization.m customization file on
the path and executes the sl_customization function. 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 contains one or more function handles, the allowTableConvertLocal property determines
whether changes in the Lookup Table Editor can be propagated.

• If the value is set to true, then the table data is converted to the nonstandard format in the
workspace variable.
• If the value is set to false, then table data is not converted to the nonstandard format in the
workspace variable.
• If the value is set to true and another customization function specifies it to be false, the Lookup
Table Editor reports an error.

See Also

More About
• “About Lookup Table Blocks” on page 42-2

42-43
42 Working with Lookup Tables

• “Anatomy of a Lookup Table” on page 42-4


• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Import Lookup Table Data from Excel Using readtable” on page 42-47

42-44
Copy and Paste Lookup Table Data from Excel

Copy and Paste Lookup Table Data from Excel


This example shows how to copy data from an Excel spreadsheet or any spreadsheet application into
a lookup table.

1 Add a 2-D Lookup Table block to a model.


2 Open the Lookup Table Editor. For example, open the block dialog and click Edit table and
breakpoints.
3 Create or open an existing Excel spreadsheet, for example, an Excel spreadsheet that contains
this data.

-10 1 25
-7 2 35
-4 4 42
4 Copy and paste the contents of the Excel spreadsheet into the lookup table spreadsheet.

5 Notice that the pasted elements in the lookup table spreadsheet have a yellow border. This
yellow border indicates that the data has not yet been saved. To save the data to the data source,
click Apply. In this example, the data source is the 2-D Lookup Table block.
6 At the bottom of the Lookup Table Editor is a table of sources for the data.

42-45
42 Working with Lookup Tables

To display and hide this table, click Data Source in the toolstrip.
7 To get the data from the data source into the Lookup Table Editor, click Reload. If you do not
click Apply before clicking Reload, the editor discards the spreadsheet before loading the data
from the data source.
8 To save the data from Lookup Table Editor spreadsheet to the data source, click Apply.

See Also

Related Examples
• “Anatomy of a Lookup Table” on page 42-4
• “Import Lookup Table Data from MATLAB” on page 42-39
• “Import Lookup Table Data from Excel Using readtable” on page 42-47

42-46
Import Lookup Table Data from Excel Using readtable

Import Lookup Table Data from Excel Using readtable


This workflow outlines how to use the readtable function in a model to import data into a lookup
table.

Tip Instead of importing data into a lookup table, you can also copy and paste the contents of an
Excel spreadsheet into a Lookup Table spreadsheet (see “Copy and Paste Lookup Table Data from
Excel” on page 42-45).

1 Create or open an existing Excel spreadsheet, for example, an Excel spreadsheet that contains
this data.

1 25
-7 2 35
-4 4 42
2 Save the Excel file in a folder on the MATLAB path, for example MySpreadsheet.xlsx.
3 Create a model and add a 2-D Lookup Table block.
4 In this model, select Model Settings > Model Properties.
5 In the Model Properties dialog box, in the Callbacks tab, click PostLoadFcn callback in the
model callbacks list.
6 Enter the code to import the Excel spreadsheet data from Sheet1 in the text box. Use the
MATLAB readtable function, as shown in this example for a 2-D lookup table.

% Import the data from Excel for a lookup table


data = readtable('MySpreadsheet','Sheet','Sheet1');
% 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};
7 Click OK.

After you save your changes, the next time you open the model, Simulink invokes the callback and
imports the data. To see the imported data, click the View diagnostics link.

See Also

More About
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Import Lookup Table Data from MATLAB” on page 42-39

42-47
42 Working with Lookup Tables

Visualize Data Through Plots


This example shows how to use the plots to visualize the data in the Lookup Table Editor.

1 Add a 2-D Lookup Table block to a model.


2 Open the Lookup Table Editor. For example, open the block dialog and click Edit table and
breakpoints.
3 By default, the 2-D Lookup Table block has this data as an example.

4 To create two tabs, one for the spreadsheet and one for the plot, pause between the spreadsheet
and plot and click the red X. To view or tile the panes, drag the panes as you want to position
them.
5 Click the data points in the spreadsheet and observe the corresponding red dot in the plot.

42-48
Visualize Data Through Plots

6 From the toolstrip, click another plot type, such as Line, Surface, or Contour, and reselect the
same data. These plots are the equivalent of the MATLAB functions line, mesh, line, surface,
and contour, using the table and breakpoint data.

Each plot type and data selection gives you another view of the data on that plot type.
7 To view heatmaps of your data, click Heatmap in the toolstrip.

See Also
contour | line | mesh | surface

42-49
42 Working with Lookup Tables

Related Examples
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23

42-50
Generate Report of Lookup Table

Generate Report of Lookup Table


Generate a report of one or more lookup tables in a model. Lookup Table Editor supports report
generation only for the n-D Lookup Table, 1-D Lookup Table, n-D Lookup Table, Interpolation Using
Prelookup, Prelookup, and Direct Lookup Table blocks. Lookup Table Editor returns a message for
blocks for which it does not generate a report.

1 Start the model sldemo_fuelsys.

openExample('sldemo_fuelsys')
2 Open the Lookup Table Editor. For example, type lookupTableEditor in the MATLAB
Command Window.
3 In the lookup table path browser, type openExample('sldemo_fuelsys') and press Enter.

The sldmeo_fuelsys model and the subsystems that contain lookup table blocks display in the
Lookup Table Blocks pane.

4 Select fuel_rate_control, then click Generate Report.


5 The software evaluates the number of lookup tables in the model (5). Click OK.
6 The software generates an HTML file, saved to current_folder/lookupTableReport.html.
Each numbered section of the file contains a report of a lookup table, including information such
as:

• Breakpoint data BP1 versus BP2.


• A plot of the lookup table outputs against the breakpoints
• Data types
• Notes about the report generation.

See Also

Related Examples
• “Use the Lookup Table Editor” on page 42-19

42-51
42 Working with Lookup Tables

Register Custom Lookup Table Blocks

You can use the Lookup Table Editor to register custom lookup table blocks that you have created.
Configure the Lookup Table Editor to recognize the custom lookup table blocks in your model.

Tip Entries must be valid MATLAB variable names.

1 In the Lookup Table Editor toolstrip, click Register Custom. The Lookup Table Blocks Type
Configuration dialog box appears.

The dialog box displays a table of the lookup table block types that the Lookup Table Editor
currently recognizes. This table includes the standard blocks. Each row of the table displays key
attributes of a lookup table block type.
2 Click Add Row on the dialog box. A new row appears at the bottom of the block type table.
3 Enter information for the custom block in the new row under these headings. You must enter an
entry for each table cell.

Field Name Description


Block type Block type of the custom block. The block type is the
value of the BlockType parameter of the block.
Mask type Mask type of the custom block. The mask type is the
value of the MaskType parameter of the block.

42-52
Register Custom Lookup Table Blocks

Field Name Description


Breakpoint Parameter(s) Names of the block parameters that are used as
breakpoints. Separate multiple breakpoints with
commas.
Table Parameter Names of the block parameters that store the table.

The Lookup Table Editor uses the information in the Block Type and Mask Type columns to
identify the block type. The editor uses the information in the Breakpoint Parameters and
Table Parameter to find the lookup table data.
4 Click OK.

• 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 and
click Delete Row.
• To automatically populate a table row with the mask characteristics of a masked block, select the
block in the model and click Autopopulate for Current Block. Clicking this button also enables
the autocompletion of the block and table name fields.

See Also

More About
• “Use the Lookup Table Editor” on page 42-19
• “Edit Lookup Table Data with Lookup Table Spreadsheet” on page 42-23
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control” on page 43-103

42-53
42 Working with Lookup Tables

Visualize Lookup Tables Visualized Through Lookup Table


Control
If you use the Lookup Table Control on page 43-103 to visualize and edit N-dimensional lookup table
data in mask dialogs, the Lookup Table Editor can display these tables without registration. For
example, the slexMaskLookupTableControlExample model has multiple custom lookup tables.

1 Open the model.


openExample('simulink_masking/MaskLookupTableControlExample')

2 Open the Lookup Table Editor for the 2-D Table Lookup Table S-Function lookup table.
lookupTableEditor('slexMaskLookupTableControlExample/2-D Table Lookup S-Function')

3 In the Lookup Table Blocks hierarchy pane, expand 2-D Table Lookup S-Function.

4 In the hierarchy pane, click fuelflowmap.

5 Compare this Lookup Table Editor view with the custom lookup table block.

42-54
Visualize Lookup Tables Visualized Through Lookup Table Control

See Also

Related Examples
• “Register Custom Lookup Table Blocks” on page 42-52
• “Use the Lookup Table Editor” on page 42-19
• “Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control” on page 43-103

42-55
42 Working with Lookup Tables

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. (If you want to skip the procedure, you can open
the model directly.)
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 vector 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.

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.

42-56
Create a Logarithm Lookup Table

5 Start simulation.

The following behavior applies to the n-D Lookup Table block.

Value of the Constant Action by the n-D Example of Block Behavior


Block Lookup Table Block Input Value Output Value
Equals a breakpoint Returns the 5 0.699
corresponding output
value
Falls between Linearly interpolates the 7.5 0.874
breakpoints output value using
neighboring breakpoints
Falls outside the range of Linearly extrapolates the 10.5 1.023
the breakpoint vector output value from a pair
of values at the end of the
breakpoint vector

For the n-D Lookup Table block, the default settings for Interpolation method and
Extrapolation method are both Linear.

See Also
n-D Lookup Table

More About
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Import Lookup Table Data from MATLAB” on page 42-39

42-57
42 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 Enables reuse of index search For more information, see “Using
to table data, followed by an results to look up data in multiple the Prelookup and Interpolation
interpolation and extrapolation tables, which reduces simulation Blocks”.
stage that computes outputs time
Set breakpoint and table data types Lowers memory required to store: For more information, see “Saving
explicitly Memory in Prelookup and
• Breakpoint data that uses a Interpolation Blocks by Using
smaller type than the input Smaller Data”.
signal
• Table data that uses a smaller
type than the output signal
Provides easier sharing of: For more information, see “Sharing
Parameters in Prelookup and
• Breakpoint data among Interpolation Blocks” (Fixed-Point
Prelookup blocks Designer).
• Table data among Interpolation
Using Prelookup blocks
Enables reuse of utility functions in For more information, see “Shared
the generated code Utility Functions for Prelookup
Blocks” (Fixed-Point Designer).
Set the data type for intermediate Enables use of higher precision for For more information, see “High
results explicitly internal computations than for table Precision Calculations in
data or output data Interpolation Block” (Fixed-Point
Designer).

See Also
Prelookup | Interpolation Using Prelookup

More About
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5

42-58
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 42-59
“Optimize Breakpoint Spacing in Lookup Tables” on page 42-60
“Reduce Data Copies for Lookup Table Blocks” on page 42-60
“Efficient Code for Row-Major Array Layout” on page 42-61

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
2-D Lookup Table code

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.

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 For code efficiency
lookup table blocks that generate expensive
out-of-range checking code
By Product >Simulink Check > Modeling For safety-critical applications
Standards > DO-178C/DO-331 Checks >
Check usage of lookup table blocks

For more information about the Model Advisor, see “Check Your Model Using the Model Advisor” on
page 5-2 in the Simulink documentation.

42-59
42 Working with Lookup Tables

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 Evenly Spaced Data Unevenly Spaced Data
Data
Execution speed The execution speed is the The execution speed is The execution speed is the
fastest. The position faster than that for slowest of the different
search and interpolation unevenly-spaced data spacings because the
are the same as for evenly- because the position position search is slower,
spaced data. However, to search is faster and the and the interpolation
increase speed a bit more interpolation uses a simple requires more operations.
for fixed-point types, a bit division.
shift replaces the position
search, and a bit mask
replaces the interpolation.
Error The error can be larger The error can be larger The error can be smaller
than that for unevenly- than that for unevenly- because approximating a
spaced data because spaced data because function with nonuniform
approximating a function approximating a function curvature requires fewer
with nonuniform curvature with nonuniform curvature points to achieve the same
requires more points to requires more points to accuracy.
achieve the same accuracy. achieve the same accuracy.
ROM usage Uses less command ROM, Uses less command ROM, Uses more command
but more data ROM. but more data ROM. ROM, but less data ROM.
RAM usage Not significant. Not significant. Not significant.

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 “Check Your Model Using the Model Advisor” on
page 5-2 in the Simulink documentation.

Reduce Data Copies for Lookup Table Blocks


When you use workspace variables to store table and breakpoint data for Lookup Table blocks, and
then configure these variables for tunability, you can avoid data copies by using the same data type
for the block parameter and variable. Workspace variables include numeric MATLAB variables and
Simulink.Parameter objects that you store in a workspace, such as the base workspace, or in a

42-60
Optimize Generated Code for Lookup Table Blocks

data dictionary. If the data type of the variable is smaller than the data type of the block parameter,
the generated code implicitly casts the data type of the variable to the data type of the block
parameter. This implicit cast requires a data copy which can potentially significantly increase RAM
consumption and slow down code execution speed for large vectors or matrices.

For more information, see “Parameter Data Types in the Generated Code” (Embedded Coder) and
“Create Tunable Calibration Parameter in the Generated Code” (Simulink Coder).

Efficient Code for Row-Major Array Layout


To generate efficient code for row-major array layout, select the model configuration parameter Math
and Data Types > Use algorithms optimized for row-major array layout. The row-major
algorithms perform with the best speed and memory usage when operating on table data with row-
major array layout. Similarly, the default column-major algorithms perform best with column-major
array layout. Consider using the algorithm that is optimized for the specified array layout to achieve
best performance. For example, use row-major algorithms when array layout is set as row-major
during code generation.

Array Layout Algorithm Cache-Friendly Algorithm


Column-major Column-major Recommended
Row-major Row-major Recommended
Row-major Column-major Not recommended
Column-major Row-major Not recommended

For more information, see “Column-Major Layout to Row-Major Layout Conversion of Models with
Lookup Table Blocks” (Simulink Coder).

See Also
n-D Lookup Table | Prelookup | Interpolation Using Prelookup

More About
• “Check Your Model Using the Model Advisor” on page 5-2
• “Guidelines for Choosing a Lookup Table” on page 42-5
• “Column-Major Layout to Row-Major Layout Conversion of Models with Lookup Table Blocks”
(Simulink Coder)

42-61
42 Working with Lookup Tables

Row-Major Algorithm in Existing Models Containing Lookup


Table Blocks
The Direct Lookup Table (n-D), Interpolation Using Prelookup, and n-D Lookup Table blocks have
algorithms that work with row-major array layouts or column-major array layouts. This capability
requires a Simulink Coder license. For more information on row-major support, see “Code Generation
of Matrices and Arrays” (Simulink Coder).

Prior to R2018b, lookup table blocks supported only column-major array layouts. When selecting
algorithms optimized for row-major array layout for a model previously configured for algorithms
optimized for column-major array layout, you may need to preserve lookup table block semantics. For
example, if a model contains lookup table blocks configured like these:

• An Interpolation Using Prelookup block configured with a subtable selection before interpolation.
• A Direct Lookup Table (n-D) configured for a vector or 2-D matrix output

Use the permute function to rearrange the dimensions of the array and preserve the semantics.

For an example of preserving semantics by using table permutations, see “Direct Lookup Table
Algorithm for Row-Major Array Layout” (Simulink Coder) .

For an example of converting column-major arrays to row-major arrays see “Column-Major Layout to
Row-Major Layout Conversion of Models with Lookup Table Blocks” (Simulink Coder).

See Also
Direct Lookup Table (n-D) | Interpolation Using Prelookup | n-D Lookup Table

42-62
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 42-63
“Compatibility of Models with Older Versions of Lookup Table Blocks” on page 42-64
“How to Update Your Model” on page 42-64
“What to Expect from the Model Advisor Check” on page 42-65

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 • Block renamed as 1-D Lookup • Default integer rounding mode changed from Floor to
Table Table 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
• Table data with complex values
• Fixed-point data types with word lengths up to 128
bits
• Specification of data types for fraction and
intermediate results
• Specification of index search method
• Specification of diagnostic for out-of-range inputs

42-63
42 Working with Lookup Tables

Block Changes Enhancements


Lookup • Block renamed as 2-D Lookup • Default integer rounding mode changed from Floor to
Table (2-D) Table 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
• Table data with complex values
• Fixed-point data types with word lengths up to 128
bits
• Specification of data types for fraction and
intermediate results
• Specification of index search method
• 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 • Block renamed as n-D Lookup • Default integer rounding mode changed from Floor to
Table (n-D) Table 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.

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 simulink/Lookup Tables/1-D
Table Lookup Table
Lookup Table (2-D) simulink/Lookup Tables/Lookup simulink/Lookup Tables/2-D
Table (2-D) Lookup Table
Lookup Table (n-D) simulink/Lookup Tables/Lookup simulink/Lookup Tables/n-D
Table (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:

42-64
Update Lookup Table Blocks to New Versions

Step Action Reason


1 Run the Upgrade Advisor. 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 Modify each Lookup Table or Lookup Table (2-D)
settings: 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 Ensure that block replacement works for the
the results of the Upgrade Advisor check. entire model.

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 Upgrade Advisor, see “Model Upgrades”.

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 Parameter Settings After Automatic Block Replacement
Table or Lookup Table (2-D) Block 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 Index Search Method After Automatic Block
Lookup Table (2-D) Block Replacement
Not evenly spaced Binary search
Evenly spaced and tunable A prompt appears, asking you to select Binary
Evenly spaced and not tunable search or Evenly spaced points.

Blocks with Incompatible Settings

When a block has incompatible parameter settings, the Model Advisor shows a warning and a
recommended action, if applicable.

42-65
42 Working with Lookup Tables

• 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 Change the lookup method to one of The Lookup Method changes to
Nearest or Use Input Above. the following options: Interpolation - Use End
The replacement block does not Values.
support these lookup methods. • Interpolation -
Extrapolation In the replacement block, this
• Interpolation - Use End setting corresponds to:
Values
• Interpolation set to Linear
• Use Input Below
• Extrapolation set to Clip
The Lookup Method is Change the extrapolation method or
Interpolation - the port data types of the block. You also see a message that
Extrapolation, but the input and explains possible numerical
output are not the same floating- differences.
point type. The replacement block
supports linear extrapolation only
when all inputs and outputs are the
same floating-point type.
The block uses small fixed-point None You see a message that explains
word lengths, so that interpolation possible numerical differences.
uses only one rounding operation.
The replacement block uses two
rounding operations for
interpolation.

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.

See Also
n-D Lookup Table | Prelookup | Interpolation Using Prelookup

More About
• “Model Upgrades”
• “About Lookup Table Blocks” on page 42-2
• “Anatomy of a Lookup Table” on page 42-4
• “Guidelines for Choosing a Lookup Table” on page 42-5

42-66
43

Working with Block Masks

• “Masking Fundamentals” on page 43-3


• “Create a Simple Mask” on page 43-7
• “Manage Existing Masks” on page 43-10
• “Mask Callback Code” on page 43-12
• “Mask Display and Initialization Commands” on page 43-13
• “Get Started with Mask Initialization and Callback Code” on page 43-17
• “Author Mask Initialization and Callbacks” on page 43-21
• “Promote Block Parameters on a Mask” on page 43-27
• “Control Masks Programmatically” on page 43-32
• “Pass Values to Blocks Under the Mask” on page 43-36
• “Mask Linked Blocks” on page 43-38
• “Dynamic Mask Dialog Box” on page 43-41
• “Dynamic Masked Subsystem” on page 43-45
• “Debug Masks That Use MATLAB Code” on page 43-49
• “Introduction to System Mask” on page 43-50
• “Create and Reference a Masked Model” on page 43-52
• “Create and Display System Mask Programmatically” on page 43-56
• “Handling Large Number of Mask Parameters” on page 43-58
• “Customize Tables for Masked Blocks” on page 43-59
• “Control Custom Table Programmatically” on page 43-61
• “Add Images in Masks” on page 43-64
• “Create Hierarchical List in Mask Dialog” on page 43-65
• “Validating Mask Parameters Using Constraints” on page 43-66
• “Custom Constraint for Mask Parameter” on page 43-71
• “Share Parameter Constraints Across Multiple Block Masks” on page 43-76
• “Control Constraints Programmatically” on page 43-82
• “Define Measurement Units for Masked Blocks” on page 43-83
• “Masking Example Models” on page 43-84
• “Create a Custom Table in the Mask Dialog” on page 43-86
• “Create a Block Mask Icon” on page 43-89
• “Mask a Variant Subsystem” on page 43-91
• “Tune Mask Enumeration Parameters - Popup and Radio Button” on page 43-93
• “Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control” on page 43-103
• “Validate Input and Output Port Signals Using Port Constraints” on page 43-114
• “Graphical Icon Editor Overview” on page 43-117
43 Working with Block Masks

• “Create and Edit Block Mask Icon” on page 43-128


• “Add Dynamic Behavior to Masked Icons” on page 43-134
• “Validate Port Signals Among Ports of the Same Masked Block” on page 43-150
• “Draw Mask Icon Using Drawing Commands” on page 43-154
• “Unsafe Mask Callback Error” on page 43-155
• “Organize Mask Initialization and Callbacks in a MATLAB File” on page 43-156
• “Simulink Masking Examples” on page 43-162
• “Manage Interface Connector with Mask Initialization and Block Callbacks” on page 43-163
• “Unsafe Nested Callback” on page 43-166
• “Preserve Tunability of Parameters That Are Modified or Created in Mask Initialization”
on page 43-167
• “Share Port Constraints Across Multiple Masked Blocks” on page 43-174

43-2
Masking Fundamentals

Masking Fundamentals
A mask is a custom interface for a block that hides the block content, making it appear as an atomic
block with its own icon and parameter dialog box. It encapsulates the block logic, provides controlled
access to the block data, and simplifies the graphical appearance of a model.

When you mask a block, a mask definition is created and saved along with the block. A mask changes
only the block interface, and not the underlying block characteristics. You can provide access to one
or more underlying block parameters by defining corresponding mask parameters on the mask.

Mask a Simulink block to:

• Display a meaningful icon on a block


• Provide a customized dialog box for the block
• Provide a dialog box that enables you to access only select parameters of the underlying blocks
• Provide users customized description that is specific to the masked block
• Initialize parameters using MATLAB code

Consider the model that represents the equation of line y = mx + b.

Each block has its own dialog box, making it complicated to specify the values for the line equation
variables. To simplify the user interface, a mask is applied on the top-level subsystem block.

43-3
43 Working with Block Masks

Here the variable m represents slope and the variable b represents the intercept for the line equation
y = mx + b.

The mask dialog box displays the fields for Slope and Intercept that are internally mapped to
variables m and b.

Masked blocks do not support content preview. To preview the contents of a subsystem, see “Preview
Content of Model Components” on page 1-93.

Tip For masking examples, see “Masking Example Models” on page 43-84. The examples are
grouped by type. In an example model:

• To view the mask definition, double-click the View Mask block.


• To view the mask dialog box, double-click the block.

Examples of few blocks that cannot be masked are:

43-4
Masking Fundamentals

• Scope blocks
• Simulink Function block
• Initialize, Terminate and Reset Function blocks
• Gauge blocks

Masking Terminology
Term Description
Mask icon The masked block icon generated using drawing
commands. Mask icon can be static or change
dynamically with underlying block parameter
values.
Mask parameters The parameters that are defined in the Mask
Editor and appear on the mask dialog box.
Setting the value of a mask parameter on the
mask dialog box sets the corresponding block
parameter value.
Mask initialization code MATLAB Code that initializes a masked block or
reflects current parameter values. Add mask
initialization code in the Initialization pane of
the Mask Editor dialog box. For example, add
initialization code to set a parameter value
automatically.
Mask dialog callback code MATLAB Code that runs in the base workspace
when the value of a mask parameter changes.
Use callback code to change the appearance of a
mask dialog box dynamically and reflect current
parameter values. For example, enable visible
parameters on the dialog box.
Mask documentation Description and usage information for a masked
block defined in the Mask Editor.
Mask dialog box A dialog box that contains fields for setting mask
parameter values and provides mask description.
Mask workspace Masks that define mask parameters or contain
initialization code have a mask workspace. This
workspace stores the evaluated values of the
mask parameters and temporary values used by
the mask.

See Also

More About
• “Author Block Masks”
• “Create a Simple Mask” on page 43-7
• “Mask Editor Overview”

43-5
43 Working with Block Masks

• Creating a Mask: Masking Fundamentals (3 min, 46 sec)

43-6
Create a Simple Mask

Create a Simple Mask

You can mask a block interactively by using the Mask Editor or mask it programmatically. This
example describes how to mask a block using the Mask Editor. To mask a block programmatically,
see “Control Masks Programmatically” on page 43-32

Step 1: Open Mask Editor

1. Open the model in which you want to mask a block. Consider a model that contains a Subsystem
block for the equation of a line: y = mx + b.

2. Select the Subsystem block, right-click on the Subsystem block, click Create Mask.

Step 2: Define Mask

The Mask Editor contains four tabs that enable you to define the block mask and customize the dialog
box for the mask. For detailed information on each pane, see “Mask Editor Overview”. Use
Parameters and Dialog tab to add controls like parameters, displays, and action items to the mask
dialog box.

43-7
43 Working with Block Masks

1. Add Edit parameter to the block mask, in the left pane, under Parameter, click Edit twice to add
two new rows in the Dialog box pane.

2. Type Slope and Intercept in the Prompt column for the two Edit parameters. The value that
you enter in Prompt column appears on the mask dialog box. Similarly, type m and b in the Name
column. The value you enter in the Name column is the mask parameter name. The mask parameter
name must be a valid MATLAB® name.

3. In the right pane, under Property editor, provide values in the Properties, Dialog, and Layout
sections.

4. Click Save Mask.

5. To preview the mask dialog box without exiting the Mask Editor, click Preview.

Note: A Simulink® mask parameter cannot reference another parameter on the same mask.

For detailed information, see “Parameters & Dialog Pane”

Use Code pane to specify MATLAB code to control the mask parameters. For example, you can
provide a predefined value for a mask parameter. Consider the equation y = mx + b in the example.
To set the value of the child block corresponding to m, you can use the set_param function in the
code pane.

For detailed information, see “Code Pane”

Use Icon tab to create an icon for the block mask. Mask Editor provides you with two modes of
authoring block icon.

Graphical Icon Editor: You can create and edit the mask icon of a block through a graphical
environment. The various features in Graphical Icon Editor helps you to create icons with ease.

43-8
Create a Simple Mask

Launch Graphical Icon Editor from Mask Editor. For more information, see “Graphical Icon Editor
Overview” on page 43-117.

Mask Drawing Commands: Use a set of mask drawing commands to create masked block icon. You
can use the Properties pane on the left to specify icon properties and icon visibility. For detailed
information, see “Icon drawing commands”.

Use Constraints tab to create validations on mask parameters without having to write your own
validation code. There are four types of constraints, Parameter Constraint, Cross Parameter
Constraints, Port Constraints, and Cross Port Constraints. For detailed information, see
“Constraints”.

Step 3: Operate on Mask

1. You can preview the mask and choose to unmask the block or edit the block mask.

2. Double-click the masked block.

3. Type values in the Slope and Intercept boxes of the mask dialog box. To view the output,
simulate the model.

4. Click OK.

5. To edit the mask definition, select the subsystem block and right-click Mask > Edit Mask.

6. Select the subsystem block and right click Mask > Look Under Mask to view the blocks inside
the masked subsystem.

See Also

More About
• “Author Block Masks”
• “Mask Editor Overview”
• “Masking Fundamentals” on page 43-3

43-9
43 Working with Block Masks

Manage Existing Masks

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 On the Subsystem Block tab, in the Mask group, click Edit Mask.

The Mask Editor reopens, showing the existing mask definition. Change the mask as needed. After
you change a mask, click Apply to preserve the changes.

View Mask Parameters


To display a mask dialog box, double-click the block. Alternatively, select the block and on the Block
tab, in the Mask group, click Mask Parameters.

Tip Each block has a block parameter dialog box. To view the block parameters dialog box of a
masked block, right-click the masked block and select Block Parameters (BlockType).

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, select the block and on the Subsystem tab, click Look Under Mask.

Remove Mask
To remove a mask from a block,

1 Select the block.


2 On the Block tab, in the Mask group,click Edit Mask.

The Mask Editor opens and displays the existing mask, for example:

43-10
Manage Existing Masks

3 Click Delete Mask in the of the Mask Editor.

The Mask Editor removes the mask from the block.

See Also

More About
• “Create a Simple Mask” on page 43-7

43-11
43 Working with Block Masks

Mask Callback Code


Mask callback allows you to customize the behavior of mask dialog if there is a change in the mask
dialog. For example, certain block parameter in the mask dialog is disabled or enabled upon changing
the value of a block parameter in the mask dialog.

Execute Callback Code


Mask parameter callback codes are executed in a temporary workspace and not in the base
workspace. If you need a variable created in the callback to be available later (not during callback
processing), you must explicitly assign those variables to the base workspace.

Simulink executes the callback commands when there is a change in the value of the parameter.
Parameter callbacks are executed in the following scenarios:

• Open mask dialog box and callback commands execute sequentially, starting with the top mask
dialog box.
• Modify a parameter value in the mask dialog box and then change the cursor location/ press Apply.
For example, you press the Tab key or click into another field in the dialog box after changing the
parameter value.
• Modify the parameter value by using the set_param command.
• Open the model with Edit Time Warnings and Errors in Diagnostics enabled.
• If you close a mask dialog box without saving the changes, the Callback command for parameters
is executed sequentially.

Note

• Buttons on mask dialog box are unavailable when the callback code associated with the button is
being executed.
• Callback commands do not execute if the mask dialog box is open when the block tool tip appears.

See Also

More About
• “Author Block Masks”
• “Get Started with Mask Initialization and Callback Code” on page 43-17
• “Organize Mask Initialization and Callbacks in a MATLAB File” on page 43-156
• “Manage Interface Connector with Mask Initialization and Block Callbacks” on page 43-163
• “Unsafe Mask Callback Error” on page 43-155
• “Unsafe Nested Callback” on page 43-166

43-12
Mask Display and Initialization Commands

Mask Display and Initialization Commands

Create icons for the masked blocks. You can either create static or dynamic icons. Static icons remain
unchanged. Dynamic icons are created with the mask parameters, hence the icon changes with a
change in the mask parameters. This example shows how to use drawing commands to create a mask
icon.

Explore the model

This model has four subsystem blocks which demonstrates drawing static and dynamic mask icons.

open_system("slexMaskDisplayAndInitializationExample");

Draw Static Icon

A static mask icon remains unchanged, independent of the value of the mask parameters. To create a
static icon:

1. Right click the block Independent static Icon > Mask > Edit Mask.

2. Go to Icon pane, and use the patch command to draw color patch of specified shape on masked
icon.

patch([0 5 10 15 20 15 10 5 0], [0 20 8 20 0 16 6 16 0], [0 0 1])

43-13
43 Working with Block Masks

You can also select an image to display on the mask icon.

Draw Dynamic Icon

Draw Dynamic Icon Depending on Mask Parameters

A dynamic icon changes with the values of the mask parameters. In this example, the shape of the
icon changes between triangle or quadrilateral based on the mask popup parameter. Also, the colour
intensity of the shape can be changed based on the mask parameter.

To create a dynamic icon:

1. Right-click the block Icon Dependent on Parameters > Mask > Edit Mask.

2. Create a popup parameter graphic_opt, enter the Type options as Triangle and
Quadrilateral.

3. Create an edit parameter colorIntensity to control the color intensity of the shape.

4. Use this code in the Icon pane.

Use get_param to obtain the text of the selected element

gr_opt = get_param(gcb, 'graphic_opt');

if strcmp(gr_opt,'Quadrilateral')
% Here we can use the mask parameter 'colorIntensity'
% directly because it is of type 'edit'
patch([1 4 12 22], [3 23 32 10], [1 0 0]*colorIntensity);
elseif strcmp(gr_opt,'Triangle')

43-14
Mask Display and Initialization Commands

patch([4 12 22], [23 32 10], [1 0 0]*colorIntensity);


end

Double-click the block Icon Dependent on Parameters to view the block parameters. Select the
Shape as Quadrilateral and enter Colour Intensity as .8. Click Ok to see the change in mask
icon.

Draw Mask Icon Depending on Mask Workspace Variable

You can either use a mask parameter to directly control the mask icon or use a derived mask
parameter to control the mask icon. In this example, the mask parameter is multiplied by four and the
result is displayed in the mask icon.

1. Right-click the block Icon Dependent on Mask Workspace > Mask > Edit Mask.

2. Create an edit parameter gain_val_param and set the initial value to 2.

3. In the Code pane, use this code to multiply the initial value of the mask parameter by 4.

function initialization()
final_gain_val = gain_val_param * 4;

end

4. In the Icon pane, use this code to display the value on the mask icon.

disp(['Final Gain Value: ',num2str(final_gain_val)])

Double-click the block Icon Dependent on Mask Workspace to view the block parameters. Enter
the value for the Gain Value parameter and click Ok to see the change in mask icon.

43-15
43 Working with Block Masks

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 Also

More About
• “Graphical Icon Editor Overview” on page 43-117
• “Author Block Masks”

43-16
Get Started with Mask Initialization and Callback Code

Get Started with Mask Initialization and Callback Code


Mask initialization enables you to define or modify parameters for the masked block. These
parameters can be used within the block diagram to configure the behavior of the underlying
subsystem. During the initialization phase, any code or scripts associated with the mask are executed.
This can include setting up variables, running MATLAB code, or initializing states that are necessary
for the subsystem to function correctly.

Mask initialization can include checks to ensure that the parameters provided by the user are valid.
This helps prevent simulation errors and ensures that the subsystem operates within the expected
parameters.

Mask initialization can be used to dynamically show or hide parameters based on other parameter
values. This can simplify the interface by only presenting relevant options to the user.

When you have a masked block that is used in multiple models, mask initialization ensures that all
instances of the block start with the same configuration, promoting consistency and reducing the
chance of errors.

When to Author Mask Initialization Code?


Author mask initialization code when you want to:

• Create new parameter or update an existing parameter in the mask based on the value of mask
dialog parameters. This new parameter can be used as the value of child block parameters.
• Modify the value of mask dialog parameters.
• Change the subsystem contents structurally or change the value of the child block parameters
based on the value of the mask dialog parameters. Use set_param command to do this.

When does Mask Initialization Code Execute?

Initialization commands for all masked blocks in a model run to retain the block in the right state. If
there is a change in the value of the block parameter, to retain a right state of the block and its
nested blocks the initialization commands execute. Initialization code executes in the following
scenarios:

• Change the mask parameter value and update the diagram or simulate or generate code.
• Change the value of the parameter and click Apply on mask dialog.
• Change the value of a parameter using set_param which in turn changes the parameter in the
mask dialog. Mask initialization code is executed when Simulink detects any change in the
parameter value.
• Save the mask using Save Mask in Mask Editor.
• Rotate or flip the masked block or draw, or redraw block icon in scenarios where the icon drawing
depends on initialization code. The initialization code executes only when the Run Initialization
property in the Mask Editor Icon pane is set.

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 of these visible masked blocks as well as their
parent block if they meet either of the following conditions:

43-17
43 Working with Block Masks

• 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 during model load.
• The masked subsystem belongs to a library and has the Allow library block to modify its
contents parameter enabled.

When you load a model into memory without displaying the model graphically, initialization
commands are not run for the masked blocks except for library blocks with self-modifiable mask. See
“Load a Model” on page 1-2 and load_system for information about loading a model without
displaying it.

The order of execution of initialization code is model InitFcn, block InitFcn, and then block mask
initialization.

Note The non-tunable parameters of a masked block are not evaluated if the model is already
compiled (initialized).

Mask Initialization Best Practices

Mask initialization commands must adhere to the following rules:

• Do not use initialization code to create dynamic mask dialog boxes (Dialog boxes whose
appearance or control settings change depending on changes made to other control settings).
Instead, use the mask callbacks. For more information, see “Dynamic Mask Dialog Box” on page
43-41.
• Do not use initialization code to add or delete blocks during loading the model.
• For nested masked subsystem, do not use set_param on a parent block from a child block. The
child block mask and the parent block mask both could be initializing the same parameter of the
block leading to unexpected behavior. For more information, see “Unsafe Mask Callback Error” on
page 43-155.
• Do not use set_param commands on blocks that reside in another masked subsystem that you
are initializing. Trying to set parameters of blocks in child level masked subsystems can trigger
unresolved symbol errors if child level masked subsystems reference symbols defined by parent
level masked subsystems.

Suppose, for example, a masked subsystem A contains a 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 this command:

set_param([gcb '/B/C'], 'SampleTime', '-1');

Simulating or updating a model containing A causes an unresolved symbol error.


• Do not use mask initialization code to create data objects. Data objects are objects of these
classes:

• Simulink.Parameter and subclasses


• Simulink.Signal and subclasses
• Do not add initialization code to delete the same masked block.

43-18
Get Started with Mask Initialization and Callback Code

• When you reference a block, or copy a block into a model, the mask dialog box displays the
specified default values. Do not use mask initialization code to change mask parameter default
values in a library block or any other block.
• Do not use mask initialization code to comment or uncomment a block.
• Avoid unconditionally modifying the contents of a subsystem from the mask initialization code.
Such unconditional modification does not work properly when using model reference.
• Avoid using clear commands for clearing variables in mask initialization code.
• Do not modify parameters at model level such as StartTime and
SolverJacobianMethodControl in mask initialization code section, as these parameters
cannot be modified once simulation starts.

Mask Callback Code


In Simulink, a mask callback is a function, or a script associated with a masked block that is executed
in response to certain actions or events.

Mask callbacks can be used to update other parameters dynamically based on the changes made to
one parameter. This helps in maintaining parameter relationships and dependencies.

Callbacks can control the visibility, enablement, and interactivity of parameters in the mask dialog,
allowing for a more responsive and user-friendly interface. Mask callbacks can automate tasks such
as updating display labels, setting block properties, or initializing states when a parameter is
changed.

Callbacks provide a way to interact with the MATLAB workspace, allowing you to read and write
variables to and from the mask parameters. Mask callbacks can be used to execute code at specific
points in the simulation process, such as before simulation starts or after it ends, to set up or clean
up resources.

When does Mask Callback Code Execute?

Mask parameter callback codes are executed in a temporary workspace and not in the base
workspace. If you need a variable created in the callback to be available later (not during callback
processing), you must explicitly assign those variables to the base workspace.

Simulink executes the callback commands when there is a change in the value of the parameter.
Parameter callbacks are executed in the following scenarios:

• Open mask dialog box and callback commands execute sequentially, starting with the top mask
dialog box.
• Modify a parameter value in the mask dialog box and then change the mouse or cursor location or,
press Apply. For example, you press the Tab key or click into another field in the dialog box after
changing the parameter value.
• Modify the parameter value by using the set_param command.
• Open the model with Edit Time Warnings and Errors in Diagnostics enabled.
• If you close a mask dialog box without saving the changes, the Callback command for parameters
is executed sequentially.
• If the callbacks have not run even once then they will run as part of model update.

Note

43-19
43 Working with Block Masks

• Buttons on mask dialog box are disabled when the callback code associated with the button is
being executed.
• Callback commands do not execute if the mask dialog box is open when the block tool tip appears.

See Also

More About
• “Author Mask Initialization and Callbacks” on page 43-21
• “Organize Mask Initialization and Callbacks in a MATLAB File” on page 43-156
• “Author Block Masks”
• “Masking Fundamentals” on page 43-3

43-20
Author Mask Initialization and Callbacks

Author Mask Initialization and Callbacks


You can write MATLAB code in the code pane of the Mask Editor for mask initialization and callbacks.
Mask initialization code enables you to modify the behavior of a block during block evaluation state.
You can initialize the mask or update the mask parameters of a block or its child block. For example,
you may want to create a new parameter based on the state of an existing block parameter and use
this new parameter in the child block.

Parameter callbacks and dialog control callbacks helps you to achieve different behaviors for the
block. The callback section typically consists of the actions to be performed on changing the value of
a parameter. For example, you may want to disable an edit parameter on clicking the checkbox
parameter on the mask dialog or you may want to populate a popup parameter with different option
on clicking the checkbox parameter on the mask dialog box.

By using a separate MATLAB class file you can:

• Use code debugging capabilities such as breakpoints in MATLAB Editor.


• Reduce the memory footprint of the masks since the callbacks are stored in a MATLAB class file
instead of in memory.
• Edit the mask callback code using either Mask Editor or MATLAB Editor.

You can author mask callback code and save it in a separate MATLAB class file or you can save the
callback within the mask itself.

To author a mask callback code on a masked block:

43-21
43 Working with Block Masks

1 Open Mask Editor and click Code pane.


2 Click New in the toolstrip and enter the Callback File Name to create a new MATLAB class file.
The default mode of authoring mask callbacks is using the MATLAB class file.
3 Click Browse to load an existing MATLAB class file. The MATLAB class file is created with a .m
extension. The name of the callback file and the name of the class that the function belongs to
must be the same. For example, if the name of the callback file is mask_cb_file_example then
the name of the class file must be mask_cb_file_example. The mask callback file must be
located in the MATLAB path.

Alternatively, if you want to save callbacks in mask, select Switch Callback Mode and click Mask.

How to Author Mask Initialization Code?


Mask initialization code in Simulink refers to the code that is executed when a masked block is
initialized during the simulation or when the model is loaded. Mask Initialization code enables you to
set initial parameter values or configure the block's behavior. The mask initialization function in the
mask callback file must be in the following format:

• The method in the callback file that executes the mask initialization code must be Static.
• Mask initialization function must be named as MaskInitialization.
• Input argument to the mask initialization function is a context structure with these properties:

• BlockHandle: Handle of the block.


• MaskObject: Mask object of the masked block. To know more about mask object, see “Control
Masks Programmatically” on page 43-32
• MaskWorkspace: Use this property to access the mask workspace. Simulink associates a
workspace with each masked block. Simulink stores the evaluated values of the block's mask
parameters in the workspace as well as any variables created by the block's mask initialization
code.

maskWorkspace = maskInitContext.MaskWorkspace;

• Use the set function to create or update a mask workspace variable. For example,
maskWorkspace.set('biasValue',0);. If biasValue is a mask workspace variable then
its value will be set to 0, otherwise a new variable biasValue is created in mask workspace
and its value will be set to 0.
• Use the get function to get the value of a mask workspace variable. For example,
enableBiasValue = maskWorkspace.get('EnableBias');. The value of EnableBias
is retrieved from the mask workspace.

Note The properties of the input argument of the initialization function are case sensitive.

function MaskInitialization(maskInitContext)
blkHandle = maskInitContext.BlockHandle; % Block Handle of this block
maskObj = maskInitContext.MaskObject; % Mask object of this masked block
maskWorkspace = maskInitContext.MaskWorkspace; % Use this to work with mask workspace
disp('Mask initialization triggered');
% Get value of 'EnableBias' parameter using mask workspace get() API.
enableBiasValue = maskWorkspace.get('EnableBias');
if ~enableBiasValue
% Set 'BiasValue' parameter value to 0 using mask workspace set() API.

43-22
Author Mask Initialization and Callbacks

maskWorkspace.set('biasValue',0);
end
end

How to Author Mask Parameter Callback Code?


Parameter callback code in Simulink refers to the code that is executed when a parameter value of a
masked block is changed. It allows you to perform custom actions based on parameter changes.
Parameter callback code in mask callback file must be in the following format:

• The function name of the parameter callback must be same as the parameter name.
• Input argument to the mask parameter callback function is a context structure with these
properties.

• BlockHandle: Block handle of the block.


• ParameterObject: Parameter object of a mask dialog parameter. The ParameterObject
contains the properties of the specific parameter. For example, the edit parameter object looks
like

MaskParameter with properties:

Type: 'edit'
TypeOptions: {0×1 cell}
Name: 'speed'
Prompt: ''
Value: '0'
ConstraintName: ''
Evaluate: 'on'
Tunable: 'on'
NeverSave: 'off'
Hidden: 'off'
ReadOnly: 'off'
Enabled: 'on'
Visible: 'on'
ShowTooltip: 'on'
Callback: ''
Alias: ''
VariableName: ''
DialogControl: [1×1 Simulink.dialog.parameter.Edit]

Note Parameter callback code does not have access to mask workspace.

function EnableBias(callbackContext)
blkHandle = callbackContext.BlockHandle; % Block Handle of this block
maskObj = Simulink.Mask.get(blkHandle);
parameterObj = callbackContext.ParameterObject; % Parameter object for 'EnableBias'.
disp('EnableBias callback triggered');
% Set the 'Enabled' property for each parameter
if strcmp(get_param(blkHandle,'EnableBias'),'on')
maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
else

43-23
43 Working with Block Masks

maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'off';
end
end

Write Mask Dialog Control Callback


The dialog control callback in Simulink refers to the code that is executed when a specific action or
event occurs on a dialog control element of a masked block. It allows you to customize the behavior of
the dialog controls and perform actions based on user interactions. The dialog control callback must
be in the following format:

• The function name for the control callback must be same as the name of the dialog control.
• Input argument to the mask control callback function is a struct with these properties.

• BlockHandle: Block handle of the block.


• DialogControlObject: Dialog control object of the dialog control. The
DialogControlObject contains the properties of the specific dialog control. For example,
the button object looks like

Button with properties:

Name: 'Enable'
Prompt: ''
Callback: ''
FilePath: ''
Row: 'new'
Enabled: 'on'
Visible: 'on'
HorizontalStretch: 'on'
Tooltip: ''

function ResetVisibility(callbackContext)
blkHandle = callbackContext.BlockHandle; % Block Handle of this block
maskObj = Simulink.Mask.get(blkHandle);
resetButtonObj = callbackContext.DialogControlObject; % Dialog Control object for 'ResetVisib
disp('ResetVisibility button callback triggered');
% Reset mask enables.
maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
end

Migrate Existing Callback Code to MATLAB File


You can migrate existing callback code stored in mask to a MATLAB class file. Inspect the mask
initialization code and make corrections before executing it. For example, you must modify the code
to create, modify, or retrieve the values of parameters or variables from the mask workspace in the
mask initialization section using the mask workspace methods set and get.

To migrate the existing callback code, right-click the masked block, from the context menu select
Mask > Edit Mask. In the Code tab, click Switch Callback Mode and select Callback File.

43-24
Author Mask Initialization and Callbacks

In the dialog box, click Yes to migrate the existing callback and save. Click No, to save mask
callbacks in a separate MATLAB file and without migrating the code. Save the mask to save the
callback file.

Note If you want to store the mask callback in the mask object rather than in a separate MATLAB
file, go to Mask Editor, click Code > Switch Callback Mode > select Mask.

Create or Update Mask Workspace Variables


After migrating the existing mask callback to the MATLAB class file mode, you will have to inspect
the mask initialization code and make corrections before executing it. For example, you must modify
the code to set and get values of variables from the mask workspace in the mask initialization section
using the mask workspace methods set and get.

• Use the set function to create or update a mask workspace variable. For example,
maskWorkspace.set('biasValue',0);. If biasValue is a mask workspace variable then its
value will be set to 0, otherwise a new variable biasValue is created in mask workspace and its
value will be set to 0.
• Use the get function to get the value of a mask workspace variable. For example,
enableBiasValue = maskWorkspace.get('EnableBias');. The value of EnableBias is
retrieved from the mask workspace.

43-25
43 Working with Block Masks

Save Callback File with the Model


You can also package the callback file along with the model. Use the option Save callback file with
model in the toolstrip. You must also save the model to package the callback file along with the
model.

Note To edit the callback file saved with the model, you must load the model. Use the Open option in
the toolstrip to open the callback file in MATLAB editor.

See Also
“Mask Callback Code” on page 43-12 | “Get Started with Mask Initialization and Callback Code” on
page 43-17

Related Examples
• “Organize Mask Initialization and Callbacks in a MATLAB File” on page 43-156

43-26
Promote Block Parameters on a Mask

Promote Block Parameters on a Mask

Blocks and subsystems can have multiple parameters associated with them. Block masks allow you to
expose one or more of these parameters while hiding others from view. You can promote any
underlying parameter of a block either to a block mask or to a subsystem mask. For any subsystem,
you have a single view of all the nested blocks, the block parameters, and internal parameters. You
can click on any node to access any promotable parameter within the nested blocks. By promoting
parameters from the block dialog box to the mask you can:

• Customize the mask dialog box by moving the required parameters from the block dialog box to
the mask dialog box.

• Reuse a library block at different instances of a model. For each instance of the library block, you
can create individual mask dialog box by promoting parameters for each block.

• Simplify the interface and specify the parameters that the user of the block can view and set.

These options are available for promoting parameters:

Promote One-to-One: Use this option on the Mask Editor for one-to-one correspondence between
the block parameter and the mask parameter. For each block parameter, one mask parameter is
created. For example, consider the block dialog box of the Gain block, which has parameters such as
Gain, Multiplication. To expose only the Gain parameter, mask the Gain block and promote the
Gain parameter to the mask dialog box.

Promote Many-to-One: Use this option to create a many-to-one correspondence between the block
parameter and the mask parameter. You can associate a single mask parameter with multiple
promoted parameters For example, you can promote multiple Gain parameters in a subsystem to a
single parameter on your mask.

Note:

• If the parameter is of data type popup or DataType, the options must also be the same for the
parameters to be promoted.

• The Evaluate attribute must be the same for all the promoted parameters.

• You can also change the attributes of a promoted parameter. For example, you can make a
promoted parameter read-only or hidden. For more information on attributes, see “Property
editor”.

Explore the Model

The model contains two subsystem blocks: one for promoting on-to-one parameters, Selective
Promotion of Parameters and one for promoting many to one parameters, Promote Many to
One.

open_system('slexMaskParameterPromotionExample.slx');

43-27
43 Working with Block Masks

Promote One-to-One

You can create an one-to-one correspondence for each underlying block parameters and the mask
parameter.

Consider the model containing the subsystem Selective Promotion of Parameters, which
contains three Gain blocks. The value of one of the Gain blocks is fixed. To simplify the user
interface, the parameters of the variable Gain blocks are promoted to the mask.

To promote the parameters:

1. Go to Mask Editor > Parameters & Dialog > Parameter > Promote One-to-One.

2. Select the variable Gain parameters Gain and Gain1, then click Promote.

43-28
Promote Block Parameters on a Mask

Note: You can modify the prompt of the promoted parameter.

3. Save the mask and simulate the model. Note that the value of the Gain1 block is taken from the
mask parameter gain1_promoted.

4. Simulate the model. Notice that the value of the Gain3 block is fixed and set in the
initialization. The variable Gain parameters appear in the mask dialog box.

Promote Many-to-One

Use the option Promote-Many-to-One in the Mask Editor to promote multiple block parameters to a
single mask parameter. For example, this model contains a subsystem named Promote Many to
One that has three Gain blocks ( Gain1, Gain2, and Gain3 ). The variable K represents the Gain
parameter for these Gain blocks. You can promote only the Gain parameter of each of these Gain
blocks to the block mask as a single parameter. When you do so, the parameter K is available on the
mask for editing, and its value will be applied to Gain1, Gain2, and Gain3 blocks.

43-29
43 Working with Block Masks

1. Go to Mask Editor > Parameters & Dialog > Promote-Many-to-One.

2. Select the Gain parameters Gain1, Gain2, and Gain3.

3. Click Promote.

4. Simulate the model. Notice that the value 4 is passed from the mask to the underlying blocks
Gain1, Gain2 , and Gain3 . In this case, the output shows 64.

Best Practices

• Set the value of a promoted parameter only in the mask dialog box and not in the underlying block
dialog box or from the command line.

• Parameters once promoted cannot be promoted again to any other mask.

• Do not edit the Evaluate attribute of the promoted parameter. This property is inherited from the
block parameter.

43-30
Promote Block Parameters on a Mask

• If you are promoting a nontunable parameter, do not edit the Tunable attribute.

• Parameters of a masked or linked child block cannot be viewed or promoted.

• Callbacks associated with a block parameter are promoted to the block mask and not to the
subsystem mask. User-defined callbacks are sequentially executed after the dynamic dialog
callback execute.

43-31
43 Working with Block Masks

Control Masks Programmatically

Simulink® defines a set of parameters that help in setting and editing masks. To set and edit a mask
from the MATLAB® command line, you can use Simulink.Mask and Simulink.MaskParameter
class methods. You can also use the get_param and set_param functions to set and edit masks.
However, since these functions use delimiters that do not support Unicode® (Non-English)
characters it is recommended that you use methods of the Simulink.Mask and
Simulink.MaskParameter class methods to control masks.

Use Simulink.Mask and Simulink.MaskParameter

Use methods of Simulink.Mask and Simulink.MaskParameter classes 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 Simulink.Mask.create method is used to create a block mask:

new_system('mask_example');
add_block('built-in/subsystem','mask_example/subsystem');
save_system;
open_system('mask_example');
maskObj = Simulink.Mask.create(gcb);

In this example, the mask object is assigned to variable maskObj using the Simulink.Mask.get
method:

maskObj = Simulink.Mask.get(gcb);
maskObj

maskObj =
Mask with properties:

Type: ''
Description: ''
Help: ''
Initialization: ''
SelfModifiable: 'off'
BlockDVGIcon: ''
Display: ''
SaveImageFileWithModel: 'off'
IconFrame: 'on'
IconOpaque: 'opaque'
RunInitForIconRedraw: 'analyze'
IconRotate: 'none'
PortRotate: 'default'
IconUnits: 'autoscale'
SaveCallbackFileWithModel: 'off'
CallbackFile: ''
ParameterConstraints: [0x0 Simulink.Mask.Constraints]
PortConstraints: [0x0 Simulink.Mask.PortConstraint]
Parameters: [0x0 Simulink.MaskParameter]

43-32
Control Masks Programmatically

PortIdentifiers: [0x0 Simulink.Mask.PortIdentifier]


CrossParameterConstraints: [0x0 Simulink.Mask.CrossParameterConstraints]
CrossPortConstraints: [0x0 Simulink.Mask.CrossPortConstraint]
BaseMask: [0x0 Simulink.Mask]

For examples of other mask operations, like creating and editing mask parameters and copying and
deleting masks, see Simulink.Mask and Simulink.MaskParameter.

Use get_param and set_param

The set_param and get_param functions have parameters for setting and controlling the mask. You
can use these functions to set the mask of any block in the model or library based on a value passed
from the MATLAB command line:
set_param(gcb,'MaskStyleString','edit,edit',...
'MaskVariables','maskparameter1=@1;maskparameter2=&2;',...
'MaskPromptString','Mask Parameter 1:|Mask Parameter 2:',...
'MaskValues',{'1','2'});
get_param(gcb,'MaskStyleString');
set_param(gcb,'MaskStyles',{'edit','edit'},'MaskVariables',...
'maskparameter1=@1;maskparameter2=&2;','MaskPrompts',...
{'Mask Parameter 1:','Mask Parameter 2:'},...
'MaskValueString','1|2');
get_param(gcb,'MaskStyles');

where

• | separates individual character vector values for the mask parameters.


• @ indicates that the parameter field is evaluated.
• & indicates that the parameter field is not evaluated but assigned as a character vector.

Note

• When you use get_param to get the Value of a mask parameter, Simulink returns the value that
was last applied using the mask dialog. Values that you have entered into the mask dialog box but
not applied are not reflected when you use the get_param command.
• To specify the value of a mask parameter programmatically, it is recommended to use set_param
command on the mask parameter instead of using set_param on MaskValues.

To control the mask properties programmatically for a release before R2014a, see “Mask
Parameters”.

Restrictions Using set_param and Mask Object APIs on Linked Blocks

Simulink imposes certain constraints while modifying the mask parameters using set_param and
mask object APIs on linked blocks. On a non-self-modifiable linked block, you can change the
properties of a mask parameter such as Value, Visible, and Enable. On a self-modifiable linked
block, you can change few other properties in addition to Value, Visible, and Enable.

Programmatically Create Mask Parameters and Dialogs

This example shows how to create this simple mask dialog, add controls to the dialog, and change the
properties of the controls.

Step 1: Create the mask for a block you selected in the model.

43-33
43 Working with Block Masks

Step 2: To customize the dialog and to use tabs instead of the default group, remove the Parameters
group box.
maskObj.removeDialogControl('ParameterGroupVar');
open_system('mask_example/subsystem');

Simulink preserves the child dialog controls–the two check boxes in this example–even when you
delete the ParametersGroupVar group surrounding them. These controls are parameters that
cannot be deleted using dialog control methods.

You can delete parameters using methods such as Simulink.Mask.removeAllParameters, which


belongs to the Simulink.Mask class.

Step 3: Create a tab container and get its handle.


tabgroup = maskObj.addDialogControl('tabcontainer','tabgroup');

Step 4: Create tabs within this tab container.


tab1 = tabgroup.addDialogControl('tab','tab1');
tab1.Prompt = 'First';
maskObj.addParameter('Type','checkbox','Prompt','Option 1',...
'Name','option1','Container','tab1');
maskObj.addParameter('Type','checkbox','Prompt','Option 2',...
'Name','option2','Container','tab1');
tab2 = tabgroup.addDialogControl('tab', 'tab2');
tab2.Prompt = 'Second';
tab3 = tabgroup.addDialogControl('tab','tab3');
tab3.Prompt = 'Third (invisible)';

Make the third tab invisible.


tab3.Visible = 'off';
tab3

tab3 =
Tab with properties:

Name: 'tab3'
Prompt: 'Third (invisible)'
Enabled: 'on'
Visible: 'off'
AlignPrompts: 'off'
DialogControls: [0x0 Simulink.dialog.Control]

You can change the location and other properties of the parameters on the dialog by using the
Simulink.dialog.Control commands.

For example, to change the dialog layout options, consider a Gain block with a Popup parameter
named Parameter2 added. To set the dialog layout options of the parameter, you can use an instance
of Simulink.dialog.parameter.Popup class. The following code shows how to set the prompt
location in dialog layout:
add_block('built-in/gain','mask_example/gain2');
maskobj = Simulink.Mask.create(gcb);
set_param(gcb,'MaskStyleString','popup',...
'MaskVariables','maskparameter2=&2;',...

43-34
Control Masks Programmatically

'MaskPromptString','Mask Parameter 2:');


a = Simulink.Mask.get('mask_example/gain2');
d = a.Parameters(1).DialogControl;
d

d =
Popup with properties:

Name: 'Parameter1'
PromptLocation: 'left'
Row: 'new'
HorizontalStretch: 'on'
Tooltip: ''

Now, to set the PromptLocationproperty, use the command:

d.PromptLocation = 'left';

This sets the PromptLocationas 'left'. The available values are 'left' and 'top'. The output
confirms the change of the PromptLocationproperty value to left:

d =
Popup with properties:

Name: 'Parameter1'
PromptLocation: 'left'
Row: 'new'
HorizontalStretch: 'on'
Tooltip: ''

save_system;

For more information on dialog controls and their properties, see Simulink.dialog.Control.

See Also

More About
• “Author Block Masks”
• “Masking Fundamentals” on page 43-3
• “Get Started with Mask Initialization and Callback Code” on page 43-17

43-35
43 Working with Block Masks

Pass Values to Blocks Under the Mask


A masked block can pass values to the block parameters under the mask. The underlying blocks use
the passed values during simulation to execute the block logic.

A masked block has variables associated with mask parameters. These variables are stored in the
mask workspace for a model and can correspond to a block parameter under the mask. When such a
block is evaluated, the block variables look for matching values in the mask workspace to get a value.

The mapping of variables from the mask workspace to the base workspace must be correct. A correct
mapping ensures that the right block variable is assigned the value that is passed from the mask.

Use any of these options to pass values to blocks under the mask:

• Parameter promotion (recommended)


• Mask initialization
• Referencing block parameters using variable names (For the Edit Parameter only)

Parameter Promotion
When you promote a block parameter to its mask, the block parameter becomes accessible from the
mask dialog box, allowing you to pass a value for the block parameter. Parameter promotion ensures
correct mapping of parameter values and is a recommended way to pass values to the block from the
mask dialog box. Note that, when you promote parameters of an in-built block, the internal callbacks
associated with these parameters are also inherited in the new parameter. For more information on
promoting a parameter, see “Promote Block Parameters on a Mask” on page 43-27.

Mask Initialization
You can use MATLAB code in the Initialization pane of the Mask Editor to assign or pass values to the
block parameters under the mask. You can assign a fixed value to a block parameter, specify an
acceptable range for the input values, or specify a value for the child block. For more information, see
“Get Started with Mask Initialization and Callback Code” on page 43-17.

Referencing Block Parameters Using Variable Names


You can add an Edit parameter to the mask dialog box and pass values to the block parameters
through it. The values that you provide for the Edit parameter in the mask dialog box automatically
becomes associated with the block parameter, by using the techniques described in “Symbol
Resolution” on page 73-151.

Consider the model, which contains a masked Subsystem block and governs the equation y = mx +
b. Here, m and b are variables controlling the slope and intercept of the equation and are associated
with the Gain and the Constant block, respectively.

43-36
Pass Values to Blocks Under the Mask

The variables m and b are assigned to the mask parameters Slope and Intercept, respectively, as
parameter names in the Mask Editor.

When you type values for Slope and Intercept in the mask dialog box, these values are internally
assigned to the variables m and b. When the model is simulated, the Gain block and the Constant
block search for numeric values of m and b and apply them to resolve the equation y = mx + b.

See Also

More About
• “Author Block Masks”
• “Masking Fundamentals” on page 43-3
• Creating a Mask: Masking Fundamentals (3 min, 46 sec)

43-37
43 Working with Block Masks

Mask Linked Blocks


In this section...
“Guidelines for Mask Parameters” on page 43-39
“Mask Behavior for Masked, Linked Blocks” on page 43-39
“Mask a Linked Block” on page 43-40

Simulink libraries can contain blocks that have masks. An example of this type of block is the Ramp
block. These blocks become library links when copied to a model or another library. You can add a
mask on this linked block. If this linked block is in a library and copied again, you can add another
mask to this new linked block thus creating a stack of masks. Masking linked blocks allows you to add
a custom interface to the link blocks similar to other Simulink blocks.

You can also apply a mask to a block, then include the block in a library. Masking a block that is later
included in a library requires no special provisions. For more information, see “Create Custom
Library” on page 45-2.

The block mask that is present as part of the library is the base mask. A derived mask is the one
created on top of the base mask.

For example, in the figure, Library A contains Block A, which has a Mask A. Block A is copied to
Library B, and Mask B is added to it. When Block A is copied to Library B, a library link from Library
B to Library A is created.

Block B is then copied to a model, and Mask C is added to it. This creates a library link from Block C
to Library B. Block C now has Mask A, Mask B, and Mask C. Mask C is the derived mask and Mask B
is the base mask.

For Block C:

• Mask parameter names are unique in the stack.


• You can set mask parameters for Mask B and Mask C.

43-38
Mask Linked Blocks

• Mask B and Mask C inherit MaskType and MaskSelfModifiable parameters from Mask A.
• Mask initialization code for Mask C executes first, followed by Mask B and Mask A.
• Variables are resolved starting from the mask immediately above the current mask in the stack. If
the current mask is the top mask, it follows the regular variable resolution rules.

Creating or changing a library block mask 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 exist as separate
copies.

To view related example, see “Dynamic Masked Subsystem” on page 43-45.

Guidelines for Mask Parameters


• You cannot use same names for the mask parameters. The exception is the Promote type mask
parameter, for which the name is inherited and is the same as that of the parameter promoted to
it.
• You cannot set mask parameters for masks below the base mask. Mask parameters for masks
below the base mask are inherited from the library.

Mask Behavior for Masked, Linked Blocks


The following are some of the behaviors that are important to understand about masked, linked
blocks.

• The MaskType and the MaskSelfModifiable parameters are inherited from the base mask.
• The mask display code for the derived mask executes first, followed by the display code for the
masks below it until we come across a mask whose MaskIconFrame parameter is set to opaque.
• The mask initialization code for the derived mask executes first, followed by the initialization code
for the masks below it.
• Variables are resolved starting from the mask immediately above the current mask in the stack. If
the current mask is the top mask, the regular variable resolution rules apply.
• When you save a Simulink model or library containing a block with multiple masks, using Save >
Export Model to > Previous Version on the Simulation tab, the Sourceblock parameter is
modified to point to the library block having the bottom-most mask.
• The following occurs when you disable, break, or reestablish links to libraries:

• If you disable the link to the library block, the entire mask hierarchy is saved to the model file
so that the block can act as a standalone block.
• If you break the link to the library block, the block becomes a standalone block.
• If you reestablish the link after disabling by doing a restore, all changes to the mask are
discarded. If you mask subsystems, you must reestablish the link after disabling by doing a
push. When you do a push, subsystem changes are pushed to the library block and top mask
changes are pushed to the immediate library.

43-39
43 Working with Block Masks

Mask a Linked Block


Step 1: Create Custom Library with Masked Linked Block

1
In the Simulink Library Browser, click the arrow next to and select New Library.
2 Open the Ramp block in the Library editor window.
3 Select the Ramp block and on the Block tab, in the Mask group, click Create Mask.

The Mask Editor opens.


4 In the Icons pane, type:

plot ([0:10],[0,1:10])
5
In the Parameter & Dialog pane, select Promote to promote the Slope and Initial
Output parameters.
6 Click OK.
7 Rename the block to Derived Ramp block.

Step 2: Add a Mask to the Masked, Link Block

1
In the Simulink Library Browser, click the arrow next to and select New Model. The
Model editor window opens.
2 Drag the Derived Ramp block from the Library editor to the Model editor.

The Derived Ramp block in the model has multiple masks on it. You can set parameters of the
derived mask.

Step 3: View Masks Below the Top Mask

• Right-click the Derived Ramp block in the model and select Mask > View Base Mask. This
opens the Mask Editor displaying the base mask definition.

See Also

More About
• “Author Block Masks”
• “Linked Blocks” on page 45-12

43-40
Dynamic Mask Dialog Box

Dynamic Mask Dialog Box

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.

Note: Mask parameter addition, deletion, or modification is restricted from mask callback.

Creating a dynamic masked dialog box entails using the Mask Editor 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. The callback function can in turn use the set_param command to set
mask parameters that affect the appearance and settings of other controls on the dialog box. Finally,
you save the model or library containing the masked subsystem to complete the creation of the
dynamic masked dialog box.

Explore the Model

This example has two subsystem blocks Making a Parameter Invisible and Disabling a
Parameter to change the visibility of the mask parameter and disable the mask parameter.

open_system("slexMaskDDGExample.slx");

43-41
43 Working with Block Masks

Change the Visibility of a Mask Parameter

The subsystem block Making a Parameter Invisible is referenced to explain in this section.
This example shows how to change the visibility of one mask parameter based on the value of another
mask parameter. The value of Enable Bias is set by selecting or clearing the Enable Bias check box. It
is used to change the visibility of the Bias Value parameter.

To change the visibility of the mask parameter:

1. Create two edit parameters Gain Value and Bias. Create a check box parameter Enable Bias.

2. Use this code in the Initialization section of the Code pane.

function initialization()
%In the Initialization command, the variable 'enableBias' corresponding to
the checkbox returns the following values:

unchecked = 0
checked = 1

% If the box is unchecked, we set the bias value to zero

43-42
Dynamic Mask Dialog Box

if ~enableBias
biasValue = 0;
end
% Othewise, the value from the mask parameter is used
end

3. Use this code in the parameter callback section for enableBias.

function enableBias_callback()
% Control parameter visiblity. Get the value of the Enable Bias checkbox
% unchecked = 'off'
% checked = 'on'
enab = get_param(gcb,'enableBias');

% Set the 'MaskVisibilities' property for each parameters


if strcmp(enab,'on')
set_param(gcb,'MaskVisibilities',{'on','on','on'});
else
set_param(gcb,'MaskVisibilities',{'on','on','off'});
end

% Note that the value of the bias is not handled here.


% See the Initialization tab

end

4. Double-click the subsystem block Making a Parameter Invisible. Uncheck the Enable
Bias parameter and notice that the Bias parameter is invisible.

Disable a Mask Parameter

The subsystem block Disabling a Parameter is referenced in this example. This example shows
how to disable a mask parameter based on the value of another mask parameter. The checkbox
Enable Bias is used to disable the Bias Value parameter, which is grayed out.

To disable a mask parameter:

1. Create two edit parameters Gain Value and Bias. Create a check box parameter Enable Bias.

2. Use this code in the Initialization section of the Code pane.

function initialization()
% In the Initialization command, the variable 'enableBias' corresponding to
% the checkbox returns the following values:
% unchecked = 0
% checked = 1

If the box is unchecked, we set the bias value to zero


if ~enableBias
biasValue = 0;
end
% Othewise, the value from the mask parameter is used
end

43-43
43 Working with Block Masks

3. Use this code in the parameter callback section for enableBias.

function enableBias_callback()
% Enable and disable parameters
% Get the value of the Enable Bias checkbox
% unchecked = 'off'
% checked = 'on'
enab = get_param(gcb,'enableBias');
Set the 'MaskEnables' property for each parameters
if strcmp(enab,'on')
set_param(gcb,'MaskEnables',{'on','on','on'});
else
set_param(gcb,'MaskEnables',{'on','on','off'});
end
% Note that the value of the bias is not handled here.
% See the Initialization tab
end

4. Double-click the subsystem block Disabling a Parameter. Uncheck the Enable Bias
parameter and notice that the Bias parameter is grayed.

See Also

“Dynamic Masked Subsystem” on page 43-45|

43-44
Dynamic Masked Subsystem

Dynamic Masked Subsystem

Create masked library blocks that can modify their structural contents.

Allow Library Block to Modify Its Contents

The option Allow mask initialization code to modify the subsystem's content 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). To set this option at the MATLAB® prompt,
select the self-modifying block and enter the following command and then save the block.
set_param(gcb, 'MaskSelfModifiable', 'on');

open_system("slexMaskSelfModifiableExample.slx")

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

Simulink® runs the mask-initialization code for a self-modifiable library block when you load the
block.

Creating Self-Modifying Masks Using the Mask Editor

To create a self-modifying mask using the Mask Editor:

43-45
43 Working with Block Masks

1. Unlock the library. See “Lock and Unlock Libraries” on page 45-6

2. Select the block in the library.

3. On the Block tab, in the Mask group, click Edit Mask. The Mask Editor opens.

4. In the Mask Editor Code pane, select the Allow mask initialization code to modify the
subsystem's content option.

5. Enter the code that modifies the masked subsystem in the mask Initialization pane.

Do not enter code that structurally modifies the masked subsystem in a dialog parameter callback,
see “When does Mask Callback Code Execute?” on page 43-19. Doing so triggers an error when you
edit the parameter.

6. Click Apply to apply the change or Ok to apply the change and close 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.

Create Self-Modifying Mask

In this example if you change the Time domain on the mask dialog box, the block within the
Subsystem is replaced accordingly. For example, if you select the Time domain as Discrete, the
Integrator block is replaced with a Discrete-Time Integrator block and vise-versa.

43-46
Dynamic Masked Subsystem

1. In the Library window, on the Library tab, click Locked Library to unlock the library.

2. On the Subsystem Block tab, in the Mask group, click Edit Mask. The Mask Editor opens.

3. The Mask Editor Parameters & Dialog pane defines a parameter Time domain that stores the
value for the time option. This mask dialog box callback replaces the Integrator block with a
Discrete-Time Integrator block and vise-versa.

4. To allow the dialog box callback to function properly, the Allow mask initialization code to
modify the subsystem's content option on the Mask Editor Code pane is selected. If this option is
not selected, copy of the library block could not modify their structural contents. Also, changing the
selection in the Time Domain list would produce an error.

43-47
43 Working with Block Masks

See Also

More About
• “Author Block Masks”
• “Create a Simple Mask” on page 43-7
• “Get Started with Mask Initialization and Callback Code” on page 43-17
• “Mask Linked Blocks” on page 43-38

43-48
Debug Masks That Use MATLAB Code

Debug Masks That Use MATLAB Code


In this section...
“Code Written in Mask Editor” on page 43-49
“Code Written Using MATLAB Editor/Debugger” on page 43-49

Code Written in Mask Editor


Debug initialization commands and parameter callbacks entered directly into the Mask Editor by:

• Removing the terminating semicolon from a command to echo its results to the MATLAB
Command Window.
• Placing a keyboard command in the code to stop execution and give control to the keyboard.

Tip To stop debugging the mask initialization callback code when an error is encountered, use the
command dbstop if caught error.

Code Written Using MATLAB Editor/Debugger

Note You cannot debug icon drawing commands using the MATLAB Editor/Debugger. For
information on icon drawing commands syntax, see “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.

See Also

More About
• “Get Started with Mask Initialization and Callback Code” on page 43-17
• “Mask Callback Code” on page 43-12

43-49
43 Working with Block Masks

Introduction to System Mask


A system mask can be applied to a model or a subsystem block diagram. A model consists of multiple
blocks, with each block containing its own parameter and block dialog box.

The advantages of using a system mask are:

1 A system mask allows you to customize the appearance and behavior of a block to specific
requirements or modeling scenarios.
2 Enable the parameterization of Simulink blocks by exposing key parameters through the mask
interface.
3 Enhance the reusability of Simulink blocks by encapsulating custom functionality and parameters
within a system mask. You can create blocks with predefined behaviors that can be easily reused
in different models or projects. This reusability not only saves time but also promotes consistency
and standardization across different simulations.

When you reference a masked model from a Model block, a mask is generated automatically on the
Model block. The generated mask on the Model block is a copy of the model mask that it is
referencing. You can reference a masked model from multiple Model block instances.

Consider a model that represents the DC motor equation. Plant in this model is a Model block that
references a masked model, simplifying the user interface.

The Plant block contains the same mask as that of the masked model and the mask is uneditable.
The mask can only be edited from the Mask Editor dialog box of the masked model.

Limitations

Mask initialization code is not supported for system mask on a model. This is to prevent any direct
modification of the referenced model from the model reference block.

See Also

More About
• “Create and Reference a Masked Model” on page 43-52
• “Create and Display System Mask Programmatically” on page 43-56
• “Add a System Mask to a Subsystem File” on page 4-49

43-50
Introduction to System Mask

• “Masking Fundamentals” on page 43-3

43-51
43 Working with Block Masks

Create and Reference a Masked Model


This example shows how to mask a model and reference the masked model from the Model block.

Step 1: Define Mask Arguments


1 Open the model in Simulink. For example, consider a simple model containing two Gain blocks, a
Constant block, and a Display block.

2 On the Modeling tab, under Design, click Model Explorer > Model Workspace.
3 Click Add > MATLAB Variable. A variable of data type double is created in the Model
Workspace.
4 Select the Argument check box corresponding to the MATLAB variables to make it a model
argument, for example, k and l.

Step 2: Create Model Mask


1 In the Model Workspace pane, click Create System Mask.

Alternatively, in Simulink, on the Modeling tab, under Component, click Create Model Mask,
or right-click the model, and select Mask > Create System Mask.

The Mask Editor dialog box opens.

43-52
Create and Reference a Masked Model

2 Click the Parameters & Dialog tab. The model arguments that you select in Model Explorer
appear in the Mask Editor dialog box as mask parameters.

Tip Ensure that the model arguments you have selected in the Model Explorer dialog box are
added as block parameters in the model. For example, the arguments k and l are passed to Gain
A and Gain B blocks, respectively.

3 Select a mask parameter (k or l) on the Dialog box pane and edit its properties in the Property
editor, as required. For example, you can change the prompt name, parameter type, value, or
orientation.

By default, the Edit parameter type is assigned to a model mask parameter. You can change the
parameter type by editing the Type property in the Property editor section.

Note

• Simulink supports only the Edit, Slider, Dial, and Spinbox parameter types for system mask.
• Simulink does not support non tunable parameters for system mask.
• System mask supports all types of display and action controls.

4 Click OK. The Simulink model is now masked and contains the model arguments as the mask
parameter.

43-53
43 Working with Block Masks

5 Save the model.

Step 3: View System Mask Parameters


1 To view the mask parameter dialog box, on the Component tab, under System Mask, click
Mask Parameters.

Tip To edit the system mask parameters, on the Component tab, under System Mask, click
Edit System Mask.
2 Save the masked model.

Step 4: Reference Masked Model


1 Open a blank model in Simulink and add the Model block from the library.
2 To reference the masked model from the Model block, specify the name of the masked model as
the Model name in the Block parameter dialog box.

3 To view the parameter dialog box of the referenced model, right-click the Model block, and in the
context menu, click Mask > Mask Parameters. Alternatively, double-click the Model block.
4 Type 2 and 3 as the parameter values for k and l respectively.

43-54
Create and Reference a Masked Model

5 Click OK.
6 Simulate the model and view the result on the display block.
7 To view the referenced model from the Model block, click Mask > Look Under Mask.
8 To view the mask, select the Model block and click Mask > View Mask. The Mask Editor dialog
box opens. The Mask Editor dialog box displays the uneditable mask parameters of the
referenced model.

See Also

More About
• “Introduction to System Mask” on page 43-50
• “Create and Display System Mask Programmatically” on page 43-56
• “Masking Fundamentals” on page 43-3

43-55
43 Working with Block Masks

Create and Display System Mask Programmatically

You can apply a system mask to a model or a subsystem block diagram. By masking a model, you
encapsulate the model to have its own customizable mask parameter dialog box. When you mask a
model, the model arguments become the mask parameters. Referencing a masked model results in a
better user interface for a model by controlling the model parameters through the mask.

This example shows how to create and display system mask programmatically.

Create System Mask

Use the function Simulink.Mask.Create to create a mask on a subsystem.

new_system('sysmask');
save_system;
maskObj = Simulink.Mask.create('sysmask')

maskObj =
Mask with properties:

Type: 'sysmask'
Description: ''
Help: ''
Initialization: ''
SelfModifiable: 'off'
BlockDVGIcon: ''
Display: ''
SaveImageFileWithModel: 'off'
IconFrame: 'on'
IconOpaque: 'opaque'
RunInitForIconRedraw: 'analyze'
IconRotate: 'none'
PortRotate: 'default'
IconUnits: 'autoscale'
SaveCallbackFileWithModel: 'off'
CallbackFile: ''
ParameterConstraints: [0x0 Simulink.Mask.Constraints]
PortConstraints: [0x0 Simulink.Mask.PortConstraint]
Parameters: [0x0 Simulink.MaskParameter]
PortIdentifiers: [0x0 Simulink.Mask.PortIdentifier]
CrossParameterConstraints: [0x0 Simulink.Mask.CrossParameterConstraints]
CrossPortConstraints: [0x0 Simulink.Mask.CrossPortConstraint]
BaseMask: [0x0 Simulink.Mask]

Display System Mask

Get the mask for the model sysmask and store it in maskObj.

maskObj = Simulink.Mask.get('sysmask')

maskObj =
Mask with properties:

Type: 'sysmask'
Description: ''

43-56
Create and Display System Mask Programmatically

Help: ''
Initialization: ''
SelfModifiable: 'off'
BlockDVGIcon: ''
Display: ''
SaveImageFileWithModel: 'off'
IconFrame: 'on'
IconOpaque: 'opaque'
RunInitForIconRedraw: 'analyze'
IconRotate: 'none'
PortRotate: 'default'
IconUnits: 'autoscale'
SaveCallbackFileWithModel: 'off'
CallbackFile: ''
ParameterConstraints: [0x0 Simulink.Mask.Constraints]
PortConstraints: [0x0 Simulink.Mask.PortConstraint]
Parameters: [0x0 Simulink.MaskParameter]
PortIdentifiers: [0x0 Simulink.Mask.PortIdentifier]
CrossParameterConstraints: [0x0 Simulink.Mask.CrossParameterConstraints]
CrossPortConstraints: [0x0 Simulink.Mask.CrossPortConstraint]
BaseMask: [0x0 Simulink.Mask]

Note:

To get the model mask as a mask object in the mask callback, you can use Simulink.Mask.get
without passing a system name or system handle.

See Also

More About
• “Create and Reference a Masked Model” on page 43-52
• “Introduction to System Mask” on page 43-50
• “Masking Fundamentals” on page 43-3

43-57
43 Working with Block Masks

Handling Large Number of Mask Parameters


The Table control in Mask Editor dialog box allows you to organize large number of mask
parameters. The Table control can handle large (500+) number of mask parameters. You can include
Edit, Checkbox, and Popup parameters within a Table.

You can also add large number of mask parameters in a Table programmatically. An example follows,
% Get mask object.
aMaskObj = Simulink.Mask.get(gcbh);

% Add Table controls to the mask.


aMaskObj.addDialogControl('Table', 'MyTable');

% Add parameters to table container.


for i = 1:length(Parameters) % To import values from an array called 'Parameters'
aMaskObj.addParameter('Name', Parameters(i).Name, 'Type', Parameters(i).Type, 'Container', 'MyTable');
end

See Also

More About
• “Author Block Masks”
• “Create a Simple Mask” on page 43-7
• “Mask Editor Overview”

43-58
Customize Tables for Masked Blocks

Customize Tables for Masked Blocks


The Custom Table parameter allows you to add customized table with structured data on a mask
dialog box without writing custom codes. As a mask parameter, the custom table widget supports
parameter promotion unlike the tables created using custom block dialog code.

You can provide input to the Custom Table parameter as a string in the cell array format.

Adding a Custom Table Parameter


1 Open a Simulink model.
2 Select any block and on the Block tab, in the Mask group, click Create Mask. The Mask Editor
opens.
3 In the Parameters & Dialog tab, click Custom Table to add it to the mask as a parameter.
Specify a name and prompt for the parameter, as required.
4 In the Property Editor pane, click the Columns field to enter the column properties, such as
the name of each column, type of column, visibility and expression evaluation. The available
column types are edit, checkbox, and popup. Use the Add button to add a column and Remove
button to remove an existing column.

5 In the Property Editor pane, click the Value field and add the required number of rows by
clicking . If required, enter default values in the newly added rows. Click Save to save your
changes.

43-59
43 Working with Block Masks

6 Click Save Mask to save the changes to the mask. Double-click the block to view this custom
table.

If you want to edit the custom table, right-click the block and select Mask > Edit Mask.

See Also

More About
• “Control Custom Table Programmatically” on page 43-61

43-60
Control Custom Table Programmatically

Control Custom Table Programmatically

Use a programmatic interface to control custom tables. You can add a custom table on the mask
dialog box programmatically and control its properties using programmatic interface. For information
on creating a custom table from the Mask Editor, see “Customize Tables for Masked Blocks” on page
43-59.

Add a Custom Table Parameter

You can add a custom table parameter to a mask dialog box using these commands:

new_system('mask_custom_table');

Warning: The model name 'mask_custom_table' is shadowing another name in the MATLAB workspace or

add_block('built-in/subsystem','mask_custom_table/subsystem');
save_system;
open_system('mask_custom_table');
% Mask Object
maskObj = Simulink.Mask.create(gcb);

% Add custom table parameter


tableParam = maskObj.addParameter( 'Name', 'myTable', 'Type', 'customtable' );

Add Columns to a Table

You can add columns to a custom table using the addColumn command:

tableControl = maskObj.getDialogControl('myTable');
tableControl.addColumn( 'Name', 'HDL Name', 'Type', 'edit' );
tableControl.addColumn( 'Name', 'I/O Mode', 'Type', 'popup', 'TypeOptions', {'Input', 'Output'} )
tableControl.addColumn( 'Name', 'Sample Time', 'Type', 'edit' );
tableControl.addColumn( 'Name', 'Data Type', 'Type', 'popup', 'TypeOptions', {'Inherit', 'FixedPo
tableControl.addColumn( 'Name', 'Sign', 'Type', 'checkbox' );
tableControl.addColumn( 'Name', 'Fraction Length', 'Type', 'edit' );
tableControl.Columns(2).Width=500

tableControl =
CustomTable with properties:

Name: 'myTable'
Row: 'new'
HorizontalStretch: 'on'
Tooltip: ''
ShowFilter: 'on'
Multiselect: 'on'
Sortable: 'off'
Columns: [1×6 Simulink.Mask.TableParamColumnInfo]

% Add values to the table


tableParam.Value = join( [ "{'sig1', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit';", ...
" 'sig2', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit';", ...
" 'sig3', 'Output', '10', 'Inherit', 'off', 'Inherit';", ...
" 'sig4', 'Output', '10', 'Inherit', 'off', 'Inherit'}" ] );

43-61
43 Working with Block Masks

Note:

• You can use the Width property to specify initial column width for a custom table.

Set and Get Table Properties

You can fetch the value of a cell if it had a change and set a new value for a cell in the table using
these commands:
% get values of the changed cell
open_system('mask_custom_table/subsystem')

% get value of a particular cell


tableControl.getValue( [1 3] );

% Set value for a particular cell


tableControl.setValue( [1 3], '20' );

changedCells = tableControl.getChangedCells();

Set and Get Cell Level Specifications

You can set and fetch the value of a particular cell in a custom table. The commands used are:
% set value for a particular table cell
tableControl.setTableCell( [1 3], 'Type', 'checkbox', 'Value', 'off', 'Enabled', 'off' )

% get value from a particular table cell


tableCell = tableControl.getTableCell( [1 5] )

tableCell =
CustomTableParamCellObject with properties:

Value: 'on'
Type: 'checkbox'
Enabled: 'on'
TypeOptions: {0×1 cell}

Note:

• The setTableCell and getTableCell APIs must be used as part of mask parameter call backs while
getting the number of rows in a table.
• The setTableCell and getTableCell APIs displays the correct result only when the dialog with the
custom table parameter is opened.

Edit Rows in a Custom Table

You can insert, remove, swap, and get the value of a specific row in a custom table. The commands
used are:
% add a row to the table
tableControl.addRow( 'sig5', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit' )

% Insert a row at a specific location in the table


tableControl.insertRow( 4, 'insertSig4', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit' )

% Remove a particular row

43-62
Control Custom Table Programmatically

tableControl.removeRow( 2 )

% Swap two rows


tableControl.swapRows( 3, 4 )

tableControl.getSelectedRows()

Get and Set Table Parameter

You can use the set_param and get_param commands to set or get the values of the custom table
parameter you created in a mask dialog box.

get_param( gcb, 'myTable' )

ans =
'{'sig1', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit'; 'sig2', 'Input', 'Inherit', 'Inherit'

set_param( gcb, 'myTable', "{ 'sig1', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit' }" )

Edit Columns in a Custom Table

You can insert, remove, swap, and get the value of a specific column in a custom table. The
commands used are:

% add a column to the table


tableControl.addColumn( 'Name', 'Hardware Name', 'Type', 'edit' );
% Remove a column from the table
tableControl.removeColumn( 1 );
% Insert a column at a particular location in the table
tableControl.insertColumn( 1, 'Name', 'HDL Name', 'Type', 'edit' );
tableControl.getColumn( 4 );

Insert Column and Enable Evaluation of the Column Cells

Insert a new column with the Evaluate check box selected. The command used is:

tableControl.insertColumn( 2, 'Name', 'Counter', 'Type', 'edit','Evaluate','on' );

See Also

More About
• “Customize Tables for Masked Blocks” on page 43-59

43-63
43 Working with Block Masks

Add Images in Masks


You can add images as icons on a Simulink mask and save them along with the model.

1 Select a masked block and on the Block tab, click Add Image.
2 In the Add mask icon image dialog box, click Browse to select an image from your local
repository.

3 Select Save a copy of the image with model to save the image with the model.
4 Click Edit Icon to set the properties of the icon such as Opaque, Transparent, and Opaque
with ports.
5 Click OK to save your changes.

You can remove an icon from the masked block. Select the masked block and on the Block tab, click
Remove Image.

Store Mask Images Programmatically


• Convert mask image to internal for one block

Simulink.Mask.convertToInternalImage
• Convert mask image to internal for the whole model

Simulink.Mask.convertToInternalImages
• Convert mask image to external for one block

Simulink.Mask.convertToExternalImage

See Also

More About
• “Control Custom Table Programmatically” on page 43-61

43-64
Create Hierarchical List in Mask Dialog

Create Hierarchical List in Mask Dialog


You can use the Tree Control option available in the Display section of the Mask Editor to create the
hierarchical list of data in mask dialog box.

Consider a scenario in which you want to create a parent-child hierarchy on a mask dialog box as
shown here:

To do so,

1 Right-click a block and in the content menu click Mask > Create Mask or Mask > Edit Mask.
2 In the Parameters & Dialog pane, click Tree Control from the Display section.
3 In the Property editor section, specify these in the Tree Items field:

{ 'Node1', {'ChildNode1', 'ChildNode2'}, 'Node2', {'ChildNode1',


'ChildNode2'}, 'Node3', {'ChildNode1', 'ChildNode2'}, 'Node4',
{'ChildNode1', 'ChildNode2'}}
4 Click Apply.

See Also

More About
• “Mask Editor Overview”

43-65
43 Working with Block Masks

Validating Mask Parameters Using Constraints


A mask can contain parameters that accept user input values. You can provide input values for mask
parameters using the mask dialog box. Mask parameter constraints help you to create validations on
a mask parameter without having to write your own validation code. Constraints ensure that the
input for the mask parameter is within a specified range. For example, consider a masked Gain block.
You can set a constraint where the input value must be between 1 and 10. If you provide an input that
is outside the specified range, an error displays.

Create and Associate a Constraint

Constraint Manager is embedded inside Mask Editor with attributes and options to create your
constraints. Click Constraints tab to create or load an existing constraint.

Create a Constraint

You can create constraints according to your specification using the built-in attributes in the
Constraint Manager. To create a constraint:
1 In the Mask Editor, click Constraints tab and then click New in the toolstrip to create a
constraint.
2 Select attributes for the constraint in the Rule section. Based on the data type selection, the
applicable rule attributes gets enabled/disabled.

For more details on rule attributes, see “Rule Attributes” on page 43-69.

43-66
Validating Mask Parameters Using Constraints

Associate the Constraint to a Mask Parameter

Once a constraint is created, you can associate it with any Edit or Combobox parameters in the
Mask Editor.

1 In the Mask Editor, select the parameter you want to associate a constraint with.
2 Select the constraint name from the Constraint drop-down menu.

Validate the Constraint

To check if the parameter is in adherence with the associated constraint:

1 Select a parameter with a constraint associated with it.


2 Provide the input values for the parameter in the Property editor. If the input is outside the
specification for the associated constraint, an error displays.

43-67
43 Working with Block Masks

Note The parameter callback code gets executed after validating the parameter value against the
associated constraint. If the validation fails, the callback code is not executed.

Create a Cross-Parameter Constraint


Cross-parameter constraints are applied among two or more Edit or Combobox type mask
parameters. You can use a cross parameter constraint when you want to specify scenarios such as,
Parameter1 must be greater than Parameter2.

1 In the Mask Editor, click Constraints tab.


2 Click Cross-Parameter Constraints.
3 Click Create Constraint. A new cross-parameter constraint is created with a default name
(Constraint_1). You can change the constraint name.
4 Specify the following values for the new constraint:

• Name – Specify a name for the constraint


• MATLAB Expression – Specify a valid MATLAB expression. This expression is evaluated
during edit time and simulation
• Error Message – Specify the error message to be displayed when the constraint rule is not
met. If no error message is specified, a default error message displays.

43-68
Validating Mask Parameters Using Constraints

Rule Attributes
Rule attributes to create constraints are shown in the table:

Rule Attribute Attribute Value Description


Data type numeric, double, single, Specify the acceptable data type
half, int8, uint8, int16, of the mask parameter value.
uint16, int32, uint32, You can choose multiple data
int64, uint64 boolean, enum, types. To validate the parameter
string value against a specific range,
use the Minimum and
Maximum properties because
the Data Type property does
not validate the parameter value
against the range. For example,
to validate the parameter value
against the data type numeric
and range 0 - 127, select
numeric in Data Type and
enter 0 and 127 in the
Minimum and Maximum
properties respectively.
Complexity real, complex Specify if the mask parameter
value can be a real or complex
number.
Dimensions scalar, row vector, column Specify the acceptable
vector, 2-D matrix, n-D dimensions for the mask
matrix parameter.
Sign positive, negative, zero Specify if the input value must
be positive, negative, or zero.
Finiteness finite, inf, -inf, NaN Specify the acceptable
finiteness of mask parameter
value.
Fraction integer, decimal Specify if the input value must
be an integer or decimal.
Range Minimum, Maximum Specify the acceptable range of
mask parameter value.
Custom Rule Valid MATLAB expression Specify custom constraint for
the mask parameter using a
valid MATLAB expression. You
can use the value token to
parameterize the expression.
During validation, the evaluated
value of the parameter replaces
the value token.

43-69
43 Working with Block Masks

Rule Attribute Attribute Value Description


Error Message Character vector Specify a custom error message
for the custom constraint. You
can specify the error message
as character vector or as a
message catalog ID.

Support Constraints on Literal Edit Parameters


You can associate constraints to literal edit parameters. If the Evaluate option is not selected,
Simulink takes a literal reading of the input entry as you type it in the mask parameter dialog box.
For example, the IP address stored in a literal edit parameter is validated against a custom rule.

See Also

More About
• “Share Parameter Constraints Across Multiple Block Masks” on page 43-76
• “Custom Constraint for Mask Parameter” on page 43-71

43-70
Custom Constraint for Mask Parameter

Custom Constraint for Mask Parameter

A mask can contain parameters that accept user input values. You can provide input values for mask
parameters using the mask dialog box. Mask parameter constraints help you to create validations on
a mask parameter without having to write your own validation code. Constraints ensure that input
value for the mask parameter satisfies the rules associated with the constraints. For example,
consider a masked Subsystem block. You can set a constraint where the input value must be even
number. If you provide an input that is not an even number, an error is displayed. If the rule you want
specify is not present as one of the attributes, then specify a MATLAB® expression that returns a
scalar. You can also associate a literal edit parameter to a constraint. The constraint is either a rule
specified with the available attributes or is a MATLAB expression.

Explore Model

The example model contains a subsystem block whose block parameters evenNoParam1 and
evenNoParam2 must be an even number. You have custom the constraint using MATLAB expression
as the rule you want to specify is not present as one of the attributes.
open_system("slexMaskConstraints.slx");

Create and Associate Custom Constraint to Mask Parameter

In the example model, refer to the Custom Constraint section.

To create a custom constraint:

1. Create a mask on the subsystem block.

43-71
43 Working with Block Masks

2. In the Mask Editor, select Constraints > Parameter.

a. Enter the name of the constraint as evenNumberConstraint.

b. Enter the MATLAB expression as mod(value,2)==0.

Note: You can use the value token to parameterize the expression, which helps in assigning a
constraint to multiple parameters. During validation, the evaluated value of the parameter replaces
the value token. For example, if the MATLAB expression for a constraint is value > 100 and is
associated with the edit type mask parameter, Parameter1, then the MATLAB expression evaluates
as Parameter1 > 100. This helps in assigning the constraint to multiple parameters.

c. In Error Message, enter The value of the parameter must be even number. Save the
mask.

Associate Custom Constraint to Mask Parameters

You must associate constraints to mask parameters. You can associate the same constraint among
multiple mask parameters.

1. In the Mask Editor, click the Parameters & Dialog tab.

2. Click the mask parameter.

3. In the Property Editor, go to the Attributes section, and select the constraint from the
Constraint.

43-72
Custom Constraint for Mask Parameter

Note: You can associate the same constraints with multiple mask parameters. The Constraints
Browser helps you to manage constraints. If you want to create a constraint that involves multiple
parameters, use cross-parameter constraints instead of custom constraints.

Validate Constraint

To check if a parameter adheres to the associated constraint:

1. Go to the Mask Editor and select the parameter.

2. In the Property Editor, provide input values that are outside of the range specified in the
associated constraint. An error displays.

Define and Associate Constraint to Mask Literal Edit Parameter

You can associate constraints to literal edit parameters. If the Evaluate option is not selected,
Simulink® takes a literal reading of the input entry as you type it in the mask parameter dialog box.

43-73
43 Working with Block Masks

For example, you can store an IP address in a literal edit parameter and validate it against a custom
rule.

In the example model, refer to the Define and Associate Constraint to Mask Literal Edit Parameter
section.

To create a custom constraint:

1. Create a mask on the subsystem block.

2. Create an edit parameter IPAddress. Clear the Evaluate option in the Attributes section to store
the literal value of the parameter IPAddress.

3. In the Mask Editor, select Constraints > Parameter.

a. Enter the name of the constraint as IPAddressConstraint.

b. Specify the MATLAB expression as slexMaskIsValidIPAddress(value).

The function slexMaskIsValidIPAddress stored in slexMaskIsValidIPAddress.m file checks


if IPAddress is a valid IP address. The function returns true if IPAddress is a valid IP address and
returns false otherwise.

function out = slexMaskIsValidIPAddress(addr)


out = true;
if ~isempty(regexp(strtrim(addr), '^\d{1,3}(\.\d{1,3}){3}$', 'once'))

43-74
Custom Constraint for Mask Parameter

ipVec = sscanf(addr, ['%u' '.' '%u' '.' '%u' '.' '%u']);


if ~all(ipVec <= 255)
out = false;
end
else
out = false;
end
end

Associate Constraint to Mask Literal Edit Parameter

1. In the Mask Editor, click the Parameters & Dialog tab.

2. Click the mask parameter.

3. In the Property Editor pane in the Attributes section, select the constraint
IPAddressConstraint from Constraint.

Validate the Constraint

To check if the parameter adheres to the constraint:

1. Double-click the Constraint on literal edit parameter Subsystem block.

2. Enter an inavlid IP address in the mask dialog box and click OK.

3. This error message appears.

See Also

More About
• “Validating Mask Parameters Using Constraints” on page 43-66

43-75
43 Working with Block Masks

Share Parameter Constraints Across Multiple Block Masks

This example shows how to create a parameter constraint and share it across masks of different
blocks in the same model or different models. You can save the parameter constraint in a XML file
and associate the constraint across multiple block masks. Defining a shared constraint in an XML file
enables you to edit the data and compare the file with a previous version.

A mask can contain parameters that accept user input values. You can provide input values for mask
parameters using the mask dialog box. Mask parameter constraints enable you to create validations
on a mask parameter without having to write your own validation code. Constraints ensure that the
input value for the mask parameter satisfies the rules associated with the constraints. For example,
consider a masked Subsystem block. You can set a constraint where the input value must be between
1 and 10. When you provide an input that is outside the specified range, the software displays an
error. For information on mask parameter constraints, see “Validating Mask Parameters Using
Constraints” on page 43-66.

Note: To use shared constraint created in a MAT file, you must convert it to an XML file using the
syntax Simulink.Mask.Constraints.convertMatToXML(matFileName, xmlFileName).
matFileName is the name of the MAT file to convert and xmlFileName is the name of the XML file
to create. See Simulink.Mask.Constraints.convertMatToXML for more details.

Explore the Model

This model has two subsystem blocks named SharedConstraintBlock1 and


SharedConstraintBlock2. Each block parameter value on each subsystem block must be a real
scalar. Instead of creating separate constraints for these blocks, you can create a single constraint in
an XML file and share it across the two subsystem blocks.

open_system("slexMaskConstraints.slx");

43-76
Share Parameter Constraints Across Multiple Block Masks

Create Shared Constraint

In the example model, refer the shared constraint blocks SharedConstraintBlock1 and
SharedConstraintBlock2.

Create a shared constraint:

1. Create a mask on the SharedConstraintBlock1 block.

2. Go to Mask Editor, on the Constraints tab, click new and enter the name of the XML file,
sharedConstraint.

3. Create the parameter constraint in the XML file. Click Parameter Constraint and specify the
attributes for the constraint. The Constraint Browser helps you to manage shared constraint.

43-77
43 Working with Block Masks

4. On the Parameters & Dialog tab, click the parameter.

5. Select Property Editor > Attributes > Constraint and select the XML file constraint.

43-78
Share Parameter Constraints Across Multiple Block Masks

Associate Constraint Across Multiple Blocks or Models

Reuse the constraint sharedConstraint:realScalarPositiveConstraint in the


SharedConstraintBlock2 block.

1. Create a mask on the SharedConstraintBlock2 block.

2. Select Mask Editor > Constraint > Load to load the constraint. Select the XML file and save the
mask.

43-79
43 Working with Block Masks

3. Go to the Parameters & Dialog tab and click the parameter.

4. Select Property Editor > Attributes > Constraints and select the XML file.

43-80
Share Parameter Constraints Across Multiple Block Masks

Validate the Constraint

Provide an invalid value to the parameter using mask dialog. Observe that an error dialog is displayed
on Apply.

See Also

• “Custom Constraint for Mask Parameter” on page 43-71


• “Validate Input and Output Port Signals Using Port Constraints” on page 43-114
• Simulink.Mask.SharedConstraintFile
• Simulink.Mask.Constraints.convertMatToXML

43-81
43 Working with Block Masks

Control Constraints Programmatically


You can create a custom constraint programmatically from the MATLAB command window

To create a custom constraint:


% Get mask constraint handle
paramConstraint = maskObj.getParameterConstraint('const1');

% Add rules to the constraint.


paramConstRule = paramConstraint.addParameterConstraintRule('CustomConstraint','mod(value,2) ==0')

This creates a custom constraint:

ans =

ParameterConstraintRules with properties:

DataType: ''
Dimension: {0×1 cell}
Complexity: {0×1 cell}
Sign: {0×1 cell}
Finiteness: {0×1 cell}
Minimum: ''
Maximum: ''
CustomConstraint: 'mod(value,2) ==0''

You can create and save constraints in a MAT file and load constraints from a MAT file
programmatically from the MATLAB command window:

To save a constraint in a MAT file:


uint16Constraint = Simulink.Mask.Constraints;
uint16Constraint.Name = 'uint16Constraint';
uint16Constraint.addParameterConstraintRule('DataType', 'uint16');
save('constraintList.mat', 'uint16Constraint','-append'); % appends 'uint16Constraint'
save('constraintList.mat', 'uint16Constraint') % overwrites the MAT file with 'uint16Constraint'

Note It is recommended that the constraint name (for example, uint16Constraint.Name =


'uint16Constraint') and the variable used for storing the constraint (for example,
uint16Constraint = Simulink.Mask.Constraints) have the same name.

To load a constraint from a MAT file:


myConstraints = load(‘constraintList’) % loads constraints into the variable 'myConstraints'

See Also

More About
• “Validating Mask Parameters Using Constraints” on page 43-66

43-82
Define Measurement Units for Masked Blocks

Define Measurement Units for Masked Blocks


Measurement units translate the amount of entities supplied to your computations. They are also
crucial when diverse users using different systems of measurement are using the same equation. You
can add measuring units to a Simulink model to enhance the usability and to avoid confusion while
analyzing equations.

To specify measuring units for masked blocks, you can:

• Promote a Unit parameter from the underlying block to the mask. For more information, see
“Promote Block Parameters on a Mask” on page 43-27.
• Add a Unit parameter to the mask dialog box as shown in the following steps:

1 Open a Simulink Model.


2 Select the block to be masked and press Ctrl+M. The Mask Editor opens.
3 In the Mask Editor, click the Parameters & Dialog tab.
4 In the Parameters section, click Unit.
5 Click the Code tab in the Mask Editor dialog box.
6 To define the measurement unit for the Unit parameter, specify the initialization command by
using the following syntax:
set_param([gcb '/<blockname>'], '<unit parameter name>', get_param(gcb, '<unit parameter name>'));

For example, to associate the Unit parameter with the measuring unit of the Inport block,
use:

set_param([gcb '/In1'], 'Unit', get_param(gcb, 'Unit'));

See Also

More About
• “Masking Fundamentals” on page 43-3
• “Promote Block Parameters on a Mask” on page 43-27

43-83
43 Working with Block Masks

Masking Example Models


The Simulink Masking example models help you to understand and configure mask parameters,
properties, and features. See “Simulink Masking Examples” on page 43-162 for more information on
Masking models. The examples are grouped by type. In an example model:

• To view the mask definition, double-click the View Mask block.


• To view the mask dialog box, double-click the block.

Goals Example Models Related Topics


Add Parameters control type to Mask parameters. Model: “Mask Editor Overview”
mask dialog box. For example, ( slexMaskParameterOption
Evaluate, Tune, Add Image, Pop- sExample)
up, Combo-box, Slider and Dial,
Slider Range
• Add an opaque mask with Mask Icon Drawing Commands. “Mask Editor Overview”
visible port labels (Icon Model
Transparency). ( slexMaskDrawingExamples)
• Specify Run Initialization
instructions
Use dialog layout options to: Dialog Layout Options. Model
( slexMaskLayoutOptionsEx
• Add horizontal stretch on ample)
mask dialog box
• Group multiple parameters
in to tabs
• Create a dynamic pop-up
parameter
• Create a collapsible content
panel in a mask dialog box
• Create a table container to
group multiple parameters
Promote parameters to a mask Parameter Promotion. Model: “Promote Block Parameters on a
(slexMaskParameterPromoti Mask” on page 43-27
onExample)
Execute Mask Callback Mask Callback. Model: “Mask Callback Code” on page
(slexMaskCallbacksExample 43-12
)
Display an Image as icon on a Mask Display and Mask “Add Image to Block Icon” on
mask Initialization. Model: page 51-58
(slexMaskDisplayAndInitia
lizationExample)
• Make a parameter invisible Dynamic Mask Callback. Model:
in the mask (slexMaskDDGExample)
• Disable a mask parameter

43-84
Masking Example Models

Goals Example Models Related Topics


Set a mask to be self-modifying Self Modifiable Library Block. “Dynamic Masked Subsystem”
Model: on page 43-45
(slexMaskSelfModifiableEx
ample)
Mask a variant subsystem Masking Variant Blocks. Model:
(slexMaskVariantExample)
Create a self-modifiable Self-Modifiable Interface Blocks.
interface block Model:
(slexMaskSelfModifiableIn
terfaceBlocks)

There are certain bad practices, which when followed may result in unexpected behavior of the
masking features. The following table shows some of the bad practices.

Bad Practice Example Models


Use of Mask callbacks, where the callback slexMaskUnsafeCallbacksErrorExample
modifies entities outside of its scope may result in
unexpected behavior
Setting parameters outside of the hierarchical slexMaskUnsafeNestedUsageErrorExample
boundary in nested masks may lead to
unexpected behavior

See Also

More About
• “Author Block Masks”
• “Mask Editor Overview”
• “Masking Fundamentals” on page 43-3

43-85
43 Working with Block Masks

Create a Custom Table in the Mask Dialog

This example shows how to create a custom table in a mask dialog. This model includes a Subsystem
block with a mask on it. The mask has a callback that modifies the table content based on the values
provided in the cells. The callback comes from an external supporting file. To create this table, start
by adding a mask to the block or editing an existing mask.

Add and Configure a Custom Table parameter

To add a Custom Table parameter, open the Mask Editor,go to the Parameters & Dialog tab and
click Custom Table. Then, add values in the Property editor section. For this example, in the Value
field, add:

{ 'sig1', 'Input', 'Inherit', 'Inherit', 'Signed', 'Inherit'; 'sig2',


'Input', 'Inherit', 'Inherit', 'Signed', 'Inherit'; 'sig3', 'Output', '10',
'Inherit', 'Signed', 'Inherit'; 'sig4', 'Output', '10', 'Inherit', 'Signed',
'Inherit' }.

In the Columns field, click the Edit icon and add the name of columns. The column names used in
this example are: HDL Name, I/O Mode, Sample Time, Data Type, Sign, and Fraction Length.

In the Dialog section, edit the Callback field to add your callback. The callback used in this example
is from an external file named CustomTableCallback.m. Enter the filename in the callback field.
This callback defines how the values change in a cell based on the value from other cells and
columns.

43-86
Create a Custom Table in the Mask Dialog

Add Buttons and Options to Control the Custom Table

In this example, four buttons are added to add a new row, delete a selected row, and move a row up
or down. To add the buttons, in the Action section click the Button parameter four times. Name the
buttons as New, Delete, Up, and Down. To configure the buttons, edit the Callback field in the
Property editor and add the appropriate callbacks. The callback used for each button is:

New

maskObj = Simulink.Mask.get(gcb);
tableControl = maskObj.getDialogControl( 'CustomTable' );

hdlName = 'sig';
rowIndex = tableControl.getNumberOfRows();
hdlName = strcat( 'sig', num2str( rowIndex + 1 ) );
tableControl.addRow( hdlName, 'Input', 'Inherit', 'Inherit', 'Signed', 'Inherit' )

Delete

maskObj = Simulink.Mask.get(gcb);
tableControl = maskObj.getDialogControl( 'CustomTable' );

rowIndex = tableControl.getSelectedRows();
hdlName = 'sig';

if ( ~isempty(rowIndex) )
tableControl.removeRow( rowIndex(1) );
end

Up

maskObj = Simulink.Mask.get(gcb);
tableControl = maskObj.getDialogControl( 'CustomTable' );

rowIndex = tableControl.getSelectedRows();

if ( ~isempty(rowIndex) )
tableControl.swapRows( rowIndex(1)-1, rowIndex(1) );
end

Down

maskObj = Simulink.Mask.get(gcb);
tableControl = maskObj.getDialogControl( 'CustomTable' );

rowIndex = tableControl.getSelectedRows();

if ( ~isempty(rowIndex) )
tableControl.swapRows( rowIndex(1)+1, rowIndex(1) );
end

In addition to these buttons, the table also has a check box to enable direct feedthrough and an
autofill button that automatically creates the signal interface from a specified HDL component
instance. To add these options, add a check box and a button control and add the appropriate
configurations.

After adding all the values, click OK to save the changes. You can preview the table using the
Preview button. This is a preview of the final table created in this example:

43-87
43 Working with Block Masks

43-88
Create a Block Mask Icon

Create a Block Mask Icon

You can create block icons on mask using various mask drawing commands. This model contains a
collection of subsystem blocks, each showing a particular mask drawing command in use. To create a
mask icon on a block, you must create a mask and add the icon drawing command to the mask in the
mask editor. To create a mask:

1 Select a Subsystem block . For example, the Graph as Icon block.


2 On the Subsystem Block tab, in the Mask group, click Create Mask/Edit Mask.
3 In the Mask Editor dialog box, click the Icon & Ports tab.
4 Enter the command in the Icon drawing commands pane on the right. You can set the Run
Initialization value to On, Off or Analyze based on the dependency on mask workspace.

Plotted function as Icon

This command let you plot a graph and set it as the mask icon. Select the subsystem Graph as Icon. In
the Mask Editor > Icon and Ports tab, enter plot([10 20 30 40], [10 20 10 15]). Run Initialization
can be set to Off as there is no mask workspace dependency.

Transfer Function as Icon

This command helps to set a Transfer function as the mask icon. Select the subsystem Transfer
Function as Icon. In the Mask Editor > Icon and Ports tab, enter droots([-1], [-4 -5], 4). Run
Initialization can be set to Off as there is no mask workspace dependency.

Color patch as Icon

This command lets you to set a color patch as mask icon. Select the subsystem Color patch as Icon. In
the Mask Editor > Icon and Ports tab, enter patch([0 10 20 30 30 0], [10 30 20 25 10 10],[1 0
0]). Run Initialization can be set to Off as there is no mask workspace dependency.

Image as Icon

This command lets you to set a color patch as mask icon. Select the subsystem Image as Icon. In the
Mask Editor > Icon and Ports tab, enter image('maskimage.png','center'). Run Initialization is set
to On. Make sure the image is available in the current folder in MATLAB.

Contained block icon as Icon

This command lets you promote the icon of a block contained in a subsystem to the subsystem mask.
Select the subsystem Promoted block Icon . In the Mask Editor > Icon and Ports tab, enter
block_icon(Assertion).

open_system('mask_icon_drawing_example');

43-89
43 Working with Block Masks

43-90
Mask a Variant Subsystem

Mask a Variant Subsystem

This example shows how to use a masked Variant Subsystem block in a Simulink model. Click the
Open Model button located on the top right corner to view the related example model. This example
model references masked library blocks.

When you mask a Variant Subsystem block, you can specify the variant choice from the mask dialog
box. The variant choice that you specify on the mask dialog box is applied on the underneath Variant
Subsystem block.

43-91
43 Working with Block Masks

To pass the variant choice from the mask to the Variant Subsystem block, you can either use the
set_param command or the parameter promotion option.

Let us consider the cases described in the example model.

• Case 1: The mask parameter promotion option is used to promote the Variant Subsystem block
parameter to the mask. The Variant Subsystem block is wrapped within a masked Subsystem
block. Initialization code (set_param) is used in the Variant Subsystem block to define the variant
choice which is further passed on to the mask on the Subsystem block using parameter promotion.
This promoted parameter records the variant choice specified from the masked Subsystem block.
• Case 2: The Popup mask parameter is used to create the choice option on the top level masked
Subsystem block. This masked Subsystem block contains a Variant Subsystem block. Initialization
code (set_param) is used in the Variant Subsystem block to define the variant choice. The value
that you specify as a variant choice from the mask dialog box (Popup parameter) is transferred to
the underneath Variant Subsystem block to set it choices.
• Case 3: This case is similar to Case 2 with an additional layer of Variant Subsystem block in the
model. Initialization code (set_param) in the Subsystem block is used to define the variant
choice.
• Case 4: Parameter promotion is used to record the choice from the parent block on the masked
Subsystem block. The masked Subsystem block contains a masked Variant Subsystem block
within. Initialization code (set_param) in the Variant Subsystem block mask sets the parameter
value that is passed from the Subsystem block (MaskedSubsystem1).

More About

• “Masking Fundamentals” on page 43-3


• “Initialization Function” on page 4-82

43-92
Tune Mask Enumeration Parameters - Popup and Radio Button

Tune Mask Enumeration Parameters - Popup and Radio Button

You can visualize the behavior of a Simulink® model under different conditions by tuning block
parameter values. You can assign numeric or string values to the popup and radio button parameters
instead of indexes.

Achieve tunability for mask popup and radio buttons in these ways:

• Select from list of option - Select the option for the popup or radio button parameter from the
mask dialog box. The corresponding value is used in simulation and code generation. Using a list
of options allows for tunability in simulation but not in generated code.

• Provide external enumeration file - Populate the options for the popup or radio button parameter
from an external enumeration file. Select the option from the mask dialog and the corresponding
value from the enumeration file is used in simulation and code generation. You can achieve
tunability in both simulation and code generation with this method.

• Create enumeration class - Provide data to create an enumeration class internally. You can select
the option for the popup or radio button parameter. The corresponding value is used in simulation
and code generation. You can achieve tunability in both simulation and code generation with this
method.

Note: You can create options and achieve tunability for a radio button using the above methods, but
you cannot achieve tunability by associating a model workspace variable to a radio button.

Explore the Model

This example model contains four scenarios where you can associate values to the popup parameter
to achieve tunability.

• The Subsystem block ListofOptions uses a list of options for the popup parameter.

• The Subsystem block EnumClass uses an enumeration class with the provided data and
associates it with the popup parameter.

• The Subsystem block ExternalEnum references an external enumeration file and associates the
values to the popup parameter.

• The Subsystem block Associate Variable associates a variable with the popup parameter. The
parameter values and display strings are populated from external enumeration file XFactor. The
popup parameter is associated with model workspace variable workspaceVar.

open_system("slexMaskTunablePopupExample.slx");

43-93
43 Working with Block Masks

Associate Values to Popup Parameter Using List of Options

To create and associate a list of options for the popup parameter:

1. Create a Subsystem block ListofOptions and mask the block.

2. Create a popup parameter XFactorParam.

3. Double-click Type options and select List of options.

43-94
Tune Mask Enumeration Parameters - Popup and Radio Button

4. Enter the Description of each option as alpha(0.001), beta(0.0001), and gamma(0.00001),


and their Values as 0.001, 0.0001, and 0.00001.

5. Click Save, then click Save Mask to save the list of options and the mask.

You can associate string values to the popup options. To enter string values as options to the popup
parameter, enter string values enclosed in single quotes in the Values column.

6. Reference the popup parameter in child block. Create a Constant block inside the Subsystem
block. Set the Constant value parameter in the Constant block to XFactorParam.

7. Double-click the block ListofOptions and select the value for XFactor and simulate the model.
Observe that the selected value appears in the Display block.

Reference an External Enumeration File for Popup Options

An external enumeration file can have multiple members with different display names and values.
When the enumeration file is associated with a popup parameter:

43-95
43 Working with Block Masks

• The display name of the enumeration member becomes the popup parameter option.
• The enumeration member value becomes the value assigned to the popup parameter option.

1. Create a Subsystem block ExternalEnum and mask the block.

2. Create a popup parameter XFactorParam.

3. Double-click Type options select Use enumeration, then select Reference Enumeration file.

4. Enter the name of the enumeration file as XFactor without the file extension.

The contents of the file appear in the Name, Description, and Value columns. Observe that the
contents are read-only and cannot be edited from the interface.

Numeric values are associated with popup options from the enumerated file Xfactor.m. The
enumeration class of the file Xfactor, is derived from Simulink.Mask.EnumerationBase. The
class has three enumeration members, alpha, beta, and gamma. These enumerated members have
numeric values 0.001, 0.0001, and 0.00001, respectively.

classdef XFactor < Simulink.Mask.EnumerationBase


enumeration
alpha(0.001, 'alpha (0.001)')
beta (0.0001, 'beta (0.0001)')
gamma(0.00001,'gamma (0.00001)')
end
end

In the generated code, the default data type for the enumeration member is double. Alternatively, you
can also specify a data type for the enumeration members. For example use
alpha(int32(0.001),'alpha(0.001)') in the enumeration class file. All members of the
enumeration class must be of the same data type.

5. Click Save Mask.

6. Reference the popup parameter in the child block. Create a Constant block inside the Subsystem
block. The value of the Constant parameter inside the subsystem is set as XFactorParam.

7. Simulate the model and generate code.

43-96
Tune Mask Enumeration Parameters - Popup and Radio Button

The parameter value is evaluated as the enumeration member corresponding to the display name you
select. For example, if you select alpha(0.0001) from the Parameters drop-down, the value of
XFactorParam is set to XFactor.alpha.

classdef XFactor < Simulink.Mask.EnumerationBase


enumeration
alpha(0.001, 'alpha (0.001)')
beta (0.0001, 'beta (0.0001)')
gamma(0.00001,'gamma (0.00001)')
end
end

You can generate code using Simulink Coder™ or Embedded Coder™. In the generated code:

• The value array XFactorValues is generated in the modelname.c file.


const real_T XFactorValues[3] = { 0.001, 0.0001, 1.0E-5 } ;

• The enumeration is generated in the code according to the referenced enumeration file.
typedef enum {
XFactor_alpha = 1, /* Default value */
XFactor_beta,
XFactor_gamma
} XFactor;

• The mask parameter XFactorParam appears in the parameter structure.


/* Parameters (default storage) */
struct P_slexMaskTunablePopupExample_T_ {
XFactor ExternalEnum_XFactorParam;/* Mask Parameter: ExternalEnum_XFactorParam
* Referenced by: '<S1>/Constant'
*/
};

• Tunable variable XFactorParam is referenced while generating the output. You can specify
different values to XFactorParam and thus XFactorParam tunable.
/* Model step function */
void slexMaskTunablePopupExample_step(void)
{
/* Outport: '<Root>/Out3' incorporates:
* Constant: '<S1>/Constant'
*/
slexMaskTunablePopupExample_Y.Out3 = XFactorValues[(int32_T)
slexMaskTunablePopupExample_P.ExternalEnum_XFactorParam - 1];
}

Create and Associate Enumeration Class to Popup Parameter

An enumeration class can be created with the user data and associated with the popup parameter. To
create an enumeration class:

1. Create a Subsystem block EnumClass and mask the block.

2. Create a popup parameter XFactorParam.

3. Double-click Type options. Select Use enumeration and then select Create new Enumeration.

43-97
43 Working with Block Masks

4. Enter the name of the enumeration class as XFactorInternal and enter the values for Name,
Description, and Value.

5. Click Save and then click Save Mask to save the enumeration class and the mask.

6. Reference the popup parameter in the child block. Create a Constant block inside the Subsystem
block. The value of the Constant parameter inside the subsystem is set as XFactorParam.

7. Simulate the model and generate the code.

The mask parameter |(XFactorParam)| appears in the parameter structure.

/* Parameters (default storage) */


struct P_slexMaskTunablePopupExample_T_ {
XFactorInternal EnumClass_XFactorParam;/* Mask Parameter: EnumClass_XFactorParam
* Referenced by: '<S1>/Constant'
*/
};

The tunable parameter XFactorParam is referenced while generating the output. You can specify
different values to XFactorParam and thus XFactorParam is tunable.

/* Model step function */


void slexMaskTunablePopupExample_step(void)
{
/* Outport: '<Root>/Out2' incorporates:
* Constant: '<S1>/Constant'
*/
slexMaskTunablePopupExample_Y.Out2 = XFactorInternalValues[(int32_T)
slexMaskTunablePopupExample_P.EnumClass_XFactorParam - 1];
}

Create and Associate Variables Using the Mask Dialog Box

By default, optimization of code generation inlines all parameters in the generated code. To achieve
tunability for a specific parameter, create a variable of type Simulink.Parameter with a specific
storage class (other than Auto) in the workspace and associate it with the mask popup parameter.
You cannot associate a variable to the radio button parameter.

1. Create a Subsystem block ExternalEnum and mask the block.

2. Create a popup parameter XFactorParam.

3. Double-click Type options. Select the option Use enumeration, then select Reference
Enumeration file.

43-98
Tune Mask Enumeration Parameters - Popup and Radio Button

4. Enter the name of the enumeration file as XFactor without the file extension.

5. Click Save Mask.

6. Reference the popup parameter in the child block. Create a Constant block inside the Subsystem
block. The value of the Constant parameter inside the subsystem is set as XFactorParam.

7. Open the mask dialog box. Click the action widget.

8. Select Associate Variable. You can associate an existing variable with the popup parameter, or
create a new variable in one of the available locations and associate it with the popup parameter.

After associating the variable with the popup parameter, the variable appears next to the popup
option.

The value of the associated variable and the popup value are always synchronized. For example, if
you change the popup option from alpha (0.001) to beta (0.0001), the value of workspaceVar
is updated to XFactor.beta . Similarly, when you change the value of the variable, the value of the
parameter reflects the change in the mask dialog box.

9. Simulate the model and generate code.

The associated variable value appears in the parameter structure corresponding to the tunable popup
parameter.
/* Parameters (default storage) */
struct P_slexMaskTunablePopupExample_T_ {

43-99
43 Working with Block Masks

XFactor workspaceVar; /* Variable: workspaceVar


* Referenced by: '<S1>/Constant'
*/
};

The associated variable is referenced in the step function to generate output.

/* Model step function */


void slexMaskTunablePopupExample_step(void)
{
/* Outport: '<Root>/Out4' incorporates:
* Constant: '<S1>/Constant'
*/
slexMaskTunablePopupExample_Y.Out4 = XFactorValues[(int32_T)
slexMaskTunablePopupExample_P.workspaceVar - 1];
}

Tune Popup Parameter Programmatically

You can use a set of APIs to tune popup parameters programmatically.

1. Create an object of Simulink.Mask.EnumerationMember and define the number of options.

typeOptions = Simulink.Mask.EnumerationMember.empty(3,0)

2. Define options for the popup parameter.

typeOptions=Simulink.Mask.EnumerationMember.empty(3,0);
typeOptions(1)=Simulink.Mask.EnumerationMember('alpha','XFactorAlpha',0.001);
typeOptions(2)=Simulink.Mask.EnumerationMember('beta','XFactorbeta',0.0001);
typeOptions(3)=Simulink.Mask.EnumerationMember('gamma','XFactorgamma',0.00001);

%TypeOptions defined using List of Options method

enumObj = Simulink.Mask.EnumerationTypeOptions('EnumerationMembers',typeOptions)
enumObj.EnumerationMembers(1)
ans =

EnumerationMember with properties:

MemberName: ''
DescriptiveName: 'alpha'
Value: 1.0000e-03

%TypeOptions defined by creating an enumeration class

enumObj =
Simulink.Mask.EnumerationTypeOptions('EnumerationMembers',typeOptions,'EnumNameInGeneratedCode','
enumObj(1)
ans =
EnumerationTypeOptions with properties:

EnumerationMembers: [1*3 Simulink.Mask.EnumerationMember]


EnumNameInGeneratedCode: 'XFactor'

%TypeOptions defined by referencing an external enumeration file

43-100
Tune Mask Enumeration Parameters - Popup and Radio Button

enumObj = Simulink.Mask.EnumerationTypeOptions('ExternalEnumerationClass', 'XFactor');


enumObj.EnumerationMembers(1)

ans =

EnumerationMember with properties:

MemberName: 'alpha'
DescriptiveName: 'XFactor.alpha'
Value: 1

3. Associate the list of options to the mask popup parameter.


addParameter(maskobj,'Type','popup','TypeOptions',enumObj);
paramHandle = maskobj.getParameter('XFactorParam');
paramHandle =

MaskParameter with properties:

Type: 'popup'
TypeOptions: [1*1 Simulink.Mask.EnumerationTypeOptions]
Name: 'XFactor'
Prompt: ''
Value: 'XFactorAlpha'
Evaluate: 'on'
Tunable: 'on'
NeverSave: 'off'
Hidden: 'off'
ReadOnly: 'off'
Enabled: 'on'
Visible: 'on'
ShowTooltip: 'on'
Callback: ''
Alias: ''
VariableName: ''
DialogControl: [1*1 Simulink.dialog.parameter.Popup]

Note: A new property VariableName is added to the mask parameter, which is used for associating
tunable variable to the popup parameter.

Use this command to associate the workspace variable to the value of the parameter.
paramHandle.VariableName = 'workspaceVar'

Associate Enumeration File Derived from Simulink.IntEnumType

If you have an existing enumeration class derived from Simulink.IntEnumType, you can use the
enumeration file to associate numeric values to the popup parameter instead of creating a new
enumeration class derived from Simulink.Mask.EnumerationBase. To associate enumeration file
derived from Simulink.IntEnumType, follow these steps.

1. Define the enumeration file Color

classdef Color < Simulink.IntEnumType


enumeration
red(1)
green(100)
blue(1000)

43-101
43 Working with Block Masks

end
methods(Static)
function aOut = addClassNameToEnumNames()
aOut = false;
end
end
end

2. Specify the name of the enumeration class.

3. The popup options will be populated with the enumeration members in the specified class prefixed
by the enumeration class name.

4. Set the Constant parameter value to the popup parameter XFactorParam.

See Also

Simulink.Mask.EnumerationTypeOptions

43-102
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

Visualize and Plot N-Dimensional Data Using Mask Lookup


Table Control

Use a lookup table to evaluate a sampled representation of a function using simple lookup operations.
It enables you to assess the function with less computation time than running the function. You can
visualize, edit, and plot N-dimensional lookup table data in mask dialog using the lookup table
control.

Visualize and Edit Table and Breakpoint Data Using the Lookup Table Control

Consider a scenario where the fuel flow is determined by the torque and engine speed. Specify the
data explicitly for table data and breakpoint parameters.

1. Right-click on the block LUT Control with Explicit Data, click Edit Mask to open the Mask
Editor. In the Mask Editor, go to the Parameters & Dialog pane and create Edit parameters Torque
and Engine Speed for breakpoints. In the Property Editor pane, enter the values for the
breakpoints in the Values field.

2. Create an Edit parameter Fuel Flow for table data in the Property Editor pane, enter the values
in the Value field.

3. Add a lookup table control. Enter the table properties Table Parameter, Table Unit, Table
Display Name, Breakpoint Parameters, Breakpoint Units, and Breakpoints Display Name.
Click OK.

43-103
43 Working with Block Masks

4. Double-click the masked block to view the lookup table. Click a cell to edit the value.

Reference Promoted Parameters for Table and Breakpoint Data

You can follow the same steps to reference promoted parameters to build a lookup table.

43-104
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

Specify Table Data and Breakpoint Data Using Lookup Table Object

To reference an object in the lookup table control:

1. Create an object named lutobject in the model or base workspace with table and breakpoint
data.

2. Create an Edit parameter and enter the value as lutobject created in the model workspace.

3. Create the lookup table control lutcontrol and reference the Edit parameter. The lookup table is
now populated with the table and breakpoints data.

43-105
43 Working with Block Masks

Switch Between Explicit Data Specification Mode and Data Referencing Mode

You can switch between explicit data specification mode and data referencing mode using a Popup
parameter. Create a Popup parameter and use it in the lookup table control to choose between
explicit data specification mode and data referencing mode.

Use callback code for the Popup parameter.


dataspec_paramName = 'dataspec';
bp1_paramName = 'torque'; bp2_paramName = 'enginespeed'; tbl_paramName
= 'fuelflow'; lutobj_paramName = 'lutobject'; underlyingLUTblock =
'slexMaskLookupTableControlExample/LUT Control with Data Specification
Mode/2-D Lookup Table';

dataSpec = get_param(gcb, dataspec_paramName);


maskObj = Simulink.Mask.get(gcb);
lutoParam = maskObj.getParameter(lutobj_paramName);
bp1Param = maskObj.getParameter(bp1_paramName);
bp2Param = maskObj.getParameter(bp2_paramName);
tableParam = maskObj.getParameter(tbl_paramName);
set_param(underlyingLUTblock, 'DataSpecification', dataSpec);

if strcmp(dataSpec, 'Lookup table object')


bp1Param.Visible = 'off';
bp2Param.Visible = 'off';
tableParam.Visible = 'off';
lutoParam.Visible = 'on';
else

43-106
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

bp1Param.Visible = 'on';
bp2Param.Visible = 'on';
tableParam.Visible = 'on';
lutoParam.Visible = 'off';
end

43-107
43 Working with Block Masks

Share Explicit Breakpoint Data Between Lookup Tables

Many applications use the same breakpoints for different kinds of data. You can create multiple
lookup tables by sharing breakpoint data. For example, Exhaust Temperature, Air Pressure,
and Fuel Flow use the same breakpoints Torque and Engine Speed. Create multiple containers in
the Mask Editor for each lookup table and use the same breakpoints in each table.

43-108
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

43-109
43 Working with Block Masks

Visualize Multidimensional Data

To visualize multidimensional data, create Edit parameters for table data and breakpoints and enter
the values. To visualize the data for a dimension, select the parameter for that dimension from the
list.

43-110
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

Plot Multidimensional Data

Plot multidimensional lookup data in a contour, mesh, line, or surface plot. Click a table cell to
highlight the corresponding plot point. You can also create a plot from only a subset of dimensions or
slices.

43-111
43 Working with Block Masks

Lookup Table Control Menu Options

Plot Toolbar Options

Rotate: Rotate the plot, click the rotate icon and then click the plot to rotate the plot in 3-D view.

Panning Tool: Move the plot up and down and side to side using the pan tool. Double-click the pan
tool to center it or reset it to the original position.

Zoom: Zoom in or zoom out of the plot.

Home: Click the home icon to restore the view.

Settings

Spreadsheet: Show or hide the spreadsheet view of the lookup table data.

Heat Map: Show or hide the heat map in the spreadsheet view.

Plot: Select the desired plot. The available plots are Contour, Mesh, Line, and Surface. One
dimensional data can be plotted only with Line plot.

Add Lookup Table Control Programmatically

Add mask lookup table control programmatically by following these steps.

1. Get the mask object.


maskObj = Simulink.Mask.get(blkhndl);

43-112
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control

2. Add table data and breakpoint parameters to the mask.

maskObj.addParameter('Name', 'torque', 'Prompt , 'Torque:', 'Type', 'edit');


maskObj.addParameter('Name', 'speed', 'Prompt', 'Engine speed:', 'Type', 'edit');
maskObj.addParameter('Name', 'fuelflowtable', 'Prompt', 'Fuel Flow Map:', 'Type', 'edit');

3. Set the table properties.

lutControl.Table.Name = 'fuelflowtable';
lutControl.Table.Unit = 'kg/s ;
lutControl.Table.FieldName = 'Fuel Flow';

Set the breakpoint properties of first dimension.

lutControl.Breakpoints(1).Name = 'torque';
lutControl.Breakpoints(1).Unit = 'Nm';
lutControl.Breakpoints(1).FieldName = 'Torque';

Set breakpoint properties of second dimension.

lutControl.Breakpoints(2).Name = 'speed';
lutControl.Breakpoints(2).Unit = 'rpm';
lutControl.Breakpoints(2).FieldName = 'Speed';

4. Add lookup table control.

lutControl = maskObj.addDialogControl('Name','fuelflowlut','Type','lookuptablecontrol');

See Also

Simulink.dialog.LookupTableControl Simulink.dialog.LookupTableControl.Table
Simulink.dialog.LookupTableControl.Breakpoints

See Also

More About
• “Mask Callback Code” on page 43-12
• “Data Objects” on page 73-76

43-113
43 Working with Block Masks

Validate Input and Output Port Signals Using Port Constraints

You can validate compile-time signal attributes on the input and output ports of a masked block by
using port constraints. Compile-time signal attributes include data type, complexity, and dimensions.
You can define the rules to validate the data types, the complexity (real or complex), and dimensions
(scalar, vector, or 2-D matrix) of port signals. You can also add parameter conditions to the constraint.
The port constraints are active on the associated port only when it satisfies all the parameter
conditions. Port constraints allow you to check that signal attributes satisfy the specified rules
without having to write validation code. The mask identifies each port with port identifiers. You
associate the port constraint to a port identifier.

Explore Model

This example has a subsystem with two input ports and two output ports. The port constraints mypc,
mypc2, and mypc3 validate input and output signals.

Create Port Identifiers

First, create port identifiers to associate with the port constraint. To create port identifiers, right-
click subsys_mask > Edit Mask > Constraints > Port Identifiers. The Port Identifiers pane lists
the port identifiers for the masked Subsystem block subsys_mask.

Name: Enter the name for the port. This name uniquely identifies the port identifier in the mask.
Multiple ports can have the same port identifier.

Type: Select the type of the port as either Input or Output.

Identifier Type: Select the type of identifier as name or index. Select name if you want to identify
the ports using names. Select index, if you want to identify the ports using numbers.

Identifier(s): Enter the name of the port in case Identifier Type is name. Each port name in a block is
unique. Enter indices in case Identifier Type is index. You can map multiple ports to one port
identifier when the identifier type is index.

Note: If you select name as the Identifier Type, then you do not need to select the Type of port,
because each port name is unique.

Create Port Constraints

Next, create port constraints for the masked block. Create mask on the block. Go to Constraints >
Port. The list of port constraints appears in the Constraint Browser.

Constraint Name: Enter the name for the constraint.

43-114
Validate Input and Output Port Signals Using Port Constraints

Associations: Select the port from the list. The list of port identifiers created appears here. You can
select any port identifier to associate it with the constraint.

Rule: Set the rules for the constraint. You can set the permitted Data Types, Complexity, and
Dimensions for the port values. When you set the Data Type as fixed point, you can also select the
Signedness, Scaling, and Wordlength.

Parameter Conditions: Set mask parameter conditions for the constraints. The port constraints are
active on the associated port only when the port satisfies all the parameter conditions. To add
parameter conditions in the Parameter Conditions section, click Add. In Parameter Name, select
the parameter name. In Parameter Values, specify the permitted values as comma-separated list.

Diagnostic Level: If the port constraint is not satisfied, you can display an error or a warning
message during compile time. Select error or warning.

Diagnostic Message: You can specify an error or a warning message that will be displayed if the
port constraint validation fails.

Validate Port Constraints

Simulate the model. During the compilation stage, the compile process validates specified port
constraints for the associated port. If the port constraint validation fails, then the error or warning
message entered in the port constraint is displayed in the Diagnostic Viewer.

=== Simulation (Elapsed: 3 sec) ===


Error:Data at 'Input Port 1' of block 'slexMaskPortConstraints/subsys_mask' is invalid.
Caused by:
Expected data types for the port must be double. However, the port data type is single.
'To meet constraints of the mask'.
Error:An error occurred while propagating data type 'single' from 'slexMaskPortConstraints/In4',

43-115
43 Working with Block Masks

See Also

• “Custom Constraint for Mask Parameter” on page 43-71


• “Share Port Constraints Across Multiple Masked Blocks” on page 43-174
• “Validate Port Signals Among Ports of the Same Masked Block” on page 43-150

43-116
Graphical Icon Editor Overview

Graphical Icon Editor Overview

Create and edit mask icon of a block in a graphical environment. The features in the Graphical Icon
Editor help you to easily create icons. You can also create and edit the block mask icons using a set of
drawing commands. For more information, see “Mask Display and Initialization Commands” on page
43-13.

You can launch the Graphical Icon Editor from the Mask Editor. In the Mask Editor, select the Icon
tab. In the toolstrip, in the Authoring section, select Graphical. Using the Graphical Icon Editor, you
can:

• Preview the icon to check how it appears when the icon is horizontally stretched, flipped, or
scaled.
• Use Grid and Snap to grid to achieve precisely positioned icon elements.
• Name the elements and hide, lock, arrange, and regroup them in the icon.
• Use the Parts feature to render multiple variations of the same block. See “Render Multiple
Variations of Same Block Icon Using Parts” on page 43-134 for more information.
• Hide or unhide specific elements in the icon based on conditions on the block parameters or mask
parameters. See “Hide or Unhide Elements in the Icon Based on Block Parameters or Mask
Parameters” on page 43-140 for more information.
• Position each element on the icon relative to the canvas. See “Position Elements Relative to Other
Elements Using Layout Constraints” on page 43-143 for more information.

Edit Properties of Block Mask Icon and Its Elements


The graphical mode of authoring has a set of tabbed panes that help you to author block mask icons.
The options available in these tabbed panes are context sensitive.

43-117
43 Working with Block Masks

• Icon - Use the options in the Icon tab to control the properties of the icon such as the canvas
height and width.
• Element - All the properties specific to an element of the icon are available in the Element tab, for
example, alignment options and transformation options.

Icon Toolstrip

Section Property Functionality


Import Import Icon Part Import a part into the icon.
Import Icon Import a new icon.
Save Save Mask Save the mask.
Save image file with Select to save the mask icon with the model.
model
Authoring Mode Toggle editor Switch between the command and graphical editors.
Canvas Height Set the height of the canvas.
Width Set the width of the canvas.
Drawing Aids Grid and Snap to grid Enable these options to create precisely positioned
elements. These options help you to visualize the
number of pixels each element occupies in the icon.
Snap to grid allows enables you to snap the element
to the nearest grid line.
Grid Size Control the spacing between the grid lines.
Grid Color Select a color for the grid.
Smart Guides and Use smart guides and rulers to align or position an
Rulers element with respect to other elements in the icon
or the canvas.
Port Grid Display port grids to align elements with respect to
the ports.
Parts Add Add a new part to the icon.
Duplicate Duplicate an existing part.
Delete Delete an existing part.
Configuration Ports Define the number of ports on the left, right, top,
and bottom of the icon.
Dynamization Add Dynamism Add dynamic capabilities to the icon such as setting
visibility conditions, parametrize text, and, repeating
icon elements.
Preview Preview in Model Visualize the icon in its original scale and after
transformations such as scaling, horizontal and
vertical stretching, and clockwise and
counterclockwise rotation. You can also preview the
icon with parameter variations and width height
variations.

43-118
Graphical Icon Editor Overview

Element Toolstrip

Section Property Functionality


Shape Stroke, Stroke Width, Define the visual appearance of elements by
Bold, Italics, Underline, specifying these properties.
and Fill
Arrange Group and Ungroup Group and ungroup elements in the icon.
Flip Horizontal Flip the selected element horizontally.
Flip Vertical Flip the selected element vertically.
Order Send Backward Send the element one level backwards.
Send to Back Send the element to the back.
Bring Forward Bring the element one level forward.
Bring to Front Bring the element to the front.
Align Align Left Align the selected elements to the left.
Align Horizontal Center Align the selected elements to the horizontal center.
Align Right Align the selected elements to the right.
Align Bottom Align the selected elements to the bottom.
Align Top Align the selected elements to the top.
Align Vertical Center Align the selected elements to the vertical center.
Port Binding Bind Port or Unbind Port Bind or unbind port labels and icon elements to a
port. Binding the elements to the port enables to
inherit the style from the port. For example, the
color codes associated with the port of a block gets
inherited by the element. To bind the port and label
or element, select the port and the label or element.
Specify the port using Select Port. To find the
number of elements bound to a port, click the port,
which highlights all the elements bound to the port.
You can bind multiple elements to a port, but you
cannot bind a single element to multiple ports.
Select Unbind Port to unbind a label or element to a
port.

43-119
43 Working with Block Masks

Icon Properties Pane

Design tab
Section Property Functionality
Transform H and W Set the height and width of the canvas. Remove the
lock to change the height and width of the canvas
without preserving the aspect ratio between height
and width.
Icon Dynamization Visibility Set visibility condition for the icon. Visibility
conditions support JavaScript expressions only.
Render tab
Section Property Functionality
General Frame Rectangle — Set the frame shape to rectangle.
Custom — Customize the frame shape. You can
create an element of the desired shape and name it
as frame in the element browser. The icon takes the
shape of the element.
None — The default shape is retained and does not
show a frame for the block.
Transform Rotate Set this option to rotate the icon along with the
block.
Resize Off — Icon retains its original size when the block
resizes.
On — Icon resizes to fit to the block.
Shrink Only — Icon resizes to fit to the block
while shrinking but not otherwise.
Stroke Behavior Normalize Width On — Select this option to set the stroke width of all
the elements to 1 pixel.
Scale With Ports On — Select this option to scale the stroke width of
the element by the style of the line that is
connected to the port that is associated with this
element.
Scale on Zoom On — Select this option to increase the stroke width
when the canvas is zoomed in and decrease the
stroke width when the canvas is zoomed out.
Scale on Resize On — Scale stroke linearly on resizing icon.
Off — Maintain constant stroke width on resizing
icon.
Shrink Only — Scale stroke linearly when the
icon shrinks and do not scale when icon is
enlarged.
Appearance Foreground Allow — Change foreground color of the icon. The
foreground color can be changed by right-clicking
the context menu on the Simulink canvas.

43-120
Graphical Icon Editor Overview

Disallow — Retain the original color of the canvas


even when it is changed by right-clicking the
context menu on the Simulink canvas.
Inherit from Ports — Use the color of the port
associated with this element as the foreground
color.
Background Allow — Change background color of the icon. The
background color can be changed by right-clicking
the context menu on the Simulink canvas.
Disallow — Retain the original color of the canvas
even when it is changed by right-clicking the
context menu on the Simulink canvas.
Transparent — Use a transparent background for
the block. This option is selected by default for
Simscape blocks.

43-121
43 Working with Block Masks

Element Properties Pane

Design tab
Section Property Functionality
Transform X, Y Set the X and Y coordinates of the element.
W, H Set the width and height of the element. Remove
the lock to change the width and height of the
element without preserving the aspect ratio.
Specify an angle between -360 to 360 to rotate the
Angle
element to the specified angle.
Flip the element horizontally.
Flip horizontally
Flip the element vertically.
Flip vertically
Define the radius of an element's corners.
Corner radius
Format Fill Select a color to fill the element and enter a value
between 0 to 1 to adjust the transparency of the
color .
Stroke Select a stroke color and enter a value between 0 to
1 to adjust transparency of the stroke color.
Stroke style Enter the stroke width and select the stroke style.
Cap type Select the style for the end of the line or path.
Join type Select the style for the joints for the path element.
Start type Select the start arrow head type. Toggle to fill the
arrow head and then select the size of the arrow
head.
End type Select the end arrow head type. Toggle to fill the
arrow head and the select the size of the arrow
head.
Text Font Size Select the size of the text from the available
options.
Style Bold, italicize, underline, or strike through the text
on the icon.
Letter case Choose the font casing. You can also format the text
as superscript or subscript.
Fill Select the color for the text. You can also choose
the transparency of the text.
Stroke Select the color for the border of the text. You can
also choose the transparency for the border of the
text.
Render tab
Transform Rotate With Parent — Rotate the element with its
parent.

43-122
Graphical Icon Editor Overview

Design tab
Section Property Functionality
Readable — Maintain readable text element. The
text appears from left to right or bottom to top
without mirrored.
Fixed — Maintain orientation of the element even
if the block is rotated.
With Ports — Rotate the element along with the
port.
Resize On — Scale linearly along with parent when the
icon is resized.
Off — Maintain the size of the element when the
icon is resized.
Shrink Only — Shrink the element linearly when
its parent shrinks but maintains the size when its
parent is enlarged.
Adaptive — Scale port labels appropriately along
with the block.
Resize Limit Set the maximum limit to which the element is
resizable.
Horizontal Scaling On — Scale the element horizontally along with the
block.
Off — Maintain the width of the element.
Shrink Only — Shrink horizontally when its
parent shrinks but maintain the size when its
parent is enlarged.
Vertical Scaling On — Scale the element vertically along with the
block.
Off — Maintain the height of the element.
Shrink Only — Shrink vertically when its parent
shrinks but maintain the size when its parent is
enlarged.
Scale On Zoom On — Scale the element linearly when the canvas is
zoomed.
Off — Maintain the size of the element when the
canvas is zoomed.
Shrink Only — Shrink the element when the
canvas is zoomed out and maintain its size when
the canvas is zoomed in.
Stroke Behavior Normalize Width Inherit — Inherit the style from the icon. If the
element is part of a group then it inherits the style
from its parent element.
On — Set the stroke width of all the elements to 1
pixel.

43-123
43 Working with Block Masks

Design tab
Section Property Functionality
Scale With Ports Inherit — Inherit the style from the icon. If the
element is part of a group then it inherits the style
from its parent element.
On — Scale the stroke width of the element by the
style of the line that is connected to the port that is
associated with this element.
Scale On Zoom Inherit — Inherit the style from the icon. If the
element is part of a group then it inherits the style
from its parent element.
On — Scale the stroke width of the elements when
the canvas is zoomed out. Maintain a constant
stroke width when the canvas is zoomed in.
Scale On Resize Inherit — Inherit the style from the icon. If the
element is part of a group then it inherits the style
from its parent element.
On — Scale element's stroke linearly on resizing
icon.
Off — Maintain constant stroke width of the
elements on resizing icon.
Shrink Only — Scale stroke of the elements
linearly when the icon shrinks and do not scale
when icon is enlarged.
Element Dynamization
Visibility Set visibility condition for the element. Visibility
conditions support JavaScript expressions only.
Repeat Port Position Repeat elements on each port in the icon.

• Left Ports— Repeat element on all left ports


of the icon.
• Right Ports— Repeat element on all right
ports of the icon.
• Top Ports— Repeat element on all top ports of
the icon.
• Bottom Ports— Repeat element on all bottom
ports of the icon.
Set Position Set the alignment of the element. Align the element
to the Left of the block, Right of the
block, Top of the block, Bottom of the
block, or Center of the block. You can also
set the Offset for the elements from the port.
Text Dynamization

43-124
Graphical Icon Editor Overview

Design tab
Section Property Functionality
Visibility Set visibility condition for the text element.
Visibility conditions support JavaScript expressions
only.
Repeat Port Position Repeat elements on each port in the icon.

• Left Ports— Repeat element on all left ports


of the icon.
• Right Ports— Repeat element on all right
ports of the icon.
Set Position Set the alignment of the element. Align the element
to the Left of the block, Right of the
block or Center of the block. You can also set
the Offset for the elements from the port.
Text Dynamic Text • Parameter/Value— Enter mask parameter. It
returns the text or value during runtime. To see
the evaluated value of a block parameter on the
block icon, preview the icon on the Simulink
canvas.
• Width Contraction— Set the minimum number
of characters that should be available in the text
to add ellipses at the end of the text. The default
value is 3 characters.
• Height Contraction— Set the minimum
number of rows that should be available in a
multiline text to add ellipses at the end of the
line. The default value is 1 row.
Editing Behavior Edit Handler— Select Parameter, if you want to
edit the value of the block parameter in the block
icon itself and as a result the block parameter value
in the mask is also updated. Select MATLAB
Handler if you want to write MATLAB code to edit
the block parameter value.

43-125
43 Working with Block Masks

Design tab
Section Property Functionality
Appearance Inherit Background Color Select this option to set the fill color of a closed
shape to the background color selected from the
block context menu. The block background remains
transparent.

Clear this option to set the fill color of a closed


shape to the color selected from the Fill palette in
the Format section under the Design tab of the
Element Properties pane. If you select a fill color
first, the Inherit Background Color check box is
cleared by default.

To enable this option, set the Background of the


block to Transparent under the Render tab of the
Icon Properties pane and select a closed shape in
the Icon Editor canvas.

Drawing Tools
Tool Functionality
Path Create the desired shape using the Path tool.
Rect Draw a rectangle or square using the Rect tool.
Ellipse Draw an ellipse or circle using the Ellipse tool.
Line Draw lines using Line tool.
Curvature Simplify path creation. To draw curves, click on the canvas in two
separate locations to create anchor points. Drag the center point to
draw the curve. Drag the edge points of the curve to enlarge it. You
can also rotate the curve clockwise or anticlockwise to form loops.
Equation Tool Write equations using LaTeX markup. This tool is similar to the
equation tool present in MATLAB® and Simulink.
Edit Shape Use the Edit Shape tool to edit all supported shapes, such as
rectangles, ellipses, lines, and paths. To edit a shape, select the Edit
Shape tool in fixed palette above the canvas and click on an element.
All edit points that form the shape appear.
Scissor Split a path or element on the canvas at an anchor point or along a
segment. Click a point on the path you want to split. To modify the
object, select the anchor points that are created due to splitting.
Connector Connect two or more open paths. This connection creates a single path
element. Click the tool and drag to connect open paths.

Note Along with using these tools to draw shapes, you can use predefined shapes from Electrical,
Translational, and Rotational libraries. You can also use basic shapes like Cylinder, Triangle, Axis, and
Wave.

Element Browser

43-126
Graphical Icon Editor Overview

The element browser provides you the following functionalities:

• Identify each element using a unique name.


• Hide or unhide an element so that it does not get in the way while modifying other elements.
• Lock or unlock an element so that the position of the element is locked in the icon.
• Arrange elements within the group.
• Delete elements.
• Maintain a stack order for the elements.

Other Menu Options

Menu Property Functionality


Properties Transform Change the position, rotation, and corner radius of an
element in the icon.
Path Points X and Y Select an edit point in a shape, then modify the X and
Y coordinates of the edit point.
Point Type Change between smooth point and corner point.
Symmetric Handles Symmetrically move the handles of the edit point.

See Also

More About
• “Create and Edit Block Mask Icon” on page 43-128
• “Add Dynamic Behavior to Masked Icons” on page 43-134
• “Mask Editor Overview”

43-127
43 Working with Block Masks

Create and Edit Block Mask Icon


Create block mask icon using Graphical Icon Editor and Mask Drawing commands. You can toggle
between the two modes from Mask Editor. This example shows how to draw a block icon with the
following features using the Graphical Icon Editor.

• The icon has the elements as shown in the following image.


• Depending on the value of the block parameter FieldType, the permanent magnet or the spring
is be visible on the icon.
• The text that appears in the center of the icon takes the value of the block parameter
CenterText defined in the Mask Editor.

To create the block icon:

1 Add a Subsystem block. To create mask on the block, right-click the block, then select Mask >
Create Mask.
2 In the Icon tab, click Drawing Commands and select Graphical.
3 Draw the icon.

• Select Rect from the drawing tools and draw a square.

Note Enable the Grid and Snap to grid options to help shapes precisely align with each
other.
• Select the Line to draw a horizontal line touching the middle of the square.

Note Enable the Rulers and Smart Guides options to align the element relative to other
elements in the canvas.
• Select the square and line elements and make a copy of them. Flip the copies horizontally.

43-128
Create and Edit Block Mask Icon

• Select Ellipse to draw a circle joining the two squares.


• Add the text element DC in the center of the icon.
• To draw the magnet, select Rect and draw a rectangle. Make a copy of the rectangle and
place the rectangles next to each other. Fill the left rectangle.

• You can hide the magnet element to position the spring element in the place of the magnet. To
hide the magnet, select the magnet element, right-click, and select Hide. To draw the spring
element, select Inductor and place it on the canvas. Flip the inductor element vertically.
Adjust the edit points of the inductor element to form the loops of the spring.

43-129
43 Working with Block Masks

Note You can rename the elements in the Element Browser for easy identification. You can also
group or ungroup elements as per your requirements.
4 Bind ports to the icon.

• Enter the labels for the left and right ports using the text tool.
• Bind the ports and port labels of the icon to align the port labels to the port in the canvas so
that even when you resize the icon the ports and port labels remain together. To bind the port
to the port labels, select the port label, go to Port Binding and select the port. You can also
unbind the port.

5 Hide or unhide spring and magnet elements based on the block parameter condition.

Configure the spring element to be visible when the FieldType parameter is Wound and the
magnet element to be visible when the parameter is Permanent magnet

• Right-click the magnet element and select Conditional Visibility > Add Condition.
• Enter the condition FieldType=='Permanent magnet'.

43-130
Create and Edit Block Mask Icon

• Similarly, enter the condition FieldType=='Wound' for the spring element.


6 Parameterize text.

• Define the mask block parameter CenterText in the Mask Editor. The value of this block
parameter appears in the center of the icon.

• Select the text element and click Text Parameterization.


• Enter the mask block parameter name CenterText in Parameter/Value.

43-131
43 Working with Block Masks

Parameter/Value returns the text or value during runtime. To see the evaluated value of a
block parameter on the block icon, preview the icon on the Simulink canvas.
7 Preview the icon in Simulink.

43-132
Create and Edit Block Mask Icon

8 Click Save Mask to save the mask. Mask editor also allows you to save the icon separately as an
SVG file.

Note If you have changes in both Command Editor and Graphical Editor, you can save the
changes in either one of the modes.

See Also

More About
• “Graphical Icon Editor Overview” on page 43-117
• “Add Dynamic Behavior to Masked Icons” on page 43-134
• “Mask Editor Overview”

43-133
43 Working with Block Masks

Add Dynamic Behavior to Masked Icons


Using Graphical Icon Editor, you can add dynamic behavior to masked block icons:

• Render multiple variations of the same block icon using parts.


• Hide or unhide elements in the icon based on block parameters or mask parameters.
• Position icon elements relative to other elements using layout constraints.
• View the evaluated value of a block parameter on the block icon.
• Create a block icon that dynamically changes size when you resize the block.
• Repeat icon elements on multiple ports.

Render Multiple Variations of Same Block Icon Using Parts


Create icon parts in Graphical Icon Editor to store multiple variations of a block icon in a single file.
Each variation is a separate part and is visible based on conditions you place on the block or mask
parameters.

Consider a masked Subsystem block with the popup parameter set to portSelection with the
prompt No.of.Ports. The block icon changes based on the value you select for No.of.Ports in the
Block Parameters dialog box. If you specify the No. of Ports as 3, an image of a three-switch port
appears on the block icon. If you specify No. of Ports as 4, an image of a four-switch port appears on
the block icon

To create block icon variations using parts:

1 Create a mask on the Subsystem block.


2 In the Mask Editor, in the Controls pane, click Popup to create a popup parameter. In the
Property Editor pane, double-click the cell to the right of Type options and select List of
options. Add two rows, specify both the Description and Value for the first row as 3, and

43-134
Add Dynamic Behavior to Masked Icons

specify both the Description and Value for the second row as 4. Click Save.

3 In the Icon tab, click Drawing Commands and select Graphical.


4 Draw the icon image shown. Pin this part to make it the base part of the block mask icon. Click

to pin this part to make it the base part of the block mask icon. The elements in the base part
appear in all other parts, reducing the need to replicate icon elements.

Note You cannot modify the elements of the base part and their positions in other parts.
5
Click to create a new icon part. Use the graphical drawing commands to draw an icon with
four-switch port elements. . Double-click the part name to rename the part as
Four_switch_port.

43-135
43 Working with Block Masks

6
Click to duplicate the Four_switch_port part. Modify the duplicated part to show a three-
switch port. Rename the part as Three_switch_port.

7 To control when a particular part appears as the block icon, enter part's conditions based on the

corresponding block parameters by clicking . In this example, specify the conditions as


portSelection == 3 for Three_switch_port and portSelection == 4 for the part
Four_switch_port. Click Apply.

43-136
Add Dynamic Behavior to Masked Icons

8 Save the mask. In the Block Parameters dialog box, change the value of the No. of Ports
parameter. Observe how the block icon changes based on the value you select for the parameter.

Design Complex Block Icon Using Parts and Preview the Variations

You can design complex block icons using icon parts and combine the parts based on the parameter
conditions.

For example, each element in the icon of an integrator block is designed in individual parts and these
parts are combined based on the visibility condition specified for each part. This helps in avoiding a
cluttered canvas with all the icon elements. Each variation of the integrator block is assembled based
on the parameter settings and visibility conditions.

43-137
43 Working with Block Masks

This image shows a few of the Integrator block icon variations based on visibility conditions.

Preview the variations of the icon on Simulink canvas using the options Parameter Variations and
Width Height Variations along with other preview options.

43-138
Add Dynamic Behavior to Masked Icons

Click Parameter Variations and Width Height Variations to view all the permutation and
combination of the integer block based on parameters and conditional visibility.

43-139
43 Working with Block Masks

Hide or Unhide Elements in the Icon Based on Block Parameters or


Mask Parameters
Hide or unhide elements in the icon by applying certain conditions to the block parameters.

43-140
Add Dynamic Behavior to Masked Icons

For example, consider a Gain block icon with matrix values. The elements in the Gain block appear
and disappear based on the conditions set on the block parameters.

Set the condition in the following figure where the element uvec in the Gain block is visible only
when the value of the Multiplication parameter is Matrix_Ku_Vector.

Note Visibility conditions support JavaScript expressions only.

Set Visibility Condition Based on Evaluated Value of Parameters

You can access evaluated workspace variables as icon data. You can use these values to set
conditional visibility, layout constraints, or text parameterization. Additionally, you can retrieve the
integer values of enumerations assigned to the workspace variables.

The syntax to access the evaluated value of a mask workspace variable is:

43-141
43 Working with Block Masks

value@maskWorkspaceVariable === value

The syntax to access the evaluated value of an enumeration member is:

value@maskParameter === "enumerationValue"

For example, consider a Subsystem with a block icon having translational damper and rotational
damper elements. These elements must be visible based on an enumeration value. The enumeration
options are stored in an enumeration file Damper.m.

classdef Damper < Simulink.IntEnumType


enumeration
A(1)
B(2)
end
methods(Static)
function aOut = addClassNameToEnumNames()
aOut = false;
end
end
end

To set the visibility condition based on the enumerated value:

1 Create a mask on the Subsystem block.


2 In the Parameters & Dialog tab, create a mask popup parameter DamperSelection. Double-
click the cell to the right of Type options in the Property Editor pane to provide the list of
options for the popup parameter.
3 Select Use enumeration and then select Reference Enumeration file. Enter the name of the
enumeration file as Damper, omitting the extension. The enumeration options are displayed in
the table. Click Save.

Note The enumeration file must be available in MATLAB path.


4 In the Icon tab, click Drawing Commands select Graphical.
5 Insert both translational and rotational dampers onto the icon canvas.
6 Right-click on the translational damper and select Add Dynamization.
7 Set the visibility condition as value@DamperSelection===1 which will control the visibility of
the element in the block icon.

43-142
Add Dynamic Behavior to Masked Icons

8 Similarly set the visibility condition for the rotational damper as well.

Upon changing the options of the mask parameter, either the translational or the rotational damper is
displayed accordingly.

Position Elements Relative to Other Elements Using Layout


Constraints
Layout constraints help you to position each icon element relative to other icon elements on the
canvas or the canvas itself. To set layout constraints on the icon elements, select the element, right-
click and select Set Layout Constraints. In the Layout Constraints pane, pin both the Source
element and the Relative to element using the pinning panel. Specify the Offset. Click More to
specify complex conditions to position the elements.

Click Preview in Model to see the effects of layout constraints.

43-143
43 Working with Block Masks

You can also set complex conditions in layout constraints. For example, you can force the left bracket
of the matrix in the icon of the Gain block to be three pixels to the left of the first element of the
matrix.

To set this complex condition:

1 Right-click leftBracket and select Set Layout Constraints.


2 In the Layout Constraints pane, click More
3 Specify Right, Top and Bottom as matrix.left-3, matrix.top, andmatrix.bottom
respectively.

Text Parameterization
You can view the evaluated value of a block parameter on the block icon. Enter the block parameter
name or a placeholder in Parameter/Value that will return the text or value during simulation. To
see the evaluated value of a block parameter on the block icon, preview the icon on the Simulink
canvas.

For example, to display a parameter value on a block icon:

1 Create a mask on the block.


2 In the Parameters & Dialog pane, create an Edit parameter Speed and specify the value as
120.

43-144
Add Dynamic Behavior to Masked Icons

3 On the Icon tab, click Drawing Commands and select Graphical.


4 Create a text element in the canvas. Right-click the text element and select Add Dynamization.

5 In the Text Parameterization pane, in the Text pane, select Dynamic Text and enter the
parameter name Speed in Parameter/Value.

43-145
43 Working with Block Masks

6 Select Editing Behavior. Select Parameter in the Edit Handler list and specify the
Parameter Name as Speed.

Note In Edit Handler, select Parameter, if you want to edit the value of the block parameter
in the block icon itself and as a result the block parameter value in the mask is also updated.
Select MATLAB Handler if you want to write MATLAB code to edit the block parameter value.
7

8 Click Preview in Model and observe that the value of the parameter is displayed on the icon.

43-146
Add Dynamic Behavior to Masked Icons

Display Elements That Fit Size of Icon


You can create a block icon that dynamically changes sizes when you resize the block.

Select elements in the canvas, right-click and select Convert to First Fit. This groups the selected
elements and these elements that fits the size of the icon appears when you resize the icon.

For example, the following figure shows a Gain block with four elements of different sizes grouped
under a first-fit element. When you resize the block, the element that fits in the size of the Gain block
appears as the icon of the block.

43-147
43 Working with Block Masks

Repeat Icon Elements on Multiple Ports


You can repeat the same icon element dynamically on multiple ports without having to manually
repeat the element at each port and avoid clutter on the canvas.

For example, consider this block icon where the rectangle element is repeating on all the right ports
of the block.

To repeat the rectangle element across multiple ports:

1 Create a mask on the block.


2 On the Icon tab, click Drawing Commands and select Graphical.
3 Create a rectangle element in the canvas. Right-click the rectangle element and select Add
Dynamization.
4 Under Element Dynamization, select Repeat.
5 Select Right Ports from the Port Position list to repeat the element on the selected port.
6 Select Right of the Block from the Repeat Position list to align the element to the port.
7 Set the Offset as -2 to set the distance of the element from the canvas.

43-148
Add Dynamic Behavior to Masked Icons

Note The alignment of the elements and the offset is set to Right of the Block and -2 by
default.

See Also

More About
• “Mask Editor Overview”
• “Graphical Icon Editor Overview” on page 43-117
• “Create and Edit Block Mask Icon” on page 43-128

43-149
43 Working with Block Masks

Validate Port Signals Among Ports of the Same Masked Block

This example shows how to create cross port constraints to validate compile-time signal attributes
among ports of the same masked block. For example, you can set a constraint among the input and
output port signals of the masked block to have the same data type. The rules for the cross port
constraints are predefined. The available rules are Same Data Type and Same Dimension.
Additionally, you can also set parameter conditions. Each port in the masked block is identified by
port identifiers. The cross port constraint association is done through port identifiers.

Explore the Model

This example model multiplies the input signals and displays the product in the output. This models
uses cross port constraint feature to check if the input and output port signals have same dimensions
and datatypes. It has a subsystem block with two input ports and one output port. The input port
identifiers are 1 and Input_2. The output port identifier is 1. The cross port constraints
CheckDimensions and CheckDatatype are defined to validate the compile-time port signals of the
input and output ports for same dimensions and same datatypes respectively.

open_system("slexMaskCrossPortConstraints")

Create Port Identifiers

First, create port identifiers to associate with the port constraint. To create port identifiers, right-
click subsys_mask > Edit Mask > Constraints > Port Identifiers. The Port Identifiers pane lists
the port identifiers for the masked Subsystem block subsys_mask.

1 Enter the Name for the port as Input_1, Input_2, and Output_1.

43-150
Validate Port Signals Among Ports of the Same Masked Block

This name uniquely identifies the port identifier in the mask. Multiple ports can have the same port
identifier.

2 Select the Type of the port as either Input or Output.

3 Select the Type of Identifier as name or index.

Select name if you want to identify the ports using names. Select index, if you want to identify the
ports using numbers.

4 Enter 1, Input_2 in Identifier(s) as the Type of Identifier for these were selected as index.
Enter 1 in Identifier(s) as the Type of Identifier for this was selected as name in the previous step,
selecting the type of port is optional as the name for a port is unique. Each port name in a block is
unique. You can map multiple ports to one port identifier when the identifier type is index.

Note: If you select name as the Identifier Type, then you do not need to select the Type of port,
because each port name is unique.

Create Cross Port Constraints

Next, create cross port constraints for the masked block. Create cross port constraint
CheckDimensions, to validate the input signals for the same dimension. To create cross port
constraints, create mask on the block. Go to Constraints > Cross Port. The port constraint appears
in the Constraint Browser.

1. Enter the Constraint Name for the constraint as CheckDimensions.

2. In Parameter Conditions, select the Parameter Name as checkCrossPortDimensions and


enter the Parameter Values as on.

3. In Rule, select the Rule as Same Dimension.

4. In Associations, click add and select the Port Identifiers Input_1 and Input_2 to which the
constraint needs to be associated.

5. In Diagnostic Level, select error or warning if the port constraint is not satisfied, you can
display an error or a warning message during compile time.

6 Specify Diagnostic Message that will be displayed if the port constraint validation fails.

43-151
43 Working with Block Masks

Similarly, create another cross port constraints CheckDataType to check for same datatype among
all the ports Input_1, Input_2, and Output_1.

Validate Cross Port Constraints

Change the Dimension of the Input_1 and simulate the model. In the Diagnostic Viewer the
following message is displayed.

43-152
Validate Port Signals Among Ports of the Same Masked Block

The following two ports must have same dimensions. Caused by: Data at
port 1 of block
'slexMaskCrossPortConstraints/Mask_CrossPortConstraints', which is
'[1]' , must be the same as data at port 2 of block
'slexMaskCrossPortConstraints/Mask_CrossPortConstraints', which is
'[2]'. 'The inputs to the masked block must be of same dimensions'.

43-153
43 Working with Block Masks

Draw Mask Icon Using Drawing Commands

This example shows the various drawing commands used for drawing mask icons.

open_system('slexMaskDrawingExamples')

43-154
Unsafe Mask Callback Error

Unsafe Mask Callback Error

In this example, the "System Configurator" is a masked subsystem that is used to configure the "Gain"
block. Such use of Mask callbacks, where the callback modifies entities outside of its scope may
result in unexpected behavior.

open_system("slexMaskUnsafeCallbacksErrorExample")

43-155
43 Working with Block Masks

Organize Mask Initialization and Callbacks in a MATLAB File

You can organize mask initialization and mask callback code in a separate MATLAB® class file. By
using a separate MATLAB file you can:

• Use code debugging capabilities such as breakpoints in MATLAB Editor.

• Reduce the memory footprint of the masks since the callbacks are stored in a .m file instead of in
memory.

• Edit the mask callback code using either Mask Editor or MATLAB Editor.

Explore the Model

This example model implements the equation y = u*gain + bias through mask initialization and
callbacks. There are three mask parameters, gain, bias, and EnableBias. The value of
EnableBias is set by selecting or clearing the Enable Bias check box. In the mask initialization
section, the value of EnableBias is retrieved from the mask workspace. If it is not enabled, then the
value of bias is set to 0. In the mask parameter callback section, if EnableBias is enabled, then the
property Enabled of all the parameters are set to on. Otherwise the Enabled property of all
parameters are set to on except Enable Bias parameter. In the mask control callback section, you
can set the Enabled property for all parameters to on clicking the Reset Visibility button.

open_system("slexMaskCallbackFileExample.slx");

43-156
Organize Mask Initialization and Callbacks in a MATLAB File

Author Mask Callback Code in MATLAB File

You can organize mask initialization and callback code in a single MATLAB file. The name of the
callback file and the name of the class that the function belongs to must be the same. For example, if
the name of the callback file is mask_cb_file_example then the name of the class file must be
mask_cb_file_example. The MATLAB file must be located in the MATLAB path.

43-157
43 Working with Block Masks

Write Mask Initialization Code

In this example, the mask initialization code sets the biasValue to 0 if the parameter EnableBias is
cleared.

To view the mask initialization written for this example, right-click Masked Block Using a Mask
Callback File. In the context menu, click Mask > Edit Mask. On the Code tab, the
mask_cb_file_example file contains the initialization and callback code for the model.

The mask initialization function should be in the following format:


function MaskInitialization(maskInitContext)
blkHandle = maskInitContext.BlockHandle; % Block Handle of this block
maskObj = maskInitContext.MaskObject; % Mask object of this masked block
maskWorkspace = maskInitContext.MaskWorkspace; % Use this to work with mask workspace
disp('Mask initialization triggered');
% Get value of 'EnableBias' parameter using mask workspace get() API.
enableBiasValue = maskWorkspace.get('EnableBias');
if ~enableBiasValue
% Set 'BiasValue' parameter value to 0 using mask workspace set() API.
maskWorkspace.set('biasValue',0);
end
end

• The method that executes the mask initialization code must be Static.

• Mask initialization function must be named as MaskInitialization.

• Input argument to the mask initialization function is a struct with these properties:

BlockHandle: Handle of the block.

MaskObject: Mask object of the masked block.

MaskWorkspace: Use this property to access the mask workspace:


maskWorkspace = maskInitContext.MaskWorkspace;

Note: The properties of the input argument of the initialization function are case sensitive.

43-158
Organize Mask Initialization and Callbacks in a MATLAB File

• Use set and get methods along with the MaskWorkspace property to set and retrieve the values
of MaskWorkspace variables.

Write Mask Parameter Callback Code

In this example, the parameter callback code enables or disables the Bias parameter in the mask
dialog on enabling or disabling the Enable Bias.

function EnableBias(callbackContext)
blkHandle = callbackContext.BlockHandle; % Block Handle of this block
maskObj = Simulink.Mask.get(blkHandle);
parameterObj = callbackContext.ParameterObject; % Parameter object for 'EnableBias'.
disp('EnableBias callback triggered');
% Set the 'Enabled' property for each parameter
if strcmp(get_param(blkHandle,'EnableBias'),'on')
maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
else
maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'off';
end
end

• The function name of the parameter callback must be same as the parameter name.

• Input argument to the mask parameter callback function is a struct with these properties.

BlockHandle: Block handle of the block.

MaskObject: Mask object of the masked block or the dialog control object of the dialog control.

• Use set_param and get_param to set and retrieve the values of parameters.

Write Mask Dialog Control Callback

In this example, the dialog control callback code is written to enable all the mask parameters on
clicking the ResetVisibility button in the mask dialog control.

The control callback code should be in the following format:

function ResetVisibility(callbackContext)
blkHandle = callbackContext.BlockHandle; % Block Handle of this block
maskObj = Simulink.Mask.get(blkHandle);
resetButtonObj = callbackContext.DialogControlObject; % Dialog Control object for 'ResetVisi
disp('ResetVisibility button callback triggered');
% Reset mask enables.
maskObj.getParameter('gainValue').Enabled = 'on';
maskObj.getParameter('biasValue').Enabled = 'on';
maskObj.getParameter('EnableBias').Enabled = 'on';
end

• The function name of the control callback must be same as the name of the property set by the
dialog box control.

• Input argument to the mask control callback function is a struct with these properties.

43-159
43 Working with Block Masks

BlockHandle: Block handle of the block.

DialogControlObject: Dialog control object of the dialog control.

• Use set_param and get_param to set and retrieve the values of parameters.

Migrate Existing Callback Code to MATLAB File

You can migrate existing callback code to a MATLAB file. A classdef wrapper is created and mask
functions are converted to member functions. You will have to inspect the mask initialization code and
make corrections before executing it. For example, you must modify the code to set and get values of
variables from the mask workspace in the mask initialization section using the set and get methods.

To migrate the existing callback code, right-click the masked block, from the context menu select
Mask > Edit Mask. In the Code tab, click Switch Callback Mode and select Callback File.

In the dialog box, click Yes to migrate the existing callback and save. Click No, to save mask
callbacks in a separate MATLAB file and without migrating the code. Save the mask to save the
callback file.

Note: If you want to store the mask callback in the mask object rather than in a separate MATLAB
file, go to Mask Editor, click Code > Switch Callback Mode > select Mask.

Save Callback File with the Model

You can also package the callback file along with the model. Use the option Save callback file with
model in the toolstrip. You must also save the model to package the callback file along with the
model.

Note: To edit the callback file saved with the model, you must load the model. Use the Open option in
the toolstrip to open the callback file in MATLAB editor.

43-160
Organize Mask Initialization and Callbacks in a MATLAB File

43-161
43 Working with Block Masks

Simulink Masking Examples

The slexMaskingExamples model contains a set of conceptual examples that demonstrate


capabilities of Simulink® Masking.

43-162
Manage Interface Connector with Mask Initialization and Block Callbacks

Manage Interface Connector with Mask Initialization and Block


Callbacks

This example shows how to manage Interface Connector with mask initialization and block callbacks.
This example illustrates

• How to do edit time operations outside of the masked subsystem using mask initialization.

• How to check for structural errors at update diagram time using mask initialization code

• How to invoke the mask initialization code of another block from a callback

Explore the Model

This example consists of the following blocks

Interface In: Accepts a signal name identifying the name of a root Inport, which the Interface In
reads.

Interface Out: Accepts a signal name identifying the name of root Outport block to write to, multiple
Interface Out blocks can write to the same root Outport and will be automatically merged.

Interface Connector: Manages the connections from the Interface In and Interface Out blocks to
the root Inports.

Interface In blocks can be placed within virtual subsystems in your model and the signal name
specified within the Interface In block will come from a root Inport block with the same name.
Similarly, Interface Out blocks can be placed within virtual subsystems in your model and the signal
name specified within the Interface Out block will write to a root Outport block with the same name.
Multiple Interface Out blocks with the same signal name will write to the same root Outport via a
Merge block.

The Interface Connector block which must reside in the root window of your block diagram. The
Interface Connector dynamically manages connections for the Interface In and Interface Out blocks.
As the Interface In and Interface Out blocks are edited, the Interface Connector automatically
updates.

open_system("slexMaskSelfModifiableInterfaceBlocks.slx")

43-163
43 Working with Block Masks

Limitations

As a general rule, mask blocks which have "[x] Allow library block to modify its contents" selected
(mask self-modifiable blocks) are allowed to edit their contents via the mask initialization action.

43-164
Manage Interface Connector with Mask Initialization and Block Callbacks

When they modify the contents, the interface of the masked block should not change during update
diagram. Furthermore, the mask initialization code must not modify structure outside of the mask
block. The mask initialization action is always invoked during update diagram. Mask initialization
action of mask self-modifiable can change the masked block interface or make modifications outside
of the contents of the masked block during edit only. This example illustrates this. This model
contains Variant blocks. During model compile the variant conditions are analyzed before Simulink
runs the mask initialization action code, thus the structure of the model cannot change when the
mask initialization action is run by model compile. This example illustrates how to do all mask
initialization actions at edit time. During compile the mask initialization code of the Interface
Connector validates that the connections are valid and if not, an error is produced aborting the model
compile.

43-165
43 Working with Block Masks

Unsafe Nested Callback

This example shows a subsystem Simplified Multi Gain System containing another subsystem
Multi Gain System. The objective is to tweak the parameter of the gain block in Multi Gain
System through the mask parameters of Simplified Multi Gain System.

Section 1 Title

open_system("slexMaskUnsafeNestedUsageErrorExample.slx")

43-166
Preserve Tunability of Parameters That Are Modified or Created in Mask Initialization

Preserve Tunability of Parameters That Are Modified or


Created in Mask Initialization

A desirable feature of code generated from a model is the ability to tune variables to different values.
To achieve this, user-defined variables in the model must be present in the generated code. If a model
contained blocks with mask initialization commands that creates a new variable or modified an
existing mask dialog parameter in the mask initialization, and if that parameter or variable is
referenced in a child block, the values of the mask parameter or variable were in-lined in the
generated code. The parameters were not tunable even if they referred to a workspace variable.

You can preserve the tunability of the mask parameters. The expressions corresponding to mask
parameters referenced in the child block appear in the generated code. The expression is generated
even if the parameters are created in mask initialization section of the top-level mask. The tunability
of these parameters is retained only if the mask initialization code is created using a mask callback
file and the parameter value is defined in the format mentioned in the example. See “Organize Mask
Initialization and Callbacks in a MATLAB File” on page 43-156.

Explore the Model

This example shows two scenarios in which the tunability of parameters is preserved in the generated
code.

The first scenario demonstrates how tunability is preserved when a parameter is modified in the mask
initialization code. The model contains a Subsystem block DataRounding, which rounds numerical
data by a preferred rounding method. The value of the mask parameter is modified in the mask
initialization code according to the selected rounding method in mask dialog box.

The second scenario demonstrates how tunability is preserved when a parameter is created in the
mask initialization code. The model contains a Subsystem block CalculateForce which calculates
force as the product of mass and acceleration. The parameter outForce is created in the mask
initialization code to calculate force.

open_system("slexMaskPreserveTunabilityOfMaskInitVariable.slx")

43-167
43 Working with Block Masks

Preserve Tunability of Mask Parameters Modified in Mask Initialization Code

Preserve the tunability of a parameter in generated code if the mask parameter is modified in the
mask initialization code.

1. Create a mask on the Subsystem block DataRounding.

2. In the Mask Editor, create an edit parameter Data and a popup parameter DataRoundingMode
with options floor, Round, and Nearest.

43-168
Preserve Tunability of Parameters That Are Modified or Created in Mask Initialization

3. In the Code tab, enter the Callback File Name as maskInitFuncDataChange. Include this code
in the editor.

classdef maskInitFuncDataChange
methods(Static)
function MaskInitialization(maskInitContext)
ws = maskInitContext.MaskWorkspace;
ws.set('Data','maskInitFuncDataChange.updateData','Data', 'DataRoundingMode');
end
function outData = updateData(inData, inRoundingMode)
switch(inRoundingMode)
case 1
outData = floor(inData);
case 2
outData = round(inData);
case 3
outData = nearest(inData);
otherwise
outData = inRoundingMode;
end
end
end
end

The function updateData updates the parameter Data based on the selected DataRoundingMode.

4. Click Save Mask.

5. Double-click the block DataRounding. In the Block Parameters dialog box, enter the value for
Data as 5.3 and select the Data Rounding Mode as Round. Click OK.

6. Simulate the model and generate code.


/* Model step function */
void slexMaskPreserveTunabilityOfMaskInitVariable_step(void)

43-169
43 Working with Block Masks

{
/* Outport: '<Root>/Out1' incorporates:
* Constant: '<S1>/Constant'
*/
switch ((int32_T)slexMaskPreserveTunabilityOfM_P.DataRounding_DataRoundingMode)
{
case 1:
slexMaskPreserveTunabilityOfM_Y.Out1 =
slexMaskPreserveTunabilityOfM_P.DataRounding_Data;
slexMaskPreserveTunabilityOfM_Y.Out1 = floor
(slexMaskPreserveTunabilityOfM_Y.Out1);
break;
case 2:
slexMaskPreserveTunabilityOfM_Y.Out1 =
slexMaskPreserveTunabilityOfM_P.DataRounding_Data;
slexMaskPreserveTunabilityOfM_Y.Out1 = rt_roundd_snf
(slexMaskPreserveTunabilityOfM_Y.Out1);
break;
case 3:
slexMaskPreserveTunabilityOfM_Y.Out1 =
slexMaskPreserveTunabilityOfM_P.DataRounding_Data + 0.5;
slexMaskPreserveTunabilityOfM_Y.Out1 = floor
(slexMaskPreserveTunabilityOfM_Y.Out1);
break;
default:
slexMaskPreserveTunabilityOfM_Y.Out1 =
slexMaskPreserveTunabilityOfM_P.DataRounding_DataRoundingMode;
break;
}

/* End of Outport: '<Root>/Out1' */


}

Observe that tunability is preserved for the mask parameter Data in the generated code.

Preserve Tunability of Mask Parameters Created in Mask Initialization Code

In the example model, the subsystem block CalculateForce calculates force. The parameter
outForce is created in the mask initialization code to calculate force as the product of mass and
acceleration. The generated code contains an expression for the parameter outForce.

1. Create a mask on the subsystem CalculateForce.

2. In the Mask Editor, create edit parameters mass and acceleration.

43-170
Preserve Tunability of Parameters That Are Modified or Created in Mask Initialization

3. In the Code tab, enter the Callback File Name as maskInitFuncNewVariable. Include this in
the editor.

classdef maskInitFuncNewVariable
methods(Static)
function MaskInitialization(maskInitContext)
ws = maskInitContext.MaskWorkspace;
ws.set('force','maskInitFuncNewVariable.calculateForce', 'mass', 'acceleration');
end
function outForce = calculateForce(inMass, inAcceleration)
outForce = inMass * inAcceleration;
end
end
end

The function calculateForce takes the arguments mass and acceleration and calculates the
outForce as the product of mass and acceleration. See Author Mask Callback Code in MATLAB
File section in “Organize Mask Initialization and Callbacks in a MATLAB File” on page 43-156 for
more information about setting and retrieving values from mask workspace.

4. Click Save Mask.

5. Double-click the block CalculateForce. In the Block Parameters dialog box, enter the value for
Mass as 100 and Acceleration as 10. Click OK.

6. Simulate the model and generate code.


/* Model step function */
void slexMaskPreserveTunabilityOfMaskInitVariable_step(void)

43-171
43 Working with Block Masks

{
/* Outport: '<Root>/Out2' incorporates:
* Constant: '<S1>/Constant'
*/
slexMaskPreserveTunabilityOfM_Y.Out2 =
slexMaskPreserveTunabilityOfM_P.CalculateForce_mass *
slexMaskPreserveTunabilityOfM_P.CalculateForce_acceleration;
}

Observe that the expression corresponding to the variable is generated in the code.

Limitations

• Tunability will not be preserved if the function that modifies or creates the mask parameter
contains Simulink® APIs such as get_param and set_param.

• Tunability will not be preserved if the same mask parameter is modified using a simple set
API(ws.set('Parameter1', '5'). Tunability of the mask parameter is retained only if the variable is
modified using ws.set(' modified/new variableName ', ' outpuitFunction ', '
maskParamName1 ', ' maskParamName2 ') format.

• To preserve tunability, write any such code involving get_param and set_param inside the mask
initialization function and pass the value as an argument to the function which modifies/creates
mask parameter value.

• The function call to modify or create mask parameters must be in the following format:

i. The first argument of the function call must be the mask parameter that you want to modify or
create. This argument must be a string.

ii. The second argument must be the function that modifies or creates the mask parameter and it
should be in the form className. functionName. The function must be static.

iii. The next set of arguments must be mask parameter names that are passed to the static function.
These parameters must be strings.

iv. Other values you want to pass to this function must not be strings. You must pass the argument
names or values.

Example:

classdef mycallback
methods(Static)
function MaskInitialization(maskInitContext)
ws = maskInitContext.MaskWorkspace;
constVal = 5;
ws.set('newVar','mycallback.update','maskParam1', constVal);
end
function out = update(in1, in2)
out = in1+in2;
end
end
end

43-172
Preserve Tunability of Parameters That Are Modified or Created in Mask Initialization

See Also

“Tune Mask Enumeration Parameters - Popup and Radio Button” on page 43-93| “Design a Mask
Dialog Box”

43-173
43 Working with Block Masks

Share Port Constraints Across Multiple Masked Blocks

This example shows how to create a port constraint and share it across masks of different blocks in
the same model or different models. The port constraint definition is saved in an XML file and can be
associated with ports across multiple masked blocks. The XML file must be available on the
MATLAB® path.

Port constraints enables you to validate compile-time signal attributes on the input and output ports
of a masked block without having to write validation code. Sharing of port constraints eliminates the
need to repeatedly update multiple blocks, making maintenance and management of constraints more
efficient. Defining a shared constraint in an XML file enables you to compare the constraint definition
with a previous version.

Explore the Model

Open the model slexMaskSharedPortConstraint. The model has two subsystem blocks,
Engine_1 and Engine_2. The shared port constraint ScalarInt8SharedConstraint is saved in
an XML file sharedPortChecks.xml. The constraint validates whether the signals at input ports at
index 1 of the subsystem blocks are int8, scalar, and real at compile time.

open_system("slexMaskSharedPortConstraint");

Create Shared Port Constraint

To create a port constraint ScalarInt8SharedConstraint in an XML file


sharedPortChecks.xml:

43-174
Share Port Constraints Across Multiple Masked Blocks

1. Create a Subsystem block with one input port In1 port and one output port Out1. Name the block
Engine_1.

2. Create a mask on the block Engine_1.

3. In the Mask Editor, create a checkbox parameter Battery Check. The parameter Battery
Check is created to add the parameter condition to the constraint.

4. In the Constraints tab, click New and enter sharedPortChecks as the name of the XML file.

5. In the toolstrip, click Port to create a port constraint. Specify Constraint name as
ScalarInt8SharedConstraint and set the rule for Data Type as int8, Complexity as real, and
Dimension as scalar.

6. Set the Parameter Conditions. Click Add to select the parameter BatteryCheck in Parameter
Name and set the value to on. The signal at the port is validated only when the parameter condition
is satisfied.

7. Select error from the Diagnostic Level list and enter a diagnostic message in the Diagnostic
Message box.

8. Create a port identifier for the input port with index 1. Click Port Identifiers from the tool strip.
In the Port Identifiers section, click Add. Specify Name as Eng_1_Inport_1, select Input from
the Type list, select index from the Identifier Type list, and specify Identifier(s) as 1.

9. To associate the port at index 1 with the constraint using the port identifier Eng_1_Inport_1,
select the port identifier Eng_1_Inport_1 in Associations.

10. Save the mask.

43-175
43 Working with Block Masks

Share Port Constraint

The port constraint ScalarInt8SharedConstraint is created in the XML file


sharedPortChecks.xml in the previous section. To associate this port constraint with another
subsystem block Engine_2 in the example model:

1. Create a subsystem block with one input port In1 with index 2 and one output port Out1 with
index 2. Name the block as Engine_2.

2. Create a mask on the subsystem block Engine_2.

3. In the Mask Editor, create a checkbox parameter Battery Check.

4. In the Constraints tab, click Load and select the XML file sharedPortChecks.xml to load the
port constraint ScalarInt8SharedConstraint.

5. Create a port identifier for the input port with index 1. Click Port Identifiers from the tool strip.
In the Port Identifiers section, click Add. Specify Name as Eng_2_Inport_1, select Input from
the Type list, select index from the Identifier Type list, and specify Identifier(s) as 1.

6.To associate the port constraint to the port identifier, select the port Eng_2_Inport_1 in
Associations.

Note: The port constraint definition is shared across blocks but you must associate port identifiers
and association for each block.

Validate Port Constraint

To validate the associated port constraints:

1. Double click the input port In1 of the Engine_1 block.

2. In the Signal Attributes tab, change the Data type to int16 and click OK

43-176
Share Port Constraints Across Multiple Masked Blocks

3. Simulate the model. The Diagnostic Viewer displays the message.

Data at 'Input Port 1' of block 'slexSharedPortConstraint/Engine_1' is


invalid. Caused by: Expected data types for the port must be int8.
However, the port data type is int16. 'The signal at the battery component is incorrect'.
Component:Simulink | Category:Model error An
error occurred while propagating data type 'int16' from
'slexSharedPortConstraint/In1', 'Output Port 1'. Component:Simulink |
Category:Model error

4. Reset the Data type to int8 and click OK so that the validation is successful for the block
Engine_2.

5. To demonstrate sharing of port constraints with the block Engine_2, double-click the input port
In1 of the Engine_2 block.

6. In the Signal Attributes tab, change the signal attribute to int16 and click OK.

7. Simulate the model. The Diagnostic Viewer displays the message.

Data at 'Input Port 1' of block 'slexSharedPortConstraint/Engine_2' is


invalid. Caused by: Expected data types for the port must be int8.
However, the port data type is uint16. 'The signal at the battery component is incorrect'.
Component:Simulink | Category:Model error An
error occurred while propagating data type 'uint16' from
'slexSharedPortConstraint/In2', 'Output Port 1'. Component:Simulink |
Category:Model error

See Also

• “Custom Constraint for Mask Parameter” on page 43-71


• “Validate Input and Output Port Signals Using Port Constraints” on page 43-114
• “Validate Port Signals Among Ports of the Same Masked Block” on page 43-150
• Simulink.Mask.SharedConstraintFile
• Simulink.Mask.Constraints.convertMatToXML

43-177
44

Creating Custom Blocks

• “Types of Custom Blocks” on page 44-2


• “Comparison of Custom Block Functionality” on page 44-5
• “Design and Create a Custom Block” on page 44-12
• “Integrate Python GPS Text Message Parsing Algorithms in Simulink” on page 44-29
44 Creating Custom Blocks

Types of Custom Blocks

In this section...
“MATLAB Function Blocks” on page 44-2
“MATLAB System Blocks” on page 44-2
“Subsystem Blocks” on page 44-3
“C Caller Block” on page 44-3
“C Function Block” on page 44-3
“S-Function Blocks” on page 44-3
“Masked Blocks” on page 44-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 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.
• The Fcn block allows you to use a MATLAB expression to define a single-input, single-output
(SISO) block.

Each of these blocks has advantages in particular modeling applications. For example, you can
generate code from models containing MATLAB Function blocks, whereas you cannot generate code
for models containing a Fcn block.

MATLAB System Blocks


A MATLAB System block allows you to use System objects written with the MATLAB language to
define custom functionality. These blocks are a good starting point for creating a custom block if:

• You have an existing System object that models the custom functionality.
• You find it easier to model custom functionality using the MATLAB language than using a Simulink
block diagram.
• The custom functionality includes discrete dynamic states.

44-2
Types of 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
handwritten 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 box.
2 Placing the block in a library to prohibit modifications and allow for easily updating copies of the
block.

For more information, see “Custom Libraries” and “Author Block Masks”.

C Caller Block
The C Caller block allows you to integrate C code into Simulink blocks. These blocks serve as a good
starting point for creating a custom block if:

• You have existing C code that models custom functionality.


• Your C functions do not read or write global/static variables.
• You want blocks to easily integrate with other Simulink features, such as Simulink Coverage,
Simulink Test, and Simulink Coder.
• You are not modeling dynamic systems.

C Function Block
The C Function block allows you to integrate C code into Simulink blocks. These blocks serve as a
good starting point for creating a custom block if:

• You have existing C code that models custom functionality.


• You want to call multiple C functions from the block, or call C functions conditionally.
• You want to include C code to preprocess and postprocess data before and after calling C
functions.
• You want to specify different code for simulation and code generation.
• You are not modeling dynamic systems with continuous states.

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:

44-3
44 Creating Custom Blocks

• You have existing MATLAB, C, or C++ code that models custom functionality.
• You use 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.

• 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 “Author Blocks Using C MEX S-Functions”.)
• The S-Function Builder block assists you in creating a C MEX S-function or a wrapper function to
incorporate legacy C or C++ code. (See “Author Blocks Using C MEX 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 “Use S-Function Target for Model or Subsystem” (Simulink
Coder) in the Simulink Coder User's Guide for details and limitations on using the S-function target.

Masked Blocks
You can customize any block by adding a mask to it. A mask is a custom interface to the block. You
can customize a block using a mask in many ways, such as:

• Change the block appearance.


• Hide some or all of the parameters from the user of the block.
• Customize block parameters.

To learn more about masked blocks, see “Author Block Masks”.

See Also
Fcn | Interpreted MATLAB Function | C Caller | C Function | Level-2 MATLAB S-Function | MATLAB
Function | MATLAB System | S-Function | S-Function Builder | Simulink Function | Subsystem

More About
• “Comparison of Custom Block Functionality” on page 44-5
• “Design and Create a Custom Block” on page 44-12

44-4
Comparison of Custom Block Functionality

Comparison of Custom Block Functionality


In this section...
“Model State Behavior” on page 44-6
“Simulation Performance” on page 44-6
“Code Generation” on page 44-8
“Multiple Input and Output Ports” on page 44-9
“Speed of Updating the Simulink Diagram” on page 44-9
“Callback Methods” on page 44-10
“Comparing MATLAB S-Functions to MATLAB Functions for Code Generation” on page 44-11
“Expanding Custom Block Functionality” on page 44-11

When creating a custom block, consider:

• Does the block model continuous or discrete state behavior on page 44-6?
• Is the simulation performance on page 44-6 important?
• Do you need to generate code on page 44-8 for a model containing the custom block?

This table shows how each custom block type addresses the three concerns.

Modelling Considerations

Custom Block Type Model State Dynamics on Simulation Performance Code Generation on page
page 44-6 on page 44-6 44-8
Interpreted MATLAB No Less fast Not supported
Function
Level-2 MATLAB S- Yes Less fast Requires a TLC file
Function
MATLAB Function No Fast Supported with exceptions
MATLAB System Yes Fast Supported with exceptions
S-Function Yes Fast Requires a TLC file or non-
inline S-Function support
C Caller No Fast Supported
C Function Yes Fast Supported
S-Function Builder Yes Fast Supported
Simulink Function Yes Fast Supported
Subsystem Yes Fast Supported
Fcn No Very fast Supported

For detailed design of custom blocks, consider:

• Does the custom block need multiple input and output ports on page 44-9?
• What are the callback methods on page 44-10 to communicate with the Simulink engine and
which custom blocks let you implement all or a subset of these callback methods?

44-5
44 Creating Custom Blocks

• How important is the effect of the custom block on the speed of updating the Simulink diagram on
page 44-9?

Model State Behavior


You need to model the state behavior for a block that requires some or all of its previous outputs to
compute its current outputs. See “State variables” for more information.

Custom Block Type Notes


Fcn, Interpreted Does not allow you to model state behavior.
MATLAB Function, C
Caller
MATLAB Function, C Allows you to model a discrete state using persistent variables.
Function
Level-2 MATLAB S- Allows you to model both continuous and discrete state behavior using the
Function ContStates or Dwork run-time object methods in combination with block
callback methods. For a list of supported methods, see “Level-2 MATLAB S-
Function Callback Methods” in “Write Level-2 MATLAB S-Functions”.
MATLAB System Allows you to model discrete state behavior using DiscreteState properties
of the System object, in combination with block callback methods. This block
uses System object methods for callback methods: mdlOutputs (stepImpl,
outputImpl), mdlUpdate (updateImpl), mdlInitializeConditions
(resetImpl), mdlStart (setupImpl), mdlTerminate (releaseImpl). For
more information see “What Are System Objects?”.
C MEX S-Function, Allows you to model both continuous and discrete state behavior in
S-Function Builder combination with block callback methods. For more information, see “Callback
Methods for C MEX S-Functions”
Simulink Function Communicates directly with the engine. You can model the state behavior using
appropriate blocks from the continuous and discrete Simulink block libraries.
When multiple calls to this function originate from different callers, the state
values are also persistent between these calls. For more information, see “Call
a Simulink Function Block from Multiple Sites” on page 10-165.
Subsystem Communicates directly with the engine. You can model the state behavior using
appropriate blocks from the continuous and discrete Simulink block libraries.

Simulation Performance
For most applications, all custom block types provide satisfactory simulation performance. Use the
Simulink profiler to get the actual performance indication. See “How Simulink Profiler Captures
Performance Data” on page 34-5 for more information.

The two categories of performance indication are the interface cost and the algorithm cost. The
interface cost is the time it takes to move data from the Simulink engine into the block. The algorithm
cost is the time it takes to perform the algorithm that the block implements.

Custom Block Type Notes


Fcn Has the highest simulation performance. The block is tightly integrated with
the Simulink engine and optimized for simulation and code generation.

44-6
Comparison of Custom Block Functionality

Custom Block Type Notes


Interpreted MATLAB Has a slower performance due to the interface, but has the same algorithm
Function 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, the
performance can be substantially slow.
Once the data has been converted, the MATLAB execution engine executes the
algorithm. As a result, the algorithm cost is the same as for MATLAB function.
Level-2 MATLAB S- Incurs the same algorithm costs as the Interpreted MATLAB Function block,
Function but with a slightly higher interface cost. Since 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 execution engine for each block method you implement, whereas the
Interpreted MATLAB Function block calls the MATLAB execution engine only
for the Outputs method.
MATLAB Function Performs simulation through code generation and incurs the same interface
cost as other Simulink built-in 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 the MATLAB
function run at about the same speed.
If the MATLAB Function block has code that uses coder.extrinsic to call
out to the MATLAB execution engine, it incurs all the costs that the MATLAB S-
Function or Interpreted MATLAB Function block incur. Calling out to the
MATLAB execution engine from a MATLAB Function block produces a warning
to prevent you from doing so unintentionally.
To reduce the algorithm cost, you can disable debugging for all MATLAB
Function blocks.
MATLAB System In the interpreted execution mode, performance is similar to that of the Level-2
MATLAB S-function because the model simulates the block using the MATLAB
execution engine. In the code generation mode, performance is similar to that
of the MATLAB Function because the model simulates the block using the
generated code. For more information, see the MATLAB Function entry in this
table.
C Caller, C Function First time model simulation with could be slower due to parsing and building of
the custom code. To speed up the simulation after the first compile, from
Configuration parameters, select Faster Builds for faster compile and
select Faster Runs for faster simulation.
C MEX S-Function Simulates via the compiled code and incurs the same interface cost as Simulink
built-in blocks. The algorithm cost depends on the complexity of the S-
Function.
S-Function Builder This block only builds an S-Function from the specifications and C code you
supply. You can also use this block as a wrapper for the generated S-Function
in models. The algorithm cost of this block compared to C MEX S-Function is
incurred only from the wrapper.

44-7
44 Creating Custom Blocks

Custom Block Type Notes


Simulink Function, If included in a library, introduces no interface or algorithm costs beyond what
Subsystem would normally be incurred if the block existed as a regular subsystem in the
model.
Performance 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 Simulink loads any unloaded libraries the first time the diagram is
updated or readied for simulation. If all referenced library blocks remain
unchanged, Simulink does not subsequently reload the library. Compiling the
model becomes faster than if the model did not use libraries.

Code Generation
You need code generation if your model is part of a bigger system. Not all custom block types support
code generation with Simulink Coder.

Custom Block Type Notes


Fcn Supports code generation.
Interpreted MATLAB Does not support code generation.
Function
C Caller, C Function Supports code generation.
Level-2 MATLAB S- Generates code only if you implement the algorithm using a Target Language
Function Compiler (TLC) function. In accelerated and external mode simulations, you
can choose to execute the S-Function in the interpretive mode by calling back
to the MATLAB execution engine without implementing the algorithm in TLC. If
the MATLAB S-Function is SimViewingDevice, the Simulink Coder product
automatically omits the block during code generation.
MATLAB Function, Supports code generation. However, if your block calls out to the MATLAB
MATLAB System execution engine, it will build with the Simulink Coder product only if the calls
to the MATLAB execution engine 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.
C MEX S-Function, Both supports code generation.
S-Function Builder
• For non-inlined S-Functions, the Simulink Coder product uses the C MEX
function during code generation.
• In the case of C MEX S-Functions, if you need to either inline the S-
Function or create a wrapper for handwritten code, you must write a TLC
file for the S-Function.
• In the case of S-Function Builder, you can choose the Generate wrapper
TLC option to automatically generate a TLC file.

See “S-Functions and Code Generation” (Simulink Coder) for more


information.
Simulink Function Supports code generation.

44-8
Comparison of Custom Block Functionality

Custom Block Type Notes


Subsystem Supports code generation as long as the blocks contained within the subsystem
support code generation. For more information, see “Subsystems” (Simulink
Coder).

Multiple Input and Output Ports


These types of custom blocks support multiple input and output ports.

Custom Block Type Notes


Fcn, Interpreted Supports only a single input and a single output port.
MATLAB Function
MATLAB Function Supports multiple input and output ports, including buses. For more
information, see “Create Structures in MATLAB Function Blocks” on page 50-
75 and “Attach Buses to MATLAB Function Blocks” on page 50-68.
MATLAB System Supports multiple input and output ports, including buses. In addition, you can
modify the number of input and output ports based on System object
properties using the getNumInputs and getNumOutputs methods.
C Caller, C Function Supports multiple input and output ports, including buses.
Level-2 MATLAB S- Supports multiple input and output ports. In addition, you can modify the
Function, C MEX S- number of input and output ports based on user-defined parameters. The C
Function, S-Function MEX S-Function and S-Function Builder support buses.
Builder
Simulink Function Supports multiple input and output ports, including buses.
Subsystem Supports multiple input and output ports, including buses. In addition, you can
modify the number of input and output ports based on user-defined
parameters. See “Self-Modifiable Linked Subsystems” on page 45-18 for more
information.

Speed of Updating the Simulink Diagram


Simulink updates the diagram before every simulation and when requested by the user. Every block
introduces some overhead into the diagram update process.

Custom Block Type Notes


Fcn, Interpreted Low diagram update cost.
MATLAB Function
MATLAB Function, C Simulation is performed through code generation, so this blocks can take a
Caller, C Function significant amount of time when first updated. However, because code
generation is incremental, Simulink does not repeatedly update the block if the
block and the signals connected to it have not changed.
MATLAB System Faster than MATLAB Function because code is not generated to update the
diagram. Since, code generation is incremental, Simulink does not repeatedly
update the block if the block and the signals connected to it have not changed.

44-9
44 Creating Custom Blocks

Custom Block Type Notes


C MEX S-Function, Incurs greater costs than other Simulink blocks only if it overrides methods
Level-2 MATLAB S- executed when updating the diagram. If these methods become complex, they
Function 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,
Simulink invokes all relevant methods in the model initialization phase up to,
but not including, mdlStart.
Simulink Function, The speed is proportional to the complexity of the algorithm implemented in
Subsystem the subsystem. If the subsystem is contained in a library, some cost is incurred
when Simulink loads any unloaded libraries the first time the diagram is
updated or readied for simulation. If all referenced library blocks remain
unchanged, Simulink does not subsequently reload the library. Compiling the
model becomes faster than if the model does not use libraries.

Callback Methods
Simulink blocks communicate with the Simulink engine through block callback methods, which fully
specify the behavior of blocks (except the Simulink Function block). Each custom block type allows
you to implement a different set of callback methods. To learn how blocks interact with Simulink
engine, see “Simulink Engine Interaction with C S-Functions”. This table uses “S-Function Callback
Methods” names as equivalents.

Custom Block Type Notes


Fcn, Interpreted All create a mdlOutputs method to calculate the value of outputs given the
MATLAB Function, value of inputs. You cannot implement any other callback methods using one of
MATLAB Function, C these blocks and, therefore, cannot model state behavior.
Caller
C Function Allows implementation of start, output, and terminate callback methods. Allows
modeling of discrete states with persistent data.
Level-2 MATLAB S- Allows implementation of a larger subset of callback methods, including
Function methods you can use to model continuous and discrete states. For a list of
supported methods, see “Level-2 MATLAB S-Function Callback Methods” in
“Write Level-2 MATLAB S-Functions”.
MATLAB System Uses System object methods for callback methods: mdlOutputs (stepImpl,
outputImpl), mdlUpdate (updateImpl), mdlInitializeConditions
(resetImpl), mdlStart (setupImpl), mdlTerminate (releaseImpl). For
more information, see “Simulink Engine Interaction with System Object
Methods” on page 51-26
C MEX S-Function Allows implementation of a complete set of callback methods.
S-Function Builder Allows implementation of mdlOutputs, mdlDerivatives and mdlUpdate.
Simulink Function Packaged as a standalone function. Any caller to this function becomes part of
one of the callback methods based on the caller’s location.
Subsystem Communicates directly with the engine. You can model state behaviors using
appropriate blocks from the continuous and discrete Simulink block libraries.

44-10
Comparison of Custom Block Functionality

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 whereas MATLAB functions for code
generation are a subset of the MATLAB language. For a list of supported functions for code
generation, see “Functions and Objects Supported for C/C++ Code Generation” on page 55-2.
• MATLAB S-functions can model discrete and continuous state dynamics whereas MATLAB
functions for code generation cannot model state dynamics.

Expanding Custom Block Functionality


You can expand the functionality of any custom block using callbacks and MATLAB 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 “Block
Callbacks” on page 4-75.

App Designer, the MATLAB graphical user interface development environment, provides tools for
easily creating custom user interfaces. See “App Building” for more information on using App
Designer.

See Also
Fcn | Interpreted MATLAB Function | Level-2 MATLAB S-Function | MATLAB Function | MATLAB
System | S-Function | S-Function Builder | Simulink Function | Subsystem | C Caller | C Function

More About
• “Types of Custom Blocks” on page 44-2
• “Design and Create a Custom Block” on page 44-12

44-11
44 Creating Custom Blocks

Design and Create a Custom Block

In this section...
“Setup Working Environment to Design and Create a Custom Block” on page 44-12
“How to Design a Custom Block” on page 44-12
“Defining Custom Block Behavior” on page 44-14
“Deciding on a Custom Block Type” on page 44-14
“Placing Custom Blocks in a Library” on page 44-18
“Adding a User Interface to a Custom Block” on page 44-19
“Adding Block Functionality Using Block Callbacks” on page 44-25

Setup Working Environment to Design and Create a Custom Block

This example open a directory containing the following files required for this topic.

1 ex_customsat_lib.slx
2 sldemo_customsat.slx
3 msfuntmpl.m
4 custom_sat.m
5 custom_sat_final.m
6 customsat_callback.m
7 customsat_plotcallback.m
8 custom_sat_plot.m
9 plotsat.m

How to Design a Custom Block


In general, use the following process to design a custom block:

1 “Defining Custom Block Behavior” on page 44-14


2 “Deciding on a Custom Block Type” on page 44-14
3 “Placing Custom Blocks in a Library” on page 44-18
4 “Adding a User Interface to a Custom Block” on page 44-19

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 ex_customsat_lib contains the two
versions of the customized saturation block.

44-12
Design and Create a Custom Block

The example model sldemo_customsat uses the basic version of the block.

44-13
44 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.
• 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:

44-14
Design and Create a Custom Block

• 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 44-5 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.
• 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. Open this file 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.

44-15
44 Creating Custom Blocks

% 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


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; % double
block.InputPort(1).Complexity = 'Real';

% 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
%% -----------------------------------------------------------------
% 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');

44-16
Design and Create a Custom Block

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

%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;

44-17
44 Creating Custom Blocks

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;

%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. If your
custom block requires a bus as an interface, you can share the bus object with library users by
creating the bus object in a data dictionary and attaching the dictionary to the library (See “Attach
Data Dictionary to Custom Libraries” on page 80-35).

This example places the custom saturation block into a library.

1 In the Simulink Editor, in the Simulation tab, select New > Library.
2 From the User-Defined Functions library, drag a Level-2 MATLAB S-Function block into your new
library.

3 Save your library with the filename saturation_lib.


4 Double-click the block to open its Function Block Parameters dialog box.

44-18
Design and Create a Custom Block

5 In the S-function name field, enter the name of the S-function. For example, enter
custom_sat. In the Parameters field enter 2,-1,2,1.

6 Click OK.

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 user interface.

Adding a User Interface to a Custom Block


You can create a block dialog box for a custom block using the masking features of Simulink. Masking
the block also allows you to add port labels to indicate which ports corresponds to the input signal
and the saturation limits.

44-19
44 Creating Custom Blocks

1 Open the library saturation_lib that contains the custom block you created.
2 Right-click the Level-2 MATLAB S-Function block and select Mask > Create Mask.
3 On the Icon & Ports pane in the Icons drawing commands box, enter
port_label('input',1,'uSig'), and then click Apply.

This command labels the default port as the input signal under saturation.

4 In the Parameters & Dialog pane, add four parameters corresponding to the four S-Function
parameters. For each new parameter, drag a popup or edit control to the Dialog box section, as
shown in the table. Drag each parameter into the Parameters group.

Type Prompt Name Evalua Tunabl Popup options Callback


te e
popup Upper upMode ✓ No limit customsat_callback('upperbou
boundary nd_callback', gcb)
: Enter limit as
parameter

Limit using input


signal
edit Upper upVal ✓ ✓ N/A customsat_callback('upperpar
limit: am_callback', gcb)

Type Prompt Name Evalua Tunabl Popup options Callback


te e
popup Lower lowMod ✓ No limit customsat_callback('lowerbou
boundary e nd_callback', gcb)
: Enter limit as
parameter

Limit using input


signal

44-20
Design and Create a Custom Block

Type Prompt Name Evalua Tunabl Popup options Callback


te e
edit Lower lowVal ✓ ✓ N/A customsat_callback('lowerpar
limit: am_callback', gcb)

The MATLAB S-Function script custom_sat_final.m contains the mask parameter callbacks.
Find custom_sat_final.m in your working folder to define the callbacks in this example. This
MATLAB script has two input arguments. The first input argument is a character vector
indicating which mask parameter invoked the callback. The second input argument is the handle
to the associated Level-2 MATLAB S-Function block.

The figure shows the completed Parameters & Dialog pane in the Mask Editor.

5 In the Initialization pane, select the Allow library block to modify its contents check box.
This setting allows the S-function to change the number of ports on the block.
6 In the Documentation pane:

• In the Mask type field, enter

Customized Saturation
• In the Mask description field, enter

Limit the input signal to an upper and lower saturation value


set either through a block parameter or input signal.

44-21
44 Creating Custom Blocks

7 Click OK.
8 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.
9 Change the S-function name field to custom_sat_final and the Parameters field to
lowMode,lowVal,upMode,upVal.

The figure shows the Function Block Parameters dialog box after the changes.

10 Click OK. Save and close the library to exit the edit mode.
11 Reopen the library and double-click the customized saturation block to open the masked
parameter dialog box.

44-22
Design and Create a Custom Block

To create a more complicated user interface, place a MATLAB graphics user interface on top of the
masked block. The block OpenFcn invokes the MATLAB graphics user interface, which uses calls to
set_param to modify the S-function block 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 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 character vectors 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 text.

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

44-23
44 Creating Custom Blocks

%% 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; % double
block.InputPort(1).Complexity = 'Real';

% 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
%% -----------------------------------------------------------------
% 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];

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;

44-24
Design and Create a Custom Block

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 ex_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 Mask +
Create Mask.
b On the Mask Editor Parameters pane, add a fifth mask parameter with the following
properties.

Prompt Name Type Tunabl Type Callback


e options
Plot plotche checkb No NA customsat_callback('plots
saturatio ck ox aturation',gcb)
n limits
c Click OK.

44-25
44 Creating Custom Blocks

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');
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;
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)

44-26
Design and Create a Custom Block

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


% This routine is called by the S-function block's StopFcn.

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.

44-27
44 Creating Custom Blocks

See Also

More About
• “Types of Custom Blocks” on page 44-2
• “Comparison of Custom Block Functionality” on page 44-5

44-28
Integrate Python GPS Text Message Parsing Algorithms in Simulink

Integrate Python GPS Text Message Parsing Algorithms in


Simulink

This example shows how to parse text messages in NMEA GPS format using Simulink® string blocks
and Python®. NMEA sentences are used for communication between marine devices, and the model
in the example decodes RMB and RMC sentences in NMEA. RMB is the sentence for the
recommended navigation data for GPS. RMC is the sentence for the recommended minimum data for
GPS sentences.

In the model, you can choose to decode RMB and RMC sentences using Simulink or by incorporating
Python code. This example explains the details of incorporating Python for decoding. For more
information about the model and using Simulink® blocks for decoding, see “Simulink Strings” on
page 73-58. For more on using Python in MATLAB®, see “Access Python Modules from MATLAB -
Getting Started”.

MATLAB supports the reference implementation of Python, often called CPython. If you are on a Mac
or Linux® platform, you already have Python installed. If you are using Windows®, you need to
install a distribution, such as those found at https://www.python.org/downloads/. For more
information, see “Configure Your System to Use Python”.

Explore the Model

In the model, the subsystem named NMEA Data Generator generates data and sends the data to
the subsystem named Data Classifier. The Data Classifier classifies the sentences as RMB,
RMC, or unsupported. The sentences are then sent to RMB Decoder, RMC decoder, or
Unsupported, depending on their type.

44-29
44 Creating Custom Blocks

Model RMB and RMC Decoders Using Python or Simulink String Blocks

If you double-click the block named RMB Decoder, you can choose to model the decoder using
Simulink string blocks or Python code.

44-30
Integrate Python GPS Text Message Parsing Algorithms in Simulink

Look under the mask. Observe that when you select Python, the decoder is modeled by using a
MATLAB System block.

Open the source code. Observe that the Python code to decode the message is incorporated into the
setupImpl and stepImpl functions.

function setupImpl(obj)
py.importlib.import_module('RMBDecode');
end

function y = stepImpl(obj,sentence)
% convert sentence to python string
pstr = py.str(sentence);

% call python module for string processing


plist = py.RMBDecode.parseRMBSentence(pstr);

% assign python list elements to Simulink bus


y.Status = string(plist{1});
y.Error = str2double(string(plist{2}));
y.ErrorDirection = string(plist{3});
y.OriginWaypointID = uint16(str2double(string(plist{4})));
y.DestinationWaypointID = uint16(str2double(string(plist{5})));
y.DestinationWaypointLatitudeDegree = uint16(str2double(string(plist{6})));
y.DestinationWaypointLatitudeMinute = str2double(string(plist{7}));

44-31
44 Creating Custom Blocks

y.DestinationWaypointNS = string(plist{8});
y.DestinationWaypointLongitudeDegree = uint16(str2double(string(plist{9})));
y.DestinationWaypointLongitudeMinute = str2double(string(plist{10}));
y.DestinationWaypointEW = string(plist{11});
y.RangeToDestination = str2double(string(plist{12}));
y.TrueBearing = str2double(string(plist{13}));
y.Velocity = str2double(string(plist{14}));
y.ArrivalAlarm = string(plist{15});
y.Checksum = string(plist{16});
end

Simulate Model and Review Results

Simulate the model and observe the decoded RMB and RMC sentences.

See Also

More About
• “Call Python Function Using MATLAB Function and MATLAB System Block” on page 51-122
• “Types of Custom Blocks” on page 44-2

44-32
45

Working with Block Libraries

• “Create Custom Library” on page 45-2


• “Add Libraries to Library Browser” on page 45-8
• “Linked Blocks” on page 45-12
• “Parameterized Links and Self-Modifiable Linked Subsystems” on page 45-15
• “Create a Self-Modifiable Library Block” on page 45-20
• “Display Library Links” on page 45-21
• “Disable or Break Links to Library Blocks” on page 45-23
• “Lock Links to Blocks in a Library” on page 45-25
• “Restore Disabled Links” on page 45-27
• “Restore Parameterized Links” on page 45-30
• “Fix Unresolved Library Links” on page 45-32
• “Control Linked Block Programmatically” on page 45-34
• “Maintain Compatibility of Library Blocks Using Forwarding Tables” on page 45-37
45 Working with Block Libraries

Create Custom Library


You can create your own library and, optionally, add it to the Simulink Library Browser. You save a
library as a .slx file similar to the way you save a model. However, you cannot simulate in a library,
and a library becomes locked for editing each time you close it. You must unlock a library before you
make changes to it. See “Lock and Unlock Libraries” on page 45-6.

1 From the Simulink start page, select Blank Library and click Create Library.

Note The Library Browser only supports libraries. You cannot display the contents of a model in
the Library Browser.
2 (Optional) Define data types to be used on block interfaces in a Simulink data dictionary. Then,
attach the data dictionary to the library. Library users automatically gain access to the data
contained in the dictionary when they drag a block from the library into their model.
3 Add blocks to the new library. Make the changes you want to the blocks, such as changing block
parameters, adding masks, or adding blocks to subsystems.

Subsystem names in a library hierarchy must be unique. For example, do not create a hierarchy
such as Subsystem_Name1/Subsystem_Name2/Subsystem_Name1.
4 (Optional) Add annotations or images. Right-click the ones you want to appear in the library in
the Library Browser and select Show in Library Browser.
5 If you plan to add the library to the Library Browser, you can order the blocks and annotations in
your library. By default, they appear alphabetically in the Library Browser, with subsystems first,
then blocks, and then annotations. The user of your library can use the Library Browser context
menu to choose between viewing them in alphabetical order or the order you specified. When the
user selects this option, the order in which they appear in your library determines the order they
appear on the grid in the library in the Library Browser.
6 If you want the library to appear in the Library Browser, enable the EnableLBRepository
library property before you save the library.

set_param(gcs,'EnableLBRepository','on');
7 Save the library.

Where you save the library depends on how you plan to use it. If you want to add it to the Library
Browser, save it to a folder on the MATLAB path or add the location to the MATLAB path.
Otherwise, save it to a location where the models that use the blocks can access it.

If you want the library to appear in the Library Browser, you must also create a function slblocks
on your MATLAB path that adds the library to the browser. For an example that shows complete steps
for adding a library to the browser, see “Add Libraries to Library Browser” on page 45-8.

Note To update the Library Browser with your custom libraries, right-click anywhere in the Library
Browser library list and select Refresh Library Browser. Refreshing the Library Browser also
updates the quick insert menu to include the blocks in custom libraries currently in effect. The quick
insert menu lets you add blocks to a model without leaving the canvas. Click the canvas and start
typing to add blocks from the quick insert menu.

45-2
Create Custom Library

Data Dictionary for Custom Libraries


When you define data types — such as bus and enumeration types — to be used on block interfaces,
you can make these data types available to users by storing them in a data dictionary that is attached
to the library. When a user drags a block from the library into their model, the model automatically
gains access to the data contained in the dictionary.

1 Create a data dictionary.


2 In the dictionary, define bus objects, enumeration types, or other data objects that you will use
for the interface definitions of your library blocks.
3 Attach the dictionary as an external data source for your library programmatically by using
set_param or in the UI by using the External Data tab in the Library Properties dialog box. The
Model Explorer displays the attached dictionary and its content as an external data source for
the library.
4 To save the data dictionary specifications, save the library.

The types that you defined in the library are now available to you while developing library blocks. See
“Attach Data Dictionary to Custom Libraries” on page 80-35.

Blocks for Custom Libraries


Your library can contain the blocks you need, configured for your purposes. Subsystems, masked
blocks, and charts in your library become linked blocks as instances in the model and stay updated if
you change them in your library. Knowing about custom blocks is also useful when you create a
library. See “Design and Create a Custom Block” on page 44-12.

You can create blocks in custom libraries with settings for specific purposes.

Create a Sublibrary

If your library contains many blocks, you can group the blocks into subsystems or separate
sublibraries. To create a sublibrary, you create a library of the sublibrary blocks and reference the
library from a Subsystem block in the parent library.

1 In the library you want to add a sublibrary to, add a Subsystem block.
2 Inside the Subsystem block, delete the default input and output ports.
3 If you want, create a mask for the subsystem that displays text or an image that conveys the
sublibrary purpose.
4 In the subsystem block properties, set the OpenFcn callback to the name of the library you want
to reference.

To learn more about masks, see “Create a Simple Mask” on page 43-7.

Prevent Library Block from Linking to Instance

You can configure a library block so the instances created from it are not linked blocks and are
instead copies. Set the block’s CopyFcn callback.

set_param(gcbh,'LinkStatus','none');

45-3
45 Working with Block Libraries

Include Block Description in Linked Block

To add a description that appears in the linked block, mask the library block and add the description
in the Documentation pane of the mask. Descriptions added to the library block through the block’s
properties do not appear on the linked block.

Configure Block with Keywords for Quick Insert

You can add one or more keywords to a block in your library. The keyword lets you add the block to
your model from the quick insert menu by entering the keyword or the block name.

For example, suppose you have a custom Gain block in your library. You can add the keyword My
Gain to the block. Then, you can add the block to your model by entering My Gain at the quick
insert menu.

Note You cannot add keywords to the blocks from Commonly Used Blocks as they are a place to
view frequently used blocks from various libraries. If you want to add keywords to a block available in
Commonly Used Blocks, make sure that you set it in the library where the block is defined.

To add the keyword to the block in your library, use set_param with the 'BlockKeywords'
parameter. You can use a character vector, string scalar, or string array as the value. For example:

set_param(gcb,'BlockKeywords',{"My Gain","Your Gain"})


set_param(gcb,'BlockKeywords','My Integrator')

Note The supported special characters in keywords are '&', '(', ')', '+', '@', '!'.

Note The quick insert menu also supports searching for blocks in languages other than English by
using internationalized keywords.

Configure Subsystems with OpenFcn Callback for Library Browser

A common use of a Subsystem block in a custom library is to set the OpenFcn callback property to
open a library, creating a library hierarchy. However, you can use the OpenFcn callback property of a
Subsystem block for other purposes, for example to run MATLAB code or to open a link.

If a Subsystem block in a library is empty and its OpenFcn callback contains code that performs an
action other than point to a library, then you need to add a 'ShowInLibBrowser' mask parameter
to the subsystem to have it appear in the Library Browser.

1 Right-click the subsystem and select Mask > Create Mask. If the block already has a mask,
select Edit Mask instead.

45-4
Create Custom Library

2 In the Mask Editor Parameters & Dialog tab, on the Controls pane, click Check box.
3 In the Dialog box pane, set the prompt and name for the new check box to ShowInLibBrowser
and click OK.

Annotations in Custom Libraries


You can add annotations in your custom library and optionally have them appear in the Library
Browser. For example, you can add an annotation that documents the library. You can also add
annotations that the user of your library can add to their model from the Library Browser.
Annotations can contain text and images or display an equation. Annotations can also perform an
action when clicked. Learn more about annotations in “Annotate Models” on page 1-76.

You can add callout lines from annotations to blocks in your library. However, the callouts do not
appear in the Library Browser.

If you want the annotation to appear in the Library Browser, after you add it to your library, right-
click it and select Show in Library Browser. If you want a description to appear in a tooltip when
the user hovers over the annotation in the Library Browser, add the description to the annotation
programmatically. At the MATLAB command prompt, enter:

45-5
45 Working with Block Libraries

set_param(annotationHandle,'Description','descriptionText)

To get the annotation handle, use find_system. This example gets all the annotations in the library
mylib:

ann = find_system('mylib','FindAll','on','Type','annotation');

To get a specific annotation, turn on regular expression search and specify part of the annotation text
with the 'Name' argument:

ann = find_system('mylib2',FindAll','on','RegExp',...
'on','Type','annotation','Name','matchingText');

“Add Libraries to Library Browser” on page 45-8 includes instructions for adding an annotation
that appears in the Library Browser.

Lock and Unlock Libraries


When you close a library, it becomes locked for editing. When you next open it, unlock it if you want
to make changes to it. Click the lock badge in the lower-left corner of the library to unlock it.
Additionally, if you try to modify a locked library, a message prompts you to unlock it.

You can unlock a library programmatically. At the MATLAB command prompt, enter:

set_param('library_name','Lock','off');

To lock the library programmatically, enter:

set_param('library_name','Lock','on');

Prevent Disabling of Library Links


By default, a user of the blocks in your library can disable the link to library blocks. If you want to
control editing of linked blocks and prevent the block user from disabling links, you can lock links to
your library. Locking library links prevents the user from making any changes to the block instances.

• In your library, on the Library tab, click Lock Links.

To understand how the block user interacts with blocks from locked libraries, see “Lock Links to
Blocks in a Library” on page 45-25.

See Also

More About
• “Explore Types of Model Components” on page 23-4
• “Design and Create a Custom Block” on page 44-12
• “Masking Fundamentals” on page 43-3
• “Annotate Models” on page 1-76
• “Add Libraries to Library Browser” on page 45-8
• “Linked Blocks” on page 45-12

45-6
Create Custom Library

• “Customize Library Browser Appearance” on page 84-52

45-7
45 Working with Block Libraries

Add Libraries to Library Browser


This example shows how to create a block library and add it to the Simulink Library Browser. This
example also shows how to add a sublibrary.

To specify information about your library, you create a function named slblocks.

Add Library to Library Browser


1 On the Simulink start page, in the search box, type library. Select Blank Library, then click
Create Library.

Note The Library Browser only supports libraries. You cannot display the contents of a model in
the Library Browser.
2 Add a Gain block to the library.
3 In the MATLAB Command Window, enter this command to set the EnableLBRepository library
property to 'on'. Your library will appear in the Library Browser only if this property is enabled
when you save your library.

set_param(gcs,'EnableLBRepository','on');
4 Save the library in a folder on the MATLAB path. For this example, name the library mylib.
5 In the MATLAB Current Folder Browser, open the folder that contains mylib, then, in the
MATLAB Toolstrip, click New Script.
6 In the MATLAB Editor that opens, add this function, which specifies that the library mylib
should appear in the Library Browser with the name My Library.

function blkStruct = slblocks


% This function specifies that the library 'mylib'
% should appear in the Library Browser with the
% name 'My Library'

Browser.Library = 'mylib';
% 'mylib' is the name of the library

Browser.Name = 'My Library';


% 'My Library' is the library name that appears
% in the Library Browser

blkStruct.Browser = Browser;
7 Save the function as slblocks.m.

Note You can save the function as an .m or .mlx file. You cannot save the function as a P-code
file.
8 To open the Library Browser, in the Simulink Toolstrip, click Library Browser.
9 To see the new library in the Library Browser, right-click the library list and select Refresh
Library Browser.

45-8
Add Libraries to Library Browser

The figure shows the example library mylib with the Library Browser name My Library.

Note If you save your library without setting 'EnableLBRepository' to 'on', a message appears
at the top of the Library Browser.

Click Fix and respond to the prompt as appropriate.

Add Sublibrary to Library Browser


Follow these steps to add a sublibrary named mylib2 to your mylib library.

1 Create a library named mylib2. Add some blocks to it.


2 In the MATLAB Command Window, set the EnableLBRepository library property to 'on' for
the new library.

set_param(gcs,'EnableLBRepository','on');
3 Save mylib2 to the folder that contains mylib.
4 Add a Subsystem block to the mylib library.
5 Remove the input and output ports from the subsystem by deleting the Inport and Outport blocks
inside the subsystem.
6 Name the Subsystem block My Sublibrary.
7 To link the Subsystem block to the sublibrary, set the OpenFcn callback to mylib2 by using the
Property Inspector.

45-9
45 Working with Block Libraries

8 Save mylib.
9 To see the new sublibrary in the Library Browser, right-click the library list and select Refresh
Library Browser.

The figure shows the example sublibrary mylib2 with the Library Browser name My
Sublibrary.

Because of the callback you created, expanding My Sublibrary displays the contents of the
mylib2 library.

45-10
Add Libraries to Library Browser

Specify Library Order in Library List


You can specify the order of your library relative to the other libraries in the list by adding a
sl_customization.m file to the MATLAB path and setting the sort priority of your library. For
example, to see your library at the top of the list, you can set the sort priority to -2. By default, the
sort priority of the Simulink library is -1. The other libraries have a sort priority of 0 by default, and
these libraries appear below the Simulink library. Libraries with the same sort priority appear in
alphabetical order.

This sample content of the sl_customization.m file places the new library at the top of the list of
libraries.

function sl_customization(cm)
% Change the order of libraries in the Simulink Library Browser.
cm.LibraryBrowserCustomizer.applyOrder({'My Library',-2});
end

To make the customization take effect immediately, in the MATLAB Command Window, enter:

sl_refresh_customizations

See Also

More About
• “Create Custom Library” on page 45-2
• “Customize Library Browser Appearance” on page 84-52
• “Register Customizations with Simulink” on page 84-56

45-11
45 Working with Block Libraries

Linked Blocks
In this section...
“Rules for Linked Blocks” on page 45-13
“Linked Block Terminology” on page 45-13

When you add a masked library block or a Subsystem block from a library to a Simulink model, a
referenced instance of the library block is created. Such referenced instance of a library block is
called a linked block and contains link or path to the parent library block. The link or path allows the
linked block to update when the library block is updated.

To optimize the performance, the child blocks (and the parameters) of a linked block are not saved
with the Simulink model. When such a model is loaded and viewed, the child blocks are referenced
from the parent library. If you change the parameter value of a child block of such a linked block, the
changed information is saved as linked data in the model.

To locate the parent library block of a linked block, right-click the block and select Library Link >
Go To Library Link (Ctrl + L). This option is available only for the blocks that are linked and not for
the Simulink built-in blocks. To prevent unintentional disabling of library links, use the locked links
option on the library. For more information, see “Lock Links to Blocks in a Library” on page 45-25.

Note The tooltip for a linked block shows the name of the referenced library block.

When you edit a library block (either in Simulink Editor or at the command line), Simulink updates
the changes in the linked blocks. The outdated links are updated when you:

• Simulate or update the model.


• Use the find_system command.
• On the Modeling tab, select Update Model > Refresh Blocks (or press Ctrl+K).
• Load the model or library (only the visible links are updated).
• Use get_param to query the link status of the block (see “Control Linked Block
Programmatically” on page 45-34).

You can use the LinkStatus parameter or the StaticLinkStatus parameter to query the link
status.

• LinkStatus: First updates the linked block and then returns the link status.
• StaticLinkStatus: Returns the link status without updating the linked block.

Selective usage of StaticLinkStatus over LinkStatus can result in better Simulink


performance. For more information on StaticLinkStatus and LinkStatus, see “Control
Linked Block Programmatically” on page 45-34.

45-12
Linked Blocks

Rules for Linked Blocks


• You can change the values of a linked block parameter (including the existing mask) in the mask
dialog box.
• To allow the library block initialization code to change the values of a linked block parameter,
select the Allow library block to modify its contents check box in the Initialization pane of
the library block.
• It is not recommended to set callback parameters for a linked block.
• If the reference library block of a linked block is a subsystem, you can make nonstructural
changes such as changing the parameter value of the linked subsystem. To make structural
changes to a linked block, disable the link of the linked block from its library block (See “Disable
or Break Links to Library Blocks” on page 45-23).
• During model compilation, Simulink may open some libraries implicitly to fully instantiate or load
the model. However, to optimize memory usage, Simulink closes these libraries after the
compilation. You must open the libraries explicitly instead of depending on the implicit opening by
Simulink, to ensure the libraries do not close after the compilation.

Linked Block Terminology


Terminology Definition
Parent library block Library block from which the linked blocks are
referenced.
Linked block Reference instance of a library block that
contains links or path to its parent library block.
Locked links Prevents unintentional modification of a linked
block. For more information, see “Lock Links to
Blocks in a Library” on page 45-25.
Disabled links Library links that are temporarily disconnected
from their parent library block. For more
information, see “Disable or Break Links to
Library Blocks” on page 45-23.
Restore links Restores the disabled link of a linked block to
their parent library block. For more information,
see “Restore Disabled Links” on page 45-27.
Break links Permanently breaks the link of a linked block
from its parent library block. For more
information, see “Disable or Break Links to
Library Blocks” on page 45-23.
Self-modifiable links Linked block with the ability to have structural
changes in a linked Subsystem block. For more
information, see “Self-Modifiable Linked
Subsystems” on page 45-18.
Parameterized links Created when the parameter values of a linked
subsystem block are modified. For more
information, see “Parameterized Links and Self-
Modifiable Linked Subsystems” on page 45-15.

45-13
45 Working with Block Libraries

Terminology Definition
Forwarding Tables Maps the old library block path to new library
block path. For more information, see “Maintain
Compatibility of Library Blocks Using Forwarding
Tables” on page 45-37.
Transformation function Corrects the mismatch of parameters in the
InstanceData of the new and old library links
to ensure that the library links continue to work.
For more information, see “Maintain
Compatibility of Library Blocks Using Forwarding
Tables” on page 45-37.

See Also
find_system

More About
• “Explore Types of Model Components” on page 23-4
• “Display Library Links” on page 45-21
• “Control Linked Block Programmatically” on page 45-34
• “Fix Unresolved Library Links” on page 45-32

45-14
Parameterized Links and Self-Modifiable Linked Subsystems

Parameterized Links and Self-Modifiable Linked Subsystems


A parameterized link is created when you change the parameter values of the child blocks of a linked
subsystem block without changing the parameter values or disabling links in the parent library block.

Similarly, you can change the structure of a linked subsystem without modifying the parent library
block when you have a linked subsystem block with a self-modifiable mask.

Parameterized Links
A parameterized link provides the flexibility to have different parameter values for the linked block
compared to the parent library block. You can override or customize specific parameter values in the
linked block without affecting the original values in the parent library block. For such parameterized
linked blocks, the link to the parent block is still retained.

Note Changing the mask value of a parent library block does not create a parameterized link.

Consider a custom library Libraries with a subsystem block Subsystem. Subsystem contains a Gain
block with its parameter value set as 1.

Add the Subsystem block in a model to create linked blocks Subsystem and Subsystem1.

45-15
45 Working with Block Libraries

In your model, you can modify the parameter values of the child blocks of the linked blocks without
changing the value of the parent library block. For example, you can change the parameter value of
the Gain block inside the linked Subsystem block to 100. For more information on changing
parameter values, see “Edit Block Parameters” on page 1-48

To change the parameter values programmatically use these commands:

pathName = [ModelName,'/Gain_Subsystem/Gain'];
set_param(pathName, 'Gain', '100')

Similarly, you can change the parameter value of the Gain block inside the linked Subsystem1 block
to 200.

45-16
Parameterized Links and Self-Modifiable Linked Subsystems

When you modify a parameter value in a linked block, it overrides the previous parameter value that
was obtained from the parent library block. This differentiation between the child block value and its
parent library block creates a parameterized link.

When you save a model containing a parameterized link, Simulink saves the changes to a local copy
of the Subsystem with the path to the parent library. When you reopen the model, Simulink copies the
library block into the loaded model and applies the saved changes.

To view the parameterized links in a model, in the Simulink toolstrip go to Subsystem Block tab, and
click Link Manager. The Library Link Manager opens. Click the Parameterized Links tab to
display all the parameterized links in the model.

45-17
45 Working with Block Libraries

Identifying Parameterized Links

To identify a parameterized link, use these identifications on the link badge of the linked subsystem
block:


Black links with a red star icon on the link badge . For more information, see “Display Library
Links” on page 45-21.
• Tooltip of the link badge displays Modified parameter in link.

Self-Modifiable Linked Subsystems

Tip We recommend using variant blocks over self-modifiable linked subsystems.

A self-modifiable linked subsystem is a linked block with the ability to have structural changes in the
subsystem without disabling the link with the parent library block. A self-modifiable linked subsystem
is created when you use a library block containing a self-modifiable mask as the linked block. You can
use the mask initialization code to change the structural contents. For more information, see
“Dynamic Masked Subsystem” on page 43-45 and Self-Modifiable Mask on page 45-20.

45-18
Parameterized Links and Self-Modifiable Linked Subsystems

See Also

More About
• “Linked Blocks” on page 45-12
• “Create Custom Library” on page 45-2
• “Disable or Break Links to Library Blocks” on page 45-23
• “Restore Parameterized Links” on page 45-30
• “Restore Disabled Links” on page 45-27

45-19
45 Working with Block Libraries

Create a Self-Modifiable Library Block

A self-modifiable linked block is created when you add a self-modifiable masked subsystem block from
the library to your model. Such linked blocks allow structural changes within the subsystem block.

You can observe that in this example, if you change the 'Time domain' on the mask dialog box, the
block within the Subsystem is replaced accordingly. For example, if you select the 'Time domain' as
'Discrete', the continuous integrator block is replaced with a discrete integrator block and vise-versa.

This dynamic change in the structure of the self-modifiable linked block is controlled using the
MATLAB® code that is added in the Initialization pane of the Mask Editor.

The structural changes take place only if the option 'Allow library block to modify its contents'
available on the Initialization pane is selected.

open_system('self_modifiable_mask_example');

45-20
Display Library Links

Display Library Links


Each linked block has a link badge associated with it. The badge makes it easier to identify the linked
block in a model and also displays its link status.

To control the display of library link badges in a Simulink model, on the Debug tab, select
Information Overlays and then one of these options:

• Hide All Links — Displays no links.


• Disabled Links — Displays only disabled links (the default for new models).
• User-Defined Links — Displays only links to user libraries.
• Show All Links — Displays all links.

If activated, link badges are displayed at the bottom left corner of a linked block. You can right-click
the link badge to access link menu options.

The color and icon of the link badge indicates the status of the link.

Link Badge Status


Black links Active link

Gray separated Inactive link


links

Black links with a Active and modified (parameterized link)


red star icon

White links, black Locked link


background

See Also

More About
• “Linked Blocks” on page 45-12

45-21
45 Working with Block Libraries

• “Disable or Break Links to Library Blocks” on page 45-23


• “Restore Disabled Links” on page 45-27

45-22
Disable or Break Links to Library Blocks

Disable or Break Links to Library Blocks

Structural changes in a model include addition or deletion of blocks or adding ports while non-
structural changes include changes in parameter value.

A linked block does not allow structural changes to it. You can disable the link of a linked block from
its parent library block and perform required modifications. A disabled linked block behaves like a
local instance of a block and allows you to make structural and nonstructural changes.

To disable a link, right-click the linked block and select Library Link > Disable Link. The Disable
Link menu choice is made available only if the parent block of the linked block is disabled. If the
menu option is grayed out, you must disable the link of the parent block first.

Alternatively, you can right-click the link icon in the graph on the bottom left corner of the canvas and
click Disable Link. This action recursively disables the links of all the blocks up in the hierarchy.

To prevent unintentional disabling of a linked block, you can lock its links to the library. To lock a link,
in the Library window, on the Library tab, click Lock Links. You can later choose to unlock the
locked link by clicking Links Locked.

Note Simulink offers to disable the library links (unless the link is locked) when you try to make
structural changes to a block that contains active library links.

Do not use set_param to make structural changes to an active link. The result of this type of change
is undefined.

A disabled link of a linked block can be restored. For more information, see “Restore Disabled Links”
on page 45-27.

Disabled links can cause merge conflicts and failure to update all instances of the same model
component. In a hierarchy of links, you can accidentally disable all links without being aware of it,
and only restore one link while leaving others disabled.

Break Links
You can permanently break links to the parent library. Before you break a library link, the link must
first be disabled. When you break a link, the linked block is converted to a standalone block, and you
cannot detect what the block linked to previously.

To break a link, use any of these options:

• For disabled links, right-click the linked block and select Library Link > Break Link.
• To copy and break links to multiple blocks simultaneously, select multiple blocks and then drag.
The locked links are ignored and not broken.
• When you save the model, you can break links by supplying arguments to the save_system
command. For more information, see save_system.

Note

45-23
45 Working with Block Libraries

• Some models can contain blocks from third-party libraries or optional Simulink block sets.
Breaking the link for such models does not guarantee that you can run the model standalone. 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.
• Breaking a link can cause a model to fail when you install a new version of the library on a system.
For example, if a model block invokes a function that is supplied from a library. If you break the
link for such a block, the function can no longer be invoked from the model, causing simulation to
fail. To avoid such problems, avoid breaking links to libraries.

See Also
“Linked Blocks” on page 45-12 | “Restore Disabled Links” on page 45-27

45-24
Lock Links to Blocks in a Library

Lock Links to Blocks in a Library


You can lock links to a library. Lockable library links prevent unintentional disabling of these links.
Lockable libraries ensure robust usage of mature stable libraries.

To lock links to a library, in the Library window, on the Library tab, click Lock Links. The link from
the linked block to its parent library is now locked. When you refresh the model, you see a change in
the link badge. The locked link badges have a black background.

Locked linked block links cannot be disabled from the parent library block. Such links can only be
disabled from the command line by changing the LinkStatus to inactive. For more information,
see “Control Linked Block Programmatically” on page 45-34.

The context menu of a locked linked block displays Locked Library Link and not Library Link. Also
notice that the only enabled option on this menu is Go To Library Block.

If you open a locked linked block, the window title displays Locked Link: blockname. The bottom
left corner shows a lock icon and a link badge. You can also hover over the link badge to view lock
information.

To unlock links from the Library window, on the Library tab, click Links Locked. If the library is
locked, the option to lock or unlock the links is disabled. You must unlock the library to enable the
option.

Rules for Locked Links


• Locked links cannot be edited. If you try to make a structural change to a locked link (such as
editing the diagram), you see a message that you cannot modify the link because it is either locked
or inside another locked link.
• 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.

45-25
45 Working with Block Libraries

• When you copy a block, the library status determines the status of a link (locked or not). 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 the links.
• If you use sublibraries, when you lock links to a library, lock links to the sublibraries.

See Also

More About
• “Linked Blocks” on page 45-12

45-26
Restore Disabled Links

Restore Disabled Links

You can restore a disabled linked block or push a linked block value to the parent library block either
individually or hierarchically.

Restore Disabled Links Individually


When you push or restore a disabled block in individual mode, the disabled or edited block is pushed
to or restored from the library, preserving the changes inside the block without acting on the
hierarchy. All other links are unaffected. You can restore or push individual disabled blocks in three
ways:

• Select the disabled linked block and in the Simulink toolstrip, on the Subsystem Block tab, select
Restore Link or Push Link.

• Right-click a disabled linked block and from the context menu, select Library Links and click
Push Link to push the changes or Restore Link to restore the values from the parent library
block.
• Right-click the link badge on the bottom-left corner of a disabled linked block and from the
context menu, click Push Links to push the changes or Restore Link to restore the values from
the parent library block.

Restore Disabled Links Hierarchically


When you push or restore disabled links in the hierarchy mode, the operation is applied to the whole
hierarchy of links. To push or restore in hierarchy mode, use the Library Link Manager tool. The
Library Link Manager displays all the disabled and parameterized linked blocks in the model.

You can launch the Library Link Manager in two ways:

• In the Modeling tab of the Simulink toolstrip, go to Design section, and select Library Link
Manager.

or
• Select any disabled linked block in the model and in the Subsystem Block tab of the Simulink
toolstrip, click Link Manager.

45-27
45 Working with Block Libraries

The Library Link Manager window appears. It has two tabs showing disabled Links and
parameterized links in the model. By default, the Disabled Links tab is selected.

The table shows two columns where the Linked Block column displays the list of linked blocks
that have disabled links and the Library Block column displays the parent library block of the
corresponding linked blocks.

To push or restore disabled blocks,

1 Select the disabled block or blocks as per your requirement.


2 Click Push to replace the version of the block in the library with the version in the model or
Restore to replace the version of the linked block in the model with the version in the library.

You can use the Filter Blocks field to filter the displayed linked blocks based on your preference.
This is useful when you have a huge number of blocks in the model.

45-28
Restore Disabled Links

Pushing or Restoring Link Hierarchies

Pushing a hierarchy of disabled links affects the disabled links inside and outside 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 unchanged. This operation does not affect outer (parent)
links with changes unless you also explicitly selected them for push. The Library Link Manager starts
to push from the lowest inside links and then moves up in the hierarchy.

For 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.
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 Library Link Manager can manipulate only the top
level.

Tip To compare files and view structural changes, in the Modeling tab, select Compare > Compare
Models.

See Also

More About
• “Linked Blocks” on page 45-12
• “Restore Parameterized Links” on page 45-30

45-29
45 Working with Block Libraries

Restore Parameterized Links

A parameterized link is created when you change the parameter values of the child blocks of a linked
subsystem block. You can choose to push the new values from the linked block to the parent block or
restore the linked block with values from the parent block. You can push or restore parameterized
links using the Library Link Manager.

To restore or push parameterized links:

1 In the Simulink toolstrip, go to Subsystem Block tab, and click Link Manager.

The Library Link Manager opens. Click the Parameterized Links tab to display all the
parameterized links in the model.

The table has the following columns:

• Block - Displays the block name.

45-30
Restore Parameterized Links

• Parameter - The name of the parameter in the block.


• Parameterized Value - The changed value of any edited parameter in the model.
• Library Value - The original value of the parameter in the parent library block.
2 Select the blocks you want to push or restore.
3 Click Push to replace the value of the block in the library with the parameterized value in the
model or Restore to replace the version of the linked block in the model with the version in the
library.

See Also

More About
• “Parameterized Links and Self-Modifiable Linked Subsystems” on page 45-15
• “Linked Blocks” on page 45-12
• “Restore Disabled Links” on page 45-27

45-31
45 Working with Block Libraries

Fix Unresolved Library Links


If Simulink is unable to find either the library block or the source library on your MATLAB path
during a linked block update, the link becomes unresolved. Simulink changes the appearance of these
blocks.

Install Missing Product


Simulink helps you find and install missing products that a model needs to run.

• Blocks are labeled with missing products (for example, SimEvents not installed).
• Tooltips include the name of the missing product.
• Diagnostic messages provide links to open the Add-On Explorer and install any missing products.
• When you double-click the block, the dialog box provides a link to open the Add-On Explorer and
install any missing products.

Resolve Path to Source Block


If Simulink is unable to find the library, you can fix the unresolved link using one of these methods:

• Fix the reference to point to the correct location of the library block. Double-click the block to
open its dialog box. Then, correct the path of the library block in the Source block text box and
click OK.

45-32
Fix Unresolved Library Links

• 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. Then, on the Modeling tab,
click Update Model.

Specify Unresolved Block Details for Custom Libraries


You can set a custom message for a library that is displayed in a dialog box when there is an
unresolved link associated with a block from that library.

Use the set_param function to set the LibraryInfo parameter that describes the unresolved link
for a library EVlib.

set_param('EVlib', 'LibraryInfo',...
'To download the library, visit https://www.mathworks.com');

See Also

More About
• “Linked Blocks” on page 45-12
• “Display Library Links” on page 45-21

45-33
45 Working with Block Libraries

Control Linked Block Programmatically

Linked Block Information


Use the libinfo command to get information about the linked blocks in the model. libinfo also
provides information about the parent library blocks of a linked block.

For example, here is a model with linked blocks:

“Mask a Variant Subsystem” on page 43-91

When you execute the libinfo(gcb) command on this block:


Block: 'slexMaskVariantExample/VariantSubsystem2' %Linked block
Library: 'slexMaskingVariants_libraryblock' %Parent library block
ReferenceBlock: 'slexMaskingVariants_libraryblock/VariantSubsystem2'
LinkStatus: 'resolved' %Link status

The ReferenceBlock property gives the path of the library block to which a block links. You can
change this path programmatically by using the set_param command. For example:
set_param('slexMaskVariantExample/VariantSubsystem2','ReferenceBlock','slexMaskVariantExample2/VariantSubsystem')

Here, slexMaskVariantExample/VariantSubsystem2 is the original library block path and


slexMaskVariantExample2/VariantSubsystem is the new library block path.

Note It is not recommended to change the properties of a referenced block by using the set_param
command in the mask initialization code or callback code of the same block. For such modeling
patterns, you can use Variant blocks or use the ReferenceBlock parameter on the callback code or
the mask initialization code of the parent block of the reference block.

Lock Linked Blocks


Use the LockLinksToLibrary command to lock or unlock a linked block in a library from the
command line. When you set the value of LockLinksToLibrary to on, the linked block links to the
library are locked.

set_param('MyLibraryName', 'LockLinksToLibrary', 'on') %Lock links

set_param('MyLibraryName', 'LockLinksToLibrary', 'off') %Unlock links

Link Status
All blocks have a LinkStatus parameter and a StaticLinkStatus parameter to indicate whether
the block is a linked block.

Use get_param(gcb, 'StaticLinkStatus') to query the link status without updating the linked
blocks. You can use StaticLinkStatus to query the status of a linked block that is either active or
outdated.

Use get_param to send a query to get the value of the LinkStatus.

45-34
Control Linked Block Programmatically

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.
Suppose that A is a link to a subsystem in a library that contains the Gain
block. If you open A and select the Gain block, get_param(gcb,
'LinkStatus') returns implicit.
inactive Disabled link.

Use set_param to set the LinkStatus.

Set LinkStatus Value Description


none Breaks link. Use none to break a link, for example, set_param(gcb,
'LinkStatus', 'none').
breakWithoutHierar Breaks links in place without breaking the nested parent hierarchy of link.
chy For example, set_param(gcb, 'LinkStatus',
'breakWithoutHierarchy').
inactive Disables link. Use inactive to disable a link, for example,
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. It discards any
changes in the local copy of the library block.

restore 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. propagate is equivalent to Push Individual in the
Links Tool.
restoreHierarchy Restores all disabled links in the hierarchy with their corresponding library
blocks. restoreHierarchy is equivalent to Restore in hierarchy mode
in the Links Tool.
propagateHierarchy Pushes all links with changes in the hierarchy to their libraries.
propagateHierarchy is equivalent to Push in the Hierarchy mode of
the Links Tool. See “Restore Disabled Links” on page 45-27.

Note

• When you use get_param to query the link status of a block, the outdated block links also resolve.
• Using the StaticLinkStatus command to query the link status when get_param is being used
in the callback code of a child block is recommended. StaticLinkStatus command does not
resolve any outdated links.

45-35
45 Working with Block Libraries

If you call get_param on a block inside a library link, Simulink resolves the link wherever necessary.
Executing get_param can involve loading part of the library and executing callbacks.

See Also

More About
• “Linked Blocks” on page 45-12
• “Display Library Links” on page 45-21

45-36
Maintain Compatibility of Library Blocks Using Forwarding Tables

Maintain Compatibility of Library Blocks Using Forwarding


Tables
Forwarding Table allow you to check that the changes to blocks in a library do not break the model if
you have saved the model with an older version of the library block. Forwarding tables help you to
maintain compatibility of library blocks when you change the path or name of the library, or add,
remove, or rename the parameters in the library block. For more information see, “Create Custom
Library” on page 45-2.

Create a forwarding table entry for mapping old library blocks to new library blocks. When you open
the model, the links to the old library block are updated automatically without losing data or
functionality. Forwarding tables are executed when you open a model, close a model, or when you
execute the add_block or replace_block command.

Create a forwarding table entry when you:

• Rename a block.
• Move a block from one library to another library.
• Add or remove parameters from the block.
• Split the functionality of a block.

Forwarding Table Entry for a Renamed Block


Consider an example where the block name in a library testlib is renamed from ss1 to ss2.

1 Open the locked library Lib1.


2 In the Library window, on the Library tab, click Locked Library. The library is now unlocked for
editing.
3 On the Modeling tab, click Library Properties. The Library Properties dialog box opens.
4 Click the Forwarding Table tab.
5 Click Add New entry. A new row is added in the forwarding table.
6 Specify the name of the old block in Old Block Path and the corresponding new block path in
the New Block Path. If you do not know the path, select the block in the model and click Get
gcb button. The path of the block is automatically populated in the respective columns.

45-37
45 Working with Block Libraries

The mapping of the old path to new path is created in the forwarding table. Now, open a model that
contains links to the library. The links to the old library blocks in the model are updated automatically.
You can use the search bar above the table to filter the table contents. You can sort the columns in
ascending or descending order. You can also group columns by their values.

Assign Version Numbers to Library Blocks

In the Version column, you can specify a version number for the library block.

If the old block name is the same as new block name, the forwarding table populates the version
number automatically. The initial value of the library version LibraryVersion is derived from the
ModelVersion property of the library at the time the library link is created. Any subsequent updates
to the library block will update the library version to match the model version of the library.

The version number:

• Must be a numeric value.


• Must be of the format <major_version>. <minor_version> when the old and the new block
paths are the same.
• Must not have more than one dot notation. For example, a version number of 1.3 is acceptable. A
version number 1.3.1 is not acceptable.
• Format is not critical when you use a forwarding table to move a library block from one library to
another.

Move Block from One Library to Another


Consider an example where a block ss1 is moved from testlib1 to testlib2`. The forwarding
table entry in this case is shown here:

45-38
Maintain Compatibility of Library Blocks Using Forwarding Tables

Add or Remove Parameters from the Block


Consider an example where the Gain parameter of ss1 in library testlibis removed, and two other
parameters Initial condition and Delay length are added to it.

To handle this change we use a transformation function. A transformation function corrects the
mismatch of parameters between the new and old library links, which ensures that the library links
continue to work. You can define a transformation function using a .m function file on MATLAB path,
then call the function in the Transformation Function column of the Forwarding Table.

A linked block contains an instance of the block parameters in the form of name-value arguments to
instantiate the block. This instance data is passed to transformation function as InstanceData along
with forwarding entry. This data is stored as struct fields.

When you create versions of a library block, parameters are added or removed from the
InstanceData. In this example, the InstanceData before removal of the Gain parameter and after
the addition of initial condition and delay length looks like this

Before:
'RTWMemSecFuncInitTerm' 'Inherit from model'
'RTWMemSecFuncExecute' 'Inherit from model'

45-39
45 Working with Block Libraries

'RTWMemSecDataConstants' 'Inherit from model'


'RTWMemSecDataInternal' 'Inherit from model'
'RTWMemSecDataParameters' 'Inherit from model'
'ContentPreviewEnabled' 'on'
'Gain' '0'

After:

'RTWMemSecFuncInitTerm' 'Inherit from model'


'RTWMemSecFuncExecute' 'Inherit from model'
'RTWMemSecDataConstants' 'Inherit from model'
'RTWMemSecDataInternal' 'Inherit from model'
'RTWMemSecDataParameters' 'Inherit from model'
'ContentPreviewEnabled' 'on'
'DelayLength' '1'
'InitialCondition' '0'

This is the syntax for transformation function.

function outData = TransformationFcn(inData)

In this function syntax:

• inData is a structure with fields ForwardingTableEntry and InstanceData.


ForwardingTableEntry is also a structure.
• • The ForwardingTableEntry has the old name, new name, old path, and new path of a block.
Refer to the code to access the members of the ForwardingTableEntry.
• outData is a structure with fields NewInstanceData and NewBlockPath.

To add or remove parameters from a block:

1 Obtain the instance data and the forwarding table entry.


2 Extract the list of name-value pair and block names.
3 Get the old and new block names.
4 Check if the old and new block names are same. If so, then extract the versions of the block.
5 Check if the old version is 1.1 and the new version is 1.2. Then, remove the Gain parameter and
add the parameters Delay length and Initial condition.

Note You can have multiple transformation function files for your library. However, for effective
maintenance it is recommended that you have one transformation function file per library.

To add or remove parameters, use this transformation function.

function [outData] = txFcnTestlib(inData)


outData.NewBlockPath = '';
outData.NewInstanceData = [];

% Get linked block instance data and forwarding entry for which
% function is called
instanceData = inData.InstanceData;
forwardingTableEntry = inData.ForwardingTableEntry;

% Get list of name value pair and block names

45-40
Maintain Compatibility of Library Blocks Using Forwarding Tables

[ParamNames{1:length(instanceData)}] = instanceData.Name;

% Get old and new block paths or simply names


oldName = forwardingTableEntry.('__slOldName__');
newName = forwardingTableEntry.('__slNewName__');

% If block names are same and its subsys block in the lib
if strcmp(oldName, newName)
% Get old and new block versions from forwarding table
oldVer = forwardingTableEntry.('__slOldVersion__');
newVer = forwardingTableEntry.('__slNewVersion__');

% Each forwarding entry with different version can have separate


% entry. Here, for one single entry in forwarding table i.e.
% 1.2->1.3 or 1.3->2.0, we have separate transformation making one
% TX Fcn for one library or block.
if strcmp(oldName, 'testlib/ss1')
% Forwarding with same block name ss1
if oldVer == '1.1' && newVer == '1.2'
% Remove gain param
if (ismember('Gain',ParamNames))
for (i = 1:length(instanceData))
if (strcmp(instanceData(i).Name,'Gain') == true)
instanceData(i) = [];
break;
end
end
end

% Add delay length param


if (ismember('DelayLength',ParamNames))
for (i = 1:length(instanceData))
if (strcmp(instanceData(i).Name,'Value') == true)
instanceData(i).Value = '5';
break;
end
end
else
instanceData(end+1).Name = 'DelayLength';
instanceData(end).Value = '1';
end

% Add initial condition param


if (ismember('InitialCondition',ParamNames))
for (i = 1:length(instanceData))
if (strcmp(instanceData(i).Name,'InitialCondition') == true)
instanceData(i).Value = '0';
break;
end
end
else
instanceData(end+1).Name = 'InitialCondition';
instanceData(end).Value = '0';
end
elseif (oldVer == '1.2' && newVer == '1.3')
% Do version 1.2 to 1.3 specific changes
elseif (oldVer == '1.3' && newVer == '2.0')
% Do version 1.3 to 2.0 specific changes

45-41
45 Working with Block Libraries

else
% Do default changes not applicable to any version if
% required
end
elseif strcmp(oldName, 'testlib/ss2')
% Forwarding for block ss2 with version upgrade
end
elseif strcmp(oldName, 'testlib/oldblk') && strcmp(newName, 'testlib2/newblk')
% Block moved to new library or just block is renamed within same
% library, no version is checked here. Do transformation is
% required i.e. is block has been modified while renaming or moving
% to new lib.
elseif strcmp(oldName, 'testlib/blkX') && isempty(newName)
% We are splitting the block into 2 different blocks. Hence, kept
% newName empty in fwd table. Using one of the block param from its
% instance data (which is name-value pair of all block params) to
% decide how and what to divide.

% Get the index of param we are interested in i.e. param X


i = find(contains({instanceData.Name},'X'), true);

% Based on its value, do block splitting


switch (instanceData(i).Value)
case 'op1'
newName = 'newlibX/blkX';
% Remove existing param or add new param or modify existing
% params etc.
case 'op2'
newName = 'newlibY/blkX';
otherwise
newName = oldName;
end
end

% Return new instance data and new block path


outData.NewInstanceData = instanceData;
outData.NewBlockPath = newName;
end

Split Block Functionality


Splitting the functionality of a block involves adding, removing, or modifying the existing parameter
of the block and adding it to the new block. To split the functionality of a block:
1 Leave the newName argument empty.
2 Get the index and value of the parameter.
3 Split the block based on its value.
4 Return the NewBlockPath with the updated InstanceData if required.

Create Mask Parameter Aliases


If you rename a mask parameter, you must ensure that the existing MATLAB scripts that use the old
parameter names, continues to work. To check compatibility, you can create an alias for a mask
parameter name. An alias 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.

45-42
Maintain Compatibility of Library Blocks Using Forwarding Tables

Consider a masked block that contains an Edit parameter. The mask parameter name for this Edit
parameter is p1.

MaskObj = Simulink.Mask.get(gcb));
hEdit = MaskObj.getParameter('p1');

hEdit=
% MaskParameter with properties:

Type: 'edit'
TypeOptions: {0×1 cell}
Name: 'p1'
Prompt: 'p1'
Value: '0'
Evaluate: 'on'
Tunable: 'on'
NeverSave: 'off'
Hidden: 'off'
Enabled: 'on'
Visible: 'on'
ToolTip: 'on'
Callback: ''
Alias: ''

Notice that the Edit mask parameter does not have an alias. To add an alias for the mask parameter,
set a value for the Alias mask parameter property.

MaskObj.Alias = 'pa'

You can either use the mask parameter name or the alias to do a function call on the mask parameter.
For example, you can either use set_param(gcb, 'p1, '10) (mask parameter name) or
set_param(gcb, 'pa, '10) (mask parameter alias) to set a value for the Edit mask parameter.

See Also

More About
• “Linked Blocks” on page 45-12

45-43
46

Integrating Custom C/C++ Code

• “Specify and Configure Custom C/C++ Code” on page 46-2


• “Debug Custom C/C++ Code” on page 46-8
46 Integrating Custom C/C++ Code

Specify and Configure Custom C/C++ Code


You can specify sources of custom C/C++ code for your Simulink model. These sources can include
header files, source code files, and precompiled library files. Once you specify these sources, you can
use functions and variables from the sources in blocks such as the C Caller and C Function blocks.

Configure Custom Code

Specify Custom Code Settings for Simulation

The examples for specifying C source, header, and library files are based on this folder structure.

To configure your model to access custom code during simulation, follow these steps.

1 Open the Configuration Parameters dialog box. For information on how to do this, see “Set
Configuration Parameters by Using the Dialog Box” on page 13-2.
2 In the Simulation Target pane, in the Code Information tab, specify these parameters:

• Include headers — Enter the code to include at the top of the generated model.h header
file, which declares custom functions and data in the generated code. The code appears at the
top of all generated source code files and is visible to all generated code. For example, use
this parameter to enter #include and #define statements. When you include a custom
header file, you must enclose the file name in double quotes. For more information, see
“Include headers”.

Note

• The code you specify in this parameter can include extern declarations of variables or
functions, such as extern int x or extern void myfun(void). However, global

46-2
Specify and Configure Custom C/C++ Code

variable or function definitions such as int x or void myfun(void) cause linking errors
because the definitions appear multiple times in the source files of the generated code.

• Include directories — Enter a list of the folder paths that contain custom header, source,
and library files that you include either directly in the configuration parameters or indirectly
in the compiled target. You can separate entries with newlines, spaces, or semicolons. For
more information, see “Include directories”.

• Source files — Enter a list of source files to compile and link into the target separated by
newlines, spaces, or semicolons. For more information, see “Source files”.

46-3
46 Integrating Custom C/C++ Code

• Libraries — Enter a list of static libraries that contain custom object code to link into the
target, separated by newlines, spaces, or semicolons. For more information, see “Libraries”.

• Defines — Enter a space-separated list of preprocessor macro definitions to add to the


generated code. For more information, see “Defines”.
• Compiler flags — Enter additional compiler flags to be added to the compiler command line
when your custom code is compiled. For more information, see “Compiler flags”.
• Linker flags — Enter additional linker flags to be added to the linker command line when
your custom code is linked. For more information, see “Linker flags”.
3 Under Advanced parameters, check that Import custom code is selected. This parameter is
enabled by default.

For information on setting simulation options by using the command-line API, see “Set Configuration
Parameters Programmatically” (Stateflow).

46-4
Specify and Configure Custom C/C++ Code

Specify Custom Code Settings for Code Generation

To configure your model to access custom code for code generation, use the Code Generation >
Custom Code pane of the Configuration Parameters dialog box. You can use the same custom code
settings for code generation that you use for simulation or use unique custom code settings.

• To use the same custom code settings used for simulation, select Use the same custom code
settings as Simulation Target. Specify the custom code settings in the Simulation Target pane
as described in “Specify Custom Code Settings for Simulation” on page 46-2.
• To use unique custom code settings, clear Use the same custom code settings as Simulation
Target. In the Code Information tab, specify custom code settings for code generation. For
descriptions of the parameters in this tab, see “Specify Custom Code Settings for Simulation” on
page 46-2.

For more information, see Use the same custom code settings as Simulation Target (Simulink Coder)
and “Integrate External Code by Using Model Configuration Parameters” (Simulink Coder).

Specify Relative Paths to Custom Code

When you update your model or start the simulation, the model searches for custom code files in
these folders:

• Current folder
• Model folder (if this folder is different from the current folder)
• Custom list of folders that you specify
• All folders on the MATLAB search path, excluding the toolbox folders

You can specify the location of your custom code by using paths relative to one of these folders. For
instance, suppose that, in the previous example, you store the source and header files for your

46-5
46 Integrating Custom C/C++ Code

custom code in the model folder subfolders CustomCode/SourceFiles and CustomCode/


HeaderFiles. To access these files, use the Include directories parameter to specify the relative
paths of the subfolders.

Alternatively, you can use relative pathnames to specify the header and source files individually:

• Under Include headers, enter this pathname.

#include "./CustomCode/HeaderFiles/sf_custom_code_constants_vars_fcns_hdr.h"
• Under Source files, enter this pathname.

./CustomCode/HeaderFiles/sf_custom_code_constants_vars_fcns_src.c

Guidelines for Relative Path Syntax

When you construct relative paths for custom code, follow these syntax guidelines:

• Use a single period (.) to indicate the starting point for the relative path.
• Use forward slashes (/) or backward slashes (\) as file separators, regardless of the platform you
are using.
• Enclose paths in double quotes ("...") if they contain nonstandard path characters such as
spaces or hyphens (-).
• Enclose expressions with dollar signs ($...$) to evaluate them in the MATLAB workspace. For
example, suppose that CustomCodeFolder is a variable that you define in the MATLAB
workspace as "module1". If you specify your custom code files using the path name .\work
\source\$CustomCodeFolder$, then the model searches for the custom code files in the
folder .\work\source\module1.

46-6
Specify and Configure Custom C/C++ Code

See Also
“Model Configuration Parameters: Simulation Target” | “Integrate C Code Using C Caller Blocks” on
page 47-2 | “Integrate External C/C++ Code into Simulink Using C Function Blocks” on page 48-
2 | “Integrate C/C++ Code into Simulink” | C Caller | C Function

46-7
46 Integrating Custom C/C++ Code

Debug Custom C/C++ Code


When you integrate custom C/C++ code into your model, you can debug your code from within
Simulink by launching an external debugger and setting breakpoints in your custom code. This option
applies to custom code specified in the Simulation Target pane of the Model Configuration
Parameters dialog box. You can integrate this custom code into your model using any of these blocks:

• C Caller
• C Function
• MATLAB Function
• MATLAB System
• Stateflow chart

Note To debug custom code, the Import custom code check box in the Simulation Target pane of
the Model Configuration Parameters dialog must be selected. This parameter is selected by default.

This table gives information about debugger support.

Operating System Supported Debuggers


Windows Microsoft Visual Studio® IDE.
Visual Studio Code with MinGW® GDB. Requires
installation of MATLAB Coder Interface for Visual
Studio Code Debugging support package. See
https://www.mathworks.com/matlabcentral/
fileexchange/103555-matlab-coder-interface-for-
visual-studio-code-debugging.
macOS LLDB.
Visual Studio Code with LLDB. Requires
installation of MATLAB Coder Interface for Visual
Studio Code Debugging support package. See
https://www.mathworks.com/matlabcentral/
fileexchange/103555-matlab-coder-interface-for-
visual-studio-code-debugging.
Linux GNU® Data Display Debugger (DDD).
Visual Studio Code with GDB. Requires
installation of MATLAB Coder Interface for Visual
Studio Code Debugging support package. See
https://www.mathworks.com/matlabcentral/
fileexchange/103555-matlab-coder-interface-for-
visual-studio-code-debugging.

To select a compiler to use with C or C++ code, execute the command mex -setup C or mex -
setup C++.

To launch the external debugger, on the Debug tab of the Simulink toolstrip, in the Breakpoints
section, click the arrow to the right of the Add Breakpoint button. From the menu, select Set
Breakpoints in Custom Code.

46-8
Debug Custom C/C++ Code

Debugging is supported only when simulating in normal or accelerated mode and only in normal
mode for referenced models. If debugging is not supported, the button to launch the debugger is
disabled.

Once the debugger is launched, you can set breakpoints in your custom code.

Note The Select Entities to Debug dialog box that lists all the entities that can be debugged in the
model opens if your model contains an S-function or S-function Builder block. Select the model name
under Model Custom Code in the dialog to debug the custom C/C++ code specified in the
Simulation Target pane of the Model Configuration Parameters dialog box.

When you simulate your model, the simulation pauses when it reaches a breakpoint in the custom
code. Note that when the simulation is paused during debugging, the simulation time step display at
the bottom of the Simulink window may not be up-to-date.

To end a debugging session, first detach the active process from the debugger, then close the
debugger window.

Caution Do not kill the process attached to the debugger. Issuing a kill command from the process
in which the debugger is running can cause MATLAB to stop running, and you can lose work.

46-9
46 Integrating Custom C/C++ Code

Note On Linux or macOS platforms, do not close the debugger before issuing a detach command
from the process in which the debugger is running.

Note To use the Microsoft Visual Studio debugger in in-process mode, you must set the value of the
Windows registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session
Manager\DebuggerMaxModuleMsgs to 4096 or greater.

To obtain the current value of DebuggerMaxModuleMsgs, execute this command in MATLAB.


winqueryreg('HKEY_LOCAL_MACHINE','SYSTEM\CurrentControlSet\Control\Session Manager','DebuggerMaxModuleMsgs')

If this registry key does not exist yet, this command will produce an error.

If this key does not exist or is set to a lower number than 4096, use this procedure to set it:

1 Start the Registry Editor.


2 Locate this subkey in the registry, and click Session Manager:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager
3 In the list of entries on the right, if DebuggerMaxModuleMsgs exists, go to step 6. Otherwise,
continue to step 4.
4 On the Registry Editor window, select Edit > New > DWORD Value.
5 In the list of entries on the right, change the new value name to DebuggerMaxModuleMsgs and
press Enter.
6 Right-click the DebuggerMaxModuleMsgs entry name and select Modify.
7 In the Edit DWORD Value dialog, in the Value data field, enter 4096. For the Base value, select
Decimal. Click OK.
8 Close the Registry Editor.
9 Reboot your machine.

In-Process and Out-of-Process Simulation

When simulating a model containing custom C or C++ code, you have the option to run the custom
code in a separate process outside of MATLAB. This process is called out-of-process simulation. This
option may be useful when debugging your custom code. By running in a separate process, problems
with the custom code do not cause MATLAB to crash, and you can more easily debug and resolve
such problems. Problems can arise due to unexpected exceptions in the custom code or errors in the
interface between Simulink and the custom code.

To enable out-of-process simulation, in the Model Configuration Parameters dialog box, in the
Simulation Target pane, on the Import settings tab, select “Simulate custom code in a
separate process”.

46-10
Debug Custom C/C++ Code

If Simulate custom code in a separate process is not selected, that is, if you are using in-process
simulation, then when you launch an external debugger, the entire MATLAB process attaches to the
debugger. This action could cause the debugger to take more time to launch. Debugging is generally
faster with out-of-process simulation.

Debugging with out-of-process simulation is not supported on macOS, and not all custom code
functions are supported in out-of-process simulation. Note that simulation time is generally faster
with in-process simulation.

When you simulate a model out-of-process, if you encounter a run-time exception, Simulink gives you
the option to launch the external debugger. For example, this model contains a C Caller block that
calls the function adder(), which accesses an object called adderObj. Before calling the function,
the object must be created, which you can do by calling initAdder() from the Initialize code
specified on the Additional source code tab of the Simulation Target pane of the Model
Configuration Parameters dialog box.

46-11
46 Integrating Custom C/C++ Code

If initAdder() is not called before adder(), then adder() attempts to access an uninitialized
pointer, which causes a run-time exception. During in-process simulation, this exception can cause
MATLAB to crash when you simulate the model. However, with out-of-process simulation, simulating
the model produces an error message within Simulink.

You can then click Open to launch your external debugger and resolve the issue that caused the
error.

46-12
Debug Custom C/C++ Code

After the debugger launches, it restarts the simulation and stops at the breakpoints of custom
function entries automatically.

See Also
C Caller | C Function

46-13
47

Integrate C Code in Simulink Models

• “Integrate C Code Using C Caller Blocks” on page 47-2


• “Use C Caller Block with Conditional Execution” on page 47-13
47 Integrate C Code in Simulink Models

Integrate C Code Using C Caller Blocks


In this section...
“Specify Source Code and Dependencies” on page 47-2
“N-D Array Handling” on page 47-4
“Call C Caller Block and Specify Ports” on page 47-5
“Map C Function Arguments to Simulink Ports” on page 47-5
“Create a FunctionPortSpecification Object and Edit C Caller Block Properties” on page 47-10
“Create a Custom C Caller Library” on page 47-10
“Debug Custom Code” on page 47-11
“Generate Code from Model” on page 47-11
“Limitations” on page 47-11

You can integrate new or existing C code into Simulink using the C Caller block. To create custom
blocks in your Simulink models, the C Caller block allows you to call external C functions specified in
external source code and libraries. The advantages of the C Caller block are:

• Automated integration of simple C functions including functions defined under namespace


• Integration with Simulink Coverage, Simulink Test, and Simulink Design Verifier
• Integration with Simulink Coder

The C Caller block and the C Function block allow you to bring C algorithms into Simulink. To model
dynamic systems, use the S-Function Builder instead. Next steps describe the workflow to integrate C
code into Simulink using the C Caller block.

Note C99 is the standard version of C language supported for custom C code integration into
Simulink.

Specify Source Code and Dependencies


Specify your external source code file that contains your C functions.

1 From Simulink toolstrip, open the Configuration Parameters.


2 In the left pane, select Simulation Target.
3 Select Include headers and enter the name of your header file with the #include tag.

47-2
Integrate C Code Using C Caller Blocks

The directories and file paths can be absolute and relative file paths to model directories or to
the current working directory. See “Specify Relative Paths to Custom Code” (Stateflow).

Tip After you have entered information for Source files in the next step, you can click Auto-fill
from source files to have the header file name filled in automatically, using information
contained in your source files.
4 Select Source files and enter the path and the name of the source file. If the model and the
source files are in different directories, enter the directory that contains the source file before
the file name.

5 Select Include directories, and enter the folders where additional build information, such as
header files, are stored.

47-3
47 Integrate C Code in Simulink Models

To verify that your custom code can be parsed and built successfully, click Validate.

Note If your header file declares a function but your source files do not define the function, by
default the function is not visible in the C Caller block dialog. You can set the Undefined function
handling parameter in Configuration Parameters to specify other behaviors in this situation,
including throwing an error, generating a stub function, or ignoring the condition.

Note To use a C Caller block in a For Each subsystem or with continuous sample time, or to optimize
the use of the block in conditional input branch execution, the custom code function called by the
block must be deterministic, that is, always producing the same outputs for the same inputs. Identify
which custom code functions are deterministic by using the Deterministic functions and Specify
by function parameters in the Simulation target pane. For a conditional input branch execution
example, see “Use C Caller Block with Conditional Execution” on page 47-13.

N-D Array Handling


Simulink can pass N-D array data to custom code functions in C Caller blocks, and receive data from
such blocks. When you do so, you must specify the correct array layout to achieve the intended
results. See Default function array layout and Exception by function. For examples of the use of
array data with C Caller blocks, see “Use Custom Image Filter Algorithms as Reusable Blocks in
Simulink” and “Call Legacy Lookup Table Function Using C Caller Block” on page 48-27.

You can specify the order of how matrix data is handled in your C functions. Matrix data passed to
and from your C functions is converted if necessary to the array layout you specify. If the array layout
is not specified, the matrix data is passed through the C function in the same order of your Simulink
data, and computational errors may occur due to row-column major disagreement. Ensure that you
follow the same default function array layout for all Simulink data.

• Column-Major — The C function handles input array data in column-major order. Suppose that
you have a 3-by-3 matrix. In the C function, this matrix is accessed in this sequence: first column,
second column, and third column.
• Row-Major — The C function handles input array data in row-major order. Suppose that you have
a 3-by-3 matrix. In the C function, this matrix is accessed in this sequence: first row, second row,
and third row.
• Any — The C function is indifferent to the layout of input array data. This would be the case if, for
example, the function performs only element-wise operations on the data.
• Not specified — The C function makes no assumption about the layout of input array data.
Compared to the Any setting, you can generate code only in column-major setting. Attempting to
generate code in row-major setting produces an error. See Array layout. Select this option only if
needed for compatibility with older models.

To learn more about the row-major and column-major array layouts in Simulink, see “Default function
array layout”.

47-4
Integrate C Code Using C Caller Blocks

1 Select an array layout option under Default function array layout.


2 If you need to apply a specific array layout to some of the functions in your code, click Exception
by function to select these functions.
3 Click Apply to accept your changes.

If your C functions accept only scalar and/or vector inputs, the Default function array layout
setting has no effect.

Call C Caller Block and Specify Ports


You can start your custom C code integration into Simulink by typing C Caller in the Simulink
canvas. Alternatively, drag a C Caller block from the User-Defined Functions library onto the canvas.
Double-click the block to open the Block Parameters dialog box to see the names of your functions
and port specifications.

1
Click on the Refresh button to import your source code and its dependencies.
2 Your C functions are displayed under Function Name. If you do not see your full list of

functions, click on the to reimport your source code.


3
To view function definitions in the source file, click the . The source code for the selected
function is displayed in the MATLAB Editor. If the source code is not available, the function
declaration in the header file is displayed.
4 To change source files and their dependencies, or to define and select function array layouts,

click the custom code settings button to open the Simulation Target pane in Model
Configuration Parameters.

Map C Function Arguments to Simulink Ports


You can map C function arguments from your source code to Simulink ports using the Port
specification table in the C Caller block or by creating a FunctionPortSpecification object
through the command line. In your source code, the header file includes the C function arguments to
be connected to Simulink ports.

extern void mean_filter(const unsigned char* src,


unsigned char* dst,
unsigned int width, unsigned int height,
unsigned int filterSize);

The Port specification table shows the details of your arguments and how they connect to your C
Caller block in Simulink.

47-5
47 Integrate C Code in Simulink Models

The table has these columns:

Name

Specifies the name of input and output arguments. Name is the function argument or parameter
name as defined in your C functions from source code. This column is for reference purposes only.

Scope

Specifies how C function arguments map to the Simulink scope. Your arguments have default scopes
depending on the function definition, and you can change the scopes depending your function
definition in the source code.

Simulink Scope Scope to Block Mapping


Input Block input port
Output Block output port
InputOutput Block input and output port
Global Not applicable
Parameter Block tunable parameter
Constant Constant value

For an argument passed by pointer, when the argument has a constant qualifier definition such as
const double *u, the argument can only be an input or a parameter. When there is no constant
qualifier, the argument is an InputOutput by default, and you can change it to an Input, Output,
or Parameter scope. In the case of an Input or Parameter scope, ensure that the C function does
not modify the memory pointed to by the pointer. If the argument is of an Output scope, every
element pointed to by this pointer should be reassigned in every call for the function.

C Argument Simulink Scope


Function return Output
double u Input, Parameter, Constant

47-6
Integrate C Code Using C Caller Blocks

C Argument Simulink Scope


double *u InputOutput (default), Output, Input,
Parameter
double u[]

double u[][2]

double u[2][3]
const double *u Input (default), Parameter

const double u[]

const double u[][2]

const double u[2][3]

Use the InputOutput scope to map an input passed by a pointer in your C functions. Ports created
using an InputOutput scope have the same name for input and output ports. The InputOutput
scope enables reuse of buffer for input and output ports. This may optimize the memory use
depending on the signal size and the block layout.

To map a C function argument to an InputOutput scope, define the variable as a pointer in your
function.
extern void mean_filter(unsigned char* src,
unsigned int width, unsigned int height,
unsigned int filterSize);

Then set the scope to InputOutput in the Port Specification table and assign the resulting
function output to the input variable in the custom function.

You can use global variables in your custom code, mapping them to the appropriate Simulink scope.
To enable the use of global variables in your model, select “Enable global variables as function
interfaces” from Model Settings > Configuration Parameters > Simulation Target. You can map
the global variables to an Input, Output, InputOutput or Global scope on the C Caller block. The
availability of the these scopes depend on the use of the global variable in your custom code.

A Global scope enables you to transfer data between custom code and the C Caller block and lets
you use the global variable during calculations on the block. Values transferred using Global scope

47-7
47 Integrate C Code in Simulink Models

are not visible on the block interface. This table shows example code snippets and their default and
available ports.

Example Code Simulink Scope


double data; Global variable data only reads the variable
data. Available scopes are:
void foo(void)
{ Input (default)
int temp = data;
} Global
double data; Data is written to a global variable. Available
scopes are:
void bar(void)
{ Output (default)
data = 0;
} Global

InputOutput
double data; Data is both read and written on a global
variable. Available scopes are:
void foo2(void)
{ Global (default)
data = data + 1;
} InputOutput

Output

Label

Indicates the label for the corresponding argument in a Simulink block. By default, your argument
label is the same as the argument name, unless you change it. Change the Scope to configure the
options for the port labels.

Scope Simulink Port Label


Input, Output Port name
InputOutput Port name in both input and output ports
Global Port name and global variable name
Parameter Parameter name
Constant Expression for the constant value.

size expressions using input argument names, for


example size(in1,1)

Type

Specifies the data type of the argument. Data types in the C function must match equivalent data
types in Simulink. This table shows the supported C data types you can use in the C Caller block, and
the equivalent Simulink data types.

47-8
Integrate C Code Using C Caller Blocks

C Argument Data Type Simulink Data Type


signed char/unsigned char int8/uint8
char int8 or uint8, depending on the compiler
*
int/unsigned int int32/uint32
*
short/unsigned short int16/uint16
*
long/unsigned long int32/uint32 or int64/uint64, depending on
the operating system
long long/unsigned long long* int64/uint64
float single
double double
*
int8_t/uint8_t int8/uint8
*
int16_t/uint16_t int16/uint16
*
int32_t/uint32_t int32/uint32
*
int64_t/uint64_t int64/uint64
bool boolean
typedef struct {…} AStruct** Bus: AStruct
typedef enum {..} AnEnum** Enum: AnEnum
* If the C Caller takes an integer type, for example, int16_t, you can modify it to a fixed-point type
with matching base type, for example to fixdt(1, 16, 3).

** The C Caller sync button prompts you to import struct or enum types used by a C function as
Simulink bus and enumeration types.

Size

Specifies the data dimensions in the argument.

C Argument Dimensions Simulink Port Dimensions


double u scalar (1)
double u[] inherited (-1) (default)

double u[][2] If the argument is for an output port, its size must
be specified and cannot be inherited, unless the
argument is mapped to an InputOutput scope
or the model configuration parameter Simulate
custom code in a separate process is selected.
double *u inherited (-1) (default)

If the argument is for an output port, its size must


be specified and cannot be inherited, unless the
argument is mapped to an InputOutput scope
or the model configuration parameter Simulate
custom code in a separate process is selected.

For global variables, size is scalar (1).

47-9
47 Integrate C Code in Simulink Models

C Argument Dimensions Simulink Port Dimensions


double u[2][3] Size is [2, 3].

Note When using a pointer type as an output port, you must write to each element of the underlying
buffer in your C function. For example, if you use a pointer to a five-by-six matrix as an output, you
must write to all 30 elements. Otherwise, you may see unexpected values in the array.

Create a FunctionPortSpecification Object and Edit C Caller Block


Properties
To change Port Specification table properties programmatically, you can create a
FunctionPortSpecification object and modify its properties. To create a
FunctionPortSpecification object for a selected C Caller block in a model, type in the command
line:
myCCallerConfigObj = get_param(gcb, 'FunctionPortSpecification')

myCCallerConfigObj =

FunctionPortSpecification with properties:

CPrototype: 'real_T add(real_T u1, real_T u2);'


InputArguments: [1×2 Simulink.CustomCode.FunctionArgument]
ReturnArgument: [1×1 Simulink.CustomCode.FunctionArgument]
GlobalArguments: [1×0 Simulink.CustomCode.FunctionArgument]

The CPrototype property is read-only, and shows the declaration of C function input variables. The
InputArgument and ReturnArgument properties create a FunctionArgument object that you can
further edit its properties according to the rules defined for Port Specification table above. See
FunctionPortSpecification to learn more.

To modify the global arguments in a C Caller block, create a handle to the GlobalArguments object
using getGlobalArg and modify its properties.

Create a Custom C Caller Library


It is recommended to create a library model to group your C Caller blocks and keep your models
organized. You can also link a data dictionary to the library to hold custom types defined in your code.
Using a library model is especially useful when you have multiple models or a model reference
hierarchy that uses custom C code.
1 Open a new library model. On the Simulation tab, select New > Library.
2 On the Modeling tab, under Design, click Simulation Custom Code.
3 Select C or C++ in the Language option, depending on your code, and ensure the Import
custom code box is selected.
4 Follow the instructions in “Specify Source Code and Dependencies” on page 47-2 to add your
source files and their dependencies.
5 Create C Caller blocks to call C functions.
6 To insert a block from your library model to a Simulink model, simply drag the block into your
model.

47-10
Integrate C Code Using C Caller Blocks

You can also create a library of C Caller blocks from your custom code using the Simulink Code
Importer. See “Create Block Library from C/C++ Code”.

Debug Custom Code


You can debug your code from within Simulink by launching an external debugger and setting
breakpoints in your custom code. For more information, see “Debug Custom C/C++ Code” on page
46-8.

Generate Code from Model


The C Caller supports code generation. In the code generated from your model, each execution of a C
Caller block corresponds to a call to the external C function associated with the block. In order to
build the generated code, the Code Generation > Custom Code pane of the Model Configuration
Parameters must be populated with the correct information regarding the custom code. See “Model
Configuration Parameters: Code Generation Custom Code” (Simulink Coder).

Limitations
• Initialization/Termination of Custom Code Settings — If you need to allocate and deallocate
memory for your custom code, insert allocate and deallocate in the Initialize function and
Terminate function fields of custom code settings, or use a C Function block.
• Complex Data Support — The C Caller block does not support complex data types in Simulink.
• Variable Arguments — Variable arguments in C are not supported, for example, int
sprintf(char *str, const char *format, ...).
• C++ Syntax — The C Caller block does not support native C++ syntax directly. You need to write
a C function wrapper to interface with C++ code.

To test models that include C Caller blocks, see “Test Integrated C Code” (Simulink Test).

Note If a model has custom code, after the model is updated or run, the slprj folder may be locked
due to the loaded custom code simulation executable file. You cannot delete the folder when it is
locked. To unload the executable file and unlock the slprj folder, use the clear mex command. See
clear.

See Also
Blocks
C Caller | C Function | S-Function | S-Function Builder

Functions
getGlobalArg | legacy_code

Objects
FunctionPortSpecification

More About
• “Debug Custom C/C++ Code” on page 46-8

47-11
47 Integrate C Code in Simulink Models

• “Comparison of Custom Block Functionality” on page 44-5


• “Integrate C Code by Using the MATLAB Function Block” on page 50-119
• “Integrate C Functions Using Legacy Code Tool”
• “Row-Major and Column-Major Array Layouts” (MATLAB Coder)
• “Default function array layout”
• “Exception by function”

47-12
Use C Caller Block with Conditional Execution

Use C Caller Block with Conditional Execution

This example shows how to use a C Caller block with conditional execution. The example model
contains two C Caller blocks whose outputs are input branches into a Switch block. Each C Caller
block calls one of the custom C code functions sort_ascend() and sort_descend(). Only one of
the values from the input branches is passed to the output side of the Switch block. A C Function
block with the same settings can also be used in place of a C Caller block to call these custom code
functions.

This example illustrates the following concepts:

• Calling custom C code from a Simulink® block in a conditional execution context.


• Configuring deterministic functions by function in custom code.

Examine the Model

This model calls custom code through a C Caller block that is connected to an input branch of a
Switch block.

open_system('slexCCallerConditional');

Generate Code

The custom code functions in this model have not been identified as deterministic functions. When
code is generated from the model, both C functions are executed during simulation and in the
generated code, even though the Switch block requires the output of only one of the functions.

slbuild(bdroot);
cfile = fullfile('slexCCallerConditional_grt_rtw','slexCCallerConditional.c');
coder.example.extractLines(cfile,'/* Model step', '/* Matfile logging', 1, 0);

47-13
47 Integrate C Code in Simulink Models

### Starting build procedure for: slexCCallerConditional


### Successful completion of build procedure for: slexCCallerConditional

Build Summary

Top model targets built:

Model Action Rebuild Reason


=================================================================================================
slexCCallerConditional Code generated and compiled. Code generation information file does not e

1 of 1 models built (0 models already up to date)


Build duration: 0h 1m 21.879s

/* Model step function */


void slexCCallerConditional_step(void)
{
real_T rtb_CCallerascend[6];
real_T rtb_CCallerdescend[6];
int32_T i;

/* CCaller: '<Root>/C Caller (ascend)' incorporates:


* Inport: '<Root>/In2'
*/
for (i = 0; i < 6; i++) {
rtb_CCallerascend[i] = slexCCallerConditional_U.In2[i];
}

sort_ascend(&rtb_CCallerascend[0], 6);

/* End of CCaller: '<Root>/C Caller (ascend)' */

/* CCaller: '<Root>/C Caller (descend)' incorporates:


* Inport: '<Root>/In2'
*/
for (i = 0; i < 6; i++) {
rtb_CCallerdescend[i] = slexCCallerConditional_U.In2[i];
}

sort_descend(&rtb_CCallerdescend[0], 6);

/* End of CCaller: '<Root>/C Caller (descend)' */


for (i = 0; i < 6; i++) {
/* Switch: '<Root>/Switch' incorporates:
* Inport: '<Root>/In1'
*/
if (slexCCallerConditional_U.In1 > 0.0) {
/* Outport: '<Root>/Out3' */
slexCCallerConditional_Y.Out3[i] = rtb_CCallerascend[i];
} else {
/* Outport: '<Root>/Out3' */
slexCCallerConditional_Y.Out3[i] = rtb_CCallerdescend[i];
}

/* End of Switch: '<Root>/Switch' */


}

47-14
Use C Caller Block with Conditional Execution

Specify Custom Code Deterministic Functions

Open the Configuration Parameters dialog box.

In the Simulation Target pane, set Deterministic functions to By Function. Click Specify by
function and add the functions sort_ascend and sort_descend to the list. This action tells the
model that the specified custom code functions have deterministic behavior, that is, the same input
values to the functions always give the same outputs. If a function is set to be deterministic, it does
not need to be called if it is in the input branch corresponding to a false value of the Switch block.

47-15
47 Integrate C Code in Simulink Models

configset.highlightParameter(bdroot,'DefaultCustomCodeDeterministicFunctions');
set_param(bdroot,'DefaultCustomCodeDeterministicFunctions','ByFunction');
set_param(bdroot,'CustomCodeDeterministicFunctions','sort_ascend,sort_descend');

Generate Code Again

Now that you have specified the deterministic functions, the generated code is more efficient because
only the C Caller block in the true branch of the Switch block is executed. The same efficiency applies
when you simulate the model in Simulink.

slbuild(bdroot);
cfile = fullfile('slexCCallerConditional_grt_rtw','slexCCallerConditional.c');
coder.example.extractLines(cfile,'/* Model step', '/* Matfile logging', 1, 0);
close_system(bdroot, 0);

### Starting build procedure for: slexCCallerConditional


### Successful completion of build procedure for: slexCCallerConditional

Build Summary

Top model targets built:

Model Action Rebuild Reason


=======================================================================================
slexCCallerConditional Code generated and compiled. Generated code was out of date.

1 of 1 models built (0 models already up to date)

47-16
Use C Caller Block with Conditional Execution

Build duration: 0h 0m 29.655s

/* Model step function */


void slexCCallerConditional_step(void)
{
real_T rtb_CCallerascend[6];
int32_T i;

/* Switch: '<Root>/Switch' incorporates:


* Inport: '<Root>/In1'
*/
if (slexCCallerConditional_U.In1 > 0.0) {
/* CCaller: '<Root>/C Caller (ascend)' incorporates:
* Inport: '<Root>/In2'
*/
for (i = 0; i < 6; i++) {
rtb_CCallerascend[i] = slexCCallerConditional_U.In2[i];
}

sort_ascend(&rtb_CCallerascend[0], 6);

/* End of CCaller: '<Root>/C Caller (ascend)' */


} else {
/* CCaller: '<Root>/C Caller (descend)' incorporates:
* Inport: '<Root>/In2'
*/
for (i = 0; i < 6; i++) {
rtb_CCallerascend[i] = slexCCallerConditional_U.In2[i];
}

sort_descend(&rtb_CCallerascend[0], 6);

/* End of CCaller: '<Root>/C Caller (descend)' */


}

/* End of Switch: '<Root>/Switch' */

/* Outport: '<Root>/Out3' */
for (i = 0; i < 6; i++) {
slexCCallerConditional_Y.Out3[i] = rtb_CCallerascend[i];
}

/* End of Outport: '<Root>/Out3' */

See Also
“Deterministic functions” | “Specify by function” | C Function | C Caller

47-17
48

Integrate Algorithms Using C Function


Blocks

• “Integrate External C/C++ Code into Simulink Using C Function Blocks” on page 48-2
• “Interface with C++ Classes Using C Function Block” on page 48-7
• “Modify States of a C Function Block Using Persistent Symbols” on page 48-12
• “Change Values of Signals Using C Function Block and Buses” on page 48-14
• “Access Elements of a Matrix Using Output Code in a C Function Block” on page 48-16
• “Use External Functions with Matrix Input in a C Function Block” on page 48-18
• “Define an Alias Type in a C Function Block” on page 48-21
• “Use Enumerated Data in a C Function Block” on page 48-23
• “Use Inherited Sizes in a C Function Block” on page 48-25
• “Call Legacy Lookup Table Function Using C Caller Block” on page 48-27
• “Start and Terminate Actions Within a C Function Block” on page 48-29
• “Call C++ Class Methods Using C-Style Wrapper Function from C Function Block” on page 48-31
• “Call C++ Class Methods Directly from a C Function Block” on page 48-33
• “Call Legacy Lookup Table Functions Using C Function Block” on page 48-34
• “Use C Function Block Within For Each Subsystem” on page 48-36
48 Integrate Algorithms Using C Function Blocks

Integrate External C/C++ Code into Simulink Using C Function


Blocks
In this section...
“Write External Source Files” on page 48-2
“Enter the External Code Into Simulink” on page 48-3
“Specify Simulation or Code Generation Code” on page 48-5
“Specify Declaration for Target-Specific Function for Code Generation” on page 48-6

You can call and integrate your external C code into Simulink models using C Function blocks. C
Function blocks allow you to call external C code and customize the integration of your code using
the Output Code, Start Code, Initialize Conditions Code, and Terminate Code panes in the
block parameters dialog. Use the C Function block to:

• Call functions from external C code including functions defined under namespace, and customize
the code for your Simulink models.
• Preprocess data to call a C function and postprocess data after calling the function.
• Specify different code for simulation and code generation.
• Call multiple functions.
• Initialize and work with persistent data cached in the block.
• Allocate and deallocate memory.

Use the C Function block to call external C algorithms into Simulink that you want to modify. To call a
single C function from a Simulink model, use the C Caller block. To integrate dynamic systems that
have continuous states or state changes, use the S-Function block.

Note C99 is the standard version of C language supported for custom C code integration into
Simulink.

The following examples use C Function blocks to calculate the sum and mean of inputs.

Write External Source Files


Begin by creating the external source files.

1 Create a header file named data_array.h.

/* Define a struct called DataArray */


typedef struct DataArray_tag {
/* Define a pointer called pData */
const double* pData;
/* Define the variable length */
int length;
} DataArray;

/* Function declaration */
double data_sum(DataArray data);

48-2
Integrate External C/C++ Code into Simulink Using C Function Blocks

2 In the same folder, create a new file, data_array.c. In this file, write a C function that
calculates the sum of input numbers.

#include "data_array.h"

/* Define a function that takes in a struct */


double data_sum(DataArray data)
{
/* Define 2 local variables to use in the function */
double sum = 0.0;
int i;
/* Calculate the sum of values */
for (i = 0; i < data.length; i++) {
sum = sum + data.pData[i];
}
/* Return the result to the block */
return sum;
}

Enter the External Code Into Simulink


1 Create a new, blank model and add a C Function block. The C Function block is in the User-
Defined Functions library of the Library Browser.
2
Double-click the C Function block to open the block dialog. Click to open the Model
Configuration Parameters dialog. In the Simulation Target pane, define your header file under
Include headers on the Code information tab.

Tip After you have entered information for Source file in the next step, you can click Auto-fill
from Source files to have the header file name filled in automatically, using information
contained in your source files.
3 Define the source file under Source files on the Code Information tab. To verify that your
custom code can be parsed and built successfully, click Validate custom code.

48-3
48 Integrate Algorithms Using C Function Blocks

Note To use a C Function block in a For Each subsystem or with continuous sample time, or to
optimize the use of the block in conditional input branch execution, all custom code functions
called by the block must be deterministic, that is, always producing the same outputs for the
same inputs. Identify which custom code functions are deterministic by using the Deterministic
functions and Specify by function parameters in the Simulation target pane. If the block
references any custom code global variables, then Deterministic functions must set to All in
order for the block to be used in a For Each subsystem, in conditional input branch execution, or
with continuous sample time.

For an example showing a C Function block in a For Each subsystem, see “Use C Function Block
Within For Each Subsystem” on page 48-36.
4 In the Output Code pane of the C Function block parameters dialog, write the code that the
block executes during simulation. In this example, the external C function computes a sum. In the
Output Code pane, write code that calls the data_array.c function to compute the sum, then
computes the mean.

/* declare the struct dataArr */


DataArray dataArr;
/* store the length and data coming in from the input port */
dataArr.pData = &data[0];
dataArr.length = length;

/* call the function from the external code to calculate sum */


sum = data_sum(dataArr);

/* calculate the mean */


mean = sum / length;

You can specify code that runs at the start of a simulation and at the end of a simulation in the
Start Code and Terminate Code panes.
5 Use the Symbols table to define the symbols used in the code in the block. Add or delete a
symbol using the Add and Delete buttons. Define all symbols used in the Output Code, Start
Code, Initialize Conditions Code, and Terminate Code panes to ensure that ports display
correctly.

48-4
Integrate External C/C++ Code into Simulink Using C Function Blocks

In the Symbols table, for each symbol used in the code in the block, define the Name, Scope,
Label, Type, Size, and Port, as appropriate.

Close the block parameters dialog. After filling in the data in the table, the C Function block now
has one input port and two output ports with the labels specified in the table.
6 Add a Constant block to the Simulink canvas that will be the input to the C Function block. In the
Constant block, create a random row array with 100 elements. To display the results, attach
display blocks to the outputs of the C Function block.

Note If a model has custom code, after the model is updated or run, the slprj folder may be locked
due to the loaded custom code simulation executable file. You cannot delete the folder when it is
locked. To unload the executable file and unlock the slprj folder, use the clear mex command. See
clear.

Specify Simulation or Code Generation Code


You can specify different Output Code for simulation and code generation for the C Function block
by defining MATLAB_MEX_FILE. For example, to specify code that only runs during the model
simulation, use the following.

48-5
48 Integrate Algorithms Using C Function Blocks

#ifdef MATLAB_MEX_FILE
/* Enter simulation code */
#else
/* Enter code generation code */
#endif

Specify Declaration for Target-Specific Function for Code Generation


For code generation purposes, if you do not have the external header file with the declaration of a
function (such as a target-specific device driver) that you want to call from the C Function block, you
can include a declaration with the correct signature in the Output Code pane of the block. This
action creates a function call to the expected function when code is generated, as in the following
example:

#ifndef MATLAB_MEX_FILE
extern void driverFcnCall(int16_T in, int16_T * out);
driverFcnCall(blockIn, &blockOut);
#endif

See Also
Functions
addSymbol | deleteSymbol | getSymbol

Objects
SymbolSpec | Symbol

Blocks
C Function

More About
• “Debug Custom C/C++ Code” on page 46-8

48-6
Interface with C++ Classes Using C Function Block

Interface with C++ Classes Using C Function Block


You can use code that you specify in a C Function block to interface directly with C++ classes defined
in your custom code.

• Instantiate an object of a C++ class defined in your custom code.


• Read and write to public data members of the class object.
• Call public class methods (class member functions) of the object.

This example demonstrates the use of a C Function block with C++ classes.

Create Source Code Files


Before introducing your custom code, select C++ as the custom code language. In the Model
Configuration Parameters, on the Simulation Target pane, set Language to C++.

Next, create the header and source files. Create a header file named adder.h that defines a C++
class adder and its methods.

#ifndef _ADDER_CPP_
#define _ADDER_CPP_

class adder {
private:
int int_state;
public:
adder();
adder(int init_value);
int add_one(int increment);
int get_val();
};

#endif /* _ADDER_CPP_ */

Implement the class and its methods in a source file. Create the source file, adder.cpp.

#include "adder.h"

adder::adder()
{
int_state = 0;
}

adder::adder(int init_value)
{
int_state = init_value;
}

int adder::add_one(int increment)


{
int_state += increment;
return int_state;
}

48-7
48 Integrate Algorithms Using C Function Blocks

int adder::get_val()
{
return int_state;
}

Configure the C Function Block


To instantiate an object of a C++ class defined in the custom code in your model:

1 Add a C Function block to the model.


2 Double-click the C Function block to open it.
3 Define the header and source files:

a
Click the Configure custom code settings button to open the Configuration Parameters
window. In the Simulation Target pane, in the Code information tab, under Include
headers, define the header file by entering #include "adder.h".
b In the Code Information tab, under Source files, define the source file by entering
adder.cpp.

For more information, see “Enter the External Code Into Simulink” on page 48-3.
4 Define the class object. In the block dialog, in the Symbols table, click Add to define a symbol.
5 Specify the symbol properties. Set the Scope of the symbol to Persistent, set the name of the
object in the Name column, set the symbol Type by using the following format:

Class: <ClassName>

For example, this Symbols table instantiates an object of the adder class named obj. The
int_state property of obj is initialized with the default value of zero.

To pass arguments to the class constructor, enclose those arguments in parentheses, separated by
commas, following the symbol name in the Name field.

ObjectName(Argument1,Argument2,...)

You can use literal constants as well as expressions with Parameter and Constant symbols defined
in the Symbols table for the argument specification. Such expressions can use C syntax, including
expressions like &p and p[0], where p is a Parameter or Constant symbol. Overloaded class
constructors are supported.

For example, this Symbols table instantiates an object of the adder class named obj, and initializes
the int_state property of the object with the value of 10 by passing that value to the constructor.

48-8
Interface with C++ Classes Using C Function Block

Simulink creates the object at the start of simulation and destroys the object when simulation ends.
During simulation, the object is cached in the block as a block state like other Persistent symbols.
You cannot explicitly call the class constructor or destructor from the block.

You can use the Output Code and other code in the block to read and write to public data members
of the class object and to call public class methods of the object. Overloaded methods and operators
are supported, as are static methods. Default arguments for class methods are supported if they are
specified in the header file that defines the class.

Use Start Code or Initialize Conditions Code to initialize data members and Terminate Code to
call cleanup methods. The class object is created before the Start Code executes and is destroyed
after the Terminate Code executes. To access properties and methods, use dot notation.

PropertyValue = ClassObjectName.PropertyName;
ReturnValue = ClassObjectName.MethodName(Arguments);

In the Output Code, the block invokes the add_one method of obj. The block passes the block input
as an argument to the method and sends the return value to the block output.

If a class constructor or other class method receives multidimensional array data from Simulink or
passes such data to Simulink, you must specify the correct array layout to achieve the intended
results, as for any other custom code function. See “N-D Array Handling” on page 47-4. To indicate
the array layout of a class method in the dialog box for Exception by function, for the Function
Name, use the syntax ClassName::MethodName.

48-9
48 Integrate Algorithms Using C Function Blocks

Limitations
The C Function block cannot be used to directly access all C++ classes. These types of classes are
not supported:

• Template classes
• Standard Template Library (STL) containers
• Classes with private constructors and destructors

In such cases, you can access C++ class data members and methods indirectly by writing and calling
a C-style wrapper function. For an example, see “Call C++ Class Methods Using C-Style Wrapper
Function from C Function Block” on page 48-31.

Expressions used for constructor arguments are limited to literal constants and Parameter and
Constant symbols. Such expressions may not call other functions or access global variables.

The C Function block cannot call overloaded functions that are not class methods.

These actions are not supported in the code in the C Function block:

• Copying and assigning a class object


• Passing a class object to a function or method, either by value or by reference
• Explicitly calling a class constructor or destructor
• Defining a class
• Accessing class static data members
• Accessing multidimensional data members of a class

See Also

Related Examples
• “Call C++ Class Methods Directly from a C Function Block” on page 48-33

48-10
Interface with C++ Classes Using C Function Block

• “Integrate External C/C++ Code into Simulink Using C Function Blocks” on page 48-2

48-11
48 Integrate Algorithms Using C Function Blocks

Modify States of a C Function Block Using Persistent Symbols

This example shows a unit delay system where a C Function block takes in a sine wave signal and
delays its output by a specified sample period.

open_system('CFunctionPersistentExample');

An initial value, specified as a parameter, is cached in the block as persistent data in the Start Code
pane.

In the Output Code pane, a calculation is done on this state. A new input is passed to the block as
the next state at the next time step.

48-12
Modify States of a C Function Block Using Persistent Symbols

The Symbols table defines the attributes of the symbols used in the code. Note that the scope of the
initialValue symbol is specified as Parameter, so its value can be changed using the block
dialog. The state is defined as having Persistent scope. This value changes at each time step.

See Also
Objects
SymbolSpec | Symbol

Blocks
C Function

48-13
48 Integrate Algorithms Using C Function Blocks

Change Values of Signals Using C Function Block and Buses

This example shows how to use buses with a C Function block. In this example two Constant blocks
supply values. These signals are combined using a Bus Creator block. Code in the C Function block
changes the values of these signals. Using a Bus Selector block, the values are displayed separately
in two Display blocks.

open_system('mCFunction_BusWithoutCStruct')

The Output Code pane contains code that changes the values of the signals.

Add the symbols used in the code to the Symbols table. To use buses with a C Function block, set the
Type of the symbol to Bus: SimpleBus.

48-14
Change Values of Signals Using C Function Block and Buses

See Also
Objects
SymbolSpec | Symbol

Blocks
C Function

48-15
48 Integrate Algorithms Using C Function Blocks

Access Elements of a Matrix Using Output Code in a C Function


Block

This example shows how to access elements of a matrix from a C Function block using the Output
Code pane.

open_system('mMatrixColumnSumOutputCode')

Elements in each column of the input matrix are accessed and added to calculate a sum for each
column.

You must define all symbols used in code on the Symbols table of the Block Parameters. To set the
size of the input matrix, specify size as [r c]. r corresponds to the number of rows in the input
matrix and c corresponds to the number of columns in the input matrix.

48-16
Access Elements of a Matrix Using Output Code in a C Function Block

See Also
Objects
SymbolSpec | Symbol

Blocks
C Function

48-17
48 Integrate Algorithms Using C Function Blocks

Use External Functions with Matrix Input in a C Function Block

This example shows how to pass a matrix input to a C Function block and do row-major operations
using external custom code.

open_system('mMatrixColumnSumExternalCode');

In this example, a matrix input is used by external custom code to calculate the sum of the each
column of the matrix and the results are passed to the output block. The external function accesses
input array arr as row-major using arr[r][c].

The custom code is called in the Output Code pane of the C Function block.

48-18
Use External Functions with Matrix Input in a C Function Block

The external source and header files are specified on the Configuration Parameters > Simulation
Target pane.

48-19
48 Integrate Algorithms Using C Function Blocks

For the matrix input, the size of the input symbol on the matrix table is specified as [r c], where r
corresponds to the number of rows in the matrix input and c corresponds to the number of columns.

Specify the Default Function Array Layout

The external C function accesses input array arr using row-major layout. To ensure the validity of
calculations with MATLAB, go to Default Function Array Layout under Configuration
Parameters > Simulation Target and select Row-major.

48-20
Define an Alias Type in a C Function Block

Define an Alias Type in a C Function Block

This example shows how to specify alias data types in a C Function block. The model reads in a
source and header file from the Configuration Parameters > Simulation Target pane.
Calculations are performed using the functions in the source file.

Simulink.importExternalCTypes('multiply_func.h');
open_system('mCFunction_AliasType');

Define an Alias type in the header file

To define an alias type in your C source code to be used in your C Function block, use the typedef
keyword. In this example, a double alias is defined as typedef double doubleAlias in the
multiply_func.h file.

Specify the alias types in the C Function block

You must define your symbols in the Symbols table of the C Function block parameters. Define the
symbols in the block as alias types by entering the alias type in the Type column of the Symbols
table.

See Also
Objects
SymbolSpec | Symbol

48-21
48 Integrate Algorithms Using C Function Blocks

Blocks
C Function

48-22
Use Enumerated Data in a C Function Block

Use Enumerated Data in a C Function Block

This example shows how to define and use enumerated data in a C Function block. In this example, a
series of traffic lights are defined in an Enumerated Constant block using the Data Type Assistant.
The code that controls the traffic lights is written in the Output Code pane of the C Function block
dialog. In the Symbols table, the data types of the block inputs and outputs are defined as Enum:
classname. In this example, the enumerations are defined in the class TrafficLightColor_t, so
the type is defined as Enum: TrafficLightColor_t.

open_system('CFunctionEnum')

Output Code to Switch Traffic Lights

48-23
48 Integrate Algorithms Using C Function Blocks

Symbols Table to Define Enumerations

See Also
Objects
SymbolSpec | Symbol

Blocks
C Function

48-24
Use Inherited Sizes in a C Function Block

Use Inherited Sizes in a C Function Block

This example shows how to use a C Function block to compute a scaled vector dot product from two
input vectors. In this example, the C Function block takes two row vectors as inputs with inherited
sizes. The block scales the data using parameters. The vector dimension, which is used to define loop
indices in the C code, is defined as a constant. The block calculates the dot product, and displays the
results.

open_system('CFunctionVectorDotProduct');

In the C Function Block Parameters dialog, the Output Code pane contains the code that performs
the vector dot product calculations on the two input vectors.

You must define all symbols used in the code in the Symbols table of the Block Parameters. To specify
that the sizes of the input vectors are inherited, specify -1 in the Size field of the table. The symbols
scaleA and scaleB are defined as parameters of the block. These parameters appear on the block
parameter mask. The definitions of all symbols used in this example are shown in the following table.

48-25
48 Integrate Algorithms Using C Function Blocks

See Also
Objects
SymbolSpec | Symbol

Blocks
C Function

48-26
Call Legacy Lookup Table Function Using C Caller Block

Call Legacy Lookup Table Function Using C Caller Block

This example shows how to use the C Caller block to call legacy C functions that implement N-
dimensional table lookups.

In this example the legacy C functions are defined in lookupTable.h, and implemented in
directLookupTableND.c. The type definitions used in this example can be found in
your_types.h.

To enable calling the C functions from the C Function block, in the model, specify the header file and
the source file in the Configuration Parameters > Simulation Target pane. The prototype of the
legacy function being called in this example is:

FLT directLookupTableND(const FLT *tableND, const UINT32 nbDims, const UINT32


*tableDims, const UINT32 *tableIdx)

where FLT is a type definition to a floating-point type, and UINT32 is a type definition to an unsigned
32-bit integer.

• const FLT *tableND - Table


• const UINT32 nbDims - Dimensionality of the table
• const UINT32 *tableDims - Size of the table
• const UINT32 *tableIdx - Table index

In the C Caller block, tableND and tableDims are mapped to C Caller block parameters, nbDims is
a block constant, and tableIdx is the input to the block. The value returned by the legacy C function
is the output of the block.

mdl = 'slexCCallerLookupTable';
open_system(mdl);
sim(mdl);

48-27
48 Integrate Algorithms Using C Function Blocks

See Also
Blocks
C Caller | Direct Lookup Table (n-D)

Related Examples
• “Integrate C Code Using C Caller Blocks” on page 47-2

48-28
Start and Terminate Actions Within a C Function Block

Start and Terminate Actions Within a C Function Block

This example shows how to use the C Function block to integrate legacy C functions that have start
and terminate actions.

In this example, the legacy C functions are defined in fault.h, and implemented in fault.c.

To enable calling the C functions from the C Function block, in the model, specify the header file and
the source file in the Configuration Parameters > Simulation Target pane. This model opens a log
file, writes data to it, and then closes the log file. The openLogFile function is called in the Start
Code section and the closeLogFile function is called in the Terminate Code section of the C
Function block. In the Output Code section, the incAndLogFaultCounter function is called. The
prototype of the legacy functions are:

• void* openLogFile()
• closeLogFile(void* fid)
• incAndLogFaultCounter(void *fid, unsigned int counter, double time)

where, void *fid is a file pointer, unsigned int counter is the fault counter, and double time
indicates the time. The maximum value of InputVal signal can be 255. Each time the signal equals
or exceeds a constant value of 250, a fault condition is encountered, and the output code
incAndLogFaultCounter is invoked. The output code increases the fault counter by 1 and appends
a new line in slex_CFunction_fault.log file with time stamp. In the model, the fault signal is
represented by FaultVal signal.

In this example the ports of the C Function block are configured as follows:

• The file pointer returned by openLogFile function and the fault counter are persistent symbols
of the C Function block.
• The input of the C Function block is mapped to time.

model = 'slexCFunctionStartTerm';
open_system(model);
sim(model);

Use the Scope block to visualize the output. The output compares the InputVal signal value with the
value of FaultVal signal.

48-29
48 Integrate Algorithms Using C Function Blocks

open_system('slexCFunctionStartTerm/Scope')

See Also
Blocks
C Function | Enabled Subsystem

Related Examples
• “Integrate External C/C++ Code into Simulink Using C Function Blocks” on page 48-2

48-30
Call C++ Class Methods Using C-Style Wrapper Function from C Function Block

Call C++ Class Methods Using C-Style Wrapper Function from C


Function Block

This example shows how to use the C Function block to call C++ class methods using a C-style
wrapper function. For some C++ classes, such as template classes, the C Function block does not
support direct instantiation of class objects or calling of class methods, so it is necessary to use C
wrapper functions. See “Interface with C++ Classes Using C Function Block” on page 48-7. For an
example of a C Function block accessing C++ class members and methods directly, see “Call C++
Class Methods Directly from a C Function Block” on page 48-33.

In this example, the C-style wrapper functions are declared in adder_wrapper.h and implemented
in adder_wrapper.cpp.

To run this example model, you must configure MATLAB® to use a C++ compiler. This can be done
using the mex -setup command, and selecting a C++ compiler.

To enable calling of the C functions from the C Function block, in the model, specify the header file
and the source file in the Simulation Target pane of the Model Configuration Parameters dialog. In
this model the custom code header file adder_template.h defines an adder class template along
with the class member functions. The header file adder_wrapper.h contains declarations of C-style
wrapper functions which are called in the C Function block. The prototypes of the C-style wrapper
functions are:

• void *createAdder()
• void deleteAdder(void *obj)
• int adderOutput(void *obj, int increment)

where void *obj is the class object handle and increment is an input used by the adder function.

The createAdder function is called in the Start Code section of the C Function block dialog to
construct an object of the adder class. The deleteAdder function is called in the Terminate Code
section to destruct the adder class object. In the Output Code section, the adderOutput function is
called. In this example the ports of the C Function block are configured as follows:

• The adder class object, obj, return by the createAdder function, is a Persistent symbol of
the C Function block.
• The input of the C Function block is mapped to increment.
• The output of the C Function block is mapped to the return value of the adderOutput function.

48-31
48 Integrate Algorithms Using C Function Blocks

See Also
C Function

48-32
Call C++ Class Methods Directly from a C Function Block

Call C++ Class Methods Directly from a C Function Block

This example shows how to use the C Function block to call C++ class methods. In this example, a C
++ class and its methods are defined in adder_cpp.h and implemented in adder_cpp.cpp.

To run this example model, you must configure MATLAB® to use a C++ compiler. This can be done
using the mex -setup C++ command, and selecting a C++ compiler.

To enable access to the C++ class from the C Function block, in the model, specify the header file
and the source file in the Configuration Parameters > Simulation Target pane. In this model, the
custom code header file adder_cpp.h declares an adder class along with the class methods.

In the Output Code section, the class method is called. In this example, the ports of the C Function
block are configured as follows:

• The adder class object adderObj is a persistent symbol of the C Function block, which
instantiates the class object for use in the block. The object is destroyed at the end of simulation.
• The input of the C Function block is mapped to increment, which is an input argument to the
class method add_one.
• The output of the C Function block is mapped to output, which receives the return value of the
class method add_one.

See Also
C Function

Related Examples
• “Interface with C++ Classes Using C Function Block” on page 48-7

48-33
48 Integrate Algorithms Using C Function Blocks

Call Legacy Lookup Table Functions Using C Function Block

This example shows how to use the C Function block to call legacy C functions that implement n-
dimensional table lookups.

In this example the legacy C functions are defined in lookupTable.h, and implemented in
directLookupTableND.c. The type definitions used in this example can be found in your_types.h.

In the model, the header file and the source file are specified in Model Configuration Parameters
> Simulation Target. Now the C function can be called in the C Function block. The prototype of
the function being called in this example is:

FLT directLookupTableND(const FLT *tableND, const UINT32 nbDims, const UINT32


*tableDims, const UINT32 *tableIdx)

where FLT is a type definition to a floating-point type, and UINT32 is a type definition to an unsigned
32-bit integer.

This example defines two macro functions that use the function directLookupTableND, which are
called using the C Function blocks. They are:

• DirectLookupTable3D - 3D lookup table


• DirectLookupTable4D - 4D lookup table

Both these functions take the following input arguments:

• const FLT *tableND - Table


• const UINT32 *tableDims - Size of the table
• const UINT32 *tableIdx - Table index

where the tableND and tableDims are mapped to C Function block parameters and tableIdx is
the input to the block. The value returned by the legacy C function is the output of the block.

model = 'slexCFunctionLookupTable';
open_system(model);
sim(model);

48-34
Call Legacy Lookup Table Functions Using C Function Block

See Also
Blocks
C Function | Direct Lookup Table (n-D)

Related Examples
• “Integrate External C/C++ Code into Simulink Using C Function Blocks” on page 48-2

48-35
48 Integrate Algorithms Using C Function Blocks

Use C Function Block Within For Each Subsystem

This example shows how to use a C Function block within a For Each subsystem. The example passes
a vector signal into the For Each subsystem, which repeats execution of the C Function block on each
element of the input signal and concatenates the results. The C Function block calls the custom code
function customSaturateFcn(), which implements a saturation algorithm and outputs a clipped
version of the input signal. A C Caller block with the same settings can also be used in place of a C
Function block in a For Each subsystem.

This example illustrates the following concepts:

• Calling a C function from a Simulink® block inside a For Each subsystem.


• Configuring deterministic functions in custom code.

Examine the Model

This model calls custom code from a For Each subsystem. When the model runs, the scope displays
the output.

open_system('slexCFunctionForEach');

Identify Custom Code Deterministic Functions

Open the Configuration Parameters dialog box.

In the Simulation Target pane, set the value of Deterministic functions to All. This setting tells
the model that all custom code functions have deterministic behavior, that is, the same input values to
the function always give the same outputs. If a custom code function is specified as deterministic, it
can be safely called from a C Function or C Caller block inside a For Each subsystem. If not all
custom code functions are deterministic, specific functions can be set to be deterministic with the By
Function option. If a For Each subsystem contains a C Function or C Caller block that calls a custom
code function that is not specified as deterministic, Simulink produces an error.

48-36
Use C Function Block Within For Each Subsystem

configset.highlightParameter(bdroot,'DefaultCustomCodeDeterministicFunctions');
set_param(bdroot,'DefaultCustomCodeDeterministicFunctions','All');

Simulate the Model

Simulate the model and view the results.

sim(bdroot);
open_system('slexCFunctionForEach/Scope');

48-37
48 Integrate Algorithms Using C Function Blocks

See Also
“Deterministic functions” | “Specify by function” | C Function | C Caller | For Each Subsystem

48-38
49

Simulink Code Importer

• “Import Custom Code Using the Simulink Code Importer Wizard” on page 49-2
• “Import Custom C++ Class Using the Simulink Code Importer Wizard” on page 49-13
49 Simulink Code Importer

Import Custom Code Using the Simulink Code Importer Wizard

This example uses C code for a heat pump controller to show how to use the Simulink® Code
Importer wizard to import custom C/C++ code into a Simulink library. The example also shows how
to perform the equivalent actions using the Simulink Code Importer command-line interface in
MATLAB®. For more information, see “Create Block Library from C/C++ Code”.

Heat Pump Controller Custom Code

These C code source and header files contain the complete code for the heat pump controller.

The source files are in the src directory:

• tempController.c
• utils.c

The header files are in the include directory:

• tempController.h
• utils.h
• controllerTypes.h

The file tempController.c contains the algorithm for the custom C code for a heat pump unit. The
Controller function in that file uses the room temperature (Troom_in) and the set temperature
(Tset) as inputs. The output is a pump_control_bus type structure with signals that control the
fan, the heat pump, and the direction of the heat pump (heat or cool). The pump_control_bus
structure has these fields: fan_cmd, pump_cmd, and pump_dir. The pump_control_bus structure
type is defined in the file controllerTypes.h.

This table summarizes the output of the Controller algorithm.

Temperature Condition System State Fan Command Pump Command P


|Troom_in ‐ Tset| < DeltaT_fan Idle 0 0
DeltaT_fan <= |Troom_in ‐ Tset| < DeltaT_pump Fan only 1 0
|Troom_in ‐ Tset| >= DeltaT_pump and Tset < Troom_in Cooling 1 1
|Troom_in ‐ Tset| >= DeltaT_pump and Tset > Troom_in Heating 1 1

The Controller function uses two utility functions, absoluteTempDifference and


pumpDirection, which are defined in the utils.c file. The absoluteTempDifference function
returns the absolute difference between Tset and Troom_in as a double. The pumpDirection
function returns one of these PumpDirection type enum values.

Temperature Condition Pump Direction


Tset < Troom_in COOLING
Tset > Troom_in HEATING

The PumpDirection enum type is defined in the file controllerTypes.h.

49-2
Import Custom Code Using the Simulink Code Importer Wizard

Open the Code Importer Wizard

To open the Code Importer wizard, create an empty Simulink library where the src and include
folders are located and save it. For this example, the library is saved as heatpumpController.

Then, on the Modeling tab, select Design > Code Importer.

Specify the Simulink Library

Once the Welcome page loads, click Start to begin the import process.

49-3
49 Simulink Code Importer

On the Settings page:

1 The Library or model name field is auto-populated with the saved library name, in this case,
heatpumpController.
2 The Output folder field is auto-populated with location of the saved Simulink library.

Optionally, select Add generated library to the Simulink Library Browser to create an slblocks.m
file.

The slblocks.m file is used to add the generated library into the Simulink library browser. For more
information, see “Add Library to Library Browser” on page 45-8.

49-4
Import Custom Code Using the Simulink Code Importer Wizard

Click Next to continue.

Alternatively, to specify the library name and folder location programmatically, use the following
MATLAB code.
obj = Simulink.CodeImporter('heatpumpController');
obj.LibraryFileName = 'heatpumpController';
obj.OutputFolder = '$pwd$'; %This evaluates to the pwd

Specify the Custom Code to Import

On the Specify Custom Code page:


1 For Language, select C.
2 For Interface headers, specify the required header files. For this example, specify
tempController.h.
3 For Source files, specify the required source files. For this example, specify the
tempController.c and utils.c files location in the src folder as .\src
\tempController.c; .\src\utils.c.
4 For Include directories, specify the required include directories. For this example,
specify .\include.

49-5
49 Simulink Code Importer

Then, click Next.

Click Next on the Analyze page.

Alternatively, to specify the custom code programmatically, use the following code.

% The src and include directories should be located in pwd


obj.CustomCode.InterfaceHeaders = 'tempController.h';
obj.CustomCode.Language = 'C';
obj.CustomCode.SourceFiles = {'.\src\tempController.c', '.\src\utils.c'};
obj.CustomCode.IncludePaths = '.\include';

% Analyze the specified custom code


obj.parse();

Specify Import Settings

Specify Functions to Import

On the Configure page, select the functions to import into the Simulink library. For this example,
select Controller. Then, click Next.

49-6
Import Custom Code Using the Simulink Code Importer Wizard

Set the Block Port Specifications

For each function selected on the previous page, the wizard generates a function port specification.
The selected ports are used for the generated C Caller block.

49-7
49 Simulink Code Importer

In this example, the port specification table lists the formal arguments Tset, Troom_in, and out for
the Controller function.

Change the label of the out argument to control_out. Click Next.

Alternatively, to set the block properties programmatically, use the following code.
% Requires a successful obj.parse() to get the function objects
fcnObj = obj.ParseInfo.getFunctions();

%fcnObj =
%
% Function with properties:
%
% Name: "Controller"
% CPrototype: "pump_control_bus Controller(real_T Tset, real_T Troom_in);"
% PortSpecification: [1×1 Simulink.CodeImporter.SimulinkPortSpecification]
% IsEntry: 1
% IsDefined: 1
% IsStub: 0
% ArrayLayout: NotSpecified

49-8
Import Custom Code Using the Simulink Code Importer Wizard

% IsDeterministic: 0

fcnObj.PortSpecification.ReturnArgument.Label = 'control_out';

Specify Types to Import

Next, select the types to import into Simulink. If a type is required by the functions you selected for
import, it is selected and dimmed. For this example, pump_control_bus and PumpDirection is
required. The wizard creates a Simulink data dictionary containing this type and links the dictionary
to the generated library.

Click Next.

Specify Library Update Setting

This option is not available if you are importing the Controller function to the
heatpumpController library for the first time. This is available only if you have imported the
Controller function to the heatpumpController library at least once before. In such a scenario,
this page allows you to confirm the update operation to be performed on the library.

49-9
49 Simulink Code Importer

1 Select Replace existing blocks to replace the existing blocks with the new C Caller blocks for
the selected custom code functions.
2 Select Import as new blocks to preserve the existing blocks and add a new C Caller block for
the selected custom code functions.

For this example, select Import as new blocks, then click Next.

Create Test Harness

This option is available only if you have a Simulink Test™ license.

To test the imported custom code function using Simulink Test Manager, select Automatically
create test harness for all imported functions or classes. Each block in the created library will
be attached to an internal test harness.

For this example, select Skip. Click Next to generate the Simulink library.

49-10
Import Custom Code Using the Simulink Code Importer Wizard

After the code imports, the wizard creates a library attached to a Simulink data dictionary that
defines pump_control_bus as a Simulink.Bus object.

Alternatively, to create the test harness programmatically, use the following code.

49-11
49 Simulink Code Importer

% Requires Simulink Test license to generate the test harness


obj.Options.CreateTestHarness = true;
obj.import('Functions', 'Controller', ...
'Types', 'pump_control_bus', ...
'Overwrite', 'off');

If you have an existing project file (PRJ file), you can select Add, select the desired project file, and
add the generated file to that project.

Click Finish to close the wizard.

When you click Finish, select whether to save the current import settings to a JSON file. You can use
this file to load the Code Importer wizard with the current import settings.

See Also
“Import Custom C++ Class Using the Simulink Code Importer Wizard” on page 49-13 | “Integrate C
Code Using C Caller Blocks” on page 47-2 | C Caller | “Add Libraries to Library Browser” on page 45-
8 | “Create Block Library from C/C++ Code”

49-12
Import Custom C++ Class Using the Simulink Code Importer Wizard

Import Custom C++ Class Using the Simulink Code Importer


Wizard
Use Simulink Code Importer to import a custom C++ class into Simulink library.

In this workflow, the source file and the header file are adder_cpp.cpp and adder_cpp.h,
respectively.

For adder_cpp.h:
#ifndef _ADDER_CPP_
#define _ADDER_CPP_

class adder {
private:
int int_state;
public:
adder();
adder(int init_value);
int add_one(int increment);
int get_val();
};

#endif /* _ADDER_CPP_ */

For adder_cpp.cpp:
#include "adder_cpp.h"

/**********************************/
/**** Class method definitions ****/
/**********************************/

adder::adder()
{
int_state = 0;
}

adder::adder(int init_value)

You might also like