Reputation: 21
The round
function in MATLAB can only round a number to its nearest integer. How can we round a number to its second-nearest integer?
For example, for 10.3, we get 11; for 10.6, we get 10.
Upvotes: 1
Views: 445
Reputation: 21
Thank you for your suggestions.
I found a tricky way to solve this problem.
round2 = @(x) round(x) + sign(x-round(x));
The logic is:
-1
for x<round(x)
; 1
for x>round(x)
) with sign(x-round(x))
.round(x)
) toward the direction of x
.Example
a = [-10.6, -10.4, 0, 10.4, 10.6];
round2(a)
% ans = [-10, -11, 0, 11, 10]
In this solution, the result of an integer is itself.
Upvotes: 1
Reputation: 30047
You could use the following logic
round2 = @(x) round( floor(x) + 1 - rem(x,1) );
The logic here is:
floor(x)
0.6
becomes 0.4
) with 1-rem(x,1)
A side effect of this is integers get "rounded" up to the next integer.
Test:
round2 = @(x) round( floor(x) + 1 - rem(x,1) );
a = [10.3, 10.6, 11];
round2(a)
% ans = [11, 10, 12]
Upvotes: 1