跳转到主内容
websoft网络软件专家 - 深耕网络技术,打造实用软件!

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={−1x<01x>0 y= \begin{cases} -1\quad &x<0\\ 1\quad &x>0 \end{cases}y={−11​x<0x>0​ syms x y = piecewise(x < 0,-1, 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)={−1x<01x>0 y(x)= \begin{cases} -1\quad &x<0\\ 1\quad &x>0 \end{cases}y(x)={−11​x<0x>0​ syms y(x) y(x) = piecewise(x < 0,-1,x > 0,1) 因为 y(x) 是符号函数,因此可以直接计算。 y([-2 0 2]) ⇨ ans = (−1 NaN 1) 3、定义如下表达式 y={−2x<−20−2syms y(x) y(x) = piecewise(x < -2,-2, (-2 < x) & (x < 0),0, 1) 通过 linspace 生成 x 值,再计算 y(x) xvalues = linspace(-3,1,5) ⇨ xvalues = -3 -2 -1 0 1 yvalues = y(xvalues) ⇨ yvalues = (−2 1 0 1 1 ) 4、对如下分段表达式进行微分、积分与求极限 y={1xx<−1sin⁡(x)xx≥−1 y= \begin{cases} \dfrac{1}{x}\quad &x<-1\\[2ex] \dfrac{\sin(x)}{x}\quad &x\geq-1\\ \end{cases}y=⎩⎨⎧​x1​xsin(x)​​x<−1x≥−1​ syms x y = piecewise(x < -1,1/x,x >= -1,sin(x)/x); diffy = diff(y,x) % 微分 inty = int(y,x) % 积分 limit(y,x,0) % 极限 limit(y,x,-1,'right') % 右极限 limit(y,x,-1,'left') % 左极限 5、修改和增添分段表达式 syms x pw = piecewise(x < 2,-1,x > 0,1); % 生成分段表达式 pw = subs(pw,x < 2,x < 0) % 将条件 x < 2 变更为 x < 0 pw = piecewise(x > 5,1/x,pw) % 增添条件 x > 5 时值为 1/x

相关文章