Convolution in Python

Here it is illustrated how to perform convolution in python between two discrete sequence and draw the output sequence.

In the following python code, the convolution function takes two input sequences x and h as arguments. It first initializes the output sequence y with zeros, with a length equal to the sum of the lengths of x and h minus 1.

The nested loops iterate over each element of x and h, and for each pair of elements, it performs the convolution operation by multiplying the corresponding elements and adding the result to the appropriate index of y.

Finally, the result y is printed, which will be the convolution of x and h.

import matplotlib.pyplot as plt

def convolution(x, h):
    m = len(x)
    n = len(h)
    y = [0] * (m + n - 1)  # Initialize output sequence with zeros
    for i in range(m):
        for j in range(n):
            y[i + j] += x[i] * h[j]  # Convolution operation
    return y

# Example usage:
x = [4, 2, 3, 4]  # Input sequence x
h = [1, -1, 0.5]    # Impulse response h

y = convolution(x,h)

# Plotting the convolution result
plt.title('Convolution y[n]')

To plot the output sequence y after performing the convolution, we can use the Matplotlib library in Python. The plt.xlabel, plt.ylabel, and plt.title functions are used to set labels for the x-axis, y-axis, and the title of the plot, respectively. The plt.grid(True) function adds a grid to the plot.

Finally, the function is called to display the plot.




Post a Comment

Previous Post Next Post