help-octave
[Top][All Lists]
Advanced

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

RE: Vectorizing simple loops


From: Jose Marcos Ferraro
Subject: RE: Vectorizing simple loops
Date: Thu, 3 Dec 2015 18:49:28 +0000

-----Original Message-----
From: address@hidden [mailto:address@hidden On Behalf Of pawelz
Sent: quinta-feira, 3 de dezembro de 2015 10:04
To: address@hidden
Subject: Re: Vectorizing simple loops

Brian - sure, you are welcome. I learned a lot to reuse later too. Indeed the 
solution is very elegant, I never suspected such would be possible. I am 
pasting it here too, for reference:

in = [ 1 0 2 0 7 7 7 0 5 0 0 0 9 ]
out = nonzeros(in).'(cumsum(in~=0))

Btw -  this second challenge <http://stackoverflow.com/questions/34046161>
is still unanswered. Given that I thought the same about the first one, I don't 
trust my judgment entirely, but to me the second challenge seems more difficult 
- if able to be vectorized at all...



--
View this message in context: 
http://octave.1599824.n4.nabble.com/Vectorizing-simple-loops-tp4673742p4673781.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



I believe the second problem can also be vectorized, but I may have 
misunderstood what was being asked.
 Define three functions propagate.m , fsm.m and fsmf.m and fill them with

function outz  = propagate(inz)

z = find(inz, 1);
if(length(z)==0)
        outz = inz;
        return
endif
in = inz(z:end);
n = nonzeros(in)';
out = n((cumsum(in!=0)));
outz = [zeros(1,z-1) out];

endfunction


function out  = fsm(in )


#trim leading 0s

sinal = propagate(sign(in));
step = abs(in) == 2;
stepup = step .* (sinal>0);
stepdown = step .* (sinal<0);
rampup = cumsum(stepup);
rampdown =  cumsum(stepdown);
plateauup = propagate(rampup .* (sinal<0));
plateaudown = propagate(rampdown .* (sinal>0));
rampup_centered = rampup - plateauup;
rampdown_centered = rampdown - plateaudown;
ramp = -rampdown_centered+rampup_centered;
out = ramp;

endfunction

function out  = fsmf(in , step , top )


z = find(in, 1);
if(length(z)==0)
        out = in;
        return
endif
in2 = in(z:end);

sim = fsm(in2);
sim2 = sim * step;
sim3 = min(sim2 , top);
sim4 = max(sim3 , -top);

out = diff([0 sim4]);

endfunction

Then you will have 

octave:120> fsmf([2 2 2 2 0 1 0 -1 0 -2 -2 -1 0 1] , 3 , 9)
ans =

   3   3   3   0   0   0   0  -9   0  -3  -3   0   0   6

Jose Marcos Ferraro     
www.LOGITeng.com



reply via email to

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