# FIR Filter implementation vs Linear convolution implementation

I 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?

• In your second code snippet the index to the array x[] is i-4+1+j. Now, as an example, if i=0 and j=0 (which will happen), what will the resulting index be then? Ask yourself if this makes sense. Then ask yourself if this whole question makes any sense. Feb 27, 2020 at 11:37
• @MattL. All the negative indexed values are getting replaced with 0. I verified it too. It is as expected, right?
– rkc
Feb 27, 2020 at 11:57
• No, you can't count on that, you have to make that sure in your code. Feb 27, 2020 at 11:58
• @MattL. Yes. I verified by printing every value of x. All the negative indexed values of x are 0.
– rkc
Feb 27, 2020 at 12:00
• OK, but how does that guarantee anything? By addressing out-of-range values of an array you're just hoping to be lucky. The result can be completely arbitrary. Feb 27, 2020 at 12:02