%% Moving Average of Noisy Ramp Signal
% Compute the moving average of a noisy ramp signal using the  |dsp.MovingAverage| 
% object.
%% Initialization
% Set up |movavgWindow| and |movavgExp| objects. |movavgWindow| uses the sliding 
% window method with a window length of 10. |movavgExp| uses the exponentially 
% weighting method with a forgetting factor of 0.9. Create a time scope for viewing 
% the output.

FrameLength = 1001;
Fs = 1000;
movavgWindow = dsp.MovingAverage(10);
movavgExp = dsp.MovingAverage('Method','Exponential weighting',...
    'ForgettingFactor',0.9);
scope  = timescope('SampleRate',Fs,...
    'TimeSpanOverrunAction','Scroll',...
    'ShowGrid',true,...
    'YLimits',[-0.5 1.5]);
title = 'Sliding Window Average(blue) and Exponentially Weighted Average(red)';
scope.Title = title;
%% Compute the Average
% Generate a ramp signal with an amplitude of 1.0 and a time span of 2 seconds. 
% Apply the sliding window average and exponentially weighted average to the ramp. 
% View the output on the time scope.
%%
for i = 1:500
    t = (0:0.001:1)';
    unitstep = t>=0;
    ramp = t.*unitstep;
    x = ramp + 0.1 * randn(FrameLength,1);
    y1 = movavgWindow(x);
    y2 = movavgExp(x);
    scope([x,y1,y2]);
end

%% 
% Copyright 2012 The MathWorks, Inc.