## FIR filtering vs linear convolution

Started by 3 years ago●4 replies●latest reply 3 years ago●207 viewsI came across a C code for the FIR filter on one of the websites. It is as follows

void fir(short * y, const short *x, const short *h, int n_out, int n_coefs)

{

int n;

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

{

int k, sum = 0;

for(k = 0; k < n_coefs; k++)

{

sum += h[k] * x[n - n_coefs + 1 + k];

}

y[n] = sum;

}

}

I used the following input in my main function. Considered n_coeffs as 4 and n_out as 7 (4+4-1). And the coefficients are as follows (after padding)

x ={1,2,3,4,0,0,0};

h={1,2,3,4,0,0,0};

And then, I modified the above FIR code as follows and used it in my function

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

{

y[i] = 0;

for(j = 0; j < 4; j++)

{

y[i] = y[i] + h[j] * x[i - 4 + 1 + j];

}

}

And the obtained output is {4,11,20,30,20,11,4}

But when I perform convolution operation,

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

{

y[i] = 0;

for(j=0;j<4;j++)

{

y[i] = y[i] + h[j] * x [i-j];

}

}

The obtained output is {1,4,10,20,25,24,16}.

Ideally, both convolution and FIR Filter should give the same output, right?

And one more thing I observed is the output will be {4,11,20,30,20,11,4} when the h coefficients are time-reversed before padding i.e. when h={4,3,2,1,0,0,0}.

I am confused a bit, where I am going wrong? Is the code written in such a manner that it gives correct output when the coefficients are reversed?

X is not defined for negative indexes. Using negative indexes brings shame to you ancestors.

Check the values for your index for x[n].

In the FIR filter it looks like x is getting indexed backwards, which is why it doesn't match the convolution. Also, in both functions it looks like negative indices are being referenced (those values are undefined!).

Hello chaitanya02.

Just so you know, the convolution of your 'h' and 'x' sequences is:

[1, 4, 10, 20, 25, 24, 16, 0, 0, 0, 0, 0, 0].

The convolution of two seven-sample sequences produces

a (7+7-1) = 13-sample sequence.