Octave time series Moving average

AlgoMan picture AlgoMan · Jun 25, 2010 · Viewed 18.4k times · Source

I have a matrix with each column represents a feature over time. I need to find the moving average of these values with a given window size.

Is there a function like the one in MATLAB?

output = tsmovavg(vector, 's', lag, dim)

Answer

Amro picture Amro · Jun 25, 2010

You can use the FILTER function. An example:

t = (0:.001:1)';                                %#'
vector = sin(2*pi*t) + 0.2*randn(size(t));      %# time series

wndw = 10;                                      %# sliding window size
output1 = filter(ones(wndw,1)/wndw, 1, vector); %# moving average

or even use the IMFILTER and FSPECIAL from the Image Package

output2 = imfilter(vector, fspecial('average', [wndw 1]));

One final option is using indexing (not recommended for very large vector)

%# get indices of each sliding window
idx = bsxfun(@plus, (1:wndw)', 0:length(vector)-wndw);
%'# compute average of each
output3 = mean(vector(idx),1);

Please note the difference in padding: output1(wndw:end) corresponds to output3