Here is a code for calculating Convolution(maths). it perfectly works for the input sequence lengths of 3 and 2 for first two inputs...

compile and try this:

Input:

1. 3

2. 2

3. 1 2 3

4. 1 2

Final Output:

Convoluted

1

4

7

6

here is the code:

C Code:<div class="bbcode_container"> <div class="bbcode_description">Code:</div> <pre class="bbcode_code"style="height:1212px;">#include<stdio.h> #include<malloc.h> typedef struct _Matrix{ float **mat; int m,n; }Matrix; Matrix* matrix_new_Matrix(int m, int n) { Matrix *newMat = (Matrix*)malloc(sizeof(float)); newMat->mat = (float*)malloc(sizeof(float)*m); int i = 0; for(i =0 ; i < m ; i++){ newMat->mat[i] = (float*)malloc(sizeof(float)*n); } newMat->m = m; newMat->n = n; return newMat; } Matrix* matrix_multiply(Matrix *A, Matrix *B) { if(A->n != B->m){ printf("\nMatrices cannot be multiplied"); return NULL; }else{ Matrix *C = matrix_new_Matrix(A->m,B->n); int i,j,k; for(i = 0 ;i< A->m; i++){ for(j=0; j < B->n ; j++){ C->mat[i][j] = 0; for( k =0;k < A->n;k++){ C->mat[i][j]+=A->mat[i][k] * B->mat[k][j]; } } } return C; } } int matrix_print(Matrix *matA, char* name) { int i=0 , j=0; printf("\n%s\n",name); for(i = 0; i < matA->m; i++){ for(j = 0; j < matA->n; j++ ){ printf("%0.3f\t",matA->mat[i][j]); } printf("\n\n"); } return 0; } Matrix *convolve(int *X,int Xn, int *Y,int Yn) { int N = Xn+Yn-1; Matrix *A = matrix_new_Matrix(N,Yn); Matrix *B = matrix_new_Matrix(Yn,1); matrix_print(A,"A"); int i,j; printf("\nj\ti\t,Xn+i\tA->mat[j][i]\tYn\tN"); for(i=0 ; i < Yn; i++ ){ for(j=0; j<i; j++){ A->mat[j][i] = 0; printf("\n%d\t%d\t%d\t%f\t%d\t%d",j,i,Xn+i,A->mat[j][i],Yn,N); } for(j =j; j< Xn+i; j++){ A->mat[j][i] = X[j-i]; printf("\n%d\t%d\t%d\t%f\t%d\t%d",j,i,Xn+i,A->mat[j][i],Yn,N); } for(j =j; j<N; j++){ A->mat[j][i] = 0; printf("\n%d\t%d\t%d\t%f\t%d\t%d",j,i,Xn+i,A->mat[j][i],Yn,N); } } matrix_print(A,"x(n)"); for(i=0; i< Yn; i++){ B->mat[i][0] = Y[i]; } matrix_print(B,"h(n)"); Matrix *C = matrix_multiply(A,B); return C; } int main() { int m,n,i; printf("\nEnter the number of points in first sequence: "); scanf("%d",&m); printf("\nEnter the number of points in second sequence: "); scanf("%d",&n); printf("\nEnter the first sequence: \n"); int *x = (int*)malloc(sizeof(int)*m); for(i =0; i< m;i++){ scanf("%d",&x[i]); } printf("\nEnter the second sequence: \n"); int *h = (int*)malloc(sizeof(int)*n); for(i =0; i< n;i++){ scanf("%d",&h[i]); } /* m=4 ; n=3; int x[4] = { 1, 2, 3, 4 }; int h[3] = { 1, 2, 3}; */ Matrix *Y = convolve(x,m,h,n); printf("\n\n\n\n"); matrix_print(Y, "Convoluted"); }</pre> </div>

link to download the source:

https://docs.google.com/file/d/0B616lfmlormnN0hNOUhvOGlzZnc/preview

Tweet This+ 1 thisPost To Linkedin