MATLAB Answers

Eric Sampson

How to perform a 'chunked average', similar to a rolling average?

Asked by Eric Sampson
on 1 May 2013

Hi, I don't know what the right terminology is, but I'd like to know if there is a nice vectorized syntax for calculating a 'chunked' average/max/etc over a vector. Basically for any given average/max/etc type function, I'd like to do something like this:

for chunk = 1:num_chunks
  chunked_max(chunk) = average(input(chunk_start_index(chunk):chunk_end_index(chunk)));

Thanks for your thoughts!



No products are associated with this question.

1 Answer

Answer by Image Analyst
on 1 May 2013
 Accepted answer

Take your vector and reshape it into a 2D matrix and then call mean(). Or you could use blocproc(). Here's a little demo for you:

% Generate sample data.
m = randi(9, [1, 24])
[mRows mCols] = size(m);
% Reshape it into a 2D matrix.
% Turn into a row vector if necessary.
numberOfRows = 8;
numberOfColumns = 3;
m2 = reshape(m(:), [numberOfRows, numberOfColumns])
% IMPORTANT: the (:) helps make sure it doesn't matter if m
% is a row vector or a column vector to start with.
% Now take the mean within each columns, 
% going down the rows to get the mean,
% before moving over to the next column.
theMeans = mean(m2, 1)
meanFilterFunction = @(theBlockStructure) mean(;
blockSize = [1 numberOfRows];
theMeansBP = blockproc(m, blockSize, meanFilterFunction)

Sample data in the command window:

m =
     6     2     6     8     5     6     8     3     6     2     5     8     9     5     3     6     9     5     9     2     2     3     4     4
m2 =
     6     6     9
     2     2     5
     6     5     9
     8     8     2
     5     9     2
     6     5     3
     8     3     4
     3     6     4
theMeans =
                       5.5                       5.5                      4.75
theMeansBP =
                       5.5                       5.5                      4.75


Brilliant example of 'out of the box' thinking, I neglected to consider reshaping the original matrix! If the desired numberOfColumns*numberOfRows ~= numel(m), is there a nice syntax to tell MATLAB to fill the 'leftover' entries with NaNs?

Yeah, but not so out of the box. This is asked so often that it really should be in the FAQ and I just gave the standard answer. Well, maybe a little better than the standard since my code works for column vectors as well as row vectors and many people don't prepare for that so their code only works for one direction or the other. But I wasn't the first one to think of this approach, though it is somewhat clever. Even another approach is to use conv() to take a moving average where the box slides along one element at a time, and then subsample it.

Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

MATLAB Academy

New to MATLAB?

Learn MATLAB today!