共轭转运营商QUOT; .H"在numpy的 [英] Conjugate transpose operator ".H" in numpy

查看:196
本文介绍了共轭转运营商QUOT; .H"在numpy的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是numpy的非常方便使用 .T 属性获得的 ndarray 转置版本。然而,不存在类似的方式来获得的共轭转置。 numpy的的矩阵类有 .H 运营商,而不是ndarray。因为我喜欢读code,因为我懒得总是写 .conj():T ,我想。 ^ h 属性始终可以提供给我。我怎样才能增加这个功能?是否有可能增加它,以便它可以brainlessly每次numpy的是进口的?

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?

(类似的问题可以通过询问有关 .I 逆算子)。

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

推荐答案

在一般情况下,这个问题的困难在于numpy的是C扩展,它不能被猴子修补...或者可以吗?该 forbiddenfruit 模块允许一个做到这一点,虽然感觉有点像用刀子玩。

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. 安装非常简单 forbiddenfruit

确定用户的自定义目录:

Determine the user customization directory:

import site
print site.getusersitepackages()


  • 在该目录中,修改 usercustomize.py 来包括以下内容:

    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)))
    


  • 测试一下:

  • Test it:

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

    结果:

    [[ 1.+0.j  0.+1.j]]
    [[ 1.-0.j]
     [ 0.-1.j]]
    


  • 这篇关于共轭转运营商QUOT; .H"在numpy的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆