Search code examples
pythonmatlabmatplotlibspectrogram

Difference between Matlab spectrogram and matplotlib specgram?


I am trying to incorporate a preexisting spectrogram from Matlab into my python code, using Matplotlib. However, when I enter the window value, there is an issue: in Matlab, the value is a scalar, but Matplotlib requires a vector. Why is this so?


Solution

  • The arguments are just organized differently.

    In matplotlib, the window size is specified using the NFFT argument. The window argument, on the other hand, is only for specifying the window itself, rather than the size. So, like MATLAB, the window argument accepts a vector. However, unlike MATLAB, it also accepts a function that should take an arbitrary-length vector and return another vector of the same size. This allows you to use functions for windows instead of just vectors.

    So to put it in MATLAB terms, the MATLAB window argument is split into the window and NFFT arguments in matplotlib, while the MATLAB NFFT argument is equivalent to the matplotlib pad_to argument.

    As for the reason, specifying the window and window size independently allows you to use a function as the argument for window (which, in fact, is the default). This is impossible with the MATLAB arguments.

    In Python, functions are first-class objects, which isn't the case in MATLAB. So it tends to be much more common to use functions as arguments to other functions in Python compared to MATLAB. Python also allows you to specify arguments by name, something MATLAB really doesn't. So in MATLAB it is much more common to have arguments that do different things depending on the inputs, while similar functions in Python tend to split those into multiple independent arguments.