如果它超过了一个阈值(不是0.5),那么我希望能够"舍入"一个数字,否则向下舍入.
这是我提出的一些糟糕的代码.在matlab中是否有内置函数,或更优雅的解决方案(矢量化可能)?
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
Run Code Online (Sandbox Code Playgroud)
谢谢
只是用
round(x - treshold + 0.5)
Run Code Online (Sandbox Code Playgroud)
测试用例:
>> 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
Run Code Online (Sandbox Code Playgroud)
正数也正确舍入,除了在边界上:-0.8舍入到-1而不是0,但这与圆正常的行为相同:round(-0.5)返回-1
这是一个解决方案,如果数字超过阈值,我们会从零舍入
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
Run Code Online (Sandbox Code Playgroud)
注意:如果数字只在 0 到 1 之间,那就更简单了:
%# this does exactly what your code does
out = double(in>th);
Run Code Online (Sandbox Code Playgroud)