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

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

Interpolation Scipy in Python with meshgrid

问题

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

这是我在MATLAB中的代码:

  1. x = linspace(-10,10,10);
  2. y = linspace(-5,5,10);
  3. DATA = rand(10,10);
  4. [XX,YY] = ndgrid(x,y);
  5. XX2 = XX;
  6. YY2 = YY;
  7. DATA2 = interpn(XX,YY,DATA,XX2,YY2);

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

  1. import numpy as np
  2. import scipy.interpolate
  3. x = np.linspace(-10,10,10)
  4. y = np.linspace(-5,5,10)
  5. DATA = np.random.rand(10,10)
  6. [XX,YY] = np.meshgrid(x,y,indexing='ij')
  7. XX2 = XX
  8. YY2 = YY
  9. 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 :

  1. x = linspace(-10,10,10);
  2. y = linspace(-5,5,10);
  3. DATA = rand(10,10);
  4. [XX,YY] = ndgrid(x,y);
  5. XX2 = XX;
  6. YY2 = YY;
  7. 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.

  1. import numpy as np
  2. import scipy.interpolate
  3. x = np.linspace(-10,10,10)
  4. y = np.linspace(-5,5,10)
  5. DATA = np.random.rand(10,10)
  6. [XX,YY] = np.meshgrid(x,y,indexing='ij')
  7. XX2 = XX
  8. YY2 = YY
  9. DATA2 = scipy.interpolate.interpn(XX,YY,DATA,XX2,YY2) # NOT WORKING

Any ideas on how to solve this issue ?

答案1

得分: 0

我找到了解决方案。以下是使用Python和Scipy编写的代码:

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

gridToInterpolate仅是一个包含新网格所有点的向量。因此,最后只需重新整形你的数据即可。

英文:

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

  1. import numpy as np
  2. import scipy.interpolate
  3. x = np.linspace(-10,10,10)
  4. y = np.linspace(-5,5,10)
  5. DATA = np.random.rand(10,10)
  6. [XX,YY] = np.meshgrid(x,y,indexing='ij')
  7. XX2 = XX
  8. YY2 = YY
  9. gridInitial = (x,y)
  10. gridToInterpolate = np.stack((XX2.ravel(),YY2.ravel()),axis=1)
  11. DATA2 = scipy.interpolate.interpn(gridInitial,DATA,gridToInterpolate,method='linear',bounds_error=False,fill_value=0)
  12. 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:

确定