Skip to main content
v2026.11,986 entries · CC-BY 4.0

Factorial in MATLAB: factorial(), Limits and Exact Results

How to compute factorial in MATLAB with factorial(n), where double, single and integer results stop being exact, and what to use instead.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In MATLAB, factorial(n) returns n!, the product of all positive integers less than or equal to n. For example, factorial(10) returns 3628800. The input must be a real nonnegative integer (or an array of them), and the answer is only exact up to a limit that depends on the numeric class of the input: up to n = 21 for double, up to n = 13 for single, and far less for small integer classes. This guide covers the syntax, those class-specific limits, exact results with the Symbolic Math Toolbox, and the gamma-function route for non-integers.

What the factorial function is used for in research

The factorial function appears wherever counting arrangements matters: permutations and combinations in sampling designs, binomial and Poisson probability terms, series expansions such as Taylor terms, and combinatorial checks on experimental designs. In MATLAB the built-in factorial (documented by MathWorks as the function that returns the product of all positive integers less than or equal to n) is the standard way to compute these terms without writing a loop. Researchers often meet it inside larger expressions, for instance when coding a probability mass function by hand, and the details below determine whether the numbers they get back can be trusted.

The notation matters. The mathematical shorthand n! is not valid MATLAB syntax; you must call the function, as in factorial(n). A line such as 5! produces a syntax error rather than 120.

How to install or access it

MATLAB is a commercial product of MathWorks, and the factorial function is part of base MATLAB, so no add-on is needed for the numeric calls in this guide. MATLAB itself is obtained from the MathWorks website (mathworks.com); many universities supply it under an institutional arrangement, so check with your research computing or IT group before acquiring anything separately. The exact symbolic outputs shown later use factorial on symbolic input, which is documented on MathWorks’ Symbolic Math Toolbox pages; confirm that your installation includes that toolbox before relying on them. Licensing terms and prices are set by MathWorks and are not covered here.

If you cannot use MATLAB, GNU Octave offers a function of the same name; see the free alternatives section.

Step-by-step: computing a factorial in MATLAB

Step 1: call factorial on a scalar

  1. Open MATLAB and click in the Command Window.
  2. Type f = factorial(10) and press Enter.
  3. MATLAB displays f = 3628800.

The general syntax is f = factorial(n). A scalar input gives a scalar output. By definition, factorial(0) is 1, which the array example below also shows.

Step 2: pass a vector or matrix

The function works element by element, and the output has the same size as the input. MathWorks gives this example:

A = [0 1 2; 3 4 5];
factorial(A)

ans =
     1     1     2
     6    24   120

Because the result keeps the size of the input, you can feed whole vectors of counts through a probability formula without a loop.

Step 3: choose the numeric class on purpose

The input can be of class single, double, or any of the signed and unsigned integer classes int8 through int64 and uint8 through uint64. The output has the same class as the input. That detail is where most surprises come from, as the next section explains. MathWorks’ own example uses factorial(uint64([5 10 15 20])), which returns 120, 3628800, 1307674368000 and 2432902008176640000 exactly.

Step 4: see more digits for large results

By default MATLAB shows about five significant digits. Run format long before a large call to see the stored value. For example, after format long, factorial(22) displays 1.124000727777608e+21. MathWorks notes that for double input only the first 15 digits of that value are accurate.

Step 5: the equivalent product expression

For a scalar n, factorial(n) equals prod(1:n), a relationship stated in the GNU Octave documentation and the reason MathWorks lists prod as a related function. A hand-written loop gives the same value:

n = 6;
f = 1;
for k = 2:n
    f = f*k;
end
f   % 720

The loop is useful for teaching and for checking, but the built-in function is shorter, vectorised and documented, so prefer it in analysis code. For loop mechanics in MATLAB, see our guide to loops in MATLAB, and for adding up the results see the MATLAB sum function.

Output and how to read it: exact, approximate, saturated and Inf

Reading the output correctly means knowing which of four situations you are in. The data table below this article lists the thresholds and cites the source for each.

Double precision (the default)

Numbers typed into MATLAB are double unless you say otherwise. For double, the result is exact for n up to 21. Above that, the magnitude is right but only the first 15 digits are accurate. The largest finite result is 170!, and factorial(171) returns Inf. If a downstream formula divides by a factorial or multiplies factorials, an Inf will quietly poison the result, so check for it with isinf when n can be large.

Single precision

For single, results are exact up to n = 13, accurate to the first 8 digits beyond that, and overflow at factorial(single(35)). Single precision is common when working with GPU arrays or memory-constrained data, so convert deliberately.

Integer classes saturate rather than wrap

For integer classes, MathWorks documents the point at which the result saturates, meaning it is clipped to the maximum value of the class instead of being computed. The thresholds are factorial(21) for uint64 and int64, factorial(13) for uint32 and int32, factorial(9) for uint16, factorial(8) for int16, and factorial(6) for uint8 and int8. In practice this means factorial(uint8(6)) and anything larger returns the class maximum rather than a true factorial, with no error message. Choosing an integer class to save memory is therefore risky for factorials of anything but small n.

One further limit: 64-bit integers are not supported for GPU arrays or distributed arrays.

Worked example: when double is not enough

Suppose you need 22!. In double precision, factorial(22) gives 1.124000727777608e+21, which is correct in the first 15 digits only. For an exact integer, the Symbolic Math Toolbox version of factorial accepts symbolic input; MathWorks’ example factorial(sym(20)) returns exactly 2432902008176640000. The rule from its documentation is to wrap numbers in sym() to get exact symbolic output, while non-symbolic input calls the built-in MATLAB function. If you only need exactness up to 20! or 21!, uint64 input also works, as the MathWorks uint64 example above shows.

The gamma function for non-integer inputs and very large n

factorial accepts only nonnegative integers. For other real values, use gamma. MathWorks documents that for an integer n, gamma(n+1) equals factorial(n), and that gamma(0.5) returns 1.7725, which is the square root of pi. The gamma function has poles at zero and the negative integers, and it overflows to Inf at gamma(172) (or gamma(single(36)) for single precision). That is the same boundary as factorial(171), since gamma(172) corresponds to 171!.

When the factorial itself is too large but you only need its logarithm, for example when computing a probability from ratios of factorials, use gammaln, which MathWorks lists next to gamma. Working on the log scale and exponentiating the final difference avoids the overflow entirely.

Troubleshooting

“Unexpected MATLAB operator” or a syntax error after typing 5!

The postfix ! is not MATLAB syntax. Write factorial(5).

An error for negative or non-integer input

The documented input is a real nonnegative integer. For 2.5 or other non-integers use gamma(x+1). Gamma has poles at the negative integers, so it is not a substitute for negative inputs.

Result is Inf

You have passed the double limit (n of 171 or more) or the single limit. Use gammaln for logarithms or work with ratios before evaluating.

Result looks too small or identical for several inputs

Check the class of the input with class(n). If it is an integer class such as uint8, the output has saturated to the class maximum. Convert with double(n) before calling factorial.

The digits after the 15th look random

For double input above 21! only the first 15 digits are accurate. Use sym() input if you need all digits.

Code will run on a GPU or distributed array

Avoid 64-bit integer input in that case, because those classes are not supported.

Free alternatives

GNU Octave, a free open-source numerical computing environment, has a factorial function with the same call pattern. Its documentation describes it as returning the factorial of n where n is a real non-negative integer, applied elementwise to arrays; for a scalar it equals prod(1:n). It warns that results overflow in double precision once n exceeds 171, and it points to gamma for non-integers and gammaln for large values.

Need MATLAB GNU Octave
Factorial of nonnegative integers, array-wise factorial(n) factorial(n)
Equivalent product for a scalar prod(1:n) prod(1:n)
Non-integer argument gamma(n+1) gamma
Logarithm of a very large factorial gammaln gammaln

Octave’s documentation also cautions that gamma values can grow quite large even for small inputs and recommends gammaln where precision matters. Always test code moved between the two programs on a few values near the overflow boundary.

Frequently asked questions

How do I write a factorial in MATLAB?

Call factorial(n). The expression n! is not valid MATLAB syntax.

What does the factorial function in MATLAB return for 0?

It returns 1, consistent with the definition of 0!; MathWorks’ array example factorial([0 1 2; 3 4 5]) returns 1 in the first position.

What is the largest factorial MATLAB can compute?

In double precision the largest finite result is 170!; factorial(171) returns Inf. Only n up to 21 is exact.

How do I get an exact factorial for larger n?

Use symbolic input, as in factorial(sym(20)), which returns the exact integer 2432902008176640000, or avoid the need by working with gammaln.

Can I compute the factorial of a decimal number?

Not with factorial. Use gamma(x+1) for real non-integer x; for example gamma(0.5) is the square root of pi, about 1.7725.

Is there a free alternative?

GNU Octave provides factorial, gamma and gammaln with similar behaviour.

Sources

All documentation pages were read on 2026-11-12.

Related reading on this site: MATLAB coding basics and the while command in MATLAB.

Data: MATLAB factorial() thresholds by numeric class

Input values n at which MATLAB's factorial function stops returning exact results, overflows to Inf, or saturates to the class maximum, for each numeric input class, compiled from the MathWorks factorial reference page.

MATLAB factorial() thresholds by numeric class
Input classnBehaviour
double21Largest n with an exact result
double171Returns Inf (170! is the largest finite value)
single13Largest n with an exact result
single35Overflow at factorial(single(35))
uint64 / int6421Result saturates to class maximum at factorial(21)
uint32 / int3213Result saturates at factorial(13)
uint169Result saturates at factorial(9)
int168Result saturates at factorial(8)
uint8 / int86Result saturates at factorial(6)

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Factorial in MATLAB: factorial(), Limits and Exact Results

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →