create a function that calculates the gcd between 2 numbers in matlab

main.m
function [output] = calculateGCD(a,b)
% This function calculates the greatest common divisor (GCD) between two numbers
% Inputs:
%     a: an integer number
%     b: an integer number
% Output:
%     output: the GCD between a and b

% Calculate the remainder of a/b
r = rem(a,b);

% If the remainder is zero, the GCD is b
if r == 0
    output = b;
else
    % Recursively call the function with b as the first argument and r
    % as the second argument
    output = calculateGCD(b,r);
end

end
493 chars
22 lines

To use this function, simply call it with the two numbers as inputs, like so:

main.m
result = calculateGCD(10,15);
30 chars
2 lines

This will return the value 5, which is the GCD between 10 and 15.

gistlibby LogSnag