pythonarraysnumpymathnumpy-einsum

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)?


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)


Solution

  • 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.