Is there any easy way to sum up every nth row in Matlab? Lets say I have:
A =
1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18
I wish to add every 2 rows, like this: row1+row3+row5
, and then row2+row4+row6
, so my output is:
B =
21 24 27
30 33 36
I know that it is possible to do it by sum(A(1:2:end,:))
but this is not helpful if you have large matrix and many nth rows, for
loop is another option but I couldn't get it working so far. Do you have any suggestions/solutions how this could be solved with a for
loop, or maybe there is a built-in function?
How about that?
B = cell2mat(arrayfun(@(x) sum(A(x:n:end,:)),1:n,'uni',0)')
I first thought about using accumarray
but it requires a vector as input. It's still possible, if you follow this answer.
Another accumarray alternative:
[a,b] = size(A);
idx = bsxfun(@plus, 1:b,repmat([0:b:b*n-1]',a/n,1))
B = reshape(accumarray(idx(:),A(:)),b,[]).'
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