我需要测试矩阵是否对称。如果它是对称的,函数需要返回0,否则返回1.对我来说,这段代码是有意义的,但我不明白弹出的错误。循环矩阵元素时出现索引错误
IndexError Traceback (most recent call last)
<ipython-input-3-903eff7c516e> in <module>()
20 # here's the matrix I'm testing :
21
---> 22 isSymmetric(np.matrix(([(1,0,0),(5,6,5),(8,0,1)])))
<ipython-input-3-903eff7c516e> in isSymmetric(A)
10 i=0
11 for i in np.matrix(A) :
---> 12 m = A[i]
13 n = A[:,i]
14 if m==n :
/usr/local/lib/python2.7/site-packages/numpy/matrixlib/defmatrix.pyc in __getitem__(self, index)
316
317 try:
--> 318 out = N.ndarray.__getitem__(self, index)
319 finally:
320 self._getitem = False
IndexError: index 5 is out of bounds for axis 0 with size 3
这里是我的代码:
import numpy as np
def isSymmetric (A) :
"""
A : the matrix that will be checked if it's symmetric
"""
#check if rows are same as columns
i=0
for i in np.matrix(A) :
m = A[i]
n = A[:,i]
if m==n :
print(1)
else:
print(0)
# here's the matrix I'm testing :
isSymmetric(np.matrix(([(1,0,0),(5,6,5),(8,0,1)])))
http://stackoverflow.com/questions/5320324/testing-if-a-numpy-array-is-symmetric – ewcz
您的代码被错误地缩进,修复。 – Morgoth
请将您的错误消息复制并粘贴到问题中,而不是使用图像。它更具可读性。 – Cecilia