Karim Akhnoukh
Karim Akhnoukh

Reputation: 101

Row by column dot product in numpy array

I have two numpy arrays (A, B) of equal dimensions lets say 3*3 each. I want to have an output vector of size (3,) that has the dot product of the first row of A and first column of B, second row of A and second column of B and so on.

    A = np.array([[ 5, 1 ,3], [ 1, 1 ,1], [ 1, 2 ,1]])
    B = np.array([[1, 2, 3], [1, 2, 3], [1, 2, 3]])

What I want to have as result is [16,6,8] which would be equivilant to

    np.diagonal(A.dot(B.T))

but of course I don't want this solution because the matrix is very large.

Upvotes: 0

Views: 1464

Answers (1)

akuiper
akuiper

Reputation: 215117

Just do an element wise multiplication and then sum the rows:

(A * B).sum(axis=1)
# array([16,  6,  8])

Or use np.einsum:

np.einsum('ij,ij->i', A, B)
# array([16,  6,  8])

Upvotes: 2

Related Questions