# Trying to implement MATLAB $\tt pwelch$ in Python

I'm implementing an existing MATLAB script in Python and noticing some differences in the behaviour of MATLAB's pwelch function compared to scipy.signal.welch.

From the docs, scipy.signal.welch uses a default window size of 256, whereas MATLAB's pwelch doc says:

By default, x is divided into the longest possible segments to obtain as close to but not exceed 8 segments with 50% overlap".

Both use Hamming windows and overlap by 50%, so I assume the differences I'm seeing are due to window sizes.

However, if I set the same window size for both, I still see different frequency resolution in the results. e.g. for data series of length 6144, sampled every 0.292969 seconds, and set window size as follows:

n = 1000
freqs, power = signal.welch(timeseries, fs=1.0/0.292969, scaling='density', nperseg=n)
print(freqs[2]) # output 0.0034

n = 1500
freqs, power = signal.welch(timeseries, fs=1.0/0.292969, scaling='density', nperseg=n)
print(freqs[2]) # output 0.00227555370371


for MATLAB:

n = 1000;
dt = 0.292969;
[psd,freq] = pwelch(timeseries,n,[],[],1/dt);
freq(2) % output 0.0033

n = 1500;
[psd,freq] = pwelch(timeseries,n,[],[],1/dt);
freq(2) % output 0.0017


For higher window size the difference in output resolution is quite stark, and results in quite different amplitudes for peaks in the spectrum. Am I missing some other parameter which needs adjusting?

• It looks like nfft might need adjusting... MATLAB uses the higher of 256 or the next power of 2 greater than the window size – samb8s Dec 5 '17 at 12:35

This was an oversight on my part - I needed to adjust nfft to be the next power of 2 above window size.

• If that solved your problem you can accept your answer by clicking on the check mark symbol. – Matt L. Dec 5 '17 at 13:37
• @MattL. I would but I can't before two days have expired ;) thanks! – samb8s Dec 5 '17 at 13:39
• OK, didn't know/remember that. Anyway, try to come back and accept, so everybody knows this case is closed. – Matt L. Dec 5 '17 at 13:40