Moving average filter
This article goes through the basic theory of a moving average filter and calculation of transfer function, phase and magnitude expressions.
It also shows the implementation of a moving average filter in C and explains the advantages and disadvantages of moving average filter.
Moving average filter — Theory
A moving average filter takes the average of M samples including the current sample andn calculates the average of these M samples.
Expanding the above equation gives
Using Z-transform for the above equation gives
Using geometric series equation gives
Using z = e^(-jwT) gives
The phase response of the filter is linear
It can be shown that the corner frequency of the filter decreases with the increase in the window size M.
Implementation in C
The implementation is pretty straight forward. For each input sample, calculate the average of all inputs including the current input. Store the input samples in a buffer and track the current input sample using an index variable. If the sample index exceeds the sample/input buffer size, reset buffer index to 0.
struct moving_average_filter {
float* input;
size_t size;
int index;
float output;
};
#define MOVING_AVERAGE_FILTER_DEFINE(__name__, __size__) \
\
float __name__##_moving_average_filter_input_buffer[__size__] = {0}; \
\
struct moving_average_filter moving_average_filter_##__name__ = { \
.input = &__name__##_moving_average_filter_input_buffer, \
.size = __size__, \
.index = 0, \
.output = 0.0f, \
};
#define MOVING_AVERAGE_FILTER_HANDLE(__name__) \
((struct moving_average_filter*)&moving_average_filter_##__name__)
static float moving_average_filter_process(struct moving_average_filter* filter, float input)
{
int index;
float output = 0.0f;
filter->input[filter->index] = input;
filter->index++;
if(filter->index >= filter->size) {
filter->index = 0;
}
for(index = 0 ; index < filter->size ; index++)
{
output += filter->input[index];
}
filter->output = output / (float)filter->size;
return filter->output;
}Results of moving average filter
Two observations can be immediately be made: the 3dB cutoff frequency decreases with the increase in the filter window size. The slope of the phase roll-off increases with the increase in the window size.
Advantages and disadvantages of moving average filter
Advantages
Get Patrick A Joseph’s stories in your inbox
Join Medium for free to get updates from this writer.
Since the phase roll-off is linear, the filter is relatively stabel when compare to IIR filters.
The phase characteristics is linear in nature, thereby the phase delay d(phase)/d(omega) is always constant, ensuring constant delay between the input and output waveforms at all frequencies.
The implementation is quiet simple and not mathematically intensive.
Disadvantages
For a steep gain roll-off a high window size is required which consumes more system memory and filter computation time when compared to an IIR filter.






