How to use mex file in a simulink model
Show older comments
Hello team,
I have created a mex file having a mex function definition. I have created this mex to use output of a C-function in simulink model. The C-function definition which corresponds to created mex function is as follows:
T_SftyReason Sfty_GetReason(void)
{
return SftyValues.SftyInfo.SReason;
}
I need to use this mex function in simulink model. The outputs from this mex function need to be assigned to variables in mathworks workspace for futher use. Request to please guide us for the step-by-step process to use this mex function in simulink model.
Answers (1)
Ruchika Parag
on 30 Jun 2025
Hi @Shalaka, to use the output of your MEX function in a Simulink model and assign it to variables in the MATLAB workspace, there are two main approaches, depending on how your MEX function is structured.Option 1: Use a MATLAB Function Block (if the MEX behaves like a regular MATLAB function)
If your MEX file is callable directly from MATLAB using a syntax like:
result = myMexFunction();
then you can follow these steps:
- In your Simulink model, insert a MATLAB Function block.
- Double-click the block and write a wrapper like:
function y = fcn()
y = myMexFunction();
end
Option 2: Create a C-based S-Function (if the MEX is low-level or incompatible with MATLAB syntax)
If your MEX function isn't directly usable in MATLAB (e.g., it returns a struct or requires complex pointers), you can wrap the C code into a Simulink-compatible S-function:
- Write an S-function in C that calls your Sfty_GetReason() function inside mdlOutputs.
- Compile it with mex in MATLAB:
mex mysfunction.c
- Add an S-Function block to your model and specify the compiled .mex file.
- Connect the output to a To Workspace block to log values during simulation.
Hope this helps!
Categories
Find more on Event Functions in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!