me47
me47

Reputation: 215

Vectorized component wise multiplication

Store 2N vectors of size d in two matrices a and b where a.shape = b.shape = (N,d) (so a[i] is the ith vector in a, which contains N vector, same with b).

I would like to construct in a vectorized manner the tensor T of shape (N,d,d) such that T[i,p,q] = a[i,p]*b[i,q].

In other words, I would like to have a tensor which ith component is the (d by d)-matrix of component wise multiplication of the elements of a[i] and b[i], without doing a for loop.

I tried using tensordot on multiple axes, or dot with no avail. Any idea?

Upvotes: 0

Views: 131

Answers (1)

hpaulj
hpaulj

Reputation: 231540

With einsum the calculation writes itself:

np.einsum('ip,iq->ipq', a,b)

That expression also makes it clear that there's no summation - just products. This is a kind of outer product, not an inner or matrix one. In which case tensordot won't help. But broadcasting should:

a[:,:,None] * b[:,None,:]

(Sometimes I have to reverse the order of the None. It helps to use p and q that are different to check that.)

You didn't provide a MCVE to check my answer against.

Upvotes: 2

Related Questions