Computing a moving average

淺唱寂寞╮ 提交于 2019-11-28 11:40:20

There are two more alternatives:

1) filter

From the doc:

You can use filter to find a running average without using a for loop. This example finds the running average of a 16-element vector, using a window size of 5.

data = [1:0.2:4]'; %'
windowSize = 5;
filter(ones(1,windowSize)/windowSize,1,data)

2) smooth as part of the Curve Fitting Toolbox (which is available in most cases)

From the doc:

yy = smooth(y) smooths the data in the column vector y using a moving average filter. Results are returned in the column vector yy. The default span for the moving average is 5.

%// Create noisy data with outliers:

x = 15*rand(150,1); 
y = sin(x) + 0.5*(rand(size(x))-0.5);
y(ceil(length(x)*rand(2,1))) = 3;

%//  Smooth the data using the loess and rloess methods with a span of 10%:

yy1 = smooth(x,y,0.1,'loess');
yy2 = smooth(x,y,0.1,'rloess');

In 2016 MATLAB added the movmean function that calculates a moving average:

N = 9;
M_moving_average = movmean(M,N)

Using conv is an excellent way to implement a moving average. In the code you are using, wts is how much you are weighing each value (as you guessed). the sum of that vector should always be equal to one. If you wish to weight each value evenly and do a size N moving filter then you would want to do

N = 7;
wts = ones(N,1)/N;
sum(wts) % result = 1

Using the 'valid' argument in conv will result in having fewer values in Ms than you have in M. Use 'same' if you don't mind the effects of zero padding. If you have the signal processing toolbox you can use cconv if you want to try a circular moving average. Something like

N = 7;
wts = ones(N,1)/N;
cconv(x,wts,N);

should work.

You should read the conv and cconv documentation for more information if you haven't already.

I would use this:

% does moving average on signal x, window size is w
function y = movingAverage(x, w)
   k = ones(1, w) / w
   y = conv(x, k, 'same');
end

ripped straight from here.

To comment on your current implementation. wts is the weighting vector, which from the Mathworks, is a 13 point average, with special attention on the first and last point of weightings half of the rest.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!