필터 지우기
필터 지우기

Cumulative sum within group, reset when encounters a 0

조회 수: 9 (최근 30일)
Namrata Goswami
Namrata Goswami 2020년 12월 17일
답변: Eric Sofen 2021년 1월 6일
I have a table and I want to get the cumulative sum within a group(by ID), but the cumulative count should reset if the counter is 0 at any point within a group and again start the cumulative count from 1.
Input
ID Counter
A 1
A 0
A 1
A 1
B 1
B 0
B 1
Expected output:
ID Counter Cumulative
A 1 1
A 0 0
A 1 1
A 1 2
B 1 1
B 0 0
B 1 1

답변 (1개)

Eric Sofen
Eric Sofen 2021년 1월 6일
It took me a while to come up with a way to do this without looping, then it clicked! You need to create groups based on where the 0s are. To do that, flip the logic of the counter and cumsum that:
t.ResetGroup = cumsum(~t.Counter);
Then, you can use varfun to group by both ID and ResetGroup and do the cumsum.
t = varfun(@cumsum, t, "GroupingVariable",["ID","ResetGroup"])

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by