Reputation: 85
I need to test if a matrix is symmetric or not. If it is symmetric, the function needs to return 0, and if not, then it returns 1. To me, this code makes sense, but I don't understand the error that's popping up.
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
Here's my code:
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)])))
Upvotes: 1
Views: 208
Reputation: 3483
Testing if a matrix is symmetric would be done with something like np.all(A == A.T)
. A.T
gives the transposed matrix and ==
checks equlity elementwise, so checking if for all elements you get True
with np.all
after the ==
lets you eventually know if your matrix is symmetric.
However, if you are working with floating points it is useful to introduce some finite tolerance. ==
has tolerance zero which is not always good when working with floating points. Instead you can use np.allclose(A, A.T)
here.
These methods return either True
or False
. If you want to stick with 1
and 0
, you can return 1 * <return value of np.all or np.allclose>
.
Upvotes: 0
Reputation: 8131
To be honest there are a bunch of things wrong with your code. The reason you're getting the warning (and my version has an outright error) is this:
i=0
for i in np.matrix(A) :
This doesn't make any sense. for i in container
will loop by setting i
equal to all of the things inside the container in succession. In this case the container is np.matrix(A)
, so it's looping through every actual item in the array. Obviously these don't make sense when you then use them as an index. If you want to loop over the indexes, you need something like:
M = np.matrix(A)
for i in range(M.shape[0]):
This loops over all the possible values for the first index of the matrix.
By the way, a much neater way to do this is by using the concise definition of a symmetric matrix, i.e. transpose(M) = M. You can do this in Python as:
def is_symmetric(M):
return (M == M.transpose()).all()
Upvotes: 2