How to get dot product of each array in (n,1,3) numpy array with all arrays of (n,3) array and get the resultant array of shape (n,n)?

67 Views Asked by At

I tried einsum np.einsum but this is giving me error that the output cannot have same letters repeated.

np.einsum('aij,aj->aa', vector1, vector2)

Also tried np.dot method but that attempt is also futile.

(Broadcasting might be having an answer for this.)
Tried

np.sum(vector1[:,np.newaxis] * vector2, axis=axis)

But, this is also giving me an error Here are the vectors 1 and 2

vector1 = np.arange(12).reshape((4,1,3))
vector2 = np.arange(12).reshape((4,3))

Thank you everyone for the comments.Apologies for asking the question incorrectly. (I needed n,n shape rather than n,3).

I am able to achieve it in the following way: np.einsum(‘ijk,bk->ib’,vector1,vector2)

2

There are 2 best solutions below

2
KamiSama On BEST ANSWER

Indeed my friend. Broadcasting is the answer. Try this

vector1 = np.arange(12).reshape((4, 1, 3))
vector2 = np.arange(12).reshape((4, 3))

result = np.sum(vector1 * vector2[:, np.newaxis], axis=2)

np.sum(..., axis=2) is like adding up the results from the previous step along the last dimension (axis 2). This gives you the dot product for each pair of arrays in vector1 and vector2.

0
Jesse Sealand On

Solution:

The key here is to be able to control which axes are bring worked on. np.dot() and np.tensordot() are unsuitable for this use case. So your intuition for using np.einsum is correct your notation needs adjusted a bit. For example

import numpy as np

vector1 = np.arange(12).reshape((4,1,3))
vector2 = np.arange(12).reshape((4,3))

np.einsum('ijk,ij->ik',vector1,vector2)