0

I wrote a script to compute simple moving average of a vector using for-loop:

X=rand(1000,1); 
Y=nan(size(A));
for i=100:length(A);
    Y(i)=mean(X(i-99:i));
end

Could I use any vectorization method to avoid the loop? Thanks.

GK.Ai
  • 23
  • 5

1 Answers1

0

You can easily avoid the loop by using either convolution (conv) or smooth if you have the curve fitting toolbox.

filterSize = 5;
Y = conv(X, ones(1, filterSize) / filterSize, 'same');

% Or with the curve-fitting toolbox
Y = smooth(X, filterSize);
Suever
  • 64,497
  • 14
  • 82
  • 101