Sum columns of matrix

조회 수: 6 (최근 30일)
Esegboria Osarhemen
Esegboria Osarhemen 2019년 2월 10일
편집: Stephen23 2019년 2월 10일
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에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by