create a mod function without using the mod function in matlab

To create a mod function without using the built-in mod function in MATLAB, you can use the following code:

main.m
function result = myMod(a,b)
%MYMOD calculates the modulus of two numbers without using the MOD function
%   Syntax: result = myMod(a,b)
    quotient = fix(a/b);
    result = a - quotient*b;
end
195 chars
7 lines

In this function, we first calculate the quotient using the fix function. We then subtract quotient*b from a to get the modulus. We can call the myMod function to calculate the modulus of two numbers as follows:

main.m
x = 10;
y = 3;

modulus = myMod(x,y);
38 chars
5 lines

The value of modulus in this case would be 1, which is the expected result of 10 mod 3.

gistlibby LogSnag