I just have some results; looks like cumulative sum is the way to go:
%%%%%%% data = "" %make random data to test the moving average codes.
% original version. feel free to preallocate on avgs1; it sped things up by about 5 second for me,
% but still not as fast as the other two methods. tic avgs1=[]; for i=1:9001 avgs1(i,:) = sum(data(i:(999+i),:),1)/1000; end t1=toc
% add new data, remove old data on each iteration. tic
avgs2 = zeros(9001,20); avgs2(1,:) = sum(data(1:1000,:),1)/1000; for i=2:9001 avgs2(i,:) = avgs2(i-1,:) + (data(999+i,:) - data(i-1,:))/1000; end t2=toc
% Check if we have the same result as the original method by taking the norm of the difference.
norm1 = norm(avgs1-avgs2) norm2 = norm(avgs1-avgs3) %%%%%%%
I get the result: t1 = 6.0183 t2 = 0.34102 t3 = 0.012001