필터 지우기
필터 지우기

Moving average - for loop vectorization

조회 수: 2 (최근 30일)
Dawid Smolen
Dawid Smolen 2016년 4월 21일
댓글: Stephen23 2018년 12월 5일
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.

채택된 답변

Stephen23
Stephen23 2016년 4월 21일
편집: Stephen23 2016년 4월 21일
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
yari lazzaro
yari lazzaro 2018년 12월 4일
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 2018년 12월 5일
@yari lazzaro: Use conv2 with a row vector.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by