KAHIBARO Bookshelves
Discord Login Register

7.5. Rounding, Modulo, and Special Values

Overview

This chapter focuses on three related topics that appear all the time when you work with numbers in MATLAB: rounding, modulo operations, and special numeric values. You will see how MATLAB represents these operations, which functions are available, and what to pay attention to when using them in your own code.

Rounding Numbers

Rounding is the process of converting a number to a nearby integer, following some rule. MATLAB provides several functions that implement different rounding behaviors. You should choose the one that matches the mathematical or practical rule you need.

`round`: To the nearest integer

The function round returns the nearest integer. By default, halfway values are rounded away from zero. For example, round(2.5) gives 3, and round(-2.5) gives -3. The basic syntax is

matlab
y = round(x);

where x can be a scalar, vector, matrix, or higher dimensional array, and y has the same size as x. MATLAB applies the rounding elementwise.

MATLAB also supports rounding to a specified number of decimal digits. For instance,

matlab
y = round(x, 2);

rounds x to two decimal places. If x = 3.14159, round(x, 2) returns 3.14. You can also round to a power of ten using a third argument in newer versions, but for beginners the digits argument is usually enough.

`floor`: Round toward negative infinity

The function floor always rounds toward negative infinity. This means it returns the greatest integer less than or equal to the input. For example,

matlab
floor(2.9)    % returns 2
floor(-2.1)   % returns -3

This directional behavior is important. With negative numbers, floor does not “drop the decimal,” it moves to the more negative integer.

floor is often used when you need a “lower bound” integer index or when you need to convert continuous coordinates to discrete bins where you always want to go down.

`ceil`: Round toward positive infinity

The function ceil always rounds toward positive infinity. It returns the smallest integer greater than or equal to the input. For example,

matlab
ceil(2.1)     % returns 3
ceil(-2.9)    % returns -2

Again, observe the behavior for negative numbers. ceil(-2.9) goes to -2, because that is the next integer in the positive direction.

ceil is useful when you want an “upper bound” integer index or when you need to ensure you never underestimate.

`fix`: Round toward zero

The function fix rounds toward zero, that is, it truncates the fractional part. It behaves like chopping off the decimals for positive and negative values:

matlab
fix(2.9)      % returns 2
fix(-2.9)     % returns -2

You can think of fix as keeping the sign and taking the integer part in magnitude. This is often used when you want simple truncation behavior that is symmetric around zero.

Comparing rounding behaviors

To see the differences, consider the same value with each function:

matlab
x = [-2.7 -2.5 -2.3 2.3 2.5 2.7];
round(x)  % nearest, halves away from zero
floor(x)  % toward -Inf
ceil(x)   % toward +Inf
fix(x)    % toward 0

The results show that these functions only differ when the number has a fractional part or when it is exactly at a halfway point, like ±2.5 for round.

When working with arrays, all of these functions operate elementwise and preserve the size and shape of the input.

Modulo and Remainder

Modulo-related operations compute integer remainders, which are useful for cyclic behavior, periodic patterns, indexing, and many discrete math tasks. MATLAB provides two related operations: mod and rem. They are similar for positive numbers, but behave differently when negative numbers are involved.

`mod`: Modulo operation

The function mod computes the remainder after division, with the result having the same sign as the divisor. The basic syntax is

matlab
r = mod(a, b);

Here r is the remainder after dividing a by b. For positive a and positive b, this matches the usual idea of modulo arithmetic. For example,

matlab
mod(10, 3)   % returns 1
mod(7, 2)    % returns 1
mod(8, 4)    % returns 0

For negative numbers, mod is defined such that

$$
\text{mod}(a, b) = a - b \cdot \left\lfloor \frac{a}{b} \right\rfloor
$$

where the floor function is used. As a result, the outcome always lies between 0 and b if b is positive. For instance,

matlab
mod(-10, 3)  % returns 2
mod(-1, 4)   % returns 3

This property makes mod especially useful when you need to wrap indices or angles into a fixed interval, such as mapping any angle into [0, 2*pi) or any index into the range 1 to n (with some adjustment).

`rem`: Remainder operation

The function rem also computes a remainder but uses truncation toward zero internally. The basic syntax is the same:

matlab
r = rem(a, b);

For positive inputs, rem and mod agree:

matlab
rem(10, 3)   % returns 1

For negative values, rem uses the formula

$$
\text{rem}(a, b) = a - b \cdot \text{fix}\left(\frac{a}{b}\right)
$$

Since fix rounds toward zero, the remainder keeps the sign of the dividend a. For example,

matlab
rem(-10, 3)  % returns -1
rem(10, -3)  % returns 1
rem(-10, -3) % returns -1

This differs from mod. The choice between mod and rem depends on which sign convention you want. In many applications that involve wrapping or periodicity, mod is preferred, because it yields results in a fixed nonnegative range when the divisor is positive.

Choosing between `mod` and `rem`

If you want a remainder that behaves like “wraparound” and stays between 0 and b for positive b, use mod. For instance, to map arbitrary integer time steps into a repeating cycle of length n, you can write

matlab
k = mod(t, n) + 1;

which gives indices in the range 1 to n.

If you want a remainder that aligns with truncation toward zero, for example when you conceptually think about a = q*b + r with q as fix(a/b), use rem.

When in doubt, for cyclical indexing, angle wrapping, and similar tasks, mod is usually the safer and more intuitive choice.

Special Numeric Values: `NaN`, `Inf`, and `-Inf`

MATLAB uses special numeric values to represent undefined or unbounded results. Understanding these values and how they behave is very important for numerical work, since they can propagate silently through calculations if you are not careful.

`Inf` and `-Inf`: Infinity

The values Inf and -Inf represent positive and negative infinity. They appear when an expression overflows the range of floating point numbers or when division by zero occurs in a meaningful mathematical sense. For example,

matlab
1 / 0       % returns Inf
-1 / 0      % returns -Inf
1e308 * 1e308

The last expression is too large to represent as a finite double precision number and produces Inf.

In arithmetic, Inf behaves as you would expect in many cases:

matlab
Inf + 1     % Inf
Inf * 2     % Inf
1 / Inf     % 0

However, some operations with infinity are undefined. For example,

matlab
Inf - Inf
0 * Inf
0 / 0
Inf / Inf

These yield NaN, which represents “Not a Number”.

`NaN`: Not a Number

The value NaN represents an undefined numeric result. It is still stored in numeric arrays and behaves like a numeric value in terms of type, but arithmetic with NaN usually produces NaN again. For example,

matlab
0/0        % NaN
Inf - Inf  % NaN
NaN + 1    % NaN
NaN * 5    % NaN

NaN is often used to mark missing data or invalid results, because it prevents you from accidentally using these values in further calculations without noticing. Many MATLAB functions provide options to ignore NaN values when computing statistics, but the default behavior is that NaN contaminates sums, means, and similar operations.

Testing for special values: `isnan`, `isinf`, and `isfinite`

You cannot compare NaN using ==. The expression NaN == NaN returns logical 0 (false). This is by design and follows the IEEE floating point standard. To test whether a value is NaN, use isnan:

matlab
x = [0/0, 1/0, 5];
isnan(x)    % returns [1 0 0]

Similarly, use isinf to test for infinity:

matlab
isinf(x)    % returns [0 1 0]

This is useful for detecting overflow or division by zero.

If you want to know whether a value is a finite number (that is, not Inf, not -Inf, and not NaN), use isfinite:

matlab
isfinite(x) % returns [0 0 1]

These functions work elementwise on numeric arrays and return logical arrays of the same size.

Behavior of rounding and modulo with special values

Rounding functions and modulo operations have specific behaviors with NaN and Inf.

If you apply round, floor, ceil, or fix to NaN, the result is NaN. If you apply them to Inf or -Inf, the result is still Inf or -Inf. For instance,

matlab
round(NaN)    % NaN
floor(Inf)    % Inf
ceil(-Inf)    % -Inf
fix(NaN)      % NaN

Similarly, if you pass NaN to mod or rem, the result is NaN. If you use Inf or -Inf as either operand in mod or rem, the behavior may not be meaningful and often results in NaN. For example,

matlab
mod(Inf, 3)   % NaN
rem(5, Inf)   % 5

In the second case, dividing 5 by infinity is effectively 0 with remainder 5, so the result is finite. Understanding these behaviors helps you reason about edge cases and avoid surprises.

Practical Considerations and Common Pitfalls

When writing code that uses rounding, modulo, and special values, there are a few patterns you will encounter frequently.

When you convert from continuous quantities to discrete indices, you should choose the rounding function that matches your indexing convention. In many cases floor or ceil is better than round, because it is asymmetric and easier to reason about for interval boundaries.

When you implement wrapping behavior, such as mapping any integer to a range 1:n, use mod with positive divisors and adjust for MATLAB’s one based indexing. A typical pattern is

matlab
idx = mod(k-1, n) + 1;

which maps any integer k into the set {1, 2, ..., n}.

When you read external data that has missing entries, you may convert missing markers to NaN. Many functions have options to ignore NaNs when computing statistics, which you will see elsewhere in the course. Until then, remember that basic arithmetic and simple aggregate functions like sum or mean will propagate NaN by default, so you should test for NaN when needed.

Finally, be cautious with comparisons. Testing equality with NaN using == never works as expected. Always use isnan. Likewise, if you suspect that some computations may overflow or divide by zero, use isinf or isfinite to detect these conditions and handle them explicitly in your code.

Important points to remember:
round, floor, ceil, and fix all round differently. Know which direction each one uses, especially for negative numbers.
Use mod for wraparound behavior. It returns nonnegative remainders for positive divisors, which is usually what you want for indexing and periodic patterns.
NaN represents undefined numeric results and spreads through calculations. You cannot use == to test for NaN. Use isnan instead.
Inf and -Inf represent overflow or division by zero. Use isinf and isfinite to detect and handle these special values.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Getting Started with MATLAB
    • ☰ 1.1. What Is MATLAB and What Is It Used For
      • ☰ 1.2. Installing MATLAB and Setting Up the Environment
        • ☰ 1.3. Understanding the MATLAB Desktop Interface
          • ☰ 1.4. Command Window, Workspace, and Current Folder
            • ☰ 1.5. Basic Workflow and Running Simple Commands
              • ☰ 1.6. Getting Help and Documentation
              • ☰ 2. MATLAB Language Basics
                • ☰ 2.1. MATLAB Syntax and Expressions
                  • ☰ 2.2. Variables and Assignment
                    • ☰ 2.3. Data Types and Type Conversion
                      • ☰ 2.4. Vectors and Matrices Fundamentals
                        • ☰ 2.5. Creating and Indexing Arrays
                          • ☰ 2.6. Basic Arithmetic and Elementwise Operations
                            • ☰ 2.7. Using Built-In Constants and Functions
                            • ☰ 3. Working with Variables and the Workspace
                              • ☰ 3.1. Creating, Viewing, and Editing Variables
                                • ☰ 3.2. Workspace Browser and Variable Inspector
                                  • ☰ 3.3. Saving and Loading Data Files
                                    • ☰ 3.4. MAT-Files and Importing External Data
                                      • ☰ 3.5. Clearing Variables and Managing the Workspace
                                      • ☰ 4. Vectors, Matrices, and Arrays
                                        • ☰ 4.1. Row and Column Vectors
                                          • ☰ 4.2. Matrix Creation and Concatenation
                                            • ☰ 4.3. Indexing, Slicing, and Logical Indexing
                                              • ☰ 4.4. Matrix Operations vs Elementwise Operations
                                                • ☰ 4.5. Reshaping and Rearranging Arrays
                                                  • ☰ 4.6. Special Matrices and Functions
                                                  • ☰ 5. Basic Programming Constructs
                                                    • ☰ 5.1. Scripts vs Functions
                                                      • ☰ 5.2. Control Flow with if, elseif, else
                                                        • ☰ 5.3. Loops with for and while
                                                          • ☰ 5.4. break, continue, and return
                                                            • ☰ 5.5. Logical Expressions and Relational Operators
                                                              • ☰ 5.6. Best Practices for Clear and Readable Code
                                                              • ☰ 6. Functions in MATLAB
                                                                • ☰ 6.1. Creating Simple Functions
                                                                  • ☰ 6.2. Function Inputs and Outputs
                                                                    • ☰ 6.3. Function Files and the Path
                                                                      • ☰ 6.4. Local vs Global Variables
                                                                        • ☰ 6.5. Anonymous Functions
                                                                          • ☰ 6.6. Organizing Code into Multiple Functions
                                                                          • ☰ 7. Working with Numbers and Math
                                                                            • ☰ 7.1. Scalars and Vectorized Computations
                                                                              • ☰ 7.2. Basic Mathematical Functions
                                                                                • ☰ 7.3. Trigonometric and Exponential Functions
                                                                                  • ☰ 7.4. Complex Numbers in MATLAB
                                                                                    • ☰ 7.5. Rounding, Modulo, and Special Values
                                                                                      • ☰ 7.6. Numerical Precision and Floating Point Considerations
                                                                                      • ☰ 8. Strings, Characters, and Categorical Data
                                                                                        • ☰ 8.1. Character Arrays and String Arrays
                                                                                          • ☰ 8.2. Creating and Manipulating Strings
                                                                                            • ☰ 8.3. Converting Between Data Types and Strings
                                                                                              • ☰ 8.4. Comparing and Searching Strings
                                                                                                • ☰ 8.5. Categorical Arrays Basics
                                                                                                • ☰ 9. Tables, Structures, and Cell Arrays
                                                                                                  • ☰ 9.1. Introduction to Tables
                                                                                                    • ☰ 9.2. Creating Tables and Accessing Data
                                                                                                      • ☰ 9.3. Modifying and Joining Tables
                                                                                                        • ☰ 9.4. Structures and Nested Structures
                                                                                                          • ☰ 9.5. Cell Arrays and Cell Indexing
                                                                                                            • ☰ 9.6. Choosing the Right Container Type
                                                                                                            • ☰ 10. Importing and Exporting Data
                                                                                                              • ☰ 10.1. Reading Text and CSV Files
                                                                                                                • ☰ 10.2. Importing Excel Spreadsheets
                                                                                                                  • ☰ 10.3. Importing Data with the Import Tool
                                                                                                                    • ☰ 10.4. Exporting Data to Files
                                                                                                                      • ☰ 10.5. Working with Image and Audio Files
                                                                                                                        • ☰ 10.6. Basic File Management from MATLAB
                                                                                                                        • ☰ 11. Plotting and Visualization
                                                                                                                          • ☰ 11.1. Introduction to 2D Plotting
                                                                                                                            • ☰ 11.2. Customizing Plots and Axes
                                                                                                                              • ☰ 11.3. Multiple Plots in One Figure
                                                                                                                                • ☰ 11.4. Labels, Titles, Legends, and Annotations
                                                                                                                                  • ☰ 11.5. Plotting with Different Line and Marker Styles
                                                                                                                                    • ☰ 11.6. Saving and Exporting Figures
                                                                                                                                    • ☰ 12. Advanced Plotting for Beginners
                                                                                                                                      • ☰ 12.1. Subplots and Tiled Layouts
                                                                                                                                        • ☰ 12.2. Bar, Scatter, and Stem Plots
                                                                                                                                          • ☰ 12.3. Histograms and Density Plots
                                                                                                                                            • ☰ 12.4. 3D Plots and Surface Plots
                                                                                                                                              • ☰ 12.5. Using plottools and Interactive Editing
                                                                                                                                                • ☰ 12.6. Basics of Handle Graphics
                                                                                                                                                • ☰ 13. Working with Scripts and Live Scripts
                                                                                                                                                  • ☰ 13.1. Creating and Running Script Files
                                                                                                                                                    • ☰ 13.2. Sectioning Code and Running Sections
                                                                                                                                                      • ☰ 13.3. Live Scripts and Rich Text
                                                                                                                                                        • ☰ 13.4. Adding Equations, Images, and Outputs
                                                                                                                                                          • ☰ 13.5. Sharing and Exporting Live Scripts
                                                                                                                                                          • ☰ 14. Debugging and Code Quality
                                                                                                                                                            • ☰ 14.1. Finding and Fixing Syntax Errors
                                                                                                                                                              • ☰ 14.2. Setting Breakpoints and Stepping Through Code
                                                                                                                                                                • ☰ 14.3. Inspecting Variable Values During Execution
                                                                                                                                                                  • ☰ 14.4. Using the Editor Debugging Tools
                                                                                                                                                                    • ☰ 14.5. Using Code Analyzer and Warnings
                                                                                                                                                                      • ☰ 14.6. Writing Clean and Maintainable MATLAB Code
                                                                                                                                                                      • ☰ 15. Basic Linear Algebra with MATLAB
                                                                                                                                                                        • ☰ 15.1. Vectors and Norms
                                                                                                                                                                          • ☰ 15.2. Matrix Addition and Multiplication
                                                                                                                                                                            • ☰ 15.3. Solving Linear Systems with Backslash
                                                                                                                                                                              • ☰ 15.4. Inverses, Determinants, and Rank
                                                                                                                                                                                • ☰ 15.5. Eigenvalues and Eigenvectors
                                                                                                                                                                                  • ☰ 15.6. Using Linear Algebra Functions Safely
                                                                                                                                                                                  • ☰ 16. Data Analysis and Statistics Fundamentals
                                                                                                                                                                                    • ☰ 16.1. Descriptive Statistics and Summary Measures
                                                                                                                                                                                      • ☰ 16.2. Sorting, Filtering, and Grouping Data
                                                                                                                                                                                        • ☰ 16.3. Basic Correlation and Regression
                                                                                                                                                                                          • ☰ 16.4. Simple Data Cleaning Techniques
                                                                                                                                                                                            • ☰ 16.5. Basic Time Series Handling
                                                                                                                                                                                            • ☰ 17. Working with Time and Dates
                                                                                                                                                                                              • ☰ 17.1. Representing Dates and Times
                                                                                                                                                                                                • ☰ 17.2. Creating and Formatting datetime Arrays
                                                                                                                                                                                                  • ☰ 17.3. Date Calculations and Differences
                                                                                                                                                                                                    • ☰ 17.4. Plotting Data over Time
                                                                                                                                                                                                    • ☰ 18. Introduction to Signal and Image Handling
                                                                                                                                                                                                      • ☰ 18.1. Basic Signal Representation in MATLAB
                                                                                                                                                                                                        • ☰ 18.2. Simple Filtering and Transformations
                                                                                                                                                                                                          • ☰ 18.3. Reading, Displaying, and Writing Images
                                                                                                                                                                                                            • ☰ 18.4. Basic Image Transformations
                                                                                                                                                                                                            • ☰ 19. Automation and Scripting Tasks
                                                                                                                                                                                                              • ☰ 19.1. Batch Processing of Files
                                                                                                                                                                                                                • ☰ 19.2. Writing Reusable Utility Scripts
                                                                                                                                                                                                                  • ☰ 19.3. Using Relative Paths and the MATLAB Path
                                                                                                                                                                                                                    • ☰ 19.4. Simple User Interaction with input and disp
                                                                                                                                                                                                                    • ☰ 20. Introduction to Toolboxes
                                                                                                                                                                                                                      • ☰ 20.1. What Are Toolboxes and How to Use Them
                                                                                                                                                                                                                        • ☰ 20.2. Exploring Installed Toolboxes
                                                                                                                                                                                                                          • ☰ 20.3. Finding Functions in Toolboxes
                                                                                                                                                                                                                            • ☰ 20.4. Add-Ons and MATLAB File Exchange
                                                                                                                                                                                                                            • ☰ 21. Best Practices and Next Steps
                                                                                                                                                                                                                              • ☰ 21.1. Organizing Projects and Folders
                                                                                                                                                                                                                                • ☰ 21.2. Version Control Basics with MATLAB
                                                                                                                                                                                                                                  • ☰ 21.3. Performance Tips for Beginners
                                                                                                                                                                                                                                    • ☰ 21.4. Learning Resources and Documentation Path
                                                                                                                                                                                                                                      • ☰ 21.5. Suggested Practice Projects for Beginners