Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a matrix is symmetric in Numpy

I'm trying to make a function with the arguments (a,tol=1e-8) that returns a boolean value that tells the user whether or not the matrix is symmetric (symmetric matrix is equal to its transpose). So far I have:

def check_symmetric(a, tol=1e-8):
if np.transpose(a, axes=axes) == np.transpose(a, axes=axes):
    return True
def sqr(s):
    rows = len(s)
    for row in sq:
        if len(row) != rows:
            return False
    return True
if a != sqr(s):
    raise ValueError

although I keep getting an axes isn't defined message so I'm pretty sure that doesn't work at all...... the tests I'd like to pass are:

e = np.eye(4)
f = np.diag([1], k=3)
g = e[1:, :]

print(check_symmetric(e))
print(not check_symmetric(e + f))
print(check_symmetric(e + f * 1e-9))
print(not check_symmetric(e + f * 1e-9, 1e-10))
try:
    check_symmetric(g)
    print(False)
except ValueError:
    print(True)

Any help is appreciated, thanks!

like image 983
plshalp Avatar asked Mar 20 '17 15:03

plshalp


People also ask

How do you check a matrix is symmetric or not in Python?

A Simple solution is to do following. 1) Create transpose of given matrix. 2) Check if transpose and given matrices are same or not.

How do you check if a matrix is symmetrical?

How to check Whether a Matrix is Symmetric or Not? Step 1- Find the transpose of the matrix. Step 2- Check if the transpose of the matrix is equal to the original matrix. Step 3- If the transpose matrix and the original matrix are equal, then the matrix is symmetric.


4 Answers

You can simply compare it to its transpose using allclose

def check_symmetric(a, rtol=1e-05, atol=1e-08):
    return numpy.allclose(a, a.T, rtol=rtol, atol=atol)
like image 154
Nils Werner Avatar answered Oct 09 '22 00:10

Nils Werner


The following function also solves the problem:

def check_symmetric(a, tol=1e-8):
    return np.all(np.abs(a-a.T) < tol)
like image 42
Andrés Marulanda Avatar answered Oct 08 '22 22:10

Andrés Marulanda


If you're not worried about the tot threshold

(a==a.T).all()

is the simplest solution. This works for N-dimensional (N>2) arrays as well.

like image 4
Achintha Ihalage Avatar answered Oct 08 '22 23:10

Achintha Ihalage


This is an old post but I would recommend another method. Especially for sparse matrices, this can be hundreds of times faster.

def is_symmetric(A, tol=1e-8):
    return scipy.sparse.linalg.norm(A-A.T, scipy.Inf) < tol;

Or similar but you get the idea. Using a norm is a much more optimized calculation.

like image 3
William Dawn Avatar answered Oct 09 '22 00:10

William Dawn