Exercise: Indexing/slicing/filtering one-dimensional arrays 3

5.11.3. Exercise: Indexing/slicing/filtering one-dimensional arrays 3#

You have 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/bcd0322a79a540d26c07fe83afde4408c1b8bd78a6f0d1cf2062630a374b1ed0.png

You want to smooth this signal using a moving average with a window of three samples. This means creating 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 this filter to the raw, noisy signal. Then, plot both the raw and filtered signals 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/62a85af70783bc772f180c16b09424650a6381dd662d9ea6ecd00ba7894e7667.png