Main Content

Customize Model Behavior with Callbacks

Callbacks are commands you can define that execute in response to a specific modeling action, such as opening a model or stopping a simulation. Callbacks define MATLAB® expressions that execute when the block diagram or a block is acted upon in a particular way.

Simulink® provides model, block, and port callback parameters that identify specific kinds of model actions. You provide the code for a callback parameter. Simulink executes the callback code when the associated modeling action occurs.

For example, the code that you specify for the PreLoadFcn model callback parameter executes before the model loads. You can provide code for PreLoadFcn that loads the variables that model uses into the MATLAB workspace.

What You Can Do with Callbacks

Callbacks are a powerful way to customize your Simulink model. A callback executes when you perform actions on your model, such as double-clicking a block or starting a simulation. You can use callbacks to execute MATLAB code. You can use model, block, or port callbacks to perform common tasks, for example Automatically Initialize Variables and Load Data.

Types of Callbacks

Simulink provides many types of callbacks, including:

  • Model callbacks — Model callbacks execute at specified action points, for example, after you load or save the model. See Model Callbacks.

  • Block callbacks — Block callbacks execute for block events, such as when a block is loaded, opened, or edited. See Block Callbacks.

  • Block mask callbacks — Block mask callbacks execute when the value of a mask parameter changes. See Initialization and Parameter Callbacks.

  • Port callbacks — A port callback executes every time the connectivity of the corresponding port changes. See Port Callbacks.

  • Annotation callbacks — An annotation can execute a callback when you click the annotation. See Simulink.Annotation.

  • Callback Button block callbacks — The Callback Button block executes a callback when you click the block.

Callback Limitations

Do not call the run command from within model or block callback code. Doing so can result in unexpected behavior such as errors or incorrect results if you load, compile, or simulate a Simulink model.

For limitations of specific callbacks, see their documentation.

Related Topics