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