function for calculating moving average

1 回表示 (過去 30 日間)
ammar ansari
ammar ansari 2015 年 5 月 17 日
コメント済み: ammar ansari 2015 年 5 月 18 日
Write a function called moving_average that takes a scalar called x as an input argument and returns a scalar. The value it returns depends not only on the input but also on previous inputs to this same function when the function is called repeatedly. That returned value is a “moving average” of those inputs. The function uses a “buffer” to hold previous inputs, and the buffer can hold a maximum of 25 inputs. Specifically, the function must save the most recent 25 inputs in a vector (the buffer) that is a persistent variable inside the function. Each time the function is called, it copies the input argument into an element of the buffer. If there are already 25 inputs stored in the buffer, it discards the oldest element and saves the current one in the buffer. After it has stored the input in the buffer, it returns the mean of all the elements in the buffer. Thus, for each of the first 24 calls to the function, the function uses only the inputs it has received so far to determine the average (e.g., the first call simply returns x, the second call averages x and the input from the first call, etc.), and after that, it returns the average of the most recent 25 inputs.

回答 (1 件)

Image Analyst
Image Analyst 2015 年 5 月 17 日
編集済み: Image Analyst 2015 年 5 月 17 日
Hints: persistent, isempty(), and mean(). To "discard" an element:
buffer(index) = []; % Get rid of element at "index"
  7 件のコメント
Image Analyst
Image Analyst 2015 年 5 月 18 日
It is not mandatory or even advised. Who said anything about add? Plus it's obvious you're totally ignoring all my recommendations and doing it your own, much more complicated, way with a bunch of unneeded code. Good luck though.
ammar ansari
ammar ansari 2015 年 5 月 18 日
Everyone has his own way of thinking I took your advice and whatever code come into my mind I used it. Don't take it personal.

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

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by