MATLAB: Do I get a Port Width mismatch error in the CMEX S-function when using dynamically_sized for either the inputs or outputs

dynamicfixedportsimulink

Why do I get a Port Width mismatch error in my CMEX S-function when using dynamically_sized for either my inputs or outputs? The other input is set to a fixed value. For example, in my Level 2 S-function I have the following:
if (!ssSetNumInputPorts(S, 1)) return;
ssSetInputPortWidth(S, 0, DYNAMICALLY_SIZED);
ssSetInputPortDirectFeedThrough(S, 0, 1);
if (!ssSetNumOutputPorts(S, 2)) return;
ssSetOutputPortWidth(S, 0, NOUTPUT);
ssSetOutputPortWidth(S, 1, NOUTPUT);
where NOUTPUT was defined as 22.
However, when I run the model, I receive errors that look like the following:
--> Port width mismatch. Output Port 1 of 'untitled/Subsystem/In1' has a width of 12.
--> Input Port 1 of 'untitled/Subsystem/S-function' has a width of 22
How can I get around this?

Best Answer

In Level 1 S-functions (Simulink 2.1 and below) the only workaround, is to either set both the input and the output to dynamically_size or both to a fixed size.
However, in Level 2 S-functions (Simulink 2.2 and above) you need to use the two new macros introduced in Level 2: mdlSetInputPortWidth and mdlSetOutputPortWidth. This is described in the S-function section of the Using Simulink User's Guide.
To fix the above code, you need to include the following after the mdlInitializeSizes subfunction:
#if defined(MATLAB_MEX_FILE)
# define MDL_SET_INPUT_PORT_WIDTH
static void mdlSetInputPortWidth(SimStruct *S, int_T port,
int_T inputPortWidth)
{
ssSetInputPortWidth(S,port,inputPortWidth);
ssSetOutputPortWidth(S,port,NOUTPUT);
}
# define MDL_SET_OUTPUT_PORT_WIDTH
static void mdlSetOutputPortWidth(SimStruct *S, int_T port,
int_T outputPortWidth)
{
ssSetInputPortWidth(S,port,DYNAMICALLY_SIZED);
ssSetOutputPortWidth(S,port,NOUTPUT);
}
#endif