此图与下边的没有任何关系,是简化中的即另一篇的原理;
FIR : y(n) = b0(x[n]) + … +bM-1(x[n-M+1])
IIR : y(n) = {b0(x[n]) + … +bM-1(x[n-M+1])} - {a1(y[n-1]) + … +aN(y[n-N}
代码仅仅可以参考因为这里只是处理一帧,当一段语音时,某些变量需要定义为头文件中的全局变量即extern类的变量,还有第二部分代码与第一部分完全不一样一个是前边的值,一个是后边的值:
void IIRFloat(double *coeffs_B, double *coeffs_A, double *input, double *output, int length, int filterLength)
{
double bcc, acc;
double *coeffa, *coeffb;
double *inputp;
double *outputp;
int n,k;
//filter length =7
for (n = 0; n < length; n++) {
coeffa = coeffs_A;
coeffb = coeffs_B;
inputp = &insamp[filterLength - 1 + n]; //insamp[6]~insamp[85]
acc = 0;
bcc = 0;
for (k = 0; k < filterLength; k++) {
bcc += (*coeffb++) * (*inputp--); //b[0] * x[6] + b[1] * x[5]...+b[6] * x[0]
}
for (k = 1; k < filterLength; k++) {
acc += (*coeffa++) * (*output--); //a[1] * y[5] + a[2] * y[4]...+a[6] * y[0]
}
output[n] = bcc-acc;
}
}
假设你有过滤器
y[n] = bx[n]-ay[n-1]
通常,第一个输出被初始化为给定值,例如0。
假设你想过滤长度的信号x,N那么你应该这样做:
double out[N]; //output vector
double a = 0.3, b=0.5; //assign the coefficients a value
out[0] = 0; //initialize the first element
for (int i=1; i<N; i++)
{
out[i] = bx[i] -a[i-1];
}
在你的代码的情况下,我不知道你在做什么inputp = &insamp[filterLength - 1 + n];,这可能是一个问题。
我会假设inputp你想要过滤的信号。
另一个问题是:使用过滤器filterLength来指示输入元素和输出元素的长度:通常不在IIR过滤器中。
从0到的输出元素filterlength应以某种方式进行初始化,假设为0.然后在第二个循环中,你将循环索引从1开始,但系数数组应该从0开始。使用索引而不是解引用数组,你的代码应该是这样的:
void IIRFloat(double *coeffs_B, double *coeffs_A, double *input, double *output, int length, int filterLength)
{
double bcc, acc;
double *inputp;
int n,k;
for (int ii=0; ii<filterLength; ii++)
{
output[ii] = 0;
}
//filter length =7
for (n = 0; n < length; n++) {
inputp = &insamp[filterLength - 1 + n]; //insamp[6]~insamp[85]
acc = 0;
bcc = 0;
for (k = 0; k < filterLength; k++) {
bcc += coeffb[k] * inputp[filterLength-k-1]; //b[0] * x[6] + b[1] * x[5]...+b[6] * x[0]
}
for (k = 0; k < filterLength; k++) {
acc += coeffa[k] * output[filterLength-k-1]; //a[1] * y[5] + a[2] * y[4]...+a[6] * y[0]
}
output[n] = bcc-acc;
}
}