Cumulative sum with condition

5 Ansichten (letzte 30 Tage)
Ravi Kumar
Ravi Kumar am 22 Okt. 2021
Bearbeitet: Dave B am 22 Okt. 2021
I want to do cumulative sum of column 3/4 with condition in coulmn 5/6 .
example:
i.e. -0.0700+0
than -0.9800 + (-0.9800+0.4950) + (-0.9800+0.4950+0.1680)+.....so on till 0.2070
than it should start summing 3: 3.3590 + (3.3590 + 1.7470) + .....

Akzeptierte Antwort

Dave B
Dave B am 22 Okt. 2021
Bearbeitet: Dave B am 22 Okt. 2021
I think what you're looking for is groupsummary (or grouptransform):
x=[rand(10,1) randi(3,10,1)];
% this is the sum for groups 1,2,3
[groupsums,groups] = groupsummary(x(:,1),x(:,2),'sum')
groupsums = 3×1
0.7349 2.6445 1.5777
groups = 3×1
1 2 3
% this is what you described, the sum of the cumulative sum
[groupsums,groups]=groupsummary(x(:,1),x(:,2),@(x)sum(cumsum(x)))
groupsums = 3×1
0.8584 9.7034 2.2265
groups = 3×1
1 2 3
% here's just the cumsum:
x=sortrows(x,2); % sorting is not necessary, just makes it easier to visualize
groupcumsums=grouptransform(x(:,1),x(:,2),@(x)cumsum(x));
[x groupcumsums]
ans = 10×3
0.1235 1.0000 0.1235 0.6113 1.0000 0.7349 0.0059 2.0000 0.0059 0.8389 2.0000 0.8448 0.7340 2.0000 1.5788 0.5824 2.0000 2.1612 0.3069 2.0000 2.4682 0.1764 2.0000 2.6445 0.6488 3.0000 0.6488 0.9288 3.0000 1.5777

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by