Filter löschen
Filter löschen

Moving average - for loop vectorization

2 Ansichten (letzte 30 Tage)
Dawid Smolen
Dawid Smolen am 21 Apr. 2016
Kommentiert: Stephen23 am 5 Dez. 2018
Hello. I've got a problem that my loop doesn't execute fast enough, even though it is simple moving average. Is there any smart way to make it work faster? x is a huge array, and there is some indexing using : in every iteration, that's probably the reason.
len = length(x); % around 6000000
A = 1/200;
for n = 100+1:len-100
MA = A*sum(x(n - 100: n + 100));
% Do something with MA. However I know that the above part is the slow one
end
I was trying to find some information about vectorization, but I can't see how could I apply these methods.

Akzeptierte Antwort

Stephen23
Stephen23 am 21 Apr. 2016
Bearbeitet: Stephen23 am 21 Apr. 2016
To efficiently calculate a moving average you should use conv, something like this:
>> xi = 0:0.1:2*pi;
>> yi = sin(xi)+0.4*rand(size(xi))-0.2;
>> N = 4; % length of moving average
>> yo = conv(yi,ones(1,N),'same')/N;
>> plot(xi,yi, xi,yo)
  3 Kommentare
yari lazzaro
yari lazzaro am 4 Dez. 2018
Hi, do you know how this solution could be adapted in case I want to calculate a moving average along the rows of a matrix? Thanks
Stephen23
Stephen23 am 5 Dez. 2018
@yari lazzaro: Use conv2 with a row vector.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by