help-octave
[Top][All Lists]
Advanced

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

## Vectorizing simple loops

 From: pawelz Subject: Vectorizing simple loops Date: Tue, 1 Dec 2015 18:23:02 -0800 (PST)

```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
here in the first case. I would appreciate your advice. My only answer at
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

--
View this message in context:
http://octave.1599824.n4.nabble.com/Vectorizing-simple-loops-tp4673742.html
Sent from the Octave - General mailing list archive at Nabble.com.

```

reply via email to

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