prod — Multiply elements across dimensions in MATLAB and RunMat.
prod(X) multiplies dense real numeric or logical elements along selected dimensions. Omitted axes, missing-data controls, and output-class policies are described below, including RunMat's accepted legacy empty-vector selectors.
Syntax
B = prod(A)
B = prod(A, dim)
B = prod(A, "all")
B = prod(A, missingflag)
B = prod(A, outtype)
B = prod(A, dim, missingflag)All supported prod forms
B = prod(A)
B = prod(A, dim)
B = prod(A, "all")
B = prod(A, missingflag)
B = prod(A, outtype)
B = prod(A, dim, missingflag)
B = prod(A, missingflag, dim)
B = prod(A, vecdim)
B = prod(A, options...)Inputs
A- Type
Any- Required
- Yes
- Description
- Input array.
dim- Type
Any- Required
- No
- Description
- Positive dimension selector or vector of dimensions; omission selects the first non-singleton axis. Only vector-shaped empty selectors (1-by-0 or 0-by-1) select this default; a 0-by-0 empty array is not a selector.
all- Type
StringScalar- Required
- No
- Default
"all"- Description
- Reduce across all dimensions.
missingflag- Type
StringScalar- Required
- No
- Default
"includemissing"- Description
- Missing-data handling mode: "includemissing" or "omitmissing".
outtype- Type
StringScalar- Required
- No
- Default
"default"- Description
- Output class specifier: "double", "default", or "native".
A- Type
Any- Required
- Yes
- Description
- Dense real numeric or logical input.
options- Type
Any- Required
- Variadic
- Description
- One dimension/vector/all selection, optional missing-data flags (last wins), and one default/double/native class control, in either supported order. A vector-shaped empty selection retains the default axis. No like form is accepted.
Returns
B- Type
Any- Description
- Product reduction in the selected numeric class, or logical for native logical input.
Errors
RunMat:prod:InvalidArgument- When
- Dimension, missing-data flag, or output class argument grammar is invalid.
- Message
prod: invalid argument
RunMat:prod:InvalidInput- When
- Input value type is unsupported for prod reduction.
- Message
prod: invalid input
RunMat:prod:ComplexUnsupported- When
- Complex inputs are passed to prod where complex support is not implemented.
- Message
prod: complex inputs are not yet supported
Behavior
prod(X) on an m × n matrix returns a row vector (1 × n) with column-wise products.
prod(X, 2) returns a column vector (m × 1) containing row-wise products.
prod(X, dims) accepts a vector of dimensions (for example [1 3]) and collapses each listed axis while leaving the others untouched.
prod(X, 'all') flattens every dimension into a single scalar product.
Logical inputs enter ordinary products as zero or one and return double. The 'native' option returns logical results; no 'like' prototype syntax is accepted.
prod(___, 'omitnan') ignores NaN values; if every element in the slice is NaN, the result becomes 1, the multiplicative identity.
prod(___, 'includenan') (default) propagates NaN whenever a NaN appears in that slice.
prod(___, outtype) accepts 'double', 'default', or 'native' to control the output class.
The accepted output-class controls are 'default', 'double', and 'native'. 'like' and its prototype are rejected before provider execution.
Empty inputs or reductions along dimensions with size 0 return ones that follow MATLAB shape semantics.
Forms, classes, and shapes
Options are case-insensitive and trimmed. A scalar dimension, vector of positive dimensions, or 'all' selects axes; repeated dimensions in one vector are collapsed. Missing flags are includenan/includemissing or omitnan/omitmissing, with the last missing flag taking precedence. Only one output-class option and one nonempty axis selection are accepted; an empty vector selection may precede a nonempty selection.
Omission selects the first extent not equal to one. Accepted 1-by-0 and 0-by-1 dimension vectors select this default; a 0-by-0 empty array is not a dimension vector. Axes beyond the stored rank are ignored. Selected zero-length axes produce multiplicative identities, while unreduced empty axes remain empty. A no-axis selection preserves each observation, including NaNs under omitnan.
Single default/native products multiply in single precision. Explicit double and ordinary integer/logical products multiply in double. Native integer products multiply with class-preserving saturation. Complex and sparse input are unsupported; character input is not numeric product data. Exactly one result slot is supported, including discarded calls.
Execution and allocation
Inputs and controls retain their invocation owners across suspension. Each call uses its selected execution context and cancellation authority. Provider outputs are checked for owner, device, physical class, shape, and forbidden input aliasing. Operational errors, cancellation, authority loss, and invalid attempted outputs remain terminal; no host replay follows them.
Eligible resident forms stay with the input's exact provider. Automatic resident placement may select an admitted host-and-restore route only before a provider attempt. Explicit gpuArray data and resident controls that require host staging are rejected before gathering; allocation policy alone is not placement consent. A later no-attempt in a multi-stage operation is terminal after earlier provider effects. Resident native integer products use their distinct saturating hooks. Ordinary integer products are not sent to those hooks: a class-conversion route must convert before floating multiplication. The current providers lack that resident integer-to-floating cast, so explicit integer default/double products remain unsupported; automatically placed data may use admitted host conversion.
Finite host allocation is not yet implemented for this operation's array scratch, shape, and output collections. Such paths reject a Managed allocation policy before unowned work; ordinary Unbounded host execution remains available. This restriction is an unfinished allocation capability, not a promise of a bounded host implementation. Native/browser execution shares the Runtime binding; long synchronous host loops do not promise browser yielding.
These operations execute through their Runtime bindings, not a certified fused reduction. The live planner declines fused prod and nnz execution. Distributed execution is not declared by these entries.
Examples
Multiplying the elements of a matrix
A = [1 2 3; 4 5 6];
colProd = prod(A);
rowProd = prod(A, 2)Expected output:
colProd = [4 10 18];
rowProd = [6; 120]Multiplying across multiple dimensions
B = reshape(1:24, [3 4 2]);
prod13 = prod(B, [1 3])Expected output:
prod13 =
16380 587520 4021920 16030080Multiplying with NaN values ignored
values = [2 NaN 4];
cleanProd = prod(values, 'omitnan')Expected output:
cleanProd = 8Rejecting unsupported prototype syntax on GPU input
G = gpuArray(ones(1024, 1024) + 0.01);
proto = gpuArray(zeros(1, 1));
gpuResult = prod(G, 'like', proto);
result = gather(gpuResult)Multiplying all elements of an array into a scalar
P = prod(1:10, 'all')Expected output:
P = 3628800Multiplying with native output type
ints = int16([2 3 4]);
nativeProd = prod(ints, 'native')Expected output:
nativeProd = int16(24)Distinguish default and native arithmetic
A=int8([100 2]); floating=prod(A); saturated=prod(A,'native'); S=prod(single([2 3])); D=prod(single([2 3]),'double');Using prod with coding agents
Open a RunMat example with live inputs, then ask the agent to explain how prod changes the result.
Run a small prod example, explain the result, then change one input and compare the output.
FAQ
When should I use the prod function?⌄
Use prod whenever you need multiplicative reductions: geometric means, determinant-like products, or scaling chains of factors.
Does prod produce double arrays by default?⌄
No. Default output is single for single input and double for double, integer, or logical input. Explicit 'double' returns double; 'native' preserves the input class. Eligible resident results may remain on their input provider.
What does prod(A) return?⌄
Products are computed along the first non-singleton dimension, which becomes size one. The other dimensions retain their sizes.
How do I compute the product of a specific dimension?⌄
Pass the dimension as the second argument (prod(A, 2) for row-wise products) or provide a dimension vector (prod(A, [1 3])) to collapse multiple axes at once.
What happens if all elements are NaN and I request 'omitnan'?⌄
The result becomes 1, matching MATLAB's multiplicative identity semantics for empty slices.
Does prod preserve integer classes?⌄
Use 'native' to preserve an integer class with exact typed saturating multiplication. Default and 'double' convert operands to double before multiplication; they do not saturate in the integer class first. 'like' is not supported.
Related Math functions
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 · rms · std · sum · trapz · var
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
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 prod is executed, line by line, in Rust.
- View the source for prod 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.