Cumsum only within groups?

Suppose I have 2 vectors:

a=[0 1 0 1 1 0 1 0 0 0 1 1 1];
b=[1 1 1 1 1 1 2 2 2 3 3 3 3];

      

For each group of numbers in b, I want a cumsum so that the result looks like this:

c=[1 3;2 1;3 3]

      

This means I have the ones b 3 in a, for group two in b. I only have one in, etc.

+3


source to share


3 answers


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.

+3


source


There have been some tricky answers so far. Try it accumarray(b',a')

.



+4


source


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.

+2


source







All Articles