Python 错误:只有整数、切片 (\`:\`)、省略号 (\`...\`)、numpy.newaxis (\`None\`) 和整数或布尔数组是有效索引

新手上路,请多包涵

我知道还有其他问题具有相同的错误消息,但是我已经看过这些并且不明白它如何适用于我目前的情况。所以我正在创建一个矩阵 u=np.zeros(shape=(nt,nx)) 然后我还有两个数组 time=nt*[0]middles=nx*[0]

这是我试图实现的关于绘制扩散方程的完整代码:

 import numpy as np
import matplotlib.pyplot as plt
import math
D=1 #diffusion constant set equal to 1
C=1 #creation rate of neutrons, set equal to 1
L=math.pi
nx=101 #number of steps in x
nt=10002 #number of timesteps
dx=L/(nx-1) #step in x
dt=0.0001 # time step
Z=(D*dt)/(dx*dx) #constant for diffusion term
Z1=C*dt #constant for u term

x1=np.arange(-math.pi/2+0.03079992797, 0, 0.03079992797)
y=np.arange(0.06159985595,math.pi/2, 0.03079992797)
z = np.hstack((x1, y))

u=np.zeros(shape=(nt,nx))
time=nt*[0]
middles=nx*[0]
u[50,0]=1/dx #setting our delta function
for j in range(0,nt-1):
 for i in range(2,nx-1):
     u[j+1,i]=Z*(u[j,i+1]-2*u[j,i]+u[j,i-1])+Z1*u[j,i]+u[j,i]
 u[j,1]=0
 u[j,nx-1]=0
 time[j]=dt*j
 middles[j]=u[j,((nx-1)/2)]
 if i==50 or i==100 or i==250 or i==500 or i==1000 or i==10000:

    plt.plot(time,middles)

 plt.title('Numerical Solution of the Diffusion Equation')
 plt.xlabel('time')
 plt.ylabel('middles')
 plt.show()

however I keep getting this error message seen in the title only integers, slices ( : ), ellipsis (), numpy.newaxis ( None ) and integer or boolean arrays are valid indices The error message is in regards到 middles[j]=u[j,((nx-1)/2)] 行我正在尝试从 Matlabe 转换这段代码,如果这能解释一些事情的话

原文由 LOC12345 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 554
2 个回答

当您不小心创建了一个 float 时,您经常会遇到此错误,其中包含您对索引值的计算之一。

在这种情况下:

 middles[j] = u[j, ((nx-1)/2)]

…将创建一个 float(nx-1) 是奇数时。所以你可以尝试:

 middles[j] = u[j, int(np.round(((nx-1)/2), 0))]

(我在这里使用 np.round ,这可能有点矫枉过正,但如果你开始除以 2 以外的数字,那么这种方法更有意义,因为它会向上或向下舍入 int() 总是会打倒它。)

Python 与 Matlab

需要注意两点:

  1. Matlab 默认为矩阵乘法,而 NumPy 默认为逐元素乘法——但这在这里不是问题。
  2. Matlab 使用 1 索引,而 Python(以及 NumPy)使用 0 索引。从 R 或 Matlab 移植的任何代码都需要将索引向下移动 1。

原文由 ajrwhite 发布,翻译遵循 CC BY-SA 4.0 许可协议

没关系…我看到了:您正在使用 float 作为最后一行代码中的索引:

 u[j,((nx-1)/2)]

将第二个索引转换为 int

 u[j, int((nx-1)/2)]

原文由 Prune 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题