# Mod Function in MATLAB

Techwalla may earn compensation through affiliate links in this story.

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:

Video of the Day

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.