help-octave
[Top][All Lists]

## Re: Vectorizing simple loops

 From: Nicholas Jankowski Subject: Re: Vectorizing simple loops Date: Wed, 2 Dec 2015 07:36:32 -0500

On Dec 2, 2015 6:56 AM, "pawelz" <address@hidden> wrote:
>
> Hi,
>
> I have been profiling some code going through big datasets and find it
> impossible to express these simple algorithms in high-performing vectorized
> form instead of slow loop version which is so trivial I don't even show it
> this point is to re-write these in C instead, which i would like to avoid.
>
> 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 ]
> I tried the merge(v==0, shift()...) but it only works for the first zero
> occurrence, not an arbitrary number of them.
>
> Case B) seems a bit more difficult but in fact it is simple. Produce an
> output with a rule based on simple memory of the previous step. The basic
> trick would be to make a decision in each step, based on the previous steps
> output, i.e. produce out(i) based on the value of acc which was built using
> out(i-1). Again tried merge(shift()) to no avail...
>
> in  = [2 2 1 -1 0 0 -2 2 0 1]
> x   = 1;
> top = 5;
> acc = 0;
> for i = 1 : length(in)
>   if     (in(i) == +2)
>           if (acc <      0) out(i) = -acc+x;
>       elseif (acc >  top-x) out(i) = 0;
>       elseif (acc >=     0) out(i) = x;
>        endif
>   elseif (in(i) == +1)
>           if (acc >=     0) out(i) = 0;
>       elseif (acc <      0) out(i) = -acc;
>        endif
>   elseif (in(i) ==       0) out(i) = 0;
>   elseif (in(i) ==      -1)
>           if (acc <=     0) out(i) = 0;
>       elseif (acc >      0) out(i) = -acc;
>        endif
>   elseif (in(i) == -2)
>           if (acc >      0) out(i) = -acc-x;
>       elseif (acc < -top+x) out(i) = 0;
>       elseif (acc <=     0) out(i) = -x;
>        endif
>   endif
>   acc += out(i);
> endfor
> out
>
> Cheers
> Pawel
>

I'll take a look later today, but in case you don't get a solution here, the people over at StackExchange watching the Matlab/Octave tags (some of whom are here) are really good at popping out code snippets for things like this.

Nick J