Moving Average in a array with overlapping elements
5 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Jan
on 29 Jan 2018
Edited: Jan
on 29 Jan 2018
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.
More Answers (0)
See Also
Categories
Find more on Entering Commands in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!