gpt4 book ai didi

c++ - C++中IIR低通滤波器的实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:45:23 36 4
gpt4 key购买 nike

我有 Butterworth 低通滤波器的滤波器系数,来自 Matlab 函数 [b, a] = butter(3, 0.4, 'low') 我实现了相同的计算 Matlab正在根据 their documentation 使用对于 filter(b, a, X)。例如,过滤常数信号 5.0 的结果是相同的,但只针对前 10 个值!?

我想我的循环缓冲区是错误的,但我找不到任何问题。使用过滤器方法在 x 中正确写入值,用零初始化数组,循环缓冲区指针 n 具有正确的值......你有什么想法?

// Interface
class LowpassFilter {
private:
double x[10]; // input vector
double y[10]; // output vector
int n; // pointer to the current array index

public:
LowpassFilter();
double filter(double sample);
};


// Implementation

// filter coefficients a and b
const double a[] = {1.0, -0.577240524806303, 0.421787048689562, -0.056297236491843};
const double b[] = {0.098531160923927, 0.295593482771781, 0.295593482771781, 0.098531160923927};
static int c = 0;

LowpassFilter::LowpassFilter() : x{0.0}, y{0.0}, n(0) { } // Constructor

double LowpassFilter::filter(double sample)
{
x[n] = sample;
y[n] = b[0] * x[n] + b[1] * x[(n-1)%10] + b[2] * x[(n-2)%10] + b[3] * x[(n-3)%10]
- a[1] * y[(n-1)%10] - a[2] * y[(n-2)%10] - a[3] * y[(n-3)%10];

std::cout << c++ << ": " << y[n] << std::endl; // for checking the result with the Matlab results

double result = y[n];
n = (n + 1) % 10; // new pointer index
return result;
}

最佳答案

感谢Mike Seymouremsr问题是 y[n] 计算中的负索引。要解决这个问题,只需采用一条线:

y[n] = b[0] * x[n] + b[1] * x[(n-1+m)%m] + b[2] * x[(n-2+m)%m] + b[3] * x[(n-3+m)%m]
- a[1] * y[(n-1+m)%m] - a[2] * y[(n-2+m)%m] - a[3] * y[(n-3+m)%m];

确保索引为正。现在它工作正常。非常感谢!

关于c++ - C++中IIR低通滤波器的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22538687/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com