I'm fairly new to programming and thought I'd try writing a piecewise linear interpolation function. (perhaps which is done with numpy.interp or scipy.interpolate.interp1d)
Say I am given data as follows: x= [1, 2.5, 3.4, 5.8, 6] y=[2, 4, 5.8, 4.3, 4]
I want to design a piecewise interpolation function that will give the coefficents of all the Linear polynomial pieces between 1 and 2.5, 2.5 to 3.4 and so on using Python. of course matlab has the interp1 function which do this but im using python and i want to do exactly the same job as matlab but python only gives the valuse but not linear polynomials coefficient ! (in matlab we could get this with pp.coefs) . but how to get pp.coefs in python numpy.interp ?
You can use polyfit
from numpy
, which gives you the list of coefficient, from the highest degree (here there are two coefficient on your degree 1
polynom) for a given fitting. The below will thus give you the list of coefficient for each segment [1, 2.5]
, [2.5, 3.4]
, etc
import numpy as np
x = np.array(x)
y = np.array(y)
[np.polyfit(x[i:(i+2)], y[i:(i+2)],1) for i in range(len(x)-1)]
#[array([ 1.33333333, 0.66666667]), array([ 2., -1.]), array([-0.625, 7.925]), array([ -1.5, 13. ])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With