Help on calculating cumulative moving average

21 次查看(过去 30 天)
Okay I need help , because I have been trying to solve this for the past 6 hours :(
I am importing a data set with importdata(filename)
And its 1 Column with a 1000 rows of numbers
So I have been trying to compute and output the cumulative moving average. eg. [1, 2 , 3 ] would compute into a row of values :
Below is the maths for It.
1. 1/1 = 1
2. 1+2/2 = 1.5
3. 1+2 +3 /3 = 2 etc
This is the code I got so far RA = movmean(A,2); disp('Moving Average of all the data: '); disp(RA);
but it is outputting incorrect values.
preferably im trying to make a function to do the cumulative moving average rather than use built in function
thanks
edit I have added A = importdata(filename);
size(A); NumberOfRows=1000; NumberOfColums=1;
disp(A)
so hopefully it wil be easier now :S

回答(2 个)

Chris Turnes
Chris Turnes 2016-10-17
If you're trying to do a cumulative moving mean, where each time you move to the next element it is the mean of that element and all elements before it, then instead try:
b = movmean(A, [length(A)-1 0]);
By default, since Endpoints are shrink, this will give you b(1) = A(1), b(2) = 1/2*(A(1) + A(2)), b(3) = 1/3*(A(1) + A(2) + A(3)), etc.

David Goodmanson
David Goodmanson 2016-10-14
编辑:David Goodmanson 2016-10-14
movmean doesn't work because it uses a fixed window width and yours increases as you go. The command B = cumsum(A) will give you the moving sum of terms that you need. The vector n = (1:length(A))' will give you the denominator for calculating the average, where ' turns the row vector into a column vector. Then if you divide these two quantities term-by-term with ./ you should get the result.
It's always a good idea to try this on a short vector and view it.

类别

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

产品

Community Treasure Hunt

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

Start Hunting!

Translated by