'Dot products of self vectors in a matrix

I would like to get the dot products of self vectors xi in a matrix xi is the i-th row vector in matrix X

enter image description here

Here is my code

xi = np.diagonal(np.dot(x, x.T))

Is there a better way to do so? Because there are a lot of unnecessary computations



Solution 1:[1]

How about using np.einsum?

import numpy as np

x = np.arange(9).reshape(3, 3)
output = np.einsum('ij, ij -> i', x, x)
print(x)
print(output)
# [[0 1 2]
#  [3 4 5]
#  [6 7 8]]
# [  5  50 149]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1