How to use mex file in a simulink model

조회 수: 9 (최근 30일)
Shalaka
Shalaka 2025년 6월 24일
답변: Ruchika Parag 2025년 6월 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