c++ 自己实现matlab的filter函数
时间: 2023-08-14 15:06:28 浏览: 313
实现MATLAB的filter函数需要使用差分方程,并且需要实现FIR和IIR两种滤波器类型。下面是一个使用C++实现MATLAB的filter函数的示例代码:
```
#include <iostream>
#include <vector>
using namespace std;
// FIR滤波器
vector<double> fir_filter(vector<double> x, vector<double> b)
{
int n = x.size();
int m = b.size();
vector<double> y(n);
for (int i = 0; i < n; i++) {
y[i] = 0;
for (int j = 0; j < m; j++) {
if (i - j >= 0) {
y[i] += b[j] * x[i-j];
}
}
}
return y;
}
// IIR滤波器
vector<double> iir_filter(vector<double> x, vector<double> a, vector<double> b)
{
int n = x.size();
int m = a.size();
int l = b.size();
vector<double> y(n);
for (int i = 0; i < n; i++) {
y[i] = 0;
for (int j = 0; j < l; j++) {
if (i - j >= 0) {
y[i] += b[j] * x[i-j];
}
}
for (int k = 1; k < m; k++) {
if (i - k >= 0) {
y[i] -= a[k] * y[i-k];
}
}
y[i] /= a[0];
}
return y;
}
// filter函数
vector<double> filter(vector<double> b, vector<double> a, vector<double> x)
{
vector<double> y;
if (b.size() > a.size()) {
y = fir_filter(x, b);
} else {
y = iir_filter(x, a, b);
}
return y;
}
// 示例代码
int main()
{
vector<double> x = {1, 2, 3, 4, 5};
vector<double> b = {1, 2, 3, 2, 1};
vector<double> a = {1, -0.5};
vector<double> y = filter(b, a, x);
for (int i = 0; i < y.size(); i++) {
cout << y[i] << " ";
}
cout << endl;
return 0;
}
```
在示例代码中,我们实现了FIR和IIR两种滤波器类型,并通过filter函数实现了MATLAB的filter函数。你可以将你自己的滤波器系数和输入信号传递给filter函数来获得滤波后的输出信号。
阅读全文