Share and Reuse Block Parameter Values by Creating Variables
To set a block parameter value, such as theGainparameter of aGainblock, you can use numeric variables that you create and store in workspaces such as the base workspace, a model workspace, or a Simulink®data dictionary. You can use the variable to set multiple parameter values in multiple blocks, including blocks in different models. To change the values of the block parameters, you change the value of the variable in the workspace.
使用一个变量设置一块参数值so enables you to:
Change the parameter value without having to modify the model file (if you store the variable outside the model workspace).
Identify the parameter by a specific, meaningful name when sweeping or tuning the value.
For basic information about setting block parameter values, seeSet Block Parameter Values.
Reuse Parameter Values in Multiple Blocks and Models
You can create a numeric MATLAB®variable in a workspace, such as the base workspace or a data dictionary, and use it to specify one or more block parameter values.
The example modelsldemo_fuelsys
代表gasolin的加油系统e engine. A subsystem in the model,feedforward_fuel_rate
, calculates the fuel demand of the engine by using the constant number14.6
, which represents the ideal (stoichiometric) ratio of air to fuel that the engine consumes. Two blocks in the subsystem use the number to set the values of parameters. In this example, to share the number between the blocks, you create a variable namedmyParam
.
Open the model.
sldemo_fuelsys
In the model, selectView>Model Data Editor. In the Model Data Editor, inspect theParameterstab.
In the model, navigate into the subsystem.
open_system(...'sldemo_fuelsys/fuel_rate_control/fuel_calc/feedforward_fuel_rate')
In the Model Data Editor, in theFilter contentsbox, enter
14.6
.The data table contains two rows, which correspond to theConstant valueparameters of two of theConstantblocks in the subsystem.
Use theValuecolumn to replace the literal number
14.6
withmyParam
. Perform the replacement for both parameters.In theFilter contentsbox, enter
myParam
.While editing the value of one of the parameters, click the action button
and selectCreate.
In theCreate New Datadialog box, setValueto
14.6
and clickCreate.The variable,
myParam
, appears in the base workspace.
Because the variable exists in the base workspace, you can use it in multiple models. However, when you end your MATLAB session, you lose the contents of the base workspace. Consider permanently storing the variable in a model workspace or data dictionary.
Define a System Constant
To define a system constant, such as a variable that represents the radius of the Earth, consider creating aSimulink.Parameter
object instead of a numeric MATLAB variable. Parameter objects allow you to specify physical units and custom documentation as well as other characteristics.
To create and use parameter objects in models, seeData Objects.
Typically, the value of a system constant influences the values of other parameters and signals through mathematical relationships. To model these relationships explicitly, set the values of the dependent data by using expressions. SeeSet Variable Value by Using a Mathematical Expression.
Set Variable Value by Using a Mathematical Expression
You can set the value of a variable to an expression involving literal numbers and other variables. With expressions, you can:
Express the value as a relationship between known physical constants instead of as an unidentifiable literal number.
Explicitly model algebraic dependencies between parameter data. When you change the values of independent data, you do not need to remember to adjust the values of dependent data.
General Technique
Convert the variable to aSimulink.Parameter
object. Then, set theValue
property of the object by using an expression:
Interactively — For example, with the Model Data Editor or the Model Explorer, precede the expression with an equals sign,
=
. The figure shows how to specify the expressionmyVar + myOtherVar
.Programmatically — Use the
slexpr
function, specifying the expression in a character vector or string. For example, to set the value of a parameter object namedmyParam
to the expressionmyVar + myOtherVar
:myParam.Value = slexpr('myVar + myOtherVar')
Explicitly Model Algebraic Relationship Between Variables
The examplesldemo_metro
(seeExploring the Solver Jacobian Structure of a Model) models a system of three identical, pointlike metronomes suspended from a moving platform. Blocks in the model use these MATLAB variables from the base workspace:
m
— Mass of each metronome, initial value 0.1 kgr
— Length of each metronome, initial value 1.0 mJ
— Moment of inertia of each metronome, initial value 0.1 kg/m2
These variables share an algebraic relationship: the moment of inertia of each metronome is equal to the mass times the length squared. In this example, you record this relationship in the value ofJ
.
Open the model.
sldemo_metro
Update the block diagram. A model callback creates the variables in the base workspace.
To prevent the callback from overwriting changes that you make to the variables, for this example, remove the callback code.
set_param('sldemo_metro','InitFcn','')
In the model, selectView>Model Data Editor.
On the Model Data EditorParameterstab, activate theChange scopebutton.
The blocks that use the variables are in the subsystems, so you must configure the Model Data Editor to show data in subsystems.
Click theShow/refresh additional informationbutton.
The data table contains rows that correspond to the variables in the base workspace.
In theFilter contentsbox, enter
J
.In the data table, find the row that corresponds to
J
. In theValuecolumn, set the value of the variable toSimulink.Parameter(J)
.Simulink converts
J
to aSimulink.Parameter
object.In theValuecolumn, set the value of the parameter object to
=m*r^2
.Optionally, simulate the model with different metronome masses and lengths. As you change the values of
m
andr
, you do not have to remember to correct the value ofJ
.
Limitations and Considerations for Other Modeling Goals
If the expression contains fixed-point data or data of an enumerated type, the expression can operate on only one variable or object.
You cannot set the data type (
DataType
property) of the parameter object that uses the expression toauto
(the default) and set the data types of parameter objects that appear in the expression to a value other thanauto
. For example, in the expressionJ = m*r^2
, you cannot set the data type ofJ
toauto
and the data types ofm
andr
tosingle
.To retain the benefits of
auto
(described inContext-Sensitive Data Typing) for the object that uses the expression, set the data types of the objects in the expression toauto
. In other words, useauto
for all of the involved objects. The objects in the expression acquire the same data type as the object that uses the expression.To use a value other than
auto
for an object that appears in the expression, set the data types of all dependent parameter objects to a value other thanauto
. In other words, do not useauto
for any involved objects.You must use the same data type for all objects used in the expression.
If you haveSimulink Coder™and Embedded Coder®初始化一个许可证,您可以生成代码global variable by using the expression. However, the code generator can preserve the expression only if it conforms to certain requirements. SeeExpression Preservation(Simulink Coder).
Control Scope of Parameter Values
Thescopeof a variable is the set of models and blocks that can use the variable. For example, variables that you create in the base workspace have global scope because all blocks in all open models can use the variables. Variables that you store in a model workspace have limited scope because only the blocks in the host model can use the variables.
You cannot create two variables that have the same name in the same scope. Controlling the scope of a variable helps you to avoid name conflicts and establish clear ownership of the variable.
The table describes the different ways that you can control the scope of a reusable parameter value.
Scope | Technique |
---|---|
All open models | Create a variable in the base workspace. |
One or more targeted models | Create a variable in a data dictionary. To reuse the variable in multiple models, create a referenced dictionary. SeeWhat Is a Data Dictionary? |
One model, including all subsystems in the model | Create a variable in the model workspace. SeeModel Workspaces. |
Multiple blocks inside a subsystem, including blocks in nested subsystems | Mask the subsystem and create a mask parameter instead of a workspace variable. To prevent blocks inside a subsystem from using workspace variables, in the subsystem block dialog box, setPermit Hierarchical Resolutionto For information about subsystems, seeSubsystem. For information about masking, seeMasking Fundamentals. |
To avoid name conflicts when you have a large model with many variables in the same scope, consider packaging the variables into a single structure. For more information, seeOrganize Related Block Parameter Definitions in Structures.
For basic information about how blocks use the variable names that you specify, seeSymbol Resolution.
Permanently Store Workspace Variables
Variables that you create in the base workspace do not persist between MATLAB sessions. However, you can store the variables in a MAT-file or script file, and load the file whenever you open the model using a model callback. A modelcallbackis a set of commands that Simulink executes when you interact with a model in a particular way, such as opening the model. You can use a callback to load variables when you open the model. Use this technique to store variables while you learn about Simulink and experiment with models.
In a model that contains aGainblock, set the value of theGainparameter to
K
.At the command prompt, create a variable
K
in the base workspace.K = 27;
In the Workspace browser, right-click the variable and selectSave As.
To save multiple variables in one file, select all of the target variables in the Workspace browser, and then right-click any of the selected variables.
In the dialog box, setSave as typeto
MATLAB Script
. SetFile nametoloadvar
and clickSave.The script file
loadvar.m
appears in your current folder. You can open the file to view the command that creates the variableK
.In the model, selectFile>Model Properties>Model Properties.
In theCallbackstab of the Model Properties dialog box, select
PreLoadFcn
as the callback that you want to define. In the模型预先加载函数pane, enterloadvar
and clickOK.Save the model.
The next time that you open the model, thePreloadFcn
callback loads the variableK
into the base workspace. You can also save the variable to a MAT-file, for exampleloadvar.mat
, and set the model callback toload loadvar
.
To learn about callbacks, seeCallbacks for Customized Model BehaviorandCallbacks for Customized Model Behavior. To programmatically define a callback for loading variables, seeProgrammatically Store Workspace Variables for a Model.
When you save variables to a file, you must save the changes that you make to the variables during your MATLAB session. To permanently store variables for a model, consider using a model workspace or a data dictionary instead of a MAT-file or script file. For more information about permanently storing variables, seeDetermine Where to Store Variables and Objects for Simulink Models.
Programmatically Store Workspace Variables for a Model
In the example above, you define a model callback that creates variables when you open a model. You can programmatically save the variable and set the model callback.
At the command prompt, create the variable
K
in the base workspace.K = 27;
Save the variable to a new script file named
loadvar.m
.matlab.io.saveVariablesToScript('loadvar.m','K')
Set the model callback to load the script file.
set_param('mymodel','PreloadFcn','loadvar')
Save the model.
save_system('myModel')
The functionmatlab.io.saveVariablesToScript
保存变量代币t file. To save variables to a MAT-file, use the functionsave
. To programmatically set model properties such as callbacks, use the functionset_param
.
Manage and Edit Workspace Variables
When you use variables to set block parameter values, you store the variables in a workspace or data dictionary. You can use the command prompt, the Model Explorer, and the Model Data Editor to create, move, copy, and edit variables. You can also determine where a variable is used in a model, list all of the variables that a model uses, and list all of the variables that a model does not use. For more information, seeCreate, Edit, and Manage Workspace Variables.
Package Shared Breakpoint and Table Data for Lookup Tables
To share breakpoint vectors or table data between multiplen-D Lookup Table,Prelookup, andInterpolation Using Prelookupblocks, consider storing the data inSimulink.LookupTable
andSimulink.Breakpoint
objects instead of MATLAB variables orSimulink.Parameter
objects. This technique improves model readability by clearly identifying the data as parts of a lookup table and explicitly associating breakpoint data with table data.
Store Standalone Lookup Table inSimulink.LookupTable
Object
A standalone lookup table consists of a set of table data and one or more breakpoint vectors. You do not share the table data or any of the breakpoint vectors with other lookup tables.
When you share a standalone lookup table, you use all of the table and breakpoint data together in multiplen-D Lookup Tableblocks. To store this data in aSimulink.LookupTable
object:
Create the object in a workspace or data dictionary. For example, at the command prompt, enter:
myLUTObj = Simulink.LookupTable;
Use the properties of the object to store the values of the table and breakpoint data.
Use the properties of the object to configure a unique name for the structure type in the generated code. In the property dialog box, underStruct Type definition, specifyName.
In then-D Lookup Tableblocks, setData specificationto
Lookup table object
.To the right ofData specification, setNameto the name of the
Simulink.LookupTable
object.
For ways to create and configureSimulink.LookupTable
objects, seeSimulink.LookupTable
Store Shared Data inSimulink.LookupTable
andSimulink.Breakpoint
Objects
When you usePrelookupandInterpolation Using Prelookupblocks to more finely control the lookup algorithm, you can share breakpoint vectors and sets of table data. For example, you can share a breakpoint vector between two separate sets of table data. With this separation of the breakpoint data from the table data, you can share individual parts of a lookup table instead of sharing the entire lookup table.
To store breakpoint and table data:
Create a
Simulink.LookupTable
object for each unique set of table data. Create aSimulink.Breakpoint
object for each unique breakpoint vector, including breakpoint vectors that you do not intend to share.Use the properties of the objects to store the values of the table and breakpoint data.
Configure the
Simulink.LookupTable
objects to refer to theSimulink.Breakpoint
objects for breakpoint data. In theSimulink.LookupTable
objects, setSpecificationtoReference
. Specify the names of theSimulink.Breakpoint
objects.In theInterpolation Using Prelookupblocks, setSpecificationto
Lookup table object
. SetNameto the name of aSimulink.LookupTable
object.In thePrelookupblocks, setSpecificationto
Breakpoint object
. SetNameto the name of aSimulink.Breakpoint
object.
The example modelfxpdemo_lookup_shared_param
contains twoPrelookup和两个Interpolation Using Prelookupblocks. Configure the blocks so that each combination of aPrelookupand anInterpolation Using Prelookupblock represents a unique lookup table. Share the breakpoint vector between the two lookup tables. In this case, each lookup table has unique table data but shared breakpoint data.
Open the example model.
In thePrelookupblock dialog box, setSpecificationto
Breakpoint object
. SetNametosharedBkpts
.Click the button
next to the value of theNameparameter. SelectCreate Variable.
In theCreate New Datadialog box, setValueto
Simulink.Breakpoint
and clickCreate.A
Simulink.Breakpoint
object appears in the base workspace.In the property dialog box for
sharedBkpts
, specifyValueas a vector such as[1 2 3 4 5 6 7 8 9 10]
. ClickOK.In thePrelookupblock dialog box, clickOK.
In thePrelookup1block dialog box, setSpecificationto
Breakpoint object
. SetNametosharedBkpts
.In theInterpolation Using Prelookupblock dialog box, setSpecificationto
Lookup table object
. SetNametodataForFirstTable
.Click the button
next to the value of theNameparameter. SelectCreate Variable.
In theCreate New Datadialog box, setValueto
Simulink.LookupTable
and clickCreate.A
Simulink.LookupTable
object appears in the base workspace.In the property dialog box for
dataForFirstTable
, specifyValueas a vector, such as[10 9 8 7 6 5 4 3 2 1]
.SetSpecificationto
Reference
.In the table underSpecification, setNameto
sharedBkpts
and clickOK.In theInterpolation Using Prelookupblock dialog box, clickOK.
Configure theInterpolation Using Prelookup1block to use a
Simulink.LookupTable
object nameddataForSecondTable
. In the object property dialog box, specifyValueas a vector, such as[0 0.5 1 1.5 2 2.5 3 3.5 4 4.5]
. Configure the object to refer tosharedBkpts
for the breakpoint data.
The model now represents two unique lookup tables:
A combination of
sharedBkpts
anddataForFirstTable
.A combination of
sharedBkpts
anddataForSecondTable
.
These lookup tables share the same breakpoint data throughsharedBkpts
.