Moving Average in a array with overlapping elements

5 visualizaciones (últimos 30 días)
Saurabh Sawant
Saurabh Sawant el 29 de En. de 2018
Comentada: Saurabh Sawant el 29 de En. de 2018
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

Respuesta aceptada

Jan
Jan el 29 de En. de 2018
Editada: Jan el 29 de En. de 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.
  1 comentario
Saurabh Sawant
Saurabh Sawant el 29 de En. de 2018
Thanks, both methods worked! I attempted tot use the 'movmean' command but it didn't work the way I wanted it to.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Entering Commands en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by