factorial — Compute elementwise factorial values while preserving numeric class and shape.
factorial evaluates nonnegative integer-valued input, preserves floating or fixed-width integer storage, applies documented saturation, and supports validated provider-resident execution.
Syntax
F = factorial(N)
F = factorial(N, "like", prototype)Inputs
N- Type
NumericArray- Required
- Yes
- Description
- Dense real, finite, nonnegative integer-valued input.
like- Type
StringScalar- Required
- Yes
- Description
- Literal string "like".
prototype- Type
LikePrototype- Required
- Yes
- Description
- RunMat output-residency prototype; the result class still follows N.
Returns
F- Type
NumericArray- Description
- Elementwise factorial values with the input class and shape.
Errors
RunMat:factorial:InvalidArgument- When
- The invocation has an invalid arity or malformed optional arguments.
- Message
factorial: invalid argument
RunMat:factorial:InvalidInput- When
- Input is complex, sparse, nonnumeric, nonfinite, negative, or not integer-valued.
- Message
factorial: invalid input
RunMat:factorial:GpuUnsupported- When
- Resident output is requested but no compatible provider owns or can create it.
- Message
factorial: gpu output not supported
Values, classes, and saturation
factorial(N) multiplies the positive integers from 1 through each element of N. Input must be dense, real, finite, nonnegative, and integer-valued. Zero returns one; a negative, fractional, infinite, NaN, complex, sparse, or nonnumeric input produces an error.
The result has the same size and numeric class as N. Double overflows to positive infinity at 171, single at 35, and each fixed-width integer class saturates at its maximum value when the mathematical result no longer fits.
RunMat extensions
RunMat compatibility mode also accepts logical input, returning double values, and provides factorial(N, "like", prototype). The prototype selects host or provider residency only; it does not change the class or shape selected from N.
A MATLAB compatibility pin rejects both extension forms. The one-input form, including all eight fixed-width integer classes and their saturating result rules, remains compatible.
Accelerated and distributed execution
Provider-resident real single and double input uses the owning provider's factorial operation when available. The runtime validates the returned shape, storage, precision, owner, device, and non-aliasing before preserving the input's residency intent.
A typed unsupported operation gathers through the exact owner, evaluates on the host, and restores the result when the provider can represent it. Other provider failures remain errors. Compatible GPU and distributed forms exclude 64-bit integer input; RunMat's explicit like form can request provider residency for a host result.
Examples
Compute a scalar factorial
F = factorial(5)Expected output:
F = 120Evaluate an array element by element
N = [0 1 3; 4 5 6];
F = factorial(N)Expected output:
F = [1 1 6; 24 120 720]Preserve exact uint64 results
N = uint64([5 10 20]);
F = factorial(N)Expected output:
F is a uint64 row vectorSaturate at an integer class boundary
F = factorial(uint8([5 6]))Expected output:
F = uint8([120 255])Observe floating-point overflow
Fd = factorial(171);
Fs = factorial(single(35));Expected output:
Fd and Fs are positive infinityUse logical input in RunMat mode
F = factorial(logical([0 1 1]))Expected output:
F = [1 1 1]Keep compatible integer input resident
G = gpuArray(uint16([3 4 5]));
Gf = factorial(G);
F = gather(Gf)Expected output:
F = uint16([6 24 120])Select output residency in RunMat mode
prototype = gpuArray(0);
Gf = factorial([3 4], 'like', prototype);
F = gather(Gf)Expected output:
F = [6 24]Using factorial with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how factorial changes the result.
Run a small factorial example, explain the result, then change one input and compare the output.
FAQ
Which inputs are valid?⌄
Dense real single, double, and fixed-width integer values are supported when every element is finite, nonnegative, and integer-valued. RunMat mode also accepts logical values.
Does factorial preserve integer classes?⌄
Yes. Each fixed-width integer class is preserved, and a result beyond that class's range saturates at its maximum value.
Why does factorial(171) return Inf?⌄
The mathematical value of 171! exceeds the largest finite double. Single precision reaches positive infinity at 35!.
What happens for a fractional or negative value?⌄
factorial reports an invalid-input error. Use gamma(X + 1) when the gamma-function extension is the intended calculation.
Does the like prototype choose the result class?⌄
No. RunMat's like extension chooses host or provider residency. The input to factorial determines the result class and shape.
Can a provider input remain resident?⌄
Yes. A valid provider result remains resident, and typed unsupported operations use exact-owner gather and protected restoration when the output representation is supported.
Related Math functions
Elementwise
abs · angle · besselj · bsxfun · complex · conj · double · eps · erf · erfcinv · exp · expm1 · flintmax · gamma · gammaln · heaviside · hypot · imag · int16 · int32 · int64 · int8 · intmax · intmin · ldivide · log · log10 · log1p · log2 · minus · nextpow2 · plus · pow2 · power · rdivide · real · realmax · realmin · realsqrt · rescale · sign · single · sqrt · times · typecast · uint16 · uint32 · uint64 · uint8
Optim
acceptancesa · annealingboltz · annealingfast · coneprog · crossoverarithmetic · crossoverheuristic · crossoverintermediate · crossoverlaplace · crossoverscattered · crossoversinglepoint · crossovertwopoint · eqnproblem · EquationProblem.solve · EquationProblem.subsasgn · EquationProblem.subsref · evaluate · fgoalattain · fitscalingprop · fitscalingrank · fitscalingshiftlinear · fitscalingtop · fminbnd · fmincon · fminimax · fminsearch · fminunc · fseminf · fsolve · fzero · ga · gacreationlinearfeasible · gacreationnonlinearfeasible · gacreationsobol · gacreationuniform · gacreationuniformint · gaplotbestf · gaplotbestindiv · gaplotdistance · gaplotexpectation · gaplotgenealogy · gaplotmaxconstr · gaplotrange · gaplotscorediversity · gaplotscores · gaplotselection · gaplotstopping · integerConstraint · integral · intlinprog · linprog · lsqcurvefit · lsqlin · LsqlinWarmStart.subsasgn · LsqlinWarmStart.subsref · lsqnonlin · lsqnonneg · mutationadaptfeasible · mutationgaussian · mutationpositivebasis · mutationpower · mutationuniform · optimexpr · optimget · OptimizationConstraint.evaluate · OptimizationConstraint.subsasgn · OptimizationConstraint.subsref · OptimizationExitflag.double · OptimizationExitflag.eq · OptimizationExitflag.ne · OptimizationExitflag.string · OptimizationExpression.acos · OptimizationExpression.acosh · OptimizationExpression.acot · OptimizationExpression.acoth · OptimizationExpression.acsc · OptimizationExpression.acsch · OptimizationExpression.asec · OptimizationExpression.asech · OptimizationExpression.asin · OptimizationExpression.asinh · OptimizationExpression.atan · OptimizationExpression.atanh · OptimizationExpression.cat · OptimizationExpression.cos · OptimizationExpression.cosh · OptimizationExpression.cot · OptimizationExpression.coth · OptimizationExpression.csc · OptimizationExpression.csch · OptimizationExpression.ctranspose · OptimizationExpression.cumprod · OptimizationExpression.cumsum · OptimizationExpression.diag · OptimizationExpression.diff · OptimizationExpression.dot · OptimizationExpression.eq · OptimizationExpression.evaluate · OptimizationExpression.exp · OptimizationExpression.ge · OptimizationExpression.horzcat · OptimizationExpression.ldivide · OptimizationExpression.le · OptimizationExpression.log · OptimizationExpression.mean · OptimizationExpression.minus · OptimizationExpression.mldivide · OptimizationExpression.mpower · OptimizationExpression.mrdivide · OptimizationExpression.mtimes · OptimizationExpression.norm · OptimizationExpression.plus · OptimizationExpression.power · OptimizationExpression.prod · OptimizationExpression.rdivide · OptimizationExpression.reshape · OptimizationExpression.sec · OptimizationExpression.sech · OptimizationExpression.sin · OptimizationExpression.sinh · OptimizationExpression.sqrt · OptimizationExpression.subsasgn · OptimizationExpression.subsref · OptimizationExpression.sum · OptimizationExpression.tan · OptimizationExpression.tanh · OptimizationExpression.times · OptimizationExpression.trace · OptimizationExpression.transpose · OptimizationExpression.uminus · OptimizationExpression.uplus · OptimizationExpression.vertcat · OptimizationExpression.zeros · OptimizationExpression.zerosLike · OptimizationProblem.solve · OptimizationProblem.subsasgn · OptimizationProblem.subsref · OptimizationVariable.subsasgn · OptimizationVariable.subsref · optimoptions · optimplotconstrviolation · optimplotfirstorderopt · optimplotfunccount · optimplotfval · optimplotfvalconstr · optimplotmilp · optimplotstepsize · optimplotx · optimproblem · optimset · optimvar · optimwarmstart · particleswarm · patternsearch · psplotbestf · psplotbestx · psplotfuncount · psplotmaxconstr · psplotmeshsize · pswcreationuniform · pswplotbestf · quad · quadprog · QuadprogWarmStart.subsasgn · QuadprogWarmStart.subsref · saplotbestf · saplotbestx · saplotf · saplotstopping · saplottemperature · saplotx · savemilpsolutions · secondordercone · selectionremainder · selectionroulette · selectionstochunif · selectiontournament · selectionuniform · simulannealbnd · solve · surrogateopt · surrogateoptplot · temperatureboltz · temperatureexp · temperaturefast
Trigonometry
acos · acosd · acosh · acotd · acscd · asecd · asin · asind · asinh · atan · atan2 · atan2d · atand · atanh · cos · cosd · cosh · cospi · deg2rad · pol2cart · rad2deg · sin · sind · sinh · sinpi · tan · tand · tanh
Reduction
all · any · bounds · cummax · cummin · cumprod · cumsum · cumtrapz · diff · gradient · max · maxk · mean · median · min · mink · movmax · movmean · movmedian · movmin · movprod · movstd · movsum · movvar · nnz · prod · rms · std · sum · trapz · var
Structure
bandwidth · isdiag · ishermitian · issymmetric · istril · istriu · symrcm
Signal
blackman · butter · buttord · cheb2ord · conv · conv2 · deconv · downsample · envelope · filter · filtfilt · fir1 · freqz · gauspuls · hamming · hann · hilbert · periodogram · pulstran · pwelch · rectpuls · resample · sawtooth · sinc · spectrogram · square · tripuls · unwrap · upsample · zplane
Factor
chol · decomposition · decomposition.ctranspose · decomposition.mldivide · decomposition.mrdivide · decomposition.mtimes · decomposition.rdivide · decomposition.subsref · decomposition.times · decomposition.uminus · decomposition.uplus · eig · eigs · gmres · ichol · ilu · lu · ordeig · ordqz · ordschur · pcg · qr · qz · rsf2csf · schur · svd
Ops
cross · ctranspose · dot · mldivide · mpower · mrdivide · mtimes · pagemtimes · pagetranspose · trace · transpose
Interpolation
griddedInterpolant · griddedInterpolant.subsref · interp1 · interp1q · interp2 · pchip · ppval · spline
Integer Division
Source you can read
Every RunMat function's source is public. Read exactly how factorial is executed, line by line, in Rust.
- View the source for factorial in Rust on GitHub
- Learn how the RunMat runtime works
- Found a bug? Open an issue with a minimal reproduction.
About RunMat
RunMat is a runtime that executes MATLAB-syntax code fast on any GPU. The runtime is free for individuals, including freelancers; students and faculty at an academic institution, for teaching or research there; contributors to an open-source project, for work on that project; organizations with 250 or fewer people and US$10M or less in annual revenue; and anyone, for non-production use. See runmat.com/license.
- RunMat automatically optimizes your math for GPU execution on Apple, Nvidia, and AMD hardware. No code changes needed. Simulations that took hours now take minutes.
- Start running code in seconds. RunMat runs in the browser, on the desktop, or from the CLI. No license server, no IT ticket.