Here's a solution where we round off from zero if the number has passed the threshold
in = [0.2,-3.3,4.1];
th = 0.2;
%
frac = mod(in,1); %
%
%
sig = sign(in);
%
upIdx = frac>th; %
%
out = abs(in);
out(upIdx) = ceil(out(upIdx));
out(~upIdx) = floor(out(~upIdx));
%
out= out.*sig
out =
0 -4 4
Note. If the numbers are only between 0 and 1, this is even simpler:
%# this does exactly what your code does
out = double(in>th);
Jonas source
share