Matlab过滤器和深度过小的Python lfilter ValueError对象

时间:2019-02-25 05:40:05

标签: python matlab scipy filtering

我想在Matlab代码的启发下在Python中过滤信号。 Matlab具有功能filter,应该与scipy.signal.lfilter类似(来自问题:Matlab filter() with SciPy lfilter())。但是,我仍然得到ValueError: object of too small depth for desired array

Matlab代码(以Octave执行):

% Matlab
x = [1.0485e-04  -2.4193e-04  -3.0078e-04  1.5750e-03  -1.9698e-03  1.3902e-04  2.7568e-03  -3.8059e-03  2.0123e-03  3.3257e-03]
xfilt = filter(1, [1 -0.992217938], x);
disp(xfilt);

% output
1.0485e-04  -1.3790e-04  -4.3760e-04   1.1408e-03  -8.3788e-04  -6.9233e-04   2.0699e-03  -1.7522e-03   2.7378e-04   3.5974e-03

Python:

# Python
from scipy.signal import lfilter

x = np.array([1.0485e-04, -2.4193e-04, -3.0078e-04, 1.5750e-03, -1.9698e-03, 1.3902e-04, 2.7568e-03, -3.8059e-03, 2.0123e-03, 3.3257e-03])
lfilter(1, np.array([1, -0.992217938]), x, axis=0)

导致错误的原因:

ValueError                                Traceback (most recent call last)
<ipython-input-87-d5c23d362b45> in <module>
      1 x = np.array([1.0485e-04, -2.4193e-04, -3.0078e-04, 1.5750e-03, -1.9698e-03, 1.3902e-04, 2.7568e-03, -3.8059e-03, 2.0123e-03, 3.3257e-03])
----> 2 print(lfilter(1, np.array([1, -0.992217938]), x, axis=0))

~/anaconda3/envs/*env*/lib/python3.6/site-packages/scipy/signal/signaltools.py in lfilter(b, a, x, axis, zi)
   1378     else:
   1379         if zi is None:
-> 1380             return sigtools._linear_filter(b, a, x, axis)
   1381         else:
   1382             return sigtools._linear_filter(b, a, x, axis, zi)

ValueError: object of too small depth for desired array

系统

  • Python:3.6.8
  • Scipy:1.2.0

尝试

基于问题“ Matlab filter not compatible with Python lfilter,我尝试将axis=0添加到lfilter,但是仍然出现ValueError。

问题

如何在Python中执行Matlab代码?

1 个答案:

答案 0 :(得分:1)

SciPy的lfilter期望b参数是一维数组(或“类似数组的数组”,例如列表),而不是标量。例如,

lfilter([1], np.array([1, -0.992217938]), x, axis=0)