Suppose I have point array $y_i$ of size $N$. How to implement moving average algorithm that conserves quantity $$ I = \sum_{i=1}^{N}y_i $$ NOTE: I don't want time shift so I would prefer to use symmetric SMA in the middle: $$ \hat{y}_i = \frac{1}{n}\sum_{k = i-\frac{n-1}{2}}^{i+\frac{n-1}{2}}y_k $$ where $\hat{y}_i$ - filtered point, $n$ - window size of SMA.

It is easy to show that the above algorithm conserves $I$ "in the middle" but problem is when processing edges of a signal. So question is how to process edges of a signal in order to conserve $I$?

After several failures to construct simple method to do it I am here.

  • $\begingroup$ HiL I'm familar with moving averages but not the concept of conservation. could you explain what you mean by that in more detail ? $\endgroup$
    – mark leeds
    Oct 2 '18 at 8:09
  • $\begingroup$ That means that the sum of resulting points after filtering equals the of the sum of original ones. $\endgroup$
    Oct 2 '18 at 8:40

Why do you want to preserve the the sum? Is it to make the filter with the same gain everywhere?

If you want to keep the sum the same you need to pad the beginning and the end of the signal as: $$ .... ,y_2,y_1,y_0 ---- y_0,y_1, y_2,...., y_n ---- y_n, y_{n-1},y_{n-2}... $$ Example: suppose that you have 6 samples

$$ y_0, y_1, y_2, y_3,y_4, y_5 $$

and you want to to do a moving average with length 5:

Special treatment at the beginning:

$$ \hat y_0 = (y_1 + y_0 + y_0 + y_1 + y_2)/5, $$ $$ \hat y_1 = (y_0 + y_0 + y_1 + y_2 + y_3)/5 $$

Normal filtering:

$$ \hat y_2 = (y_0 + y_1 + y_2 + y_3 + y_4)/5, $$ $$ \hat y_3 = (y_1 + y_2 + y_3 + y_4 + y_5)/5, $$

Special treatment at the end:

$$ \hat y_4 = (y_2 + y_3 + y_4 + y_5 + y_5)/5, $$ $$ \hat y_5 = (y_3 + y_4 + y_5 + y_5 + y_4)/5, $$

  • $\begingroup$ Firstly, thank you for an answer. Simple. Secondly, answering your question, in our experiments integral (sum) is the most significant value, based on which many results have been obtained. On the other hand, it is needed to fit each signal some function in order to determine some quantity. Filtering is just preprocessing before fit. So I don't want to change integral distribution. $\endgroup$
    Oct 2 '18 at 10:22
  • $\begingroup$ To add: The matlab/ octave command circshift would be useful for this to avoid special treatment. Also this toolbox of file exchange does a "circular mean" directly as well as other circular statistics mathworks.com/matlabcentral/fileexchange/… $\endgroup$ Oct 2 '18 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.