主要内容

fold

Combine (fold) vector elements using function

Description

y = fold(fun,x) folds the elements of x by using fun. That is, fold applies the function fun on the first two elements of x, and then recursively applies fun on the result and the next element until the last element is combined. Programmatically, this syntax is equivalent to fold(fun,x) = fun(fold(fun,x(1:end-1)),x(end)).

example

y = fold(fun,x,initVal) folds the elements of x starting from the initial value initVal by using fun. (since R2026a)

example

Examples

collapse all

Fold a vector of symbolic variables using the power function. The output shows how fold combines elements of the vector from left to right by applying the specified function.

syms a b c d
x = [a b c d];
y = fold(@power,x)
y = abcd

Set an assumption that the variable x belongs to the set of values 1, 2, ..., 10. Applying the or function to the conditions x == 1, ..., x == 10 using fold. Check that the assumption is set by using assumptions.

syms x
cond = fold(@or, x == 1:10);
assume(cond)
assumptions
ans = x=1x=2x=3x=4x=5x=6x=7x=8x=9x=10

Since R2026a

You can specify an initial value for the fold operation by using the third input argument. For example, apply the power function recursively using the initial value of 100 and the elements [a 2 3]. The result is 100^(6*a), which is equal to ((100^a)^2)^3.

syms a
x = [a 2 3];
y = fold(@power,x,100)
y = 1006a

Input Arguments

collapse all

Function used to fold the vector, specified as a function handle.

Example: @or

Example: @power

Vector to fold, specified as a vector, symbolic vector, or cell vector. If an element of x is a symbolic function, then the formula or definition of the symbolic function is used by applying formula(x(i)).

Initial value of the fold operation, specified as a number, vector, matrix, or multidimensional array, or a symbolic number, variable, vector, matrix, multidimensional array, function, or expression.

Before R2026a: Specify the default value using the third argument. The fold function returns this default value if the input vector to fold is empty.

Output Arguments

collapse all

Result of fold operation, returned as a number, symbolic number, or symbolic expression.

Version History

Introduced in R2016b

expand all

See Also

|