help-octave
[Top][All Lists]
Advanced

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

Re: vectorization challenge


From: Jaroslav Hajek
Subject: Re: vectorization challenge
Date: Fri, 6 Aug 2010 08:44:29 +0200

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



reply via email to

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