Checking if a matrix is symmetric in Numpy

Question:

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!

Asked By: plshalp

||

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)
Answered By: 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)
Answered By: Andrés Marulanda

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.

Answered By: William Dawn

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.

Answered By: Achintha Ihalage

If using SciPy is acceptable, you can use scipy.linalg.issymmetric() (as of v1.8.0), which also includes some input validation.

  • See implementation here.
  • A note regarding performance (from the docs; emphasis mine):

    When atol and/or rtol are set, then the comparison is performed by numpy.allclose and the tolerance values are passed to it. Otherwise, an exact comparison against zero is performed by internal functions. Hence performance can improve or degrade depending on the size and dtype of the array.

Answered By: Dev-iL
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.