1
$\begingroup$

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?

$\endgroup$
  • $\begingroup$ 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. $\endgroup$ – Matt L. Feb 27 at 11:37
  • $\begingroup$ @MattL. All the negative indexed values are getting replaced with 0. I verified it too. It is as expected, right? $\endgroup$ – rkc Feb 27 at 11:57
  • $\begingroup$ No, you can't count on that, you have to make that sure in your code. $\endgroup$ – Matt L. Feb 27 at 11:58
  • $\begingroup$ @MattL. Yes. I verified by printing every value of x. All the negative indexed values of x are 0. $\endgroup$ – rkc Feb 27 at 12:00
  • $\begingroup$ 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. $\endgroup$ – Matt L. Feb 27 at 12:02
0
$\begingroup$

I believe that the code is written in such a way that it gives a correct output only when the coefficients are passed in the reverse fashion. Comparatively, the code will be simpler if we pass the coefficients in reverse fashion.

| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.