% AVERAGE ( MatLinks) Smooth an arbitrary function by windowed averaging.
%
% AVERAGE(X,N,W) averages data vector X, N times, with a window W.
%
% The averaging window extends W data to the left and W to the right of the
% point in question, which makes the overall window size 2*W+1. The larger
% W is, the more detail is smoothed out. A value W=0 results in no
% averaging. The default value for W=1.
%
% The number of times smoothing is performed is controlled via N. As N
% increases, noise reduction can be performed very effectively with little
% loss of overall detail. The default value for N=1.
%
% [Y,S]=AVERAGE(...) returns the average of X in Y, and the shift of Y
% relative to X, as S. When N=1 or W=1, Y(I) corresponds to X(I+S).
%
% AVERAGE(...) by itself plots X along with the averaged function.
%
% See also SMOOTH.
%
% Type HELP MATLINKS for a full listing of all MatLinks ToolChest functions.
%
function [Y, S] = average(X, N, W)
%===============================================================================
% Copyright 1999,2000 Julian Andrew de Marchi, Ph.D. (julian@matlinks.net)
% Use & distribution covered by GNU General Public License (www.gnu.org)
%===============================================================================
%------------------
% parse the inputs
%------------------
if (nargin == 0), error('No data vector X supplied.');
elseif (nargin == 1), N = 1; W = 1;
elseif (nargin == 2), W = 1;
end;
%---------------------
% perform the average
%---------------------
Y = X;
for j = 1:N,
tmp = Y;
for i = 1+W : length(tmp)-W,
Y(i-W) = mean(tmp(i-W : i+W));
end;
S = W-1+j;
end;
%fudge = 1 + N/2500; % this adjusts the amplitude somewhat
fudge = 1;
Y = fudge * Y(1 : (length(Y)-S));
%------------------------------------------------
% plot the average if there's no output variable
%------------------------------------------------
if nargout == 0,
hold off,
plot((S+1) : length(X), X((1+S) : length(X)),'b'), hold on;
plot(S + (1:length(Y)), Y,'g'), hold off, zoom on;
title(['Average (n=' num2str(N) ', w=' num2str(W) ')']),
xlabel('i'), ylabel('x(i)'), hold off;
end;
%===============================================================================
% End-of-File
%===============================================================================