0% found this document useful (0 votes)
52 views144 pages

Matlab Simulink

The document provides information about using MATLAB and Simulink. It discusses how to start Simulink, open models, load and save models, use the Simulink editor, simulate models, and get an overview of how Simulink works for modeling dynamic systems. The document is a user guide that teaches the basics of the Simulink modeling environment.

Uploaded by

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

Matlab Simulink

The document provides information about using MATLAB and Simulink. It discusses how to start Simulink, open models, load and save models, use the Simulink editor, simulate models, and get an overview of how Simulink works for modeling dynamic systems. The document is a user guide that teaches the basics of the Simulink modeling environment.

Uploaded by

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

MATLAB AND SIMULINK

Simulink Introduction
J. ABELL
Simulink Basics
1
Start the Simulink Software Open the MATLAB Software Open the Library Browser
Open the Simulink Editor
Open a Model
What Happens When You Open a Model Open an Existing Model
Models with Different Character Encodings Avoid Initial Model Open Delay
Load a Model
Load Variables When Loading a Model
Save a Model
How to Tell If a Model Needs Saving
Save a Model for the First Time
Model Names
Save a Previously Saved Model
What Happens When You Save a Model?
Saving Models in the SLX File Format
Saving Models with Different Character Encodings Export a Model to a Previous
Simulink Version Save from One Earlier Simulink Version to Another
Simulink Editor
Editor Layout
Undoing Commands Window Management
Zoom and Pan Block Diagrams
v
Update a Block Diagram
Updating the Diagram
Simulation Updates the Diagram Update Diagram at Edit Time
Copy Models to Third-Party Applications
Print a Block Diagram
Print Interactively or Programmatically Systems to Print
Title Block Print Frame
Paper Size and Orientation
Diagram Positioning and Sizing Tiled Printing
Print Sample Time Legend
Printing Limitations
Generate a Model Report Model Report Options
End a Simulink Session
Keyboard and Mouse Shortcuts for Simulink Model Viewing Shortcuts
Block Editing Shortcuts
Line Editing Shortcuts
Signal Label Editing Shortcuts
Annotation Editing Shortcuts
Simulink Demos Are Now Called Examples

Simulation Stepping
2
Simulation Stepping
How Stepping Through a Simulation Works Simulation Stepper Interface
Simulation Stepper Limitations
Step Through a Simulation Configure Simulation Stepping Step Forward and Back
Set Conditional Breakpoints for Stepping a Simulation
Conditional Breakpoints Limitations
Add and Edit Conditional Breakpoints Observe Conditional Breakpoint Values

How Simulink Works


3
How Simulink Works
Modeling Dynamic Systems Block DiagramSemantics Creating Models
Time
States
Block Parameters
Tunable Parameters
Block Sample Times
Custom Blocks
Systems and Subsystems Signals
Block Methods
Model Methods
Simulating Dynamic Systems Model Compilation
Link Phase
Simulation Loop Phase
Solvers
Zero-Crossing Detection Algebraic Loops
Referencing a Model, 6XEV\VWHPVDQG9DULDQW6\VWHPV

Start the Simulink Software


Open the MATLAB Software

To start the Simulink software, first start the MATLAB®technical computing environment.
For details about starting MATLAB, see “Startup and Shutdown”.

Open the Library Browser

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

).
•At the MATLAB prompt, enter the simulinkcommand.
The Library Browser opens. It displays a tree-structured view of the Simulink block
libraries installed on your system. The Simulink library window displays icons
representing the pre-installed block libraries.
Start the Simulink® Software
Note On computers running the Windows®operating system, you can display the Simulink
library window by right-clicking the Simulink node in the Library Browser window.
To create models, copy blocks from the Library Browser into a model window in the
Simulink Editor.

Open the Simulink Editor

Use one of the following approaches to open the Simulink Editor:


•Open an existing model. For example, at the MATLAB prompt, enter the name of a
model. For details, see “Open an Existing Model”.
•In the Library Browser, select File > Open. Choose a model or enter
thefilenameofthemodel.
•At the MATLAB prompt, use the open_systemcommand. For example, to open a model
named vdp:
open_system(‘vdp’)
Note To have the Simulink Editor display properly, use 32-bit color mode.
Typically, remote desktop connections (for example, a VNC connection) use a default
color mode of 16-bits or less.

Open a Model

In this section…
“What Happens When You Open a Model” “OpenanExistingModel”
“Models with Different Character Encodings” “Avoid Initial Model Open Delay”

What Happens When You Open a Model

Opening a model brings the model into memory and displays the model graphically in the
Simulink Editor.
You can also bring a model into memory without displaying it, as described in “Load a
Model”

Open an Existing Model

To open an existing model, use one of these approaches:


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

Models with Different Character Encodings

If you open a model created in a MATLAB software session configured to support one
character set encoding (for example, Shift_JIS), in a session configured to support another
character encoding (for example, US_ASCII), Simulink displays a warning for SLX files.
For MDL files, you might see a warning or an error message, depending on whether it can
encode the model, using the current character encoding. The warning or error message
specifies the encoding of the current session and the encoding used to create the model. To
display the model’s text correctly:
1Close all models open in the current session.
2Use the slCharacterEncodingcommand to change the character encoding of the current
MATLAB software session to that of the model as specified in the warning message.
3Reopen the model.
You can now edit and save the model.
Simulink can check if models contain characters unsupported in the current locale. For
more details, see “Check file for foreign characters” and “Saving Models with Different
Character Encodings”.

Avoid Initial Model Open Delay

The first model that you open in a MATLAB session takes longer to open than do
subsequent models. This is because MATLAB does not load the Simulink product into
memory until the first time that you open a Simulink model. This just-in-time loading of
the Simulink product reduces the MATLAB startup time and avoids unnecessary
consumption of system memory.
To avoid the initial model opening delay, you can have MATLAB load the Simulink
software when the MATLAB product starts up. You can issue the command to load
Simulink at MATLAB startup from one of two places:
• The -rcommand line option
•The MATLAB startup.mfile Use one of these commands:
• load_simulink— loads the Simulink product
• simulink— loads the Simulink product and opens the Simulink Library Browser
For example, to load the Simulink product when the MATLAB software starts up on a
computer running the Microsoft®Windows operating system, create a desktop shortcut
with the following target:
matlabroot\bin\win32\matlab.exe
-r load_simulink
Similarly, the following command loads the Simulink software when the MATLAB
software starts up on Macintosh and Linux®computers:
matlab -r load_simulink LoadaModel

Load a Model

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

Load Variables When Loading a Model

You can use model callbacks to load variables and perform other actions when a model is
loaded. For details, see “Callbacks for Customized Model Behavior” .
You can use the PreloadFcncallback to automatically preload variables into the MATLAB
workspace when you open a model.
Parameters in different parts of the Simulink model might require some variables. For
example, if you have a model that contains a Gain block and the gain is specified as K,
Simulink looks for the variable Kto be defined. You can automatically define Kevery time
the model loads.
You can define variables, such as K, in a MATLAB script. You can use the
PreLoadFcncallback to execute the MATLAB script.
To create model callbacks interactively, in the Simulink Editor, select File > Model
Properties > Model Properties and use the Callbacks tab to edit callbacks.
To create a callback programmatically, at the MATLAB command prompt, enter the
following :
set_param(‘mymodel‘,‘PreloadFcn’, ‘expression’)
where expressionis a valid MATLAB command or a MATLAB script that exists in your
MATLAB search path.
For example, if your model is called modelname.slxand your variables are defined in a
MATLAB script called loadvar.m, you would type the following:
set_param(‘modelname’,‘PreloadFcn’, ‘loadvar’)
Now save the model. Every time you subsequently open this model, the loadvarfunction
executes. You can see the variables from the loadvar.m declared in the MATLAB
workspace.
For example, if you have a model that contains a Gain block with a gain specified as K,
Simulink looks in the MATLAB base workspace for the variable Kto be defined. You can
use the PreLoadFcncallback, to automatically define Keverytimeyouopenthemodel.
Assuming that you have several variables (such as K)predefinedina MATLAB file called
loadvar.m,tobeusedinamodelcalled modelname.slx, you can use the PreLoadFcncallback
to execute the MATLAB file loadvar.m. For example, type the following at MATLAB
command prompt:
set_param(‘modelname’,‘PreLoadFcn’, ‘loadvar’)
After saving the model, every subsequent time you open this model, the loadvarfunction
executes. After opening modelname.slx,type:
whos The variables from the loadvar.mfile are in the MATLAB workspace.

Save a Model

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

How to Tell If a Model Needs Saving

To tell whether a model needs saving, look at the title bar in the Simulink Editor. If the
model needs saving, an asterisk appears next to the model name in the title bar.
To determine programmatically whether a model needs saving, use the model parameter
Dirty. For example:
if strcmp(get_param(gcs, ‘Dirty’), ‘on’)
save_system;
end

Save a Model for the First Time

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

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

Save a Previously Saved Model


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

What Happens When You Save a Model?

Simulink saves the model by generating a specially formatted file called the model file that
contains the block diagram and block properties. The Simulink software follows this
process while saving a model:
1Ifthe model file already exists, Simulink renames the model file as a temporary file.
2All block PreSaveFcncallback routines execute first, then the block diagram
PreSaveFcncallback routine executes.
3 Simulink writes the model file to a new file using the same name and, by default, an
extension of .slx.
4All block PostSaveFcncallback routines execute, then the block diagram
PostSaveFcncallback routine executes.
5Simulink deletes the temporary file.
If an error occurs during this process, Simulink:
• Renames the temporary file to the name of the original model file
•Writes the current version of the model to a file with an .errextension
•Issues an error message
If an error occurs in Step 2 of the save process, then Step 3 is omitted and Steps 4 and 5
are performed.

Saving Models in the SLX File Format

SaveNewModelsasSLX
You save new models and libraries in the SLX format by default, with file extension .slx.
SLX is a compressed package that conforms to the Open Packaging Conventions (OPC)
interoperability standard. SLX stores model information using Unicode®UTF-8 in XML
and other international formats. Saving Simulink models in the SLX format:
•Typically reduces file size compared to MDL. The file size reduction between MDL and
SLX varies depending on the model.
•Solves some problems in previous releases with loading and saving MDL files containing
Korean and Chinese characters.
You can specify your file format for saving new models and libraries with the Simulink
preference “File format for new models and libraries”.
Upgrade Models to SLX
If you upgrade an MDL file to SLX file format, the file contains the same information as
the MDL file, and you always have a backup file. All functionality and APIs that currently
exist for working with models, such as the get_paramand set_paramcommands, are also
available when using the SLX file format. If you upgrade an MDL file to SLX file format
without changing the model name or location, then Simulink creates a backup file by
renaming (if writable) and Simulink does not remove the MDL file.
IfyousaveanexistingMDLfileusing File > Save, Simulink respects the file’s current format
and saves your model in MDL format.
To save an existing MDL file in the SLX file format,
1Select File > Save As.
2Leave the default Save as type as SLX, and click Save.

Simulink saves your model in SLX format, and creates a backup file by renaming the
MDL (if writable) to mymodel.mdl.releasename, e.g., mymodel.mdl.R2010b.
Alternatively, use save_system:
save_system mymodel mymodel.slx
This command creates mymodel.slx, and if the existing file mymodel.mdlis writable it is
renamed mymodel.mdl.releasename.
SLX files take precedence over MDL files, so if both exist with the same name and you do
not specify a file extension, you load the SLX file.
Simulink Projects can help you migrate files to SLX. For an example, see “Upgrade
Model Files to SLX and Preserve Revision History”.
Caution If you use third-party source control tools, be sure to register the model file
extension .slxas a binary file format. If you do not, these third-party tools might corrupt
SLX files when you submit them.
Operations
with Possible
Compatibility
Considerations when using SLX
Hard-coded references to file names with
extension .mdl.
What Happens Action
Scripts cannot find or process models saved with new file extension .slx.
Third-party source control tools that assume a text format by default.
Binary format of
SLX files can cause third-party tools to corrupt the files when you submit them.
Changing character encodings.
Some cases are
improved, e.g., SLX solves some problems in previous releases with loading and saving
MDL files containing Korean and Chinese characters. However, sharing models between
different locales
remains problematic. Make your code work with both the .mdland .slxextension.
Use functions like
whichand whatinstead of strings with .mdl.
Register .slxas a
binary file format with third-party source
control tools. Also recommended for .mdl files. See “Register Model Files with Source
Control Tools”
.
See “SLX Files and Character Encodings” .
The format of content within MDL and SLX files is subject to change. To operate on
model data, use documented APIs (such as get_param, find_systemand
Simulink.MDLInfo.

Saving Models with Different Character Encodings

•“Differences in Character Encodings”


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

It’s possible that your model’s original encoding can represent all the text changes that
you’ve made in the current session, albeit incorrectly. For example, suppose you open a
model whose original encoding is A in a session whose current encoding is B. Further
suppose that you edit the model to include a character that has different encodings in A
and B and then save the model. If in addition the encoding for x in B is the same as the
encoding for y in A, and if you insert x in the model while B is in effect, save the model,
and then reopen the model with A in effect the Simulink software will display x as y. To
alert you to the possibility of such corruptions, the software
1-14
displays a warning message whenever you save a model in which the current and original
encoding differ but the original encoding can encode, possibly incorrectly, all of the
characters to be saved in the model file.
SLX Files and Character Encodings
Saving Simulink models in the SLX format typically reduces file size and solves some
problems in previous releases with loading and saving MDL files containing Korean and
Chinese characters.
Considerations for choosing a model file format:
•Use SLX if you are loading and saving models with Korean or Chinese characters
•Use SLX if you would benefit from a compressed model file
• Whether you use SLX or MDL, Simulink can detect and warn if models contain
characters unsupported in the current locale. For SLX, you can use the Model Advisor to
help you, see “Check file for foreign characters”.

Export a Model to a Previous Simulink Version

You can export (save) a model created with the latest version of the Simulink software in a
format used by an earlier version, such as Simulink 7.0 (R2007b). For example, you might
want to perform such an export to make a model available to colleagues who only have
access to a previous version of the Simulink product.
To export a model in an earlier format:
1In the Simulink Editor, select File > Save. This saves a copy in the latest version of
Simulink. This step avoids compatibility problems.
2Simulink Editor, select File > Export Model to > Previous Version.
The Export to Previous Version dialog box appears.
3In the dialog box, from the Save as type list, select the previous version to which to
export the model.
4 Click the Save button. When you export a model to a previous version’s format, the
model is saved in the earlier format, regardless of whether the model contains blocks and
features that were introduced after that version. If the model does contain blocks or use
features that postdate the earlier version, the model might not give correct results when
you run it in the earlier version of Simulink software. In addition, Simulink converts
blocks that postdate an earlier version into yellow empty masked Subsystem blocks. For
example, if you export a model to Release R2007b, and the model contains Polynomial
blocks, Simulink converts the Polynomial blocks into yellow empty masked Subsystem
blocks. Simulink also removes any unsupported functionality from the model.

Save from One Earlier Simulink Version to Another

You can open a model created in an earlier version of Simulink and export that model to a
different earlier version. To prevent compatibility problems, use the following procedure if
you need to save a model from one earlier version to another earlier version.
1Use the current version of Simulink to open the model created with the earlier version.
2Before you make any changes, save the model in the current version by selecting File >
Save.
After saving the model in the current version, you can change and resave it as needed.
3Save the model in the earlier version of Simulink by selecting File > Export Model to >
Previous Version.
4Start the earlier Simulink version and use it to open the model that you exported to that
earlier version.
5Save the model in the earlier version by selecting File > Save.
You can now use the model in the earlier version of Simulink exactly as you could if it had
been created in that version.
See also the Simulink preferences that can help you work with models from earlier
versions:
•“Do not load models created with a newer version of Simulink”
•“Save backup when overwriting a file created in an older version of Simulink”

Simulink Editor

In this section… “Editor Layout” “Undoing Commands” “Window Management”


Editor Layout

Opening a Simulink model or library displays the model or library in the Simulink Editor.
For more information, see “Open the Simulink Editor”

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

Inthetopleftcorner,thetitlebardisplaysthenameofthemodelor subsystem
that is open in the model window.
• Menu bar and toolbar

At the top of the Simulink Editor, you can access commands to work with models. Several
buttons in the toolbar provide quick access to commonly used Simulink Editor menu
options. Other buttons in the toolbar open other Simulink tools, such as the Model
Explorer (for details, see “Open Simulink Tools from the Toolbar”).
• Palette
The icons in the vertical bar on the right side of the Simulink Editor perform very
common tasks, such as adding an annotation.
• Explorer bar
The breadcrumb shows the systems that you have open in the editor. Select a system in the
breadcrumb to open that system in the model window. If you click in the Explorer bar
whitespace, you can edit the hierarchy. Also, the down arrow at the right side of the
Explorer bar provides a history.

• Model Browser

Click the double arrows

in the bottom left corner of the Simulink Editor to open or close a tree-structured view of
the model in the editor.
• Canvas — The canvas is area where you edit the block diagram. You can use the mouse
and keyboard to create and connect blocks, select and move blocks, edit block labels,
display block dialog boxes, and so on.
To display context menus specific to a particular model object in the canvas, such as a
block, right-click the object.
• Status information — Near the top of the editor, you can see (and reset) the simulation
time and the simulation mode. The bottom status line shows the status of Simulink
processing, the zoom factor, and the solver.
Open Simulink Tools from the Toolbar
The Simulink Editor toolbar provides several buttons for quick access to other Simulink
tools.
For buttons that have associated menu options, clicking the button invokes the first menu
option.
Tools
Library Browser
Model Explorer
Buttons and Associated Menus

Simulation Stepper
Simulation Data Inspector
Advisor Tools Next Step
Previous Step

Undoing Commands

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

Window Management

One Simulink Editor Per Model


When youopen a model, that model appears in its own Simulink Editor window.For
example, if you have one model already open, and then you open a secondmodel, the
second model appears in a second Simulink Editor.
To openthe same model in two separate Simulink Editor windows, at the
MATLABcommand prompt, enter the open_systemcommand, using the windowargument.
For example, if you already have the vdpmodel open, then to open another instance of the
vdpmodel in a separate Simulink Editor, enter:
open_system (‘vdp’, ‘window’)
Open a Subsystem
The Simulink Editor displays only one active window at a time. By default, if you open a
Subsystem block, the opened subsystem replaces (in terms of being displayed in the model
window) the model from which you opened the subsystem.
You can use tabs in the Simulink Editor to make it easier to navigate between model
windows for the top model and subsystems. To open a subsystem in a separate tab:
1Right-click the Subsystem block.
2From the context-menu, select Open In New Tab. In the example below, there are
separate tabs for the ex_sscreate2model and for the Subsystem.

Navigate between the top model and subsystems by clicking the appropriate tab. Or,
choose an option following options from the View > Navigate menu, such as Back, Back
to Parent,or Previous Tab.
For more information about opening subsystems, see “Navigate Model Hierarchy”.
To rearrange the order of tabs within a Simulink Editor window:
1Select the tab that you want to move.
2Drag the tab to where you want it to appear.
3Release the mouse button.

Open a Referenced Model


If you open a Model block, the referenced model opens in a separate Simulink Editor.
Bring the MATLAB Desktop Forward
Simulink Editor windows open on top of the MATLAB desktop. To bring the MATLAB
desktop back to the top of your screen, in the Simulink Editor, select View > MATLAB
Desktop.
Zoom and Pan Block Diagrams

Zoom and Pan Block Diagrams


You can enlarge or shrink the view of the block diagram in the current Simulink Editor
window.
Goal of Zoom or Pan Enlarge the model
diagram incrementally Enlarge the model
diagram dynamically
Zoom by a factor of two, displaying the selected model object
Zoom until the whole model diagram just fits in the current window
Zoom and pan
What You Do
Select View > Zoom > Zoom In or press Ctrl++.
Roll the mouse scroll wheel forward.
1In the palette, drag the zoom button (

)to the object that you want to include in the enlarged view.
2Press the left mouse button.
Select View > Zoom > Fit to View or press Spacebar.
Pan with the mouse 1Roll the mouse scroll wheel forward.
2Release the scroll wheel.
3Hold the scroll wheel down and pan to the desired positioning by moving the mouse.
4Release the scroll wheel.

To disable the zoom and pan behavior for the scroll wheel, clear the File > Simulink
Preferences > Editor Defaults > Scroll wheel controls zooming preference.
Hold down Spacebar and drag mouse.
Goal of Zoom or Pan Pan incrementally with arrow keys
Shrink the model diagram incrementally
Shrink the model diagram dynamically
Restore the model diagram to 100%
What You Do
If scroll bars are visible, then with nothing selected, use Shift+Left Arrow (or the right,
up, or down arrow key) or for finer panning, just the arrow key.
Select View > Zoom > Zoom Out.
Roll the mouse scroll wheel backward.
Select View > Zoom > Normal View (100%) or press Alt+1.
To disable the zoom and pan behavior for the scroll wheel, clear the File > Simulink
Preferences > Editor Defaults > Scroll wheel controls zooming preference. If you hold
the Ctrl key and use the scroll wheel, the scroll wheel behavior is the opposite of how the
preference is set.
Update a Block Diagram

Update a Block Diagram


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

Simulation Updates the Diagram


Simulink updates the block diagram at the start of a simulation. The updated diagram
provides the simulation with the results of the latest changes that youhavemadetoamodel.

Update Diagram at Edit Time


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

2In the Simulink Editor, select Display > Signals & Ports
> Port Data Types.
The data types of the output ports of the Constant and Gain blocks appear. The data type
of both ports is double, the default value.

3In the Constant block parameters dialog box, set Output


data type to single.
The output port data type displays on the block diagram do not reflect this change.
4In the Simulink Editor, select Simulation > Update Diagram.
The updated block diagram reflects the change that you made previously.

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

Copy Models to Third-Party Applications


On a computer running the Microsoft Windows operating system, you can:
1Copy a Simulink product model to the Windows operating system clipboard.
2Paste the model from the clipboard to a third-party application, such as word processing
software.
You can copy a model in either bitmap or metafile format. You can then paste the
clipboard model to an application that accepts figures in bitmap or metafile format. For a
description of how to set up the figure settings and save a figure to the clipboard on a
Windows platform, see “Exporting to the Windows or Macintosh Clipboard”.

Print a Block Diagram

In this section…
“Print Interactively or Programmatically” “Systems to Print”
“Title Block Print Frame”
“Paper Size and Orientation” “Diagram Positioning and Sizing” “Tiled Printing”
“Print Sample Time Legend”
“Printing Limitations”

Print Interactively or Programmatically

You can print a block diagram:


•Interactively in the Simulink Editor, by selecting File > Print.
•Programmatically, by using the MATLAB printcommand.
To control some additional aspects of printing a block diagram, use the
param_setcommand with model parameters.

Systems to Print

From the Simulink Editor


To specify what systems in a block diagram that you want to print:
1In the Simulink Editor, selectFile>Print>Print.
The Print Model dialog box appears.
2In the Options section, select one of the following:
• Current system — The current system only
• Current system and above — The current system and all systems above it in the model
hierarchy
• Current system and below — The current system and all systems below it in the model
hierarchy, with the option of looking into the contents of masked and library blocks
• All systems — All systems in the model, with the option of looking into the contents of
masked and library blocks
To print the contents of masked subsystems that are at or below the level of the current
block, select the Look under mask dialog check box. When you print all systems, the
top-level system is the current block, so Simulink looks under all masked blocks.
To print the contents of library blocks that are systems, in the Print Model dialog box,
select the Expand unique library links check box. Only one copy is printed, regardless
of how many copies of the block that the model contains.
The print log lists the blocks and systems printed. To print the print log, select the Include
Print Log check box.
With the Print Command
The format of the printcommand is
print -ssys device -tileall -pagesp filename
sys is the name of the system to be printed. Precede the system name with the -sswitch
identifier. The name of the system is the only required argument. The system must be open
or must have been open during the current session. If the system name contains spaces or
takes more than one line, you need to specify the name as a string.
The printcommand prints only the system that you specify. The command does not have
options to specify the scope of the systems to be printed (for example, current system and
below). To specify the scope of the systems to be printed, use the Simulink Editor.
This example shows how to print the currently selected subsystem (Controller).
open_system(‘f14’);
open_system(‘f14/Controller’); print([‘-s’, gcs])
This example shows how to print the contents of a subsystem named Controllerin the
current system.
open_system(‘f14’); print -sController
This example shows how to print the contents of a subsystem named Aircraft Dynamics
Model.
open_system(‘f14’);
print ([‘-sAircraft Dynamics Model’])
To print a system whose name appears on multiple lines, assign the newline character to a
variable and use that variable in the printcommand. This example shows how to print a
subsystem whose name, Aircraft Dynamics Model, appears on three lines.
open_system(‘f14’);
cr = sprintf(‘\n’);
print ([‘-sAircraft’ cr ‘Dynamics’ cr ‘Model’])
The devicespecifies the device type. For a list of device types, see the documentation for
the printfunction.
The filenameis a PostScript®file to which you save the output. If filename exists, it is
replaced. If filenamedoes not include an extension, an appropriate one is appended.

Title Block Print Frame


A title block print frame is a border that contains information relevant to the block
diagram, such as the name of the block diagram. After you create a print frame, you can
print a block diagram with a print frame: 1In the Simulink Editor, selectFile>Print>Print.
The Print Model dialog box appears.
2Select the Frame check box.
3In the adjacent edit box, enter the path to the title block frame.

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

Paper Size and Orientation


On Windows platforms, you can use the Simulink Editor to specify the type and
orientation of the paper for printing a model.
1Select File > Print > Printer Setup.
The Print Setup dialog box appears.
2In the Paper and Orientations section, set the fields for paper size and orientation.
On all platforms, you can set the paper orientation alone, using the MATLAB
orientcommand.
On all platforms, you can also set the paper type and orientation by using the
set_paramcommand with the model’s PaperTypeandPaperOrientation properties,
respectively (see “Model Parameters”).

Diagram Positioning and Sizing

To position and size the model diagram on the printed page, use the set_paramcommand
with a model’s PaperPositionModeand PaperPosition parameters.
The value of the PaperPositionparameter is a vector of form [left bottom width height].
The first two elements specify the bottom-left corner of a rectangular area on the page,
measured from the page’s bottom-left corner. The last two elements specify the width and
height of the rectangle. If you set the PaperPositionModeparameter to manual, Simulink
positions (and scales, if necessary) the model diagram to fit inside the specified print
rectangle. If PaperPositionModeis auto, Simulink centers the model diagram on the
printed page, scaling the diagram, if necessary, to fit the page.
For example, these commands print the block diagram of the vdpmodel in the lower-left
corner of a U.S. letter-size page in landscape orientation.
open_system(‘vdp’);
set_param(‘vdp’, ‘PaperType’, ‘usletter’); set_param(‘vdp’, ‘PaperOrientation’,
‘landscape’); set_param(‘vdp’, ‘PaperPositionMode’, ‘manual’); set_param(‘vdp’,
‘PaperPosition’, [0.5 0.5 4 4]); print -svdp

Tiled Printing
By default, each block diagram is scaled during the printing process so that it fits on a
single page. That is, the size of a small diagram is increased or the size of a large diagram
is decreased to confine its printed image to one page. In the case of a large diagram,
scaling can make the printed image difficult to read.
By contrast, tiled printing enables you to print even the largest block diagrams without
sacrificing clarity and detail. Tiled printing allows you to distribute a block diagram over
multiple pages. You can control the number of pages over which Simulink prints the block
diagram, and hence, the total size of the printed diagram.
Also, you can set different tiled-print settings for each of the systems in your model.
Consequently, you can customize the appearance of all printed images to best suit your
needs. The following sections describe how to use tiled printing.
Enable Tiled Printing
To enable tiled printing for a model or subsystem, use one of these approaches:
• In the Simulink Editor, select File > Print > Enable Tiled Printing.
•At the MATLAB command prompt:
1 Use the set_paramcommand to set the PaperPositionModeparameter to tiled(see ).
2 Use the printcommand with the -tileallargument.
For example, to open the f14model and enable tiled printing for the Controllersubsystem,
enter:
open_system(‘f14’);
set_param(‘f14/Controller’, ‘PaperPositionMode’, ‘tiled’); print(‘-sf14/Controller’, ‘-
tileall’)
Display Page Boundaries
Displaying the page boundaries in the Simulink Editor can help you to visualize the model
size and layout with respect to the page. To make the page boundaries visible, select File >
Print > Show Page Boundaries.
Simulink renders the page boundaries on the Simulink Editor canvas. If tiled printing is
enabled, Simulink represents page boundaries with a checkerboard pattern. Each
checkerboard square indicates the extent of a separate page.
If tiled printing is disabled, only a single page appears on the canvas.
To display the page boundaries programmatically, use the set_param command, with the
system’s ShowPageBoundariesparameter set to on(see “Model Parameters”). For example:
open_system(‘vdp’);
set_param(‘vdp’, ‘ShowPageBoundaries’, ‘on’)
Scaling and Margins
To scale the block diagram so that more or less of it appears on a single tiled page, use the
set_paramcommand with the TiledPageScaleparameter. By default, its value is 1. Values
greater than 1proportionally scale the diagram such that it occupies a smaller percentage
of the tiled page, while values between 0and 1proportionally scale the diagram such that it
occupies a larger percentage of the tiled page. For example, a TiledPageScaleof 0.5makes
the printed diagram appear twice its size on a tiled page, while a TiledPageScale of
2makes the printed diagram appear half its size on a tiled page.
To specify the margin sizes associated with tiled pages, use the set_param command with
the TiledPaperMarginsparameter. The value of TiledPaperMarginsis a vector of form [left
top right bottom].Each element specifies the size of the margin at a particular edge of the
page. The value of the PaperUnitsparameter determines the margin’s units of
measurement. Each margin to 0.5 inches by default. By decreasing the margin sizes, you
can increase the printable area of the tiled pages.
Range of Tiled Pages
By default, Simulink prints all of a system’s tiled pages.
On a Microsoft Windows platform, to specify a range of tiled page numbers to print, you
can use the Simulink Editor.
1In the Simulink Editor, selectFile>Print>Print.
The Print Model dialog box appears.
2In the Options section, select Current system and Enable tiled printing for all systems.

3 In the Print range section in the middle of the dialog box, select Pages and enter a page
range.
To specify a range of tiled page numbers programmatically, use the print command with
the -tileallargument and the -pagesargument. Append to
-pagesa two-element vector that specified the range.
Note Simulink uses a row-major scheme to number tiled pages. For example, the first
page of the first row is 1, the second page of the first row is 2, and so on.
For example, to print the second, third, and fourth pages:
open_system(‘vdp’);
print(‘-svdp’, ‘-tileall’, ‘-pages[2 4]’)

Print Sample Time Legend


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

Printing Limitations

Printing Properties (Windows)


On Windows platforms, the File > Print > Print dialog box includes:
•Printing options, such as the printer to use, the print range, the number of copies, and
which systems to print.
• A Properties button, which displays additional printing properties, such as paper
orientation and resizing options. Simulink ignores the settings for these additional printing
properties. Simulink only uses the settings in the main Print dialog box.
Printer Name (Mac)
On Mac platforms, the printer name that you specify in the File > Print > Print dialog
box must:
•Use only alphanumeric characters (letters and numbers), and not special characters such
as an underscore or ampersand (&)
•Include no blank spaces

Generate a Model Report

A model report is an HTML document that describes the structure and content of a model.
The report includes block diagrams of the model and its subsystems and the settings of its
block parameters.
Tip If you have the Simulink Report Generator™ installed, you can generate a detailed
report about a system. To do so, in the Simulink Editor, select File > Reports > System
Design Description. For more information, see “System Design Description”.
To generate a model report for the current model:
1In the Simulink Editor, select File > Print > Print Details.
The Print Details dialog box appears.
2Select the desired report options. For details, see “Model Report Options” .
3Select Print.

The Simulink software generates the HTML report and displays the report in your default
HTML browser.
While generating the report, Simulink displays status messages on a messages pane that
replaces the options pane on the Print Details dialog box.

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

Model Report Options

Use the Print Details dialog box allows you to specify the following report options.
Directory
The folder where the HTML report is stored. The options include your system’s temporary
folder (the default), your system’s current folder, or another folder whose path you specify
in the adjacent edit field.
Increment filename to prevent overwriting old files Creates a unique report file name
each time you generate a report for the same model in the current session. This preserves
each report.
Current object
Include only the currently selected object in the report.
Current and above
Include the current object and all levels of the model above the current object in the report.
Current and below
Include the current object and all levels below the current object in the report.
Entire model
Include the entire model in the report.
Look under mask dialog
Include the contents of masked subsystems in the report.
Expand unique library links
Include the contents of library blocks that are subsystems. The report includes a library
subsystem only once even if it occurs in more than one place in the model.

End a Simulink Session

To terminate a Simulink software session, close all Simulink windows.


To terminate a MATLAB software session, in the Simulink Editor, select File > Exit
MATLAB.

Keyboard and Mouse Shortcuts for Simulink


In this section…
“Model Viewing Shortcuts”
“Block Editing Shortcuts”
“Line Editing Shortcuts”
“Signal Label Editing Shortcuts”
“Annotation Editing Shortcuts”

Model Viewing Shortcuts

The following table lists keyboard shortcuts for viewing models.


Task
Zoom in
Zoom out
Zoom to normal (100%) Pan
Fit diagram to screen Pan with mouse
Delete selection
Move selection
Shortcut
Ctrl++
Ctrl+
Alt+1
Hold the mouse scroll wheel down and drag the mouse
Spacebar
Hold down Spacebar and drag mouse Delete or Backspace
Make selection and use arrow keys

Block Editing Shortcuts

The following table lists mouse and keyboard actions that apply to blocks.
Task Shortcut
Select one block Left mouse button (LMB) Select multiple blocks Shift+LMB
Task
Copy block from another window
Move block
Resize block, keeping same ratio of width and height
Shortcut Drag block
Drag block
Select block, press Shift, and resize block
Resize block from the center Select block, press Ctrl,andresizeblock Ctrl+R
Ctrl+Shift+R
Rotate block clockwise Rotate block
counterclockwise
Flip block
Duplicate block
Connect blocks
Disconnect block
Create subsystem from selected blocks
Open selected subsystem Go to parent of selected subsystem
Look under a block mask Comment out a block Uncomment a block
Ctrl+I
Ctrl+C,then Ctrl+V
Select output port, hover over input port, and press Ctrl+LMB
Shift + drag block
Ctrl+G
Enter Esc
Ctrl + U
Select block and press Ctrl+Shift+X
Select commented block and press Ctrl+Shift+X

Line Editing Shortcuts

The following table lists mouse and keyboard actions that apply to lines.
Task
Select one line
Select multiple lines
Draw branch line
Route linesaround blocks Move line segment
Move vertex
Shortcut
Left mouse button (LMB)
Shift+LMB
Ctrl + drag line; or RMB and drag line Shift+drawlinesegments
Drag segment
Drag vertex

Signal Label Editing Shortcuts


The nexttable lists mouse and keyboard actions that apply to signal labels.
Action
Create signal label Copy signal label Movesignal label Edit signal label
Shortcut
Double-click line, then enter label Ctrl + drag label
LMB +drag label
Clickinlabel,thenedit

Annotation Editing Shortcuts

The next table lists mouse and keyboard actions that apply to annotations.
Action
Create annotation Copy annotation Move annotation Edit annotation
Shortuct
Double-click in diagram, then enter text Ctrl+C then Ctrl+V
Drag annotation
Click in text, then edit

Simulink Demos Are Now Called Examples

Starting in R2012b, Simulink models and videos that were previously called demos are
now called examples. There are two ways to access these examples from the Help
browser:
•At the top of the product landing page, click Examples.
•On any documentation page, click the Table of Contents button ,and then select
Examples.

You can filter documentation search results to display only examples.


Simulink® Demos Are Now Called Examples

For more information about changes to the Help browser, see the R2012b MATLAB
Release Notes.
Simulation Stepping
• “Simulation Stepping”
•“Step Through a Simulation”
•“Set Conditional Breakpoints for Stepping a Simulation”

Simulation Stepping

In this section…
“How Stepping Through a Simulation Works” “Simulation Stepper Interface”
“Simulation Stepper Limitations”

How Stepping Through a Simulation Works

The Simulation Stepper lets you step through the major time steps of a simulation. Access
the Simulation Stepper from the Simulink Editor toolbar or from the Simulation menu:

The stepping capabilities enable you to analyze your model in various ways. For example,
you can analyze plotted data at a particular moment in simulation time. (Stepping does not
modify the model or change the course of the simulation.) You can:
• Play a complete simulation of Simulink models
•Start and stop a simulation
•Step forward and back through a simulation
•Change from running to paused (Pause button) or step back (if backward stepping is
enabled).
•Set conditions to pause a simulation, before and during simulation.
•Add breakpoints at simulation time
You can use the stepping capabilities to perform actions such as analyze plotted data at a
particular moment in simulation time.
To step back through a model, the software stores simulation states, or snapshots. A
snapshot captures all the information required to continue a simulation from that point in
the simulation. A simulation snapshot contains simulation state (SimState) and
information related to logged data and visualization blocks. For more information on
snapshots, see “Simulation Snapshots”.
In conjunction with enabling the step back capability, you must also simulate the model or
step it forward to save snapshots for the step back capability.
Tip Snapshots for stepping back are available only during a single simulation.
TheSimulationStepperdoesnotsavethestepsfromonesimulationtothe next.
The Simulink software stores simulation state when it steps forward through a simulation.
Then, when you step back, the software uses the simulation snapshot, stored as SimState,
to display the previous state of the simulation. (The model does not simulate in reverse
when stepping back.)
How Simulation Stepper Differs from Simulink Debugger The Simulation Stepper and
the Simulink Debugger both enable you to start, stop, and step through a model
simulation. Both allow you to use breakpoints as part of a debugging session. However,
Simulation Stepper and Simulink Debugger are different in their intended use. Simulation
Stepper lets you seeallthedatabetweenmajorsteps.
Use Simulink Debugger for advanced debugging scenarios that involve custom blocks
(such as S-functions). The Simulink Debugger can help you analyze the issues with a
particular block method. Simulink Debugger also gives you finer control on breakpoints.
It also gives you finer control to step from one method to another block method within a
time step. For more information, see “Introduction to the Debugger”.
Action Simulation Stepper Simulink Debugger
Look at state of system

after executing a major


time step.
Observe dynamics of

the entire model from


step to step.
Step simulation back.

Pause across major


steps.
Control a Stateflow®

debugging session.
Step through

simulation by major
steps.
Monitor single block

dynamics (for example,


output and update)
during a single major
time step.
Look at state of system

while executing a major


time step.
Observe solver

dynamics during a
single major step.
Show various stages of

Simulink simulation.
Pause within a major

step.
Action Simulation Stepper Simulink Debugger
Step through a

simulation block by
block.
Access via a

command-line
interface.
To better understand the difference between Simulation Stepper and Simulink Debugger,
you need to understand the simulation process. (For an overview of model simulation
stages, see “Simulating Dynamic Systems”.)

Simulation Stepper Interface

Simulation Stepper Toolbar Buttons


Button

Action
Open the Simulation > Simulation Stepping Options dialog box to configure stepping
options, such as pausing after a specific simulation time and enabling stepping back. This
button is not available after you enable stepping back.
Step the simulation back to a previously captured simulation state. Clicking this button to
the final step of the simulation ends the simulation.
Stepping back is not available because there are no saved states to step back to.
Start/continue simulation.
Pause simulation.
Button

Action
Step the simulation forward.
Stop the simulation.
Simulation Stepping Options Dialog Box
Click the Stepping Options button
or Simulation > Stepping Options to open the Simulation Stepping Options dialog
box.

You use this dialog box to


enable stepping back through a simulation. When stepping back is enabled, after you start
the simulation, the button changes
to

, which you use to step back. For more information, see “Simulation Stepping Options”.
If you clear the Enable previous stepping check box, the software clears the stored
snapshot cache.
Simulation Stepper Pause Status
The status bar at the bottom of the Simulink Editor displays the simulation time of the last
completed simulation step. While a simulation is running, the editor updates the time
display to indicate the simulation progress. This display is approximate because the status
bar is not updated at every simulation time step. When you pause a simulation, the status
bar display time catches up to the actual time of the last completed step.

When you use Simulation Stepper to step through a simulation, the time on the status bar
updates at every major time step of the simulation. The value that is displayed (the time of
the last completed step) is not always the same as the time of the solver. This event occurs
because of the difference in the way that different solvers propagate the simulation time in
a single iteration of the simulation loop. Simulation Stepper pauses at a single position
within the simulation loop. However, some solvers perform their time advance before the
stepper pauses, and others perform their time advance after the stepper pauses, which then
becomes part of the next step. As a result, for continuous and discrete solvers, the solver
time is always one major step ahead of the time of the last model output.
When this condition occurs, and the simulation is paused, the status bar time displays an
asterisk. The asterisk indicates that the solver in this simulation has already advanced past
the displayed time (which is the time of the last completed simulation step).
Simulation Snapshots
When you set up simulation stepping, you specify:
• The maximum number of steps, or snapshots, to capture while simulating forward.
Thegreaterthenumber,themorememorythesimulation occupies and the longer the
simulation takes to run.
• The number of steps to skip between snapshots. This parameter enables you to save
snapshots of simulation state for stepping backward at periodic intervals, such as every
three steps forward. This interval is independent
ofthenumberofstepstakenineithertheforwardorbackwarddirection. Because taking
simulation snapshots affects simulation speed, saving snapshots less often can improve
simulation speed.
This figure shows how you can step through the simulation using the parameters in the
Simulation Stepping Options dialog box. Because you can change the stepping parameters
as you step through the simulation, you can step through a simulation as shown in this
figure: sometimes by single steps, sometimes by two or more steps.

This figure shows snapshot captures in which the interval for stored snapshots is three.

This example shows the flexibility of the stepper, which allows you to change the stepping
options while stepping forward. At the fourth step, the interval between stored back steps
changed the snapshot steps from 3 to 1. This capability is useful when you want to capture
more snapshots around a simulation time of interest.
This figure shows how the snapshots settings of the stepper can change what happens
when stepping back. Suppose that the interval between snapshots is set to 3, and starting at
state 6, the stepper Move back/forward by setting is set to 1. The stepper first restores the
simulation state to the last saved snapshot (state 3), and then simulates two major times
steps to arrive at the desired state (5). This capability is helpful for memory usage and
simulation performance.

Steppingto the final step ends the simulation. You cannot, then, step back after reaching
the end of simulation. You must restart the simulation to step backward.
Tune Parameters
While using the stepper, when the simulation is paused, you can change tunable
parameters, including some solver settings.
Although you can change tunable parameters when you have paused a simulation, changes
to the solver step size take effect when the solver advances the simulation time. For some
solvers, this occurs after the next simulation step is taken.
The Simulation Stepper takes into account the size of a movement ( Move back/forward
by) and the frequency of saving steps (Interval between stored back steps). If you
specify a frequency that is larger than the step size, the stepper first steps back to the last
saved step and then simulates forward until the total step count difference reaches the size
of the desired movement. Values for tunable parameters are applied when simulating
forward. For this reason, if you change any tunable parameter before stepping back, the
resulting simulation output might not match the previous simulation output at that step.
For example, if you double-click the Manual Switch block, you change its input direction
and thus affect simulation results.
For example, assume a snapshot save frequency of 3 and a step size of 1. The stepper first
steps back to the last saved step, up to three steps and then simulates forward until the
total step count difference reaches one. If you change tunable parameters before stepping
back, the resulting simulation output might not match the previous simulation output at
that step.
Referenced Models
When using the stepper and Model block, the referenced model shares the stepping
options of the top model throughout a simulation. As a result, changing the stepper
settings for the referenced model during simulation changes the stepper settings of the top
model. When the simulation ends, the stepper settings of the referenced model revert to
the original values; the stepper settings of the top model stay at the changed settings.
•When the model is not simulating, the top model and referenced model retain their own
independent stepping options.
•When the model is simulating and you change a referenced model stepping option, the
top model stepping option changes to the same value.
•When the model is simulating and you change a top model stepping option, the
referenced model stepping option changes to the same value.
• When the model stops simulating, the referenced model stepping options change back to
the settings before simulation started; the top model keeps the new values set during
simulation.
Simulation Stepper and Stateflow Debugger
When you debug a Stateflow chart (for example, when the simulation stops at a Stateflow
breakpoint), Simulation Stepper adds buttons to control the Stateflow debugging session.
When the Stateflow debugging session ends, the Simulation Stepper interface returns to
the default. For more information about controlling the Stateflow debugger using the
Simulink Editor toolbar, see “Control Chart Execution in the Debugger”.

Simulation Stepper Limitations


•Thereisnocommand-line interface for the Simulation Stepper.
•Simulation stepping (forward and backward) is available only for Normal and
Accelerator modes.
• The step back capability relies on SimState (“Save and Restore Simulation State as
SimState”) technology for saving and restoring the
state of a simulation. As a result, the step back capability is available only for models that
support SimState.
• Some blocks do not support stepping back for reasons other than SimState support.
Overall, this capability is not available in a model that uses any of these blocks:
- S-functions that have P-work vectors but do not declare their SimState compliance level
or declare it to be unknown or disallowed (see “S-Function Compliance with the
SimState”)
- SimMechanics™ First Generation blocks
- Model blocks configured for Accelerator mode
- SimEvents®blocks
• MATLAB Function blocks generally support stepping back. However, use of certain
constructs in the MATLAB code of this block can prevent the block from supporting
stepping back. These scenarios prevent the MATLABFunction blocks from being fully
supported or stepping back:
- Persistent variables of opaque data type. Attempts to step back under this condition cause
an error message based on the specific variable type.
- Extrinsic functions calls that can contain state (such as properties of objects or persistent
data of functions). No warnings or error messages appear, but the result likely will be
incorrect.
- Calls to custom C code (through MEX function calls) that do not contain static variables.
No warnings or error messages appear, but the result likely will be incorrect.
• Some visualization blocks do not support stepping back. Because these blocks are not
critical to the state of the simulation, no errors or warnings appear when you step back on
a model that contains these blocks:
- XY Graph
- Floating Scope
- Signal Viewer
- Auto Correlator
- Cross Correlator
- Spectrum Analyzer
- Averaging Spectrum Analyzer
- Power Spectral Density
- Averaging Power Spectral Density
- Floating Bar Plot
- 3Dof Animation
- MATLAB Animation
- VR Sink
- Any blocks that implement custom visualization in their output method (for example, an
S-function that outputs to a MATLAB figure) are not fully compliant with stepping back
because the block method Output does not execute while stepping back. While the state of
such blocks remains consistent with the simulation time (if the blocks comply with
SimState), the visualization component is inconsistent until the next step forward of the
simulation.
Because these blocks do not affect the numerical result of a simulation, stepping back is
not disabled for these blocks. (The values these blocks output are inaccurate until the
simulation steps forward again.)
• Simulation Stepper steps through the major time steps of a simulation without changing
the course of a simulation. Choosing a refine factor greater than unity produces loggable
outputs at times between the major time steps of the solver. These times are not major time
steps, and you cannot step to a model state at those times.
If you run a simulation with stepping back enabled, the Simulink software checks whether
the model can step back. If it cannot, a warning appears at the MATLAB command
prompt. In some cases, stepping back capability is not supported for that simulation. The
step back capability is then disabled until the end of that simulation (at which point the
setting resets to the originally requested value).

Step Through a Simulation


In this section…
“Configure Simulation Stepping” “Step Forward and Back”

Configure Simulation Stepping

To control aspects of the simulation stepping operations, such as to enable stepping back
or set how many simulation snapshots to capture, use the Simulation Stepping Options
dialog box. To open this dialog box:
•In the Simulation toolbar, click the Stepping Options button

.
•Select Simulation > Stepping Options. This method is useful when the toolbar icon is
unavailable.
For more information on simulation snapshots, see “Simulation Snapshots” .
For a description of the parameters, see “Simulation Stepping Options Dialog Box”.

Step Forward and Back


This example shows how to step forward and back through a simulation.
1In the MATLAB Command Window, type
vdp
A sample model and its scope appear in the Simulink Editor.
2In the Simulation toolbar, click

to open the Simulation Stepping options dialog box.


3In the dialog box, select the Enable previous stepping check box, and then click OK.
Step Through a Simulation
4In the Simulation toolbar, click
.
The simulation simulates one step, and the software stores a simulation snapshot for that
step.
5Click the Step Forward button again to step forward again and store simulation data.
When you view the results of the simulation, 25 clicks plots this data:
Note You must step forward before you can
step backward to create the simulation state that the step backward operation requires.
6In the Simulation toolbar, click

one or more times to step backward to the previously stepped simulation snapshot.
The scope updates to reflect the step back.

Set Conditional Breakpoints for Stepping a Simulation

Set conditional breakpoints to cause the stepper to stop when a specified condition is met.
One example of a good use for conditional breakpoints is when you want to examine
results after a certain number of iterations in a loop. The Simulation Stepper allows you to
set conditional breakpoints for scalar signals. A conditional breakpoint is a breakpoint that
is triggered based on a certain expression evaluated on a signal. When the breakpoint is
triggered, the corresponding simulation pauses. Breakpoints appear for signals as follows:
Icon Description

Enabled breakpoint. Appears when you add the conditional breakpoint.


Enabled breakpoint hit. Appears when the simulation reaches the condition specified for
the breakpoint and triggers the breakpoint.
Disabled breakpoint. Appears when you disable a conditional breakpoint (see “Add and
Edit Conditional Breakpoints” ).

Invalid breakpoint. Appears when the software determines that a breakpoint is invalid for
the signal. An enabled breakpoint icon changes to this icon when, during simulation, the
software determines that the conditional breakpoint is invalid.
Notes:
• When simulation arrives at a conditional breakpoint, simulation does not stop when the
block is executed. Instead, simulation stops after the current simulation step completes.
•You can add multiple conditional breakpoints to a signal line.
For more information on working with conditional breakpoints, see:
•“Add and Edit Conditional Breakpoints”
•“Observe Conditional Breakpoint Values”

Conditional Breakpoints Limitations

You can set conditional breakpoints on real scalar signals of only the following data types:
• double
•single
•int
•bool
Conditional breakpoints also have the same limitations as those for port value displays
(“Port Value Display Limitations”).

Add and Edit Conditional Breakpoints


This tutorial describes how to add conditional breakpoints to a model. For a description of
how to see the values of a signal for which you have set a conditional breakpoint, see
“Observe Conditional Breakpoint Values” .
1Right-click
the signal and select Add Conditional Breakpoint.
The Add Conditional Breakpoint dialog box appears.
2From the drop-down list, select the condition
for the signal, for example, greater than or less than:
3Enter the signal value where you want simulation to pause and click OK.
The affected signal line displays a conditional breakpoint icon, such as . 4Click the icon
to view and edit the conditions set for the signal.

Condition values:
•Must be numeric. They cannot be expressions.
•Cannot be NaN.
5Simulate the model and notice that the model pauses as simulation steps through the
conditional breakpoints.

Observe Conditional Breakpoint Values

To observe a conditional breakpoint value of a block signal, use data tips to display block
port values. You can add data tips before or after you add conditional breakpoints. This
tutorial describes how to enable a display a port value after you add a conditional
breakpoint. For a more detailed description of how to add conditional breakpoints, see
“Add and Edit Conditional Breakpoints”.
1Toenable the value display for the signal, right-click the signal line and select Show
Value Label of Selected Port.
Thedata tip for the value display is added.

2Simulate the model and observe the conditional breakpoint


and data tip when the simulation triggers the breakpoint.
How Simulink Works
• “How Simulink Works”
•“Modeling Dynamic Systems”
•“Simulating Dynamic Systems”
3How Simulink® Works

How Simulink Works

Simulink is a software package that enables you to model, simulate, and analyze systems
whose outputs change over time. Such systems are often referred to as dynamic systems.
The Simulink software can be used to explore the behavior of a wide range of real-world
dynamic systems, including electrical circuits, shock absorbers, braking systems, and
many other electrical, mechanical, and thermodynamic systems. This section explains how
Simulink works.
Simulating a dynamic system is a two-step process. First, a user creates a block diagram,
using the Simulink model editor, that graphically depicts time-dependent mathematical
relationships among the system’s inputs, states, and outputs. The user then commands the
Simulink software to simulate the system represented by the model from a specified start
time to a specified stop time.
For more information on this process, seeWKHERRNV:
•“Modeling Dynamic Systems”
•“Simulating Dynamic Systems”

Overview of Model Referencing

In this section…
“About Model Referencing” “Referenced Model Advantages” “Masking Model Blocks”
“Models That Use Model Referencing” “Model Referencing Resources”

About Model Referencing

You can include one model in another by using Model blocks. Each instance of a Model
block represents a reference to another model, called a referenced model or submodel. For
simulation and code generation, the referenced model effectively replaces the Model block
that references it. The model that contains a referenced model is its parent model. A
collection of parent and referenced models constitute a model reference hierarchy. A
parent model and all models subordinate to it comprise a branch of the reference
hierarchy.
The interface of a referenced model consists of its input and output ports (and control
ports, in the case of a conditional referenced model) and its parameter arguments. A Model
block displays inputs and outputs corresponding to the root-level inputs and outputs of the
model it references. These ports enable you to incorporate the referenced model into the
block diagram of the parent model.
For example, the sldemo_mdlref_basicmodel includes Model blocks that reference three
instances of the same referenced model, sldemo_mdlref_counter.

Use the ports on a Model block to connect the submodel to other elements of the parent
model. Connecting a signal to a Model block port has the same effect as connecting the
signal to the corresponding port in the submodel. For example, the Model block CounterA
has three inputs: two Constant blocks and a Pulse Generator block with a sample time of
.1. The Model block CounterB also has three inputs: the same two Constant blocks, and a
Pulse Generator block with a sample time of .5. Each Model block has an output to a
separate Scope block.
The referenced model includes Inport and Outport blocks (and possibly Trigger or Enable
blocks) to connect to the parent model. The sldemo_mdlref_countermodel has three Inport
blocks (upper, input, and lower) and one Outport block (output).
A referenced model can itself contain Model blocks and thus reference lower-level
models, to any depth. The top model is the topmost model in a hierarchy of referenced
models. Where only one level of model reference exists, the parent model and top model
are the same. To prevent cyclic inheritance, a Modelblock cannot refer directly or
indirectly to a model that is superior to it in the model reference hierarchy. This figure
shows cyclic inheritance.
Top modelA
Model AB
Referenced
models Model B

A parent model can contain multiple Model blocks that reference the same submodel as
long as the submodel does not define global data. The submodel can also appear in other
parent models at any level. You can parameterize a referenced model to provide tunability
for all instances of the model. Also, you can parameterize a referenced model to let
different Model blocks specify different values for variables that define the behavior of the
submodel.
By default, the Simulink software executes a top model interpretively, just as it would if
the model did not include submodels. Simulink can execute a referenced model
interpretively, as if it were an atomic subsystem, or by compiling the submodel to code
and executing the code.
.
You can use a referenced model as a standalone model, if it does not depend on data that is
available only from a higher-level model. An appropriately configured model can function
as both a standalone model and a referenced model, without changing the model or any
entities derived from it.

Referenced Model Advantages


Like subsystems, referenced models allow you to organize large models hierarchically;
Model blocks can represent major subsystems. Like libraries, referenced models allow you
to use the same capability repeatedly without having to redefine it. However, referenced
models provide several advantages that are unavailable with subsystems and/or library
blocks:
• Modular development
You can develop a referenced model independently from the models that use it.
• Model Protection
You can obscure the contents of a referenced model, allowing you to distribute it without
revealing the intellectual property that it embodies.
• Inclusion by reference
You can reference a model multiple times without having to make redundant copies, and
multiple models can reference the same model.
• Incremental loading
Simulink loads a referenced model at the point it needs to use the model, which speeds up
model loading.
• Accelerated simulation
Simulink can convert a referenced model to code and simulate the model by running the
code, which is faster than interactive simulation.
• Incremental code generation
Accelerated simulation requires code generation only if the model has changed since the
code was previously generated.
• Independent configuration sets
The configuration set used by a referenced model can differ from the configuration set of
its parent or other referenced models.
For additional information about how model referencing compares to other Simulink
componentization techniques

Masking Model Blocks

You can use the masking facility to create custom dialog boxes and icons for Model
blocks. Masked dialog boxes can make it easier to specify additional parameters for
Model blocks. For information about block masks, see “Masking”.

Models That Use Model Referencing


Simulink includes several models that illustrate model referencing.
The Introduction to Managing Data with Model Referenceexample introduces the basic
concepts and workflow related to managing data with model referencing. To explore these
topics in more detail, select the Detailed Workflow for Managing Data with Model
Referenceexample.
In addition, the sldemo_absbrakemodel represents a wheel speed calculation as a Model
block within the context of an anti-lock braking system (ABS).

Model Referencing Resources


The following are the most commonly needed resources for working with model
referencing:
• The Model block, which represents a model that another model references. See the
Model block parameters in “Ports & Subsystems Library Block Parameters” for
information about accessing a Model block programmatically.
• The Configuration Parameters > Diagnostics > Model Referencing pane, which
controls the diagnosis of problems encountered in model referencing. See “Diagnostics
Pane: Model Referencing” for details.
• The Configuration Parameters > Model Referencing pane, which provides options
that control model referencing and list files on which referenced models depend. See
“Model Referencing Pane” for details.

Create a Model Reference

A model becomes a submodel when a Model block in some other model references it. Any
model can function as a submodel, and such use does not preclude using it as a separate
model also.
For a video introducing how to create model references, see Getting Started with Model
Referencing.
To create a reference to a model (submodel) in another model (parent model):
1If the folder containing the submodel you want to reference is not on the MATLAB path,
add the folder to the MATLAB path.
2In the submodel:

• Enable Configuration Parameters > Optimization > Inline parameters. You must
enable Inline parameters for all models in a model reference hierarchy except the top
model in the hierarchy. See “Inline Parameter Requirements”.
•Set Configuration Parameters > Model Referencing > Total number of instances
allowed per top model to:
– One, if the hierarchy uses the model at most once
– Multiple, to use the model more than once per top model. To reduce overhead, specify
Multipleonly when necessary.
– Zero, which precludes referencing the model
3 Create an instance of the Model block in the parent model by dragging a Model block
instance from the Ports & Subsystems library to the parent model. The new block is
initially unresolved (specifies no submodel) and has the following appearance:

4Open the new Model block’s parameter dialog box by double-clicking the Model block.
See “Navigating a Model Block” for more about accessing Model block parameters.

5Enter the name of the submodel in the Model name field. This name must contain fewer
than 60 characters. (See “Name Length Requirement”)
6-10
•For information about Model Arguments and Model argument values, see “Using
Model Arguments”.
•For information about the Simulation mode, see “Referenced Model Simulation Modes”.
6Click OK or Apply.

If the referenced model contains any root-level inputs or outputs, Simulink displays
corresponding input and output ports on the Model block instance that you have created.
Use these ports to connect the referenced model to other ports in the parent model.
A signal that connects to a Model block is functionally the same signal outside and inside
the block. Therefore that signal is subject to the restriction that a given signal can have at
most one associated signal object. See Simulink.Signalfor more information. For
information about connecting a bus signal to a referenced model, see “Bus Usage
Requirements”.

Convert a Subsystem to a Referenced Model


Conversion Process

The process for converting a subsystem to a referenced model involves these tasks:
1“Select Subsystems to Convert”.
2“Prepare the Model for Conversion”.
3“Run a Conversion Tool”.
4“Connect the Model Block and Perform Other Post-Conversion Tasks” .

Select Subsystems to Convert

Model referencing offers several benefits for modeling large, complex systems and for
team-based development, as summarized in “Referenced Model Advantages”.
Subsystems or libraries are better suited for some modeling goals than model referencing.
Many large models involve using a combination of subsystems and referenced models.
For information to help you to decide which subsystems to convert to referenced models,
see “Componentization Guidelines”.
The types of subsystems that you can convert to a referenced model are:
• Atomic Subsystem
•“Triggered Subsystems”
•“Enabled Subsystems”
•“Triggered and Enabled Subsystems”
•“Function-Call Subsystems”
Note If you want to create a referenced model that accepts an asynchronous function call,
see “Asynchronous Support Limitations”.
If you convert a masked subsystem, you might need to perform some additional tasks to
maintain the same general behavior that the masked subsystem provided. For details, see
“Convert a Masked Subsystem” .

Prepare the Model for Conversion


Simulink provides a tool that you can use to convert a subsystem to a referenced model.
When the conversion tool identifies a change that you need to make to a model or
subsystem to support the conversion, the conversion processing stops. The conversion tool
reports conversion issues one at a time. To perform the conversion efficiently, before using
the conversion tool, consider modifying your model as described in the following steps.
When you run the conversion tool, it will flag any additional model modifications that you
may need to make.
1Save a backup copy of the model.

You can use the backup copy of the model to help you to configure the model after
performing the conversion. For example, if you convert a masked subsystem and want to
have a masked Model block, you might want to copy information from the masked
subsystem into the masked Model block.
Also, you can revert to the original version of the model if you decide not to convert the
subsystem after you have started to modify the model, or if the conversion processing is
unsuccessful.
2Use the Configuration Parameters dialog box to set the following model configuration
parameters.
a Select Optimization > Inline parameters.
b Set Diagnostics > Data Validity > Signal resolution to Explicit only.

c Set Diagnostics > Connectivity > Mux blocks used to create bus signals to Error. For
information about proper mux usage, see “Avoid Mux/Bus Mixtures”.
As an alternative for steps b and c, consider using the associated Model Advisor checks.
3Configure subsystem interfaces to the model.
Subsystem Interface
Goto or From blocks
What to Look For Model Modification
Crossing of subsystem boundaries.
Data stores Data Store Memory blocks
accessed by Data Store Read or Data Store Write blocks from outside of the subsystem.
Tunable
parameters Global tunable parameters listed in the dialog box that opens when you select
the Configuration Parameters > Optimization > Signals and Parameters > Configure
button.
Add input or output ports to the subsystem. Reconfigure the model as necessary to reflect
the added ports.
Replace the Data Store Memory block with a global data store. Define a global data store
with a Simulink.Signal object. For details, see “Data Stores with Signal Objects”.
Use tunablevars2parameterobjects to create a Simulink.Parameterobject for each tunable
parameter.
The Simulink.Parameterobjects must have a non-Auto storage class.
For more information, see “Parameterize Model References” and
“Tunable Parameters”.
4Configure the subsystem and its contents.
Subsystem
Configuration
Inactive
subsystem
variants
What to Look For Model Modification
Variant Subsystem blocks.
Make active the subsystem variant that you want to convert. The conversion tool does not
convert inactive subsystem variants.
To have the new Model block behave similar to the subsystem variant, convert each
variant subsystem separately.
For details, see “Set Up Variant Subsystems”
Function calls Function-call signals that cross virtual
subsystem boundaries.
Function-call outputs. Move the Function-Call Generator block inside of the subsystem
that you want to convert.
Change the function-call outputs to data triggers. Wide function-call ports. Eliminate wide
signals for
Sample times Sample time of an Inport block that does not match the sample time of the
block driving the Inport.
Inport blocks Merged Inport blocks.
Constant Constant blocks that blocks input to subsystems. function-call subsystems. Insert
Rate Transition blocks where appropriate.
Configure the model to avoid merged Inport blocks. See the Merge block documentation.
Consider moving the Constant blocks into the subsystem.
Subsystem What to Look For Configuration
Buses Bus signals that enter and exit a subsystem.
Duplicate signal names in buses.
Signal names that are not valid MATLAB identifiers. A valid identifier is a character
string of letters, digits, and underscores, such that the first character is a letter, and the
length of the string is less than or equal to the value returned by the namelengthmax
function.
Model Modification
Match signal names and bus element names for blocks inside of the subsystem.
Make signal names of the bus elements unique.
Change any invalid signal names to be valid MATLAB identifiers.
Run a Conversion Tool

Run a conversion tool, using one of these approaches:


•From the context menu of the subsystem, select Subsystem & Model Reference >
Convert Subsystem to > Referenced Model.
•Use the Simulink.SubSystem.convertToModelReferencecommand.
This function provides more capabilities than the Referenced Model menu option. For
example, with the function, you can replace a subsystem with an equivalent Model block
in a single operation.
Simulink saves the contents of the subsystem as a new model, then creates and opens an
untitled model that contains a Model block whose referenced model is the new model.
Model Name
Simulink automatically provides a model name that is based on the block name and is
unique in the MATLAB path. This name always contains fewer than 60 characters.
Error Handling
During the conversion, if an error occurs, the outcome depends on the kind of error.
•For some errors, a message box appears that gives you the choice of cancelling or
continuing.
Before you continue, note any changes that you want to make after the conversion. If you
cancel, then the conversion tool exits.
• If continuing is impossible, Simulink cancels the conversion without
offeringachoicetocontinue. IfthenewModelblockhas not been created, then the model is
not affected by the conversion tool processing.
What Gets Copied by the Conversion?
The conversion tool copies the following elements from the original model to the newly
created referenced model:
• Configuration sets – If the referencing model uses a configuration set that is not a
referenced configuration set, then the conversion tool copies that entire configuration set
to the referenced model.
If the referencing model uses a referenced configuration set, then both the referencing and
referenced models use the same referenced configuration set.
• Variables – All of the model workspace variables of the original model are copied into
the model workspace of the referenced model.
• Requirements links – Requirements links created with the Simulink Verification and
Validation software (for example, requirements links to blocks and signals) are copied.
Any requirements links on the subsystem that you convert are transferred to the new
Model block.

Connect the Model Block and Perform Other Post-Conversion Tasks

After you successfully complete the conversion:


1 Connect the referenced model.
a Delete the subsystem block from the source model.
b Copy the new Model block to the location of the deleted subsystem block.

Simulink automatically reconnects all signals. The source model is a parent model that
contains the referenced model.
2For root Inport blocks in the new referenced model, check the Interpolate data
parameter to make sure it is appropriate. For details, see the Inport block documentation.
3(Optional) Delete unused duplicate variables.
The conversion tool copies into the model workspace of the referenced model (for
example, ModelB) all of the model workspace variables of the referencing model
(ModelA). This step results in duplicate variables in the two model workspaces. To
improve the reliability of your model in case the model changes in the future, consider
removing unused variables or moving variables that are used by both ModelAand
ModelB:
• For a model workspace variable used only by the referencing model (ModelA), delete
the variable from the model workspace of the referenced model (ModelB).
• For a model workspace variable used only by the referenced model (ModelB), delete the
variable from the model workspace of the referencing model (ModelA).
•For model workspace variables used by both the referencing and referenced model,
consider moving that variable to the base workspace.
4 (Optional) To achieve similar results in the new referenced model as you did by using
the Variant Subsystem block, convert each of the variant subsystems to referenced models,
and then use a Model Variants block. For more information, see “Set Up Model Variants”.
If you convert a masked subsystem, you may need to perform some additional tasks to
maintain the same general behavior that the masked subsystem provided. For details, see
“Convert a Masked Subsystem”.

Convert a Masked Subsystem

Perform the tasks described in:


• “Select Subsystems to Convert”.
•“Prepare the Model for Conversion”.
•“Run a Conversion Tool”.
•“Connect the Model Block and Perform Other Post-Conversion Tasks” .
If the subsystem that you converted contains a mask, then you might want to mask the
Model block in your new referenced model (see “Masking”). Configure the referenced
model to support the functionality that was in the masked subsystem.
Note The referenced model does not support the functionality that you can achieve with
mask initialization code to create masked parameters.
Masked
Subsystem Functionality
Masked
parameters
Referenced Model Configuration
1In the model workspace of the referenced model, create a variable for each masked
parameter.
2In the Model Explorer, select the Model Workspace node. In the Dialog pane, in the
Model arguments parameter, enter the variables that you want to be model arguments.
Masked
Subsystem Functionality Referenced Model Configuration
Masked callbacks, icons, ports, and documentation 3In the new Model block, for the
Model arguments
parameter, specify the values for the model arguments.
In the backup copy of the masked subsystem, open the Mask Editor and select the content
to copy into to masked Model block.
In the Mask Editor for the new Model block, copy the appropriate content from the
masked subsystem that you converted.

Referenced Model Simulation Modes

In this section…
“Simulation Modes for Referenced Models”
“Specify the Simulation Mode”3
“Mixing Simulation Modes”
“Using Normal Mode for Multiple Instances of Referenced Models”
“Accelerating a Freestanding or Top Model”

Simulation Modes for Referenced Models

Simulink executes the top model in a model reference hierarchy just as it would if no
referenced models existed. All Simulink simulation modes are available to the top model.
Simulink can execute a referenced model in any of four modes: Normal, Accelerator,
Software-in-the-loop (SIL), or Processor-in-the-loop (PIL).
Normal Mode
Simulink executes a Normal mode submodel interpretively. Normal mode, compared to
other simulation modes:
•Requires no delay for code generation or compilation
•Works with more Simulink and Stateflow tools, supporting tools such as:
- Scopes, port value display, and other output viewing tools
•Scopes work with Accelerator mode referenced models, but require using the Signal &
Scope Manager and adding test points to signals. Adding or removing a test point
necessitates rebuilding the SIM target for a model, which can be time-consuming.
- Model coverage analysis
- Stateflow debugging and animation
•Provides more accurate linearization analysis
•Supports more S-functions than Accelerator mode does
Normal mode executes slower than Accelerator mode does.
Simulation results for a given model are nearly the same in either Normal or Accelerator
mode. Trivial differences can occur due to differences in the optimizations and libraries
that you use.
You can use Normal mode with multiple instances of a referenced model. For details, see
“Using Normal Mode for Multiple Instances of Referenced Models”.
Accelerator Mode
Simulink executes an Accelerator mode submodel by creating a MEX-file (or simulation
target) for the submodel, then running the MEX-file. See “Model Reference Simulation
Targets” f or more information. Accelerator mode:
•Takes time for code generation and code compilation
•Does not fully support some Simulink tools, such as Model Coverage and the Simulink
Debugger.
•Executes faster than Normal mode
Simulation results for a given model are nearly identical in either Normal or Accelerator
mode. Trivial differences can occur due to differences in the optimizations and libraries
that you use.
Software-in-the-Loop (SIL) Mode
Simulink executes a SIL-mode referenced model by generating production code using the
model reference target for the submodel. This code is compiled for, and executed on, the
host platform.
With SIL mode, you can:
•Verify generated source code without modifying the original model
•Reuse test harnesses for the original model with the generated source code
SIL mode provides a convenient alternative to PIL simulation when the target hardware is
not available.
This option requires Embedded Coder software.
For more information, see “Numerical Equivalence Testing” in the Embedded Coder
documentation.
Processor-in-the-Loop (PIL) Mode
Simulink executes a PIL-mode referenced model by generating production code using the
model reference target for the submodel. This code is cross-compiled for, and executed on,
a target processor or an equivalent instruction set simulator.
With PIL mode, you can:
•Verify deployment object code on target processors without modifying the original model
•Reuse test harnesses for the original model with the generated source code
This option requires Embedded Coder software.
For more information, see “Numerical Equivalence Testing” in the Embedded Coder
documentation.

Specify the Simulation Mode

The Model block for each instance of a referenced model controls its simulation mode. To
set or change the simulation mode for a submodel:
1Access the block parameter dialog box for the Model block. (See “Navigating a Model
Block”.)
2Set the Simulation mode parameter. 3Click OK or Apply.

Mixing Simulation Modes

The following table summarizes the relationship between the simulation mode of the
parent model and its submodels.
Parent Model Simulation Mode Normal
Accelerator
SIL
PIL
Submodel Simulation Modes
•Submodels can use Normal, Accelerator, SIL, or PIL mode.
• A submodel can execute in Normal mode only if every model that is superior to it in the
hierarchy also executes in Normal mode. A Normal mode path then extends from the top
model through the model reference hierarchy down to the Normal mode submodel.
•All subordinate models must also execute in Accelerator mode.
• When a Normal mode model is subordinate to an Accelerator mode model, Simulink
posts a warning and temporarily overrides the Normal mode specification.
• When a SIL-mode or PIL-mode model is subordinate to an Accelerator mode model, an
error occurs.
• All subordinate models also execute in SIL mode, provided their simulation modes are
Normal, Accelerator, or SIL. Otherwise, an error occurs. See “Simulation Mode Override
Behavior in Model Reference Hierarchy”.
•The SIL mode Model block uses the model reference targets of the blocks beneath.
• Multiple Model blocks, starting at the top of a model reference hierarchy, can execute at
a time in SIL mode. However, during code coverage or code execution profile, only one
Model block can execute at a time in SIL mode.
• All subordinate models also execute in PIL mode, provided their simulation modes are
Normal, Accelerator, or PIL. Otherwise, an
Parent Model Submodel Simulation Modes Simulation Mode
error occurs. See “Simulation Mode Override Behavior in Model Reference Hierarchy”.
•The PIL mode Model block uses the model reference targets of the blocks beneath.
• Only one Model block, starting at the top of a model reference hierarchy, can execute at
a time in PIL mode.
For more information about SIL and PIL modes, see in the Embedded Coder
documentation:
•“Code Interfaces for SIL and PIL”
•“SIL and PIL Simulation Support and Limitations”

Using Normal Mode for Multiple Instances of Referenced Models


You can simulate a model that has multiple references in Normal mode.
Normal Mode Visibility
All instances of a Normal mode referenced model are part of the simulation. However,
Simulink displays only one instance in a model window; that instance is determined by the
Normal Mode Visibility setting. Normal mode visibility includes the display of Scope
blocks and data port values.
If you do not set Normal Mode Visibility, Simulink picks one instance of each Normal
mode model to display.
After a simulation, if you try to open a referenced model from a Model block that has
Normal Mode Visibility set to off, Simulink displays a warning.
For a description of how to set up your model to control which instance of a referenced
model in Normal mode has visibility and to ensure proper simulation of the model, see
“Specify the Instance That Has Normal Mode Visibility”.
Note If you change the Normal Mode Visibility setting for a referenced model, you must
simulate the top model in the model reference hierarchy to make use of the new setting.
Examples of a Model with Multiple Referenced Instances in Normal Mode
sldemo_mdlref_basic. The sldemo_mdlref_basicmodel has three Model blocks
(CounterA, CounterB, and CounterC) that each reference the
sldemo_mdlref_countermodel.
If you update the diagram, the sldemo_mdlref_basicdisplays different icons for each of the
three Model blocks that reference sldemo_mdlref_counter.

Model Block
CounterA
Icon
Corners White
CounterB
CounterC
Gray
corners Black
corner
Simulation Mode and Normal Mode Visibility Setting
Normal mode, with Normal Mode Visibility enabled
Normal mode, with Normal Mode Visibility disabled
Accelerator mode (Normal Mode Visibility is not applicable)
If you do the following steps, then the ScopeAblock appears as shown below:
1Simulate sldemo_mdlref_basic.
2Open the sldemo_mdlref_countermodel. 3Open the ScopeAblock.

That ScopeAblock reflects the results of simulating the CounterAModel block, which has
Normal Mode Visibility enabled.
If you try to open mdlref_countermodel from the CounterBModel block (for example, by
double-clicking the Model block), ScopeA in mdlref_counter still showstheresultsofthe
CounterAModel block, because that is the Model block with Normal Mode Visibility set
to on.
sldemo_mdlref_depgraph. The sldemo_mdlref_depgraphmodel shows the use of the
Model Dependency Viewer for a model that has multiple Normal mode instances of a
referenced model. The model shows what you need to do to set up a model with multiple
referenced instances in Normal mode.
Set Up a Model with Multiple Instances of a Referenced Model in Normal Mode
This section describes how to set up a model to support the use of multiple instances of
Normal mode referenced models.
1Setthe Configuration Parameters > Model Referencing > Total number of instances
allowed per top model parameter to Multiple.
If you cannot use the Multiplesetting for your model, because of the requirements
described in the “Total number of instances allowed per top model” parameter
documentation, then you can have only one instance of that referenced model be in
Normal mode.
2For each instance of the referenced model that you want to be in Normal mode, in the
block parameters dialog box for the Model block, set the Simulation Mode parameter to
Normal. Ensure that all the ancestors in the hierarchy for that Model block are in Normal
mode.
The corners of icons for Model blocks that are in Normal mode can be white (empty), or
gray after you update the diagram or simulate the model.
3 (If necessary) Modify S-functions used by the model so that they work with multiple
instances of referenced models in Normal mode. For details, see “Supporting the Use of
Multiple Instances of Referenced Models That Are in Normal Mode”.
By default, Simulink assigns Normal mode visibility to one of the instances. After you
have performed the steps in this section, you can specify a non-default instance to have
Normal mode visibility. For details, see “Specify the Instance That Has Normal Mode
Visibility”.
Specify the Instance That Has Normal Mode Visibility This section describes how to
specify Normal Mode Visibility for an instance other than the one that an instance that
Simulink selects automatically.
You need to:
1 (Optionally) “Determine Which Instance Has Normal Mode Visibility” .
2“Set Normal Mode Visibility”.

3Simulate the top model to apply the new Normal Mode Visibility settings.
Determine Which Instance Has Normal Mode Visibility. If you do not already know
which instance currently has Normal mode visibility, you can determine that by using one
of these approaches:
• If you update the diagram and have made no other changes to the model, then you can
navigate through the model hierarchy to examine the Model blocks that reference the
model that you are interested in. The Model block that has white corners has Normal
Mode Visibility enabled.
•When you are editing a model or during compilation, use the
ModelReferenceNormalModeVisibilityBlockPathparameter. If you use this parameter
while editing a model, you must update the diagram before you use this parameter.
The result is a Simulink.BlockPathobject that is the block path for the Model block that
references the model that has Normal Mode Visibility enabled. For example:
get_param(‘sldemo_mdlref_basic’,…
‘ModelReferenceNormalModeVisibilityBlockPath’)
ans =
Simulink.BlockPath Package: Simulink
Block Path:
‘sldemo_mdlref_basic/CounterA’
• For a top model that is being simulated or that is in a compiled state, you can use the
CompiledModelBlockInstancesBlockPathparameter. For example:
a = get_param(‘sldemo_mdlref_depgraph’,… ‘CompiledModelBlockInstancesBlockPath’)
a= sldemo_mdlref_F2C: [1x1 Simulink.BlockPath] sldemo_mdlref_heater: [1x1
Simulink.BlockPath] sldemo_mdlref_outdoor_temp: [1x1 Simulink.BlockPath]
Set Normal Mode Visibility. To enable Normal Mode Visibility for a different instance of
the referenced model than the instance that currently has Normal Mode Visibility, use one
of these approaches:
•Navigate to the top model and select the Diagram > Subsystem & Model Reference >
Model Block Normal Mode Visibilitymenu item.
The Model Block Normal Mode Visibility dialog box appears. That dialog box includes
instructions in the right pane. For additional details about the dialog box, see “Model
Block Normal Mode Visibility Dialog Box” .
•From the MATLAB command line, set the
ModelReferenceNormalModeVisibilityparameter.
For input, you can specify:
- An array of Simulink.BlockPathobjects. For example:
bp1 = Simulink.BlockPath({‘mVisibility_top/Model’, … ‘mVisibility_mid_A/Model’});
bp2 = Simulink.BlockPath({‘mVisibility_top/Model1’, …
‘mVisibility_mid_B/Model1’});
bps = [bp1, bp2];
set_param(topMdl, ‘ModelBlockNormalModeVisibility’, bps);
- A cell array of cell arrays of strings, with the strings being paths to individual blocks and
models. The following example has the same effect as the preceding example (which
shows how to specify an array of Simulink.BlockPathobjects):
p1 = {‘mVisibility_top/Model’, ‘mVisibility_mid_A/Model’}; p2 =
{‘mVisibility_top/Model1’, ‘mVisibility_mid_B/Model1’}; set_param(topMdl,
‘ModelBlockNormalModeVisibility’, {p1, p2});
- An empty array, to specify the use of the Simulink default selection of the instance that
has Normal mode visibility. For example:
set_param(topMdl, ‘ModelBlockNormalModeVisibility’, []);
Using an empty array is equivalent to clearing all the check boxes in the Model Block
Normal Mode Visibility dialog box.
Note You cannot change Normal Mode Visibility during a simulation.
Model Block Normal Mode Visibility Dialog Box
If you have a model that has multiple instances of a referenced model in Normal mode,
you can use the Block Model Normal Mode Visibility dialog box to set Normal Mode
Visibility for a specific instance. For a description of Normal mode visibility, see “Normal
Mode Visibility”
Alternatively, you can set the ModelReferenceNormalModeVisibility parameter. For
information about how to specify an instance of a referenced model that is in Normal
mode that is different than the instance automatically selected by Simulink, see “Specify
the Instance That Has Normal Mode Visibility”.
Open the Model Block Normal Mode Visibility Dialog Box. To open the Model Block
Normal Mode Visibility dialog box, navigate to the top model and select Diagram >
Subsystem & Model Reference > Model Block Normal Mode Visibility.
The dialog box for the sldemo_mdlref_basicmodel, with the hierarchy pane expanded,
looks like this:

The model hierarchy pane shows a partial model hierarchy for the model from which you
opened the dialog box. The hierarchy stops at the first Model block that is not in Normal
mode. The model hierarchy pane does not display Model blocks that reference protected
models.
Select a Model for Normal Mode Visibility.
The dialog box shows the complete model block hierarchy for the top model. The Normal
mode instances of referenced models have check boxes. Select the
checkboxfortheinstanceofeachmodelthatyouwanttohaveNormal mode visibility.
When you select a model, Simulink:
•Selects all ancestors of that model
•Deselects all other instances of that model
When a model is deselected, Simulink deselects all children of that model.
Opening a Model from the Model Block Normal Mode Visibility Dialog Box. You can
open a model from the Model Block Normal Mode Visibilitydialogboxbyright-
clickingthemodelinthemodelhierarchypane and clicking Open.
Refreshing the Model Reference Hierarchy. To ensure the model hierarchy pane of the
Model Block Normal Mode Visibility dialog box reflects the current model hierarchy,
click Refresh.

Accelerating a Freestanding or Top Model

You can use Simulink Accelerator mode or Rapid Accelerator mode to achieve faster
execution of any Simulink model, including a top model in a model reference hierarchy.
For details about Accelerator mode, see the “Acceleration” documentation. For
information about Rapid Accelerator mode, see “Rapid Simulations”.
When you execute a top model in Simulink Accelerator mode or Rapid Accelerator mode,
all submodels execute in Accelerator mode. For any submodel that specifies Normal
mode, Simulink displays an warning message.
Be careful not confuse Accelerator mode execution of a referenced model with:
•Accelerator mode execution of a freestanding or top model, as described in
“Acceleration”
•Rapid Accelerator mode execution of a freestanding or top model, as described in “Rapid
Simulations”
While the different types of acceleration share many capabilities and techniques, they have
different implementations, requirements, and limitations.
View a Model Reference Hierarchy
View a Model Reference Hierarchy

Simulink provides tools and functions that you can use to examine a model reference
hierarchy:
• Model Dependency Viewer — Shows the structure the hierarchy lets you open
constituent models. The Referenced Model Instances view displays Model blocks
differently to indicate Normal, Accelerator, and PIL modes. See “Model Dependency
Viewer”.
• view_mdlrefs function — Invokes the Model Dependency Viewer to display a graph of
model reference dependencies.
• find_mdlrefs function — Finds all models directly or indirectly referenced by a given
model.

Display Version Numbers

To display the version numbers of the models referenced by a model, for the parent model,
choose Display > Blocks > Block Version for Referenced Models. Simulink displays the
version numbers in the icons of the corresponding Model block instances.

The version number displayed on a Model block icon refers to the version of the model
used to either:
• Create the block
•Refresh the block most recently changed
See “Manage Model Versions” andRefresh0odeO Blocks” .

Model Reference Simulation Targets

In this section…
“Simulation Targets”
“Build Simulation Targets”
“Simulation Target Output File Control”
“Parallel Building for Large Model Reference Hierarchies”

Simulation Targets

A simulation target,or SIM target, is a MEX-file that implements a referenced model that
executes in Accelerator mode. Simulink invokes the simulation target as needed during
simulation to compute the behavior and outputs of the referenced model. Simulink uses
the same simulation target for all Accelerator mode instances of a given referenced model
anywhere in a reference hierarchy.
If you have a Simulink Coder license, be careful not to confuse the simulation target of a
submodel with any of these other types of target:
•Hardware target — A platform for which Simulink Coder generates code
•System target — A file that tells Simulink Coder how to generate code for particular
purpose
•Rapid Simulation target (RSim) — A system target file supplied with Simulink Coder
•Model reference target — A library module that contains Simulink Coder code for a
referenced model
Simulink creates a simulation target only for a submodel that has one or more Accelerator
mode instances in a reference hierarchy. A submodel that executes only in Normal mode
always executes interpretively and does not use a simulation target. When one or more
instance of a submodel executes in Normal mode, and one or more instance executes in
Accelerator mode:
•Simulink creates a simulation target for the Accelerator mode instances.
•The Normal mode instances do not use that simulation target.
Because Accelerator mode requires code generation, it imposes some requirements and
limitations that do not apply to Normal mode. Aside from these constraints, you can
generally ignore simulation targets and their details when you execute a referenced model
in Accelerator mode. See “Limitations on Accelerator Mode Referenced Models”.

Build Simulation Targets

Simulink by default generates the needed target from the referenced model:
•If a simulation target does not exist at the beginning of a simulation
•When you perform an update diagram for a parent model
If the simulation target already exists, then by default Simulink checks whether the
submodel has structural changes since the target was last generated. If so, Simulink
regenerates the target to reflect changes in the model. For details about how Simulink
detects whether to rebuild a model reference target, see the “Rebuild” parameter
documentation.
You can change this default behavior to modify the rebuild criteria or specify that
Simulink always or never rebuilds targets. See “Rebuild” for details.
To generate simulation targets interactively for Accelerator mode referenced
models,dooneofthesesteps:
•Update the diagram on a model that directly or indirectly references the model that is in
Accelerator mode
•Execute the slbuildcommand with appropriate arguments at the MATLAB command line
While generating a simulation target, Simulink displays status messages at the MATLAB
command line to enable you to monitor the target generation process. Target generation
entails generating and compiling code and linking the compiled target code with compiled
code from standard code libraries to create an executable file.
Reduce Change Checking Time
You can reduce the time that Simulink spends checking whether any or all simulation
targets require rebuilding by setting configuration parameter values as follows:
• In all referenced models throughout the hierarchy, set Configuration Parameters >
Diagnostics > Data Validity > Signal resolution to Explicit only. (See “Signal
resolution”.)
• To minimize change detection time, consider setting Configuration Parameters >
Model Referencing > Rebuild options to If any changes in known dependencies
detectedon the top model. See “Rebuild”.
These parameter values exist in the configuration set of a referenced model, not in the
individual Model block, so setting either value for any instance of a referenced model sets
it for all instances of that model.

Simulation Target Output File Control

Simulink creates simulation targets in the slprjsubfolder of the working folder. If slprjdoes
not exist, Simulink creates it.
Note Simulink Coder code generation also uses the slprjfolder. Subdirectories in
slprjprovide separate places for simulation code, Simulink Coder code, and other files. For
details, see “Control the Location for Generated Files”.
By default, the files generated by Simulink diagram updates and model builds are placed
in a build folder, the root of which is the current working folder (pwd). However, in some
situations, you might want the generated files to go to a root folder outside the current
working folder. For example:
•You need to keep generated files separate from the models and other source materials
used to generate them.
• You want to reuse or share previously-built simulation targets without having to set the
current working folder back to a previous working folder. You might also want to separate
generated simulation artifacts from generated production code.
To allow you to control the output locations for the files generated by diagram updates and
model builds, the software allows you to separately specify the simulation cache folder
build folder. The simulation cache folder is the root folder in which to place artifacts used
for simulation.
To specify the simulation cache folder, use one of these approaches:
•Use the CacheFolderMATLAB session parameter.
• Open the Simulink Preferences dialog box (File > Simulink Preferences) and specify a
location on your file system for the Simulation cache
folder,which,ifspecified,providestheinitialdefaultsfortheMATLAB session parameters.
Control Output Location for Model Build Artifacts Used for Simulation
The Simulink preference Simulation cache folder provides control over the output
location for files generated by Simulink diagram updates. The preference appears in the
Simulink Preferences Window, Main Pane, in the File generation control group. To
specify the root folder location for files generated by Simulink diagram updates, set the
preference value by entering or browsing to a folder path, for example:

The folder path that you specify provides the initial default for the MATLAB session
parameter CacheFolder. When you initiate a Simulink diagram update, any files generated
are placed in a build folder at the root location specified by CacheFolder(if any), rather
than in the current working folder (pwd).
For example, using a 32-bit Windows host platform, if you set the Simulation cache
folder to ‘C:\Work\mymodelsimcache’and then simulate the model rtwdemo_capi, files
are generated into the specified folder as follows:

As an alternative to using the Simulink preferences GUI to set Simulation cache folder,
you also can get and set the preference value from the command line using get_paramand
set_param. For example,
>> get_param(0, ‘CacheFolder’)
ans =

>> set_param(0, ‘CacheFolder’, fullfile(‘C:’,‘Work’,‘mymodelsimcache’)) >> get_param(0, ‘CacheFolder’)
ans =
C:\Work\mymodelsimcache
Also, you can choose to override the Simulation cache folder preference value for the
current MATLAB session.
Override Build Folder Settings for the Current MATLAB Session The Simulink
preferences Simulation cache folder and Code generation folder provide the initial
defaults for the MATLAB session parameters CacheFolderand CodeGenFolder, which
determine where files generated by Simulink diagram updates and model builds are
placed. However, you can override these build folder settings during the current MATLAB
session, using the Simulink.fileGenControlfunction. This function allows you to directly
manipulate the MATLAB session parameters, for example, overriding or restoring the
initial default values. The values you set using Simulink.fileGenControlexpire at the end
of the current MATLAB session. For more information and detailed examples, see the
Simulink.fileGenControlfunction reference page.

Parallel Building for Large Model Reference Hierarchies


In a parallel computing environment, you can increase the speed of diagram updates for
models containing large model reference hierarchies by building referenced models that
are configured in Accelerator mode in parallel whenever conditions allow. For example, if
you have Parallel Computing Toolbox™ software, updating of each referenced model can
be distributed across the cores of a multicore host computer. If you additionally have
MATLAB Distributed Computing Server™ (MDCS) software, updating of each
referenced model can be distributed across remote workers in your MATLAB Distributed
Computing Server configuration.
To take advantage of parallel building for a model reference hierarchy:
1Set up a pool of local and/or remote MATLAB workers in your parallel computing
environment.
a Make sure that Parallel Computing Toolbox software is licensed and installed.
b To use remote workers, make sure that MATLAB Distributed Computing Server
software is licensed and installed.
c Issue appropriate MATLAB commands to set up the worker pool, for example,
matlabpool 4.
2 In the Configuration Parameters dialog box, go to the Model Referencing pane and
select the Enable parallel model reference builds option. This selection enables the
parameter MATLAB worker initialization for builds.

3
4
For MATLAB worker initialization for builds, select one of the following values:
• Noneif the software should perform no special worker initialization. Specify this value if
the child models in the model reference hierarchy do not rely on anything in the base
workspace beyond what they explicitly setup(forexample,withamodelloadfunction).
• Copy base workspaceif the software should attempt to copy the base workspace to each
worker. Specify this value if you use a setup script to prepare the base workspace for all
models to use.
• Load top modelif the software should load the top model on each worker. Specify this
value if the top model in the model reference hierarchy handles all of the base workspace
setup (for example, with a model load function).
Optionally, inspect the model reference hierarchy to determine, based on model
dependencies, which models will be built in parallel. For example, you can use the Model
Dependency Viewer from the Simulink Tools menu.
Update your model. Messages in the MATLAB command window record when each
parallel or serial build starts and finishes.
The performance gain realized by using parallel builds for updating referenced models
depends on several factors, including how many models can be built in parallel for a given
model referencing hierarchy, the size of the referenced models, and parallel computing
resources such as number of local and/or remote workers available and the hardware
attributes of the local and remote machines (amount of RAM, number of cores, and so on).
The following notes apply to using parallel builds for updating model reference
hierarchies:
• For local pools, the host machine should have an appropriate amount of RAM available
for supporting the number of local workers (MATLAB sessions) that you plan to use. For
example, setting matlabpoolto 4 results in five MATLAB sessions on your machine, each
using approximately 120 MB of memory at startup.
• Remote MDCS workers participating in a parallel build must use a common platform
and compiler.
•A consistent MATLAB environment must be set up in each MATLAB worker session as
in the MATLAB client session — for example, all shared base workspace variables,
MATLAB path settings, and so forth. Oneapproachistousethe PreLoadFcncallback of the
top model. If you configure your model to load the top model with each MATLAB worker
session, its preload function can be used for any MATLAB worker session setup.

Simulink Model Referencing Requirements

In this section…
“About Model Referencing Requirements” “Name Length Requirement”
“Configuration Parameter Requirements” “Model Structure Requirements”

About Model Referencing Requirements


A model reference hierarchy must satisfy various Simulink requirements, as described in
this section. Some limitations also apply, as described in “Model Referencing
Limitations”.

Name Length Requirement

The name of a referenced model must contain fewer than 60 characters, exclusive of the
.slxor .mdlsuffix. An error occurs if the name of a referenced model is too long.

Configuration Parameter Requirements

A referenced model uses a configuration set in the same way that any other model does, as
described in “Manage a Configuration Set”. By
default, every model in a hierarchy has its own configuration set. Each model uses its
configuration set the same way that it would if the model executed independently.
Because each model can have its own configuration set, configuration parameter values
can be different in different models. Furthermore, some parameter values are intrinsically
incompatible with model referencing. The Simulink response to an inconsistent or
unusable configuration parameter depends on the parameter:
• Where an inconsistency has no significance, or a trivial resolution exists that carries no
risk, Simulink ignores or resolves the inconsistency without posting a warning.
•Where a nontrivial and possibly acceptable solution exists, Simulink resolves the conflict
silently, resolves it with a warning, or generates an error. See “Model configuration
mismatch” for details.
•Where no acceptable resolution is possible, Simulink generates an error. Change some or
all parameter values to eliminate the problem.
Manually eliminating all configuration parameter incompatibilities can be tedious when:
•A model reference hierarchy contains many submodels that have incompatible parameter
values
•A changed parameter value must propagate to many submodels
You can control or eliminate such overhead by using configuration references to assign an
externally stored configuration set to multiple models. See “Manage a Configuration
Reference” for details.
Note Configuration parameters on the Code Generation pane of the Configuration
Parameters dialog box do not affect simulation in either Normal or Accelerated mode.
Code Generation parameters affect only code generation by Simulink Coder itself.
Accelerated mode simulation requires code generation to create a simulation target.
Simulink uses default values for all Code Generation parameters when generating the
target, and restores the original parameter values after code generation is complete.
The tables in the following sections list Configuration parameter options that can cause
problems if set:
•In certain ways, as indicated in the table
•Differently in a referenced model than in a parent model
Where possible, Simulink resolves violations of these requirements automatically, but
most cases require changes to the parameters in some or all models.
Configuration Requirements for All Referenced Model Simulation
Dialog Box Pane Solver
Option
Start time
Stop time
Type
Solver Requirement
The start time of the top model and all
referenced models must be the same, but need not be zero.
Simulink uses Stop time of the top
model for simulation, overriding any differing Stop time in a
submodel.
The Type and Solver of the top model
apply throughout the hierarchy. See “Solver Requirements”
Data Import/Export Initial state
Optimization Inline parameters
Application lifespan (days)
Can be onfor the top model, but must be off for a referenced model.
Can be onor off
for a top model, but must be onfor a
referenced model.
See “Inline Parameter Requirements”
Must be the same for top and referenced models.
Dialog Box Pane Model Referencing Option
Total number of instances allowed per top model
Requirement
Must not be Zeroin a referenced model. Specifying Onerather than Multipleis preferable
or required in some cases. See “Model Instance
Requirements”
Hardware
Implementation Embedded hardware options
All values must be the same for top and referenced models.
Solver Requirements. Model referencing works with both fixed-step and variable-step
solvers. All models in a model reference hierarchy use the same solver, which is always
the solver specified by the top model. An error occurs
ifthesolvertypespecifiedbythetopmodelisincompatiblewiththesolver type specified by any
submodel.
Top Model Solver Type
Fixed Step
Variable Step
Variable Step
Submodel Solver Type
Fixed Step
Variable Step
Fixed-step
Fixed Step Variable Step
Compatibility
Allowed
Allowed
Allowed unless the submodel is multi-rate and specifies both a discrete sample
time and a continuous sample time
Error
If an incompatibility exists between the top model solver and any submodel solver, one or
both models must change to use compatible solvers. For information about solvers, see
“Solvers” and “Choose a Solver” .
Inline Parameter Requirements. Simulink requires enabling Configuration Parameters
> Optimization > Inline parameters (see “Inline parameters”) for all referenced models
in a reference hierarchy. The top model can enable or disable inline parameters. If a
referenced model disables inline parameters, and you try to simulate the parent model:
• For a Normal mode submodel, Simulink generates an error and cancels the build. All
models and compiled files remain unchanged after the failed build.
• For an Accelerator mode submodel, Simulink temporarily enables inline parameters,
posts no warning, and builds the model. Inline parameters remain disabled after the build
completes.
Simulink ignores tunable parameter specifications in the Model Parameter Configuration
dialog box for both the top model and referenced models. Do not use this dialog box to
override the inline parameters optimization for selected parameters to permit them to be
tuned. Instead, see “Parameterize Model References”.
Model Instance Requirements. A referenced model must specify that it is available to be
referenced, and whether it can be referenced at most once or can have multiple instances.
The Configuration Parameters > Model Referencing > Total number of instances
allowed per top model parameter provides this specification. See “Total number of
instances allowed per top model” for more information. The possible values for this
parameter are:
• Zero— A model cannot reference this model. An error occurs if a reference to the model
occurs in another model.
• One— A model reference hierarchy can reference the model at most once. An error
occurs if more than one instance of the model exists. This value is sometimes preferable or
required.
• Multiple— A model hierarchy can reference the model more than once, if it contains no
constructs that preclude multiple reference. An error occurs if the model cannot be
multiply referenced, even if only one reference exists.
Setting Total number of instances allowed per top model to Multiple for a model that is
referenced only once can reduce execution efficiency slightly. However, this setting does
not affect data values that result from simulation or from executing code Simulink Coder
generates. Specifying Multiplewhen only one model instance exists avoids having to
change or rebuild the model when reusing the model:
•In the same hierarchy
•Multiple times in a different hierarchy
Some model properties and constructs require setting Total number of instances allowed
per top model to One. For details, see “General Reusability Limitations” and
“Accelerator Mode Reusability Limitations”.

Model Structure Requirements


The following requirements relate to the structure of a model reference hierarchy.
Signal Propagation Requirements
The signal name must explicitly appear on any signal line connected to an Outport block
of a referenced model. A signal connected to an unlabeled line of an Outport block of a
referenced model cannot propagate out of the Model block to the parent model.
Bus Usage Requirements
A bus that propagates between a parent model and a referenced model must be nonvirtual.
Use the same bus object to specify the properties of the bus in both the parent and the
referenced model. Define the bus object in the MATLAB workspace. See “About
Composite Signals”.
Sample Time Requirements
The first nonvirtual block connected to a root-level Inport or Outport block of a referenced
model must have the same sample time as the port to which it connects. Use Rate
Transition blocks to match input and output sample times, as illustrated in the following
diagram.

Parameterize Model References


In this section…
“Introduction”
“Global Nontunable Parameters” “Global Tunable Parameters” “Using Model Arguments”

Introduction
A parameterized referenced model obtains values that affect the behavior of the referenced
model from some source outside the model. Changing the values changes the behavior of
the model, without recompiling the model.
Due to the constraints described in “Inline Parameter Requirements” , you cannot use the
Model Parameter Configuration dialog box to parameterize referenced models. Simulink
provides three other techniques that you can use to parameterize referenced models:
• Global nontunable parameters
•Global tunable parameters
•Model arguments
Global parameters work the same way with referenced models that they do with any other
model construct. Each global parameter has the same value in every instance of a
referenced model that uses it. Model arguments allow you to provide different values to
each instance of a referenced model. Each instance can then behave differently from the
others. The effect is analogous to calling a function more than once with different
arguments in each call.
You can use a structure parameter to group variables for parameterizing model references.
For details, see “Structure Parameters”.

Global Nontunable Parameters

A global nontunable parameter is a MATLAB variable or a


Simulink.Parameterobject whose storage class is auto. The parameter must exist in the
MATLAB workspace.
Using a globalnontunable parameter in a referenced model sets the parameter value before
the simulation begins. This allows you to control the behavior of the referenced model. All
instances of the model use the same value. You cannot change the value during simulation,
but you can change it between one simulation and the next. The change requires
rebuilding the model in which the change occurs, but not any models that it references.
See “Specify Parameter Values” for details.

Global Tunable Parameters

A global tunable parameter is a Simulink.Parameterobject whose storage classisother than


auto. The parameter exists in the MATLAB workspace.
Using a global tunable parameter in a referenced model allows you to control the behavior
of the referenced model by setting the parameter value. All instances of the model use the
same value. You can change the value during simulation or between one simulation and
the next. The change does not requirerebuilding the model in which the change occurs, or
any models that it references. See “Tunable Parameters” for details.
To reference a model that uses tunable parameters defined with the “Model Parameter
Configuration Dialog Box”, change the model to implement tunability another way. To
facilitate this task, Simulink provides a command that converts tunable parameters
specified in the Model Parameter Configuration dialog box to global tunable parameters.
See tunablevars2parameterobjectsfor details.

Using Model Arguments

Model arguments let you parameterize references to the same model so that each instance
of the model behaves differently. Without model arguments, a variable in a referenced
model has the same value in every instance of the model. Declaring a variable to be a
model argument allows each instance of the model to use a different value for that
variable.
To create model arguments for a referenced model:
1Create MATLAB variables in the model workspace.
2Add the variables to a list of model arguments associated with the model.
3Specify values for those variables separately in each Model block that references the
model
The values specified in the Model block replace the values of the MATLAB variables for
that instance of the model.
A referenced model that uses model arguments can also appear as a top model or a
standalone model. No Model block exists to provide model argument values. The model
uses the values of the MATLAB variables as defined in the model workspace. You can use
the same model, without changing it, as a top model, a standalone model, and a
parameterized referenced model.
The sldemo_mdlref_datamngtmodel demonstrates techniques for using model arguments.
The model passes model argument values to referenced models through masked Model
blocks. Such masking can be convenient, but is independent of the definition and use of
model arguments themselves. See “Masking” for information about masking.
The rest of this section describes techniques for declaring and using model arguments to
parameterize a referenced model independently of any Model block masking. The steps
are:
• Create MATLAB variables in the model workspace.
•Register the variables to be model arguments.
•Assign values to those arguments in Model blocks.
Creating the MATLAB Variables
To create MATLAB variables for use as model arguments: 1Open the model for which you
want to define model arguments.
2Open the Model Explorer. 3In the Model Explorer Model Hierarchy pane, select the
workspace of the model:

4From ModelExplorer’s Add menu, select MATLAB Variable.


A new MATLAB variable appears in the Contents pane with a default name and value.
5In the Contents pane:
a Change the default name of the new MATLAB variable to a name that you want to
declare as a model argument.
b If you also use the model as a top or standalone model, specify the value for that variable
for use in that context. This value must be numeric.
cIfthevariabletypedoesnotmatchthedimensionsandcomplexityof the model argument,
specify a value that has the correct type. This type must be numeric.
6Repeat adding and naming MATLAB variables until you have defined all the variables
that you need.
Register the Model Arguments
To register MATLAB variables as model arguments:
1Again, in the Model Explorer Model Hierarchy pane, select the workspace ofthe model.
The Dialog pane displays the Model Workspace dialog.
2 In the Model Workspace dialog, enter the names of the MATLAB variables that you
want to declare as model arguments. Use a comma-separated list in the Model arguments
field.
For example, suppose you added two MATLAB variables named init_valueand incr, and
you declared them to be model arguments. The Contents and Dialog panes of the Model
Explorer could look like this:

3Click Apply to confirm the entered names.


Assign Model Argument Values
If a model declares model arguments, assign values to those arguments in each Model
block that references the model. Failing to assign a value to a model argument causes an
error: the value of the model argument does not default to the value of the corresponding
MATLAB variable. That value is available only to a standalone or top model. To assign
values to the arguments of a referenced model:
1Open the block parameters dialog box of the Model block by right-clicking the block and
choosing Block Parameters (ModelReference) from the context menu.
Thesecond field, Model arguments, specifies the same MATLAB variables, in the same
order, that you previously typed into the Model arguments field of the Model Workspace
dialog. This field is not editable. It provides a reminder of which model arguments need
values assigned, and in what order.
2 In the Model argument values field, enter a comma-delimited list of values for the
model arguments that appear in the Model arguments field. Simulink assigns the values
to arguments in positional order, so they must appear in the same order as the
corresponding arguments.
You can enter the values as literal values, variable names, MATLAB expressions, and
Simulink parameter objects. Any symbols used resolve to values as described in “Symbol
Resolution Process”. All values must be numeric (including objects with numeric values).
Note Simulink generates an error if you use a model argument in an expression that is
nontunable because of “Tunable Expression Limitations”.
The value for each argument must have the same dimensions and complexity as the
MATLAB variable that defines the model argument in the model workspace. The data
types need not match. If necessary, the Simulink software casts a model argument value to
the data type of the corresponding variable.
3Click OK or Apply to confirm the values for the Model block.
When the model executes in the context of that Model block, the Model arguments have
the values specified in the Model argument values field of the Model block.

Conditional Referenced Models

In this section…
“Kinds of Conditional Referenced Models” “Working with Conditional Referenced
Models” “Create Conditional Models”
“Reference Conditional Models”
“Simulate Conditional Models”
“Generate Code for Conditional Models” “Requirements for Conditional Models”

Kinds of Conditional Referenced Models

You can set up referenced models so that they execute conditionally, similar to conditional
subsystems. For information about conditional subsystems, see “About Conditional
Subsystems”.
You can use the following kinds of conditionally executed referenced models:
• Enabled
•Triggered
•Enabled and triggered
•Function-call
Enabled Models
Use an Enable block to insert an enable port in a model. Add an enable port to a model if
you want a referenced model to execute at each simulation step for which the control
signal has a positive value.
To see an example of an enabled subsystem,see enablesub. A corresponding enabled
referenced model would use the same blocks as are in the enabled subsystem.
Triggered Models
Use a Trigger block to insert a trigger port in a model. Add a trigger port to a model if you
want to use an external signal to trigger the execution of that model. You can add a trigger
port to a root-level model or to a subsystem.
This section focuses on models that contain a trigger port with an edge-based trigger type
(rising, falling,or either).
To view a model that illustrates how you can use trigger ports in referenced models, see
the Introduction to Managing Data with Model Reference example. In that example, see
the “Top Model: Scheduling Calls to the Referenced Model” section.
Triggered and Enabled Models
A triggered and enabled model executes once at the time step for which a trigger event
occurs, if the enable control signal has a positive value at that step.
Function-Call Models
Simulink allows certain blocks to control execution of a referenced model during a time
step, using a function-call signal. Examples of such blocks are a Function-Call Generator
or an appropriately configured custom S-function. See “Function-Call Subsystems” fo r
more information. A referenced model that you can invoke in this way is a function-call
model.
For an example of a function-call model, see the sldemo_mdlref_fcncall model.

Working with Conditional Referenced Models

Use a similar approach for each kind of conditionally executed referenced model for these
tasks:
• “Create Conditional Models”
•“Reference Conditional Models”
•“Simulate Conditional Models”
•“Generate Code for Conditional Models”
Each kind of conditionally executed model has some model creating requirements. For
details, see “Requirements for Conditional Models” .

Create Conditional Models


To create a conditional model:
1At the root level of the referenced model, insert one of the following blocks:

Kind of Model
Enabled
Triggered
Triggered and Enabled Function-Call
Blocks to Insert Enable
Trigger
Trigger and Enable Trigger
For an enabled model, go to Step 3.
2For the Trigger block, set the Trigger type parameter, based on the kind of model:

Kind of Model
Triggered
Triggered and enabled
Function-Call
Trigger Type Parameter Setting One of the following:
• rising
• falling
• either
function-call
3Create and connect other blocks to implement the model.
Enabled model example:
Triggered model example:

Function-call model example:

4Ensure that the model satisfies the requirements for a conditional model.
See the appropriate section:
•“Enabled Model Requirements”
•“Triggered Model Requirements”
•“Function-Call Model Requirements”

Reference Conditional Models

To create a reference to a conditional model:


1Add a Model block to the model that you want to reference the triggered model. See
“Create a Model Reference”.
The top of the Model block displays an icon that corresponds to the kind of port used in
the referenced model. For example, for a triggered model, the top of the Model block
displays the following icon.

Forenabled, triggered, and triggered and enabled models, go to Step 3.


2 For a function-call model, connect a Stateflow chart, Function-Call Generator block, or
other function-call-generating block to the function-call port of the Model block. The
signal connected to the port must be scalar. 3Create and connect other blocks to implement
the parent model.
4Ensure that the referencing model satisfies the conditions for model referencing. See
“Simulink Model Referencing Requirements” and “Model Referencing Limitations”

Simulate Conditional Models


Use Normal, Accelerator, or Rapid Accelerator mode to simulate a conditional model.
You can run a standalone simulation of a referenced model. A standalone simulation is
useful for unit testing, because it provides consistent data across simulations, in terms of
data type, dimension, and sample time. In the Trigger or Enable block, in the Signal
Attributes pane of the Block Parameters dialog box, specify values to lock down the
signal data type, dimension, and sample time.
To run a standalone simulation of a conditional model, specify the inputs using the
Configuration Parameters > Data Import/Export > Input parameter. The following
conditions apply when you use the “Input” parameter for trigger and enable port inputs:
•Use the last data input for the trigger or enable input. For a triggered and enabled model,
use the last data input for the trigger input.
•Ifyoudonotprovideanyinputvalues,thesimulationuseszeroasthe default values.
For details about how to specify the input, see “Techniques for Importing Signal Data”.
You can log data to determine which signal caused the model to run. For the Trigger or
Enable block, in the Main pane of the Block Parameters dialog box, select Show output
port.

Generate Code for Conditional Models

You can build model reference Simulink Coder and SIM targets for referenced models that
contain a trigger or enable port. You cannot generate standalone Simulink Coder or PIL
code. For information about code generation for referenced models, see “Reusable Code
and Referenced Models” and “Generate Code for Referenced Models”.

Requirements for Conditional Models

Conditional models must meet the requirements for:


•Conditional subsystems (see “Conditional Subsystems”)
•Referenced models (see “Simulink Model Referencing Requirements”)
In addition, conditional models must meet the requirements described below.
Enabled Model Requirements
•Multi-rate enabled models cannot use multi-tasking solvers. You must use single-tasking.
• For models with enable ports at the root, if the model uses a fixed-step solver, the fixed-
step size of the model must not exceed the rate for any block in the model.
•The signal attributes of the enable port in the referenced model must be consistent with
the input that the Model block provides to that enable port.
Triggered Model Requirements
The signal attributes of the trigger port in the referenced model must be consistent with the
input that the Model block provides to that trigger port.
Function-Call Model Requirements
• A function-call model cannot have an outport driven only by Ground blocks, including
hidden Ground blocks inserted by Simulink. To meet this requirement, do the following:
1Insert a Signal Conversion block into the signal connected to the outport. 2 Enable the
Exclude this block from ’Block reduction’ optimization option of the inserted block.
• The referencing model must trigger the function-call model at the rate specified by the
Configuration Parameters > Solver ‘Fixed-step size’option if the function-call model
meets both these conditions:
- It specifies a fixed-step solver
- It contains one or more blocks that use absolute or elapsed time
Otherwise, the referencing model can trigger the function-call model at any rate.
• A function-call model must not have direct internal connections between its root-level
input and output ports. Simulink does not honor the Noneand Warningsettings for the
Invalid root Inport/Outport block connection diagnostic for a referenced function-call
model. It reports all invalid root port connections as errors.
•If the Sample time type is periodic, the sample-time period must not contain an offset.
•The signal connected to a function-call port of a Model block must be scalar. Protected
Model

Protected Model

A protected model provides the ability to deliver a model without revealing the intellectual
property of the model. A protected model is a referenced model that hides all block and
line information. It does not use encryption technology. Creating a protected model
requires a Simulink Coder license. However, you can simulate a protected model with
only a Simulink license. A third party that receives a protected model must match the
platform and the version of Simulink for which the protected model was generated.
You cannot view the contents of a protected model, therefore you cannot log signals in a
protected model. Protected models do not appear in the model hierarchy in the Model
Explorer.
Simulating a protected model requires that the protected model:
•Be available somewhere on the MATLAB path.
• Be referenced by a Model block in a model that executes in Normal or Accelerator
mode. To run in Accelerator mode, the protected model must include code generation
capabilities.
•Receives from the Model block the values needed by any defined model arguments.
•Connects via the Model block to input and output signals that match the input and output
signals of the protected model.
To locate protected models in your model:
•The MATLAB Folder Browser shows a small image of a lock on the node for the
protected model file.
•A Model block that references a protected model shows a small image of a shield in the
lower left corner of the Model block.
For more information, see “Use Protected Model in Simulation” . For more information
about creating protected referenced models, see “Protect a Referenced Model”.

Use Protected Model in Simulation


When you receive a protected model it might be included in a protected model package.
The package could include additional files, such as a harness model and a MAT-file. A
protected model file has an .slxpextension. A typical workflow for using a protected model
in a simulation is:
1If necessary, unpack the files according to any accompanying directions.
2If there is a MAT-file containing workspace definitions, load that MAT-file.
3If there is aharness model, copy the Model block referencing the protected model into
your model.
4If a protected model report was generated when the protected model was created,
double-click the Model block to open it. In the Summary of the report, check that your
Simulink version and platform match the software and platform used to create the
protected model.
5Connect signals to the Model block that match its input and output port requirements.
6Provideany needed model argument values. See “Assign Model Argument Values”.
There are also other ways to include the protected model into your model:
•Use your own Model block rather than the Model block in the harness model.
Note When you change a Model block to reference a protected model, the Simulation
mode of the block is set to Accelerator. You cannot change thismode. Furthermore, you
cannot use the protected reference model block in External mode or in Rapid Accelerator
mode.
•Start with the harness model, add more constructs to it, and use it in your model.
Use Protected Model in Simulation
•Use the protected model as a variant in a Model Variant block, as described in “Set Up
Model Variants”
•Apply a mask to the Model block that references the protected model. See “Masking”.
• Configure a callback function, such as LoadFcn,toloadtheMAT-file automatically. See
“Callbacks for Customized Model Behavior” .
Now you can simulate the model that includes the protected model. Because the protected
model is set to Accelerator mode, the simulation produces the same outputs that it did
when used in Accelerator mode in the source model.

Inherit Sample Times

In this section…
“How Sample-Time Inheritance Works for Model Blocks” “Conditions for Inheriting
Sample Times”
“Determining Sample Time of a Referenced Model” “Blocks That Depend on Absolute
Time”
“Blocks Whose Outputs Depend on Inherited Sample Time”

How Sample-Time Inheritance Works for Model Blocks

The sample times of a Model block are the sample times of the model that it references. If
the referenced model must run at specific rates, the model specifies the required rates.
Otherwise, the referenced model inherits its sample time from the parent model.
Placing a Model block in a triggered, function call, or iterator subsystem relies on the
ability to inherit sample times. Additionally, allowing a Model block to inherit sample
time maximizes its reuse potential. For example, a model might fix the data types and
dimensions of all its input and output signals. You could reuse the model with different
sample times (for example, discrete at 0.1 or discrete at 0.2, triggered, and so on).

Conditions for Inheriting Sample Times

A referenced model inherits its sample time if the model:


• Does not have any continuous states
•Specifies a fixed-step solver and the Fixed-step size is auto
•Contains no blocks that specify sample times (other than inherited or constant)
• Does not contain any S-functions that use their specific sample time internally
•Has only one sample time (not counting constant and triggered sample time) after sample
time propagation
•Does not contain any blocks, including Stateflow charts, that use absolute time, as listed
in “Blocks That Depend on Absolute Time”
• Does not contain any blocks whose outputs depend on inherited sample time, as listed in
“Blocks Whose Outputs Depend on Inherited Sample Time”.
You can use a referenced model that inherits its sample time anywhere in a parent model.
By contrast, you cannot use a referenced model that has intrinsic sample times in a
triggered, function call, or iterator subsystem. To avoid rate transition errors, ensure that
blocks connected to a referenced model with intrinsic samples times operate at the same
rates as the referenced model.

Determining Sample Time of a Referenced Model


To determine whether a referenced model can inherit its sample time, set the Periodic
sample time constraint on the Solver configuration parameters dialog pane to Ensure
sample time independent. If the model is unable to inherit sample times, this setting causes
Simulink to display an error message when building the model. See “Periodic sample time
constraint” for more about this option.
To determine the intrinsic sample time of a referenced model, or the fastest intrinsic
sample time for multirate referenced models:
1Update the model that references the model
2Select a Model block within the parent model
3Enter the following at the MATLAB command line: get_param(gcb, ‘CompiledSampleTime’)

Blocks That Depend on Absolute Time


The following Simulink blocks depend on absolute time, and therefore preclude a
referenced model from inheriting sample time:
•Backlash (only when the model uses a variable-step solver and the block uses a
continuous sample time)
• Chirp Signal
•Clock
•Derivative
•Digital Clock
•Discrete-Time Integrator (only when used in triggered subsystems)
•From File
•From Workspace
•Pulse Generator
•Ramp
•Rate Limiter
•Repeating Sequence
•Signal Generator
•Sine Wave (only when the Sine type parameter is Time-based)
•Stateflow (only when the chart uses the reserved word tto reference time)
•Step
•To File
•To Workspace (only when logging to Timeseriesor Structure With Time format)
• Transport Delay
•Variable Time Delay
•Variable Transport Delay
Some blocks other than Simulink blocks depend on absolute time. See the documentation
for the blocksets that you use.

Blocks Whose Outputs Depend on Inherited Sample Time

Using a block whose output depends on an inherited sample time in a referenced model
can cause simulation to produce unexpected or erroneous results. For this reason, when
building a submodel that does not need to run at a specified rate, Simulink checks whether
the model contains any blocks whose outputs are functions of the inherited simulation
time. This includes checking S-Function blocks. If Simulink finds any such blocks, it
specifiesa default sample time. Simulink displays an error if you have set the
Configuration Parameters > Solver > Periodic sample time constraint to Ensure
sample time independent. See “Periodic sample time constraint” for more about this
option.
The outputsof the following built-in blocks depend on inherited sample time. The outputs
of these blocks preclude a referenced model from inheriting its sample time from the
parent model:
• Discrete-Time Integrator
•From Workspace (if it has input data that contains time)
•Probe (if probing sample time)
•Rate Limiter
•Sine Wave
Simulink assumes that the output of an S-function does not depend on inherited sample
time unless the S-function explicitly declares the contrary. See “Sample Times” for
information on how to create S-functions that declare whether their output depends on
their inherited sample time.
To avoid simulation errors with referenced models that inherit their sample time, do not
include S-functions in the referenced models that fail to declare whether their output
depends on their inherited sample time. By default, Simulink warns you if your model
contains such blocks when you update or simulate the model. See “Unspecified
inheritability of sample time” for details.

Refresh Model Blocks


Refreshing a Model block updates its internal representation to reflect changes in the
interface of the model that it references.
Examples of when to refresh a Model block include:
•Refresh a Model block that references model that has gained or lost a port.
•Refresh all the Model blocks that reference a model whose interface has changed.
You do not need to refresh a Model block if the changes to the interface of the referenced
model do not affect how the referenced model interfaces to its parent.
To update a specific Model block, from the context menu of the Model block, select
Subsystem & Model Reference > Refresh Selected Model Block.
To refresh all Model blocks in a model (as well as linked blocks in a library or model), in
the Simulink Editor select Diagram > Refresh Blocks.Youcan also refresh a model by
starting a simulation or generating code.
You can use Simulink diagnostics to detect changes in the interfaces of referenced models
that could require refreshing the Model blocks that reference them. The diagnostics
include:
• Model block version mismatch
• Port and parameter mismatch

S-Functions with Model Referencing

In this section…
“S-Function Support for Model Referencing” “Sample Times”
“S-Functions with Accelerator Mode Referenced Models” “Using C S-Functions in
Normal Mode Referenced Models” “Protected Models”
“Simulink®Coder™ Considerations”

S-Function Support for Model Referencing


Each kind of S-function provides its own level of support for model referencing.
Type of S-Function Level-1 MATLAB S-function
Level-2 MATLAB S-function
Handwritten C MEX S-function
S-Function Builder Legacy Code Tool
Support for Model Referencing Not supported
• Supports Normal and Accelerator mode
•Accelerator mode requires a TLC file
•Supports Normal and Accelerator mode
•May be inlined with TLC file
Supports Normal and Accelerator mode Supports Normal and Accelerator mode

Sample Times
Simulink software assumes that the output of an S-function does not depend on an
inherited sample time unless the S-function explicitly declares a dependence on an
inherited sample time.
You can control inheriting sample time by using
ssSetModelReferenceSampleTimeInheritanceRulein different ways, depending on whether
an S-function permits or precludes inheritance. For details, see “Inherited Sample Time for
Referenced Models”.

S-Functions with Accelerator Mode Referenced Models

For a referenced model that executes in Accelerator mode, set the Configuration
Parameters > Model Referencing > Total number of instances allowed per top model
to Oneif the model contains an S-function that is either:
•Inlined, but has not set the SS_OPTION_WORKS_WITH_CODE_REUSEflag
•Not inlined
Inlined S-Functions with Accelerator Mode Referenced Models For Accelerator mode
referenced models, if the referenced model contains an S-function that should be inlined
using a Target Language Compiler file, the S-function must use the ssSetOptionsmacro to
set the SS_OPTION_USE_TLC_WITH_ACCELERATORoption in its mdlInitializeSizes
method. The simulation target does not inline the S-function unless the S-function sets this
option.
A referenced model cannot use noninlined S-functions in the following cases:
• The model uses a variable-step solver.
•Simulink Coder generated the S-function.
•The S-function supports use of fixed-point numbers as inputs, outputs, or parameters.
•The model is referenced more than once in the model reference hierarchy. To work
around this limitation, use Normal mode.
•The S-function uses string parameters.

Using C S-Functions in Normal Mode Referenced Models


Under certain conditions, when a C S-function appears in a referenced model that executes
in Normal mode, successful execution is impossible. For details, see “S-Functions in
Normal Mode Referenced Models”.
Use the ssSetModelReferenceNormalModeSupportSimStruct function to specify whether
an S-function can be used in a Normal mode referenced model.
You may need to modify S-functions that are used by a model so that the S-functions work
with multiple instances of referenced models in Normal mode. The S-functions must
indicate explicitly that they support multiple execinstances. For details, see “Supporting
the Use of Multiple Instances of Referenced Models That Are in Normal Mode”.

Protected Models

A protected model cannot use noninlined S-functions directly or indirectly.

Simulink Coder Considerations

A referenced model in Accelerator mode cannot use S-functions generated by the


Simulink Coder software.
Noninlined S-functions in referenced models are supported when generating Simulink
Coder code.
The Simulink Coder S-function target does not support model referencing.
For general information about using Simulink Coder and model referencing, see “Model
Reference”.

Buses in Referenced Models

To have bus data cross model reference boundaries, use a nonvirtual bus. Use
abusobject(Simulink.Bus)todefinethebus.
For an example of a model referencing model that uses buses, see sldemo_mdref_bus. For
more information, see “Bus Data Crossing Model Reference Boundaries”
Signal Logging in Referenced Models

Signal Logging in Referenced Models

In a referenced model, you can log any signal configured for signal logging. Use the
Signal Logging Selector to select a subset or all of the signals configured for signal
logging for a model reference hierarchy. For details, see “Models with Model
Referencing: Overriding Signal Logging Settings”
6-79

Model Referencing Limitations

In this section…
“Introduction”
“Limitations on All Model Referencing” “Limitations on Normal Mode Referenced
Models” “Limitations on Accelerator Mode Referenced Models” “Limitations on PIL
Mode Referenced Models”

Introduction

The following limitations apply to model referencing. In addition, a model reference


hierarchy must satisfy all the requirements listed in “Simulink Model Referencing
Requirements”.

Limitations on All Model Referencing

Index Base Limitations


In two cases, Simulink does not propagate 0-based or 1-based indexing information to
referenced-model root-level ports connected to blocks that:
•Accept indexes (such as the Assignment block)
•Produce indexes (such as the For Iterator block)
An example of a block that accepts indexes is the Assignment block. An example of a
block that produces indexes is the For Iterator block.
The two cases result in a lack of propagation that can cause Simulink to fail to detect
incompatible index connections. These two cases are:
• If a root-level input port of the referenced model connects to index inputs in the model
that have different 0-based or 1-based indexing settings, Simulink does not set the 0-based
or 1-based indexing property of the root-level Inport block.
•If a root-level output port of the referenced model connects to index outputs in the model
that have different 0-based or 1-based indexing settings, Simulink does not set the 0-based
or 1-based indexing property of the root-level Outport block.
General Reusability Limitations
If a referenced model has any of the following characteristics, the model must specify
Configuration Parameters > Model Referencing > Total number of instances allowed
per top model as One. No other instances of the model can exist in the hierarchy. An error
occurs if you do not set the parameter correctly, or if more than one instance of the model
exists in the hierarchy. The model characteristics that require that the Total number of
instances allowed per top model setting be Oneare:
• The model contains any To File blocks
•The model references another model which is set to single instance
•The model contains a state or signal with non-auto storage class
•The model uses any of the following Stateflow constructs:
- Stateflow graphical functions
- Machine-parented data
Block Mask Limitations
• Mask callbacks cannot add Model blocks. Also, mask callbacks cannot change the
Model block name or simulation mode. These invalid callbacks generate an error.
• If a mask specifies the name of the model that a Model block references, the mask must
provide the name of the referenced model directly. You cannot use a workspace variable to
provide the name.
• The mask workspace of a Model block is not available to the model that the Mask block
references. Any variable that the referenced model uses must resolve to either of these
workspaces:
- A workspace that the referenced model defines
- The MATLAB base workspace
For information about creating and using block masks, see “Masking”.
Simulink Tool Limitations
Working with the Simulink Debugger in a parent model, you can set breakpoints at Model
block boundaries. Setting those breakpoints allows you to look at the input and output
values of the Model block. However, you cannot set a breakpoint inside the model that the
Model block references. See “Debugging” for more information.
Stateflow Limitations
You cannot reference a model multiple times in the same model reference hierarchy if that
model that contains a Stateflow chart that:
•Contains exported graphical functions
•Is part of a Stateflow model that contains machine-parented data
Subsystem Limitations
• You cannot place a Model block in an iterator subsystem, if the Model block references a
model that contains Assignment blocks that are not in an iterator subsystem.
•In a configurable subsystem with a Model block, during model update, do not change the
subsystem that the configurable subsystem selects.
Target Limitations
•The Simulink Coder grt_malloctargets do not support model referencing.
To generate reusable, reentrant code for a GRT-based model that uses model referencing,
use the Configuration Parameters > Code Generation > Interface > Generate
reusable code option.
•The Simulink Coder S-function target does not support model referencing.
Other Limitations
•Referenced models can only use asynchronous rates if the model meets both of these
conditions:
- An external source drives the asynchronous rate through a root-level Inport block.
- The root-level Inport block outputs a function-call signal. See Asynchronous Task
Specification.
• A referenced model can input or output only those user-defined data types that are fixed-
point or that Simulink.DataTypeor Simulink.Busobjects define.
• To initialize the states of a model that references other models with states, specify the
initial states in structure or structure with time format. For more information, see “Import
and Export State Information for Referenced Models”.
• A referenced model cannot directly access the signals in a multirate bus. To overcoming
this limitation, see Connecting Multi-Rate Buses to Referenced Models.
•A continuous sample time cannot be propagated to a Model block that is sample-time
independent.
• Goto and From blocks cannot cross model reference boundaries.
•You cannot print a referenced model from a top model.
• To use a masked subsystem in a referenced model that uses model arguments, do not
create in the mask workspace a variable that derives its value from a mask parameter.
Instead, use blocks under the masked subsystem to perform the calculations for the mask
workspace variable.

Limitations on Normal Mode Referenced Models

Normal Mode Visibility for Multiple Instances of a Referenced Model


You can simulate a model that has multiple instances of a referenced model that are in
Normal mode. All of the instances of the referenced model are part of the simulation.
However, Simulink displays only one of the instances in a model window. The Normal
Mode Visibility setting determines which instance Simulink displays. Normal Mode
Visibility includes the display of Scope blocks and data port values.
To set up your model to control which instance of a referenced model in Normal mode has
visibility and to ensure proper simulation of the model, see “Set Up a Model with Multiple
Instances of a Referenced Model in Normal Mode”.
Simulink Profiler
In Normal mode, enabling the Simulink Profiler on a parent model does not enable
profiling for referenced models. You must enable profiling separately for each referenced
model. See “Capture Performance Data”.
Limitation with Sim Viewing Devices in Rapid Accelerator Mode When set to Normal
mode, a Model block with a sim viewing device is not updated during Rapid Accelerator
simulation.

Limitations on Accelerator Mode Referenced Models

Subsystem Limitations
If you generate code for an atomic subsystem as a reusable function, when you use
Accelerator mode, the inputs or outputs that connect the subsystem to a referenced model
can affect code reuse. See “Reusable Code and Referenced Models” for details.
Simulink Tool Limitations
Simulink tools that require access to the internal data or the configuration of a model have
no effect on referenced models executing in Accelerator mode. Specifications made and
actions taken by such tools are ignored and effectively do not exist. Examples of tools that
require access to model internal data or configuration include:
• Model Coverage
•Simulink Report Generator
•Simulink Debugger
•Simulink Profiler
Runtime Checks
Some blocks include runtime checks that are disabled when you include the block in a
referenced model in Accelerator mode. Examples of these blocks include Assignment,
Selector, and MATLAB Function blocks)
Data Logging Limitations
The following logging methods have no effect when specified in referenced models
executing in Accelerator mode:
• To Workspace blocks (for formats other than Timeseries)
•Scope blocks
•All types of runtime display, such as Port Values Display
During simulation, the result is the same as if the constructs did not exist.
Accelerator Mode Reusability Limitations
You must set Configuration Parameters > Model Referencing > Total number of
instances allowed per top model to Onefor a referenced model that executes in
Accelerator mode and has any of the following characteristics:
• A subsystem that is marked as function
•An S-function that is:
- Inlined but has not set the option SS_OPTION_WORKS_WITH_CODE_REUSE
- Not inlined
•A function-call subsystem that:
- Has been forced by Simulink to be a function
- Is called by a wide signal
An error occurs in either of these cases:
•You do not set the parameter correctly.
•Another instances of the model exists in the hierarchy, in either Normal mode or
Accelerator mode
Customization Limitations
•For restrictions that apply to grouped custom storage classes in referenced models in
Accelerator mode, see “Custom Storage Class Limitations”.
•Simulation target code generation for referenced models in Accelerator mode does not
support data type replacement.
S-Function Limitations
• If a referenced model in Accelerator mode contains an S-function that should be inlined
using a Target Language Compiler file, the S-function must use the ssSetOptionsmacro to
set the SS_OPTION_USE_TLC_WITH_ACCELERATOR option in its
mdlInitializeSizesmethod. The simulation target does not inline the S-function unless the
S-function sets this option.
•You cannot use the Simulink Coder S-function target in a referenced model in
Accelerator mode.
•A referenced model in Accelerator mode cannot use noninlined S-functions in the
following cases:
- The model uses a variable-step solver.
- Simulink Coder generated the S-function.
- The S-function supports use of fixed-point numbers as inputs, outputs, or parameters.
- The S-function uses string parameters.
- The model is referenced more than once in the model reference hierarchy. To work
around this limitation:
1 Make copies of the referenced model.
2 Assign different names to the copies.
3 Reference a different copy at each location that needs the model.

MATLAB Function Block Limitation


A MATLAB Function block in a referenced model that executes in Accelerator mode
cannot call MATLAB functions.
Stateflow Limitation
A Stateflow chart in a referenced model that executes in Accelerator mode cannot call
MATLAB functions.
Other Limitations
• When you create a model, you cannot use that model as an Accelerator mode referenced
model until you have saved the model to disk. You can work around this limitation by
setting the model to Normal mode. See “Specify the Simulation Mode”.
•When the simcommand executes a referenced model in Accelerator mode, the source
workspace is always the MATLAB base workspace.
•Accelerator mode does not support the External mode option. If you enable the
External mode option, Accelerator mode ignores it.
Limitations on PIL Mode Referenced Models

Only one branch (top model and all subordinates) in a model reference•
hierarchy can execute in PIL mode.
• If you create a model, you cannot use that model as a PIL mode referenced model until
you have saved the model to disk. To work around this limitation, set the model to Normal
mode. See “Specify the Simulation Mode”.
For more information about using PILmode with model referencing, see “Model
Reference” in the Embedded Coder documentation.

About Conditional Subsystems

A subsystem is a set of blocks that have been replaced by a single block called a
Subsystem block. This chapter describes a special kind of subsystem for which execution
can be externally controlled. For information that applies to all subsystems, see “Create a
Subsystem”.
A conditional subsystem,alsoknownasa conditionally executed subsystem,is a subsystem
whose execution depends on the value of an input signal. The signal that controls whether
a subsystem executes is called the control signal. The signal enters a subsystem block at
the control input.
Conditional subsystems can be very useful when you are building complex models that
contain components whose execution depends on other components. Simulink supports
the following types of conditional subsystems:
• An enabled subsystem executes while the control signal is positive. It starts execution at
the time step where the control signal crosses zero (from the negative to the positive
direction) and continues execution as long as the control signal remains positive. For a
more detailed discussion, see “Enabled Subsystems” o.
• A triggered subsystem executes once each time a trigger event occurs. A trigger event
can occur on the rising or falling edge of a trigger signal, which can be continuous or
discrete. For more information about triggered subsystems, see “Triggered Subsystems”.
• A triggered and enabled subsystem executes once at the time step for which a trigger
event occurs if the enable control signal has a positive value at that step. See “Triggered
and Enabled Subsystems”
.
• A control flow subsystem executes one or more times at the current time step when
enabled by a control flow block. A control flow block implements control logic similar to
that expressed by control flow statements of programming languages (e.g., if-then, while,
do,and for). See “Control Flow Logic”.
About Conditional Subsystems
Note The Simulink software imposes restrictions on connecting blocks with a constant
sample time to the output port of a conditional subsystem. See “Using Blocks with
Constant Sample Times in Enabled Subsystems” .
For examples of conditional subsystems, see:
• Simulink Subsystem Semantics
•Triggered Subsystems
•Enabled Subsystems
•Advanced Enabled Subsystems

Enabled Subsystems

In this section…
“What Are Enabled Subsystems?”
“Creating an Enabled Subsystem”
“Blocks that an Enabled Subsystem Can Contain”
“Using Blocks with Constant Sample Times in Enabled Subsystems”

What Are Enabled Subsystems?

Enabled subsystems are subsystems that execute at each simulation step for which the
control signal has a positive value.
An enabled subsystem has a single control input, which can be a scalar or a vector.
•If the input is a scalar, the subsystem executes if the input value is greater than zero.
•If the input is a vector, the subsystem executes if any one of the vector elements is greater
than zero.
For example, if the control input signal is a sine wave, the subsystem is alternately enabled
and disabled. This behavior is shown in the following figure, where an up arrow signifies
enable and a down arrow disable.

The Simulink software uses the zero-crossing slope method to determine whether an
enable event is to occur. If the signal crosses zero and its slope is positive, then the
subsystem becomes enabled. If the slope is negative at the zero crossing, then the
subsystem becomes disabled. Note that a subsystem is only enabled or disabled at major
time steps. Therefore, if zero-crossing detection is turned off and the signal crosses zero
during a minor time step, then the subsystem will not become enabled (or disabled) until
the next major time step.

Creating an Enabled Subsystem

You create an enabled subsystem by copying an Enable block from the Ports &
Subsystems library into a Subsystem block. An enable symbol and an enable control input
port is added to the Subsystem block.

Setting Initial Conditions for an Enabled Subsystem You can set the initial output of an
enabled subsystem using the subsystems Outport blocks. The initial output value can be
either explicitly specified, or inherited from its input signal.
Specifying Initial Conditions.To specify the initial output value of the subsystem:
1Double-click each Outport block in the subsystem to open its block parameters dialog
box.
2In the Source of initial output value drop-down list, select Dialog.

3Specify a valid value for the Initial output parameter. Valid values include the empty
matrix. But Infand NaNare not valid values. If you select Dialog, you can also specify
what happens to the output when the subsystem is disabled. For more information, see the
next section: “Setting Output Values While the Subsystem Is Disabled”.
Inheriting Initial Conditions. The Outport block can inherit an initial output value for
the subsystem from the following sources:
• Output port of another conditionally executed subsystem
•Merge block (with Initial output specified)
•Function-Call Model Reference block
•Constant block (simplified initialization mode only)
•IC block (simplified initialization mode only)
The procedure you use to inherit the initial conditions of the subsystem differs depending
on whether you are using classic initialization mode or simplified initialization mode.
To inherit initial conditions in classic initialization mode:
1Double-click each Outport block in the subsystem to open its block parameters dialog
box.
2In the Source of initial output value drop-down list, select Dialog.
3Set the Initial output parameter to [](empty matrix).
4Click OK.
Note For all other driving blocks, specify an explicit initial output value.
To inherit initial conditions in simplified initialization mode:
1Double-click each Outport block in the subsystem to open its block parameters dialog
box.
2In the Source of initial output value drop-down list, select Input signal.
3Click OK.
The Initial output and Output when disabled parameters are disabled, and both values
are inherited from the input signal.
For more information on classic and simplified initialization mode, see “Underspecified
initialization detection”.
Setting Output Values While the Subsystem Is Disabled Although an enabled
subsystem does not execute while it is disabled, the output signal is still available to other
blocks. While an enabled subsystem is disabled, you can choose to hold the subsystem
outputs at their previous values or reset them to their initial conditions.
Open the block parameters dialog box for each Outport block and for the Output when
disabled parameter, select one of the choices.
•Choose heldto maintain the most recent value.
•Choose resetto revert to the initial condition. Set the Initial output to the initial value of
the output.

Set the Outport output while the subsystem is


disabled
Initial condition and value when reset

Note If you are connecting the output of a conditionally executed subsystem to a Merge
block, set Output when disabled to heldto ensure consistent simulation results.
If you are using simplified initialization mode, you must select heldwhen connecting a
conditionally executed subsystem to a Merge block. For more information, see
“Underspecified initialization detection”.
Setting States When the Subsystem Becomes Enabled When an enabled subsystem
executes, you can choose whether to hold the subsystem states at their previous values or
reset them to their initial conditions.
To do this, open the Block Parameters: Enable dialog box and select one of the choices
for the States when enabling parameter:
• Choose heldto cause the states to maintain their most recent values.
•Choose resetto cause the states to revert to their initial conditions.

Note If you are using simplified initialization mode, the subsystem elapsed time is always
reset during the first execution after becoming enabled, whether or not the subsystem is
configured to reset on enable.
For more information on simplified initialization mode, see “Underspecified initialization
detection”.
Note For nested subsystems whose Enable blocks have different parameter settings, the
settings on the child subsystem’s dialog box override those inherited from the parent
subsystem.
Outputting the Enable Control Signal
An option on the Enable block dialog box lets you output the enable control signal. To
output the control signal, select the Show output port check box.
This feature allows you to pass the control signal down into the enabled subsystem, which
can be useful where logic within the enabled subsystem is dependent on the value or
values contained in the control signal.

Blocks that an Enabled Subsystem Can Contain

An enabled subsystem can contain any block, whether continuous or discrete. Discrete
blocks in an enabled subsystem execute only when the subsystem executes, and only when
their sample times are synchronized with the simulation sample time. Enabled subsystems
and the model use a common clock.
Note Enabled subsystems can contain Goto blocks. However, only state ports can connect
to Goto blocks in an enabled subsystem. In the sldemo_clutch model, see the
Lockedsubsystem for an example of how to use Goto blocks in an enabled subsystem.
For example, this system contains four discrete blocks and a control signal. The discrete
blocks are:
• Block A, which has a sample time of 0.25 second
•Block B, which has a sample time of 0.5 second
•Block C, within the enabled subsystem, which has a sample time of 0.125 second
•Block D, also within the enabled subsystem, which has a sample time of 0.25 second
The enable control signal is generated by a Pulse Generator block, labeled Signal E, which
changes from 0 to 1 at 0.375 second and returns to 0 at 0.875 second.
The chart below indicates when the discrete blocks execute.
Blocks A and B execute independently of the enable control signal because they are not
part of the enabled subsystem. When the enable control signal becomes positive, blocks C
and D execute at their assigned sample rates until
theenablecontrolsignalbecomeszeroagain. NotethatblockCdoesnot execute at 0.875 second
when the enable control signal changes to zero.

Using Blocks with Constant Sample Times in Enabled Subsystems

Certain restrictions apply when you connect blocks with constant sample times (see
“Constant Sample Time”) to the output port of a conditional subsystem.
•An error appears when you connect a Model or S-Function block with constant sample
time to the outputport of a conditional subsystem.
• The sample time of any built-in block with a constant sample time is converted to a
different sample time, such as the fastest discrete rate in the conditional subsystem.
To avoid the error or conversion, either manually change the sample time of the block to a
non-constant sample time or use a Signal Conversion block. The example below shows
how to use the Signal Conversion block to avoid these errors.
Consider the following model ex_enabled_subsys_2.mdl.
The two Constant blocks in this model have constant sample times. When you simulate
the model, the Simulink software converts the sample time of the Constant block inside
the enabled subsystem to the rate of the Pulse Generator. If you simulate the model with
sample time colors displayed (see “View Sample Time Information”), the Pulse Generator
and Enabled Subsystem blocks are colored red. However, the Constant and Outport blocks
outside of the enabled subsystem are colored magenta, indicating that these blocks still
have a constant sample time.
Suppose the model above is referenced from a Model block inside an enabled subsystem,
as shown below. (See “Model Reference”.)
An error appears when you try to simulate the top model, indicating that the second output
of the Model block may not be wired directly to the enabled subsystem output port
because it has a constant sample time. (See “Model Reference”.)
To avoid this error, insert a Signal Conversion block between the second output of the
Model block and the Outport block of the enabled subsystem. This model simulates with
no errors. With sample time colors displayed, the Model and Enabled Subsystem blocks
are colored yellow, indicating that these are hybrid systems. In this case, the systems are
hybrid because they contain multiple sample times.

Triggered Subsystems
In this section…
“What Are Triggered Subsystems?”
“Using Model Referencing Instead of a Triggered Subsystem” “Creating a Triggered
Subsystem”
“Blocks That a Triggered Subsystem Can Contain”

What Are Triggered Subsystems?


Triggered subsystems are subsystems that execute each time a trigger event occurs.
A triggered subsystem has a single control input, called the trigger input, that determines
whether the subsystem executes. You can choose from three types of trigger events to
force a triggered subsystem to begin execution:
For example, in the following timing diagram for a discrete system, a rising trigger (R)
does not occur at time step 3 because the signal remains at zero for only one time step
prior to the rise.

A simple example of a triggered subsystem is illustrated.


In this example, the subsystem is triggered on the rising edge of the square wavetrigger
control signal.

Using Model Referencing Instead of a Triggered Subsystem

You can use triggered ports in referenced models. Add a trigger port to a referenced model
to create a simpler, cleaner model than when you include either:
•A triggered subsystem in a referenced model
•A Model block in a triggered subsystem
For information about using trigger ports in referenced models, see “Conditional
Referenced Models”.
To convert a subsystem to use model referencing, see “Convert a Subsystem to a
Referenced Model”.

Creating a Triggered Subsystem


You create a triggered subsystem by copying the Trigger block from the Ports &
Subsystems library into a subsystem. The Simulink software adds a trigger symbol and a
trigger control input port to the Subsystem block.

To select the trigger type, open the Trigger block dialog box and select one of the choices
for the Trigger type parameter.
Different symbols appear on the Trigger and Subsystem blocks to indicate rising and
falling triggers (or either). This figure shows the trigger symbols on Subsystem blocks.

Outputs and States Between Trigger Events


Unlike enabled subsystems, triggered subsystems always hold their outputs at the last
value between triggering events. Also, triggered subsystems cannot reset their states when
triggered; the states of any discrete block is held between trigger events.
Outputting the Trigger Control Signal
An option on the Trigger block dialog box lets you output the trigger control signal. To
output the control signal, select the Show output port check box.
In the Output data type field, specify the data type of the output signal as auto, int8,or
double.The autooption causes the data type of the output signal to be the data type (either
int8or double) of the port to which the signal connects.

Blocks That a Triggered Subsystem Can Contain

All blocks in a triggered subsystem must have either inherited ( -1)or constant (inf) sample
time. This is to indicate that the blocks in the triggered subsystem run only when the
triggered subsystem itself runs, for example, when it is triggered. This requirement means
that a triggered subsystem cannot contain continuous blocks, such as the Integrator block.

Action Subsystem, If Action Subsystem, Switch Case Action Subsystem

In this section…
“What Are Action Subsystems?”
“Set States when an Action Subsystem Executes”

What Are Action Subsystems?

Action subsystems are subsystems that execute in response to a conditional output from an
If block or a Switch Case block. In essence, they are subsystems with an Action port,
which allow for block execution based on conditional inputs from an If block or Switch
Case block.
Simulink has two types of action subsystems, based on the type of block they receive
conditional input from.
If Action Subsystem
The If Action Subsystem is preconfigured to serve as a starting point for creating a
subsystem whose execution is triggered by an If block. To implement an if-else condition,
connect If action subsystem blocks to the outputs of anIf block.

Switch Case Action Subsystem


The Switch Case Action Subsystem is preconfigured to serve as a starting point for
creating a subsystem whose execution is triggered by a Switch Case block. To implement
a switch condition, connect Switch Case Action Subsystem blocks to the outputs of a
Switch Case block.
Note All blocks in an action subsystem must run at the same sample time as the If or
Switch Case block that triggers its execution. You can achieve this automatically by
setting the Sample time parameter of each block in the subsystem to -1 (inherited).

Set States when an Action Subsystem Executes

When anaction subsystem is triggered to execute, you can choose whether to holdthe
subsystem states at their previous values or reset them to their initial conditions.
1Open the Action Port block inside the action subsystem.
2Select one of the following for the States when execution is resumed parameter:

• heldif you want the states to maintain their most recent values
• resetif you want the states to revert to their initial conditions

Note For nested subsystems whose Action Port blocks have different parameter settings,
the settings on the child subsystem’s dialog box override those inherited from the parent
subsystem.
For more information, see Action Port, If, and Switch Case.

Triggered and Enabled Subsystems

In this section…
“What Are Triggered and Enabled Subsystems?” “Creating a Triggered and Enabled
Subsystem” “A Sample Triggered and Enabled Subsystem” “Creating Alternately
Executing Subsystems”

What Are Triggered and Enabled Subsystems?

A third kind of conditional subsystem combines two types of conditional execution. The
behavior of this type of subsystem, called a triggered and enabled subsystem, is a
combination of the enabled subsystem and the triggered subsystem, as shown by this flow
diagram.
Atriggered and enabled subsystem contains both an enable input port and atrigger input
port. When the trigger event occurs, the enable input port is checked to evaluate the enable
control signal. If its value is greater than zero, the subsystem is executed. If both inputs are
vectors, the subsystem executes ifat least one element of each vector is nonzero.
The subsystem executes once at the time step at which the trigger event occurs.

Creating a Triggered and Enabled Subsystem

You create a triggered and enabled subsystem by dragging both the Enable and Trigger
blocks from the Ports & Subsystems library into an existing subsystem. The Simulink
software adds enable and trigger symbols and enable and trigger control inputs to the
Subsystem block.

You can set output values when a triggered and enabled subsystem is disabled as you
would for an enabled subsystem. For more information, see “Setting Output Values While
the Subsystem Is Disabled”. A lso, you can specify what the values of the states are when
the subsystem is reenabled. See “Setting States When the Subsystem Becomes Enabled”.
Set the parameters for the Enable and Trigger blocks separately. The procedures are the
same as those described for the individual blocks.

A Sample Triggered and Enabled Subsystem

A simple exampleof a triggered and enabled subsystem is illustrated in the following


model.
Creating Alternately Executing Subsystems

You can use conditional subsystems in combination with Merge blocks to create sets of
subsystems that execute alternately, depending on the current state of the model.
The following figure shows a model that uses two enabled blocks and a Merge block to
model a full-wave rectifier – a device that converts AC current to pulsating DC current.
The block labeled posis enabled when the AC waveform is positive; it passes the
waveform unchanged to its output. The block labeled negis enabled when the waveform is
negative; it inverts the waveform. The Merge block passes the output of the currently
enabled block to the Mux block, which passes the output, along with the original
waveform, to the Scope block.
The Scope creates the following display.

Function-Call Subsystems
What is a Function-Call Subsystem?
A function-call subsystem is a subsystem that another block can invoke directly during a
simulation. It is analogous to a function in a procedural programming language. Invoking
a function-call subsystem is equivalent to invoking the output methods (See “Block
Methods”) of the blocks that the subsystem contains in sorted order (See “How Simulink
Determines the Sorted Order”). The block that invokes a function-call
subsystem is called the function-call initiator. Stateflow, Function-Call Generator, and S-
function blocks can all serve as function-call initiators.

Creating Function-Call Subsystems

To create a function-call subsystem, drag a Function-Call Subsystem block from the Ports
& Subsystems library into your model and connect a function-call initiator to the function-
call port displayed on top of the subsystem. You can also create a function-call subsystem
from scratch. First create a Subsystem block in your model and then create a Trigger block
in the subsystem. Next, on the Trigger block parameters pane, set the Trigger type to
function-call.

Sample Time Propagation in Function-Call Subsystems


You can configure a function-call subsystem to be triggered (the default) or periodic by
setting the Sample time type of its Trigger port to be triggered or periodic, respectively. A
function-call initiator can invoke a triggered function-call subsystem zero, one, or multiple
times per time step. The sample times of all the blocks in a triggered function-call
subsystem must be set to inherited (-1).
A function-call initiator can invoke a periodic function-call subsystem only once per time
step and must invoke the subsystem periodically. If the initiator invokes a periodic
function-call subsystem aperiodically, the simulation is halted and an error message is
displayed. The blocks in a periodic function-call subsystem can specify a noninherited
sample time or inherited (-1) sample time. All blocks that specify a noninherited sample
time
Function-Call Subsystems
must specify the same sample time. For example, if one block specifies 0.1as the sample
time, all other blocks must specify a sample time of 0.1or -1.If a function-call initiator
invokes a periodic function-call subsystem at a rate that differs from the sample time
specified by the blocks in the subsystem, the simulation halts and an error message
appears.
Note During range checking, the design minimum and maximum are back-propagated to
the actual source port of the function-call subsystem, even when the function-call
subsystem is not enabled.
To prevent this back propagation, add a Signal Conversion block and a Signal
Specification block after the source port, set the Output of the Signal Conversion block to
Signal copy, and specify the design minimum and maximum on the Signal Specification
block instead of specifying them on the source port.
For more information, see in “Writing S-Functions” in the online documentation.

Conditional Execution Behavior

In this section…
“What Is Conditional Execution Behavior?” “Propagating Execution Contexts” “Behavior
of Switch Blocks”
“Displaying Execution Contexts” “Disabling Conditional Execution Behavior”
“Displaying Execution Context Bars”

What Is Conditional Execution Behavior?

To speed the simulation of a model, by default the Simulink software avoids unnecessary
execution of blocks connected to Switch, Multiport Switch, and of conditionally executed
blocks. This behavior is conditional execution (CE) behavior. You can disable this
behavior for all Switch and Multiport Switch blocks in a model, or for specific conditional
subsystems. See “Disabling Conditional Execution Behavior”.
The following model illustrates conditional execution behavior.
The Scope block shows the simulation
result:

This model:
•Has the Display > Signals & Ports > Execution Context Indicator menu option
enabled.
• The Pulse Generatorblock has the following parameter settings:
- Pulse type — Sample based
- Period — 100
- Pulse width — 50
- Phase delay — 50
- Sample Time — 0.01
•The Gainblock’s sorted order (1:2) is second (2) in the enabled subsystem’s execution
context (1).
•The Enabled Subsystemblock has the Propagate execution context across subsystem
boundary parameter enabled.
•In the enabled subsystem, the Out1block has the following parameter settings:
- Initial output — []
- Output when disabled — held
The outputs of the Constant block and Gain blocks are computed only while the enabled
subsystem is enabled (for example, at time steps 0.5 to 1.0 and 1.5 to 2.0). This behavior is
necessary because the output of the Constant block is required and the input of the Gain
block changes only while the enabled subsystem is enabled. When CE behavior is off, the
outputs of the Constant and Gain blocks are computed at every time step, regardless of
whether the outputs are needed or change.
In this example, the enabled subsystem is regarded as defining an execution context for
the Constant and Gain blocks. Although the blocks reside graphically in the root system of
the model, the Simulink software invokes the block methods during simulation as if the
blocks reside in the enabled subsystem. This is indicated in the sorted order labels
displayed on the diagram for the Constant and Gain blocks. The notations list the
subsystem’s (id = 1) as the execution context for the blocks even though the blocks exist
graphically at the root level (id = 0) of the model. The Gain block’s sorted order (1:2) is
second (2) in the enabled subsystem’s execution context (1).

Propagating Execution Contexts

In general, the Simulink software defines an execution context as a set of blocks to be


executed as a unit. At model compilation time, the Simulink software associates an
execution context with the model’s root system and with each of its nonvirtual
subsystems. Initially, the execution context of the root system and each nonvirtual
subsystem is simply the blocks that it contains.
When compiling, each block in the model is examined to determine whether it meets the
following conditions:
• The block output is required only by a conditional subsystem or the block input changes
only as a result of the execution of a conditionally executed subsystem.
•The execution context of the subsystem can propagate across the subsystem boundaries.
• The output of the block is not a test point (see “Test Points”).
•The block is allowed to inherit its conditional execution context.
The Simulink software does not allow some built-in blocks, such as the Delay block, ever
to inherit their execution context. Also, S-Function blocks can inherit their execution
context only if they specify the
SS_OPTION_CAN_BE_CALLED_CONDITIONALLYoption.
•The block is not a multirate block.
•The block sample time is set to inherited (-1).
If a block meets these conditions and execution context propagation is enabled for the
associated conditional subsystem (see “Disabling Conditional Execution Behavior”), the
Simulink software moves the block into the execution context of the subsystem. This
ensures that the block methods execute during the simulation loop only when the
corresponding conditional subsystem executes.
Note Execution contexts are not propagated to blocks having a constant sample time.

Behavior of Switch Blocks


This behavior treats the input branches of a Switch or Multiport Switch block as invisible,
conditional subsystems, each of which has its own execution context. This CE is enabled
only when the control input of the switch selects the corresponding data input. As a result,
switch branches execute only when selected by switch control inputs.

Displaying Execution Contexts

To determine theexecution context to which a block belongs, in the Simulink Editor, select
Display > Blocks > Sorted Execution Order. The sorted order index foreach block in the
model is displayed in the upper-right corner of the block. The index has the format
s:b,where sspecifies the subsystem to whose execution context the block belongs and bis
an index that indicates the block sorted order in the execution context of the subsystem.
For example, 0:0 indicatesthat the block is the first block in the execution context of the
root subsystem.
If a bus is connected to a block input, the block sorted order is displayed as s:B. For
example, 0:B indicates that the block belongs to the execution context of the root system
and has a bus connected to its input.
The sortedorder index of conditional subsystems is expanded to include the systemID of
the subsystem itself in curly brackets as illustrated in the followingfigure.

In this example, the sorted order index of the enabled subsystem is 0:1{1}. The 0indicates
that the enabled subsystem resides in the root system of the model. The first 1indicates
that the enabled subsystem is the second block on the sorted list of the root system (zero-
based indexing). The 1in curly brackets indicates that the system index of the enabled
subsystem itself is 1. Thus any block whose system index is 1belongs to the execution
context of the enabled subsystem and hence executes when it does. For example, the fact
that the Constant block has an index of 1:0indicates that it is the first block on the sorted
list of the enabled subsystem, even though it resides in the root system.

Disabling Conditional Execution Behavior


To disable conditional execution behavior for all Switch and Multiport Switch blocks in a
model,turnoffthe Conditional input branch execution optimization onthe Optimization
pane of the Configuration Parameters dialog box (see“Optimization Pane: General”). To
disable conditional execution behavior for a specific conditional subsystem, clear the
Propagate execution context across subsystem boundary check box on the subsystem
parameter dialog box.
Even if this option is enabled, the execution context of the subsystem cannot propagate
across its boundaries under either of the following circumstances:
•The subsystem is a triggered subsystem with a latched input port.
• The subsystem has one or more output ports that specify an initial conditionother than [].
In this case, a block connected to the subsystem output cannot inherit the execution
context of the subsystem.

Displaying Execution Context Bars

Simulinkcan optionally display bars next to the ports of subsystems across which
execution contexts cannot propagate. To display the bars, select Display > Signals &
Ports > Execution Context Indicator.
For example, it displays bars on subsystems from which no block can inherit its execution
context. In the following figure, the context bars appear next to the In1and Out1ports of
the Enabled Subsystem block.

Conditional Subsystem Output Initialization

In this section…
“Why Initialize Conditional Subsystem Output?” “Initialization Mode”
“Simplified Mode Benefits”
“Simplified Mode Behavior”
“Initialization Techniques”

Why Initialize Conditional Subsystem Output?

By default, Simulink provides inherited initial values for simulating conditional


subsystems. You can explicitly set the initial values. Initialize conditional subsystems to:
•Specify initial behaviors that meet your modeling goals.
•Explicitly specify initial values, instead of using inherited initial values, which can be
hard to identify in a complex model.
•Set initial values that reduce simulation time by reaching steady state faster.
For information about how to initialize a conditional subsystem, see “Initialization
Techniques”.

Initialization Mode
The Configuration Parameters > Diagnostics > Data
Validity > Underspecified initialization detection parameter specifies how Simulink
handles the initial conditions for conditionally executed subsystems, Merge blocks,
subsystem elapsed time, and Discrete-Time Integrator blocks. Often, the impact of the
initialization mode for Merge blocks and Discrete-Time Integrator blocks is in the context
of those blocks being used with a conditional subsystem.
The default initialization mode is Classic, which was the only way that Simulink handled
initial conditions prior to R2008b.
Simplifiedmode uses enhanced processing, which can improve consistency of simulation
results.
To convert an existing model that uses classic initialization mode to use simplified mode,
see “Simplified Initialization” an d “Comparison of Classic and Simplified Initialization
Modes”.

Simplified Mode Benefits

Consider using Simplified mode to:


•Detect whether initialization is configured well, in terms of consistency of simulation
results and robustness, to help you to:
- Attain the same simulation results with the same inputs when using the same blocks in a
different model.
- Avoid possible different simulation results as you modify a model. For details, see
“Comparison of Classic and Simplified Initialization Modes” .
•Configure a model to support more recent (after R2008b) features that require simplified
initialization mode, such as:
- Specify a structure to initialize a bus.
- Branch merged signals inside a conditional subsystem.
Features relating to conditional subsystems that are introduced after R2013a generally
require the use of simplified initialization.

Simplified Mode Behavior

Output
• The output signal of conditional subsystem is stored in separate memory that is not
shared by with any other Outport block. The initialization behavior of the memory is fully
specified at the start of simulation.
• Conditional subsystem output ports can either explicitly specify a particular initial
condition value or inherit that value from the block connected to the Outport block input
port (but not from outside of the subsystem).
•Simplified mode always uses the initial value as both the initial and reset value for output
for a Discrete-Time Integrator block.
Outport Blocks
Simplified mode has the following behavior with Outport blocks:
• Simplified mode assumes the Initial output value is derived from the input signal if
Source of initial output value is set to Input signal. This can result in initialization
behavior that is different from classic mode.
•If you set Source of initial output value to Dialog, you must specify an initial value. (An
empty matrix ([]) is not supported.)
•The Outport block can inherit the initial output value from a limited number of blocks.
For details, see “Inherit Initial Values”.
•You cannot use a Simulink.Signalobject to specify the Initial output value.
Merge Blocks
• You cannot use an empty matrix ([]) for initial output value for root Merge blocks. A root
Merge block is the final Merge block in a series of connected Merge blocks. Empty
initialization values are the default for Merge blocks.
•You cannot use single-input Merge blocks.
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 When Using Simplified Initialization Mode”.
Library Blocks
For libraries that you create in a classic mode environment and that contain blocks
affected by simplified mode, either use the Model Advisor to update the library or break
the library links for blocks.

Initialization Techniques

For an Outport block in a conditional subsystem, the block parameters dialog box includes
parameters for specifying initial conditions.
You can either explicitly specify the initial values or inherit initial values. For inheriting
values, the approach that you use depends on whether you use classic or simplified
initialization mode. See “Inherit Initial Values” .
Specify Initial Values for a Conditional Subsystem Output To explicitly specify the
initial values for a conditional subsystem: 1In the block parameter dialog box, set the
Source of initial output value parameter to Dialog.
2Enter the initial value in the Initial output parameter.
Note If you use simplified initialization mode, then you cannot specify an empty matrix
([])ora Simulink.Signalobject.
Inherit Initial Values
The Outport block can inherit the initial output value from the following sources:
• Output port of another conditionally executed subsystem
•Merge block (with Initial output specified)
•Function-Call Model Reference block
•Constant block (simplified initialization mode only)
•IC block (simplified initialization mode only)
If you use simplified mode, set the Source of initial output value parameter to Input
signal.
If you use classic mode:
1Set the Source of initial output value parameter to the default value of Dialog.
2In the Initial output parameter, enter an empty matrix ([]).

Simplified Initialization

In this section…
“When to Use Simplified Initialization” “Convert a Model to Use Simplified
Initialization”

When to Use Simplified Initialization


Use simplified initialization mode formodelsthatcontainoneormoreof the following blocks:
• Conditional subsystem
•Merge block
•Discrete-Time Integrator block
Consider using simplified initialization when you:
•Add one of the modeling elements listed above (for example, conditional subsystems).
•Debug a model that includes one of the blocks listed above.
•Use a feature that requires simplified initialization.
Simplified mode offers many benefits, compared to classic mode. For details, see
“Simplified Mode Benefits”. However, for an existing model, you can continue to use
classic mode if:
•The model does not include any modeling elements affected by simplified mode.
•The 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.
Note When you convert a model that uses classic initialization mode to use simplified
initialization mode can produce simulation results different from the classic mode results.
However, the converted model results are more robust and consistent than results from the
classic mode version of the model.

Convert a Model to Use Simplified Initialization

If you switch the initialization mode from classic to simplified mode, you are likely to
encounter a series of issues that you need to address, one-by-one. For most models, the
following approach helps you to address conversion issues more efficiently.
Note For examples of models that have been converted from classic initialization mode to
simplified initialization mode, see “Comparison of Classic and Simplified Initialization
Modes”.
1Save the existing model and simulation results for the model.
Save Model and Simulation Results
Before you convert an existing model to use simplified mode, save the existing model and
simulation results.
The conversion process can require you to make changes to your model. It is helpful to
have the original model as a reference and to compare simulation results.
For information about saving simulation results, see “Export Simulation Data”.
2Use strict bus mode. Set the Configuration Parameters > Diagnostics > Connectivity
> Mux blocks used to create bus signals diagnostic to error.
Simulate the model address any warnings.
Use strict bus mode
Simplified initialization mode requires that you use of strict bus mode. Set the Mux
blocks used to create bus signals diagnostic to errorto cause Simulink to detect and
correct muxes that are used as buses.
After you set the diagnostic to error, simulate the model and address any errors that occur.
For details, see Mux blocks used to create bus signals.
3 In the Model Advisor, in the Simulink checks section, run Check consistency of
initialization parameters for Outport and Merge blocks.
Run Model Advisor initialization check
a In the Simulink Editor, select Analysis > Model Advisor > Model Advisor.

b Select the top system to run the checks on and click OK.
c Select By Product > Simulink and clear the Simulink check box.

d Select Check consistency of initialization parameters for Outport and Merge


blocks.
e Click the Run selected checks button .
The Model Advisor displays a report identifying issues that you need to address.
4Address the issues that Model Advisor identifies.
Address Model Advisor issues
The Model Advisor provides suggested actions for you to take to address each issue that it
identifies.
For example, suppose that you see the following result:

The recommended action suggests two possible actions to deal with the issues that Model
Advisor identified.
For additional information about how to address each issue that the Model Advisor
identifies, click the Help button or right-click the check and select What’s This.
5Simulate the model to make sure that there are no errors.
6 Rerun the Model Advisor Check consistency of initialization parameters for Outport
and Merge blocks check to confirm that the modified model addresses the issues related
to initialization.
Rerun check
After you have finished addressing the issues that Model Advisor identified that relate to
initialization, rerun the check to confirm that you have addressed all the issues and not
introduced any new ones.
With the Check consistency of initialization parameters for Outport and Merge
blocks enabled, click the Run this check button (

)) to rerun the check.

Comparison of Classic and Simplified Initialization Modes

In this section…
“How Simplified Mode Addresses Classic Mode Issues”
“Identity Transformation Can Change Model Behavior”
“Discrete-Time Integrator or S-Function Block Can Produce Inconsistent Output”
“Sorted Order Can Affect Merge Block Output”

How Simplified Mode Addresses Classic Mode Issues

Using classic initialization mode can result in issues that you can address by using
simplified mode. This topic includes examples of such issues.
For more information about the tasks involved to convert a model from classic to
simplified mode, see “Convert a Model to Use Simplified Initialization” .

Identity Transformation Can Change Model Behavior


Conditional subsystems that use classic initialization mode and include identical
subsystems, one or more of which outputs to an identity transformation block, can display
different initial values before the first execution. 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.
Example
In the ex_identity_transform_clmodel, subsystems A and B are identical, but B outputs to
a Gain block, which in turn outputs to an Outport block.
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.

If you update the model to use simplified initialization mode (see


ex_identity_transform_simpl), the model looks the same. The steps required to convert
ex_identity_transform_clto ex_identity_transform_simplare:
1Use strict bus mode. Set Configuration Parameters > Diagnostics > Connectivity >
Mux blocks used to create bus signals to error.
2For the Outport blocks in subsystems A and B, set the Source of initial output value
parameter to Input signal.
You could also get the same behavior by setting the Source of initial output value
parameter to Dialogand the Initial output parameter to 1.
3Set Configuration Parameters > Diagnostics > Data
Validity > Underspecified initialization detection to Simplified.
When you simulate the updated model, the connection of an identity transformation does
not change the result. The output is consistent in both cases.

Discrete-Time Integrator or S-Function Block Can Produce Inconsistent


Output
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.
Example
In the ex_discrete_time_clmodel, the enabled subsystem includes two Constant blocks and
outputs to a Discrete-Time Integrator block. The enabled subsystem outputs to two
Display blocks.
When you simulate the model, the two display blocks show different values.

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.
If you update the model to use simplified initialization mode (see
ex_discrete_time_simpl), the model looks the same. The updated model corrects the
inconsistent output issue by using simplified mode. The steps required to convert
ex_discrete_time_clto ex_discrete_time_simplare:
1Use strict bus mode. Set Configuration Parameters > Diagnostics > Connectivity >
Mux blocks used to create bus signals to error.
2Set Configuration Parameters > Diagnostics > Data Validity > Underspecified
initialization detection to Simplified.
3 For the Outport blocks Out1 and Out2, set the Source of initial output value parameter
to Input signal. This setting explicitly inherits the initial value, which in this case is 2.
You could also get the same behavior by setting the Source of initial output value
parameter to Dialogand 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.

Sorted Order Can Affect Merge Block Output


The sorted 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.
Basic Example
The ex_basic_merge_sorted_order_1_clmodel has two identical enabled subsystems
(Enable A and Enable B) that connect to a Merge block. When you simulate the model, the
red numbers show the sorted execution order of the blocks.
When you simulate the model, the Scope block looks like this:

The ex_basic_merge_sorted_order_2_clmodel is the same as ex_merge_sorted_1_cl,


except that the block execution order is the reverse of the default execution order.
Changing the execution order involved these steps:
1Open the Properties dialog box for the Enable A subsystem and set the Priority
parameter to 2.
2Set the Priority of the Enable B subsystem to 1.
When you simulate the model with the different execution order, the Scope block looks
like this:

The change in sorted order produces different results from identical conditional
subsystems.
To update the models to use simplified initialization
mode (see ex_basic_merge_sorted_order_1_simpland
‘ex_basic_merge_sorted_order_2_simpl):
1Use strict bus mode. Set Configuration Parameters > Diagnostics > Connectivity >
Mux blocks used to create bus signals to error.
2Set Configuration Parameters > Diagnostics > Data Validity > Underspecified
initialization detection to Simplified.
3For the Merge block, set the Initial output parameter to an initial value of 2.
When you simulate each simplified mode model, both models produce the same results.
Example with Output When Disabled Parameter Set to Reset
The ex_merge_sorted_1_clmodel has two identical enabled subsystems (Enable A and
Enable B) that connect to a Merge block. When you simulate the model, the red numbers
show the sorted execution order of the blocks.

When you simulate the model, the Scope block looks like this:
The ex_merge_sorted_2_clmodel is the same as ex_merge_sorted_1_cl, except that the
block execution order is the reverse of the default execution order. Changing the execution
order involved these steps:
1Open 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.

When you simulate the model with the different execution order, the Scope block looks
like this:

The change in sorted order produces different


results from identical conditional subsystems.
To update the models to use simplified initialization mode (see
ex_merge_sorted_1_simpland ex_merge_sorted_2_simpl):
1Use strict bus mode. Set Configuration Parameters > Diagnostics > Connectivity >
Mux blocks used to create bus signals to error.
2Set Configuration Parameters > Diagnostics > Data Validity > Underspecified
initialization detection to Simplified.
3For the Outport blocks in Enable A and Enable B, set the Output when disabled
parameter to held. Simplified mode does not support reset.
When you simulate each simplified mode model, both models produce the same results.

Working with Variant Systems


In this section…
“What Are Variants?”
“Variant Controls and Active Variants” “How Simulink Represents Variants” “Workflow
for Implementing Variants”

What Are Variants?

Variants represent the different choices within a graphical model and enable you to specify
multiple configurations in a single unified block diagram and also switch
programmatically between them prior to model simulation.
For example, suppose a design engineer has a model that simulates an automobile.
Different models of an automobile can have many similarities yet differ in specific ways
such as fuel usage, engine size, or emission standards. Each implementation of the model
representing a specific automobile model is a variant. Variants are needed to:
• Represent a single model but different configurations.
•Programmatically select one active variant from multiple choices.
•Select one variant amongst available choices irrespective of the variant control (override
variants).
• Optionally, generate code using Simulink Coder with preprocessor conditionals (#if,
#elif, #endif) to enable selection of active variant at compile time.

Variant Controls and Active Variants

The variant control determines which variant is active. It can be a boolean condition
expression or a Simulink.Variantobject specifying the condition expression. During model
compilation the variant controls are evaluated and the variant choice for which the
condition expression evaluates to true becomes the active variant.
Working with Variant Systems

How Simulink Represents Variants

Simulink provides the following blocks to add variants to models:


• Model Variants
- Models as variant choices.
- Each variant has an associated variant control.
• Variant Subsystem
- Subsystems as variant choices.
- Each variant has an associated variant control.

Workflow for Implementing Variants


You can implement variants in your model by using the Model Variants block or the
Variant Subsystem block. The workflow for setting up variants and simulating a model
using the active variants is as follows:
1Create the subsystems or referenced models that you want to use as variants.
2Depending on your application, use the Model Variants block or the Variant Subsystem
block.
3Define a variant control for each variant. The active variant is the variant control that
evaluates to true during model compilation.
4Simulate using the active variant.
5Modify the variant control to select another variant and simulate again.

6(Optional) Depending on your application, you can generate code for the active variant
or for all variants. See “Generate Code for Model Variants” and “Generate Code for
Variant Subsystems”.
7Savethecontrol variables for your variants defined in the base workspace to aMAT file.
See “Exporting Workspace Variables”.

How Variant Controls Work

In this section…
“Create Variant Controls”
“Save Variant Controls”
“Reuse Simulink.Variant Objects” “Use Enumerated Types as Variant Control”
The variant control can be a boolean condition expression, or a Simulink.Variantobject
representing a boolean condition expression. You can define variant controls in the
MATLAB workspace. You can specify the condition expression directly without using
variant objects in the Variant control field of the Variant choices table. For example you
can specify VSS_MODE == 1directly, without creating variant objects.
The condition expression can include:
•Scalar variables
• Simulink.parameterobject with valid data type including enumerated types
•Operators: ==,~=, &&, ||, ~
•Parentheses for grouping
You can programmatically change the active variant by modifying the values of variant
control variables in the base work space, or from the block parameter dialog box, or from
the command line. You can also manually override the variant selection from the Variant
> Override using > variant choicemenu.
For information on selecting and overriding active variants, see “Select the Active Variant
for Simulation”.

Create Variant Controls


•You can define the condition expression as follows:
Variable == Value
For example:
VSS_MODE == 1
•You can define the variant object as follows:
variantObjectName = Simulink.Variant(conditionExpression)
For example:
VSS_NONLINEAR_CONTROLLER = Simulink.Variant (‘VSS_MODE == 1’)
Note You must define the Simulink.Variantobjects every time you simulate the model.
You can create variant controls from the block dialog box using the

Create/edit variant control button on the Variant choices table.


If you want to generate code for your model, you must define the control variables as
Simulink.Parameterobjects. You can define the Simulink.Parameterobject from the Model
Explorer. See “Generate Preprocessor Conditionals for Variant Systems”.

Save Variant Controls

If you want to reload variant control variables in your model, you must save them to a
MAT-file. Right-click the Workspace window, and select Save.

Reuse Simulink.Variant Objects

For example, the models AutoMRVarand AutoSSVar, highlight only the current active
variant (the inactive choice is greyed out). If you want to reuse some common conditions
for multiple variant choices, it can be accomplished using Simulink.Variantobjects.
Reusing variant objects, allows you to globally re-configure the model hierarchy to suit
different environments by changing only the variant control values. No matter how many
simulation environments you define, selecting an environment requires only setting a
variable or parameter value appropriately.

Use Enumerated Types as Variant Control

You can use enumerated types to give meaningful names to the integers that you use as
variant control values. For more information about defining and using enumerated types,
see “About Simulink Enumerations”.
For example, for the sldemo_mdlref_variants_enummodel, we have the following classes
defined:
classdef sldemo_mrv_CONTROLLER_TYPE < Simulink.IntEnumType enumeration
NONLINEAR (1)
SECOND_ORDER (2)
end
end
classdef sldemo_mrv_BUILD_TYPE < Simulink.IntEnumType enumeration
PROTOTYPE (1)
PRODUCTION (2)
end
end
The variant objects defined for the above classes are as follows:
VE_NONLINEAR_CONTROLLER = Simulink.Variant…
(‘E_CTRL==sldemo_mrv_CONTROLLER_TYPE.NONLINEAR’)
VE_SECOND_ORDER_CONTROLLER =Simulink.Variant…
(‘E_CTRL==sldemo_mrv_CONTROLLER_TYPE.SECOND_ORDER’)
VE_PROTOTYPE =Simulink.Variant…
(‘E_CURRENT_BUILD==sldemo_mrv_BUILD_TYPE.PROTOTYPE’)
VE_PRODUCTION =Simulink.Variant…
(‘E_CURRENT_BUILD==sldemo_mrv_BUILD_TYPE.PRODUCTION’)
For example, for the sldemo_mdlref_variants_enummodel, we have the following classes
defined:
classdef sldemo_vss_BUILD_TYPE < Simulink.IntEnumType enumeration
PROTOTYPE (1) PRODUCTION (2)
end
end
classdef sldemo_vss_CONTROLLER_TYPE < Simulink.IntEnumType enumeration
NONLINEAR (1)
SECOND_ORDER (2)
end
end
The variant objects defined for the above classes are as follows:
VSSE_NONLINEAR_CONTROLLER = Simulink.Variant…
(‘VSSE_MODE==sldemo_vss_CONTROLLER_TYPE.NONLINEAR’)
VSSE_SECOND_ORDER_CONTROLLER =Simulink.Variant…
(‘VSSE_MODE==sldemo_vss_CONTROLLER_TYPE.SECOND_ORDER’)
VSSE_PROTOTYPE =Simulink.Variant…
(‘VSSE_CURRENT_BUILD==sldemo_vss_BUILD_TYPE.PROTOTYPE’)
VSSE_PRODUCTION =Simulink.Variant…
(‘VSSE_CURRENT_BUILD==sldemo_vss_BUILD_TYPE.PRODUCTION’)
The variant objects are defined in the MATLAB workspace.
Using enumerated types, makes the generated code easy to read since it contains the
names of the values rather than integers.

Set Up Model Variants

In this section…
“Configure the Model Variants Block” “Disable and Enable Model Variants”
“Parameterize Model Variants” “Additional Examples”
Thefigureshowstheexamplemodel AutoMRVar. You can also open the model from the
MATLAB prompt as follows:
addpath([docroot ‘/toolbox/simulink/ug/examples/variants/mdlref/’]); open(‘AutoMRVar’);

Notice:
•The symbol

appears in the lower-left corner of the block to indicate that it uses variants. Also, the
outline of model variant block depends on the simulation mode.
•The name of the variant that was active the last time you saved the model appears on the
block.
• When you change the active variant, the variant block automatically refreshes. Its name
changes to reflect the current active variant.
•When you open the example model, the load function loads a MAT-file that populates the
base workspace with the variables and objects used by the model.
The example implements the following application:
•The automobile can either use a diesel or a gasoline engine.
•Each engine must meet either the European or American (USA) emission standard.
AutoMRVar implements the automobile application using the Model Variants block,
named Engine.The Engineblock specifies four referenced models. Each referenced model
represents one permutation of engine fuel and emission standards. The variant choices are
as follows:
Model Name GasolUSA
GasolEuro
DieselUSA
DieselEuro
Variant Control Condition (read only) GU FUEL==1 && EMIS==1
GE FUEL==1 && EMIS==2
DU FUEL==2 && EMIS==1
DE FUEL==2 && EMIS==2
Note You can also use condition expressions directly in the Variant control field and do
not require to create Simulink.Variantobjects.

Configure the Model Variants Block

You can configure a Model Variants block and specify your variant choices as follows:
1Open a new empty model.
2From the Simulink Library Browser, Ports and Subsystems library add a Model
Variants block to the model.
3 Right-click the Model Variants block and select Block Parameters (ModelReference)
from the menu. The Model Variants block parameters dialog box opens.
4Specify the model choices in the Model name column of the Variant choices table. To
specify a protected model, use the extension .slxpor .mdlp. For more information, see
“Protected Model”.
5 Specify the variant control in the Variant control column for each model choices. The
variant control can be a boolean condition expression or a Simulink.Variantobject
representing a boolean condition expression. Note You cannot have the variant control
column empty for any of the choices, or comment out (%) variant control values for
Model Variants block, however for Variant Subsystem blocks, you can comment out
variant choices.
For more information on variant controls, see “How Variant Controls Work”.
6Click the

Create/Edit selected variant button to edit the condition which determines the active
variant choice, and in the dialog box enter the condition:
7(Optional) Specify the model arguments and the Simulation mode. All simulation
modes work with model variants. For more information, see “Parameterize Model
Variants” and “Referenced Model Simulation Modes”.
8Click the

variant choices. Add a new variant button, if you want to add more
A new row appears below the other variant choices. 9Repeat the previous steps until you
have specified all your referenced models and their associated variant controls. For
information on the other buttons, see the Model Variants block page.
10Click OK after you have added all your variant choices to close the dialog box.
The figure shows the dialog box after adding all your variant choices.

For next steps, see “Select the Active Variant for Simulation”.

Disable and Enable Model Variants


You can disable model variants without losing your variant settings. After you enable
variants, it remains enabled until you explicitly disable variants. You can close and reopen
the Model Variants block without affecting the variant specification.
To disable variants from a Model Variants block:
1Right-click the block and select Block Parameters (ModelReference) to open the block
parameters dialog box.
2Click Disable Variants button.
Disabling variants:
•Hides and ignores the content of the Variant choices section of the dialog box.
•Retains the active variant as the model name.
•Ignores subsequent changes to variant control variables and other models, other than the
current model.
If you decide to re-enable variants later, select the Enable Variants button. The Model
Variants block selects an active variant according to the current base workspace variables
and conditions.

Parameterize Model Variants

If you want, you can apply a parameter to a variant control. Values are the same as for any
referenced model (see “Parameterize Model References” ).
1Selectthe row in the Variant choices table for the variant control, you want to
parameterize.
2Specify the parameter in the Model argument values (for this instance) field.
3Click Apply. Repeat the above steps for each parameter you want to parameterize.

Additional Examples

For additional examples select Simulink > Examples > Modeling Features > Model
Reference > Model Reference Variants in the help browser.
• The example sldemo_mdlref_variantsshows a model variant.
•The example sldemo_mdlref_variants_enumshows a model variant that uses enumerated
data type.

Set Up Variant Subsystems

In this section…
“Configure the Variant Subsystem Block” “Disable or Enable Subsystem Variants”
“Additional Example”
Thefigureshowstheexamplemodel AutoSSVar. You can also open the model from the
MATLAB prompt as follows:
addpath([docroot ‘/toolbox/simulink/ug/examples/variants/mdlref/’]); open(‘AutoSSVar’);
•The symbol

appears in the lower-left corner of the block to indicate that


variants is enabled.
•The name of the variant that was active appears on the block.
•When you change the active variant, the variant block name changes.
• When you open the example model, a callback function loads a MAT-file that populates
the base workspace with the variables, the model uses. The base workspace contains the
variant control variables.

The example model, AutoSSVar, implements the automobile models using a Variant
Subsystem block, named Engine.The Engineblock consists of a set of four subsystem
blocks. Each subsystem represents one permutation of engine fuel and emission standards.
The example shows the use of variants for the following cases:
•The automobile can either use a diesel or a gasoline engine.
• Each engine must meet either the European or American (USA) emission standard.
Double-click the Model Variant block, Engine,toviewthe subsystems.
The only blocks allowed in the Variant Subsystem block diagram are Inport, Outport, and
Subsystem. The subsystem diagram for a Variant Subsystem block has no connections.
The variant choices are as follows:
Name (read-only) Variant control DieselEuro DE
DieselUSA DU
GasolEuro GE
GasolUSA GU
Condition (read-only) FUEL==2 && EMIS==2
FUEL==2 && EMIS==1
FUEL==1 && EMIS==2
FUEL==1 && EMIS==1
Note You can also use condition expressions directly in the Variant control field and do
not require to create Simulink.Variantobjects.

Configure the Variant Subsystem Block

To configure a Variant Subsystem block and specify your variants, do the following:
1Open a new model.
2From the Simulink Library Browser, Ports and Subsystems library add a Variant
Subsystem block to the model.
3Double-click the Variant Subsystem block to expand it.
4Drag Subsystems blocks from the Simulink Library Browser to the model, that you
want as variant choices.
5Right-click the Variant Subsystem block and select Block Parameters (Subsystem).
The block parameters dialog box for the Variant Subsystem appears. The names of the
subsystem blocks that was added as variant choices in step 4 appear on the Name (read-
only) column of the Variant choices table.
6 For each variant choice add the variant control values in the Variant control column. If
the variable is a Simulink.Variantobject, you must first define the variant object in the
MATLAB workspace. If you want to use a condition expression, then you can directly
type it in the Variant control column.
For more information on creating variant controls see, “How Variant Controls Work”.
7Ifyouwanttoeditavariantcontrolwhichisa Simulink.Variantobject, click the

Create/Edit selected variant object button and use the dialog box. The

Create/Edit selected variant object button is disabled for condition expressions.


8Click Apply to apply the changes.

Disable or Enable Subsystem Variants

You can disable subsystem variants as follows:


1In the Variant choices table, double-click the name of the variant control you want to
comment out.
2Add %to the beginning of the variant control name.
3Apply your changes.
To enable the subsystem variant again, remove the %symbol. You can choose to keep the
Variant control field empty.
You can also override variants and make a specific variant always the active choice. See
“Select the Active Variant for Simulation”
.

Additional Example

For additional examples select Simulink > Examples > Modeling Features >
Subsystems > Variant Subsystems in the Help Browser.
The example sldemo_variant_subsystemsshows a variant subsystem. Convert Subsystem
Blocks to Variant Subsystem Blocks

Convert Subsystem Blocks to Variant Subsystem Blocks

You can convert both normal Subsystem blocks and Configurable Subsystems blocks (see
Configurable Subsystem) to Variant Subsystem block.
To convert a normal Subsystem block to a Variant Subsystem block do the following:
•Right-click the block and select Subsystem & Model Reference > Convert Subsystem
to > Variant Subsystem.
Converting the Subsystem block to a Variant Subsystem in a model does the following:
•Creates a Variant Subsystem block in place of the Subsystem block with all the
connections to the ports in place.
•Adds the original subsystem as a variant choice in the new Variant Subsystem block.
•Overrides the Variant Subsystem block to use the subsystem that was originally the active
choice.
•Preserves the link to the library and adds the linked subsystem as a variant choice, for
linked subsystems.
•Preserves the mask on subsystem blocks and copies it to the variant choice.

Select the Active Variant for Simulation


In this section…
“Set the Active Variant”
“Override Variants”
“Ignore Variant Choices”
“Open the Active Variant”

Set the Active Variant

At the MATLAB command line set the variant control variable to the variant choice you
want to make active. For example, in the model sldemo_variant_subsystems,set
VSS_MODE=2to make the Second-Order Controller the active variant.
Note When you change the active variant, the block display automatically refreshes. You
are not required to update the diagram (Ctrl + D), to reflect the change in active variant.
The blocks that are part of the inactive choice appear greyed out.

Override Variants

•Right-click the block and select Variant > Override using > variant choice. For
example:

• On the block parameter dialog box, select the Override variant conditions and use the
following variant check box. Then select the variant you want to set as the active variant
as the Variant value.
Select the Active Variant for Simulation
Use the set_paramcommand to override the active variant as shown in the following
example.
For example, to make the variant choice VSS_NONLINEAR_CONTROLLERactive:
set_param(gcb, ‘OverrideUsingVariant’,‘VSS_NONLINEAR_CONTROLLER’)

Ignore Variant Choices


Variant control names which are either empty or commented (starts with a %) are ignored
in selecting active variants.

Open the Active Variant

When you open a model, variant blocks display the name of the variant that was active the
last time the model was saved. You can use the Variant menu to open the active variant.
Right-click the block and select Variant > Open > (active variant).
To find the current active variant, enter the following at the command line:
get_param(gcb, ‘ActiveVariant’)
To find the path to the current active variant block, enter the following at the command
line:
get_param(gcb, ‘ActiveVariantBlock’)
Note The ActiveVariantBlockparameter is supported only for the Variant Subsystem
block.

You might also like