# Filtering on time or frequency domain?

I'm applying an ideal filter on the frequency domain. My code below:

N=512;
fs=100;
t=0:1/fs:(N-1)/fs;
s1=sin(2*pi*2*t);
s2=0.2*sin(2*pi*20*t);
s=s1+s2;
subplot(321), plot(t,s)

S=fft(s);
w=linspace(0,fs,N);
subplot(322), plot(w,log(abs(S)))

fc=12;
H=zeros(1,N);
H( w<=fc ) = 1;
H( w>=fs-fc ) = 1;
subplot(323), plot(w,abs(H))

SF=H.*S;
subplot(324), plot(w,log(abs(SF)))

ss = ifft(SF);
subplot(325), plot(t,ss); title('Filtered on freq domain')

h=ifft(H);
ss2=conv(s,h);
subplot(326), plot(t,ss2(N:end)); title('Filtered on time domain')


The results are not the same.

And so my questions are:

1. What am I doing wrong?

2. Is it better to filter on frequency domain or time-domain or it's the same?

3. Sometimes applying a filter on frequency domain results on a "strange" signal after IFFT. Why?

• The problem lies in the fact that the fft of a rectangular signal is a sinc function (which is infinite). However, you are approximating it by a given length. There are different methods to improve this approach based on windowing, for e.g. you could read windowing, also see zeroing fft bins – Irreducible Apr 8 at 5:38
• You are suggesting that I could apply a window to h (near the end of the code) ? I've tried and things don't get better. Why does the frequency domain approach works much better? – Filipe Pinto Apr 9 at 1:48

Mathematically or information-wise, you're doing the same thing.

However, filtering in time domain means convolving the signal with a filter kernel, so the algorithmic complexity would be something like $$O(n^2)$$ in terms of float additions with $$n$$ the length of the signal.

In frequency domain, filtering is an element-wise multiplication which algorithmic complexity is at most $$O(n)$$. You also have to consider the complexity of switching between time-domain and frequency-domain, meaning using an FFT algorithm. The FFT complexity is most of the time $$O(n\log(n))$$.

So the overall complexity of frequency domain filtering would then be $$O(n\log(n))$$, which is way more efficient than $$O(n^2)$$.

Considering for example a 1024-long signal, time-domain filtering would need more than 1 millions operations, while frequency-domain filtering would need approximately 3000 !

• However, if you want minimal latency, you need to do time-domain filtering. – Ben May 6 at 17:11
• not entirely, @Ben. you might wanna look up this paper from Bill Gardner. this paper went from presentation at an AES convention to publication in the Journal in the fastest time i have ever seen. – robert bristow-johnson May 7 at 2:16
• If I’m interpreting it correctly, in order to get zero latency you still need to do time domain filtering, but that frequency domain filtering can be leveraged to improve efficiencies for longer impulse responses. So Ben is technically correct. A bit of nitpicking to supplement a paper that is remarkable in both readability and usefulness. – Dan Szabo May 7 at 4:01