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 1 x > 0 y= \begin{cases} -1\quad &x<0\\ 1\quad &x>0 \end{cases} y={ 11x<0x>0

syms x
y = 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)={ 11x<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= 201x<22<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  1
yvalues = 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= x1xsin(x)x<1x1

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 

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-10 15:14:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-10 15:14:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-01-10 15:14:01       82 阅读
  4. Python语言-面向对象

    2024-01-10 15:14:01       91 阅读

热门阅读

  1. python爬虫实战(6)--获取某度热榜

    2024-01-10 15:14:01       57 阅读
  2. Linq练习

    2024-01-10 15:14:01       63 阅读
  3. Android 无限循环RecyclerView的完美实现方案

    2024-01-10 15:14:01       47 阅读
  4. Flink之Task重启策略

    2024-01-10 15:14:01       63 阅读
  5. 如何使用PHP开发缓存优化图片加载速度

    2024-01-10 15:14:01       52 阅读
  6. 广度优先搜索

    2024-01-10 15:14:01       54 阅读