Search code examples
pythonnumpymatlabscipyinterpolation

Interpolation Scipy in Python with meshgrid


I would like to do the same interpolation as MATLAB in Python with scipy. Here is an example of my code.

This is what I have in MATLAB :

x = linspace(-10,10,10);
y = linspace(-5,5,10);
DATA = rand(10,10);

[XX,YY] = ndgrid(x,y);

XX2 = XX;
YY2 = YY;

DATA2 = interpn(XX,YY,DATA,XX2,YY2);

I try to to it in Python but seems to be difficult to do it with matrix in meshgrid format.

import numpy as np
import scipy.interpolate 

x = np.linspace(-10,10,10)
y = np.linspace(-5,5,10)
DATA = np.random.rand(10,10)

[XX,YY] = np.meshgrid(x,y,indexing='ij')

XX2 = XX
YY2 = YY

DATA2 = scipy.interpolate.interpn(XX,YY,DATA,XX2,YY2) # NOT WORKING

Any ideas on how to solve this issue ?


Solution

  • I found the solution. Here the code in Python with Scipy :

    import numpy as np
    import scipy.interpolate 
    
    x = np.linspace(-10,10,10)
    y = np.linspace(-5,5,10)
    DATA = np.random.rand(10,10)
    
    [XX,YY] = np.meshgrid(x,y,indexing='ij')
    
    XX2 = XX
    YY2 = YY
    
    gridInitial = (x,y)
    gridToInterpolate = np.stack((XX2.ravel(),YY2.ravel()),axis=1)
    
    DATA2 = scipy.interpolate.interpn(gridInitial,DATA,gridToInterpolate,method='linear',bounds_error=False,fill_value=0)
    DATA2 = DATA2.reshape(XX2.shape)
    

    gridToInterpolate is just a vector with all the points of the new grid. So you just have to reshape your data at the end.