python实现matlab中的filter函数
- clc;clear all;close all;
- h = [8, -3.5, 0.5, -1.5, 0.2517, 18, 19, 20];
- a = [1];
- x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
- y = filter(h,a,x);
- % y的值:[8,12.5000000000000,17.5000000000000,21,24.7517000000000,46.5034000000000,87.2551000000000,148.006800000000,208.758500000000,269.510200000000,330.261900000000,391.013600000000,451.765300000000,512.517000000000,573.268700000000,634.020400000000]
复制代码
- import numpy as np
- from scipy.signal import lfilter
- def filter_matlab(b, a, x):
- y = []
- y.append(b[0] * x[0])
- for i in range(1, len(x)):
- y.append(0)
- for j in range(len(b)):
- if i >= j:
- y[i] = y[i] + b[j] * x[i - j]
- j += 1
- for l in range(len(b) - 1):
- if i > l:
- y[i] = (y[i] - a[l + 1] * y[i - l - 1])
- l += 1
- i += 1
- return y
- h = [8, -3.5, 0.5, -1.5, 0.2517, 18, 19, 20]
- a = [1]
- x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
- # y = filter_matlab(h, a, x) # 这个基本对 但是有bug 以后再细看
- # https://stackoverflow.com/questions/8922657/matlab-filter-with-scipy-lfilter
- y = lfilter(h, a, x)
- # According to their documentation for Matlab filter() and SciPy lfilter()
- print("python的结果(个数=%d):" % len(y), y)
- # python的结果(个数=16): [ 8. 12.5 17.5 21. 24.7517 46.5034 87.2551 148.0068
- # 208.7585 269.5102 330.2619 391.0136 451.7653 512.517 573.2687 634.0204]
复制代码
|