Circular Convolution using Matrix Method | C ++ program to compute circular convolution of two arrays ; Function to find circular convolution ; Finding the maximum size between the two input sequence sizes ; Copying elements of x to row_vec and padding zeros if size of x < maxSize ; Copying elements of h to col_vec and padding zeros if size of h is less than maxSize ; Generating 2D matrix of circularly shifted elements ; Computing result by matrix multiplication and printing results ; Driver program
#include <iostream> NEW_LINE using namespace std ; #define MAX_SIZE  10 NEW_LINE void convolution ( int * x , int * h , int n , int m ) { int row_vec [ MAX_SIZE ] , col_vec [ MAX_SIZE ] ; int out [ MAX_SIZE ] = { 0 } ; int circular_shift_mat [ MAX_SIZE ] [ MAX_SIZE ] ; int maxSize = n > m ? n : m ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= n ) { row_vec [ i ] = 0 ; } else { row_vec [ i ] = x [ i ] ; } } for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i >= m ) { col_vec [ i ] = 0 ; } else { col_vec [ i ] = h [ i ] ; } } int k = 0 , d = 0 ; for ( int i = 0 ; i < maxSize ; i ++ ) { int curIndex = k - d ; for ( int j = 0 ; j < maxSize ; j ++ ) { circular_shift_mat [ j ] [ i ] = row_vec [ curIndex % maxSize ] ; curIndex ++ ; } k = maxSize ; d ++ ; } for ( int i = 0 ; i < maxSize ; i ++ ) { for ( int j = 0 ; j < maxSize ; j ++ ) { out [ i ] += circular_shift_mat [ i ] [ j ] * col_vec [ j ] ; } cout << out [ i ] << " ▁ " ; } } int main ( ) { int x [ ] = { 5 , 7 , 3 , 2 } ; int n = sizeof ( x ) / sizeof ( int ) ; int h [ ] = { 1 , 5 } ; int m = sizeof ( h ) / sizeof ( int ) ; convolution ( x , h , n , m ) ; return 0 ; }