2012-04-26 74 views
3

我希望能夠'圓'一個數字,如果它通過了一個閾值(而不是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 

感謝

回答

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 

注意一種解決方案:如果數字是隻有0和1之間,那就更簡單了:

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

哇我是個白癡。謝謝 – waspinator 2012-04-26 22:47:50

+0

@waspinator:總是樂於提供幫助:P – Jonas 2012-04-27 01:07:14

1

這應該適用於任何數字,而不只是在0和1之間。閾值必須在[0,1)的範圍內。

我沒有測試負數。

function [result] = custom_round(num, threshold) 

if (threshold < 0) || (threshold >= 1) 
    error('threshold input must be in the range [0,1)'); 
end 

fractional = num - floor(num); 
idx1 = fractional > threshold; 
idx2 = fractional <= threshold; 
difference = 1 - fractional; 
result = num + (difference .* idx1) - (fractional .* idx2); 

end 

測試

>> custom_round([0.25 0.5 0.75 1], 0.3) 
ans = 
    0  1  1  1 

>> custom_round([0.25 0.5 0.75 1], 0.8) 
ans = 
    0  0  0  1 

>> custom_round([10.25 10.5 10.75 11], 0.8) 
ans = 
    10 10 10 11 
+0

這裏的風險在於輸出可能不是整數,這就是你所期望的。 – Jonas 2012-04-27 01:08:19

5

只使用

round(x-treshold+0.5) 

測試用例:

>> 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 

負數也是圓的正確,除了在邊界上:-0.8四捨五入得到到-1而不是0,但那與通常一樣的行爲具有:round(-0.5)return -1