help-octave
[Top][All Lists]

## Re: Vectorizing simple loops

 From: Francesco Potortì Subject: Re: Vectorizing simple loops Date: Wed, 02 Dec 2015 14:07:44 +0100

```>Case A) Fill the blanks with last non-zero value:
>Go through the input vector values one by one and output the value if not
>zero, or copy over the last non-zero value. Sample input and expected output
>vectors:
>in  = [ 1 0 2 0 7 7 7 0 5 0 0 0 9 ]
>out = [ 1 1 2 2 7 7 7 7 5 5 5 5 9 ]

Just an idea, not a complete imnplementation.

If your 0 sequences are short, you can work it out by looping as many
times as the max length of your 0 sequences.  This finds the indices of
the first 0 in each sequence:

>> a = [ 1 0 2 0 7 7 7 0 5 0 0 0 9 ];
>> zeros = find(a==0)
zeros =
2    4    8   10   11   12
>> isfirst = diff([0 zeros])>1
isfirst =
1   1   1   1   0   0
2    4    8   10

Now you can set each burst head to the previous value and start again
until no more bursts are there.  This is easy and reasonably efficient
if the burst lengths are small (if the max burst len is 10, you loop ten
times).

If the burst are few and long, then you can proceed in the opposite way:
find the burst lengths and loop over the bursts.  The data you need to

>> a = [ 1 0 2 0 7 7 7 0 5 0 0 0 9 ];
>> zeros = find(a==0)
zeros =
2    4    8   10   11   12
>> burstlengths = diff([0 zeros])
burstlengths =
2   2   4   2   1   1
>> bl = diff([0 zeros])
bl =
2   2   4   2   1   1
>> isfirst = diff([0 zeros])>1
isfirst =
1   1   1   1   0   0
2    4    8   10
>> >> burstlengths = bl(isfirst)-1
burstlengths =
1   1   3   1

If the burst are many, and some can be very long, then either you find a
way to vectorise everything based on the above, or you can loop over
burst lengths until a given burst length, then loop over remaining
bursts, depending ont he burst length distribution.

--
Francesco Potortì (ricercatore)        Voice:  +39.050.621.3058
ISTI - Area della ricerca CNR          Mobile: +39.348.8283.107
via G. Moruzzi 1, I-56124 Pisa         Skype:  wnlabisti
(entrance 20, 1st floor, room C71)     Web:    http://fly.isti.cnr.it

```