rounding numbers with custom threshold

matlab, rounding

Solution

Here's a solution where we round away from zero if the number has passed a threshold

in = [0.2,-3.3,4.1];
th = 0.2;

%# get the fractional part of the number
frac = mod(in,1); %# positive for negative in

%# find the sign so we know whether to round
%# to plus or minus inf
sig = sign(in);

%# identify which way to round
upIdx = frac>th; %# at threshold, we round down

%# round towards inf if up
out = abs(in);
out(upIdx) = ceil(out(upIdx));
out(~upIdx) = floor(out(~upIdx));
%# re-set the sign
out= out.*sig
out =
 0    -4     4

Note: If the numbers are only between 0 and 1, it's even easier:

%# this does exactly what your code does
out = double(in>th);

Problem

I want to be able to 'round' a number up if it's passed a threshold (not 0.5) and otherwise round down. here is some crappy code I came up with. Is there a built in function in matlab for this, or a more elegant solution (vectorized maybe)? ``` function [ rounded_numbers ] = custom_round( input_numbers, threshold ) %CUSTOM_ROUND rounds between 0 and 1 with threshold threshold [input_rows, input_cols] = size(input_numbers); rounded_numbers = zeros(input_rows, input_cols); for i = 1:length(input_numbers) if input_numbers(i) > threshold rounded_numbers(i) = 1; else rounded_numbers(i) = 0; end end end ``` Thanks

Original source