带有复数的Python interp2D

时间:2019-08-21 16:41:42

标签: python scipy

我需要以与matlab的interp2函数相同的方式为python设置interp2

我尝试使用与matlabs inter2相同的scipy interp2d函数

Matlab:interp2(x,y,yy,new_xx,new_yy)

x = 37,39,41

y = 2.5,2.75,3

yy = [[0.6 + 1.6j,0.6 + 1.6j,0.6 + 1.6j],[0.7 + 1.6j,0.7 + 1.6j,0.7 + 1.6j],[0.8 + 1.5j,0.8 + 1.5j ,0.8 + 1.5j]]-3x3数组

new_xx = np.linspace(37,41,401)

new_yy = np.linspace(0,3,401)

'''

stack

'''

当我运行func = scipy.interpolate.interp2d(x,y,yy)时收到错误 “ ComplexWarning:将复杂值转换为实数会丢弃虚部”

我如何遍历复数?

2 个答案:

答案 0 :(得分:1)

我在将 MATLAB 代码转换为 Python 时也遇到了这个问题。这并不完全直观,但对我有用的解决方案实际上是使用 scipy 的 griddata 函数而不是 interp2d 函数,如下所述:How can I perform two-dimensional interpolation using scipy?

以下是供参考的文档:scipy.interpolate.griddata

OP 可能看起来像这样:

import numpy as np
from scipy import interpolate

points = np.array([x, y]).T
values = yy.ravel() 
xi = np.array([new_xx, new_yy]).T

arr= interpolate.griddata(points, values, xi)

但是,我不得不做一些不同的事情,因为我的 x 和 y 是二维数组。

import numpy as np
from scipy import interpolate

# Creating x and y of size=(m,m) from someArray of size(m,) 
# (x and y here are my version of OP's new_xx and new_yy)
x, y = np.meshgrid(someArray, someArray)

# These are my version of OP's x and y
xScaled = x * scaleFactor
yScaled = y * scaleFactor

points = np.array([xScaled.ravel(), yScaled.ravel()]).T
values = myMatrix.ravel()  # myMatrix has size=(m,m) and includes complex numbers, similar to OP's yy variable
xi = np.array([x.ravel(), y.ravel()]).T

# 2D interpolation
myInterp2d = interpolate.griddata(points, values, xi, method='linear')

# Returning my data to original shape
myNewMatrix = myInterp2d.reshape(myMatrix.shape)

但是请注意您的输出,因为 griddata 函数似乎没有提供任何外推选项,它只是填充了 nans。

答案 1 :(得分:0)

一种解决方案是执行两个不同的插值:“如果V包含复数,则interp2分别对实部和虚部进行插值。”来自interp2 matlab documentation

使用scipy.interpolate.interp2d

import numpy as np
from scipy.interpolate import interp2d

x = np.array([37, 39, 41])

y = np.array([2.5, 2.75, 3])

z = np.array([[0.6 + 1.6j, 0.6 + 1.6j, 0.6 + 1.6j],
     [0.7 + 1.6j, 0.7 + 1.6j, 0.7 + 1.6j],
     [0.8 + 1.5j, 0.8 + 1.5j, 0.8 + 1.5j]])

# 2D grid interpolation
interpolator_real = interp2d(x, y, np.real(z))
interpolator_imag = interp2d(x, y, np.imag(z))

def interpolator_complex(x, y):
    return interpolator_real(x, y) + 1j*interpolator_imag(x, y)

# test
new_x = np.linspace(37, 41, 6)
new_y = np.linspace(2.5, 3, 8)

interpolator_complex(new_x, new_y)