中心频率可调的FIR带通滤波器代码
时间: 2023-10-06 18:07:48 浏览: 78
以下是一个中心频率可调的FIR带通滤波器的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成信号
fs = 1000 # 采样率
t = np.arange(0, 1, 1/fs) # 时间轴
x = np.sin(2*np.pi*50*t) + np.sin(2*np.pi*200*t) + np.sin(2*np.pi*300*t)
# 设计FIR带通滤波器
def fir_bandpass_filter(fs, lowcut, highcut, numtaps=128):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
taps = numtaps + 1
coefficients = np.zeros(taps)
for i in range(taps):
if i == numtaps // 2:
coefficients[i] = high - low
else:
coefficients[i] = (np.sin(high * np.pi * (i - numtaps // 2)) - np.sin(low * np.pi * (i - numtaps // 2))) / (np.pi * (i - numtaps // 2))
return coefficients
# 中心频率可调
def fir_bandpass_filter_center_frequency(fs, center, bandwidth, numtaps=128):
lowcut = center - bandwidth/2
highcut = center + bandwidth/2
return fir_bandpass_filter(fs, lowcut, highcut, numtaps)
# 应用滤波器
coefficients = fir_bandpass_filter_center_frequency(fs, 150, 50, 128)
filtered_x = np.convolve(x, coefficients, mode='same')
# 绘制结果
plt.subplot(2, 1, 1)
plt.plot(t, x)
plt.title('Original Signal')
plt.subplot(2, 1, 2)
plt.plot(t, filtered_x)
plt.title('Filtered Signal')
plt.show()
```
其中,`fir_bandpass_filter` 函数用于设计一个固定中心频率的带通滤波器,`fir_bandpass_filter_center_frequency` 函数则将其改为可调整中心频率。在代码中,将中心频率设为150Hz,带宽设为50Hz,生成了一个混合了50Hz、200Hz和300Hz的信号,然后应用带通滤波器进行滤波处理,并绘制了原始信号和滤波后的信号。
阅读全文