Conjugate transpose operator “.H” in numpy

后端 未结 2 988
死守一世寂寞
死守一世寂寞 2020-12-14 09:04

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 conj

相关标签:
2条回答
  • 2020-12-14 09:30

    In general, the difficulty in this problem is that Numpy is a C-extension, which cannot be monkey patched...or can it? The forbiddenfruit module allows one to do this, although it feels a little like playing with knives.

    So here is what I've done:

    1. Install the very simple forbiddenfruit package

    2. Determine the user customization directory:

      import site
      print site.getusersitepackages()
      
    3. In that directory, edit usercustomize.py to include the following:

      from forbiddenfruit import curse
      from numpy import ndarray
      from numpy.linalg import inv
      curse(ndarray,'H',property(fget=lambda A: A.conj().T))
      curse(ndarray,'I',property(fget=lambda A: inv(A)))
      
    4. Test it:

      python -c python -c "import numpy as np; A = np.array([[1,1j]]);  print A; print A.H"
      

      Results in:

      [[ 1.+0.j  0.+1.j]]
      [[ 1.-0.j]
       [ 0.-1.j]]
      
    0 讨论(0)
  • 2020-12-14 09:35

    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.

    0 讨论(0)
提交回复
热议问题