Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

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


Math Forum » Discussions » Software » comp.soft-sys.matlab

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

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
Jonathan Allan

Posts: 117
Registered: 12/7/04
Re: counting events
Posted: Aug 22, 2013 6:15 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

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.



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.