How to use mex file in a simulink model

8 次查看(过去 30 天)
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.

回答(1 个)

Ruchika Parag
Ruchika Parag 2025-6-30
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:
  1. In your Simulink model, insert a MATLAB Function block.
  2. 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:
  1. Write an S-function in C that calls your Sfty_GetReason() function inside mdlOutputs.
  2. 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!

类别

Help CenterFile Exchange 中查找有关 Simulink Coder 的更多信息

产品


版本

R2022b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by