Moving Average using a for loop

9 ビュー (過去 30 日間)
Lisa Justin
Lisa Justin 2014 年 4 月 22 日
編集済み: Jan 2014 年 4 月 22 日
Hi, How can I compute the moving average using a for loop and without using convolution (i.e conv()) or the filter function (i.e filter())?
  2 件のコメント
Jan
Jan 2014 年 4 月 22 日
If this is a homework question, and it does sound like it is one, please state this explicitly. Then show us, what you have tried so far and ask a specific question. We are not going to solve your homework.
Jan
Jan 2014 年 4 月 22 日
Did you try anything to solve this problem by your own? What about asking your favorite internet search engine for Matlab code for a moving average? You'd find many many solutions in the FileExchange.

サインインしてコメントする。

回答 (1 件)

Star Strider
Star Strider 2014 年 4 月 22 日
This seems to work:
data = rand(1,50); % Data
Dlen = length(data);
fltr = ones(1,5); % Filter
Flen = length(fltr);
datax = [data ones(1,Flen)*mean(data)]; % Pad ‘data’ vector with ones*mean(data)
mavg = [];
for k1 = 1:(Dlen)
mavg = [mavg (fltr * datax(k1:k1+Flen-1)')/Flen];
end
figure(1)
plot([1:Dlen], data)
hold on
plot([1:Dlen], mavg, '-r')
hold off
grid
  1 件のコメント
Jan
Jan 2014 年 4 月 22 日
編集済み: Jan 2014 年 4 月 22 日
The iterative growing of the output vector is extremely inefficient. Look for the term "pre-allocation" in this forum to find faster methods.
You can avoid a lot of divisions, if you apply the /FLen once to fltr instead of doing this in each iteration.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeCorrelation and Convolution についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by