Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
the_wicked Avatar asked Oct 21 '25 05:10

the_wicked


2 Answers

Here's another solution using splitapply. It works even if n does not divide the number of rows of A (the last group will then be smaller). The key is to create a vector of integers defining the groups (last input of splitapply).

A = [1 2; 3 4; 5 6; 7 8; 9 10; 11 12; 13 14]; % 7 rows
n = 2; % number of adjacent rows to add
B = splitapply(@(x) sum(x,1), A, ceil((1:size(A,1))/n).');

results in

A =
     1     2
     3     4
     5     6
     7     8
     9    10
    11    12
    13    14
B =
     4     6
    12    14
    20    22
    13    14
like image 154
Luis Mendo Avatar answered Oct 23 '25 22:10

Luis Mendo


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

like image 33
Cris Luengo Avatar answered Oct 23 '25 20:10

Cris Luengo