import numpy as np
import matplotlib.pyplot as plt
Convolution
For two functions \(f(x)\) and \(g(x)\), the convolution function \(f(x) * g(x)\) is defined as:
\[\begin{equation} (f * g) (t) = \int_{-\infty}^{\infty} f(τ) ⋅ g(t - τ) dτ \end{equation}\]
for discrete samples that we deal with: \[\begin{equation} y[n] = f[n] * g[n] = \sum_{k = -∞}^{∞} f[k] ⋅ g[n - k] \end{equation}\]
if \(f\) has \(N\) samples and \(g\) has \(M\) samples, then the convolved function has \(N + M - 1\) samples. A basic rule: “flip any one of the functions, overlap it with the stationary one, multiply and add, and then traverse over.”
def triangle(x):
if x >= 0 and x <= 5:
return 5 - x
elif x < 0 and x >= -5:
return 5 + x
else:
return 0
def rect(x):
if -5 <= x <= 5:
return 5
return 0
def signal(f, x):
return [f(i) for i in x]
= np.arange(-8, 8, 0.1)
x = signal(rect, x)
f_x = "black")
plt.plot(x, f_x, color "Time sample (N)")
plt.xlabel(
plt.grid() plt.show()
\(O(N^2)\) complexity algorithm total \((N + M - 1) \cdot M\) or \((N + M - 1) \cdot N\) computations
= signal(rect, x), signal(rect, x)
A_signal, B_kernel = len(A_signal), len(B_kernel)
N_signal, M_kernel = np.zeros(N_signal + M_kernel - 1)
Y for i in range(len(Y)):
for j in range(M_kernel):
if i - j >= 0 and i - j < N_signal:
+= A_signal[i - j] * B_kernel[j] Y[i]
Convolution of two rect(\(x\))
= (3, 3))
plt.figure(figsize = "green")
plt.plot(x, A_signal, color "Time sample (N)")
plt.xlabel(
plt.grid()
plt.show()
= (3, 3))
plt.figure(figsize = "green")
plt.plot(x, A_signal, color "Time sample (N)")
plt.xlabel(
plt.grid()
plt.show()
print(f"Signal Length: {N_signal}, Convolved Signal Lenght: {len(Y)}")
= "red")
plt.plot(Y, color "Index Number (k)")
plt.xlabel(
plt.grid() plt.show()
Signal Length: 160, Convolved Signal Lenght: 319
= signal(triangle, x), signal(triangle, x)
A_signal, B_kernel = len(A_signal), len(B_kernel)
N_signal, M_kernel = np.zeros(N_signal + M_kernel - 1)
Y for i in range(len(Y)):
for j in range(M_kernel):
if i - j >= 0 and i - j < N_signal:
+= A_signal[i - j] * B_kernel[j] Y[i]
Convolution of two triangle(\(x\))
= (3, 3))
plt.figure(figsize = "cyan")
plt.plot(x, A_signal, color "Time sample (N)")
plt.xlabel(
plt.grid()
plt.show()
= (3, 3))
plt.figure(figsize = "cyan")
plt.plot(x, A_signal, color "Time sample (N)")
plt.xlabel(
plt.grid()
plt.show()
print(f"Signal Length: {N_signal}, Convolved Signal Lenght: {len(Y)}")
= "blue")
plt.plot(Y, color "Index Number (k)")
plt.xlabel(
plt.grid() plt.show()
Signal Length: 160, Convolved Signal Lenght: 319