0
0
SimulinkHow-ToBeginner · 3 min read

How to Use MATLAB Function Block in Simulink: Step-by-Step Guide

To use the MATLAB Function block in Simulink, drag it from the User-Defined Functions library into your model, then double-click it to write your MATLAB code. This block lets you embed MATLAB functions directly in Simulink for custom computations and logic.
📐

Syntax

The MATLAB Function block uses a simple syntax where you write a MATLAB function inside the block editor. The basic structure is:

function y = fcn(u)
% Your code here
end

Here, u is the input to the block, and y is the output. You can add multiple inputs and outputs by modifying the function signature.

matlab
function y = fcn(u)
y = u^2; % Example: square the input
end
💻

Example

This example shows how to create a MATLAB Function block that squares its input signal.

matlab
function y = fcn(u)
% Square the input value
  y = u^2;
end
⚠️

Common Pitfalls

  • Not defining function inputs/outputs correctly: The function must have inputs and outputs matching the block ports.
  • Using unsupported MATLAB functions: Some MATLAB functions are not supported inside the block; check Simulink documentation.
  • Ignoring data types: Mismatched data types can cause errors; use type casting if needed.
  • Forgetting to save the block: Changes inside the block editor must be saved before running the simulation.
matlab
%% Wrong: No input or output defined
function y = fcn()
y = 5;
end

%% Right: Define input and output
function y = fcn(u)
y = u + 5;
end
📊

Quick Reference

Tips for using MATLAB Function block:

  • Drag the block from User-Defined Functions library.
  • Double-click to open the editor and write your function.
  • Define inputs and outputs clearly in the function signature.
  • Use supported MATLAB code only.
  • Save changes before running the simulation.

Key Takeaways

Drag the MATLAB Function block into your Simulink model to embed custom MATLAB code.
Always define function inputs and outputs to match the block ports.
Use only MATLAB functions supported by Simulink inside the block.
Save your code changes inside the block editor before running the simulation.
Check data types carefully to avoid simulation errors.