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

# 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)));
end
```

## Products

No products are associated with this question.

Answer by Image Analyst on 1 May 2013

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)
```
```% ALTERNATE METHOD USING blocproc()
meanFilterFunction = @(theBlockStructure) mean(theBlockStructure.data(:));
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
```