Sum alternaing columns of a matrix

7 次查看(过去 30 天)
Hi,
I have a matrix 191x4034 and I would like to sum alternating columns and put the results in a vector, but I can't understand how to do that.
It would be something like that
A= 1 3 4 5
3 6 7 8
5 6 7 9
B = (9, 18, ...) % 1st column = 9, 3rd column = 18, 5th column = ...
C = (15, 22, ...) % 2nd column = 9, 4th column = 18, 6th column = ...
Thanks for the help

采纳的回答

DGM
DGM 2021-5-12
编辑:DGM 2021-5-12
Something like
A = randi(9,3,10)
a0 = sum(A,1) % show all column sums as an example
a1 = sum(A(:,1:2:end),1) % odd col sums
a2 = sum(A(:,2:2:end),1) % even col sums
gives
A =
8 2 6 9 3 8 9 3 5 2
9 5 9 1 2 5 4 5 4 4
9 8 9 4 2 9 4 3 3 5
a0 =
26 15 24 14 7 22 17 11 12 11
a1 =
26 24 7 17 12
a2 =
15 14 22 11 11
If you need one or the other, just pick the line you need. If you need to calculate both even and odd column sums, it's generally going to be faster to do it like this, especially for large arrays.
a0 = sum(A,1); % get all column sums at once
a1 = a0(1:2:end); % sort out odd cols
a2 = a0(2:2:end); % sort out even cols

更多回答(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