Matlab/Simulink S-Function example: Square a number
The following simple S-Function examples squares the real input value and outputs the squared value.
square.cpp
#define S_FUNCTION_NAME square
#define S_FUNCTION_LEVEL 2
#include "simstruc.h"
// Function: mdlInitializeSizes ==============================================
static void mdlInitializeSizes(SimStruct *S) {
ssSetNumSFcnParams(S, 0); // No parameters
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, 1); // Single input
ssSetInputPortDirectFeedThrough(S, 0, 1); // Direct feedthrough
if (!ssSetNumOutputPorts(S, 1)) return;
ssSetOutputPortWidth(S, 0, 1); // Single output
ssSetNumSampleTimes(S, 1);
ssSetOptions(S, 0);
}
// Function: mdlInitializeSampleTimes =========================================
static void mdlInitializeSampleTimes(SimStruct *S) {
ssSetSampleTime(S, 0, INHERITED_SAMPLE_TIME);
ssSetOffsetTime(S, 0, 0.0);
}
// Function: mdlOutputs ======================================================
static void mdlOutputs(SimStruct *S, int_T tid) {
// Get input signal
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S, 0);
// Get output signal
real_T *y = ssGetOutputPortRealSignal(S, 0);
// Square the input
real_T input = *uPtrs[0];
*y = input * input;
}
// Function: mdlTerminate ====================================================
static void mdlTerminate(SimStruct *S) {
// No termination tasks required
}
#ifdef MATLAB_MEX_FILE
#include "simulink.c" // MEX-file interface mechanism
#else
#include "cg_sfun.h" // Code generation registration function
#endif
Makefile
all:
mex square.cpp
How to use in Simulink
Step-by-step guide of how to add the S-function
Example usage:
The output here is 64
because 8*8=64
.
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow