我需要測試矩陣是否對稱。如果它是對稱的,函數需要返回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