Search code examples
matlabmatrixvectorizationmeanbsxfun

How can I average a matrix every nth elements in a vectorized way?


In MATLAB, given a 36 x 17 matrix A, I want to average every 6th elements of each column, creating a 6 x 17 matrix B. I can achieve it using the following code:

A = rand(36, 17);

B = [mean(A(1:6:36,:)); mean(A(2:6:36,:)); mean(A(3:6:36,:)); mean(A(4:6:36,:)); mean(A(5:6:36,:)); mean(A(6:6:36,:))];

Although syntax is not excessively long, I was wondering if I could achieve the same result through a more compact, efficient way (i.e. using bsxfun or arrayfun?)


Solution

  • As mentioned in the comments, reshape to basically split the first dim into two with the former of length 6 to have a 3D array and then use mean along the latter of those two, which would be second dim in the 3D array and a final reshape/squeeze for 2D output -

    B = squeeze(mean(reshape(A,6,[],size(A,2)),2))