Implementing an efficient rolling average algorithm with stride tricks
Stride tricks can be useful for local computations on arrays, when the computed value at a given position depends on the neighboring values. Examples include dynamical systems, digital filters, and cellular automata.
In this recipe, we will implement an efficient rolling average algorithm (a particular type of convolution-based linear filter) with NumPy stride tricks. A rolling average of a 1D vector contains, at each position, the average of the elements around this position in the original vector. Roughly speaking, this process filters out the noisy components of a signal so as to keep only the slower components.
Getting ready
Make sure to reuse the id()
function from the Understanding the internals of NumPy to avoid unnecessary array copying recipe. This function returns the memory address of the internal data buffer of a NumPy array.
How to do it...
The idea is to start from a 1D vector, and make a virtual 2D array where...