# Why is this MATLAB butterworth filter giving me wrong results

Given a 128 Hz signal, in MATLAB I entered the following command

[B,A] = butter(2,[1/64,63/64],'bandpass'); %construct second order all pass filter
Filtered_Data = filter(B,A, Data) %filter data using butterworth filter And got This is far from what I expected since the filter should have passed all frequencies. an someone help point out what I'm doing incorrectly?

• Your design is not a second order allpass filter (as in the comment of the code), but a 4th order bandpass filter. What's the sampling frequency of the data? – Matt L. Dec 1 '14 at 9:02

Your filter is passing only between 1 and 63 Hz, assuming that you meant to say that the sampling rate is 128Hz.

Since you are removing everything below 1Hz, the plot you have looks reasonable.

The range of values in your original signal is relatively small (4395 to 4420,) and the range of values in the output plot is also relatively small (cannot tell exactly due to scaling, but it looks small.)

The high values (+4000, -2000) in your output plot are the step response of your filter. Your data jumps from zero (before the first data point comes in) to around 4400 at the beginning. This step causes the filter to overreact - the short peaks up to 4000 and down to -2000 are the result. This damps out right away, and the rest looks pretty much like what would be expected.

The offset (about 4400) looks like a DC component to the filter. Since DC is lower than 1Hz, it gets removed as well.

The problem might be in the way you are defining the cut-off frequencies. Matlab uses normalized frequencies (look at the examples here http://it.mathworks.com/help/signal/ref/butter.html), therefore you have to define them in this way:

assuming you want to cut your signal at $5 Hz$ and $100 Hz$ and your sampling frequency is $Fs$ (which you haven't specify)

cut_f1 = 5;
cut_f2 = 100;
Wn = [cut_f1/(Fs/2) cut_f2/(Fs/2)];


This is the $Wn$ you have to pass to the butter() function.

Moreover, I suggest you to use the command

filtfilt()


to filter your data in such a way to null the phase shift introduced by the filter (http://it.mathworks.com/help/signal/ref/filtfilt.html).