Median

Overview

The 3-point median filter returns the median of the three most recent samples. Its output is always one of the input samples, so a lone outlier is discarded, where an averaging filter spreads it over its neighbors. Use it against impulsive noise: sudden one-sample jumps in the signal. The filter is implemented by a class named median3.

median3 removing impulsive spikes that a moving average only smears
Figure 1. A smooth signal with single-sample spikes. median3 (blue) rejects each spike and tracks the underlying signal; the 3-tap moving average (amber) keeps a third of every spike and spreads it across three samples.

For three inputs the median is the middle value once they are sorted. median3 finds it with two min and two max operations, without sorting. A median filter costs more per sample than a moving average. It is nonlinear and does not obey superposition. It rejects brief impulsive spikes and leaves edges and slopes intact; for band limiting, use a low-pass filter.

The free function median3f(a, b, c) computes the median of three values in one call, for code that already holds the three samples and does not need the running state.

Include

#include <q/fx/median.hpp>

Declaration

inline float median3f(float a, float b, float c);

struct median3
{
            median3(float median_ = 0.0f);

   float    operator()(float a);
   float    operator()() const;
   median3& operator=(float median_);

   float    b = 0.0f;
   float    c = 0.0f;
};

Expressions

Notation

m, n

Objects of type median3.

a, b, c

Floating point input samples.

val

Floating point value.

Constructors and Assignment

Expression Semantics

median3([val])

Construct a median3, seeding the median and both stored samples with val (default 0).

median3(m)

Copy construct from median3 m.

n = m

Assign m to n.

m = val

Reset the filter, seeding the median and both stored samples with val.

C++ brace initialization may also be used.

Function Call

Expression Semantics Return Type

m(a)

Process the input sample a and return the median of the three most recent samples.

float

m()

Get the current median.

float

Access

Expression Semantics Return Type

m.b

Get or set the previous input sample.

float

m.c

Get or set the input sample before m.b.

float

Functions

Expression Semantics Return Type

median3f(a, b, c)

Get the median of a, b and c.

float

Example

Remove single-sample spikes from the input samples in, in place:

namespace q = cycfi::q;

auto despike = q::median3{};             (1)

for (auto& s : in)
   s = despike(s);                       (2)
1 Construct a median filter, with the stored samples at 0.
2 Replace each sample with the median of it and the two input samples before it.