【问题标题】:Plotting discrete piecewise function - signal绘制离散分段函数 - 信号
【发布时间】:2020-11-13 15:07:02
【问题描述】:

我需要绘制一个由分段函数定义的离散信号:

if n < 0 , x = (135/56) * (0.9)^n - (1/8)(0.1)^n - (2/7)(0.2)^n  

if 0<=n< 4, x = (135/56) * (0.9)^n + (7/8)(0.1)^n + (5/7)(0.2)^n  

if n>=4 , x = (135/56) * (0.9)^n + (7/8)(0.1)^n + (5/7)(0.2)^n + (0.1)^(-4) + (0.2)^(-4)  

我在网上搜索了很多,尤其是在这里,我想出了这段代码,经过多次更正后,它实际上在 spyder 中运行。但结果绝对不是预期的。谁能帮帮我?

import numpy as np
import matplotlib.pyplot as plt
xPoints = []
nPoints = []
q = (135 / 56)
z= -(1/8)
r = -(2/7)
m = 7/8
p = 5 /7
j = np.power(0.1, -3.5)
a = np.power(0.2, -3.5)
for n in range(-5,11):
    if n<0 :
        x = q *np.power(0.9, n) + z* np.power(0.1, n) + r* np.power(0.2, n)
    elif (n>=0 and n<4):
        x =q *np.power(0.9, n) + m* np.power(0.1, n) + p* np.power(0.2, n)
    else:
        x =q *np.power(0.9, n) + m* np.power(0.1, n) + p* np.power(0.2, n)+ j + a
    xPoints.append(x)
    nPoints.append(n)
plt.plot(nPoints, xPoints)
plt.plot.show()

【问题讨论】:

  • 您的问题到底是什么?输出错了吗?你怎么知道,错了?
  • 我知道这是错误的,因为我用计算器手动计算了一些值,但它们不匹配
  • 喜欢什么值? -2? 4? 1.3?
  • 是的,例如对于n=0,x[n] = 4,对于n=-4,x[-4]=0 等等,但是结果的明显问题是它是连续的
  • x[0] 是 4,但为什么 x[-4] 会是 0? x[-1] 为 0。

标签: python-3.x numpy matplotlib signal-processing


【解决方案1】:

在 numpy 中,可以使用 where 创建逐步函数。 numpy 最神奇的功能之一是broadcasting,其中可以一次对完整的值数组调用函数。

您的示例代码创建了预期的曲线,但仅在整数值处添加了一个点。为了创建平滑曲线,np.linspace 创建了一个长数组(下面的代码使用了 -5 和 5 之间的 1000 个小步长)。 (请注意,numpy 需要&amp; operator 用于两个数组表达式的逻辑and。在这种特殊情况下,您可以使用n &lt; 4 而不是(n &gt;= 0) &amp; (n &lt; 4),因为n &lt; 0 的情况更早处理。)

import numpy as np
import matplotlib.pyplot as plt

q = (135 / 56)
z = -(1 / 8)
r = -(2 / 7)
m = 7 / 8
p = 5 / 7
j = np.power(0.1, -3.5)
a = np.power(0.2, -3.5)

n = np.linspace(-5, 5, 1000)
x = np.where(n < 0, q * np.power(0.9, n) + z * np.power(0.1, n) + r * np.power(0.2, n),
             np.where((n >= 0) & (n < 4), q * np.power(0.9, n) + m * np.power(0.1, n) + p * np.power(0.2, n),
                      q * np.power(0.9, n) + m * np.power(0.1, n) + p * np.power(0.2, n) + j + a))
plt.plot(n, x)
plt.show()

如果您只想要整数位置,您可以使用np.arange 而不是np.linspace,然后创建散点图 (plt.scatter(n, x)) 或者stemplot:

import numpy as np
import matplotlib.pyplot as plt

q = (135 / 56)
z = -(1 / 8)
r = -(2 / 7)
m = 7 / 8
p = 5 / 7
j = np.power(0.1, -3.5)
a = np.power(0.2, -3.5)

n = np.arange(-5, 6)
x = np.where(n < 0, q * np.power(0.9, n) + z * np.power(0.1, n) + r * np.power(0.2, n),
             np.where((n >= 0) & (n < 4), q * np.power(0.9, n) + m * np.power(0.1, n) + p * np.power(0.2, n),
                      q * np.power(0.9, n) + m * np.power(0.1, n) + p * np.power(0.2, n) + j + a))
plt.stem(n, x)
plt.show()

【讨论】:

  • 问题是这不可能是正确的情节,因为首先它是连续的,我们需要一个离散的,这就是为什么我担心我的结果
  • 看来,您正在寻找plt.step(n, x, where="post")。或者甚至只是plt.scatter(n, x)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-05
相关资源
最近更新 更多