<jupyter_start><jupyter_text>Convolutionz(t) = x(t) ∗ y(t) = ∫ x(T)y(t−T)dT.Consider a continuous-time signal, which we discretize in time domain with sampling frequency Fs=100Hz. Convolve this exponential impulse x(t) with a sinc-squared function y(t). The FFT of the convolution of two functions is equal to the product of the FFT of the two individual functions!<jupyter_code># Computing convolution via the frequency domain
# Calculate the spectrum X(f)=F{x(t)} and Y(f)=F{y(t)}. Calculate the elementwise product Z(f)=X(f)⋅Y(f)
# Perform inverse Fourier transform to get back to the time domain z(t)=F−1{Z(f)}

# Ex: We take two sequences of length N=128, one being the exponential impulse and the other one being a sine wave 
# calculate the convolution once in time domain and once in the frequency domain:

import matplotlib.pyplot as plt
%matplotlib inline

N = 128
n = np.arange(N)

x_samples = np.exp(-0.1*n)
y_samples = np.sin(2*np.pi*n/32) # output 4 full waves for an easy view
z_samples = np.convolve(x_samples, y_samples)

# Application of the convolution theorem: Taking the fft of both signals, multiplying them, then taking the ifft.
z2_samples = np.fft.ifft(np.fft.fft(x_samples) * np.fft.fft(y_samples)).real

plt.subplot(2,1,1)
plt.plot(x_samples, 'c')
plt.plot(y_samples, 'y')
plt.plot(z_samples, 'b')

plt.subplot(2,1,2)
plt.plot(x_samples)
plt.plot(y_samples)
plt.plot(z2_samples)

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

frequency = 5 # show 5 full waves
t = np.arange(0,1,1/180) # take 180 data for a smooth sampling
signal = np.sin(2* np.pi* frequency*t) # create a sin sample wave
plt.plot(signal) # plot the sin wave

Y = np.fft.fft(signal) / len(signal) # take the fft
Y = np.abs(Y[:(len(signal)//2)]) # take the half and the abs value
plt.plot(np.arange((len(t)//2)), Y, '-') # view the peak at 5
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

Fs = 100    # the sampling frequency
T = 10      # the time duration for observation
t = np.arange(-T, T, 1/Fs)  # the corresponding samples

# define our two functions
x = lambda t: np.exp(-abs(t)) * (t>=0)
y = lambda t: np.sinc(t)**2

# the resulting time range, when convolving both signals
t_conv = np.arange(-2*T, 2*T, 1/Fs)[:-1]

plt.subplot(2,1,1) 
plt.plot(t, x(t))
plt.plot(t, y(t))
z = np.convolve(x(t), y(t))/Fs
plt.plot(t_conv, z)

# function to calculate the spectrum of the input signal
spec = lambda x: abs(np.fft.fftshift(np.fft.fft(x, 4*len(t))))/Fs
X = spec(x(t))
Y = spec(y(t))
Z = spec(z)
f = np.linspace(-Fs/2, Fs/2, len(X))

plt.subplot(2,1,2)
plt.plot(f, X)
plt.plot(f, Y)
plt.plot(f, Z)<jupyter_output><empty_output>
StarcoderdataJupyterStructuredCleanDedup