简体   繁体   English

将矩阵的每一行与其共轭转置的numpy相乘

[英]Multiply each row of a matrix with it's conjugate transposed numpy

I have a numpy.ndarray variable A of size MxN . 我有一个大小为MxNnumpy.ndarray变量A I wish to take each row and multiply with it's conjugate transposed. 我希望将每一行与共轭转置相乘。 For the first row we will get: 对于第一行,我们将获得:

np.matmul(np.expand_dims(A[0,:],axis=1),np.expand_dims(A[0,:].conj(),axis=0))

we get an NxN sized result. 我们得到NxN大小的结果。 I want the final result for the total operation to be of size MxNxN . 我希望整个操作的最终结果为MxNxN大小。

I can fo this with a simple loop which iterates over the rows of A and concatenates the results. 我可以通过一个简单的循环来实现这一点,该循环遍历A行并连接结果。 I wish to avoid a for loop for a faster run time with SIMD operations. 我希望避免使用SIMD操作进行for循环以加快运行时间。 Is there a way to do this in a single code line with broadcasting? 有没有办法在广播的单个代码行中做到这一点?

Otherwise, can I do something else and somehow reshape the results into my requierment? 否则,我可以做其他事情,以某种方式将结果重塑成我的要求吗?

The next code does what the same as your code snippet but without for-loop. 下一个代码的功能与您的代码段相同,但没有for循环。 On the other hand, it uses np.repeat twice, so you will need to benchmark both versions and compare them to test their memory/time performance. 另一方面,它两次使用np.repeat ,因此您需要对两个版本进行基准测试并进行比较以测试其内存/时间性能。

import numpy as np

m, n = A.shape

x, y = A.conj().repeat(n, axis=0), A.reshape([-1, 1]).repeat(n, axis=1)
B = (x * y).reshape([m, n, n])

How it works 这个怎么运作

Basically x holds the conjugate values of the array A in a single column and then is repeated n times on the column axis (it has a shape m*n by n ). x基本上在单个列中保存数组A的共轭值,然后在列轴上重复n次(其形状为m*n by n )。

y repeats each row in the conjugate matrix of A , n consecutive times (its final shape is m*n by n also) y连续n次重复A的共轭矩阵中的每一行(其最终形状也是m*n by n

x and y are multiplied element-wise and the result is unwrapped to a matrix of shape m by n by n stored in B xy逐个元素相乘,结果以B存储在形状为m by n by n的矩阵中

列表理解可以解决这个问题:

result = np.array([np.matmul(np.expand_dims(A[i,:],axis=1), np.expand_dims(A[i,:].conj(),axis=0)) for i in range(A.shape[0])])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM