Professional Documents
Culture Documents
Piecewise Function
Piecewise Function
Syntax
pw = piecewise(cond1,val1,cond2,val2,...)
pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal)
Description
pw = piecewise(cond1,val1,cond2,val2,...) returns the piecewise expression or
function pw whose value is val1 when condition cond1 is true, is val2 when cond2 is true, and
so on. If no condition is true, the value of pw is NaN.
pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal) returns the piecewise
expression or function pw that has the value otherwiseVal if no condition is true.
Examples
Define and Evaluate Piecewise Expression
Define the following piecewise expression by using piecewise.
{
y= −11xx<0>0
syms x
y = piecewise(x<0, -1, x>0, 1)
y =
piecewise(x < 0, -1, 0 < x, 1)
ans =
[ -1, NaN, 1]
y(x) =
piecewise(x < 0, -1, 0 < x, 1)
Because y(x) is a symbolic function, you can directly evaluate it for values of x.
Evaluate y(x) at -2, 0, and 2. Because y(x) is undefined at x = 0, the value is NaN. For
details,.
y([-2 0 2])
ans =
[ -1, NaN, 1]