Documentation

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.

  1. Open the model.

    sldemo_fuelsys

  2. In the model, selectView>Model Data Editor. In the Model Data Editor, inspect theParameterstab.

  3. In the model, navigate into the subsystem.

    open_system(...'sldemo_fuelsys/fuel_rate_control/fuel_calc/feedforward_fuel_rate')

  4. In the Model Data Editor, in theFilter contentsbox, enter14.6.

    The data table contains two rows, which correspond to theConstant valueparameters of two of theConstantblocks in the subsystem.

  5. Use theValuecolumn to replace the literal number14.6withmyParam. Perform the replacement for both parameters.

  6. In theFilter contentsbox, entermyParam.

  7. While editing the value of one of the parameters, click the action buttonand selectCreate.

  8. In theCreate New Datadialog box, setValueto14.6and 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.Parameterobject 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.Parameterobject. Then, set theValueproperty 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 theslexprfunction, specifying the expression in a character vector or string. For example, to set the value of a parameter object namedmyParamto 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 kg

  • r— Length of each metronome, initial value 1.0 m

  • J— Moment of inertia of each metronome, initial value 0.1 kg/m2

These variables share an algebraic relationship: the moment of inertia of each metronome is equal to the mass times the length squared. In this example, you record this relationship in the value ofJ.

  1. Open the model.

    sldemo_metro

  2. Update the block diagram. A model callback creates the variables in the base workspace.

  3. To prevent the callback from overwriting changes that you make to the variables, for this example, remove the callback code.

    set_param('sldemo_metro','InitFcn','')

  4. In the model, selectView>Model Data Editor.

  5. 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.

  6. Click theShow/refresh additional informationbutton.

    The data table contains rows that correspond to the variables in the base workspace.

  7. In theFilter contentsbox, enterJ.

  8. In the data table, find the row that corresponds toJ. In theValuecolumn, set the value of the variable toSimulink.Parameter(J).

    Simulink convertsJto aSimulink.Parameterobject.

  9. In theValuecolumn, set the value of the parameter object to=m*r^2.

  10. Optionally, simulate the model with different metronome masses and lengths. As you change the values ofmandr, 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 (DataTypeproperty) 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 ofJtoautoand the data types ofmandrtosingle.

    • To retain the benefits ofauto(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, useautofor 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 thanautofor 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 useautofor 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 ResolutiontoNone. This technique allows you to use the same name to create both a variable in a workspace and a mask parameter in the subsystem mask. The blocks in the subsystem can use only the mask parameter.

For information about subsystems, 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.

  1. In a model that contains aGainblock, set the value of theGainparameter toK.

  2. At the command prompt, create a variableKin the base workspace.

    K = 27;

  3. 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.

  4. In the dialog box, setSave as typetoMATLAB Script. SetFile nametoloadvarand clickSave.

    The script fileloadvar.mappears in your current folder. You can open the file to view the command that creates the variableK.

  5. In the model, selectFile>Model Properties>Model Properties.

  6. In theCallbackstab of the Model Properties dialog box, selectPreLoadFcnas the callback that you want to define. In the模型预先加载函数pane, enterloadvarand clickOK.

  7. Save the model.

The next time that you open the model, thePreloadFcncallback loads the variableKinto 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.

  1. At the command prompt, create the variableKin the base workspace.

    K = 27;
  2. Save the variable to a new script file namedloadvar.m.

    matlab.io.saveVariablesToScript('loadvar.m','K')

  3. Set the model callback to load the script file.

    set_param('mymodel','PreloadFcn','loadvar')

  4. Save the model.

    save_system('myModel')

The 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.LookupTableandSimulink.Breakpointobjects instead of MATLAB variables orSimulink.Parameterobjects. 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.LookupTableObject

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.LookupTableobject:

  1. Create the object in a workspace or data dictionary. For example, at the command prompt, enter:

    myLUTObj = Simulink.LookupTable;

  2. Use the properties of the object to store the values of the table and breakpoint data.

  3. Use the properties of the object to configure a unique name for the structure type in the generated code. In the property dialog box, underStruct Type definition, specifyName.

  4. In then-D Lookup Tableblocks, setData specificationtoLookup table object.

  5. To the right ofData specification, setNameto the name of theSimulink.LookupTableobject.

For ways to create and configureSimulink.LookupTableobjects, seeSimulink.LookupTable

Store Shared Data inSimulink.LookupTableandSimulink.BreakpointObjects

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:

  1. Create aSimulink.LookupTableobject for each unique set of table data. Create aSimulink.Breakpointobject for each unique breakpoint vector, including breakpoint vectors that you do not intend to share.

  2. Use the properties of the objects to store the values of the table and breakpoint data.

  3. Configure theSimulink.LookupTableobjects to refer to theSimulink.Breakpointobjects for breakpoint data. In theSimulink.LookupTableobjects, setSpecificationtoReference. Specify the names of theSimulink.Breakpointobjects.

  4. In theInterpolation Using Prelookupblocks, setSpecificationtoLookup table object. SetNameto the name of aSimulink.LookupTableobject.

    In thePrelookupblocks, setSpecificationtoBreakpoint object. SetNameto the name of aSimulink.Breakpointobject.

The example modelfxpdemo_lookup_shared_paramcontains 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.

  1. Open the example model.

  2. In thePrelookupblock dialog box, setSpecificationtoBreakpoint object. SetNametosharedBkpts.

  3. Click the buttonnext to the value of theNameparameter. SelectCreate Variable.

  4. In theCreate New Datadialog box, setValuetoSimulink.Breakpointand clickCreate.

    ASimulink.Breakpointobject appears in the base workspace.

  5. In the property dialog box forsharedBkpts, specifyValueas a vector such as[1 2 3 4 5 6 7 8 9 10]. ClickOK.

  6. In thePrelookupblock dialog box, clickOK.

  7. In thePrelookup1block dialog box, setSpecificationtoBreakpoint object. SetNametosharedBkpts.

  8. In theInterpolation Using Prelookupblock dialog box, setSpecificationtoLookup table object. SetNametodataForFirstTable.

  9. Click the buttonnext to the value of theNameparameter. SelectCreate Variable.

  10. In theCreate New Datadialog box, setValuetoSimulink.LookupTableand clickCreate.

    ASimulink.LookupTableobject appears in the base workspace.

  11. In the property dialog box fordataForFirstTable, specifyValueas a vector, such as[10 9 8 7 6 5 4 3 2 1].

  12. SetSpecificationtoReference.

  13. In the table underSpecification, setNametosharedBkptsand clickOK.

  14. In theInterpolation Using Prelookupblock dialog box, clickOK.

  15. Configure theInterpolation Using Prelookup1block to use aSimulink.LookupTableobject 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 tosharedBkptsfor the breakpoint data.

The model now represents two unique lookup tables:

  • A combination ofsharedBkptsanddataForFirstTable.

  • A combination ofsharedBkptsanddataForSecondTable.

These lookup tables share the same breakpoint data throughsharedBkpts.

Related Topics

Was this topic helpful?