MATLAB: Averaging Together Every N Columns

averagingdata manipulation

Hi!
I have a 16:10000 matrix (positive and negative decimal values) and want to reshape it to a 16:10 matrix by averaging each row every 1000 columns. What's the best way to do this?
Thanks very much! SE

Best Answer

This solution using the filter() command calculates interim results way beyond your need, but it's fast:
% Put in some pretend data
r = rand(16,10000);
% Define number of columns to average
AVG_COLS = 1000;
% Dimension over which to average
DIM = 2; % Columns
% Use filter to calculate the moving average across EVERY combination of columns
r_moving_avg = filter(ones(1,AVG_COLS)/AVG_COLS,1,r,[],DIM);
% Grab only the column averages that were actually wanted
r_avg = r_moving_avg(:,AVG_COLS:AVG_COLS:end)