Moving Average in a array with overlapping elements

조회 수: 5 (최근 30일)
Saurabh Sawant
Saurabh Sawant 2018년 1월 29일
댓글: Saurabh Sawant 2018년 1월 29일
I have an array with say 100 elements, I want to take the moving average of the first 8 (1:8) then the next 8(2:9) and then the next set and so on, until there are 100 averages. I know I have to use a loop of some sort, but I dont know how to do it.
Here is what I have so far;
for i=8:100
MA8(i)= sum(C(i:i+8))/8;
end
with some array C with 100 elements

채택된 답변

Jan
Jan 2018년 1월 29일
편집: Jan 2018년 1월 29일
Your code does almost work. Start at 1 and stop at 100-8+1. Note that 8 elements have the indices i:i+7, not i:i+8.
w = 8;
MA8 = zeros(1, 100 - w + 1); % Pre-allocation
for k = 1:100 - w + 1
MA8(k) = sum(C(k:(k+w-1))) / 8;
end
The output must be shorter than the input. The pre-allocation avoids to let the array grow iteratively, because this is very expensive. I use "k" as loop counter instead of "i" to reduce the danger of confusions with the imaginary unit "i". This is recommended in the documentation (see also: https://www.mathworks.com/matlabcentral/answers/46648-using-i-and-j-as-variables)
Do you know the movmean command?
MA8 = movmean(C, 8, 'Endpoints', 'discard');
Much faster and easier than writing your own loop.
  댓글 수: 1
Saurabh Sawant
Saurabh Sawant 2018년 1월 29일
Thanks, both methods worked! I attempted tot use the 'movmean' command but it didn't work the way I wanted it to.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Entering Commands에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by