prod

Product of array elements.

Category: Language Fundamentals > Operators and Elementary Operations

Syntax

P = prod(A)

Multiplies along the first non-singleton dimension: down the columns of a matrix, or along a vector.

P = prod(A, dim)

Multiplies along dimension dim.

P = prod(A, 'all')

Multiplies every element and returns a scalar.

Description

prod(1:n) is n!. Large products can overflow quickly: with doubles the result becomes Inf past about 1.8e308, and integer types saturate at their maximum, so prod(int8([100 2])) is 127.

For a sum of logarithms that avoids overflow, use exp(sum(log(x))) when all elements are positive.

Input arguments

A
Numeric or logical array.
dim
Dimension to multiply along.

Output arguments

P
The products. An empty array gives 1.

Example

prod(1:5)
A = [1 2; 3 4];
prod(A)
prod(A, 2)
prod(A, 'all')
prod([])
Output
ans = 120
ans = 1×2

     3     8
ans = 2×1

     2
    12
ans = 24
ans = 1

See also

sum cumprod factorial max