如何用numpy/scipy产生矩形脉冲

uwopmtnx  于 2023-04-21  发布在  其他
关注(0)|答案(2)|浏览(134)

我想用python生成一个矩形脉冲。我相信可以用numpy或scipy来完成。但是我不能从API中获得它。在我生成矩形脉冲之后,我将使用matplotlib绘制它。

5m1hhzi4

5m1hhzi41#

要创建一个1D数组,除了1.0值的延伸之外,所有值都为零-矩形脉冲:

import numpy as np
a = np.zeros( (1000,) )   # whatever size. initializes to zeros
a[150:180] = 1.0          # index range sets location, width of impulse

要查看绘图,请执行以下操作:

import matplotlib.pyplot as mp
mp.plot(a)
mp.show()
unhi4e5o

unhi4e5o2#

你也可以使用heaviside函数(在工程中也称为unit step函数),例如numpy.heaviside。脉冲是由两个heaviside序列之间的差异产生的:

n = np.arange(1-N, N)
n1, n2 = -3, 5 # pulse limits
pn = np.heaviside(n-n1, 1) - np.heaviside(n-n2, 1)

heaviside函数将输入数组的值更改为0、常量或1,这取决于它们是负的、空的还是正的。这里,输入数组包含被移位了与某个索引相对应的偏移量的索引值,并且常量是1。

完整编码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tck

# Sample numbers
N = 10
n = np.arange(1-N, N)

# Pulse limits
n1, n2 = -3, 5
pn = np.heaviside(n-n1, 1) - np.heaviside(n-n2, 1)

# Some signal clipped by pulse
xn = 3 * 0.8**n * pn

# Plot everything
fig, axes = plt.subplots(figsize=(6,6), nrows=4, sharex=True, layout='constrained')
axes = axes.flatten()

for ax, p, title in zip(axes[:2], [n1, n2], ['h1', 'h2']):
    ax.set_title(title)
    h = np.heaviside(n-p, 1)
    ax.stem(n, h)

for ax, s, title in zip(axes[2:], [pn, xn], ['pulse', 'signal clipped by pulse']):
    ax.set_title(title)
    ax.stem(n, s)

ax.xaxis.set_major_locator(tck.MultipleLocator())

相关问题