interp function in python like matlab
Question: Could someone explain how to use an interpolation function on an existing
array, in python as the one exists in matlab ?

example:

x =

    
    
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    

> > interp(x,2)

ans =

    
    
    1.0000
    1.4996
    2.0000
    2.4993
    3.0000
    3.4990
    4.0000
    4.4987
    5.0000
    5.4984
    6.0000
    6.4982
    7.0000
    7.4979
    8.0000
    8.4976
    9.0000
    9.4973
    10.0000
    10.4970
    

I'd like a function in python which does exactly this, i.e. adds more points
keeping the original intact.


Answer: A couple of issues need to be raised:

  * Are you just looking at linear interpolation (ie "connect the dots" with straight line segments)? That's simple but kind of nasty. You can get nicer results with higher-order curves (ie bicubic splines) but for that you need to provide more information to nail down a unique solution (ie endpoint first-derivatives).

  * Do you want to smooth the curve at the same time, or do you expect it to go exactly through your given points?

  * Are your input points uniformly spaced (ie along the x axis)?

  * Your data shows not just interpolation but also extrapolation (ie your last point is off the end of your data) - is this actually what you want?

[Matlab documentation](http://www.mathworks.com/help/signal/ref/interp.html)
says "`interp` inserts 0s into the original signal and then applies a lowpass
interpolating filter to the expanded sequence".

* * *

**Edit:** I think the closest equivalent is `scipy.interpolate.interp1d` \-
see
<http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html#scipy.interpolate.interp1d>

You could make a wrapper like so:

    
    
    import numpy as np
    from scipy.interpolate import interp1d
    
    def interp(ys, mul):
        # linear extrapolation for last (mul - 1) points
        ys = list(ys)
        ys.append(2*ys[-1] - ys[-2])
        # make interpolation function
        xs = np.arange(len(ys))
        fn = interp1d(xs, ys, kind="cubic")
        # call it on desired data points
        new_xs = np.arange(len(ys) - 1, step=1./mul)
        return fn(new_xs)
    

which then works like

    
    
    >>> interp([1,2,3,4,5,6,7,8,9,10], 2)
    array([  1. ,   1.5,   2. ,   2.5,   3. ,   3.5,   4. ,   4.5,   5. ,
             5.5,   6. ,   6.5,   7. ,   7.5,   8. ,   8.5,   9. ,   9.5,
            10. ,  10.5])
    

