implement factorial in matlab

To implement factorial in MATLAB, you can use either recursion or loops. Here's an example of each method:

Using recursion:

main.m
function fact = factorial(n)
    if n == 0 || n == 1
        fact = 1;
    else
        fact = n * factorial(n-1);
    end
end
127 chars
8 lines

Using loops:

main.m
function fact = factorial(n)
    fact = 1;
    for i = 1:n
        fact = fact * i;
    end
end
96 chars
7 lines

In both cases, the function takes an integer n as input and returns its factorial fact. The recursive approach is straightforward: if n is either 0 or 1, return 1, otherwise recursively call factorial with n-1 and multiply the result by n. The iterative approach is similar: initialize fact to 1, then multiply it successively by 1, 2, 3, ..., n.

gistlibby LogSnag