Matlab mod() function

Matlab mod() function is used to calculate the remainder after division. 

Syntax: Matlab mod() 

remainder = mod(dividend, divisor)

Here, 

  • dividend – the number that is being divided
  • divisor – the number that the dividend is being divided by
  • remainder – the output of the function, which is the remainder of the division

Example: Find remainder using Matlab mod()

% calculate remainder 
remainder = mod(23,5)

Output

3

Example: Remainder After Division of an array

You can also find the remainder of an array by dividing each element with a divisor. For example,

% create an array 
a = [5, 7, 11, 15];

% calculate the remainder of each element 
remainder = mod(a, 3)

Output

2     1     2     0

The above code returns a new array, with the remainder of the corresponding element of array a.


Example: Remainder After Division for Positive and Negative Values

You can also find the remainder of an array that has both positive and negative values using Matlab mod(). For example,

% create an array 
array = [-4 -1 7 9];

% define the divisor as 3
divisor = 3;

% calculate the remainders 
remainders = mod(array, divisor)

Output

2     2     1     0

If the divisor is positive the resulting array of the remainder is always positive.


Example: Remainder After Division for Negative Divisor

You can find the remainder after division by a negative divisor for a set of integers including both positive and negative values. For example,

% create an array 
array = [-4 -1 7 9];

% define the divisor 
divisor = -3;

% calculate remainders 
remainders = mod(array, divisor)

Output

-1    -1    -2     0

Remainder After Division for Floating-Point Values

Here is an example of using the mod() function to calculate the remainder after division for floating-point values in MATLAB:

dividend = 5.5;
divisor = 2.5;
remainder = mod(dividend, divisor)

Output

0.5000

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *