How to sum over rows within specific ranges without for loop?

9 ビュー (過去 30 日間)
Andy Wu
Andy Wu 2019 年 11 月 8 日
コメント済み: Andy Wu 2019 年 11 月 9 日
I would like to sum up rows over specific ranges specified by an array. I do not know if there is a vectorised solution to it.
I have a matrix A say
A = [1,0,0,2;
0,3,1,0;
1,2,3,4;
0,1,0,1;
1,0,0,1];
I have an array B specifying the ranges of rows I want to sum up:
B = [2;
1;
2];
B shows that I would like to sum up the first 2 rows, and then the next 1 row, and then the next 2 rows. sum(B) equals to the total number of rows in A.
The output C has the same number of rows as B and the same number of columns as A:
C = [1, 3, 1, 2;
1, 2, 3, 4;
1, 1, 0, 2];
Many thanks!

採用された回答

Fabio Freschi
Fabio Freschi 2019 年 11 月 8 日
編集済み: Fabio Freschi 2019 年 11 月 8 日
Not sure if it is the best way, but this seems to work
index = [0; cumsum(B)];
C = cell2mat(arrayfun(@(i)sum(A(index(i)+1:index(i+1),:),1),1:length(B),'UniformOutput',false).')
  1 件のコメント
Andy Wu
Andy Wu 2019 年 11 月 9 日
I see. Thank you, Fabio. Wondering if there is better ways to do it. The run time based on a 1e5 * 100 matrix is similar with using loops.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by