Matlab 分段函数(piecewise)

EasonZzzzzzz 2024-06-15 15:05:03 阅读 66

在这里插入图片描述

语法

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时,则值为NaNpw = piecewise(cond1,val1,cond2,val2,...,otherwiseVal)与上式唯一不同的是,若没有条件为True时,则值为otherwiseVal1

例子

1、定义如下分段表达式

y = { − 1 x < 0 1 x > 0 y= \begin{cases} -1\quad &x<0\\ 1\quad &x>0 \end{cases} y={ −11​x<0x>0​

syms xy = piecewise(x < 0,-1, x > 0,1)

通过使用 subs 将 -2,0,2 代入 x。因为 yx=0 处没有定义,所以返回值为 NaN

subs(y,x,[-2 0 2]) ⇨ ans = (−1 NaN 1)

2、用符号定义如下分段函数

y ( x ) = { − 1 x < 0 1 x > 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 = { − 2 x < − 2 0 − 2 < x < 0 1 o t h e r w i s e y= \begin{cases} -2\quad &x<-2\\ 0\quad &-2<x<0\\ 1\quad &\rm otherwise \end{cases} y=⎩ ⎨ ⎧​−201​x<−2−2<x<0otherwise​

syms 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 1yvalues = y(xvalues) ⇨ yvalues = (−2 1 0 1 1 )

4、对如下分段表达式进行微分、积分与求极限

y = { 1 x x < − 1 sin ⁡ ( x ) x x ≥ − 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 xy = 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 xpw = piecewise(x < 2,-1,x > 0,1); % 生成分段表达式pw = subs(pw,x < 2,x < 0) % 将条件 x < 2 变更为 x < 0pw = piecewise(x > 5,1/x,pw) % 增添条件 x > 5 时值为 1/x



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。