Example Moving Average

On many occasions, filtering is used to "smooth" a signal. A simple algorithm is that of a moving average. For every two consecutive points, we calculate the average and use that value instead. The points are overlapping, so a result of using the algorithm on the vector [l, 2, 0, 2] would be [1.5, 1, l]. But why stop at two samples? Moving average can be performed on several points, returning the average of those points. In Python, you could write

>>> plot(t, x) >>> hold(True) ยป> plot(t[W-l:], xf, lw=3) >>> title('Moving average')

>>> legend(['signal with noise', 'filtered signal']) >>> xlabel('t [seconds]') >>> ylabel('x []')

This is a straightforward implementation using a for loop. The input to the filter is arbitrarily chosen as 1 - exp(-t) plus noise.

There is an easier approach. A moving average is an FIR filter with all its elements equal to 1/W, where W is the length of the moving average window. In this case, a quick-and-simple way to implement a moving average filter instead of the for loop is by calling the signal. lfilter() function and passing ones(W)/W as the filter values:

>>> from scipy import signal

Figure 8-16 shows the results of plotting a moving average.

Moving average 1.41-1-.-

Moving average 1.41-1-.-

Numpy Smooth List

t [seconds]

Figure 8-16. Moving average t [seconds]

Figure 8-16. Moving average

0 0

Post a comment