Mod Function in MATLAB

Sometimes during a division calculation, the remainder is of more interest than the integer quotient. For example, when dividing 17 by three, the remainder of two could be more important to know than the integer quotient of five. One of the thousands of built-in functions in the mathematical software program MATLAB is the "mod" command, short for "modulus." The "mod" function directly computes the remainder of a division operation.

Mod Example

Suppose John has 17 apples and he wants to divide them as evenly as possible among him and two friends so that they all have an equal number of apples. How many apples will remain? Solve the problem with this one line of MATLAB code:

Mod(17,3)

MATLAB reads the code, divides 17 by three, and tells John that there will be two apples left over.

Mod Versus Rem

A closely related function to "mod" is MATLAB's "rem" function, short for "remainder." A possible pitfall for incorrect usage of the "mod" function is that the answer always keeps the sign of the divisor. For example,

Mod(-17,3)

returns positive two, because the three is positive. If a division calculation requires the correct sign on the answer, then use the "rem function" like this:

Rem(-17,3)

In this case, MATLAB will output a negative two.

Some Mod Rules

There are a handful of rules a MATLAB user should know when using the "mod" function, most of which follow from basic rules of division:

First, "mod(X,0)" returns "X," rather than error. Second, "mod(X,X)" returns "0." Third, "mod(X,Y)" will have the same sign as "Y," as long as "X" and "Y" aren't equal and "Y" is not zero. Lastly, "mod(X,Y)" and" rem(X,Y)" are the same if "X" and "Y" share the same sign, but differ by "Y" otherwise.

Use For Congruence

In modular arithmetic, two numbers are "congruent mod n" if when divided by "n," they have the same remainder. Another way of saying it is after adding or subtracting multiples of "n" to one number, you can end up at the other. For example, 6 a.m and 6 p.m. are "congruent mod 12," because adding 12 to one results in the other. Converting 6 p.m. to 1800 in military time, the following code evaluates to "true" and proves their congruence using MATLAB's "mod" command:

Mod(6,12)==Mod(18,12)

references & resources
© 2020 Leaf Group Ltd. Leaf Group Media Manage Preferences