0

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)

5
  • Please post the inputs for vector1 and vector2 so your problem can be replicated. Thank you. Commented Sep 5, 2023 at 10:24
  • Do you just want np.einsum('aij,aj->aj', vector1, vector2)? Commented Sep 5, 2023 at 10:45
  • With (n,1,3) and (n,3) arrays, what's the sum-of-products dimension? Looks like you want to preserve the '3'. A[:,0,:] *B would produce a (n,3) result without any sum's. einsum('aij,aj->aj' will use A.sum(axis=1) * B. Neither is a dot product. Commented Sep 5, 2023 at 16:15
  • Other answers make a (n,3,3) result, and then sum on one of the 3s. You suggested two arrays, but did not give a desired result. So the question is still ambiguous. Commented Sep 5, 2023 at 18:27
  • @hpaulj please revisit the question now. Made some edits. Commented Sep 6, 2023 at 11:12

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your result is (4,1). An alternative is to sum on axis 1, which is size 1, giving a (4,3).
Hey thanks for the information. Please revisit the question once. Given the sol as well.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.