Matlab/Simulink S-Function with vector input & output
The following S-function example demonstrates how to create an S-Function with vector input and output in Matlab/Simulink.
- It accepts a 3-vector of real inputs
- It will square the inputs element-wise
- It will output a 3-vector of real outputs
In general, while writing vector I/O S-functions, remember that:
ssSetInputPortWidth(S, 0, n);
orssSetOutputPortWidth(S, 0, n);
sets the number of elements in the vector ton
. You must call this function inmdlInitializeSizes
.- Input data is not given as continous array but as an array of pointers! To convert it to a vector:
InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S, 0);
// ...
std::array<double, 3> input = { *uPtrs[0], *uPtrs[1], *uPtrs[2] };
- The output is given as a pointer to a continous vector
square_vector.cpp
#define S_FUNCTION_NAME square_vector
#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, 3); // Single input
ssSetInputPortDirectFeedThrough(S, 0, 1); // Direct feedthrough
if (!ssSetNumOutputPorts(S, 1)) return;
ssSetOutputPortWidth(S, 0, 3); // 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
y[0] = *uPtrs[0] * *uPtrs[0];
y[1] = *uPtrs[1] * *uPtrs[1];
y[2] = *uPtrs[2] * *uPtrs[2];
}
// 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_vector.cpp
How to use in Simulink
Step-by-step guide of how to add the S-function
Example usage:
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow