HDsudung Simulink
HDsudung Simulink
User's Guide
R2024a
How to Contact MathWorks
Phone: 508-647-7000
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
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
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
vii
Index and Search Models with Model Finder . . . . . . . . . . . . . . . . . 1-112
Configure and Search Databases . . . . . . . . . . . . . . . . . . . . . . . . . 1-112
viii Contents
Zero-Crossing Detection in Blocks . . . . . . . . . . . . . . . . . . . . . . . . . 3-22
ix
Modeling Dynamic Systems
Creating a Model
4
Create Template from Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
Edit a Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-2
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
xi
Initialization Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-82
Model InitFcn Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-82
Block InitFcn Callback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4-84
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
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
xiii
Sample Time in Subsystems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7-32
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
xv
Sample Time Consistency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-43
Sample Rates and Solvers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8-44
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
xvii
Conditional Subsystems
10
Conditionally Executed Subsystems Overview . . . . . . . . . . . . . . . . . 10-3
xviii Contents
Specify Initial Output Values Using Dialog Parameters . . . . . . . . . 10-58
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
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
xxi
Model Client that Requires Services . . . . . . . . . . . . . . . . . . . . . . 10-197
Configure Asynchronous Execution with Function Ports . . . . . . . 10-198
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
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
xxiv Contents
Introduction to Variant Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-62
xxv
Run Iterative Simulations Without Recompiling Model for Variant
Systems Using Fast Restart . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-118
xxvi Contents
Propagate Variant Conditions to Enable or Disable Model or
Subsystem References in Hierarchy . . . . . . . . . . . . . . . . . . . . . 12-170
xxvii
Export and Import Function Mockup Unit (FMU) from Model with
Variant Subsystem Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12-239
xxviii Contents
Compare Configuration Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13-10
xxix
Implicit and Explicit Partitioning of Models . . . . . . . . . . . . . . . . . . 14-31
Partitioning Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14-31
xxx Contents
Manage Signal Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15-30
Project Setup
16
Organize Large Modeling Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-2
xxxi
Automate Shutdown Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16-32
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
xxxii Contents
Run a Project Custom Task and Publish Report . . . . . . . . . . . . . . . 17-29
xxxiii
Investigate Problem Files in File List . . . . . . . . . . . . . . . . . . . . . . 18-25
xxxiv Contents
Disable Source Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-30
xxxv
Merge Text Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-63
Merge Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-64
Extract Conflict Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19-64
Project Reference
20
Componentization Using Referenced Projects . . . . . . . . . . . . . . . . . 20-2
xxxvi Contents
Simplify Comparison Report Using Filters . . . . . . . . . . . . . . . . . . 21-10
xxxvii
Large-Scale Modeling
23
Component-Based Modeling Guidelines . . . . . . . . . . . . . . . . . . . . . . 23-2
Should You Create Model Components? . . . . . . . . . . . . . . . . . . . . . 23-2
Define Model Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23-3
xxxviii Contents
Schedule Editor
25
What are Partitions? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25-2
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
xl Contents
Systematic Diagnosis of Errors and Warnings . . . . . . . . . . . . . . . . 27-56
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
Load and Save External Inputs for a Simulink Model with App
Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29-35
xlii Contents
Cursor Measurements Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-23
xliii
Modify Signal Generator Parameters . . . . . . . . . . . . . . . . . . . . . . 30-81
Remove Signal Generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30-82
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
xlv
Plot Multidimensional Signal Data . . . . . . . . . . . . . . . . . . . . . . . 31-133
Compare Multidimensional Signals . . . . . . . . . . . . . . . . . . . . . . . 31-134
Convert Representation of Frame-Based Data . . . . . . . . . . . . . . . 31-134
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
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
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
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
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
xlix
Solver Profiler
36
Examine Model Dynamics Using Solver Profiler . . . . . . . . . . . . . . . . 36-2
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
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
li
How to Improve Performance in Acceleration Modes . . . . . . . . . . 38-30
Techniques . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-30
C Compilers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38-30
Managing Blocks
lii Contents
Listen for Method Execution Events . . . . . . . . . . . . . . . . . . . . . . . 40-31
Synchronizing Run-Time Objects and Simulink Execution . . . . . . . 40-32
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
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
lv
Create a Logarithm Lookup Table . . . . . . . . . . . . . . . . . . . . . . . . . . 42-56
lvi Contents
Control Masks Programmatically . . . . . . . . . . . . . . . . . . . . . . . . . . . 43-32
lvii
Define Measurement Units for Masked Blocks . . . . . . . . . . . . . . . . 43-83
Validate Input and Output Port Signals Using Port Constraints 43-114
Validate Port Signals Among Ports of the Same Masked Block . 43-150
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
lix
Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-12
Rules for Linked Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-13
Linked Block Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45-13
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
lxi
Start and Terminate Actions Within a C Function Block . . . . . . . . 48-29
Import Custom C++ Class Using the Simulink Code Importer Wizard
.................................................... 49-13
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
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
lxiv Contents
MATLAB Toolbox Functions That Support Enumerations . . . . . . . . 50-94
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
lxvi Contents
Add and Implement Propagation Methods . . . . . . . . . . . . . . . . . . . 51-29
When to Use Propagation Methods . . . . . . . . . . . . . . . . . . . . . . . . 51-29
Implement Propagation Methods . . . . . . . . . . . . . . . . . . . . . . . . . 51-29
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
lxvii
Set Model Reference Discrete Sample Time Inheritance . . . . . . . 51-92
lxviii Contents
Publish the Created Blockset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52-16
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
lxx Contents
Display Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54-21
lxxi
Supported Variable Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57-13
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
lxxiii
Generate Code With Implicit Expansion Enabled . . . . . . . . . . . . . . 59-31
Output Size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-31
Additional Code Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-31
Performance Variation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59-33
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
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
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
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
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
lxxviii Contents
Compilation Directive %#codegen . . . . . . . . . . . . . . . . . . . . . . . . . . . 70-5
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
Resolve Issue: Cell Array Elements Must Be Fully Defined Before Use
......................................................... 72-8
Issue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-8
Possible Solutions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72-9
Managing Data
lxxx Contents
Data Types Remain double Despite Changing Settings . . . . . . . . . 73-11
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
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
lxxxiii
Test Custom File Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-148
Register Custom File Adapter . . . . . . . . . . . . . . . . . . . . . . . . . . . 73-150
Use Custom File Adapter to Load Variables for Simulation . . . . . 73-150
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
lxxxv
Load Input Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-5
Log Output Signal Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76-6
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
lxxxvii
Understand Mapping Results . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77-18
Alternative Workflows to Load Mapping Data . . . . . . . . . . . . . . . . 77-20
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
lxxxix
Override Signal Logging Settings with Signal Logging Selector . . 78-53
Override Signal Logging Settings Programmatically . . . . . . . . . . . 78-54
Log Data to the Workspace and a File Using the Record Block . . 78-83
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
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
Managing Signals
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
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
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
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
xcvi Contents
Customizing Simulink Environment and Printed Models
xcvii
Expand or Collapse Library in Browser Tree . . . . . . . . . . . . . . . . . 84-53
xcviii Contents
Model Component Testing
Component Verification
88
Component Verification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-2
Use Foundational Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88-2
Perform Rigorous Component Verification . . . . . . . . . . . . . . . . . . . . 88-2
xcix
Validate and Activate Variant Configuration . . . . . . . . . . . . . . . . . . . . . 89-18
Apply Variant Configuration on Model . . . . . . . . . . . . . . . . . . . . . . . . . 89-19
c Contents
Analyze Variant Configurations Programmatically . . . . . . . . . . . . . . . . . 89-90
ci
Reuse Variant Parameter Values from Handwritten Code Using
Simulink.Parameter Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90-46
cii Contents
Introduction to Simulink
103
1
Simulink Basics
The following sections explain how to perform basic tasks when using the Simulink product.
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.
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')
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
1-2
Programmatic Modeling Basics
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')
set_param('modelname','PreloadFcn','K=15')
After you save the model, the PreloadFcn callback executes when you next open the model.
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]);
Next, add lines to connect all the blocks in the model. Start by connecting the Sine1 and Pulse1
blocks using routed lines.
Sine1_Port = get_param('mymodel/Sine1','PortConnectivity')
Sine1_Port =
Type: '1'
Position: [185 100]
SrcBlock: []
SrcPort: []
DstBlock: [1×0 double]
DstPort: [1×0 double]
Pulse1_Port = get_param('mymodel/Pulse1','PortConnectivity')
Pulse1_Port =
Type: '1'
Position: [185 220]
SrcBlock: []
SrcPort: []
DstBlock: [1×0 double]
DstPort: [1×0 double]
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.
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');
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');
p = get_param(gcb,'PortHandles')
l = get_param(p.Outport,'Line')
set_param(l,'Name','s9')
1-5
1 Simulink Basics
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”.
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.
Parameter Determines
ScreenColor Model background
BackgroundColor Block and annotation background
ForegroundColor Block and annotation foreground
1-6
Programmatic Modeling Basics
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:
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
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.
Destination .
1-8
Keyboard Shortcuts and Mouse Actions for Simulink Modeling
appears.
To minimize the hints panel, press ? on your keyboard. When the hints panel is minimized, only the ?
button is visible.
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-9
1 Simulink Basics
1-10
Keyboard Shortcuts and Mouse Actions for Simulink Modeling
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
1-12
Keyboard Shortcuts and Mouse Actions for Simulink Modeling
1-13
1 Simulink Basics
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
1-15
1 Simulink Basics
1-16
Keyboard Shortcuts and Mouse Actions for Simulink Modeling
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
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
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:
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:
When the Simulink Library Browser is open in standalone mode, you can open a saved model from
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.
•
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.
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.
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.
You can specify a model template to use as the default template. A new model is created using the
default template when you:
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.
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.
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
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.
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
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
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 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.
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.
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”.
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
You can specify the action point by choosing the corresponding type of callback.
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.
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.
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.
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.
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
If you are unsure of which blocks to add to create your model, see “Explore Available Blocks Using
Library Browser” on page 1-34.
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.
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
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
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.
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.
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.
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.
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.
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.
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-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.
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
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:
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.
• 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: 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.
See Also
Related Examples
• “Create a Simple Model”
• “Programmatically Add and Connect Blocks” on page 1-3
1-47
1 Simulink Basics
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.
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.
• 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-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
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
1-51
1 Simulink Basics
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.
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
• 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-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.
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
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.
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.
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
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.
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
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
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:
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.
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.)
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.
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
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.
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
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.
To change an existing signal line label, double-click the label, then type the new label.
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.
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.
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.
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
For information about how to customize block icons, see “Customize Block Icons” on page 1-70.
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.
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.
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.
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.
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
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.
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.
1-71
1 Simulink Basics
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.
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
1 In the canvas, click and drag over a blank area to draw the area shape.
2 From the action bar, click 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.
• Text
• Images
• Equations generated using LaTeX and MathML commands
• Hyperlinks that open a website or run MATLAB functions
Use image annotations when you want to resize or move an image independently from text.
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.
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.
1 Add supported TeX commands to your annotation. For example, add this text:
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
zeta leq in
eta infty o
vartheta diamondsuit 0
mu uparrow cdot
nu rightarrow vee
xi downarrow wedge
pi circ perp
rho pm mid
Delta Im lceil
Theta Re rceil
1-79
1 Simulink Basics
Xi oplus rfloor
Pi oslash langle
Upsilon cup
Phi
Psi
Omega
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.
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
Tip
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.
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.
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.
1-82
Annotate Models
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:
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
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.
• 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.
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.
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
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
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.
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.
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:
1-89
1 Simulink Basics
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”.
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
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
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.
• 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
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.
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:
• 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.
When you pause on a resolved comment, you receive options to reopen the comment and to show the
block that corresponds to the comment.
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
The model as it appears in the Simulink Editor prints on a single page using portrait orientation and
without a print frame.
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.
1-98
Print Model Diagrams
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.
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.
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.
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:
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.
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
For example, here is the print log for the sldemo_enginewc model, with All systems enabled and
Enable tiled printing cleared.
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.
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
1-104
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).
1 In the Simulink Editor, on the Simulation tab, select Print > Print Details.
2 In the Print Details dialog box, select report options.
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
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
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
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'.
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.
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
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')
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.
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]')
openExample('simulink_general/VanDerPolOscillatorExample');
print -dpng -svdp vdp_model.png
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
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.
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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
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
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.
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
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.
2-10
How Stepping Through Simulation Works
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
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.
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.
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.
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.
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.
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
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.
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.
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
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
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:
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.
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.
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
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.
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 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:
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:
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.
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.
ẋ = 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.
F(ẋ, x) = 0
are considered to be implicit. For any given value of x, you must solve this equation to calculate ẋ .
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.
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.
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 two algorithms for this purpose: nonadaptive and adaptive. For information about
these techniques, see “Zero-Crossing Algorithms” on page 3-37.
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.
3-10
Zero-Crossing Detection
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
Use the following table to prevent excessive zero-crossing errors in your model.
3-18
Zero-Crossing Detection
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.
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.
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
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.
The following table lists blocks that register zero crossings and explains how the blocks use the zero
crossings.
3-22
Zero-Crossing Detection
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.
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:
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
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
model = 'mSelfResetIntegrator';
open_system(model);
3-25
3 How Simulink Works
3-26
Zero-Crossing Detection with Fixed-Step Simulation
3-27
3 How Simulink Works
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
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
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.
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 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.
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
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.
3-39
3 How Simulink Works
xa = u – xa.
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),
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:
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.
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.
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
The system has neither algebraic variables nor direct feedthrough and does not contain an algebraic
loop.
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.
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).
• 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:
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
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');
If the algebraic loop solver cannot solve the algebraic loop with the trust-region algorithm, try
simulating the model using the line-search algorithm.
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:
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
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
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
• 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.
The getAlgebraicLoops function highlights algebraic loops in the model, including algebraic loops
in subsystems. It also creates a report with information about each 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.
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.
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.
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
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)
Simulink.BlockDiagram.getAlgebraicLoops(mdl);
3-48
Remove Algebraic Loops
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);
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
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.
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.
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
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
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.
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.
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
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.
3-58
Remove Algebraic Loops
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
• 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.
Enabling block reduction can also help Simulink solve artificial algebraic loops.
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
• 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.
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.
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:
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.
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
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.
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:
• '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.
[sys,x0,blks,st] = modelName([],[],[],"sizes");
You can also execute the sizes phase without specifying any 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:
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.
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.
out = modelName(t,x,u,"outputs");
3-67
3 How Simulink Works
derivs = modelName(t,x,u,"derivs");
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 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.
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.
• 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.
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
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.
4-4
Write In-Model Documentation Using Notes
• 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.
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:
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 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 .
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
• 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_system(new_system)
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)
This example shows how to find the annotations in the vdp model and modify the properties of one of
the annotations programmatically.
4-9
4 Creating a Model
open_system('vdp')
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')
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');
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_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
get_param(h,'PlainText')
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(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')
The model no longer has an annotation with 'Van der Pol Equation' as text.
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_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>.';
a2.Interpreter = 'rich';
a2.Text = '<a href="matlab:magic(4)">Generate magic square</a>.';
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
img = fullfile(pwd,'drivingCar_24.png');
setImage(a,img)
Create Area
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.
This example shows how to create markup annotations, which can be easily hidden.
open_system(new_system)
Create two annotations, and move the second annotation so that it does not overlap the first
annotation.
4-15
4 Creating a Model
a2.MarkupType = 'markup';
a2.Text = 'This is a markup annotation.';
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.' }
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
• 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.
• 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”.
4-17
4 Creating a Model
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
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.
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.
4-20
Group Blocks into Subsystems
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.
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.
The contents of the subsystem appear in an area labeled with the name of the replaced block.
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.
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.
• 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
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.
4-26
Connect Subsystems
You can directly edit the port labels on these types of Subsystem blocks:
• Regular subsystem
• Subsystem with mask
• Variant subsystem
• Chart subsystem
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.
This table lists the update action depending on the type of port label defined on the Subsystem block.
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
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
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
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.
• 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.
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.
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.
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
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
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.
When you simulate a model, the whole hierarchy simulates, regardless of which level you are viewing.
4-34
Navigate Model Hierarchy
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.
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.
4-35
4 Creating a Model
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
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
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.
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.
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
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.
• 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.
This example shows you how to create and reference a subsystem file in a model. The example also
demonstrates these capabilities of subsystem references:
• 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.
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.
Subsystem references allow you to reference the same subsystem file multiple times in a model
without creating redundant copies.
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.
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.
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.
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.
4-40
Create and Use Referenced Subsystems in Models
2. To view the output, add Display blocks to both subsystem reference instances.
• 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.
As each subsystem reference instance is driven by its own set of inputs in the model, you must debug
and analyze each instance individually.
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
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:
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.
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.
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:
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
Do not reference a parent subsystem from a subsystem file because it creates reference loop.
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
This example shows how you can convert a Subsystem block in a model or library to a Subsystem
Reference block.
Consider a model sldemo_mdlref_conversion with a Subsystem block Bus Counter that models
a counter algorithm.
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');
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.
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
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.
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.
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.
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
new_system(subsystemfilename,'SubSystem')
Simulink.findBlocksOfType(bdroot, 'SubSystem',...
'ReferencedSubsystem','.',Simulink.FindOptions('RegExp',1))
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.
This command changes the file being currently referenced by the Subsystem Reference block and
replaces it with the new subsystem file you specify.
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
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.
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.
4-54
Change Subsystem Reference Component Dynamically Using InitFcn
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
4-56
Define Subsystem Reference Interfaces Using Test Harnesses and Generate Reusable Code
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:
Video Walkthrough
For a walkthrough of the example, play the video.
4-57
4 Creating a Model
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.
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:
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
4-61
4 Creating a Model
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
• for
• if-else
• switch
• while
4-62
Use Control Flow Logic
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.
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 Loops
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.
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).
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.
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).
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
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.
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.
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.
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
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.
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:
Defining callback code for this parameter may be useful for generating an
interface requiring a loaded model.
Limitations include:
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
Avoid InitFcn model callbacks that edit the structure of the model.
Simulink may execute or ignore these callbacks based on the model load
status.
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.
4-72
Model Callbacks
• Model A:
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.
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.
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.
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.
4-75
4 Creating a Model
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.
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.
4-76
Block Callbacks
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
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')
4-78
Block Callbacks
Use the following form for the callback code for the ErrorFcn
parameter:
where
If you provide the original exception, then you do not need to specify
the subsystem and the error type.
set_param(subsys,'ErrorFcn','errorHandler')
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
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.
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.
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.
• 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.
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
• 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
• 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.
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:
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”.
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
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.
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.
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.
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.
4-89
4 Creating a Model
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
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.
This example shows how to discretize the f14 model using the Model Discretizer.
model='f14';
open_system(model)
4-91
4 Creating a Model
To open the tool, in the Simulink Editor, on the Apps tab, under Apps, under Control Systems, click
Model Discretizer.
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
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.
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 in the Replace current selection with field. The options are
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.
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.
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.
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
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
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.
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
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.
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
To refresh the Model Discretizer tree view of the model when the model has been changed, click the
Refresh button.
4-98
Model Discretizer
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.
4-99
4 Creating a Model
a Click the Discretized Transfer Fcn block in the Library: discretizing window.
b Drag it into the f14/Aircraft Dynamics Model window.
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.
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.
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.
The parameter dialog box for the Discretized Transfer Fcn now looks like this.
9 Click OK.
4-103
4 Creating a Model
4-104
Model Discretizer
4-105
4 Creating a Model
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
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.
4-107
4 Creating a Model
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
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).
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.
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
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
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
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:
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
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.
5-3
5 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.
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).
5-4
Check Your Model Using the Model Advisor
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
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 =
'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
For more information on why a specific check does not pass, see the documentation for that check.
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
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.
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.
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).
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.
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
openExample("vdp")
To open the Upgrade Advisor, on the Modeling tab, select Model Advisor > Upgrade Advisor.
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.
You can save the results of all checks you run in a 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
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
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.
• 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.
7-3
7 Working with Sample Times
• 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:
7-7
7 Working with Sample Times
• 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
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.)
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.
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.)
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.
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.
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')
set_param('Specify_Sample_Time/Rate Transition',...
'OutPortSampleTime', '0.2')
To access the sample time of a single block, use the API Simulink.Block.getSampleTimes.
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
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.
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.
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.
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
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
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.
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
7-18
Types of 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.
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.
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”.
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.
• 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.
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.
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:
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.
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 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.
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).
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
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.
• 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.
7-23
7 Working with Sample Times
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
Use get_param to obtain the block CompiledSampleTime parameter for each of the blocks in this
example.
get_param('model_name/block_name','CompiledSampleTime');
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
• 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
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')
(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.
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.
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.
• 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
• 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.
• 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.
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.
• 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.
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
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.
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
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
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
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
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.
7-45
7 Working with Sample Times
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
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
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.
You can use the Rate Transition block in either of the following modes:
Alternatively, you can use target-specific rate transition blocks. The following blocks are available for
the example RTOS (VxWorks):
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:
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.
See Also
More About
• “Handle Rate Transitions” (Simulink Coder)
7-52
Handle Rate Transitions
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.
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 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.
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 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).
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.
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).
• 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.
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.
• 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.
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.
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.
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
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.
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.
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.
• 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
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
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.
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.
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 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
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.
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 update the sample time colors and annotations, update or simulate the model.
7-67
7 Working with Sample Times
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:
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
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.
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.
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 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.
For example, in the sldemo_mdlref_basic model, each Model block references the
sldemo_mdlref_counter model and has:
8-5
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 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.
Duplicate data definitions can exist in a model reference hierarchy under these conditions:
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.
8-7
8 Referencing a Model
To modify how a referenced model behaves and when it executes, consider these features:
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.
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 Reuse
You can reference a model more than once in a model hierarchy unless the referenced model has any
of these properties:
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).
• 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:
8-11
8 Referencing a Model
When you use S-functions in referenced models, consider these requirements and limitations.
8-12
Model Reference Requirements and Limitations
8-13
8 Referencing a Model
8-14
Model Reference Requirements and Limitations
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
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
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.
• 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
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.
•
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.
• 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.
8-18
Reference Protected Models from Third Parties
To verify the signature on protected models by default, in the Simulink Preferences dialog box, select
Verify digital signature of protected model before opening.
• 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.
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.
8-19
8 Referencing a Model
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.
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.
8-20
Reference Protected Models from Third Parties
8-21
8 Referencing a Model
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
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.
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.
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:
8-23
8 Referencing a Model
For the conversion to succeed, the model that contains the subsystem must compile successfully.
8-24
Convert Subsystems to Referenced Models
Conversion Results
After all conversion checks pass, the software:
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.
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
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
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.
8-28
Conditionally Execute Referenced Models
Conditional models must also meet the requirements specific to each type of conditional model.
8-29
8 Referencing a Model
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.
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
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.
8-32
Inspect Model Hierarchies
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')
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
8-34
Define Model Reference Interfaces
For example, in the sldemo_mdlref_basic model, each Model block references the
sldemo_mdlref_counter model and has:
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.
This table describes the type of ports and corresponding port blocks that a model reference interface
supports.
8-36
Define Model Reference Interfaces
• 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.
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:
To be notified when Simulink detects Model blocks that might not match their referenced models,
change the default setting for these diagnostic configuration parameters:
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
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.
• 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”.
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”.
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
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).
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.
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:
• 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.
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.
• 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.
8-43
8 Referencing a Model
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
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.
• 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.
8-45
8 Referencing a Model
8-46
Choose Simulation Modes for Model Hierarchies
8-47
8 Referencing a Model
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).
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.
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
8-49
8 Referencing a Model
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.
• 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.
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.
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
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.
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.
The override takes effect only during simulation. During edit time, the Model blocks do not display
the overridden simulation modes.
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)
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: ''
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);
Build Summary
8-53
8 Referencing a Model
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.
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)
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.
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: ''
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);
Build Summary
The specified instance of sldemo_mdlref_F2C simulates in normal mode. Its parent model,
sldemo_mdlref_heater, also simulates in normal mode.
Overriding the model reference simulation modes does not dirty any of the models.
Suppose you want to simulate the entire model hierarchy in normal mode for debugging.
topmodel = "sldemo_mdlref_depgraph";
set_param(topmodel,...
ModelReferenceSimulationModeOverride="all-normal");
sim(topmodel,Debug="on");
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.
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
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
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.
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.
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 different corner colors indicate the simulation mode and normal mode visibility setting.
8-60
Simulate Multiple Referenced Model Instances in Normal Mode
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.
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:
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.
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');
8-62
Simulate Multiple Referenced Model Instances in Normal Mode
Build Summary
blocks = get_param('sldemo_mdlref_depgraph',...
'CompiledModelBlockNormalModeVisibility')
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.
sldemo_mdlref_depgraph([],[],[],'term');
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:
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
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:
• 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
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.
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.
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
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:
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
• 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.
• 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.
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.
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
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
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.
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.
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
8-76
Set Configuration Parameters for Model Hierarchies
8-77
8 Referencing a Model
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.
• 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:
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.
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.
8-78
Set Configuration Parameters for Model Hierarchies
To identify the referenced models with diagnostics that are ignored during simulation in accelerator
mode, use the Model Advisor.
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
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.
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.
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).
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.
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:
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.
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:
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.
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.
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
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.
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.
• 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”.
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.
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.
• 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.
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.
8-88
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 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.
8-89
8 Referencing a Model
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.
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.
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.
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
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
This example shows how to programmatically configure multiple instances of a referenced model to
use different values for the same block parameter.
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_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));
set_param('ex_model_arg_ref','ParameterArgumentNames','coeffArg,gainArg')
8-93
8 Referencing a 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
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.
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_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;
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));
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')
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);
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);
myParamStructType = copy(slBus1);
Set the data type of the parameter objects in the base workspace by using the bus object.
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
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.
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];
temp.StructTypeInfo.Name = 'LUTArg_Type';
mdlwks = get_param('ex_arg_LUT_ref','ModelWorkspace');
assignin(mdlwks,'LUTArg',copy(temp))
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
open_system('ex_arg_LUT')
LUTForInst1 = Simulink.LookupTable;
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
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:
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.
• Inport
• In Bus Element
• Outport
• Out Bus Element
• Signal Specification
• MATLAB Function
• Chart
• 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.
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
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.
• 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.
• 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 (_).
• 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:
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.
9-5
9 Simulink Units
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.
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.
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
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.
9-10
Unit Consistency Checking and Propagation
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 :
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
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.
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.
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.
• 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
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.
model=ex_units_fuelsys;
open_system('ex_units_fuelsys')
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
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.
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.
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
The top model now shows a warning for mismatched units between the controller and plant. To
resolve this error, you can:
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:
For the EngSensors bus object, set the Unit parameter of each element.
9-20
Update an Existing Model to Use Units
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
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:
• 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.
• 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:
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:
Save this spreadsheet in a file such as unitsDB.xlsx. You can then create the database and load it.
This example shows how to create a custom units database and then load it.
createCustomDBFromExcel('unitsDB.xlsx')
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 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
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
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.
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.
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.
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”.
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.
9-27
9 Simulink Units
• 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.
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
10-2
Conditionally Executed Subsystems Overview
• 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.
• 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
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
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.
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.
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:
For most Outport blocks that connect to conditional subsystems, keep the Ensure outport is virtual
parameter cleared.
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.
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.
Select the Ensure outport is virtual parameter of the Outport block that connects to Enabled
Subsystem C.
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.
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.
10-8
Ensure Output Port Is Virtual
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:
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.
Code generated from this model includes two functions, Init_Proc and Run_Proc.
/* Model step function */
void Init_Proc(void)
{
int32_T s3_iter;
10-10
Ensure Output Port Is Virtual
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
• 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:
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.
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:
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
• 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
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.
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.
10-15
10 Conditional Subsystems
This subsystem is enabled when the AC waveform is positive and passes the waveform unchanged to
its output.
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.
10-16
Using Enabled Subsystems
Model Examples
For model examples, see:
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
• 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.
• 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.
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
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.
Model Examples
For model examples, see:
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
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
• 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
Open the subsystem, and then open the Enable port block. From the States when enabling
drop-down list, select:
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.
Model Examples
For model examples, see:
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
10-24
Select Subsystem Execution
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.
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.
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
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.
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.
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.
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
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
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).
This example shows how to execute a subsystem until a maximum value is reached.
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
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.
10-31
10 Conditional Subsystems
This example shows a subsystem that repeats execution during a simulation time step for a specified
number of iterations.
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
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
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.
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.
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.
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.
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.
These features can make the model more compact and easier to manage.
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.
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
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
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:
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.
% 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
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.
10-41
10 Conditional Subsystems
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.
% 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.
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.
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.
10-43
10 Conditional Subsystems
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.
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.
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
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).
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:
• 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.
• 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:
10-51
10 Conditional Subsystems
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
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:
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.
• A triggered (aperiodic) function-call subsystem can execute zero, one, or multiple times during a
time step.
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.
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
10-56
Conditional Subsystem Initial Output Values
• 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.
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.
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.
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
You can control the execution of model components, such as Subsystem and Model blocks, by using
export-function models or rate-based models.
• 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
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.
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.
10-60
Create Rate-Based Model
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
• 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.
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.
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.
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
1
In the Simulink Toolstrip, on the Apps tab, click Embedded Coder .
2
On the C Code tab that opens, click Build .
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.
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.
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();
}
10-66
Generate Code from Rate-Based Model
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
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.
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.
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.
10-70
Sorting Rules for Explicitly Scheduled Model Components
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:
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:
• 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.
• 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.
10-73
10 Conditional Subsystems
10-74
Conditional Subsystem Output Values When Disabled
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
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.
Use simplified mode if your model uses features that require simplified initialization mode, such as:
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 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.
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.
Conditional subsystems that include identical subsystems can display different initial values
before the first execution if both of the following apply:
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.
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.
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:
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
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.
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.
10-84
Classic Initialization Mode
produce unexpected results. The behavior depends on how you set the Output When Disabled
parameter.
10-85
10 Conditional Subsystems
When you simulate the model, the Scope block looks like the following:
10-86
Classic Initialization Mode
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.
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
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.
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.
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 either throws a false warning or no warning when all of the following conditions are true:
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
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
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.
10-98
Create Export-Function Model
4 At the top level of the model, add Inport and Outport blocks.
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.
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:
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
To create an export-function model for this example, see “Create Export-Function Model” on page 10-
98.
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
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
10-105
10 Conditional Subsystems
If a test model references an export-function model, there are some restrictions to ensure consistency
with simulation results.
• 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.
• 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.
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:
10-106
Test Export-Function Model Simulation Using Function-Call Generators
To test and observe the export-function model behavior before generating code, simulate the
completed test model.
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
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.
10-109
10 Conditional Subsystems
4 Open the chart by double-clicking the block. Add a State block and a Default transition arrow.
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.
10-110
Test Export-Function Model Simulation Using Stateflow Chart
If a test model references an export-function model, there are some restrictions to ensure consistency
with simulation results.
• 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.
• 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.
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:
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.
To test and observe the export-function model behavior before generating code, simulate the
completed test model.
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
10-113
10 Conditional Subsystems
10-114
Test Export-Function Model Simulation Using Schedule Editor
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.
1
On the Modeling tab, click Model Settings .
2 Verify the settings for these configuration parameters on the Solver pane:
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.
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
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
10-120
Generate Code for Export-Function Model with Rate-Based Model
In this example, the Sample time for the scheduled subsystem is set to 0.01.
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.
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
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.
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 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'.
*/
export_function_model_DW.UnitDelay_DSTATE =
export_function_model_Y.output_100ms + 1.0;
}
10-125
10 Conditional Subsystems
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.
• 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.
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
• All internal blocks within the block must support code generation.
• If the Trigger block Sample time type is set to:
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.
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
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.
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).
Simulink compares function-call Inport block properties to determine their relative execution order
using the following rules:
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.
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
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.
10-135
10 Conditional Subsystems
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
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.
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:
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.
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:
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 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.
• 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.
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.
10-142
Simulink Functions Overview
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.
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.
To open slexPrinterExample, see “Monitor Ink Status on Shared Printer Using Simulink
Functions”.
10-144
Simulink Functions Overview
• 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
• 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.
• 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.
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
•
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.
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.
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
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
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.
10-151
10 Conditional Subsystems
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.
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 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 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.
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.
Set parameters to export a graphical function to a Simulink model from a Stateflow chart during a
simulation.
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 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 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.
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
Set parameters to export a MATLAB function from a Stateflow chart during a simulation.
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
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.
10-159
10 Conditional Subsystems
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.
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.
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
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.
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.
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);}
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
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.
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
10-167
10 Conditional Subsystems
• 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.
10-168
Argument Specification for Simulink Function Blocks
A bus input to a Function Caller block must be a nonvirtual bus using a bus object.
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.
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.
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
• 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.
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.
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.
10-171
10 Conditional Subsystems
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.
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.
10-172
Simulink Function Blocks in Referenced Models
For the parent model, set the solver type to Variable-step or Fixed-step.
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.
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.
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.
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.
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
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
10-176
Scoped, Global, and Port-Scoped Simulink Function Blocks Overview
• 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
10-178
Scoped, Global, and Port-Scoped Simulink Function Blocks Overview
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
10-180
Scoped Simulink Function Blocks in Subsystems
• 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.
• 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.
• 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
• 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.
• 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.
• 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.
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
10-194
Model Client-Server Communication Using Function Ports
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).
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
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.
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:
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
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.
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.
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.
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
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
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.
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 an example, see “Monitor Ink Status on Shared Printer Using Simulink Functions” or “Dynamic
Priority Scheduling of Functions”.
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.
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
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.
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.
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.
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
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.
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.
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.
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.
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.
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
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.
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.
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
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.
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
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:
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.
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.
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.
10-230
Initialize and Reset Parameter Values
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 Function, Reinitialize Function, Reset Function, and Terminate Function blocks do not
support certain blocks, signals, and modeling patterns.
10-232
Initialize, Reinitialize, Reset, and Terminate Function Limitations
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.
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
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
This example shows how to use the Initialize Function block to perform these common initialization
actions.
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.
10-238
Common Uses of the Initialize Function Block
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.
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.
10-239
10 Conditional Subsystems
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.
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.
10-240
Common Uses of the Initialize Function Block
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.
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.
10-242
Common Uses of the Initialize Function Block
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.
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('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_system('initializeFunctionUsesEnv/Model','parameter')
10-245
10 Conditional Subsystems
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.
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_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_system('initializeFunctionUsesEnv/Simulink Function2')
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
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 visualize the result using Scope blocks.
sim('initializeFunctionUsesEnv.slx');
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.
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).
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_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
Open the example to access all the model and data files used in this topic.
open_system("ex_househeat_modeling");
10-251
10 Conditional Subsystems
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.
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:
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.
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.
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:
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
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
Replacing kA/D with 1/R where R is the thermal resistance simplifies the equation to
Define the rate of temperature change in the room by subtracting the rate of heat loss from the rate
of heat gain:
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.
You can use the constant names and values in this table when building the model.
10-254
Model House Heating System
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
10-255
10 Conditional Subsystems
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.
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.
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
The temperature difference is the current room temperature subtracted from the constant
temperature of the heater (T_heater).
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
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
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.
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
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.
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 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 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.
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
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.
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
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
The output of the Gain block is the change in room temperature (dTroom/dt). To get the current
room temperature (Troom), integrate the signal.
This equation is the rate of thermal energy loss through the walls and windows:
1 In the Room subsystem, add a Sum block. Set the List of signs parameter to |+–. Select the
10-264
Model House Heating System
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 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.
10-266
Model House Heating System
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.
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).
10-267
10 Conditional Subsystems
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.
10-268
Model House Heating System
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.
10-270
Model House Heating System
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.
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
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.
10-272
Model House Heating System
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')
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
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 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
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
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:
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 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.
• Import data
• Run a simulation
10-278
Model House Heating System
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')
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 your model to save (log) signal data during a simulation. You can then view logged signals
from a simulation using the Simulation Data Inspector.
Identify signals to display in the Simulation Data Inspector, name the signals if they are unnamed,
and set the logging parameters.
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')
The model simulation runs from 0.0 to 24.0 hours using the outside temperature data from the
root import block as input.
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.
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.
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.
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
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 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.
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
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:
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
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.
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.
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
open_system("ex_if_block_floatingpoint.slx");
The block parameters are set to their default values except for the parameters listed in this table.
10-293
10 Conditional Subsystems
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.
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.
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
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.
• 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.
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).
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.
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.
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
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
• 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.
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
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 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
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.
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.
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
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.
• 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
• 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 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
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.
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
11-19
11 Messages in Simulink
• The Overwrite the oldest element if queue is full check box is cleared. Observe the block icon
change.
• In the Statistics tab, the Number of entities departed, d and Number of entities in block, n
check boxes are selected.
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.
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
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
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
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.
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
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.
To create more complex networks and channel behavior, use combinations of these simple patterns.
• 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.
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
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.
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.
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.
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. 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
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.
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.
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
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.
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
• 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
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
• Open the Scope block connected top the Transmission Buffer block. The block displays the total
number of messages transmitted through the shared 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
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.
• A MATLAB Function block generates data with a size between 46 and 1500 bytes [ 1 ].
• A Bus Creator block converts the Data, PayloadSize, and DestAddress signals to a nonvirtual
bus object called dataPacket.
• 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.
11-49
11 Messages in Simulink
The Assemble Ethernet Frame blocks convert messages to Ethernet frames by attaching Ethernet-
specific attributes to the message [ 1 ].
• 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
• entity.TxAddress is StationID.
• 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.
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.
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:
• 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.
11-52
Model an Ethernet Communication Network with CSMA/CD Protocol
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
• 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 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
• 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
11-57
11 Messages in Simulink
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
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.
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 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
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.
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 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. 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
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.
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
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. 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
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 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.
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.
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
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.
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
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:
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.
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.
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
• Events
• Messages
• Function Calls
• State Changes and Transitions
Header Pane
The header pane below the Sequence Viewer toolbar shows lifeline headers containing the names of
the corresponding blocks in a model.
To open a block in the model, click the name in the corresponding lifeline header. To show or hide a
lifeline, double-click the corresponding header. To resize a lifeline header, click and drag its right-
hand side. To fit all lifeline headers in the Sequence Viewer window, press the space bar.
Message Pane
Below the header pane is the message pane. The message pane displays messages, events, and
function calls between lifelines as arrows from the sender to the receiver. To display sender, receiver,
and payload information in the Property Inspector, click the arrow corresponding to the message,
event, or function call.
11-79
11 Messages in Simulink
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
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
To make a lifeline the root of focus for the viewer, point over the bottom left corner of the lifeline
header and click the arrow. Alternatively, you can use the navigation toolbar at the top of the
Sequence Viewer window to move the current root up and down the lifeline hierarchy. To move the
current root up one level, press the Esc key.
The Sequence Viewer window displays the current root lifeline path and shows its child lifelines. Any
external events and messages are displayed as entering or exiting through vertical slots in the
diagram gutter. When you point to a slot in the diagram gutter, a tooltip displays the name of the
sending or receiving block.
11-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.
11-83
11 Messages in Simulink
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.
openExample("slexPrinterExample")
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.
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
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.
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.
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.
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
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).
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
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 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
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
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
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.
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
12-2
What Are Variants and When to Use Them
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.
12-3
12 Modeling Variant Systems
12-4
What Are Variants and When to Use Them
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
12-6
What Are Variants and When to Use Them
This table presents a comparison between hierarchical and inline variant blocks.
12-7
12 Modeling Variant Systems
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
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
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 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
12-12
What Are Variants and When to Use Them
12-13
12 Modeling Variant Systems
12-14
What Are Variants and When to Use Them
12-15
12 Modeling Variant Systems
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.
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.
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 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.
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.
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.
12-18
What Are Variants and When to Use Them
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.
12-20
Variant Terminology
variantConfig = Simulink.VariantConfigurationData;
set_param(model, 'VariantConfigurationObject',...
'variantConfig');
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:
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
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.
12-22
Variant Terminology
• get_param behavior:
• get_param behavior:
12-23
12 Modeling Variant Systems
• get_param behavior:
• get_param behavior:
12-24
Variant Terminology
12-25
12 Modeling Variant Systems
• get_param behavior:
• get_param behavior:
12-26
Variant Terminology
• get_param behavior:
Example: get_param(gcb,
'VariantActivationTime')
• set_param behavior:
Example:
set_param(gcb,'VariantActivationTim
e', 'update diagram')
12-27
12 Modeling Variant Systems
• get_param behavior:
Example: get_param(gcb,
'VariantControlVariable')
• set_param behavior:
Example:
set_param(gcb,'VariantControlVariab
le', 'variantCtrlVar')
• get_param behavior:
Example: get_param(gcb,
'VariantChoicesEnumeration')
• set_param behavior:
Example:
set_param(gcb,'VariantChoicesEnumer
ation', 'controllerEnum')
12-28
Variant Terminology
• get_param behavior:
Example: get_param(gcb,
'VariantChoicesSpecifier')
• set_param behavior:
Example:
set_param(gcb,'VariantChoicesSpecif
ier',"{'ControllersList/*',
'ControllersList/*/*'}")
• get_param behavior:
This section lists the command line parameters you can use to control Variant Source and Variant
Sink blocks during simulation or code generation.
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
• get_param behavior:
• get_param behavior:
12-30
Variant Terminology
• get_param behavior:
• get_param behavior:
12-31
12 Modeling Variant Systems
• get_param behavior:
Indicates if the
VariantControlExpression is to be
displayed on the block or not.
• set_param behavior:
• get_param behavior:
12-32
Variant Terminology
• get_param behavior:
Example: get_param(gcb,
'OutputFunctionCall')
• set_param behavior:
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
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.
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.
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
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.
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.
• 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.
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
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.
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.
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']);
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.
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
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_system('slexVariantSubsystems')
This section explains how to define variant control variables that determine the condition under
which a variant choice is active.
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.
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.
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.
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:
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
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.
• 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.
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.
You can add subsystems, Simulink models, and subsystem references as variant choices in a variant
subsystem.
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.
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.
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.
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
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
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.
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.
12-54
Implement Variations in Separate Hierarchy Using Variant Subsystems
• 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.
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.
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:
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.
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.
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.
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.
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
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
In the dialog box, select the variant choice and change its Variant control property to (default).
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.
You can specify the values of mode and version at the MATLAB Command Window.
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,
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
get_param(gcb,'CompiledActiveChoiceControl')
Use this command to find the path to the current active choice:
get_param(gcb,'CompiledActiveChoiceBlock')
Note
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
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:
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
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.
• 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
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.
• 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.
12-65
12 Modeling Variant Systems
set_param('Model/Controller/Linear Controller',...
'VariantControl', 'VSS_MODE == 1')
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.
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.
12-66
Variant Control Modes in Variant Blocks
For list of all examples, see “Use Variant Control Variables in Variant Blocks” on page 12-78.
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
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
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.
12-69
12 Modeling Variant Systems
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.
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).
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.
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.
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.
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
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
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.
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
12-74
Variant Control Modes in Variant Blocks
12-75
12 Modeling Variant Systems
12-76
Variant Control Modes in Variant Blocks
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
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
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.
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 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.
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 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.
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.
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');
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_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.
Ensure that the Linear Controller and NonLinear Controller blocks are atomic.
12-82
Use Variant Control Variables in Variant Blocks
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).
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_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
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.
Ensure that the Linear Controller and NonLinear Controller blocks are atomic.
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:
These enumerations are also supported when permanently stored in a Simulink® data dictionary. See
“Enumerations in Data Dictionary” on page 80-13.
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_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
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.
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.
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_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.
Ensure that the Linear Controller and NonLinear Controller blocks are atomic.
12-88
Use Variant Control Variables in Variant Blocks
Simulate the model. During simulation, the Linear Controller block becomes active.
sim('slexVariantSubsystems');
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
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.
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
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
• 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
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.
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”.
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
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.
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.
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
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.
This section lists the variant activation time supported by each type of 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.
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 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.
12-101
12 Modeling Variant Systems
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.
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.
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.
12-102
Activate Variant During Different Stages of Simulation and Code Generation Workflow
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.
12-103
12 Modeling Variant Systems
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
This example shows how to verify and validate variant models with code compile variant activation
time using 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.
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.
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:
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.
12-107
12 Modeling Variant Systems
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);
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.
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.
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.
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
12-109
12 Modeling Variant Systems
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
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];
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
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.
Use parsim to simulate the model in parallel for each variant control value.
You can simulate the model using parsim with SetupFcn. This is optional. If you run parsim
without SetupFcn, set the RapidAcceleratorUpToDateCheck to on.
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
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
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.
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,
12-115
12 Modeling Variant Systems
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
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
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
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
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.
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
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.
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
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
• 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
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 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
Step 2: Set the variant choice for which tests need to be generated, then analyze the model.
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);
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)
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.
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.
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.
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.
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.
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
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
12-129
12 Modeling Variant Systems
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
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
• 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.
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.
• 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.
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.
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
12-137
12 Modeling Variant Systems
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
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.
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.
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.
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.
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
//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
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
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.
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
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
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);
}
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
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
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.
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.
See Also
More About
• “Propagate Variant Conditions to Define Variant Regions with Variant Blocks” on page 12-133
12-154
Variant Elements Within Buses
This example explains how to create buses with elements having different variant conditions.
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:
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
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).
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
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.
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.
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.
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.
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.
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
For more information on conditionally executed systems, see “Conditionally Executed Subsystems
Overview” on page 10-3.
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.
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
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.
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.
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.
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
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:
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
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.
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.
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.
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
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.
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.
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
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.
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
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.
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")
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
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
• 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.
This section explains how to control the active variant choice of Variant Subsystem blocks and inline
variant blocks by using a 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:
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
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:
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.
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:
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.
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:
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
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 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
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
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.
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
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.
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
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.
• 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.
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
• “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
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.
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.
• 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
12-199
12 Modeling Variant Systems
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
Value — • controller_generic1
getMyFilteredListOfControllerChoices • controller_generic2
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
mdl = 'slexVariantAssemblySubsystemInExpression';
open_system(mdl)
vasBlkPath = [mdl, '/Controller'];
12-201
12 Modeling Variant Systems
type controllerTypesMfile
enumeration
linearController(0)
12-202
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files
nonlinearController(1)
end
end
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.
variantCtrlVar = controllerTypesMfile.linearController;
sim(mdl);
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')
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.
Simulink.defineIntEnumType('controllerTypesInMem', ...
{'linearController', 'nonlinearController'}, 0: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.
12-204
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files
variantCtrlVar = controllerTypesInMem.linearController;
sim(mdl);
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')
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.
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.
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]
out2 =
Simulink.SimulationOutput:
tout: [1001x1 double]
yout: [1001x1 double]
12-206
Add or Remove Variant Choices of Variant Assembly Subsystem Blocks Using External Files
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.
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
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
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
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
type vas_linearController.m
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
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
The value that you specify for vssObj in the mask dialog box is mapped to the mask parameter object
obj.
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.
12-210
Control Variant Choices in Masked Variant Assembly Subsystem Block Using Mask Parameter Object
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
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
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
enumeration
linearController(0)
nonlinearController(1)
end
end
type slexVasExprControllerVariant.m
properties
variantFile slexVasExprControllerTypes;
end
end
12-213
12 Modeling Variant Systems
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
12-214
Control Variant Choices in Masked Variant Assembly Subsystem Block 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.
ctrlObj = slexVasExprLinearController;
sim(mdl);
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
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
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
• VSS 1: The mask icon on the active variant block is plain text.
12-217
12 Modeling Variant Systems
• VSS 3: The mask icon on the active variant block is a built-in icon.
12-218
Automatic Mask Icon Promotion in Variant Subsystems
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
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).
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 =
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.
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;
if ~fidErr
fprintf(fid, '#endif\n');
fclose(fid);
end
end
Note The header file can be empty for the Define storage class.
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 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
12-224
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
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).
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.
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));
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.
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 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
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.
12-232
Create Real-Time Applications Using Variants and Simulink Real-Time
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
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.
2. Write MATLAB app which can tune the variant control value externally.
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.
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.
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
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”.
2. Drag and drop a Edit Field and a push Button as shown below.
12-237
12 Modeling Variant Systems
4. Launch the app to tune the value of the variant control. Simulate with different values to see the
result.
See More
12-238
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.
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');
c. In FMU Export dialog, specify the location to save the FMU to be generated.
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.
The FMU block lets you import your applications, contained in FMUs, into Simulink® to create a
model with 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
12-241
12 Modeling Variant Systems
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
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.
12-243
12 Modeling Variant Systems
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).
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
12-245
12 Modeling Variant Systems
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.
12-246
V-Model for System Development with Simulink Variants
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.
12-247
12 Modeling Variant 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.
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
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
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.
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
12-251
12 Modeling Variant Systems
12-252
V-Model for System Development with Simulink Variants
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.
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
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).
12-254
V-Model for System Development with Simulink Variants
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.
12-255
12 Modeling Variant Systems
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.
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.
12-256
V-Model for System Development with Simulink Variants
See Also
Related Examples
• “Simulink Variant Examples” on page 12-242
12-257
12 Modeling Variant Systems
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
model="sldemo_variant_subsystems";
open_system(model);
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])
find_system(model,[email protected])
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' }
set_param(model,"SimulationCommand","update");
Using the Simulink.match.activeVariants filter returns the blocks that are active in simulation.
find_system(model,[email protected])
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])
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])
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
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.
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.
• 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.
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
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'];
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.
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.
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.
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.
• 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
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'];
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
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
Note Configurable Subsystem will be removed in a future release. Convert Configurable Subsystem
blocks in existing models to Variant Subsystem blocks.
You can convert a Configurable Subsystem block to a Variant Subsystem block in these ways:
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.
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”.
Perform these steps to convert Configurable Subsystem blocks in a model to Variant Subsystem
blocks:
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.
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
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.
• 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
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.
openExample('simulink_general/VanDerPolOscillatorExample');
get_param('vdp', 'SolverType')
ans =
'Variable-step'
For more information on how to use configuration parameters programmatically, see “Automate
Model Configuration by Using a Script” on page 13-24.
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:
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.
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
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.
• 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.
The model sldemo_fuelsys_dd contains one configuration set, which uses a variable-step solver.
Add another configuration to use a fixed-step solver.
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.
For this example, change the configuration FixedStepConfig to specify a fixed-step solver instead
of the default variable-step solver.
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
To activate the fixed-step configuration that you created in the previous section:
The active configuration displays (Active) to the right of the configuration name.
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.
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.
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.
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.
For this example, compare the default configuration Configuration to the configuration
FixedStepConfig, which you copied to the model vdp.
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
13-11
13 Managing Model Configurations
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 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.
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.
Models that have access to the data dictionary system_model.sldd can reference the new
configuration.
13-13
13 Managing Model Configurations
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.
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.
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.
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.
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
Both models now contain a configuration reference that points to the same configuration set object in
the Simulink data dictionary.
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.
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
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.
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.
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.
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
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.
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.
In the top model, you must convert the active configuration set to a configuration reference:
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.
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
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
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:
model = 'damped_nonlin_spring';
open_system(model);
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'
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');
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'
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
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
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
• 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”.
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
You can use task parallelism in scenarios such as a factory where the plant and controller run in
parallel.
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.
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.
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.
• 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.
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:
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.
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
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.
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)
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
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
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.
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
In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task four
times to add four new 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
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
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.
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.
In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task three
times to add three new 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
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
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.
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.
In the Concurrent Execution tree, under Tasks and Mapping, select CPU. Click Add task three
times to add three new 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
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
Follow these steps to configure your Simulink model to take advantage of concurrent execution.
Once you have a model that executes concurrently on your computer, you can further configure your
model in the following ways:
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
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.
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
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.
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:
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
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.
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 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.
14-26
Partition Your Model Using Explicit Partitioning
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.
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.
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:
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.
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.
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
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.
14-31
14 Configuring Models for Targets with Multicore Processors
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
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.
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
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
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:
14-36
Optimize and Deploy on a Multicore Target
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.
14-37
14 Configuring Models for Targets with Multicore Processors
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
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.
Note If an HTML profile report exists for the model, the Profile Report pane displays that file.
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.
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).
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.
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.
Alternatively, you can generate a profile report for a model configured for concurrent execution at the
command line. Use the Simulink.architecture.profile function.
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
• 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
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.
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
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.
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
See Also
More About
• “Multicore Programming with Simulink” on page 14-8
14-45
14 Configuring Models for Targets with Multicore Processors
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
This example shows how to speed up execution of a model on multiple cores using a For Each
subsystem in Rapid Accelerator simulation mode.
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.
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
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
Clean Up
bdclose(modelName);
See Also
For Each Subsystem | For Each
14-48
15
• 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.
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
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.
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.
• Simulation errors
• "Unresolved Link" icons on blocks that are library links
• Wrong results
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:
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')
• Memory issues
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
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.
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.
x = u/(s + 2)
or,
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
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.
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.
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
TF = 9/5(TC) + 32
• 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
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.
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
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.
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.
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
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
• 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
4
A′ = − 0.04A + 1 ⋅ 10 BC
4 7
B′ = 0.04A − 1 ⋅ 10 BC − 3 ⋅ 10 B2
C=1− A−B
Make these changes to your model or to the model ex_hb1ode, or open the model ex_hb1dae.
15-17
15 Modeling Best Practices
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
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
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 .
Make these changes to your model or to the model ex_hb1ode, or open the model ex_hb1dae_acb.
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.
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
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 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.
15-23
15 Modeling Best Practices
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
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.
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.
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.
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
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.
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
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
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.
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
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.
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
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.
• 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.
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
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
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
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
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
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.
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
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.
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
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
15-45
16
Project Setup
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?
— 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:
Starting in R2019a, you can use projects in MATLAB, with or without Simulink. You can share
projects with users who do not have Simulink.
Projects provide additional tools to help with Simulink workflows. For example:
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.
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
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
• 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)
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.
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.
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.
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.
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.
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.
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.
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
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.
project = currentProject;
You can use the project API to get all the project details and manipulate the project at the command
line. See currentProject.
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
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 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:
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
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:
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.
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.
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:
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
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.
• 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.
• 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
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.
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.
• 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
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
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.
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
• 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
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
• 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?
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
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.
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
More About
• “What Can You Do with Project Shortcuts?” on page 16-29
16-31
16 Project Setup
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
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.
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.
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.
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.
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
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.
• 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
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
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.
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
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:
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
• 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
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
17-4
Search Inside Project Files and Filter File Views
• 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*.
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
• 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
• 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:
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
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.
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.
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.
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
• 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.
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.
17-10
Move, Rename, Copy, or Delete Project Files
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.
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
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
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.
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.
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 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
• 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
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
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
openExample("simulink/AirframeProjectExample")
Use currentProject to get a project object to manipulate the project at the command line.
proj = currentProject
proj =
methods(proj)
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
After you get a project object, you can examine project properties such as files.
files = proj.Files
files =
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 =
Path: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframePr
Revision: "7512378c3b82a519f72204089b0ce552cfc90e1a"
SourceControlStatus: NotUnderSourceControl
Labels: [1x0 matlab.project.Label]
ans =
17-20
Automate Project Tasks Using Scripts
File
DataType
Data
Name
CategoryName
myfile =
Path: "C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframePr
Revision: "7512378c3b82a519f72204089b0ce552cfc90e1a"
SourceControlStatus: Unmodified
Labels: [1x1 matlab.project.Label]
methods(myfile)
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 =
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 =
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 =
Path
Revision
SourceControlStatus
Labels
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 =
17-22
Automate Project Tasks Using Scripts
requiredFiles =
{'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
g.Nodes.Name(indegree(g)==0);
ans =
{'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
transposed = flipedge(g)
impacted = bfsearch(transposed, which('vertical_channel'))
transposed =
impacted =
{'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
17-23
17 Project File Management
impacted2 =
{'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
shortcuts =
Name
Group
File
ans =
17-24
Automate Project Tasks Using Scripts
shortcuts(3).File
ans =
"C:\TEMP\Bdoc24a_2528353_7604\ib462BFE\17\tp7be20789\simulink\AirframeProjectExample\airframe
ans =
{["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 =
SingleValued: 0
DataType: "char"
Name: "Engineers"
LabelDefinitions: [1x0 matlab.project.LabelDefinition]
17-25
17 Project File Management
ld =
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.
Get a particular label and attach data to it, for example, some text.
label =
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'
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 =
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
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
For example custom task functions, see “Run Custom Tasks with a Project”.
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
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.
You can publish a report of your custom task results. For example, try this custom task:
17-29
17 Project File Management
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:
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
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
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
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.
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
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.
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.
You can explore model dependencies using the model hierarchy or the model instances views.
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.
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
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 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
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.
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.
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
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:
For links to requirements that are stored in external documents, you can also navigate to the linked
requirements.
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_system('slvnvdemo_fuelsys_officereq')
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
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.
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.
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
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.
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_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.
If you don't have Requirements Toolbox™ installed, then you cannot navigate to requirements that
are stored in a Requirements Toolbox requirement set.
Cleanup
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
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 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
To show only the files with the Test label in the project view, follow these steps.
17-50
Identify and Run Tests in MATLAB Projects
Alternatively, run all the tests with the Test label in the current project by using the runtests
function.
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 =
Name
Passed
Failed
Incomplete
Duration
Details
Totals:
9 Passed, 0 Failed, 0 Incomplete.
1.2533 seconds testing time.
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”.
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
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:
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");
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
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
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
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.
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 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.
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.
• 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.
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
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
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
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
• 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”.
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
• 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.
18-16
Perform an Impact Analysis
Tip To try a dependency analysis on example files, see “Perform Impact Analysis with a Project”.
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").
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.
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
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.
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
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.
18-21
18 Project Dependency Analysis
18-22
Check Dependency Results and Resolve Problems
18-23
18 Project Dependency Analysis
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).
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.
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.
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.
See Also
Related Examples
• “Run a Dependency Analysis” on page 18-5
18-25
18 Project Dependency Analysis
18-26
Find Requirements Documents in a Project
• 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
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:
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.
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.
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
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.
• “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.
19-2
About Source Control with Projects
• 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).
• Offline working
• Local repository, which provides full history
• Branching
• Multiple remote repositories, enabling large-scale hierarchical access control
19-3
19 Project Source Control
• 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
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.
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 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
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.
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.
When you disable source control, MATLAB Online does not destroy
repository information. For example, it does not remove the .svn folders.
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 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
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
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
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:
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.
For example:
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.
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.
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
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.
1 Locate your SVN config file. Look for the file in these locations:
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:
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.
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.
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:
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.
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;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
If you need to resolve merge issues, see “Resolve Conflicts” on page 19-62.
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
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.
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
• 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.
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
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 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.
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 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.
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
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.
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.
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.
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.
19-23
19 Project Source Control
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
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.
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.
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
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.
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:
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:
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
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.
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
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
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
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
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
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
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
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.
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 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
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
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.
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
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
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.
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.
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
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.
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
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:
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
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
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
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.
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.
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.
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
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
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.
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.
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
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.
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
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.
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.
• 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.
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.
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
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.
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.
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
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.
<<<<<<< .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.
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.
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.
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
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
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
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.
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:
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:
2 Configure your repository to automerge changes in different subsystems in the same SLX file
using the mlAutoMerge executable file:
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.
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
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.
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:
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
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:
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.
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.
19-72
Continuous Integration Using MATLAB Projects and Jenkins
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).
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.
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.
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.
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
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.
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 =
{'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
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
20-4
Add or Remove a Reference to Another Project
• 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 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
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
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:
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:
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
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.
See Also
Related Examples
• “Componentization Using Referenced Projects” on page 20-2
• “Organize Projects into Components Using References and Git Submodules”
20-9
21
Use the Comparison Tool to review and merge differences between two model files on disk or
between different revisions of the same file.
• 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:
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.
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.
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
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.
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.
• 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
visdiff("mysimple_stats_block1.slx","mysimple_stats_block2.slx");
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
21-6
Understand Simulink Model Comparison Changes
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
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.
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
slxmlcomp.clearWindowPositions
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.
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.
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
• 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.
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
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.
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
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
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
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.
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
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.
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.
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
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.
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
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
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 =
"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
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.
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.
• 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
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
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.
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
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
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)
21-33
21 Compare Simulink Models
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
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
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.
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
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.
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.
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:
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 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.
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.
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
Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.
This figure shows an example of a small evolution tree. An evolution tree has two important elements:
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
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.
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.
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
Note The Design Evolution Manager is available on MATLAB Online only and requires a Simulink
license.
Select the evolution tree canvas to display properties of the evolution tree. Use the Property
Inspector pane to:
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
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
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.
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:
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.
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
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.
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
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.
2. Open the Fixed-Point Tool. On the Simulink® Apps tab, under Code Generation, click the Fixed-
Point Tool icon.
4. Under System Under Design (SUD), select controller_subsystem as the system to convert to
fixed point.
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.
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
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.
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.
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.
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.
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.
8. Add a note to the evolution that the total cost of this design is 416.
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.
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.
22-20
Use Design Evolution Manager with the Fixed-Point Tool
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.
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.
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
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.
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.
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
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 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.
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.
23-3
23 Large-Scale Modeling
• 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.
23-4
Explore Types of Model Components
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.
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.
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
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
• “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
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
Forwarding tables
allow you to map old
library blocks to new
versions of the blocks.
23-10
Compare Capabilities of Model Components
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
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
23-15
23 Large-Scale Modeling
23-16
Compare Capabilities of Model Components
23-17
23 Large-Scale Modeling
23-18
Compare Capabilities of Model Components
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
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
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
External Websites
• 11 Best Practices for Developing ISO 26262 Applications with Simulink
23-23
23 Large-Scale Modeling
• 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)
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.
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.
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.
• 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.
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
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
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”.
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.
23-28
Configuration Management
• 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.
• 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
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
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.
• 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:
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.
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.
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.
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
• 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.
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.
The Simulink models for this project are located in the model folder.
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:
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.
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.
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.
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.
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.
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
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:
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.
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
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
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
24-12
Power Window
The internals of the VALIDATE PASSENGER process are the same as the VALIDATE DRIVER process.
The only difference is the different input and output.
For implementation in the Simulink environment, see “Activity Diagram: Validate Passenger” on page
24-13.
24-13
24 Power Window Example
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
For implementation in the Simulink environment, see “Activity Diagram: Detect Obstacle Endstop” on
page 24-14.
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
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
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:
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
24-21
24 Power Window Example
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
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
24-24
Power Window
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
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:
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:
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.
The sheet names of these input sets and their descriptions are:
24-29
24 Power Window Example
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:
2 To generate the Simulink Coverage coverage report for multiple input set, double click the Run
Coverage subsystem in the model.
24-30
Power Window
• Passenger up state
• Driver up and down states
• Passenger automatic down and automatic up states
For requirements presented as a context diagram, see “Context Diagram: Power Window System” on
page 24-9.
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.
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.
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).
24-32
Power Window
For requirements presented as an activity diagram, see “Activity Diagram: Detect Obstacle Endstop”
on page 24-14.
24-33
24 Power Window Example
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:
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
When you run the slexPowerWindowContinuous configureModel utility, the model uses the
continuous time solver ode23 (Bogacki-Shampine).
24-35
24 Power Window Example
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
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.
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.
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.
24-37
24 Power Window Example
Multibody System
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
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.
This table lists the additional signal for the Context Diagram: Power Window System data definitions.
24-39
24 Power Window Example
This table lists the changed signals for the Activity Diagram: Detect Obstacle Endstop data
definitions.
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
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.
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.
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.
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.
24-44
Power Window
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.
Observe a structure that is very similar to the window control system. This structure contains a:
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.
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
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
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.
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.
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.
25-4
Create Partitions
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.
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.
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.
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.
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
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.
Changes made in the Schedule Editor affect both, simulation and code generation.
• A graph that shows the partitions and the data connections between them.
25-11
25 Schedule Editor
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.
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.
• 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.
• 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.
• 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
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.
To view and edit the schedule of the export-function model, reference the model.
open_system('ThrottlePositionControlTop.slx');
25-15
25 Schedule Editor
set_param('ThrottlePositionControlTop/ThrottleControl','ScheduleRatesWith','Schedule Editor');
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');
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.
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.
25-16
Schedule the Partitions
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
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 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
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
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
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
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
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 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 =
25-27
25 Schedule Editor
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
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
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 =
Rate: "0.005"
Order: [5x3 table]
ans =
5x3 table
ans =
9x3 table
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
arguments
model char = bdroot
end
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
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
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
in = generateSimulationInputs(model, numSimulations);
out = sim(in);
plot(out);
end
ans =
25-31
25 Schedule Editor
25-32
Events in Schedule Editor
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.
• 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.
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.
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.
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.
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.
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.
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
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.
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.
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
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
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.
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 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:
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:
See “Modeling Guidelines” for application-specific guidelines for model architecture, design, and
configuration.
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 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
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.
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.
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.
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).
26-8
Simulating Dynamic Systems
9
27
Running Simulations
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”.
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:
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.
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.
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.
For example, this model stops the simulation when the simulation time reaches 10.
27-3
27 Running Simulations
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.
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
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”.
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
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.
• 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
• 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
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:
Local solvers are not supported for models referenced by Model blocks:
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.
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.
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.
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.
• System dynamics
• Solution stability
• Computation speed
• Solver robustness
As such, the numerical solvers provided by Simulink can be broadly classified by two properties.
• 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.
• 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.
27-11
27 Running Simulations
To tailor the selected solver to your model, see “Check and Improve Simulation Accuracy” on page
34-12.
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.
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.
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
ẋ = f (x, t, u)
y = g(x, t, u) .
∂f ∂f
∂x ∂u A B
J= = .
∂g ∂g C D
∂x ∂u
∂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.
ẋ 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.
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.
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.
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) .
27-15
27 Running Simulations
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:
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.
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
27-17
27 Running Simulations
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.
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.
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.
• ode45
• ode23
• ode113
• odeN
27-20
Variable Step Solvers in Simulink
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
• ode15s
• ode23s
• ode23t
• ode23tb
27-21
27 Running Simulations
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.
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”.
27-22
Variable Step Solvers in Simulink
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.
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 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.
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.
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:
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
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).
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.
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.
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
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
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
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
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:
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
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.
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
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
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.
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:
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.
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
27-46
Use Model Operating Point for Faster Simulation Workflow
27-47
27 Running Simulations
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
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 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.
siminBaseline = Simulink.SimulationInput(modelName);
siminBaseline = setModelParameter(siminBaseline,'StartTime','0','StopTime','10',...
'OutputOption','AdditionalOutputTimes','OutputTimes','[0 5 10]');
baseline = sim(siminBaseline);
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');
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.
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.
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');
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.
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
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
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.
This example shows how to access simulation metadata to manage diagnostic suppressions and to
restore diagnostic messages programmatically.
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.
model = 'Suppressor_CLI_Demo';
open_system(model)
set_param(model,'ReturnWorkspaceOutputs','on');
out = sim(model);
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)
27-59
27 Running Simulations
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');
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');
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');
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');
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
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');
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');
diag =
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 =
identifier
message
paths
cause
stack
Simulink.restoreDiagnostic(diag(1));
See Also
Simulink.getSuppressedDiagnostics | Simulink.suppressDiagnostic |
Simulink.restoreDiagnostic | restore | Simulink.SuppressedDiagnostic |
Simulink.SimulationMetadata
27-64
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.
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.
27-65
27 Running Simulations
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
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.
model = "DiagnosticDemo";
load_system(model);
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.
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
model = "DiagnosticDemo";
load_system(model);
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
output = sldiagviewer.reportError(error)
The diagnostic window opens for the model and displays the error message in red in the Analysis
stage.
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.
Create a log by file using sldiagviewer.diary and toggle the logging state.
sldiagviewer.diary
model = "DiagnosticDemo";
open_system(model);
set_param("DiagnosticDemo/Gain","Gain","xyz");
27-68
Report Diagnostic Messages Programmatically
set_param(model,"SimulationCommand","Start")
set_param("DiagnosticDemo/Gain","Gain","abc");
sldiagviewer.diary("off")
set_param(model,"SimulationCommand","Start")
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
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).
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);
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
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.
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
28-3
28 Running a Simulation Programmatically
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
paramStruct.StopTime = "20";
out = sim("ModelName",configset); Specify model configuration parameter values
using a Simulink.ConfigSet object.
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.
28-6
Run Simulations Programmatically
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.
28-7
28 Running a Simulation Programmatically
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.
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.
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
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);
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:
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
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.
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.
Note If you open models inside a parfor statement, close them again using bdclose all to avoid
leaving temporary files behind.
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;
28-14
Using sim Function Within parfor
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
• 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).
28-15
28 Running a Simulation Programmatically
parpool;
close_system(model, 0);
delete(gcp('nocreate'));
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:
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.
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.
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)
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
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.
28-19
28 Running a Simulation Programmatically
% 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
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 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.
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:
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
• 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.
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
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.
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
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.
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.
• Initial state
• External inputs
• Model parameters
• Block parameters
• Variables
29-3
29 Multiple Simulations
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:
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
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”.
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
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.
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
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
29-9
29 Multiple Simulations
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.
Limitations
• Closing the MATLAB session terminates simulations on the workers, disabling retrieval of partial
results.
29-11
29 Multiple Simulations
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).
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
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:
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.
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;
29-14
Analyze Results Using Simulation Manager
costOutput.costFromConcentration = costConcentration;
end
rng default;
numSamples = 60;
allAValues = rangeA(1) + (rangeA(2) - rangeA(1)).*rand(numSamples, 1);
allhValues = rangeH(1) + (rangeH(2) - rangeH(1)).*rand(numSamples, 1);
in(1:numSamples) = Simulink.SimulationInput('simManagerCSTR');
in = in.setPostSimFcn(@(out)calculateCost(out));
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
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.
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
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
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.
openExample('simulink/RunMultipleSimulationsThroughSimulinkExample')
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
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.
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
29-21
29 Multiple Simulations
To create a sequential combination, select the specified block parameters. Then, from the
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
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.
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
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.
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.
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
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.
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 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
• 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
This example connects UI components in the app to elements of the model using these techniques:
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.
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_system("ex_sldemo_househeat.slx");
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');
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.
• 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.
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.
Once the simulation is complete, click Save Output to save simulation outputs to a MAT file.
29-37
30
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
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.
• 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.
30-6
Scope Blocks and Scope Viewer Overview
30-7
30 Visualizing and Comparing Simulation Results
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.
• Signal Statistics
• Bilevel Measurements
• Peak Finder
30-8
Scope Blocks and Scope Viewer Overview
This table lists the differences in Configuration Property default values between the Scope and Time
Scope blocks.
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
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
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
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.
30-13
30 Visualizing and Comparing Simulation Results
Level — Enter a threshold value for an edge triggered signal. Auto level
is 50%
30-14
Scope Triggers Panel
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%.
Max Width — Enter the maximum pulse width for a pulse width
triggered signal.
30-15
30 Visualizing and Comparing Simulation Results
30-16
Scope Triggers Panel
Low — Enter a low value for a runt-triggered signal. Auto level is 10%.
30-17
30 Visualizing and Comparing Simulation Results
30-18
Scope Triggers Panel
Low — Enter a low value for a window-trigger signal. Auto level is 10%.
30-19
30 Visualizing and Comparing Simulation Results
• 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
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
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
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.
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
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.
• 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
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.
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
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.
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
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
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
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.
• 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.
• 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
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
• 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 .
• 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:
For example:
mask = SpectralMaskSpecification();
mask.EnabledMasks = 'Upper';
mask.UpperMask = 10;
scope = dsp.SpectrumAnalyzer();
scope.SpectralMask = mask;
scope.SpectralMask
ans =
EnabledMasks: 'Upper'
UpperMask: 10
LowerMask: -Inf
ReferenceLevel: 'Custom'
CustomReferenceLevel: 0
MaskFrequencyOffset: 0
30-47
30 Visualizing and Comparing Simulation Results
• 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
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.
• 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
To visualize your simulation results over time, use a Scope block or Time Scope block
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
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
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.
30-55
30 Visualizing and Comparing Simulation Results
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
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
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.
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
• 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
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 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.
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.
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.
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
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)
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.
• 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.
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
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
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.
30-70
View Values of Parameters Set as Variables
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
These tasks walk through frequently used Floating Scope and Scope Viewer procedures.
1
From the Simulation tab, click Library Browser .
2 From Simulink / Sinks, drag a copy of the Floating Scope block into your model.
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.
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.
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.
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.
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
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 .
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
The name of the generator you choose appears in a box connected to the block input.
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.
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.
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
1 Right-click a generator.
2 From the context menu, select Disconnect Generator.
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
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.
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,
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.
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.
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:
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
function sl_customization(cm)
cm.addSigScopeMgrViewerLibrary('newlib')
%end function
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
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_system(mdl,'LookUnderMasks','on','IncludeCommented','on', ...
'AllBlocks','on','BlockType','Scope')
find_system(mdl,'LookUnderMasks','on','IncludeCommented','on',...
'AllBlocks','on','BlockType','Scope','DefaultConfigurationName',...
'Simulink.scopes.TimeScopeBlockCfg')
find_system(mdl,'LookUnderMasks','on','IncludeCommented','on',...
'AllBlocks','on','BlockType','Scope','DefaultConfigurationName',...
'spbscopes.TimeScopeBlockCfg')
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
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);
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
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™.
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
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
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.
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
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
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.
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
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
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
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.
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.
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
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
out = sim(mdl);
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
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.
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
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
For more information about inspecting and analyzing multidimensional signal data, including frame-
based data, see “Analyze Multidimensional Signal Data” on page 31-131.
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
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)
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
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:
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");
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.
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.
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”.
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
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.
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 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
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.
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.
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);
io.reader.getRegisteredWorkspaceReaders
ans =
"SimpleStructReader"
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
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.
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.
31-25
31 Inspecting and Comparing Simulation 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
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 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.
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.
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.
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.
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.
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.
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"]);
io.reader.getRegisteredFileReaders
31-28
Import Data Using Custom File Reader
ans =
"ExcelFirstColumnTimeReader"
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
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.
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.
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
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.
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.
Simulink.sdi.view
The data for this example is stored in the Excel™ file LoganTripGPSData.xlsx. To import the data
In the Import dialog box, under Import from, select File. Then, enter LoganTripGPSData.xlsx in
the text box and click Import.
mapRun = Simulink.sdi.createRun("LoganTrip","file","LoganTripGPSData.xlsx");
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
31-33
31 Inspecting and Comparing Simulation Data
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
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
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 .
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
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
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
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 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
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.
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.
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
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.
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.
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
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
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:
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
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.
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
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.
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
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
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.
The data for this example is stored in the MAT file NoiseFilteringData.mat. To import the data
In the Import dialog box, under Import from, select File. Then, enter NoiseFilteringData.mat
in the text box and click Import.
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:
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
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:
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 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:
31-74
View Multidimensional Signals Using the Array Plot
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,
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
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.
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.
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
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
Metadata not
included in
exported file.
31-80
Microsoft Excel Import, Export, and Logging Format
Property Descriptions
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
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:
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.
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.
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.
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
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.
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
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:
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.
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
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
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
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 .
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
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
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.
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.
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.
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
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.
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.
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
This example shows you how to control the time axis, display scaling, and display offset to better
visualize your streaming data.
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
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
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.
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.
• 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
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.
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.
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
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.
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.
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
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
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.
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.
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.
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.
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.
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
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.
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
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.
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.
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.
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
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.
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 in the slexAircraftExample model to use the callback from the previous
section.
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.
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 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
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.
• 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.
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
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
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.
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
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 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.
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.
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:
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.
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
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
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
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.
• 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.
1 Pause on the save icon on the left side bar. Then, click Save As.
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
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.
• 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
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.
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.
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.
31-151
31 Inspecting and Comparing Simulation Data
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
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
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.
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
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.
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.
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);
When you generate a comparison report to save the comparison results, specify:
31-154
Create Interactive Comparison Reports
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.
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.
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
Add Visualizations
You can choose from several visualizations to use for your data in the Simulation Data Inspector.
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
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.
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.
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
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
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:
31-169
31 Inspecting and Comparing Simulation Data
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.
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
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.
You can select easily distinguishable colors for all of the signals in your plot.
31-173
31 Inspecting and Comparing Simulation Data
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.
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
This example shows you how to view and inspect signal data from the model slexAircraftExample
using the Simulation Data Inspector.
Open the model slexAircraftExample, mark several signals for logging, and run a simulation.
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.
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.
•
— 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
•
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:
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.
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
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
31-190
Inspect Simulation Data
Property Descriptions
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.
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
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:
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.
The slexAircraftExample model does not specify units for its signals. However, some signal
names indicate the intended units.
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.
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.
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
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.
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.
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
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
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:
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')
% 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]
% 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]
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.
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
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
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.
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
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
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.
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
Limitations
The Simulation Data Inspector does not support comparing:
See Also
Related Examples
• “Compare Simulation Data” on page 31-203
31-218
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 a run, add data to it, and then view the data in the Simulation Data Inspector.
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";
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
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 = "--";
Simulink.sdi.setSubPlotLayout(2,1);
plotOnSubPlot(sine_sig,1,1,true);
plotOnSubPlot(cos_sig,2,1,true);
31-220
Inspect and Compare Data Programmatically
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")
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.
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.
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
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');
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);
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
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++
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
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
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.
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
Run the simulation and observe the control system response to each single-point 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
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.
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.
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
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.
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.
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.
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
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
You can also disconnect dashboard blocks. For example, disconnect the Knob block from the Sine
Wave block.
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.
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('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
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.
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.
Suppose you have a structure that captures information about six gears in a transmission.
• 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.
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)
32-14
Connect Dashboard Blocks to Simulink Model
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.
Add a Rocker Switch block to the model using the Simulink® quick insert menu:
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
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('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)
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.
Add a Knob block to the model using the Simulink® quick insert menu:
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
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.
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:
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.
32-21
32 Control Simulations with Interactive Displays
To edit panels and their contents, you can use the options available:
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:
32-22
Getting Started with Panels
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.
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
Annotate Panels
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:
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.
32-24
Getting Started with Panels
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
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.
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
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.
When you lose track of your panels, you can gather them into the visible model 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.
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
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.
Pause simulation.
Stop simulation.
32-30
Getting Started with Panels
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 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.
•
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
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.
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
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:
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
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.
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.
Add the annotations from the Fault Injection area to the panel:
32-38
Use Panels to Monitor Signals and Control Parameters
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
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:
32-43
32 Control Simulations with Interactive Displays
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:
• 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.
32-45
32 Control Simulations with Interactive Displays
Add the annotations from the Fault Injection area to the panel:
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
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:
32-48
Create Tabbed Panels
To detach the tab, drag the tab name away from the panel.
32-49
32 Control Simulations with Interactive Displays
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
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
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.
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.
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
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 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.
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
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”.
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
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.
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:
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
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:
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
Connect the Dashboard Scope block on the Cabin Temp tab to the signal the block should display
during simulation.
32-65
32 Control Simulations with Interactive Displays
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.
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.
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
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.
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:
To modify the design of the Vertical Gauge block, enter design mode:
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.
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.
32-70
Design Custom Gauges
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:
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.
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.
32-71
32 Control Simulations with Interactive Displays
If the Property Inspector is not open to the Design tab with the Edit button pressed:
32-72
Design Custom Gauges
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.
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
The value bar grows from the origin. By default, the origin is the minimum of the scale.
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.
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.
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
This example shows how to use the customizable Knob block to design three knobs that look like
controls in real systems:
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.
To design the cabin temperature knob, add a customizable Knob block to the model using the
Simulink® quick insert menu:
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
32-78
Design Custom Knobs
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.
32-79
32 Control Simulations with Interactive Displays
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:
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 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
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.
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:
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:
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.
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
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:
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.
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 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.
32-85
32 Control Simulations with Interactive Displays
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
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 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
This example shows how to use the customizable Lamp block to design four lamps that look like
displays in real systems:
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.
To design the dashboard light in a passenger car, add a customizable Lamp block to the model using
the quick insert menu:
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.
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.
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.
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.
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.
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
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.
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 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.
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
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:
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.
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.
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
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.
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 Property Inspector, on the Design tab, select the Background Image component.
2 In the Select Image section, click the X button.
32-96
Design Custom Lamps
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:
To configure all states to maximize and center the icon within the area taken up by the block, in the
Size and Position section:
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.
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.
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.
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
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.
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.
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:
To configure all states to maximize and center the icon within the area taken up by the block, in the
Size and Position section:
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
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.
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.
32-102
Design Custom Lamps
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.
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.
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.
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:
32-104
Design Custom Lamps
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:
Connect the top Lamp block to the Stop Light Timer [s] signal:
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
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.
To design the diff lock switch, add a customizable Rocker Switch block to the model using the
Simulink quick insert menu:
To modify the design of the Rocker Switch block, enter design mode:
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:
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.
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.
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 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
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.
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.
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
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 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.
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:
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.
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.
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.
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.
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 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
This example shows how to use the customizable Push Button and Callback Button blocks to design
the button panel of an elevator, including:
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.
• 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.
In this example, you use the Push Button block to model the ground floor button of an elevator.
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:
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:
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:
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.
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.
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
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:
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:
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:
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
The ground floor button is now fully configured. To test the button:
32-126
Design Custom Buttons
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.
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
status_vector=zeros(8,1);
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
To create the elevator buttons for floors one through seven, for each button:
32-128
Design Custom Buttons
The elevator floor buttons are mounted to a panel on the wall. Create a Simulink panel:
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.
32-130
Design Custom Buttons
In this example, you use the Callback Button block to model the door buttons of an elevator.
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.
32-131
32 Control Simulations with Interactive Displays
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:
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.
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.
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.
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:
The button that opens the elevator door is now fully configured.
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.
32-134
Design Custom Buttons
6 To exit panel edit mode, in the action menu above the panel, select Done Editing.
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:
The elevator button now has four states: Default, Pressed, Latched, and Pressed and
Latched.
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:
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.
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.
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.
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:
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!
32-138
Design Custom Buttons
6 To exit panel edit mode, in the action menu above the panel, select Done Editing.
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
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
To design the traditional EOT, add a customizable Rotary Switch block to the model using the
Simulink quick insert menu:
To modify the design of the Rotary Switch block, enter design mode:
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
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.
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
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.
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:
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.
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.
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.
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
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
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.
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 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
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:
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.
To design the light dimmer switch, add a Vertical Slider block to the model using the quick insert
menu:
To modify the design of the Vertical Slider block, enter design mode:
You can design a custom slider using the toolbar or using the Design tab of the Property Inspector.
This example uses both.
32-157
32 Control Simulations with Interactive Displays
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
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
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
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 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.
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.
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.
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.
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.
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
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
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.
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.
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:
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.
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 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
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.
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.
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.
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 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
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.
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.
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
32-180
Connect Interactive Controls and Displays
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
You can also disconnect dashboard blocks. For example, disconnect the Knob block from the Sine
Wave block.
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
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.
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('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-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.
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.
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.
Suppose you have a structure that captures information about six gears in a transmission.
• 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('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)
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
Add a Rocker Switch block to the model using the Simulink® quick insert menu:
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
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('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)
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.
Add a Knob block to the model using the Simulink® quick insert menu:
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
• 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.
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.
33-3
33 Analyzing Simulation Results
Scope blocks, Floating Scope blocks, and the Scope Viewer support:
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.
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:
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.
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.
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.
[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
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
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
In this section...
“How Simulink Profiler Works” on page 34-5
“Start Profiler” on page 34-6
“Save Profiler Results” on page 34-10
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.
34-5
34 Improving Simulation Performance and Accuracy
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
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
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
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
34-11
34 Improving Simulation Performance and Accuracy
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.
• 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
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().
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.
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.
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.
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:
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.
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
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.
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.
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.
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.
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.
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.
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.
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.
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.
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
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
• 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
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.
• 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.
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.
Make sure the model configuration parameters are set to enable data logging.
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.
• 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.
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.
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.
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.
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.
• 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.
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.
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.
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.
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.
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.
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
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.
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
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.
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
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:
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
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.
1 In the left pane, click Performance Advisor. Select these settings and click Apply:
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
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.
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)
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
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
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.
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.
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.
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
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.
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
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
• 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.
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.
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.
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
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.
2 In the Custom Algorithm dialog box that appears, click Add and upload a MATLAB script that
contains your ranking algorithm.
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.
end
36-26
Solver Profiler Interface
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
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.
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.
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')
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.
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.
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
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
The table summarizes other options available for displaying run-time information about the model in
simulation.
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.
37-5
37 Debug Simulations
See Also
sldebug
37-6
Debug Simulation of Iterator Subsystem
This example shows how to analyze a simple summing algorithm implemented using a 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
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:
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
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.
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.
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.
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.
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
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
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?
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
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 .
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.
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
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
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.
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”.
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
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.
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
38-9
38 Accelerating Models
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.
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
Data Display
38-11
38 Accelerating Models
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
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
• 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
Additionally, rapid accelerator mode does not work if your model contains any of the following blocks:
38-14
Design Your Model for Effective Acceleration
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).
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.
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.
• 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.
• 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:
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
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.
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.
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
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.
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.
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
Control Simulation
You can control the simulation mode programmatically using the set_param command:
set_param('modelname','SimulationMode','mode')
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');
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:
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.
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.
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.
Use the AccelVerboseBuild parameter to display progress information during code generation.
The permitted values are on or off. The default is off.
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.
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.
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.
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.
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");
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);
Build Summary
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
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;
InitializationTime = [normalInit;rapidBuildInit;rapidInit];
ExecutionTime = [normalExec;rapidBuildExec;rapidExec];
TotalSimulationTime = [normalTotal;rapidBuildTotal;rapidTotal];
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
___________________ __________________ _____________
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
38-29
38 Accelerating Models
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
38-31
39
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 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, 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.
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:
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 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
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.
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.
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.
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:
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
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.
40-2
Nonvirtual and Virtual Blocks
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
For each block in a model, you can set general block properties, such as:
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.
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>
You can also create block annotations programmatically. See “Create Block Annotations
Programmatically” on page 40-7.
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.
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.
• 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.
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
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>')
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
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.
• 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
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 all port value labels in a model, on the Debug tab, in the Tools section, in the Port Values
These examples show how to use port value labels to analyze and debug a model:
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.
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.
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.
This table summarizes port value label messages that indicate the signal type.
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.
40-12
View Signal Values Using Port Value Labels
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.
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:
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.
40-14
View Signal Values Using Port Value Labels
• 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
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.
• “Block Methods”
• “Conditionally Executed Subsystems Overview” on page 10-3
• “Specify Block Execution Order, Execution Priority and Tag” on page 40-5
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.
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 .
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.
For example, in this model, the block execution order ranges from 1 to 12, with each nonvirtual block
receiving an execution order.
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.
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.
40-21
40 Working with Blocks
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.
40-22
Control and Display 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.
• Gain
• Product
• Sum
• Integrator
• Unit Delay
• Constant
• 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.
• 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:
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
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.
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
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
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.
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.
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:
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.
stemPlot = get_param(block.BlockHandle,'UserData');
est = block.Dwork(2).Data;
set(stemPlot(2),'YData',est);
drawnow('expose');
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
You can use numbers, variables, and expressions to set block parameter values. Choose a technique
based on your modeling goals. For example, you can:
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.
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 =
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')
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.
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
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.
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
• 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.
41-7
41 Working with Block Parameters
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
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.
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
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.
• 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.
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:
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:
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.
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).
• 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).
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.
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.
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.
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
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')
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.
41-14
Share and Reuse Block Parameter Values by Creating Variables
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.
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.
41-15
41 Working with Block Parameters
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
Typically, a reusable algorithm requires that numeric block parameters, such as the Gain parameter
of a Gain block, either:
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
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.
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.
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:
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.
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.
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:
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
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.
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);
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.
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.
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;
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
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.
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.
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.
% 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.
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
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.
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:
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;
41-26
Organize Related Block Parameter Definitions in Structures
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.
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.
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.
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';
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);
% 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.
41-28
Organize Related Block Parameter Definitions in Structures
• Field name
• Numeric data type, such as single or int32
• Complexity
• Dimensions
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 []).
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
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:
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.
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
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.
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.
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.
• 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.
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 =
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.
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.
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.
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.
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
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.
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_system('ex_sldemo_absbrake');
41-38
Optimize, Estimate, and Sweep Block Parameter Values
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.
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.
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);
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.
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
For more information about using Simulink.SimulationInput objects to run multiple simulations,
see sim.
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.
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')
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.
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.
41-42
Optimize, Estimate, and Sweep Block Parameter Values
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
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.
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).
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.
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.
• 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.
41-45
41 Working with Block Parameters
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.
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:
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).
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.
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 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
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
• 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).
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.
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.
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
41-51
41 Working with Block Parameters
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.
• 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.
• 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 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:
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.
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.
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.
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.
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).
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
41-54
Specify Minimum and Maximum Values for Block Parameters
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
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.
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.
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.
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 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.
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.
Optionally, create a Simulink.Bus object to use as the data type of the array of structures. You can:
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';
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 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.
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.
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.
41-60
Switch Between Sets of Parameter Values During Simulation and Code Execution
If you have Simulink Coder software, you can generate code that enables you to switch between the
parameter sets during code execution.
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.
tempEntryObj = getEntry(sectObj,'Ctrl');
Ctrl = getValue(tempEntryObj);
Ctrl.StorageClass = 'ExportedGlobal';
setValue(tempEntryObj,Ctrl);
Build Summary
#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)
{ 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
• 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:
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:
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
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
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.
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.
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
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.
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
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.
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
• 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
Note Although a breakpoint vector is strictly monotonic in double format, it might not be so after
conversion to a fixed-point data type.
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:
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
42-14
Methods for Approximating Function Values
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:
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.
The Lookup Table Dynamic block outputs the following values when using the specified lookup
methods and inputs.
42-17
42 Working with Lookup Tables
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
• 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.
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
• 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.
• 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.
• 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
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
When the Breakpoints specification property is set to Explicit values, use the lookup table
spreadsheet at the bottom to:
Alternatively, you can copy and paste the contents of a Microsoft Excel spreadsheet or any
spreadsheet application.
42-23
42 Working with Lookup Tables
42-24
Edit Lookup Table Data with Lookup Table Spreadsheet
• Built-in data types (int8, uint8, int16, uint16, int32, uint32, double, single, boolean)
42-25
42 Working with Lookup Tables
LUTObj = Simulink.LookupTable;
open LUTObj
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.
42-27
42 Working with Lookup Tables
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.
2 In the tabular area at the bottom, change the horizontal breakpoint slice to BP3. Observe the
changed view of the slice of data.
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.
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.
1 In the spreadsheet, right-click the last column of the table and select Delete > Delete Column.
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
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
Selection
42-33
42 Working with Lookup Tables
Editor
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
• 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].
42-35
42 Working with Lookup Tables
• 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.
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.
42-37
42 Working with Lookup Tables
• 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.
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
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.
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:
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
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.
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.
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
In this function:
The myGetTableConvertInfoFcn function returns the blkInfo object containing three fields.
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)
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.
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
42-44
Copy and Paste Lookup Table Data from Excel
-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
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.
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
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
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.
See Also
Related Examples
• “Use the Lookup Table Editor” on page 42-19
42-51
42 Working with Lookup Tables
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.
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.
42-52
Register Custom Lookup Table Blocks
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
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.
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
• 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.
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.
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
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
To generate code that is more efficient, you can remove the conditional statements that protect
against out-of-range input values.
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.
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
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.
• 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:
For more information about the Model Advisor, see “Check Your Model Using the Model Advisor” on
page 5-2 in the Simulink documentation.
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).
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
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
42-63
42 Working with Lookup Tables
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:
42-64
Update Lookup Table Blocks to New Versions
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”.
• 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
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.
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.
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
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.
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:
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
43-6
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
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.
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.
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.
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.
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”.
1. You can preview the mask and choose to unmask the block or edit the block mask.
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
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.
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).
Remove Mask
To remove a mask from a block,
The Mask Editor opens and displays the existing mask, for example:
43-10
Manage Existing Masks
See Also
More About
• “Create a Simple Mask” on page 43-7
43-11
43 Working with Block Masks
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
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.
This model has four subsystem blocks which demonstrates drawing static and dynamic mask icons.
open_system("slexMaskDisplayAndInitializationExample");
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.
43-13
43 Working with Block Masks
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.
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.
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
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.
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.
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.
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
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.
• 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.
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
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).
• 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:
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 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.
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
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.
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.
43-21
43 Working with Block Masks
Alternatively, if you want to save callbacks in mask, select Switch Callback Mode and click Mask.
• 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:
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
• 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.
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
• 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.
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
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.
• 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
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
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.
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”.
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.
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
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
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.
• 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.
• 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
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.
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
For examples of other mask operations, like creating and editing mask parameters and copying and
deleting masks, see Simulink.Mask and Simulink.MaskParameter.
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
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”.
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.
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.
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
d =
Popup with properties:
Name: 'Parameter1'
PromptLocation: 'left'
Row: 'new'
HorizontalStretch: 'on'
Tooltip: ''
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
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
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.
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
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:
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.
• 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
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.
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.
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.
• 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
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.
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
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.
1. Create two edit parameters Gain Value and Bias. Create a check box parameter Enable Bias.
function initialization()
%In the Initialization command, the variable 'enableBias' corresponding to
the checkbox returns the following values:
unchecked = 0
checked = 1
43-42
Dynamic Mask Dialog Box
if ~enableBias
biasValue = 0;
end
% Othewise, the value from the mask parameter is used
end
function enableBias_callback()
% Control parameter visiblity. Get the value of the Enable Bias checkbox
% unchecked = 'off'
% checked = 'on'
enab = get_param(gcb,'enableBias');
end
4. Double-click the subsystem block Making a Parameter Invisible. Uncheck the Enable
Bias parameter and notice that the Bias parameter is invisible.
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.
1. Create two edit parameters Gain Value and Bias. Create a check box parameter Enable Bias.
function initialization()
% In the Initialization command, the variable 'enableBias' corresponding to
% the checkbox returns the following values:
% unchecked = 0
% checked = 1
43-43
43 Working with Block Masks
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
43-44
Dynamic Masked Subsystem
Create masked library blocks that can modify their structural 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")
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.
43-45
43 Working with Block Masks
1. Unlock the library. See “Lock and Unlock Libraries” on page 45-6
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.
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
• 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.
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
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
43-51
43 Working with Block Masks
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.
Alternatively, in Simulink, on the Modeling tab, under Component, click Create Model Mask,
or right-click the model, and select Mask > Create System Mask.
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
Tip To edit the system mask parameters, on the Component tab, under System Mask, click
Edit System Mask.
2 Save the masked model.
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
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.
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]
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
You can also add large number of mask parameters in a Table programmatically. An example follows,
% Get mask object.
aMaskObj = Simulink.Mask.get(gcbh);
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
You can provide input to the Custom Table parameter as a string in the cell array format.
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
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.
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);
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]
43-61
43 Working with Block Masks
Note:
• You can use the Width property to specify initial column width for a custom table.
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')
changedCells = tableControl.getChangedCells();
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' )
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.
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' )
43-62
Control Custom Table Programmatically
tableControl.removeRow( 2 )
tableControl.getSelectedRows()
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.
ans =
'{'sig1', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit'; 'sig2', 'Input', 'Inherit', 'Inherit'
set_param( gcb, 'myTable', "{ 'sig1', 'Input', 'Inherit', 'Inherit', 'on', 'Inherit' }" )
You can insert, remove, swap, and get the value of a specific column in a custom table. The
commands used are:
Insert a new column with the Evaluate check box selected. The command used is:
See Also
More About
• “Customize Tables for Masked Blocks” on page 43-59
43-63
43 Working with Block Masks
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.
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
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:
See Also
More About
• “Mask Editor Overview”
43-65
43 Working with Block Masks
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
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.
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.
43-68
Validating Mask Parameters Using Constraints
Rule Attributes
Rule attributes to create constraints are shown in the table:
43-69
43 Working with Block Masks
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
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");
43-71
43 Working with Block Masks
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.
You must associate constraints to mask parameters. You can associate the same constraint among
multiple mask parameters.
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
2. In the Property Editor, provide input values that are outside of the range specified in the
associated constraint. An error displays.
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.
2. Create an edit parameter IPAddress. Clear the Evaluate option in the Attributes section to store
the literal value of the parameter IPAddress.
43-74
Custom Constraint for Mask Parameter
3. In the Property Editor pane in the Attributes section, select the constraint
IPAddressConstraint from Constraint.
2. Enter an inavlid IP address in the mask dialog box and click OK.
See Also
More About
• “Validating Mask Parameters Using Constraints” on page 43-66
43-75
43 Working with 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.
open_system("slexMaskConstraints.slx");
43-76
Share Parameter Constraints Across Multiple Block Masks
In the example model, refer the shared constraint blocks SharedConstraintBlock1 and
SharedConstraintBlock2.
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
5. Select Property Editor > Attributes > Constraint and select the XML file constraint.
43-78
Share Parameter Constraints Across Multiple Block Masks
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
4. Select Property Editor > Attributes > Constraints and select the XML file.
43-80
Share Parameter Constraints Across Multiple Block Masks
Provide an invalid value to the parameter using mask dialog. Observe that an error dialog is displayed
on Apply.
See Also
43-81
43 Working with Block Masks
ans =
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:
See Also
More About
• “Validating Mask Parameters Using Constraints” on page 43-66
43-82
Define Measurement Units for Masked Blocks
• 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:
For example, to associate the Unit parameter with the measuring unit of the Inport block,
use:
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
43-84
Masking Example Models
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.
See Also
More About
• “Author Block Masks”
• “Mask Editor Overview”
• “Masking Fundamentals” on page 43-3
43-85
43 Working with Block Masks
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.
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:
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
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
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:
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.
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.
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.
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
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.
• 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
43-92
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.
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
43-94
Tune Mask Enumeration Parameters - Popup and Radio Button
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.
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.
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.
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.
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.
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.
You can generate code using Simulink Coder™ or Embedded Coder™. In the generated code:
• 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;
• 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];
}
An enumeration class can be created with the user data and associated with the popup parameter. To
create an enumeration class:
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.
The tunable parameter XFactorParam is referenced while generating the output. You can specify
different values to XFactorParam and thus XFactorParam is tunable.
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.
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.
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.
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.
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
typeOptions = Simulink.Mask.EnumerationMember.empty(3,0)
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);
enumObj = Simulink.Mask.EnumerationTypeOptions('EnumerationMembers',typeOptions)
enumObj.EnumerationMembers(1)
ans =
MemberName: ''
DescriptiveName: 'alpha'
Value: 1.0000e-03
enumObj =
Simulink.Mask.EnumerationTypeOptions('EnumerationMembers',typeOptions,'EnumNameInGeneratedCode','
enumObj(1)
ans =
EnumerationTypeOptions with properties:
43-100
Tune Mask Enumeration Parameters - Popup and Radio Button
ans =
MemberName: 'alpha'
DescriptiveName: 'XFactor.alpha'
Value: 1
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'
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.
43-101
43 Working with Block Masks
end
methods(Static)
function aOut = addClassNameToEnumNames()
aOut = false;
end
end
end
3. The popup options will be populated with the enumeration members in the specified class prefixed
by the enumeration class name.
See Also
Simulink.Mask.EnumerationTypeOptions
43-102
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.
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
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.
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
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
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 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
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.
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.
43-112
Visualize and Plot N-Dimensional Data Using Mask Lookup Table Control
lutControl.Table.Name = 'fuelflowtable';
lutControl.Table.Unit = 'kg/s ;
lutControl.Table.FieldName = 'Fuel Flow';
lutControl.Breakpoints(1).Name = 'torque';
lutControl.Breakpoints(1).Unit = 'Nm';
lutControl.Breakpoints(1).FieldName = 'Torque';
lutControl.Breakpoints(2).Name = 'speed';
lutControl.Breakpoints(2).Unit = 'rpm';
lutControl.Breakpoints(2).FieldName = 'Speed';
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
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.
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.
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.
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.
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.
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.
43-115
43 Working with Block Masks
See Also
43-116
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.
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
43-118
Graphical Icon Editor Overview
Element Toolstrip
43-119
43 Working with Block Masks
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
43-121
43 Working with Block Masks
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.
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.
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.
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
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
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.
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
• 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
• Define the mask block parameter CenterText in the Mask Editor. The value of this block
parameter appears in the center of the icon.
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
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
43-134
Add Dynamic Behavior to Masked Icons
specify both the Description and Value for the second row as 4. Click Save.
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
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
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.
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
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.
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.
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.
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.
43-144
Add Dynamic Behavior to Masked Icons
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
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
For example, consider this block icon where the rectangle element is repeating on all the right ports
of the block.
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
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.
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")
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.
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.
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.
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.
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
This example shows the various drawing commands used for drawing mask icons.
open_system('slexMaskDrawingExamples')
43-154
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
You can organize mask initialization and mask callback code in a separate MATLAB® class file. By
using a separate MATLAB file you can:
• 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.
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
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
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 method that executes the mask initialization code must be Static.
• Input argument to the mask initialization function is a struct with these properties:
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.
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.
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.
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.
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
• Use set_param and get_param to set and retrieve the values of parameters.
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.
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
43-162
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
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
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
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.
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 the tunability of a parameter in generated code if the mask parameter is modified in the
mask initialization code.
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.
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.
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;
}
Observe that tunability is preserved for the mask parameter Data in the generated 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.
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.
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.
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
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.
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");
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.
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.
43-175
43 Working with Block Masks
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.
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.
2. In the Signal Attributes tab, change the Data type to int16 and click OK
43-176
Share Port Constraints Across Multiple Masked Blocks
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.
See Also
43-177
44
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
• 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.
• 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:
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:
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:
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:
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
• 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
• 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?
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.
44-6
Comparison of Custom Block Functionality
44-7
44 Creating Custom Blocks
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.
44-8
Comparison of Custom Block Functionality
44-9
44 Creating Custom Blocks
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.
44-10
Comparison of Custom Block Functionality
• 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.
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
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
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
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
44-14
Design and Create a Custom Block
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.
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:
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.
• 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)
44-15
44 Creating Custom Blocks
%% -----------------------------------------------------------------
%% 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
function DoPostPropSetup(block)
• 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
44-17
44 Creating Custom Blocks
end
block.OutputPort(1).Data = sigVal;
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.
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.
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.
44-20
Design and Create a Custom Block
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:
Customized Saturation
• In the Mask description field, enter
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.
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
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
block.NumInputPorts = numInPorts;
block.NumOutputPorts = 1;
%% -----------------------------------------------------------------
%% 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
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)
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;
44-26
Design and Create a Custom Block
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)
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
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”.
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);
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 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
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
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.
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.
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
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.
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:
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.
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.
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.
You can unlock a library programmatically. At the MATLAB command prompt, enter:
set_param('library_name','Lock','off');
set_param('library_name','Lock','on');
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
45-7
45 Working with Block Libraries
To specify information about your library, you create a function named slblocks.
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.
Browser.Library = 'mylib';
% 'mylib' is the name of the library
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.
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
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:
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.
45-12
Linked Blocks
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
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
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
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.
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
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
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:
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.
See Also
More About
• “Linked Blocks” on page 45-12
45-21
45 Working with Block Libraries
45-22
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.
• 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
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.
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
You can restore a disabled linked block or push a linked block value to the parent library block either
individually or hierarchically.
• 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.
• 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.
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 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:
• 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
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.
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.
45-30
Restore Parameterized Links
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
• 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.
• 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.
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
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')
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.
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.
45-34
Control Linked Block Programmatically
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
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.
• 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.
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.
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.
45-38
Maintain Compatibility of Library Blocks Using Forwarding Tables
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
After:
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.
% Get linked block instance data and forwarding entry for which
% function is called
instanceData = inData.InstanceData;
forwardingTableEntry = inData.ForwardingTableEntry;
45-40
Maintain Compatibility of Library Blocks Using Forwarding Tables
[ParamNames{1:length(instanceData)}] = instanceData.Name;
% 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__');
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.
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
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”.
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
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).
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
Alternatively, you can use relative pathnames to specify the header and source files individually:
#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
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
• 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.
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.
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:
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
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:
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.
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.
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
If your C functions accept only scalar and/or vector inputs, the Default function array layout
setting has no effect.
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
click the custom code settings button to open the Simulation Target pane in Model
Configuration Parameters.
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
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.
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.
47-6
Integrate C Code Using C Caller Blocks
double u[][2]
double u[2][3]
const double *u Input (default), Parameter
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.
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.
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
** 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
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)
47-9
47 Integrate C Code in Simulink Models
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.
myCCallerConfigObj =
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.
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”.
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
47-12
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 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
Build Summary
sort_ascend(&rtb_CCallerascend[0], 6);
sort_descend(&rtb_CCallerdescend[0], 6);
47-14
Use C Caller Block with Conditional Execution
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');
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);
Build Summary
47-16
Use C Caller Block with Conditional Execution
sort_ascend(&rtb_CCallerascend[0], 6);
sort_descend(&rtb_CCallerascend[0], 6);
/* Outport: '<Root>/Out3' */
for (i = 0; i < 6; i++) {
slexCCallerConditional_Y.Out3[i] = rtb_CCallerascend[i];
}
See Also
“Deterministic functions” | “Specify by function” | C Function | C Caller
47-17
48
• “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
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.
/* 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"
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.
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.
48-5
48 Integrate Algorithms Using C Function Blocks
#ifdef MATLAB_MEX_FILE
/* Enter simulation code */
#else
/* Enter code generation code */
#endif
#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
This example demonstrates the use of a C Function block with C++ classes.
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;
}
48-7
48 Integrate Algorithms Using C Function Blocks
int adder::get_val()
{
return int_state;
}
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:
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
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
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
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
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.
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
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');
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.
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
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')
48-23
48 Integrate Algorithms Using C Function Blocks
See Also
Objects
SymbolSpec | Symbol
Blocks
C Function
48-24
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
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:
where FLT is a type definition to a floating-point type, and UINT32 is a type definition to an unsigned
32-bit integer.
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
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
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
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
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:
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:
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
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 model calls custom code from a For Each subsystem. When the model runs, the scope displays
the output.
open_system('slexCFunctionForEach');
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');
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
• “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
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”.
These C code source and header files contain the complete code for the heat pump controller.
• tempController.c
• utils.c
• 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.
49-2
Import Custom Code Using the Simulink 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.
Once the Welcome page loads, click Start to begin the import process.
49-3
49 Simulink Code Importer
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
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
49-5
49 Simulink Code Importer
Alternatively, to specify the custom code programmatically, use the following code.
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
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.
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';
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.
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.
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
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.
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
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)