
Re: counting events
Posted:
Aug 22, 2013 6:15 PM


TideMan <mulgor@gmail.com> wrote in message <6d0130e8a4e741e98e3bc1fa56808952@googlegroups.com>... > On Friday, August 23, 2013 7:45:06 AM UTC+12, Jonathan wrote: > > Hi, > > > > > > > > I'm trying to figure out a way to perform a cumulative count of events. Here's my example. I have the following matrix: > > > > > > > > test=[0,0,1,1,1,0,0,0,0,0,1,1,0 etc].'; and I am trying to get to the following solution: test2=[0,0,1,2,3,0,0,0,0,0,1,2,0 etc]; > > > > > > > > Basically, I would like to add those events characterized by a 1, so that the end result is the sum of all the 1s in the sequence. > > > > I started with the following but its not working (I can see why but can't figure out how to get around it)... > > > > > > > > for k = 1:length(test) > > > > if test(k)>0 > > > > test3(k)=test(k1)+test2(k); > > > > elseif test(k)==0 > > > > test3(k)=0 > > > > end > > > > end > > > > test3=test3.'; > > > > > > > > Thanks > > No, you're taking completely the wrong approach. > Rather than looking at each element individually, use vector algebra: > > indx=diff(test); % Look for jumps > i1=find(indx==1) + 1; > i2=find(indx==1); > % i1 and i2 are the start and finish of each event > count=zeros(1,length(test)); % Allocate storage > % Loop through the events > for id=1:length(i1) > jndx=i1(id):i2(id); > count(jndx)=cumsum(test(jndx)); > end > > There's probably a more elegant way, avoiding the loop, but this works. > >
Elegant! This resolved my problem. Thank you.

