testing if a numpy array is symmetric?

Question:

Is there a better pythonic way of checking if a ndarray is diagonally symmetric in a particular dimension? i.e for all of x

(arr[:,:,x].T==arr[:,:,x]).all()

I’m sure I’m missing an (duh) answer but its 2:15 here… 🙂

EDIT: to clarify, I’m looking for a more ‘elegant’ way to do :

for x in range(xmax):
    assert (arr[:,:,x].T==arr[:,:,x]).all()
Asked By: Bolster

||

Answers:

If I understand you correctly, you want to do the check

all((arr[:,:,x].T==arr[:,:,x]).all() for x in range(arr.shape[2]))

without the Python loop. Here is how to do it:

(arr.transpose(1, 0, 2) == arr).all()
Answered By: Sven Marnach

If your array contains floats (especially if they’re the result of a computation), use allclose

np.allclose(arr.transpose(1, 0, 2), arr)

If some of your values might be NaN, set those to a marker value before the test.

arr[np.isnan(arr)] = 0
Answered By: Waylon Flinn

I know you asked about NumPy. But SciPy, NumPy sister package, has a build-in function called issymmetric to check if a 2D NumPy array is symmetric. You can use it too.

>>> from scipy.linalg import issymmetric
>>> import numpy as np
>>> a = np.arange(27).reshape(3,3,3)
>>> a
array([[[ 0,  1,  2],
        [ 3,  4,  5],
        [ 6,  7,  8]],

       [[ 9, 10, 11],
        [12, 13, 14],
        [15, 16, 17]],

       [[18, 19, 20],
        [21, 22, 23],
        [24, 25, 26]]])
>>> for i in range(a.shape[2]):
    issymmetric(a[:,:,i])

False
False
False
>>> 
Answered By: Sun Bear
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.