Main Content

MATLAB Function

Include MATLAB code in Simulink models

Libraries:
Simulink / User-Defined Functions
HDL Coder / User-Defined Functions

Description

The MATLAB Function block enables you to write MATLAB® functions that execute in Simulink® models. The MATLAB function executes during simulation at each time step. For more information about integrating MATLAB code into your Simulink models, see Implement MATLAB Functions in Simulink with MATLAB Function Blocks. If you have a Simulink Coder™ license, you can also generate C/C++ code from a MATLAB Function block for a Simulink Coder target.

Double-click the MATLAB Function block to open the MATLAB Function Block Editor, where you write the MATLAB function. You can also define variables, add an input trigger, and create function call outputs by using the Model Explorer or the Symbols pane. For more information, see Create and Define MATLAB Function Block Variables, Manage the Input Trigger of a MATLAB Function Block, and Manage Function Call Outputs of a MATLAB Function Block.

In the Symbols pane, you can declare a block input to be a Simulink parameter instead of a port. The MATLAB Function block also supports inheritance of types and size for inputs, outputs, and parameters. You can specify these properties explicitly. See Define and Modify Variable Data Types, Specify Size of MATLAB Function Block Variables, and Use Data in Multiple MATLAB Function Blocks by Defining Parameter Variables.

When you simulate a model that contains a MATLAB Function block, the software generates binary code or C/C++ MATLAB executable (MEX) code from the block and integrates this code with the model. The MATLAB Function block uses the same infrastructure as MATLAB Coder, which you use to generate C/C++ code from MATLAB code outside of Simulink. Consequentially, the MATLAB Function block code must use MATLAB conventions that are supported for code generation. See Code and Integration Limitations for MATLAB Function Blocks.

To support visualization of data, the MATLAB Function block supports calls to MATLAB functions for simulation only. See Use MATLAB Engine to Execute a Function Call in MATLAB Function Blocks. If you generate code using Simulink Coder, the calls do not appear in the generated code if the function calls do not directly affect the Simulink inputs or outputs.

Examples

expand all

Add a MATLAB Function to your model to modify an input signal.

  1. In the Simulation tab, click Library Browser. Select Simulink > User-Defined Functions. Drag a MATLAB Function block to the Simulink canvas.

  2. Double-click the block to open the MATLAB Function Block Editor. Replace the function body code with the following:

    y = 2*u;
  3. Return to the model by clicking the Up to Parent button . Add a Sine Wave block as the input signal and add a Scope block to capture the input and output of the MATLAB Function block.

    This shows the example model the instructions describe. It attaches a Sine Wave block and a Scope block to a MATLAB Function block you created.

  4. Run the simulation and open the Scope block to see the effects of the code.

Extended Examples

Limitations

  • Although the code for this block attempts to produce exactly the same results as MATLAB, differences might occur due to rounding errors. These numerical differences, which might be a few eps initially, can magnify after repeated operations. Reliance on the behavior of nan is not recommended. Different C compilers can yield different results for the same computation.

  • Recursive calls are not allowed in MATLAB Function blocks.

Ports

Input

expand all

Input port that corresponds to the input variables in the MATLAB code of the function. Each input variable has an associated port that uses the name of the variable.

You cannot pass data types supported by MATLAB but not supported by Simulink between the Simulink model and the function in the MATLAB Function block. You can use these data types in the MATLAB Function block.

For more information on fixed-point data type support for this block, see Fixed-Point Data Types with MATLAB Function Block (Fixed-Point Designer) and Data Type Override with MATLAB Function Block (Fixed-Point Designer).

Dependencies

To create input ports, open the block and create input variables in the Symbols pane. See Create and Define MATLAB Function Block Variables.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | Boolean | string | fixed point | enumerated | bus

Output

expand all

Output port that corresponds to the output variables in the MATLAB code in the function. Each output variable has an associated port that uses the name of the variable.

Dependencies

To create output ports, open the block and create output variables in the Symbols pane. See Create and Define MATLAB Function Block Variables.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | Boolean | string | fixed point | enumerated | bus

Parameters

expand all

To edit block parameters interactively, use the Property Inspector. From the Simulink Toolstrip, on the Simulation tab, in the Prepare gallery, select Property Inspector.

Note

MATLAB Function blocks also have Subsystem block parameters that you can access by right-clicking the block and clicking Block Parameters (Subsystem). However, updating these block parameters is not recommended.

Specify the method for activating the MATLAB Function block as one of these values:

  • Inherited — Input from the Simulink model activates the MATLAB Function block.

    If you define an input trigger, the MATLAB Function block executes in response to a Simulink signal or function-call event on the trigger port. If you do not define an input trigger, the MATLAB Function block implicitly inherits triggers from the model. These implicit events are the discrete or continuous sample times of the signals that provide inputs to the block.

    If you define data inputs, the MATLAB Function block samples at the rate of the fastest data input. If you do not define data inputs, the MATLAB Function block samples at the rate defined by the execution behavior of the parent subsystem.

  • Discrete — The MATLAB Function block activates by using the rate you specify in the Sample time parameter of the block. The block generates an implicit event at regular time intervals that correspond to the specified rate. Other blocks in the model can have different sample times.

  • Continuous — The MATLAB Function block activates during major time steps only, and computes outputs and local continuous variables during major and minor time steps. The block can register zero crossings, which allows Simulink models to sample the block whenever state changes occur. The block computes derivatives for local continuous variables.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

If you use the MATLABFunctionConfiguration object, specify the property using these options:

Parameter: UpdateMethod
Values: "Inherited" (default) | "Continuous" | "Discrete"

If you use the Stateflow.EMChart object, specify the property using these options:

Parameter: ChartUpdate
Values: "INHERITED" (default) | "CONTINUOUS" | "DISCRETE"

Specify the time interval at which the MATLAB Function block activates during simulation. The default value indicates that the block inherits the sample time from Simulink. For more information on specifying sample time, see Specify Sample Time.

Do not use the Sample Time parameter in the Subsystem block parameters. Instead, use the Property Inspector.

Dependencies

To enable this parameter, set Update method to Discrete.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: SampleTime
Values: "-1" (default) | scalar | vector
Data Types: string | char

Advanced

Specify whether the data in the MATLAB Function block saturates on integer overflow as one of these values:

  • on — The block saturates an integer by setting it to the maximum positive or negative value allowed by the word size. This setting matches MATLAB behavior.

  • off — The block generates a run-time error in simulation mode when a overflow condition occurs. When you use Simulink Coder to generate code, the behavior depends on your C language compiler.

Tips

  • When this parameter is on, MATLAB adds additional checks during simulation to detect integer overflow or underflow. If integer overflow does not occur in the MATLAB Function block code, it is more efficient to disable this option.

  • Code generated by Simulink Coder does not check for integer overflow or underflow and, therefore, may produce unpredictable results when this parameter is off. In this situation, simulate your model to test for overflow and underflow before generating code.

  • This parameter setting is relevant only for integer arithmetic. It has no effect on fixed-point or double-precision arithmetic.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: SaturateOnIntegerOverflow
Values: true or 1 (default) | false or 0
Data Types: logical

Specify whether the MATLAB Function block supports input and output data that varies in dimension during simulation. When this parameter is on, you can define variable-size outputs by enabling the Variable size property on output variables. For more information, see Declare Variable-Size MATLAB Function Block Variables and Variable size.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: SupportVariableSizing
Values: true or 1 (default) | false or 0
Data Types: logical

Specify whether the MATLAB Function block supports direct feedthrough semantics, so that the output of the block is controlled directly by the value of an input. When this parameter is off, the block outputs rely only on the current state of the block. Using nondirect feedthrough enables you to use MATLAB Function blocks in a feedback loop and prevent algebraic loops. For more information, see Use Nondirect Feedthrough in a MATLAB Function Block.

Dependencies

To disable this parameter, you must set Update method to Inherited or Discrete.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: AllowDirectFeedthrough
Values: true or 1 (default) | false or 0
Data Types: logical

Since R2021b

Specify whether the MATLAB Function block treats output variables with a dimension of length 1 as fixed size as one of these values:

  • off — The block treats output variables that have at least one dimension of length 1 as fixed size, regardless of whether you specify the variables as having variable size.

  • on — The MATLAB Function block treats output variables as variable size if you specify the variables as having variable size.

For more information, see Variable size.

Note

In release R2021b and earlier, MATLAB Function blocks always convert output column vectors to one-dimensional signals.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: VectorOutputs1D
Values: false or 0 (default) | true or 1
Data Types: logical

Since R2023a

Specify whether variables with at least one dimension of length 1 are fixed size as one of these values:

  • on — Variables that are variable size with a dimension of 1 are fixed size.

  • off — Variables in the block that have the Variable size property enabled are always variable size.

This parameter only affects output variables that have the Variable size property enabled. See Variable size.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: TreatDimensionOfLengthOneAsFixedSize
Values: true or 1 (default) | false or 0
Data Types: logical

Fixed-point properties

Specify whether to treat inherited fixed-point and integer signals as Fixed-Point Designer™ fi (Fixed-Point Designer) objects as one of these values:

  • Fixed-point — The MATLAB Function block treats all fixed-point inputs as Fixed-Point Designer fi objects.

  • Fixed-point & Integer — The MATLAB Function block treats all fixed-point and integer inputs as Fixed-Point Designer fi objects.

For more information, see Ways to Construct fi Objects (Fixed-Point Designer).

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or Stateflow.EMChart object of the block and change the object property by using dot notation.

Parameter: TreatAsFi
Values: "Fixed-point" (default) | "Fixed-point & Integer"

Specify the default fimath (Fixed-Point Designer) object properties for the MATLAB Function block as one of these values:

  • Same as MATLAB — The block uses the same fimath object properties as the current default fimath object. The text box is dimmed and displays the current global fimath object in read-only form.

  • Specify other — Specify your own fimath object in the text box one of two ways:

    • Constructing the fimath object inside the text box.

    • Constructing the fimath object in the MATLAB or model workspace and then entering its variable name in the text box. If you use this option and plan to share your model with others, define the variable in the model workspace.

For more information, see fimath Object Construction (Fixed-Point Designer) and Fixed-Point Data Types with MATLAB Function Block (Fixed-Point Designer).

Tips

  • The fimath object of a MATLAB Function block behaves as a globalfimath (Fixed-Point Designer) object for the contents of the block. The block associates the fimath object properties in this parameter with all fixed-point and integer input signals to the MATLAB Function block that you choose to treat as fi objects. Constructing fi objects in the MATLAB Function block introduces additional considerations.

    • If no fimath object is associated with a fi object when it is constructed, then the fi constructor uses the default fimath object settings regardless of the properties in MATLAB function fimath. If you perform operations on the fi object after it is constructed, the object adopts the properties in MATLAB function fimath.

    • If you specify a fimath object in the fi constructor, then the fi constructor obeys that fimath object when quantizing the value. Any fimath object settings not specified in the fi constructor use the specified properties in MATLAB function fimath.

Programmatic Use

To set the block parameter value programmatically, access the MATLABFunctionConfiguration or the Stateflow.EMChart object of the block and change the associated object property by using dot notation.

If you use the MATLABFunctionConfiguration object, specify the property using these options:

Parameter: FimathMode
Values: "SameAsMATLAB" (default) | "UserSpecified"

If you use the Stateflow.EMChart object, specify the property using these options:

Parameter: EmlDefaultFimath
Values: "Same as MATLAB Default" (default) | "Other:UserSpecified"

Block Characteristics

Data Types

Booleana | busa | doublea | enumerateda | fixed pointa | halfa | integera | singlea | stringa

Direct Feedthrough

yesa

Multidimensional Signals

yesa

Variable-Size Signals

yesa

Zero-Crossing Detection

no

a Actual data type or capability support depends on block implementation.

Tips

  • You can call functions defined in:

    • Simulink Function blocks.

    • Stateflow® functions in charts. To call functions in charts, enable the Export Chart Level Functions and Treat exported functions as globally visible properties.

  • By default, MATLAB Function blocks do not include the %#codegen directive, but check for errors as if it is included. Adding the %#codegen directive to a MATLAB Function block does not affect error checking. For more information see Compilation Directive %#codegen.

Extended Capabilities

Version History

Introduced in R2011a

expand all