Conjugate transpose operator ".H" in numpy

benpro picture benpro · Nov 14, 2014 · Viewed 37.9k times · Source

It is very convenient in numpy to use the .T attribute to get a transposed version of an ndarray. However, there is no similar way to get the conjugate transpose. Numpy's matrix class has the .H operator, but not ndarray. Because I like readable code, and because I'm too lazy to always write .conj().T, I would like the .H property to always be available to me. How can I add this feature? Is it possible to add it so that it is brainlessly available every time numpy is imported?

(A similar question could by asked about the .I inverse operator.)

Answer

Saullo G. P. Castro picture Saullo G. P. Castro · Nov 14, 2014

You can subclass the ndarray object like:

from numpy import ndarray

class myarray(ndarray):    
    @property
    def H(self):
        return self.conj().T

such that:

a = np.random.random((3, 3)).view(myarray)
a.H

will give you the desired behavior.