Checking if a matrix is symmetric in Numpy

54,327

Solution 1

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)

Solution 2

The following function also solves the problem:

def check_symmetric(a, tol=1e-8):
    return np.all(np.abs(a-a.T) < tol)

Solution 3

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.

Solution 4

This is an old post but I wold 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.

Share:
54,327
plshalp
Author by

plshalp

Updated on July 09, 2022

Comments

  • plshalp
    plshalp almost 2 years

    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!

  • jeremy_rutman
    jeremy_rutman over 6 years
    alternatively , check a-a.T<(tol*a.shape**2)
  • Giorgos Sfikas
    Giorgos Sfikas over 4 years
    This answer actually works also when the matrix elements are of a custom-type, in contrast to the 'allclose' of the accepted answer. This is the case for example with quaternionic matrices (cf. github.com/moble/quaternion)