MATLAB: How to sum every nth row

easyquestionsum

If there's a matrix, for example:
A = [1 2 3 4 5 6 ; 1 3 5 7 9 11 ; 2 4 6 8 10 12]'
A =
1 1 2
2 3 4
3 5 6
4 7 8
5 9 10
6 11 12
7 13 14
I'm trying to sum 3 rows at a time (like an attached jpg file).
So I want to get:
B =
6 9 12
15 27 30
7 13 14
Thanks a lot!

Best Answer

A = [1 2 3 4 5 6 7; 1 3 5 7 9 11 13; 2 4 6 8 10 12 14]';
[n,col] = size(A);
index = 1:n;
elem = [repmat(3,1,floor(n/3))];
endv = n-sum(elem);
if(~endv)
endv = [];
end
index = mat2cell(index,1,[elem,endv])';
B = cell2mat(cellfun(@(x) sum(A(x,:),1),index,'un',0));
B =
6 9 12
15 27 30
7 13 14