# Modulo in MATLAB

This tutorial demonstrates the modulo operation in MATLAB.

## Modulo Operation in MATLAB

Modulo is a math operation used to find the remainder when one integer is divided by another. It is represented by `%`

and usually abbreviated as `mod`

.

For example, there are two integers, a and b:

```
a mod b = r
```

Where the `a`

is the dividend, the `b`

is the modulus or divisor, and the `r`

is the remainder.

The modulo is considered a part of Modular Arithmetic and Cryptography, which concerns the operation like `wrap around`

when calculation reaches a modulus value. Modular arithmetic is fundamental in cryptography, where modulo operations are used with an extensive amount of modulus.

In MATLAB, there is a method for modulo to find the remainder after the division:

```
r = mod(a,b)
```

Where `a`

is the dividend, `b`

is the divisor, and the `r`

is the remainder.

The function used to perform the modulo operation can be represented as:

```
r = a - b.*floor(a./b)
```

The `mod()`

function with `mod(a,0)`

will follow the convention and return `a`

.

Let us try examples for modulo in MATLAB.

### Modulo Operation With Scalar Values

```
r = mod(51,7)
```

The remainder using the modulo operation is:

```
r =
2
```

### Modulo Operation With Vector Values

```
a = 2:9;
b = 7;
r = mod(a,b)
```

The remainders using the modulo operation on vector are:

```
r =
2 3 4 5 6 0 1 2
```

### Modulo Operation With Positive and Negative Values

```
a = [-6 -3 5 6];
b = 7;
r = mod(a,b)
```

The remainders using the modulo operation on positive and negative values are:

```
r =
1 4 5 6
```

### Modulo Operation With Negative Divisor

```
a = [-6 -3 5 6];
b = -7;
r = mod(a,b)
```

The remainders using the modulo operation on negative divisor are:

```
r =
-6 -3 -2 -1
```

### Modulo Operation With Floating Point Values

```
theta = [0.0 3.5 5.9 6.2 9.0 4*pi];
b = 7*pi;
r = mod(theta,b)
```

The remainders using the modulo operation on floating points values are:

```
r =
0 3.5000 5.9000 6.2000 9.0000 12.5664
```

**Sheeraz Gul**

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook