# Filtering an Audio File in MATLAB

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): However, my resulting waveform is entirely zero: 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))
filter(abs(f-f0)<25)=1;
filter(abs(f+f0)<25)=1;
f0 = f0+523;
end

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.

• Any reason not to use a standard filter design command, such as fir2?
– MBaz
May 10, 2017 at 13:55
• 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. May 10, 2017 at 14:27
• did you realize that your filter is zero everywhere? May 10, 2017 at 14:32
• 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. May 10, 2017 at 14:38

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