Search code examples
arraysmatlabmatrixvectorization

What is an elegant way to add n adjacent rows in a matrix in Matlab?


For example, for a matrix:

A = [1 2; 
     3 4; 
     5 6; 
     7 8; 
     9 10; 
     11 12]

the output would be

B = [4 6; 
     12 14; 
     20 22]

if I sum every two adjacent rows in the matrix.

ps: it would be a plus if also the function works on column vectors to sum n adjacent entries.


Solution

  • You can do this with reshape and sum:

    k = 2; % how many elements to sum
    n = size(A,1)/k;
    out = reshape(A, k, n, []);
    out = sum(out, 1);
    out = reshape(out, n, []);
    

    Of course, n must be an integer. That is, the height of the matrix must be evenly divisible by k.

    This will work for any number of columns, including a Nx1 matrix (==column vector).

    (I wrote this out in separate lines to make it clearer what is happening, but of course you can turn this into a one-liner if you're so inclined.)