Matlab/Simulink: Minimal empty template S-function
You can use this minimal, empty s-function as a template for getting started with your own S-function.
This minimal example also includes a template mdlStart()
.
Remember that if you rename the file, you also need to update the S_FUNCTION_NAME
#define
accordingly.
#define S_FUNCTION_NAME nothing_sfunction
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
// Function: mdlInitializeSizes ===============================================
// Abstract:
// Setup sizes of the various vectors.
static void mdlInitializeSizes(SimStruct *S)
{
// Add ssSetNumInputPorts() etc here
}
#define MDL_START
static void mdlStart(SimStruct *S)
{
// Optionally, perform initialization tasks here
// If not needed, you can remove this function and #define MDL_START entirely.
}
// Function: mdlInitializeSampleTimes =========================================
// Abstract:
// Initialize the sample times to be 1ms (1kHz)
static void mdlInitializeSampleTimes(SimStruct *S)
{
// For an example what to add here, see https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlOutputs =======================================================
// Abstract:
// Calculate the sine wave output based on the simulation time.
static void mdlOutputs(SimStruct *S, int_T tid)
{
// For an example what to add here, see https://techoverflow.net/2024/10/20/matlab-level-2-s-function-example-sine-wave-continous-output/
}
// Function: mdlTerminate =====================================================
// Abstract:
// This function is called at the end of simulation for cleanup.
static void mdlTerminate(SimStruct *S)
{
// No cleanup required for this example
}
// Required S-function trailer
#ifdef MATLAB_MEX_FILE
#include "simulink.c" // MEX-file interface mechanism
#else
#include "cg_sfun.h" // Code generation interface
#endif
Compile using
mex -g nothing_sfunction.cpp CXXFLAGS="-std=gnu++17 -fPIC"
Using -std=gnu++17
or newer is recommended, but not required.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow