fold

Combine (fold) vector using function

Description

example

fold(fun,v) folds v by using fun. That is, fold calls fun on the first two elements of v, and then repeatedly calls fun on the result and the next element till the last element is combined. Programmatically, the fold operation is fold(fun,v) = fun(fold(fun,v(1:end-1)),v(end)).

example

fold(fun,v,defaultVal) returns the value defaultVal if v is empty.

Examples

Fold Vector Using Function

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 using the specified function.

syms a b c d e
fold(@power, [a b c d e])
ans =
(((a^b)^c)^d)^e

Assume Variable Belongs to Set of Values

Assume the variable x belongs to the set of values 1, 2, ..., 10 by applying or 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 == 1 | x == 2 | x == 3 | x == 4 | x == 5 |...
x == 6 | x == 7 | x == 8 | x == 9 | x == 10

Specify Default Value of Fold Operation

Specify the default value of fold when the input is empty by specifying the third argument. If the third argument is not specified and the input is empty, then fold throws an error.

When creating a function to sum a vector, specify a default value of 0, such that the function returns 0 when the vector is empty.

sumVector = @(x) fold(@plus, x, 0);
sumVector([])
ans =
0

Input Arguments

collapse all

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

Example: @or

Vector to fold, specified as a vector, symbolic vector, or cell vector. If an element of v is a symbolic function, then the formula of the symbolic function is used by calling formula.

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