from
slidefilter
by Hazem Baqaen
Sliding Sum Averaging Filter (Moving Average)
|
| slidefilter(data,interval)
|
% Sliding Sum Averaging Filter
%
% Smoothes data by sliding it past itself, one sample at a time, and summing.
% The length of the output is the same as the length of the input. The output
% will be normalized. Equivalent to a moving average (lowpass) filter, but
% more efficient.
%
% Edges are treated differently and separately from the center to increase
% efficiency. The idea is that averaging is done only over those elements
% remaining within the sliding window.
%
% The main advantage of this method of averaging is the better treatment of
% the edges, combined with speed.
%
% Usage:
%
% Smoothed Data = slidefilter(Data Vector, Sliding Interval Length in Samples)
%
% See also: movave.m
% Hazem Baqaen (Hazem@brown.edu), Simmons lab., Brown University.
% MATLAB 7.
%
% Version 4, Feb. 2006.
function out = slidefilter(data,interval)
% Check dimensions of data set
[r,c] = size(data);
if (r~=1) & (c~=1)
error('Data must be a one-dimensional vector')
elseif (r~=1)
data = data';
end
clear r,c;
% Default maximum averaging interval
if interval > length(data)
interval = length(data);
warning('The window you entered is bigger than or equal to the data length. It has been reduced to match.')
end
% Shift-slide and add, filling gaps with zeros
newdata = 0; % Initialize variable
zeropaddeddata = [zeros(1,length(data)) data zeros(1,length(data))];
L = length(data);
HalfInterval = ceil(interval/2);
N1 = L-HalfInterval+1;
N2 = (2*L)-HalfInterval;
for shift = 1:interval
newdata = newdata + zeropaddeddata(N1+shift:N2+shift);
end
% Edges are treated differently and separately from center to increase
% efficiency. The idea is that averaging is done only over those elements
% remaining within the sliding window. Edges are treated symmetrically.
RightEdgeDiv = shift - [1:(shift-1)/2]; % Vectors containing numbers of elements to average over in the edge regions
LeftEdgeDiv = fliplr(RightEdgeDiv);
if rem(shift/2,1) == 0 % if shift is even
if isempty(RightEdgeDiv)
RightEdgeDiv = 1;
else
RightEdgeDiv = [RightEdgeDiv RightEdgeDiv(end)-1];
end
end
% Concatenate averages for center and edges (normalize in the process)
out = [newdata(1:length(LeftEdgeDiv))./LeftEdgeDiv newdata(length(LeftEdgeDiv)+1:end-length(RightEdgeDiv))/shift newdata(end-length(RightEdgeDiv)+1:end)./RightEdgeDiv];
|
|
Contact us at files@mathworks.com