Filter löschen
Filter löschen

Sum columns of matrix

5 Ansichten (letzte 30 Tage)
Esegboria Osarhemen
Esegboria Osarhemen am 10 Feb. 2019
Bearbeitet: Stephen23 am 10 Feb. 2019
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?

Akzeptierte Antwort

Stephen23
Stephen23 am 10 Feb. 2019
Bearbeitet: Stephen23 am 10 Feb. 2019
>> 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

Weitere Antworten (0)

Kategorien

Mehr zu Creating and Concatenating Matrices finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by