Matlab 分段函数(piecewise)
语法
pw = piecewise(cond1,val1,cond2,val2,...) pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal)
描述
pw = piecewise(cond1,val1,cond2,val2,...) 返回分段表达式或函数pw,当cond1为True时,其值为val1,当cond2为True时,其值为val2,依次类推。如果没有条件为True时,则值为NaN pw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal) 与上式唯一不同的是,若没有条件为True时,则值为otherwiseVal1
例子
1、定义如下分段表达式
y = { − 1 x 0 y= \begin{cases} -1\quad &x0 \end{cases} y={−11x0
syms x y = piecewise(x 0,1)
通过使用 subs 将 -2,0,2 代入 x。因为 y 在 x=0 处没有定义,所以返回值为 NaN 。
subs(y,x,[-2 0 2]) ⇨ ans = (−1 NaN 1)
2、用符号定义如下分段函数
y ( x ) = { − 1 x 0 y(x)= \begin{cases} -1\quad &x0 \end{cases} y(x)={−11x0
syms y(x) y(x) = piecewise(x 0,1)
因为 y(x) 是符号函数,因此可以直接计算。
y([-2 0 2]) ⇨ ans = (−1 NaN 1)
3、定义如下表达式
y = { − 2 x