2012-04-26 2 views
3

숫자가 임계 값 (0.5가 아님)을 통과하고 그렇지 않으면 반올림 한 경우 숫자를 '반올림'할 수 있기를 원합니다.사용자 지정 임계 값이있는 숫자 반올림

여기 나와있는 몇 가지 진절머리 나는 코드입니다. 이, 또는 더 우아한 솔루션 (아마 vectorized)에 대한 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에서 멀리 라운드 해결책 : 숫자는 0과 1 사이에만있는 경우에도 쉽게 :

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

와우 나는 바보입니다. 감사합니다 – waspinator

+0

@waspinator : 항상 도와 줘서 기쁩니다 : P – Jonas

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

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 반올림됩니다 0 대신에 -1이되지만, 둥근 (-0.5)이 -1을 반환합니다.

관련 문제