NumPy运行报index 4越界错误 等效Matlab代码正常如何解决
报错根源
NumPy数组采用0起始索引规则,Matlab数组采用1起始索引规则,直接照搬Matlab代码里的1基准节点编号索引NumPy数组,就会触发越界。
对应到你的代码逻辑:
node数组共4行,合法行索引范围为0-3con数组存储的节点编号范围为1-4,当取到节点编号4时,执行node[4, 1]相当于访问不存在的第5行,直接抛出index 4 is out of bounds for axis 0 with size 4报错。
修复方法
从con中读取节点编号后统一减1,转换为NumPy适配的0基准索引,再访问node数组即可,修正后代码如下:
import numpy as np NELEM = 5 con = np.array([[1,3], [1,2], [1,4], [2,3], [2,4]]) node = np.array([[1, 12, 0], [2, 8, 10], [3, 0, 10], [4, 24, 10]]) for a in range(NELEM): n1 = con[a, 0] - 1 n2 = con[a, 1] - 1 x1 = node[n1, 1] x2 = node[n2, 1] dx = x2 - x1
内容的提问来源于stack exchange,提问作者evh5366
相关产品推荐
相关产品推荐

