Y1 = fastmovav(X, w);
Y2 = accuratemovav(X, w);
The two functions return the moving average for the columns of matrix X, given a running window w. The first element of each column in Y1 or Y2 is the sample mean of the first w elements of the corresponding column of X. Thus, if X is m-by-n, Y1 and Y2 are (m-w+1)-by-n. The sliding window w must be greater than 1 and not greater than m.
The main functions are in two mex files, "fastmovingaverage.c" and "accuratemovingaverage.c", which must be compiled before using the functions in "fastmovav.m" and "accuratemovav.m".
The function fastmovav is extremely fast compared to any other alternative Matlab function that can be currently found on the web and that I am aware of. The drawback is that it may be slightly inaccurate.
The function accuratemovav is less fast than fastmovav but more accurate, and it is still very fast compared to any other alternative I am aware of.
% First of all, compile the mex functions:
% Some data:
T = 5000; N = 300; X = cumsum(randn(T, N)); w = ceil(T / 2);
% Fast moving average
tic, Y1 = fastmovav(X, w); toc
% Elapsed time is 0.034531 seconds.
% Accurate moving average
tic, Y2 = accuratemovav(X, w); toc
% Elapsed time is 6.504260 seconds.
% Check slow alternative with loops
Y3 = zeros(size(X, 1) - w + 1, size(X, 2));
for hh = 1:(size(X, 1) - w + 1)
Y3(hh, :) = mean(X(hh:hh+w-1, :));
% Elapsed time is 43.973435 seconds.
% Check accuracy
all(abs(Y1(:) - Y3(:)) < 1e-12)
all(abs(Y1(:) - Y3(:)) < 1e-15)
all(abs(Y2(:) - Y3(:)) < 1e-15)
% Another example with fastmovav - try a large matrix
T = 1e4; N = 2e3; X = cumsum(randn(T, N)); w = ceil(T / 2);
tic, Y = fastmovav(X, w); toc
% Elapsed time is 0.597617 seconds.