Moving Average in a array with overlapping elements

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

 采纳的回答

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 个评论

Thanks, both methods worked! I attempted tot use the 'movmean' command but it didn't work the way I wanted it to.

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 Entering Commands 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by