编程实现 IIR 滤波器和 FIR 滤波器matlab代码
时间: 2023-11-18 09:05:22 浏览: 44
好的,下面是 IIR 滤波器和 FIR 滤波器的 MATLAB 代码示例。
## IIR 滤波器代码示例
```matlab
% 定义滤波器系数
[b, a] = butter(4, 0.2); % 4阶低通滤波器,截止频率为 0.2
% 生成随机信号
fs = 1000; % 采样率
t = 0:1/fs:1; % 采样时间
x = sin(2*pi*50*t) + sin(2*pi*120*t) + randn(size(t));
% 滤波
y = filter(b, a, x);
% 画图
figure;
subplot(2,1,1);
plot(t, x);
title('原始信号');
xlabel('时间 (s)');
ylabel('幅值');
subplot(2,1,2);
plot(t, y);
title('滤波后的信号');
xlabel('时间 (s)');
ylabel('幅值');
```
## FIR 滤波器代码示例
```matlab
% 定义滤波器系数
b = fir1(4, 0.2); % 4阶低通滤波器,截止频率为 0.2
% 生成随机信号
fs = 1000; % 采样率
t = 0:1/fs:1; % 采样时间
x = sin(2*pi*50*t) + sin(2*pi*120*t) + randn(size(t));
% 滤波
y = filter(b, 1, x);
% 画图
figure;
subplot(2,1,1);
plot(t, x);
title('原始信号');
xlabel('时间 (s)');
ylabel('幅值');
subplot(2,1,2);
plot(t, y);
title('滤波后的信号');
xlabel('时间 (s)');
ylabel('幅值');
```
这里用到了 `butter` 函数和 `fir1` 函数来设计滤波器系数,然后用 `filter` 函数来进行滤波。生成随机信号用到了 `randn` 函数。如果需要更改滤波器类型和截止频率,可以调整相应的参数。