Scipy中的插值在Python中使用meshgrid。

huangapple go评论63阅读模式
英文:

Interpolation Scipy in Python with meshgrid

问题

以下是您的代码的中文翻译部分:

这是我在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);

我尝试在Python中实现相同的插值,但似乎很难使用网格格式的矩阵来做到这一点。

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) # 无法正常工作

有关如何解决这个问题的想法吗?

英文:

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 ?

答案1

得分: 0

我找到了解决方案。以下是使用Python和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仅是一个包含新网格所有点的向量。因此,最后只需重新整形你的数据即可。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月16日 16:13:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75469436.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定