Return the discrete linear convolution of two one-dimensional sequences with mode in Python


To return the discrete linear convolution of two one-dimensional sequences, use the numpy.convolve() method in Python Numpy. The convolution operator is often seen in signal processing, where it models the effect of a linear time-invariant system on a signal. In probability theory, the sum of two independent random variables is distributed according to the convolution of their individual distributions. If v is longer than a, the arrays are swapped before computation.

The method returns the Discrete, linear convolution of a and v. The 1st parameter, a (N,) is the first one-dimensional input array. The 2nd parameter, v (M,) is the second one-dimensional input array. The 3rd parameter, mode is optional, with values full’, ‘valid’, ‘same’. The mode ‘valid’ returns output of length max(M, N) - min(M, N) + 1. The convolution product is only given for points where the signals overlap completely. Values outside the signal boundary have no effect.

The default mode is 'full'. This returns the convolution at each point of overlap, with an output shape of (N+M-1,). At the end-points of the convolution, the signals do not overlap completely, and boundary effects may be seen.

Steps

At first, import the required libraries −

import numpy as np

Creating two numpy One-Dimensional array using the array() method −

arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])

Display the arrays −

print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

Check the Dimensions of both the arrays −

print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

Check the Shape of both the arrays −

print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

To return the discrete linear convolution of two one-dimensional sequences, use the numpy.convolve() method in Python Numpy −

print("\nResult....\n",np.convolve(arr1, arr2, mode = 'full' ))

Example

import numpy as np

# Creating two numpy One-Dimensional array using the array() method
arr1 = np.array([1, 2, 3])
arr2 = np.array([0, 1, 0.5])

# Display the arrays
print("Array1...\n",arr1)
print("\nArray2...\n",arr2)

# Check the Dimensions of both the arrays
print("\nDimensions of Array1...\n",arr1.ndim)
print("\nDimensions of Array2...\n",arr2.ndim)

# Check the Shape of both the arrays
print("\nShape of Array1...\n",arr1.shape)
print("\nShape of Array2...\n",arr2.shape)

# To return the discrete linear convolution of two one-dimensional sequences, use the numpy.convolve() method in Python Numpy
print("\nResult....\n",np.convolve(arr1, arr2, mode = 'full' ))

Output

Array1...
[1 2 3]

Array2...
[0. 1. 0.5]

Dimensions of Array1...
1

Dimensions of Array2...
1

Shape of Array1...
(3,)

Shape of Array2...
(3,)

Result....
[0. 1. 2.5 4. 1.5]

Updated on: 28-Feb-2022

479 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements