Reputation: 7297
I want to generate a rectangular impulse with python. I believe it can be done with numpy or scipy. But I cannot get it from API. After I generate the rectangular impulse, i will plot it with matplotlib.
Upvotes: 4
Views: 6099
Reputation: 7514
You can also use the heaviside function (aka unit step function in engineering), e.g. numpy.heaviside. A pulse is created by the difference between two heaviside sequences:
n = np.arange(1-N, N)
n1, n2 = -3, 5 # pulse limits
pn = np.heaviside(n-n1, 1) - np.heaviside(n-n2, 1)
The heaviside function changes the values of the input array to 0, to a constant or to 1, depending on whether they are negative, null or positive. Here the input array contains the index values shifted by an offset corresponding to some index, and the constant is 1.
Full code
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())
Upvotes: 1
Reputation: 16906
To create a 1D array, all zeros but for a stretch of 1.0 values - a rectangular impulse:
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
To see a plot:
import matplotlib.pyplot as mp
mp.plot(a)
mp.show()
Upvotes: 6