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 Center および File ExchangeEntering Commands についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by