Home > Mobile >  Equivalence of movvar matlab function using python
Equivalence of movvar matlab function using python

Time:10-05

What is the equivalence of movvar(A, k, w) MATLAB function that calculates the moving average using python/numpy/pandas?

I tried pandas.rolling.mean() using this example from Matlab documentation but the result is not consistent:

A= [4, 8, 6, -1, -2, -3, -1, 3, 4, 5]
a = pd.Series(A)

print(a.rolling(window=3).mean())

0         NaN
1    6.000000
2    4.333333
3    1.000000
4   -2.000000
5   -2.000000
6   -0.333333
7    2.000000
8    4.000000
9         NaN
dtype: float64

# using Matlab
M = movvar(A, k=3, w=1)

M = 1×10

4.0000    2.6667   14.8889   12.6667    0.6667    0.6667    6.2222    4.6667    0.6667    0.2500

CodePudding user response:

You need rolling.var and specify center=True and min_periods=1 in the rolling and ddof=0 in the var

print(a.rolling(3, center=True, min_periods=1).var(ddof=0))
0     4.000000
1     2.666667
2    14.888889
3    12.666667
4     0.666667
5     0.666667
6     6.222222
7     4.666667
8     0.666667
9     0.250000
dtype: float64
  • Related