Skip to main content
 首页 » 编程设计

python之fir2 从 matlab 到 python

2025年05月04日15mq0036

我正在尝试使用 spicy.signal.firwin2 函数将 fir2 过滤器转换为 python,但返回以下错误:

from scipy import signal as sigs 
orderFIR = 4096 
# WdBCor is a numpy array with 22050 values  
outMidFIR = sigs.firwin2(orderFIR+1,range(0,FS/2,1),10**(WdB_cor / 20)) 

错误是:

{ValueError}freq 必须以 0 开头并以 nye 结尾。

谁能解释一下问题出在哪里?或者我应该使用另一个函数来执行与 Matlab 一样的 fir2 过滤器吗?

请您参考如下方法:

阅读 fir2win 的文档很小心。对于第二个参数,freq,它表示:

freq : array_like, 1D

The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being Nyquist. The Nyquist frequency can be redefined with the argument nyq. The values in freq must be nondecreasing. A value can be repeated once to implement a discontinuity. The first value in freq must be 0, and the last value must be nyq.

因此,您首先需要提供一个名为 nyq 的附加参数,该参数重新定义奈奎斯特频率,因为它目前假设 1.0 是奈奎斯特频率。简而言之,在这种情况下您将执行 nyq=FS/2。其次,range 不 包括结束点,此函数要求您将奈奎斯特频率指定为数组中的最后一个元素。因此,您最好使用 numpy.linspace包括起点和终点。

因此,你会这样做:

import numpy as np 
from scipy import signal as sigs 
 
orderFIR = 4096 
num_points = len(Wdb_cor) # Get total number of points 
outMidFIR = sigs.firwin2(orderFIR+1,np.linspace(0,FS/2,num_points),10**(WdB_cor/20), nyq=FS/2)