How do I fix this code to get a proper moving average plot?

7 次查看(过去 30 天)
This is a homework question. I was given a set of wind speed data, and was asked to calculate moving averages as well as other information using MATLAB. Specifically, for the moving average, I am not allowed to use movmean, conv, filter, smooth or any other built in functions. So I made my own function, but its not giving the proper output. I know my plot using my function is wrong since it does not give me the same plot when I check with movmean.
This is the plot I get using movmean:
using_movmean.png
This is the plot I get using my own function:
my_own_function.png
I have attached both the data set and the .m file for the code. Any help would be very much appreciated. Thank you!

采纳的回答

Shubham Gupta
Shubham Gupta 2019-9-25
Your basic function 'running_avg' seeems to be working perfectly. However, If you want answers exactly as you would get using movmean then you should understand how movmean works.
movmean does center averaging ( there are other modes for averaging too but default is center ).
Center averaging is basically to find average by keeping the current element at the center and then take previous and future elements to make the array of size specified by window. Now,
When the window is even, average is centered about the current and previous elements.
When the window is odd, average is centered about the current element.
Note : When the window needs to be shorten due to array's indexing at the endpoints, the average is taken over only the elements that can fit in the window. For e.g. if we 3 previous elements but there are only 2 previous elements then, movmean will take only 2 previous elements and shortens the window to be averaged by 1.
So, you will have to change the code for your function 'running_avg' accordingly to get output 'exactly' as movmean.
  4 个评论
Shubham Gupta
Shubham Gupta 2019-9-25
You mean at the start ? That's because you have set "avg" to 0 for "i" smaller than window size. So now, the moving mean will be zero for indeces smaller than window size. Instead you can shorten the window size and increase it with each increment of "i" till it becomes equal to window size.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Matrix Indexing 的更多信息

标签

产品


版本

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by