Support Articles

Support Articles Modelling and Simulation Initialising Simulink Model Parameter Variables using Callbacks

Initialising Simulink Model Parameter Variables using Callbacks

In this article, we examine how to use Simulink callbacks to ensure that models with MATLAB workspace parameters run correctly when shared with other users.

Contents

 

Simulink is a powerful graphical modelling and simulation tool that is tightly coupled with the MATLAB technical computing environment. This coupling allows you, for example, to perform Monte Carlo simulations on your Simulink models, to determine the effect of parameter variations in your system. One way to achieve a Monte Carlo simulation is to parameterise your model, using variables in place of constants in some of the model parameters. Those variables can then be changed in the MATLAB base workspace, and the simulation run from a MATLAB m-file, or using a tool such as the Simulink Response Optimizer.

Users often face problems when sharing such models, because variables need to be created in the MATLAB workspace before the model can be successfully run. Thus, if those modelsare run without the variables being created, errors are displayed from Simulink. It is also difficult to "freeze" a set of parameters that are "good", for repeated use.

Fortunately, Simulink provides a mechanism to deal with this problem. We will explore this mechanism, called callbacks, in this article.

A Simple Simulink Model

The following Simulink model is an extremely simple model with a parameterised gain block. The gain parameter is defined as a.

clear all
open_system('testFcns.mdl');

This simulation runs for 1 second, and computes the result of the constant block (5) multiplied by a.

If we try to run this model without creating a in the MATLAB workspace, an error will be generated. We will catch the error using the following code:

try
  sim('testFcns.mdl');
  disp('Success:');
  disp(yout(end));
catch
  errStruct = sllasterror;
  disp('Error message:');
  disp(errStruct.Message);
end

 

Error message:
Error evaluating parameter 'Gain' in 'testFcns/Gain': Error using ==> sim
Undefined function or variable 'a'

This would happen to a user if they tried to load and run this model without first defining a in the MATLAB workspace. If we now define a, we will be able to run the simulation and view the results of the simulation.

a = 2;
sim('testFcns.mdl');
disp(yout(end))

10

From the output, we see that this result is 10. If we change the value of a, we can run the model again without changing any of the model's parameters.

a = 3;
sim('testFcns.mdl');
disp(yout(end));

15

Setting Initial Parameter Values: Callback Functions

All Simulink models have a set of properties known as callback functions. A callback function is a string, or a function handle, that defines MATLAB code to be run when a particular event occurs in a model. You can think of a callback function as a way of customising Simulink's behaviour for a particular model.

In our example, we would like the model to run without the user having to specify the value of a. Of course, we parameterised the model so that a could be changed, so we do not want to change the model to use a fixed gain value rather than a. Instead, we will use a callback function to pre-define a for the user.

Types of Callback Functions

Simulink provides support for the following callback functions:

  • PreLoadFcn: This function is called immediately prior to a model being loaded.
  • PostLoadFcn: This function is called immediately AFTER a model is loaded.
  • InitFcn: This function is called each time the model is initialised.
  • StartFcn: This function is called when a model starts executing.
  • StopFcn: This function is called when a model stops executing.
  • PreSaveFcn: This function is called before a model is saved.
  • PostSaveFcn: This function is called after a model is saved.
  • CloseFcn: This functions is called when a model is closed.

 

NOTE: There are additional callback functions available for the model, and for each individual block in a model. For more information, consult the Simulink help, in the section titled "Model and Block Parameters".

Accessing Callback Functions

You can view callback functions using m-code (shown here) or using a dialog.

The easiest way to view and edit dialogs is with the Model properties dialog. Select the File menu from your model, then choose Model properties and click on the Callbacks tab. Common model callbacks are shown in the left-hand panel, with their corresponding callback in the right-hand panel.

To view and edit callbacks from an m-file, or from the command-line, use the get_param and set_param commands.

Example: Setting the PostLoadFcn

This example uses the set_param command to set the PostLoadFcn to initialise a to 1.

set_param('testFcns', 'PostLoadFcn', 'a=1;');
save_system('testFcns', 'testFcns1');
close_system('testFcns1');

The model is now saved with the defined PostLoadFcn as testFcns1.mdl. If we repeat the code from above, we will be able to run the simulation without generating an error. Note how the variable a is automatically created for us when the model is loaded:

clear all
open_system('testFcns1.mdl');
whos

Name Size Bytes Class
a 1x1 8 double array

 

Grand total is 1 element using 8 bytes

try
  sim('testFcns1.mdl');
  disp('Success:');
  disp(yout(end));
catch
  errStruct = sllasterror;
  disp('Error message:');
  disp(errStruct.Message);
end

 

Success:
5

Choosing the Right Callback Function

We have shown how to use a callback to define a parameter that is initialised during loading. However, with 8 different callbacks to choose from, it is often difficult to decide which callback to use. The following guidelines will help you to understand which callback function to use.

  • PreLoadFcn: Use this function when your variables must exist before the model is loaded. For example, if you have a variable that defines which signal or signals to choose in a Bus Selector block, that variable must exist before Simulink loads that model.
  • PostLoadFcn: This is the most common callback that is used to initialise parameters in a model. However, this callback is only ever executed when the model loads. Be aware that if you use the clear command to clear the MATLAB workspace, variables created in the PostLoadFcn callback will also be cleared, which means that your model will no longer run.
  • InitFcn: Use this callback function if a variable is a function of other parameters in the model, and the user is not allowed to change that relationship. This function is called even when you update a model (using Ctrl-D or the Update diagram option from the Edit menu.
  • StartFcn: This function is called each time a model starts running. Use this callback if you want to log the time that a model starts, or want to initialise some external device or application only when a model is executing.
  • StopFcn: use this callback function to log results to a history, or to provide post-processing of the model outputs. For an example that uses the StopFcn for visualisation, see the toilet demo.
  • PreSaveFcn: Use this callback to update version information, or to take some other action in the model before saving (for example, you could modiyfying key parameters if you wanted to share a model but not the parameters, in order to protect your intellectual property).
  • PostSaveFcn: Use this to reset parameters after saving a model, or to log a history of save activity.
  • CloseFcn: Use this to clean up any parameters used by the model that you do not want when the model does not exist.

Example: All Callback Functions

To show the difference between callback functions, the model showcallbacks.mdl has each callback set to display the callback name when it is executed. In other words, each callback is set to disp('CallbackName')

We will show what happens when you load the model, update the model, run the model, save the model and close the model.

Load the model:

open_system('showcallbacks.mdl');

PreLoadFcn
PostLoadFcn

Update the diagram:

set_param('showcallbacks', 'SimulationCommand', 'update');

InitFcn

Run the model:

sim('showcallbacks');

InitFcn
StartFcn
StopFcn

Save the model:

save_system('showcallbacks');

PreSaveFcn
PostSaveFcn

Close the model:

close_system('showcallbacks');

CloseFcn

Conclusion

You can use parameters in your model to enhance the usefulness of your model, and to compute model parameters at run-time, based on other variables in the MATLAB workspace. By using model callbacks, you can initialise those values to default or known values when you load the model, or when you start the simulation.

Using callback functions, you can also perform custom post-processing of simulation results, or ensure that your models take specific actions before and after saving, or when closing the model.

Note that blocks also have callback functions that you can use to customise the behaviour of the block. For example, each block has an OpenFcn callback that is execute when the user "opens" the block. Some Blocksets use specific OpenFcn callbacks to implement blockset-specific dialogs, for example.