Skip to content

MATLAB - Factorial

MATLAB - Factorial Calculation and Its Nuances

Section titled “MATLAB - Factorial Calculation and Its Nuances”

The factorial of a non-negative integer ‘n’, denoted as n!, is the product of all positive integers up to n. It is a fundamental function in combinatorics, probability, and advanced mathematics.

Section titled “The Recommended Method: factorial() Function”

The most efficient, accurate, and recommended way to calculate a factorial in MATLAB is by using the built-in factorial() function. It is optimized for performance and handles various input types gracefully.

The factorial function is vectorized, meaning it can operate on each element of an array simultaneously.

The input n must be a non-negative real integer. If you provide a negative integer or a non-integer, MATLAB will throw an error.

Factorial values grow extremely rapidly. MATLAB uses double-precision floating-point numbers by default. This has two consequences:

  • Large Numbers: For n > 21, the result is too large to be represented exactly as an integer and is returned as a floating-point approximation.
  • Overflow: For n > 170, the result of factorial(n) exceeds the largest possible double-precision number and overflows to Inf.

Solution for Very Large Numbers: Symbolic Math

Section titled “Solution for Very Large Numbers: Symbolic Math”

To calculate factorials for n > 170 with perfect precision, you can use the Symbolic Math Toolbox™. Convert the number to a symbolic object first.

Educational Sidebar: Implementing Factorial Manually

Section titled “Educational Sidebar: Implementing Factorial Manually”

While you should always use the built-in factorial function in practice, writing your own version is a great programming exercise. Here are two common approaches.

This method builds the result by looping and multiplying.

A recursive function is one that calls itself. This is an elegant but often less efficient way to define factorial.

If you’re using factorials, you might also be interested in:

  • gamma(x): The Gamma function, which is a generalization of the factorial. For an integer n, gamma(n+1) = factorial(n).
  • nchoosek(n, k): Calculates the binomial coefficient “n choose k”, which is the number of ways to choose k items from a set of n. It is defined using factorials: n! / (k! * (n-k)!).