piecewise
Symbolic piecewise function defined by conditions.
Category: Symbolic Computations in MATLAB > Symbolic Variables, Expressions, Functions, and Preferences
Syntax
p = piecewise(cond1, val1, cond2, val2, ...)
Value of the first branch whose condition is true.
p = piecewise(cond1, val1, ..., otherwiseVal)
A final unpaired value is used when no condition holds.
Description
The branches are tried in order, and the first true condition decides the value. If no condition is true and no final value is given, the result is undefined (NaN) at that point. A trailing unpaired argument works as an otherwise clause and is stored with the condition symtrue.
Piecewise expressions can be evaluated with subs, differentiated with diff, and integrated; the conditions are carried along in the result.
Input arguments
cond- Symbolic condition, such as
x < 0. val- Value or expression returned when its condition is true.
Output arguments
p- Symbolic piecewise expression.
Example
Absolute value as a piecewise function
syms x
p = piecewise(x < 0, -x, x >= 0, x)
subs(p, x, -3)
subs(p, x, 2)
piecewise(x < 0, -1, x > 0, 1, 0)
Output
p = piecewise(x < 0, -x, 0 <= x, x)
ans = 3
ans = 2
ans = piecewise(x < 0, -1, 0 < x, 1, symtrue, 0)