help-octave
[Top][All Lists]

## another vectorization challenge

 From: Tim Rueth Subject: another vectorization challenge Date: Thu, 26 Aug 2010 18:36:57 -0700

For those of you who like to solve vectorization problems, I'm stuck on the following:

Let's say I have a vector with values that range from -10 to 10:

cpg_v = 20*rand(1,n) - 10;

Now, I want to create another vector cr_v of the same size with the following logic:

Whenever cpg_v drops below "cr_thd," then cr_v should get a 1.  Okay, that's easy:

cr_v = zeros(1,length(cpg));
cr_v (cpg_v < cr_thd) = 1;

I also want to know when cpg_v goes back above "rec_thd."  That's easy, too:

rec_v (cpg_v > rec_thd) = 1;

But here's the tricky part:  Reading cpg_v from 1:end, once a "1" is encountered at the corresponding location in cr_v, then cr_v should be assigned a "2" after that location (unless cpg_v drops below cr_thd again) until the point where cpg_v is greater than "rec_thd."  Note that a "2" shouldn't be assigned until there's a 1 in cr_v, and the run of 2's should stop once a 1 is encountered in rec_v.  Here's a simple example (with cr_thd = -4, rec_thd = 4), and the desired output:

cpg_v        cr_v        rec_v    desired cr_v
-------------------------------------------------------------------
6.45824   0.00000   1.00000   0.00000
7.42197   0.00000   1.00000   0.00000
-2.41237   0.00000   0.00000   0.00000
4.85508   0.00000   1.00000   0.00000
3.78177   0.00000   0.00000   0.00000
-3.24793   0.00000   0.00000   0.00000
-5.63435   1.00000   0.00000   1.00000
-2.10278   0.00000   0.00000   2.00000
-0.80376   0.00000   0.00000   2.00000
7.97556   0.00000   1.00000   0.00000
-5.11177   1.00000   0.00000   1.00000
-4.56460   1.00000   0.00000   1.00000
-8.43245   1.00000   0.00000   1.00000
4.85563   0.00000   1.00000   0.00000
-2.17610   0.00000   0.00000   0.00000
4.87113   0.00000   1.00000   0.00000
6.78267   0.00000   1.00000   0.00000
9.30517   0.00000   1.00000   0.00000
5.31377   0.00000   1.00000   0.00000
-4.93238   1.00000   0.00000   1.00000
2.10757   0.00000   0.00000   2.00000
6.94569   0.00000   1.00000   0.00000
1.67053   0.00000   0.00000   0.00000
-7.23665   1.00000   0.00000   1.00000
-5.43656   1.00000   0.00000   1.00000
-9.79481   1.00000   0.00000   1.00000
0.45726   0.00000   0.00000   2.00000
-2.14684   0.00000   0.00000   1.00000
-0.75054   0.00000   0.00000   1.00000
-2.59986   0.00000   0.00000   1.00000
Obviously, this is easy to do in a for-loop, but is there a way to do it just with vectors?

Thanks,

--Tim