How to sum up every other column of a matrix?

2 visualizzazioni (ultimi 30 giorni)
Suppose I have a matrix A,
A=[1 2 3 5 1 2 3 5;3 4 6 7 1 2 3 5;5 6 8 9 1 2 3 5]
A = 3×8
1 2 3 5 1 2 3 5 3 4 6 7 1 2 3 5 5 6 8 9 1 2 3 5
How can I sum up column(1) and column(3) to form one column, and column(5) and column(7) to form another column? Similarly with even columns, i.e. column(2) and (4) forms a new column, and the column(6) and (8) forms another. So the output would like like.
B = [4 4;9 4;13 4] % odd columns
B = 3×2
4 4 9 4 13 4
C = [7 7;11 7; 15 7] % even columns
C = 3×2
7 7 11 7 15 7

Risposta accettata

Dyuman Joshi
Dyuman Joshi il 10 Mar 2023
%Data with more columns than example mentioned
A=randi(10,3,16)
A = 3×16
9 9 1 2 9 4 9 8 8 8 9 9 7 7 10 3 8 7 3 5 3 6 7 1 9 7 8 6 3 9 3 4 2 2 2 1 9 4 7 4 4 4 5 1 6 10 8 5
%Pairing odd columns - (1,3) (5,7) (9,11) ...
B=A(:,1:4:end)+A(:,3:4:end)
B = 3×4
10 18 17 17 11 10 17 6 4 16 9 14
%Pairing even columns - (2,4) (6,8) (10,12)
C=A(:,2:4:end)+A(:,4:4:end)
C = 3×4
11 12 17 10 12 7 13 13 3 8 5 15

Più risposte (0)

Community Treasure Hunt

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

Start Hunting!

Translated by