Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?)

like image 888
AJMA Avatar asked Dec 01 '22 11:12

AJMA


2 Answers

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))
like image 86
Divakar Avatar answered Dec 05 '22 11:12

Divakar


For the curious, this can also be done with matrix multiplication (close in efficiency to Divakar's answer, even a little faster in some cases):

N = size(A, 1)/6;
B = (repmat(eye(6), 1, N)*A)./N;
like image 45
gnovice Avatar answered Dec 05 '22 13:12

gnovice