Matlab Simulink
Matlab 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
To start the Simulink software, first start the MATLAB®technical computing environment.
For details about starting MATLAB, see “Startup and Shutdown”.
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 a Model
In this section…
“What Happens When You Open a Model” “OpenanExistingModel”
“Models with Different Character Encodings” “Avoid Initial Model Open Delay”
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”
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”.
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’)
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”
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
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.
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.
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.
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”.
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.
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
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
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
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.
)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
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.
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
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”
Systems to Print
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”.
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]’)
Printing Limitations
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.
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.
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
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
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
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.
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”
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
debugging session.
Step through
simulation by major
steps.
Monitor single block
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”.)
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.
, 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”.
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”.
one or more times to step backward to the previously stepped simulation snapshot.
The scope updates to reflect the step back.
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
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”
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”).
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.
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.
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”
In this section…
“About Model Referencing” “Referenced Model Advantages” “Masking Model Blocks”
“Models That Use Model Referencing” “Model Referencing Resources”
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.
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”.
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”.
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” .
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” .
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
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”.
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”
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.
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.
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”
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.
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.
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” .
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”.
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.
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.
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.
In this section…
“About Model Referencing Requirements” “Name Length Requirement”
“Configuration Parameter Requirements” “Model Structure Requirements”
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.
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”.
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”.
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:
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”
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.
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” .
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:
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”
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”.
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”.
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”
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).
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.
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”
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”.
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.
Protected 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
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
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
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.
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.
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”
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.
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.
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.
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.
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”
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”.
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.
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.
In this section…
“What Are Action Subsystems?”
“Set States when an Action Subsystem Executes”
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.
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.
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”
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.
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.
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.
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.
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”
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).
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.
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.
In this section…
“Why Initialize Conditional Subsystem Output?” “Initialization Mode”
“Simplified Mode Benefits”
“Simplified Mode Behavior”
“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”.
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”
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.
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 (
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”
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” .
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.
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:
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.
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
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”.
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”.
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.
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.
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.
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.
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”.
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.
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
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.
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
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
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.
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’)
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.