%% Remove High-Frequency Noise Using Median Filter
% Filter high-frequency noise from a noisy sine wave signal using a median filter. 
% Compare the performance of the median filter with an averaging filter.
%% Initialization
% Set up a |dsp.MedianFilter| object, |medFilt|, and a |dsp.MovingAverage| object, 
% |movavgWin|. These objects use the sliding window method with a window length 
% of 7. Create a time scope for viewing the output.

Fs = 1000;
medFilt = dsp.MedianFilter(7);
movavgWin = dsp.MovingAverage(7);
scope  = timescope('SampleRate',Fs,...
    'TimeSpanSource','Property',...
    'TimeSpanOverrunAction','Scroll',...
    'TimeSpan',1,'ShowGrid',true,...
    'YLimits',[-3 3],...
    'LayoutDimensions',[3 1],...
    'NumInputPorts',3);
scope.ActiveDisplay = 1;
scope.Title = 'Signal + Noise';
scope.ActiveDisplay = 2;
scope.Title = 'Moving Average Output (Window Length = 7)';
scope.ActiveDisplay = 3;
scope.Title = 'Median Filter Output (Window Length = 7)';

FrameLength = 256;
count = 1;
sine = dsp.SineWave('SampleRate',Fs,'Frequency',10,...
    'SamplesPerFrame',FrameLength);
%% Filter the Noisy Sine Wave
% Generate a noisy sine wave signal with a frequency of 10 Hz. Apply the median 
% filter and the moving average object to the signal. View the output on the time 
% scope.
%%
for i = 1:500    
    hfn = 3 * (rand(FrameLength,1) < 0.02);
    x = sine() + 1e-2 * randn(FrameLength,1) + hfn;
    y1 = movavgWin(x);
    y2 = medFilt(x);
    scope(x,y1,y2);    
end
%% 
% The median filter removes the high-frequency noise more effectively than 
% the moving average object does.

%% 
% Copyright 2012 The MathWorks, Inc.