MATLAB interp2 function in Python

I need a Python equivalent to the interp2 MATLAB's function. I am trying to make this MATLAB example working in Python but I can't.

import numpy as np

from scipy.interpolate import interp2d
from scipy.interpolate import RectBivariateSpline

service = np.array(range(10, 31, 10))
years = np.array(range(1950, 1991, 10))

wage = np.array([[150.6970,199.5920,187.6250],
    [179.3230, 195.0720, 250.2870],
    [203.2120, 179.0920, 322.7670],
    [226.5050, 153.7060, 426.7300],
    [249.6330, 120.2810, 598.2430]])

ip = RectBivariateSpline(years, service, wage)

print(ip(15, 1975))

But I get this error (in RectBivariateSpline) which I can't solve:

    Traceback (most recent call last):
  File "/Users/andrea/Documents/workspace/PythonProjects/pyArmBot/src/foo.py", line 15, in <module>
    ip = RectBivariateSpline(years, service, wage)
  File "/Library/Python/2.7/site-packages/scipy-0.10.1-py2.7-macosx-10.7-intel.egg/scipy/interpolate/fitpack2.py", line 728, in __init__
    kx,ky,s)

Answers


I believe you need to be calling ip to return a value by using the following line instead of your print line.

print(ip.ev(15, 1975))

Update:

Pretty easy tweak. And was staring my in the face. You can set the value of kx and ky, which are the degrees of the bivariate spline See documentation here

Anyway, just adjust the line to be:

ip = RectBivariateSpline(years, service, wage, kx=2, ky=2)

You don't need to adjust kx if you don't want to. I doubt it will change the interpolation much if you leave kx as 3.


blueSurfer, I think the way you have set up your interpolation, the correct results will be obtained by ip(1975, 15) and not the opposite.


I have encountered the same issue, and figured out that scipy.ndimage.map_coordinates does the same as Vq = interp2(V,Xq,Yq). Please read the documentation of these commands to find out the solution for your case.

Try this for Matlab's Vq = interp2(V,Xq,Yq) :

Vq = scipy.ndimage.map_coordinates(V, [Xq.ravel(), Yq.ravel()], order=3, mode='nearest').reshape(V.shape)

Need Your Help

Saving large Python arrays to disk for re-use later --- hdf5? Some other method?

python database arrays save hdf5

I'm currently rewriting some python code to make it more efficient and I have a question about saving python arrays so that they can be re-used / manipulated later.