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.

In general, while writing vector I/O S-functions, remember that:

InputRealPtrsType uPtrs = ssGetInputPortRealSignalPtrs(S, 0);
// ...
std::array<double, 3> input = { *uPtrs[0], *uPtrs[1], *uPtrs[2] };

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

Step-by-step guide of how to add the S-function

Example usage:

Simulink Square Vector