function that returns n factorial in matlab

Here's a Matlab function that returns the factorial of a given positive integer n using recursion:

main.m
function f = factorial(n)
% Compute factorial of n
if n == 0 % base case
    f = 1;
else % recursive case
    f = n * factorial(n-1);
end
end
142 chars
9 lines

Alternatively, you can use a loop to compute the factorial:

main.m
function f = factorial(n)
% Compute factorial of n
f = 1;
for i = 1:n
    f = f * i;
end
end
93 chars
8 lines

In both cases, you can call the function with a positive integer n as an argument, like this:

main.m
>> factorial(5)
ans =
   120
29 chars
4 lines

gistlibby LogSnag