# mavg {#mavg}

## Syntax {#syntax}

`mavg(X, window|weights, [minPeriods])`

Please see [mFunctions](../Themes/mFunctions.md) for the parameters and windowing logic.

## Details {#details}

If *X* is a vector, return a vector of the same length as *X*. If the second parameter is:

-   *window*: Calculate the moving averages of *X* in a sliding window of length *window*.

-   *weights*: A weight vector used to alculate the moving weighted averages of *X* in a sliding window of length *weights*. The order of weights corresponds one-to-one with the data in the window. The length of *weights* \(the weight vector\) must be in \[0,1024\]. Return NULL for the first *\(size\(weights\) - 1\)* elements. If *weights* is specified, the parameter *minPeriods* doesn't take effect.


If *X* is a matrix/table, conduct the aforementioned calculation within each column of *X*. The result is a matrix with the same shape as *X*.

## Examples {#examples}

```
X = 7 4 6 0 -5 32 9 8;
Y = 7 4 6 NULL -5 32 9 8;
weight = 2 3 5

mavg(X, 4);
// output: [,,,4.25,1.25,8.25,9,11]

mavg(Y, 4);
// output: [,,,5.67,1.67,11,12,11]

mavg(Y, weight);
// output: [,,5.6,5.2,-1.8571,18.125,13.1,13.1]
```

```
m=matrix(1 NULL 4 NULL 8 6 , 9 NULL NULL 10 NULL 2)
m.rename!(2020.01.06 2020.01.07 2020.01.09 2020.01.11 2020.01.12 2020.01.15, `col1`col2)
m.setIndexedMatrix!()
mavg(m, 3d) // equivalent to mavg(m, 3)
```

|label|col1|col2|
|-----|----|----|
|2020.01.06|1|9|
|2020.01.07|1|9|
|2020.01.09|4||
|2020.01.11|4|10|
|2020.01.12|8|10|
|2020.01.15|6|2|

```
mavg(m, 1w)
```

|label|col1|col2|
|-----|----|----|
|2020.01.06|1|9|
|2020.01.07|1|9|
|2020.01.09|2.5|9|
|2020.01.11|2.5|9.5|
|2020.01.12|4.3333|9.5|
|2020.01.15|6|6|

Related functions: [avg](../a/avg.md)

