3
votes

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 ?

2

2 Answers

1
votes

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. ])]
1
votes

If you're doing linear interpolation you can just use the formula that the line from point (x0, y0) to (x1, y1) the line that interpolates them is given by y - y0 = ((y0 - y1)/(x0 - x1)) * (x - x0). You can take 2 element slices of your list using the slice syntax; for example to get [2.5, 3.4] you would use x[1:3].

Using the slice syntax you can then implement the linear interpolation formula to calculate the coefficients of the linear polynomial interpolations.