create a function to calculate the factorial of the integer n without using the “factorial(n)” command in matlab

Here is an implementation of a MATLAB function to calculate the factorial of an integer n without using the built-in factorial command.

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

Simply define this function in your MATLAB script and call it by passing the desired integer n as an argument. For example, to calculate the factorial of 5:

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

This implementation works by iterating over every integer from 1 to n and multiplying them together. The result is returned as a scalar output variable f.

related categories

gistlibby LogSnag