What you see here is the bass implementation of a finite impulse response (FIR) filter that implements the boxcar window function . Thinking about the problem in terms of DSP, you need to filter your incoming vector with equal FIR coefficients NO_OF_NEIGHBOURS , each of which has a value of 1/NO_OF_NEIGHBOURS . It is usually better to use the established algorithm, rather than reinvent the wheel.
Here is a rather messy implementation that I quickly developed, and the filters are doubled. You can easily change this to filter your data type. The demo shows the filtering of several cycles of the upward saw function (0, .25, .5,1) for demonstration purposes only. It compiles, so you can play with it.
#include <iostream>
Increase the number of filter coefficients using this line to see a smoother result. There is no smoothing with one filter coefficient.
boxFIR box(1);
The code is flexible enough so you can even change the shape of the window if you want. Do this by changing the coefficients defined in the constructor.
Note: this will give a slightly different result of your implementation, since it is a causal filter (it depends only on the current selection and previous samples). Your implementation is not causal, as it expects the future in future samples in order to get the average value, and therefore you need conditional operators for the situation when you are approaching the end of the vector. If you want to get a result similar to what you are trying to do with your filter using this algorithm, run your vector using this algorithm in the reverse order (this works fine while the window function is symmetrical). Thus, you can get a similar conclusion without the unpleasant conditional part of the algorithm.
source share