November 6, 2014
C/C++ : Convolution Source Code v.2
I have created a code to compute convolution from my previous post : C/C++ : Convolution Source Code. That code compute convolution from two vector. Matlab have parameter to get size of the ouput data from convolution process. If you check at Matlab documentation, we can set convolution process by “full”, “same” and “valid”.
So, I have modified my previous convolution method by “full” and “same” parameter. Please check my below code :
//convolution algorithm double *conv1(double *A, int lenA, double *B, int lenB, int *lenC, char *cmethod) { int nconv; int i, j, i1; int nb; double tmp; double *C=NULL; double *Result=NULL; nb = 0; //allocated convolution array nconv = lenA + lenB - 1; C = (double*) calloc (nconv, sizeof(double)); //convolution process for (i = 0; i < nconv; i++) { i1 = i; tmp = 0.0; for (j = 0; j < lenB; j++) { if (i1 >= 0 && i1 < lenA) tmp = tmp + (A[i1] * B[j]); i1 = i1 - 1; C[i] = tmp; } } //----------------------------------------------------- //create the result //----------------------------------------------------- if (strcmp(cmethod, "full") == 0) { //get length of convolution array *lenC = nconv; return (C); } else if (strcmp(cmethod, "same") == 0) { *lenC = lenA; nb = (lenB - 1) % 2; if (nb != 0) nb = (lenB + 1) / 2; else nb = (lenB - 1) / 2; Result = (double*) calloc(lenA, sizeof(double)); for (i = 0; i < lenA; i++) Result[i] = C[nb + i]; free(C); return (Result); } else //default=full method { //get length of convolution array *lenC = nconv; return (C); } }
Please try the above function to get convolution result by "full" and "same". You will get the same result like Matlab convolution by full and same.