%% Filter a Signal Using the filter function
% Filter a signal using a filter with various initial conditions (IC) or no initial conditions.

x = randn(100,1);    % Original signal.
b = fir1(50,.4);     % 50th-order linear-phase FIR filter.
hd = dfilt.dffir(b);    % Direct-form FIR implementation.

%
% Do not set specific initial conditions.

y1 = filter(hd,x);   % 'PersistentMemory'='false'(default).
zf = hd.states;      % Final conditions.

%
% Now use nonzero initial conditions by setting ICs before you filter.

hd.persistentmemory = true;
hd.states = 1;      % Uses scalar expansion.
y2 = filter(hd,x);
stem([y1 y2])       % Different sequences at beginning.
legend('y1','y2');

% Looking at the stem plot shows that the sequences are different at the beginning of the filter process.
%
% Here is one way to use filter with streaming data.

reset(hd);           % Clear filter history.
y3 = filter(hd,x);   % Filter entire signal in one block.

%
% As an experiment, repeat the process, filtering the data as sections, rather than in streaming form.

reset(hd);              % Clear filter history.
yloop = zeros(20,5);    % Preallocate output array.
xblock = reshape(x,[20 5]);
for i=1:5
   yloop(:,i) = filter(hd,xblock(:,i));
end

%
% Use a stem plot to see the comparison between streaming and block-by-block filtering.

stem([y3 yloop(:)]);
legend('y3','yloop')

% Filtering the signal section-by-section is equivalent to filtering the entire signal at once.
% Copyright 2012 The MathWorks, Inc.