简体   繁体   English

将 3D 矩阵与 2D 矩阵相乘得到 2D 矩阵

[英]Multiply a 3D matrix with 2D matrix to give a 2D matrix

I have 2 matrices.我有2个矩阵。 Say A of size 6 6 10 and B of size 6 10. What I want to do is multiply the 10 6 6 matrices of A with the 10 6 element vectors of B to give a 6*10 matrix.说大小为 6 6 10的 A和大小为 6 10 的B。我想要做的是将 A 的 10 6 6 矩阵与 B 的 10 6 个元素向量相乘得到一个 6*10 矩阵。 Is there a way to do this without using a loop?有没有办法在不使用循环的情况下做到这一点?

What I want is我想要的是

A = np.ones((6,6,10))
B = np.ones((6,10))
mat = np.zeros((6,10))
for i in range(10):
    mat[:,i] = A[:,:,i]@B[:,i] 

but without the for loop.但没有 for 循环。

We can use np.einsum -我们可以使用np.einsum -

mat = np.einsum('ijk,jk->ik',A,B)

Alternatively, with np.matmul/@-operator -或者,使用np.matmul/@-operator -

mat = (A.transpose(2,0,1)@B.T[:,:,None])[...,0].T

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

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