我在某个地方找到了一个如何使用Ogrid函数的例子,并且一直在使用不同的值。现在要使用它,我需要根据数组参数计算虚部/步长。因此,以下问题:
为什么这样做:
工作代码行
xi, yi = np.ogrid[0:1:10j, 0:1:10j]但这并不是:
不工作的代码行
rows = str(10) + "j"
columns = str(10) + "j"
xi, yi = np.ogrid[0:1:rows, 0:1:columns]在下列方案中:
全样本
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import griddata as gd
# define X Y V testsample
x = [0, 1, 1, 0]
y = [0, 0, 1, 1]
v = [1, 2, 3, 4]
# create grid
# Not working example
rows = str(10) + "j"
columns = str(10) + "j"
xi, yi = np.ogrid[0:1:rows, 0:1:columns]
# Working example
##xi, yi = np.ogrid[0:1:10j, 0:1:10j]
X1 = xi.reshape(xi.shape[0])
Y1 = yi.reshape(yi.shape[1])
ar_len = len(X1)*len(Y1)
X = np.arange(ar_len, dtype=float)
Y = np.arange(ar_len, dtype=float)
l = 0
for i in range(0, len(X1)):
for j in range(0, len(Y1)):
X[l] = X1[i]
Y[l] = Y1[j]
l+=1
#interpolate v on xy grid
V = gd((x,y), v, (X,Y), method='linear')
print(V)
#Plot original values
fig1 = plt.figure()
ax1=fig1.gca()
sc1=ax1.scatter(x, y, c=v, cmap=plt.hot())
plt.colorbar(sc1)
ax1.set_xlabel('X')
ax1.set_ylabel('Y')
#Plot interpolated values
fig2 = plt.figure()
ax2=fig2.gca()
sc2=ax2.scatter(X, Y, c=V, cmap=plt.hot())
plt.colorbar(sc2)
ax2.set_xlabel('X')
ax2.set_ylabel('Y')
#ax2.set_zlabel('Z')
plt.show()尝试:
我已经试过以下几点来弄清楚到底发生了什么。我创建了一个变量,将它更改为一个字符串,并向它添加了一个"j“。它等于" 10j“,但不等于10j。我认为这种差异导致了问题,但我不知道如何将字符串转换为虚数。我也尝试了np.imag(),但是这只会从复数的虚部返回数字,所以没有j。
a = str(10) + "j"
print(a)
print(a==10j) # Results in False
print(a=='10j') # Results in True发布于 2022-08-29 13:13:55
如果您想像在非工作示例中显示的那样编写代码,请执行以下操作:
# An update to the not working example
rows = 10 * 1j
columns = 10 * 1j
xi, yi = np.ogrid[0:1:rows, 0:1:columns]否则,如果确实希望将字符串更改为复数,请使用eval()方法,如下所示:
x = eval('10j')
print(type(x))产出:
<class 'complex'>https://stackoverflow.com/questions/73529239
复制相似问题