简体   繁体   English

如何使用 numpy 计算向量和矩阵的“克罗内克积”

[英]How to calculate “Kronecker Product” of a vector and a matrix with numpy

I need to compute the following forumula:我需要计算以下公式:

Fromula in TeX: TeX 中的公式:

$\sum_n^N \sum_m^N a_n * a_m * C_{nm}$

Peudocode:伪代码:

a = array of length N
C = NxN matrix
retval = 0
for n in range(N):
    for m in range(N):
         retval += a[n] * a[m] * C[n][m]

If a were a NxN matrix constructed as in the product above one could simply use np.kron for the Kronecker Matrix multiplication and then use np.sum to get the desired result.如果a是按上述乘积构造的 NxN 矩阵,则可以简单地使用np.kron进行 Kronecker 矩阵乘法,然后使用np.sum来获得所需的结果。 However I don't know a faster numpy way of constructing a matrix A as in the formula above.但是,我不知道更快的 numpy 构造矩阵 A 的方法,如上面的公式。

Any ideas?有任何想法吗?

We could directly use those iterators for np.einsum string-notation -我们可以直接将这些迭代器用于np.einsum字符串表示法 -

retval = np.einsum('n,m,nm->',a,a,C)

Alternatively, withnp.dot -或者,使用np.dot -

retval = a.dot(C).dot(a)

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

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