Help on calculating cumulative moving average

13 views (last 30 days)
nc on 14 Oct 2016
Edited: nc on 20 Jan 2017
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
edit I have added A = importdata(filename);
size(A); NumberOfRows=1000; NumberOfColums=1;
so hopefully it wil be easier now :S

Answers (2)

Chris Turnes
Chris Turnes on 17 Oct 2016
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 on 14 Oct 2016
Edited: David Goodmanson on 14 Oct 2016
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.

Community Treasure Hunt

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

Start Hunting!