Sum columns of matrix

3 次查看(过去 30 天)
If I have a 3x6 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 3x3 matrix?
And if have a 3x12 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 3x4 matrix?
Is there a general formula that will work for both situations?

采纳的回答

Stephen23
Stephen23 2019-2-10
编辑:Stephen23 2019-2-10
>> 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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by