A common question regarding Simulink is how to buffer previous values of the input to use at later times. A buffering scheme can be created via an S-function. One common S-function trick is to use discrete states to store information. The following two examples are commented S-functions, which realize two variations of a buffering scheme. The first example, sbuffer.m, creates a sliding window over the last three input values and outputs the sum of these values. The second example, sbuffer2.m, stores the last three values in a buffer, and holds the output value constant as the buffer is filling. For example, if the current sum of the buffered values is 5, the output will be held to 5 for the next three integration steps. At that time, the buffer will contain three new values. The sum of these new values will be the new output.
function [sys,x0] = sbuffer(t,x,u,flag)
if flag == 0,
sys = [0 3 1 1 0 0];
x0 = zeros(1,3);
elseif abs(flag) == 2,
sys = zeros(3,1);
sys(3) = x(2);
sys(2) = x(1);
sys(1) = u;
elseif abs(flag) == 3,
sys = sum( x );
else
sys = [];
end
function [sys,x0] = sbuffer2(t,x,u,flag)
if flag == 0,
sys = [0 5 1 1 0 0];
x0 = zeros(1,5);
elseif abs(flag) == 2,
sys = zeros(5,1);
sys(3) = x(2);
sys(2) = x(1);
sys(1) = u;
count = x(4) + 1;
if rem(count,3) == 0,
sys(4) = 0;
sys(5) = sum(x(1:2))+u;
else
sys(4) = count;
sys(5) = x(5);
end
elseif abs(flag) == 3,
if x(4) ~= 0,
sys = x(5);
else
sys = sum(x(1:3));
end
else
sys = [];
end