# Matlab spectrogram

I have to do 'inverse engineering' with piano sound and find sequence of frequencies in it. I have to use spectrogram() and adjust parameters. I set window length as 512 to see more frequencies and overlap on 256 (as default), is this correct? Also in my task there's: "FFT length (zero padding)" so I used nextpow2. Can somebody take a look at this? Here's what I've already done:

[y,fs] = audioread('piano.wav');
%sound(y,fs)
f = 0:1:0.5*fs;
Nx = length(y);
NFFT=2^nextpow2(Nx);
n= 0:Nx-1;
dt = 1/fs;
t = dt*n;
figure(1)
plot(t,y)
figure(2)
spectrogram(y,512,256,NFFT,fs); %


I set window length as 512 to see more frequencies and overlap on 256 (as default), is this correct?

No, the number of frequencies (i.e. frequency bins) will depend on the NFFT argument of your spectrogram function and will be equal to $$NFFT / 2$$. Also note that the frequency bins do not represent a single frequency component but rather have a fixed bandwidth given by $$f_s/NFFT$$ ($$f_s$$ is the sampling rate).

But, there's also one big problem with your code. NFFT, as used in your code, represents the number of samples in your entire audio file (rounded to the next power of two integer), which means that you're going to average all the frequency components found at different time points. A spectrogram is really about segmenting your audio file into smaller time chunks and then performing an FFT on it. So just replace your spectrogram function with

 spectrogram(y,512,256, 512);//the last argument is the FFT length


The NFFT and window length arguments can be the same length. The longer the NFFT argument, the more frequency components you'll get at the expense of decreased time resolution (more samples are spread over a larger time segment, thus less time resolution)

• okay, thank you so much,but what about zero padding? does nfft=512 gives us zero padding? – Sylwia Jun 16 at 7:33
• @Sylwia, zero padding is only needed if the signal length is less than nfft, (e.g for nfft=512 and signal length = 480, 32 zeros will be added ). In a spectrogram, zero padding will usually be done for the last time frame only (and the spectrogram function will likely do this automatically) – dsp_user Jun 16 at 8:11
• okay, now I get it. thank you so much for your help! :) – Sylwia Jun 16 at 8:50