Isaac Wang
Isaac Wang

Reputation: 21

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.

Upvotes: 1

Views: 445

Answers (2)

Isaac Wang
Isaac Wang

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

Upvotes: 1

Wolfie
Wolfie

Reputation: 30047

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]

Upvotes: 1

Related Questions