Reputation: 111
I am trying to convolve a square wave with itself more than once and see the resulting graph. I know how to do convolution by my hands but I am not experienced in signal processing with Python. So my questions are:
x(t) = 1 , 0 ≤ t ≤ 1
x(t) = 0, otherwise
What I have come so far is that I must use numpy's built-in convolve method; but the problem is I am stuck representing this square wave.
Upvotes: 2
Views: 4414
Reputation:
One way to create a suitable 0-1 array is np.fromfunction
, passing it a function that returns True within the wave. Converting to float results in a 0-1 array.
For this illustration it's better to position the wave in the middle of the array, avoiding boundary effects associated with convolution. Using mode='same'
allows for all curves to be plotted together. Also, don't forget to divide the output of convolve
by sample_rate
, otherwise it will grow proportionally to it with each convolution.
import numpy as np
import matplotlib.pyplot as plt
sample_rate = 100
num_samples = 500
wave = np.fromfunction(lambda i: (2*sample_rate < i) & (i < 3*sample_rate), (num_samples,)).astype(np.float)
wave1 = np.convolve(wave, wave, mode='same')/sample_rate
wave2 = np.convolve(wave1, wave, mode='same')/sample_rate
wave3 = np.convolve(wave2, wave, mode='same')/sample_rate
plt.plot(np.stack((wave, wave1, wave2, wave3), axis=1))
plt.show()
Mathematically, these are known as cardinal B-splines and as the density of Irwin–Hall distribution.
Upvotes: 4