Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: counting events
Replies: 4   Last Post: Aug 22, 2013 6:15 PM

 Messages: [ Previous | Next ]
 Jonathan Allan Posts: 123 Registered: 12/7/04
Re: counting events
Posted: Aug 22, 2013 6:15 PM

TideMan <mulgor@gmail.com> wrote in message <6d0130e8-a4e7-41e9-8e3b-c1fa56808952@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(k-1)+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.

Date Subject Author
8/22/13 Jonathan Allan
8/22/13 Derek Goring
8/22/13 Jonathan Allan
8/22/13 Alan
8/22/13 Alan