I am trying to process an audio file in Matlab by filtering out all frequencies except those within $\pm 25\ Hz$ of $523\ Hz$ (as well as its harmonics up to the Nyquist).

The resulting waveform should look like the green wave displayed below (blue being the original): enter image description here

However, my resulting waveform is entirely zero:enter image description here

Here is the simple code I wrote:

[s, Fs] = wavread('file.wav');
n = length(s);
f = linspace(-n/2, n/2, n)/(n*Fs);
S = fftshift(fft(s)/n);

filter = zeros(size(S));
f0 = 523;
while (f0<(Fs/2))
    f0 = f0+523;

s_filter = real(ifft(fftshift(S.*filter)*n));
s_filter = int16(s_filter);

Tspan = n/Fs;
t = linspace(0,n,n)/n*Tspan;

plot(t,s, t, s_filter);

The problem is that the filter array returns only zeros. But what exactly causes that?

Any help would be greatly appreciated.

  • 3
    $\begingroup$ Any reason not to use a standard filter design command, such as fir2? $\endgroup$
    – MBaz
    May 10, 2017 at 13:55
  • $\begingroup$ The most simple way is to make the filter by constructing an array which is full of zeros and only contains 1s for the frequencies we want to keep. Pre-defined functions like fir2 are beyond the scope of my DSP course, so I am trying to do it using this simple approach. $\endgroup$
    – Merin
    May 10, 2017 at 14:27
  • $\begingroup$ did you realize that your filter is zero everywhere? $\endgroup$
    – firion
    May 10, 2017 at 14:32
  • $\begingroup$ Yes, as I mentioned in my post this is the problem. But I can't see why it would be zero everywhere; the while loop should introduce 1s for positive and negative harmonics of the 523 Hz frequency up to the Nyquist. $\endgroup$
    – Merin
    May 10, 2017 at 14:38

1 Answer 1


First of all, you don't need to shift the spectrum of the signal. Also, your filter is zero everywhere. Your frequency vector contains normalized frequencies, which is fine, but then you are using real frequencies when you build the filter. Either change the frequency vector f to real frequencies or normalize f0 too


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.