4.3. Moving Window Statistics

A moving window is a contiguous subset of a vector that is used to compute local statistics. At each step, the window advances to include one new value and leaves off one old value. A statistic is calculated over the values in the window and placed at the corresponding center position of the returned data. The resulting vector reduces some of the fluctuations that are found in the original vector. MATLAB provides functions for performing several statistical operations on moving windows. The moving window functions are listed in Table 4.1. These functions all use the same syntax.

>> y = movmean(x,k)
Outputs
y – Result of the k-point moving mean applied to the data in x.
Inputs

x – Array of data.

k – Number of points in the window.

Table 4.1 Moving Window Functions
Function Description
movmin Moving minimum
movmax Moving maximum
movsum Moving sum
movmean Moving mean
movmedian Moving median
movstd Moving standard deviation
movvar Moving variance

The commands below show how the values are calculated using the movmean function with a window size of 7. Notice that the first three values are calculated with a shortened window size. The full window size is used beginning with the fourth term. The window advances for the first time to not include the first data value at the fifth term. A shortened window size is similarly used at the end of the vector. You can change this behavior by specifying the optional 'Endpoints' argument. A plot of the original data and the filtered data from the movmean function is shown in Fig. 4.2.

>> x = linspace(0, 6, 20);
>> y = 5*x - 0.3*x.^2 + sin(3*x);
>> y1 = movmean(y, 7);
>> y(1:8)
ans =
         0  2.3609  3.9862  4.7626  5.2336  6.1471  7.8329  9.9281
>> y1(1:5)
ans =
    2.7774  3.2687  3.7484  4.3319  5.7502

>> sum(y(1:4))/4
ans =
    2.7774       % y1(1) - startup, short window
>> sum(y(1:5))/5
ans =
    3.2687       % y1(2) - startup, short window
>> sum(y(1:7))/7
ans =
    4.3319       % y1(4) - first full window mean
>> sum(y(2:8))/7
ans =
    5.7502       % y1(5) - window advanced
../_images/movWind.png

Fig. 4.2 The moving window mean smooths the data fluctuations.

As with other statistical functions in MATLAB, if \bf{X} is a matrix, the function is applied to the columns of \bm{x} independently. You can change this behavior by specifying an optional dimension argument. You can also provide an optional flag to specify how NaN values are handled.

Note

Now complete Temperature Data Project.