Sum alternaing columns of a matrix

조회 수: 4 (최근 30일)
Cecilia Martinelli
Cecilia Martinelli 2021년 5월 12일
편집: DGM 2021년 5월 12일
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