fold

Combines the elements of an array with a binary function, from left to right.

Category: Symbolic Computations in MATLAB > Symbolic Variables, Expressions, Functions, and Preferences

Syntax

r = fold(f, A)

Applies the two-argument function f cumulatively along the elements of A.

Description

fold(f, [a b c]) computes f(f(a, b), c): the first two elements are combined, the result is combined with the third, and so on. Because the grouping is from the left, a non-associative function such as subtraction gives a - b - c, not a - (b - c).

It is a convenient way to apply an operation that only takes two operands, like gcd or lcm, to a whole list of symbolic values.

Input arguments

f
Function handle taking two arguments, such as @plus or @(p, q) p*q.
A
Symbolic array to reduce.

Output arguments

r
Symbolic result of folding all elements.

Example

Sum, product and subtraction

syms a b c
fold(@plus, [a 2*a 3*a])
fold(@(p, q) p*q, [a b c])
fold(@(p, q) p - q, [a b c])
Output
ans = 6*a
ans = a*b*c
ans = a - b - c

See also

children sum prod arrayfun cumsum