Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding numbers with custom threshold

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

like image 681
waspinator Avatar asked Dec 07 '22 15:12

waspinator


1 Answers

just use

round(x - treshold + 0.5)

test case:

>> x = -10:0.3:10
ans =
    -2   -1.7  -1.4  -1.1  -0.8  -0.5  -0.2  0.1    0.4   0.7    1    1.3   1.6   1.9


>> treshold = 0.8; % round everything up for which holds mod(x,1) >= treshold
>> y = round(x-treshold+0.5)

ans =
    -2    -2    -2    -1    -1    -1    -1     0     0     0     1     1     1     2

negative numbers are also rounded correctly, except on the boundary: -0.8 gets rounded to -1 instead of 0, but that's the same behaviour as round normally has: round(-0.5) returns -1

like image 150
Gunther Struyf Avatar answered Dec 31 '22 09:12

Gunther Struyf