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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With