MATLAB movmean and movmedian Function
Introduction
MATLAB提供移动(局部)均值和移动(局部)中值的计算函数movmean和movmedian,它们的属性设置基本一致。本文以movmean函数为例进行详细地解释。
Examples
Centered Moving Average of Vector
Example 1: movmean(A, 3)
1
2
3
4
clc, clear, close all
A = [4 8 6 -1 -2 -3 -1 3 4 5];
M1 = movmean(A, 3);
1
2
M1 =
6.0000 6.0000 4.3333 1.0000 -2.0000 -2.0000 -0.3333 2.0000 4.0000 4.5000

当设置window为3时,默认情况下不减少数组的维度,第一个和最后一个窗口的长度为2。
Example 2: movmean(A, 3, 'Endpoints', 'discard')
该函数在默认情况下,'Endpoint'属性是'shrink',表示“Shrink the window size near the endpoints of the input to include only existing elements”。如果想要软件只计算Full-Window Averages,可以进行下面的设置,表示“Do not output any averages when the window does not completely overlap with existing elements”:
1
M2 = movmean(A, 3, 'Endpoints', 'discard');
1
2
M2 =
6.0000 4.3333 1.0000 -2.0000 -2.0000 -0.3333 2.0000 4.0000
此时,数组的维度减少到$(10-(3-1))$:

Example 3: movmean(A, 4)
如果窗口的长度为偶数:
1
M3 = movmean(A, 4);
1
2
M3 =
6.0000 6.0000 4.2500 2.7500 0 -1.7500 -0.7500 0.7500 2.7500 4.0000

Example 4: movmean(A, 4, 'Endpoints', 'discard')
同样地,只计算Full-Window Averages:
1
M4 = movmean(A, 4, 'Endpoints', 'discard');
1
2
M4 =
4.2500 2.7500 0 -1.7500 -0.7500 0.7500 2.7500

Trailing Moving Average of Vector
Example 1: movmean(A, [2, 1])
M = movmean(A,[kb kf]) computes the mean with a window of length kb+kf+1 that includes the element in the current position, kb elements backward, and kf elements forward.这种情况可以将使滑动平均不包含“未来值”。
如:
1
M5 = movmean(A, [2, 1]);
1
2
M5 =
6.0000 6.0000 4.2500 2.7500 0 -1.7500 -0.7500 0.7500 2.7500 4.0000

Example 2: movmean(A, [2, 1], 'Endpoints', 'discard')
同样地,只计算Full-Window Averages:
1
M6 = movmean(A, [2, 1], 'Endpoints', 'discard');
1
2
M6 =
4.2500 2.7500 0 -1.7500 -0.7500 0.7500 2.7500

Example 3: movmean(A, [2, 0])
如果只由“过去值”计算均值:
1
M7 = movmean(A, [2, 0]);
1
2
M7 =
4.0000 6.0000 6.0000 4.3333 1.0000 -2.0000 -2.0000 -0.3333 2.0000 4.0000

Example 4: movmean(A, [2, 0], 'Endpoints', 'discard')
同样地,如果只计算Full-Window Averages:
1
M8 = movmean(A, [2, 0], 'Endpoints', 'discard');
1
2
M8 =
6.0000 4.3333 1.0000 -2.0000 -2.0000 -0.3333 2.0000 4.0000

参考
[1] movmean - MathWorks.
[2] movmedian - MathWork.