2015-11-01 105 views
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矩阵的一个特定单元格的正确方法是什么?

回答

1

最好在numpy中使用[i,j]风格索引。当使用np.array时,通常您可以通过[i][j]来获得,但不能与np.matrix。记住一个np.matrix总是2d。

在shell中构造一个简单的二维数组,并尝试不同的索引方法。现在尝试使用np.matrix数组。注意形状。在LHS使用时

与两个

In [9]: A[1,2] 
Out[9]: 5 
In [10]: M[1,2] 
Out[10]: 5 

A[i][j]=...工作

In [2]: A = np.arange(6).reshape(2,3) 
In [3]: A[1] # short for A[1,:] 
Out[3]: array([3, 4, 5]) # shape (3,) 
In [4]: A[1][2] # short for A[1,:][2] 
Out[4]: 5 
In [5]: M=np.matrix(A) 
In [6]: M[1] 
Out[6]: matrix([[3, 4, 5]]) # shape (1,3), 2d 
In [7]: M[1][2] 
... 
IndexError: index 2 is out of bounds for axis 0 with size 1 

正确的索引也容易出现故障。它只适用于第一部分A[i]返回view。如果产生copy,则失败。