Rounding to the second-nearest integer in MATLAB

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.

2

2 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.6 becomes 0.4) with 1-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:

  1. Find the relationship between the input and its nearest integer (-1 for x<round(x); 1 for x>round(x)) with sign(x-round(x)).
  2. Correct the result (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.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like