フィルターのクリア

Cumulative sum of groups

5 ビュー (過去 30 日間)
PGrant
PGrant 2018 年 4 月 25 日
コメント済み: PGrant 2024 年 6 月 3 日
I need the cumlative sum of the second column of Data grouped by (or reset at each change in) the first column of Data please:
Data = [[1;1;1; 2;2;2; 3;3;3], [1;0;1; 0;1;1; 0;1;0]]
Answer = [Data, [1;1;2; 0;1;2; 0;1;1]]
Data =
1 1
1 0
1 1
2 0
2 1
2 1
3 0
3 1
3 0
Answer =
1 1 1
1 0 1
1 1 2
2 0 0
2 1 1
2 1 2
3 0 0
3 1 1
3 0 1
  2 件のコメント
Stephen23
Stephen23 2018 年 4 月 25 日
編集済み: Stephen23 2018 年 4 月 25 日

@PGrant: please explain the logic of how to calculate Answer: assume that we a stupid and that every step need to be shown to us.

PGrant
PGrant 2018 年 4 月 25 日
Like a normal cumsum on column 2 of the Data with the difference being that it needs to restart for every change in column 1 of data resulting in column 3 of Answer. Columns 1 & 2 of Answer are just Data...

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

採用された回答

Stephen23
Stephen23 2018 年 4 月 25 日
編集済み: Stephen23 2018 年 4 月 25 日
>> data = [1,1;1,0;1,1;2,0;2,1;2,1;3,0;3,1;3,0];
>> C = accumarray(data(:,1),data(:,2),[],@(v){cumsum(v)});
>> [data,vertcat(C{:})]
ans =
1 1 1
1 0 1
1 1 2
2 0 0
2 1 1
2 1 2
3 0 0
3 1 1
3 0 1
  1 件のコメント
PGrant
PGrant 2018 年 4 月 25 日
Thanks so much Stephen. Greatly appreciated!

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

その他の回答 (1 件)

Lola Davidson
Lola Davidson 2024 年 6 月 3 日
The grouptransform function was introduced in R2018b to help make problems like this a bit simpler. You can avoid the tricky cell array syntax that you need to use accumarray and just do this:
Data(:,3) = grouptransform(Data(:,2),Data(:,1),@cumsum)
  1 件のコメント
PGrant
PGrant 2024 年 6 月 3 日
Beauty! Thanks Lola.

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

カテゴリ

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

製品

Community Treasure Hunt

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

Start Hunting!

Translated by