Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving mean on a circle

Tags:

matlab

mean

Is there a way to calculate a moving mean in a way that the values at the beginning and at the end of the array are averaged with the ones at the opposite end?

For example, instead of this result:

A=[2 1 2 4 6 1 1];
movmean(A,2)
ans = 2.0 1.5 1.5 3.0 5 3.5 1.0

I want to obtain the vector [1.5 1.5 1.5 3 5 3.5 1.0], as the initial array element 2 would be averaged with the ending element 1.

like image 576
shamalaia Avatar asked Aug 21 '17 02:08

shamalaia


2 Answers

Generalizing to an arbitrary window size N, this is how you can add circular behavior to movmean in the way you want:

movmean(A([(end-floor(N./2)+1):end 1:end 1:(ceil(N./2)-1)]), N, 'Endpoints', 'discard')

For the given A and N = 2, you get:

ans =

1.5000    1.5000    1.5000    3.0000    5.0000    3.5000    1.0000
like image 163
gnovice Avatar answered Sep 25 '22 03:09

gnovice


For an arbitrary window size n, you can use circular convolution with an averaging mask defined as [1/n ... 1/n] (with n entries; in your example n = 2):

result = cconv(A, repmat(1/n, 1, n), numel(A));
like image 40
Luis Mendo Avatar answered Sep 22 '22 03:09

Luis Mendo