How to Use Embedded MATLAB Function Block in Simulink
Use the
Embedded MATLAB Function block in Simulink to write custom MATLAB code that runs inside your model. Double-click the block to open the editor, write your MATLAB function, and connect inputs and outputs to use it in your simulation.Syntax
The Embedded MATLAB Function block lets you write a MATLAB function with this basic syntax inside the block editor:
function y = fcn(u) %#codegen % Your code here end
Here, u is the input to the function, and y is the output. The %#codegen directive tells Simulink to generate efficient code from your MATLAB code.
matlab
function y = fcn(u) %#codegen % Example: square the input y = u^2; end
Example
This example shows how to use the Embedded MATLAB Function block to square an input signal.
1. Drag the Embedded MATLAB Function block into your Simulink model.
2. Double-click the block to open the editor.
3. Replace the code with the example below.
4. Connect an input source (like a Constant block) and an output sink (like a Display block).
5. Run the simulation to see the squared output.
matlab
function y = fcn(u) %#codegen y = u^2; end
Output
If input u = 3, output y = 9
Common Pitfalls
- Not using %#codegen: This directive is required for code generation and efficient simulation.
- Unsupported MATLAB functions: Only a subset of MATLAB functions are supported inside the block. Check documentation for supported functions.
- Incorrect input/output sizes: Make sure input and output sizes match your function definition.
- Using workspace variables: Avoid using variables from the MATLAB workspace; define all variables inside the function.
matlab
Wrong: function y = fcn(u) y = sin(u) + workspaceVar; end Right: function y = fcn(u) %#codegen y = sin(u) + 1; % Use constants or inputs only end
Quick Reference
| Feature | Description |
|---|---|
| Block Name | Embedded MATLAB Function |
| Function Syntax | function y = fcn(u) |
| Codegen Directive | %#codegen |
| Input | Defined as function input argument |
| Output | Defined as function output argument |
| Supported Functions | Subset of MATLAB functions for code generation |
| Common Use | Custom algorithms inside Simulink models |
Key Takeaways
Use the Embedded MATLAB Function block to write custom MATLAB code inside Simulink models.
Always include %#codegen for code generation compatibility.
Check that your MATLAB code uses supported functions and matches input/output sizes.
Avoid using workspace variables; define all variables inside the function.
Test your function with simple inputs to verify correct behavior before complex use.