0
的一种特定细胞中我写了一个函数,看是否有矩阵是对称与否:阅读numpy的矩阵
def issymmetric(mat):
if(mat.shape[0]!=mat.shape[1]):
return 0
for i in range(mat.shape[0]):
for j in range(i):
if (mat[i][j]!=mat[j][i]):
return 0
return 1
它具有内置ndarrays例如运行良好numpy.ones:
import numpy as np
a=np.ones((5,5), int)
print issymmetric(a)
并与numpy的数组:
import numpy as np
a=np.array([[1, 2, 3], [2, 1 , 2], [3, 2, 1]])
print issymmetric(a)
但是,当涉及到numpy的矩阵:
import numpy as np
a=np.matrix([[1, 2, 3], [2, 1 , 2], [3, 2, 1]])
print issymmetric(a)
这gaves我这个错误:
File "issymetry.py", line 9, in issymmetric
if (mat[i][j]!=mat[j][i]):
File "/usr/lib/python2.7/dist-packages/numpy/matrixlib/defmatrix.py", line 316, in __getitem__
out = N.ndarray.__getitem__(self, index)
IndexError: index 1 is out of bounds for axis 0 with size 1
shell returned 1
这是因为没有[0] [1]
a[0]
是matrix([[1, 2, 3]])
。 a[0][0]
也是matrix([[1, 2, 3]])
,但没有a[0][1]
。
如何解决此问题,而不更改矩阵类型或功能?
一般来说,读取和更新numpy矩阵的一个特定单元格的正确方法是什么?