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.
22 Answers
You could use the following logic
round2 = @(x) round( floor(x) + 1 - rem(x,1) );The logic here is:
- Round down to the nearest integer with
floor(x) - Flip the fractional part (i.e.
0.6becomes0.4) with1-rem(x,1) - Add these together and round normally
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] 2 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:
- Find the relationship between the input and its nearest integer (
-1forx<round(x);1forx>round(x)) withsign(x-round(x)). - Correct the result (
round(x)) toward the direction ofx.
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.
1