使用 numpy 语法对 self 进行共轭转置

A.T*_*res 4 python matlab numpy matrix scipy

我正在尝试将这段 MATLAB 代码翻译成 Python。

以下是代码:

Y=C*Up(:,1:p-1)'*Y;
Run Code Online (Sandbox Code Playgroud)

这是我迄今为止的翻译:

Y = C * Up[:, 1:p-1] * Y
Run Code Online (Sandbox Code Playgroud)

我在 MATLAb 代码中使用的 self 共轭转置语法遇到问题。我不确定我的第一个想法:

Y = C * Up[:, 1:p-1].getH() * Y
Run Code Online (Sandbox Code Playgroud)

是正确的。

有人有什么想法吗?

Dev*_*-iL 5

我对 numpy 不太有经验,但根据@hpaulj的评论,我可以建议以下内容:

如果您不想受到numpy.matrix对象的限制(请参阅此处的警告),您可以定义自己的函数来执行共轭转置。您需要做的就是转置数组,然后从结果中减去结果的虚部乘以 2。我不确定这的计算效率如何,但它绝对应该给出正确的结果。

我希望这样的事情能够发挥作用:

Y = C * ctranspose(Up[:, 0:p-1]) * Y

...

def ctranspose(arr: np.ndarray) -> np.ndarray:
    # Explanation of the math involved:
    # x      == Real(X) + j*Imag(X)
    # conj_x == Real(X) - j*Imag(X)
    # conj_x == Real(X) + j*Imag(X) - 2j*Imag(X) == x - 2j*Imag(X)
    tmp = arr.transpose()
    return tmp - 2j*tmp.imag
Run Code Online (Sandbox Code Playgroud)

(解决方案适用于Python 3)


基于@AndrasDeak的评论的更优雅的解决方案:

Y = C * Up[:, 0:p-1].conj().T * Y
Run Code Online (Sandbox Code Playgroud)

另请注意,Python 和 MATLAB 之间与索引相关的两个差异:

  • Python 是从 0 开始的(即数组的第一个索引是0,与 MATLAB 不同,它是1
  • Python 中的索引与inclusive:exclusiveMATLAB 中的索引不同,MATLAB 中的索引是inclusive:inclusive.

因此,当我们想要在 MATLAB 中访问向量的前 3 个元素时,我们会这样写:

Y = C * ctranspose(Up[:, 0:p-1]) * Y

...

def ctranspose(arr: np.ndarray) -> np.ndarray:
    # Explanation of the math involved:
    # x      == Real(X) + j*Imag(X)
    # conj_x == Real(X) - j*Imag(X)
    # conj_x == Real(X) + j*Imag(X) - 2j*Imag(X) == x - 2j*Imag(X)
    tmp = arr.transpose()
    return tmp - 2j*tmp.imag
Run Code Online (Sandbox Code Playgroud)

在 Python 中我们会这样写:

Y = C * Up[:, 0:p-1].conj().T * Y
Run Code Online (Sandbox Code Playgroud)

(再次感谢@Andras 的解释)

  • 初级我亲爱的@Andras - 因为我不知道这样的函数存在:) (3认同)
  • 为什么不是“arr.conj().T”? (2认同)