Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing if a numpy array is symmetric?

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()
like image 589
Bolster Avatar asked Mar 16 '11 02:03

Bolster


2 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()
like image 160
Sven Marnach Avatar answered Sep 17 '22 13:09

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
like image 34
Waylon Flinn Avatar answered Sep 20 '22 13:09

Waylon Flinn