Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at [j][i] when [i][j] is written to?
import numpy
a = numpy.symmetric((3, 3))
a[0][1] = 1
a[1][0] == a[0][1]
# True
print(a)
# [[0 1 0], [1 0 0], [0 0 0]]
assert numpy.all(a == a.T) # for any symmetric matrix
An automatic Hermitian would also be nice, although I won’t need that at the time of writing.
If you can afford to symmetrize the matrix just before doing calculations, the following should be reasonably fast:
This works under reasonable assumptions (such as not doing both
a[0, 1] = 42and the contradictorya[1, 0] = 123before runningsymmetrize).If you really need a transparent symmetrization, you might consider subclassing numpy.ndarray and simply redefining
__setitem__:(or the equivalent with matrices instead of arrays, depending on your needs). This approach even handles more complicated assignments, like
a[:, 1] = -1, which correctly setsa[1, :]elements.Note that Python 3 removed the possibility of writing
def …(…, (i, j),…), so the code has to be slightly adapted before running with Python 3:def __setitem__(self, indexes, value): (i, j) = indexes…