# How to remove noise using mean and median filters?

I can remove the noise using moving average filter. The MATLAB code is shown bellow.

But how can I remove the noise using mean and meadian filters?

• Can you please clarify what your specific question is? It looks like you've successfully reduced the noise in your signal. – MBaz Apr 5 '16 at 13:29
• Mean is the same as average, median filter is m = medfilt1(x, len) – Eddy_Em Apr 5 '16 at 13:54
• Thanks Eddy_ Em. How does it modify with for loop. If you pls explain – Dyr Apr 5 '16 at 15:03
• Exactly, MBaz I already reduced the noise using moving average filter. But I want to reduced the noise for this signal using only median filter. How does it do? – Dyr Apr 5 '16 at 15:11
• Dyr: Keep in mind that median filter works best for outliers/spikes in your signal. – jojek Apr 5 '16 at 16:41

You do not need loops. This implements a moving average filter, a median filter, and a median filter followed by a moving average:

%x = noise1;
x = randn(1,2000)+1;
lengthMean = 5;
lengthMedian = 7;
xFiltMedian = medfilt1(x,lengthMedian);
xFiltMean = filter(ones(lengthMean,1)/lengthMean,1,x);
xFiltMedianMean = filter(ones(lengthMean,1)/lengthMean,1,xFiltMedian);
figure(1);clf;hold on
plot(x(500:1500),'b');
plot(xFiltMedian(500:1500),'r');
plot(xFiltMean(500:1500),'g');
plot(xFiltMedianMean(500:1500),'c');


As said by @jojek the median filter is often more efficient than an averaging filter for spikes and outliers. And if you choose to apply both filters, it is generally more useful to apply the median first (as done in the code above).

The choice of filter length should normally be related to properties of your signal and the noise (spectrum, distribution), and to the goal you are assigned with. But the length of the signal is usually not a criterion. For symmetry properties, odd-length filters are practical.

Without further details, you can start with longer filters (e.g. lengthMedian= 37), see how they perform (how they reduce the noise but also degrade the signal's properties), and reduce the length progressively to the equilibrium point, where shorter filters do not yield better results.

However, the noise in the valley suggests it is not stationary, so you may need more adaptive filters (e.g. with a varying length), or a little more involved like a weigthed median filter that limits the location and flattening issues you get with long median filters. It is discussed on SE Cross validated.

• Thanks Laurent Duval. Exactly above code executed. but i have a doubt about the lengthMean and lengthMedian values. my matrix has 1 row and 3110 coloumns. how do i select proper value for lengthMean and lengthMedian? however, lengthMean = 5 and lengthMedian = 7 are working properly. – Dyr Apr 6 '16 at 4:22