# Circular Convolution using python

Platform → Python 3.8.3 , numpy

Circular convolution, also known as cyclic convolution, is a special case of periodic convolution, which is the convolution of two periodic functions that have the same period. Periodic convolution arises, for example, in the context of the discrete-time Fourier transform . — Wikipedia

The algorithm we will be using here ->

# 1 ) input x(n) and h(n)# 2 ) For circular convolution we need N*N matrix so initializing empty matrix with np.zeros((shape))# 3 )Copying the x(n) into the first row of the matrix# 4 ) Run a for loop from 1 st row to Nth row.# 5 )In each iteration circularly shift the row vector# 6 )Take transpose of the matrix to get regular form as in circular convolution matrix# 7 ) Make sure that x(n) and h(n) are of same length .# 8 ) Multiply generated matrix with matrix h(n)

The code

importnumpyasnp# circular shift operation# [1 2 3 4] = [4 1 2 3]def shifter(matrix): last = matrix[len(matrix)-1] x = len(matrix) result = [0] * xforiinrange(1,len(matrix)): result[i] = matrix[i-1] result[0] = lastreturnresult# finding circular convolutiondef findCircularConvolution(x,h,n,m): primary_matrix = np.zeros((max(n,m),max(n,m)))foriinrange(0,len(primary_matrix[0])): primary_matrix[0][i] = x[i]foriinrange(1,max(n,m)): primary_matrix[i] = shifter(primary_matrix[i-1]) ultimate_matrix = np.transpose(primary_matrix) difference_in_length = abs(n-m)foriinrange(m,m+difference_in_length): h.append(0) resultant = np.dot(ultimate_matrix,h)returnresultantx = [int(x)forxininput('Enter the x(n) -> ').split()]h = [int(x)forxininput('Enter the h(n) -> ').split()]circular_convolution_result = findCircularConvolution(x,h,len(x),len(h))print(circular_convolution_result)