How to perform a 'chunked average', similar to a rolling average?
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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
Thanks for your thoughts!
0 commentaires
Réponse acceptée
Image Analyst
le 1 Mai 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
2 commentaires
Image Analyst
le 1 Mai 2013
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.
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!