I've got a vector and I want to calculate the moving average of it (using a window of width 5).
For instance, if the vector in question is [1,2,3,4,5,6,7,8], then
- the first entry of the resulting vector should be the sum of all entries in
[1,2,3,4,5](i.e.15); - the second entry of the resulting vector should be the sum of all entries in
[2,3,4,5,6](i.e.20); - etc.
In the end, the resulting vector should be [15,20,25,30]. How can I do that?
The
convfunction is right up your alley:Benchmark
Three answers, three different methods... Here is a quick benchmark (different input sizes, fixed window width of 5) using
timeit; feel free to poke holes in it (in the comments) if you think it needs to be refined.convemerges as the fastest approach; it's about twice as fast as coin's approach (usingfilter), and about four times as fast as Luis Mendo's approach (usingcumsum).Here is another benchmark (fixed input size of
1e4, different window widths). Here, Luis Mendo'scumsumapproach emerges as the clear winner, because its complexity is primarily governed by the length of the input and is insensitive to the width of the window.Conclusion
To summarize, you should
convapproach if your window is relatively small,cumsumapproach if your window is relatively large.Code (for benchmarks)