Search code examples
pythonmatlabsmoothingspline

Do we have something like MATLAB fnval function in Python?


Using MATLAB csaps function I created a cubic polynomial and using MATLAB fnval function I did function evaluations. I am writing the same code in Python. I found the csaps function from the csaps library that gives me the same result, however, I cannot find anything in Python that does MATLAB's fnval job. Any ideas?


Solution

  • Here is some python code using numpy and scipy that simulates the fneval example taken from the MATLAB documentation here. Basically, the scipy CubicSpline class can be called with the values to be evaluated at (see also the scipy CubicSpline documentation).

    import numpy as np
    from scipy.interpolate import CubicSpline
    
    x = np.array([0.074, 0.31, 0.38, 0.53, 0.57, 0.58, 0.59, 0.61, 0.65, 0.71, 0.81, 0.97])
    y = np.array([0.91, 0.96, 0.77, 0.5, 0.5, 0.51, 0.51, 0.53, 0.57, 0.62, 0.61, 0.31])
    # note: the original MATLAB example had the 0.61 value duplicated, which caused an error in the scipy interface and therefore removed here
    
    cs = CubicSpline(x, y)
    cs(0.5)
    # array(0.5294082)
    
    cs(np.arange(0, 1.01, 0.1))
    # array([0.36518816, 1.02204653, 1.15788575, 0.98591757, 0.71915931, 0.5294082 , 0.5170693 , 0.61339552, 0.61721945, 0.48367111, 0.21564924])