I can think of a way to reduce your case A to a for loop where the loop index is the kth uninterrupted stream of zeroes instead of the index of the original vector. So for the example you showed the loop would execute 4 times instead of 13. Would that be helpful to you?
2 gru 2015 12:56 "pawelz" <
address@hidden> napisał(a):
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.
_______________________________________________
Help-octave mailing list
address@hidden
https://lists.gnu.org/mailman/listinfo/help-octave