Search code examples
pythonmatlabscipysignals

What is the difference between the Matlab "smooth" function, and the Python "scipy.signal.savgol_filter"?


I am currently translating some code written in Matlab, and re-writing it in Python. I have a function below in Matlab:

yy = smooth(y, span, 'sgolay', degree)

This function is meant to smooth the signal y, using the Savitzky-Golay calculation. I found a Python function that applies this calculation to an input signal.

from scipy.signal import savgol_filter
yy = savgol_filter(y, span, degree)

Would both of these functions produce the same output yy for the same input y? If not, is there any Python equivalent of the Matlab smooth function?

Thank you in advance for the answers.


Solution

  • I would compare the impulse response function of both to answer your question. From the below test, I would say it is not a bad idea to think they does the same thing. As mentioned in the comments, boundary cases like samples without neighbors, odd/even samples, etc could be implemented differently.

    span=5;
    degree=2;
    y=zeros(100,1);
    y(length(y)/2)=1;
    figure,stem(y),hold on, stem(smooth(y, span, 'sgolay', degree))
    legend({'input','PSF'})
    
    

    enter image description here

    #%%
    import numpy as np
    from scipy.signal import savgol_filter
    import matplotlib.pyplot as plt
    
    span=5
    degree=2
    y=np.zeros(100);
    y[y.shape[0]//2]=1
    yy = savgol_filter(y, span, degree)
    
    
    plt.stem(y,linefmt='red',label='input')
    plt.stem(yy,linefmt='blue',label='PSF')
    plt.show()
    
    

    enter image description here