fold
Combine (fold) vector using function
Description
fold(
returns
the value fun
,v
,defaultVal
)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
Version History
Introduced in R2016b