Question

I'm trying to do a convolution algorithm in C but is stacking on the array of convolution.

#include <stdio.h>
#include <math.h>
#include <stddef.h>
#define convtotal 2590

int main(int argc, char *argv[]) {

    int m,n,i,j;
    double x[convtotal],h[convtotal];
    m=sizeof(x)/sizeof(double);
    n=sizeof(h)/sizeof(double);


    double aux1[convtotal], aux2[convtotal],conv[convtotal][1];
    for (i=0;i<n+m;i++){
        if (i<n)
            aux1[i]=x[i];
        else
            aux1[i]=0;

        if (i<m)
            aux2[i]=h[i];
        else
            aux2[i]=0;
    }


    for (i=0;(n+m-1);i++){
        conv[i][1]=0;
        for (j=0;j<m;j++)
            if (i-j+1>0)
                conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);
    }

}

Any suggestions for this problem?

Was it helpful?

Solution

Two problems:

for (i=0;(n+m-1);i++)

You're not limiting i to anything, so the loop doesn't exit when you reach the end of your arrays; it just keeps incrementing i until you hit memory you don't own, at which point you get the segfault. Since conv only goes to m or n, I think you meant to write

for (i = 0; i < n; i++)

Secondly, you declared conv as an Nx1 array, meaning the only legal index in the second dimension may be 0, so the lines

conv[i][1] = 0;

and

conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);

should be

conv[i][0] = 0;

and

conv[i][0]=conv[i][0]+(aux1[j]*aux2[i-j+1]);

Not sure why you declared an Nx1 array (seems you could have just declared conv with one dimension), but I may be missing something obvious.

Note that your x and h arrays initially contain random values.

OTHER TIPS

for (i=0;(n+m-1);i++){
    conv[i][1]=0;
    for (j=0;j<m;j++)
        if (i-j+1>0)
            conv[i][1]=conv[i][1]+(aux1[j]*aux2[i-j+1]);
}

(n+m-1) infinite loop with constant as a stop condition. Not actually infinite, runs untill it segfaults.

for (i=0;(n+m-1);i++){

Shouldn't it be i < m+ n - 1?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top