Exercise: Indexing/slicing/filtering unidimensional arrays 3

5.11.3. Exercise: Indexing/slicing/filtering unidimensional arrays 3#

You recorded a noisy signal:

signal = np.array(
    [
        0.436, 0.493, 0.467, 0.467, 0.482, 0.497, 0.474, 0.493, 0.474, 0.467,
        0.470, 0.455, 0.482, 0.501, 0.470, 0.482, 0.467, 0.467, 0.558, 0.413,
        0.463, 0.444, 0.463, 0.417, 0.528, 0.455, 0.486, 0.459, 0.490, 0.459,
    ]
)
_images/17580e3f346244339812d584df0403faa9750cc18bd3cfab6af9e6bcfb19fe09.png

You want to smooth this signal using a moving average with a window of three samples. This means that you want to create a new array where each value is the average of the three neighbour values of the raw signal, as illustrated in Fig. 5.10.

Fig. 5.10 Filtering using a moving average.#

Using only one line, apply such a filter on the raw, noisy signal. Then, plot both the raw and filtered signal on the same figure to verify your result.

Hide code cell content
import numpy as np
import matplotlib.pyplot as plt


filtered = (signal[0:-2] + signal[1:-1] + signal[2:]) / 3

plt.plot(signal, label="raw")
plt.plot(filtered, label="filtered")
plt.legend();
_images/2d9681d5664bfc29dd005f57a3cfc3e85b40275b047f134d65f3656cce60daa7.png