Sum alternaing columns of a matrix
5 ビュー (過去 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
0 件のコメント
採用された回答
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 件のコメント
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!