mathematics//signal processing//digital filter//median filter

A median filter is a nonlinear digital filter that outputs the median of the last few samples, and it is the standard remedy for isolated spikes in a sensor stream: a corrupted byte on a serial link, a stray lidar reflection, a glitch in an ultrasonic range. Sorting three samples and keeping the middle one costs almost nothing and runs in any microcontroller or PLC.


A median filter is a nonlinear digital filter that outputs the median of the last few samples, and it is the standard remedy for isolated spikes in a sensor stream: a corrupted byte on a serial link, a stray lidar reflection, a glitch in an ultrasonic range. Sorting three samples and keeping the middle one costs almost nothing and runs in any microcontroller or PLC.

A spike is a single sample far from its neighbours. In a window of three it is always the largest or the smallest value, so the median simply never picks it, and the output carries on as if it had not happened. A true step behaves differently: once two of the three samples sit at the new level, the median follows it, so the edge comes through sharp, delayed by one sample. A linear filter cannot do this, because it adds every sample in with some weight, and a spike of 100 times the signal leaves a visible bump whatever the weights.

Being nonlinear is what lets it do what linear filters cannot.

It removes outliers without smearing steps, and that is exactly the case where averaging fails worst. A median of three in front of a first-order low-pass filter covers a large share of real sensor cleaning (flyswatter rule).

Its strength is a limit on the weight of any single sample. The median is the robust counterpart of the mean, and a window of 2k+12k+12k+1 samples survives up to kkk bad ones in a row (robust statistics); a burst longer than that passes through.

It does little for broadband noise. On well-behaved Gaussian noise the median of a window is noisier than the mean of the same window, so the spike remover is followed by a linear smoother, and a long median window rounds off peaks and flattens narrow features.

Being nonlinear, it has no frequency response, and its delay depends on the signal; the delay of a window of 2k+12k+12k+1 on a ramp is kkk samples, so short windows are the rule inside loops (loop delay).

A spike may be the message. An outlier can be the first symptom of the fault an engineer is looking for, so a pipeline that removes spikes should also count them, and an estimator can gate a bad reading instead of filtering it (innovation gating).