Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum up every nth row in Matlab

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?

like image 436
vaitas Avatar asked Nov 29 '22 11:11

vaitas


1 Answers

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,[]).'
like image 120
Robert Seifert Avatar answered Dec 04 '22 12:12

Robert Seifert