0
$\begingroup$

I am trying to implement the following line of MATLAB code:

[pxx, f] = pwelch(data,[],[],4096,F_S)

in Python. Knowing that MATLAB using a Hamming window type that uses 8 segment with 50% overlap, my attempt was

freq, PSD =
signal.welch(data, F_S, window='hamming', nperseg=None, noverlap=None, nfft=4096)

However, I receive different results that on the eye look similar but aren't. MATLAB predicts a power peak of 0.13 at the 2nd entry of the pxx vector, while Python predicts a power peak of 0.33 at the 32nd entry of the PSD vector. Did I do something wrong?

The image comparison

$\endgroup$
3
  • 1
    $\begingroup$ Could this be the answer? $\endgroup$ Commented Aug 17, 2022 at 20:23
  • $\begingroup$ I have added the detrend = False tag, and I used Jdip's suggestion of defining the window length manually, and now it works fine! TY! $\endgroup$
    – JoJo
    Commented Aug 18, 2022 at 8:27
  • $\begingroup$ @JoJo, please mark the answer as "accepted" so that it doesn't stay in the "unanswered" category :) $\endgroup$
    – Jdip
    Commented Aug 18, 2022 at 16:33

1 Answer 1

0
$\begingroup$

Your parameters for the sciPy implementation look wrong. Matlab does divide the input data into 8 segments so you need to do the same with Python. SciPy by default sets each segment to 256 samples (see sciPy.welch)

You need something like:

N = np.floor(len(data)/8) #sets the frame length the same as Matlab's default
freq, PSD = 
   signal.welch(data, F_S, window='hamming', nperseg=N, noverlap=None, nfft=4096)

Better yet, define your own window_length (i.e nperseg) and hop_length (i.e noverlap), and re-do your comparison without relying on the default parameters of either functions.

I'd also suggest looking up the documentation for each, the scaling might be different depending on the implementation.

EDIT Seems the default scaling is the same for both implementation ;)

$\endgroup$

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.