How do I write a MATLAB file S-function when the output width depends on the input width and input value?

1 view (last 30 days)
I want to write a MATLAB file S-function that allows dynamic input and output width; besides, the output width depends on the input width and input value. For example, my mdlInitializeSizes routine contains the following code fragment:
sizes.NumOutputs = -1;
sizes.NumInputs = -1;
sizes.DirFeedthrough = 1;
and my mdlOutputs routine looks like the following:
function sys=mdlOutputs(t,x,u)
if (length(u) - 1) > 4 %% Input width larger than 4
if u(1) == 1
y = [1;u(2:5)]; %% Assign first four input elements to output
else
y = [0;u(2:length(u))]; %% Assign all input elements to output
end
else %% Input width less than or equal to 4
y = [0;u(2:length(u))]; %% Assign all input elements to output
end
sys = y;
However, the S-function does not work when the output width is different from the input width. For example, when the input is [1, 2, 3, 4, 5, 6], the output is supposed to be [1, 2, 3, 4, 5]; but I receive the following error message:
Output returned by S-function 'modified_dac' in block 'customer_dec/S-Function'
during flag=3 call must be a real vector of length 6

Accepted Answer

MathWorks Support Team
MathWorks Support Team on 23 Jan 2010
In order to make the output width dependent on input width and input value in a MATLAB file S-function, you can use the GET_PARAM function in the mdlInitializeSizes routine to define dynamic input and output width. An example, which consists of the my_decode.mdl and winnie_dec.m files, is available at the bottom of the page.
Instead of setting sizes.NumOutputs and sizes.NumInputs to -1, the following code fragment in the mdlInitializeSizes routine of the winnie_dec.m file also achieves dynamic input and output width:
L = length(str2num(get_param('my_decode/Constant','value')));
%%get the length of the vector in the constant block.
if (L - 1) > 4 %%Input width larger than 4
in = str2num(get_param('my_decode/Constant','value'));
%%Get the value of the input vector.
in1 = in(1);%%Get the first element value of the input vector.
if in1 == 1 %%First element is one
out_width = 5;
else
out_width = L;
end
else %% Less than four inputs
out_width = L;
end
sizes.NumContStates = 0;
sizes.NumDiscStates = 0;
sizes.NumOutputs = out_width;
sizes.NumInputs = L;
sizes.DirFeedthrough = 1;
In this example, input and output widths can be different and both are dynamic. For example, running the model with an input of vector [1, 2, 3, 4, 5, 6] will yield [1, 2, 3, 4, 5].

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!