# Cumsum only within groups?

If you are looking for a solution, which `b`

can be anything, then the combination `hist`

and `unique`

helps you:

```
num = unique(b(logical(a))); %# identify the numbers in b with non-zero counts
cts = hist(b(logical(a)),num); %# count
c = [num(:),cts(:)]; %# combine.
```

If you want the first column to `c`

go from 1 to the maximum `b`

, you can rewrite the first row as `num=1:max(b)`

and you will also get rows in `c`

where counts are zero.

source to share

Assuming `b`

monotonically increasing by 1:

```
c = cell2mat(transpose(arrayfun( @(x) [ x sum(a(find( b == x ))) ], min(b):max(b), 'UniformOutput',false)))
```

should give the correct answer in a single liner format, or:

```
for ii=min(b):max(b)
II = find( b == ii );
v = sum(a(II));
c(ii,:) = [ii v];
end
```

which is a little easier to read. Hope this helps.

source to share