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
?)
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))
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With