# filtfilt

## 语法

``y = filtfilt(b,a,x)``
``y = filtfilt(sos,g,x)``
``y = filtfilt(d,x)``

## 说明

````y = filtfilt(b,a,x)` 通过正向和反向处理输入数据 `x` 来执行零相位数字滤波。在对数据进行正向滤波后，该函数会匹配初始条件以最大限度地减少启动和结束时的瞬变，反转滤波后的序列，并让反转后的序列再次通过滤波器。结果具有以下特征： 零相位失真滤波器传递函数等于原始滤波器传递函数的平方幅值滤波器阶数是由 `b` 和 `a` 指定的滤波器阶数的两倍 `filtfilt` 实现了 Gustafsson 提出的算法 [1]。不要将 `filtfilt` 与微分器和希尔伯特 FIR 滤波器结合使用，因为这些滤波器的运算在很大程度上取决于它们的相位响应。```
``y = filtfilt(sos,g,x)` 使用由矩阵 `sos` 和定标值 `g` 表示的二阶节 (biquad) 滤波器对输入数据 `x` 进行零相位滤波。`

``y = filtfilt(d,x)` 使用数字滤波器 `d` 对输入数据 `x` 进行零相位滤波。使用 `designfilt` 根据频率响应设定生成 `d`。`

## 示例

```wform = ecg(500); plot(wform) axis([0 500 -1.25 1.25]) text(155,-0.4,"Q") text(180,1.1,"R") text(205,-1,"S")```

```rng default x = wform' + 0.25*randn(500,1); d = designfilt("lowpassfir", ... PassbandFrequency=0.15,StopbandFrequency=0.2, ... PassbandRipple=1,StopbandAttenuation=60, ... DesignMethod="equiripple"); y = filtfilt(d,x); y1 = filter(d,x); subplot(2,1,1) plot([y y1]) title("Filtered Waveforms") legend("Zero-phase Filtering","Conventional Filtering") subplot(2,1,2) plot(wform) title("Original Waveform")```

```d1 = designfilt("lowpassiir",FilterOrder=12, ... HalfPowerFrequency=0.15,DesignMethod="butter"); y = filtfilt(d1,x); subplot(1,1,1) plot(x) hold on plot(y,LineWidth=3) legend("Noisy ECG","Zero-Phase Filtering")```

```function x = ecg(L) %ECG Electrocardiogram (ECG) signal generator. % ECG(L) generates a piecewise linear ECG signal of length L. % % EXAMPLE: % x = ecg(500).'; % y = sgolayfilt(x,0,3); % Typical values are: d=0 and F=3,5,9, etc. % y5 = sgolayfilt(x,0,5); % y15 = sgolayfilt(x,0,15); % plot(1:length(x),[x y y5 y15]); % Copyright 1988-2002 The MathWorks, Inc. a0 = [0,1,40,1,0,-34,118,-99,0,2,21,2,0,0,0]; % Template d0 = [0,27,59,91,131,141,163,185,195,275,307,339,357,390,440]; a = a0/max(a0); d = round(d0*L/d0(15)); % Scale them to fit in length L d(15)=L; for i=1:14 m = d(i):d(i+1)-1; slope = (a(i+1)-a(i))/(d(i+1)-d(i)); x(m+1) = a(i)+slope*(m-d(i)); end end```

## 参考

[1] Gustafsson, F. “Determining the initial states in forward-backward filtering.” IEEE® Transactions on Signal Processing. Vol. 44, April 1996, pp. 988–992. https://doi.org/10.1109/78.492552.

[2] Mitra, Sanjit K. Digital Signal Processing. 2nd Ed. New York: McGraw-Hill, 2001.

[3] Oppenheim, Alan V., and Ronald W. Schafer, with John R. Buck. Discrete-Time Signal Processing. 2nd Ed. Upper Saddle River, NJ: Prentice Hall, 1999.