MATLAB: Sum columns of matrix

columnsloopsumsummationvectorization

If I have a 3×6 matrix like this
1 5 2 4 3 2
2 3 1 4 4 1
4 5 2 2 3 1
how can i sum(without a loop) columns 1:2, 3:4, 5:6, to form a new 3×3 matrix?
And if have a 3×12 like this
2 1 2 1 1 5 5 4 4 2 4 5
3 5 1 3 1 2 5 3 3 4 5 4
2 4 2 1 5 5 4 3 2 2 1 5
how can i sum(without a loop) columns 1:3,4:6,7:9,10:12, to form a new 3×4 matrix?
Is there a general formula that will work for both situations?

Best Answer

>> M = [1,5,2,4,3,2;2,3,1,4,4,1;4,5,2,2,3,1]
M =
1 5 2 4 3 2
2 3 1 4 4 1
4 5 2 2 3 1
>> M(:,1:2:end) + M(:,2:2:end)
ans =
6 6 5
5 5 5
9 4 4
>> reshape(sum(reshape(M.',2,[]),1),[],3).'
ans =
6 6 5
5 5 5
9 4 4
And
>> M = [2,1,2,1,1,5,5,4,4,2,4,5;3,5,1,3,1,2,5,3,3,4,5,4;2,4,2,1,5,5,4,3,2,2,1,5]
M =
2 1 2 1 1 5 5 4 4 2 4 5
3 5 1 3 1 2 5 3 3 4 5 4
2 4 2 1 5 5 4 3 2 2 1 5
>> reshape(sum(reshape(M.',3,[]),1),[],3).'
ans =
5 7 13 11
9 6 11 13
8 11 9 8