help-octave
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: vectorization challenge


From: Tim Rueth
Subject: RE: vectorization challenge
Date: Sat, 7 Aug 2010 03:55:35 -0700

> -----Original Message-----
> From: Jaroslav Hajek [mailto:address@hidden 
> Sent: Thursday, August 05, 2010 11:44 PM
> To: address@hidden
> Cc: Octave-ML
> Subject: Re: vectorization challenge
> 
> On Fri, Aug 6, 2010 at 6:00 AM, Tim Rueth <address@hidden> wrote:
> > I'm desperately trying to vectorize a calculation that I'm 
> currently 
> > doing in a for-loop.  I haven't been able to figure this 
> one out, and 
> > my brain now hurts.
> > I have two column vectors A and B as inputs:
> >
> >   A              B             C
> > -----------------------------------------
> > 43.94          0          0.0000
> > 44.25          0          0.7055
> > 44.34          0          0.9103
> > 44.81          0          1.9799
> > 45.00          1          2.4123
> > 44.97          0          -0.0666
> > 44.97          0          -0.0666
> > 44.66          1          -0.7555
> > 44.72          0          0.1343
> > 44.94          1          0.6269
> > 44.59          0          -0.7788
> > 43.47          0          -3.2710
> > 43.44          0          -3.3377
> > 43.41          1          -3.4045
> > 43.56          0          0.3455
> > 43.72          1          0.7141
> > 43.69          1          -0.0686
> > ...
> >
> > What I'm trying to do is calculate C without using a 
> for-loop.  C is 
> > simply the running percent change in A since the last time 
> there was a "1" in B.
> > As you might have noticed, whenever there's a "1" in B, 
> there's either 
> > a peak or a trough in A.  I can easily break B into two 
> vectors, one 
> > for peaks and one for troughs, but I don't think that will help in 
> > figuring out how to create C.
> >
> > If there really were only a few elements in these vectors, 
> a for-loop 
> > would be no big deal for me, but these vectors are very 
> long and the 
> > for-loop itself gets run often, hence the need to 
> vectorize.  Any help 
> > is greatly appreciated as always.
> >
> 
> Here's a solution that destroys B:
> 
> b = find (B);
> B(b) = diff ([0; b-1]); B(1) = 1;
> C = 100*(A ./ A(cumsum (B)) - 1);
> 
> hth
> 
> --
> RNDr. Jaroslav Hajek, PhD
> computing expert & GNU Octave developer
> Aeronautical Research and Test Institute (VZLU) Prague, Czech Republic
> url: www.highegg.matfyz.cz

Thanks Jordi and Jaroslav.  You guys are brilliant.

I used Jaroslav's solution shown above.  I only had to fix one minor thing:
I replaced A(cumsum(B)) with A(cumsum([1; B(1:end-1)])) to get everything to
line up properly.

Thanks again,

--Tim





reply via email to

[Prev in Thread] Current Thread [Next in Thread]