How can I calculate the matrix every n-th elements in a vectorized way?

In MATLAB, given the 36 x 17 matrix A, I want to average every 6 elements of each column, creating a 6 x 17 matrix B. I can achieve this 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 the syntax is not too long, I was interested to know if I can achieve the same result in a more compact, efficient way (i.e. using bsxfunor arrayfun?)

+4
source share
3 answers

, reshape, 6, 3D, mean , 3D / 2D -

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

( Divakar, ):

N = size(A, 1)/6;
B = (repmat(eye(6), 1, N)*A)./N;
+7

, 2D :

  n = 6; % average every n-th element
  C = zeros(size(A, 1) - n + 1, 1);
  C(1:n:size(A, 1), :) = 1/(size(A, 1) / n);
  B = conv2(A, C, 'valid');

, , , , , 3D, Divakar ( ), , .

+3

Source: https://habr.com/ru/post/1675653/


All Articles