Home > Mobile >  Dot products of self vectors in a matrix
Dot products of self vectors in a matrix

Time:01-29

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

CodePudding user response:

Perform an element-wise squaring and then sum across the rows:

np.square(x).sum(axis=1)

Example:

>>> x = np.arange(9).reshape(3,3)
>>> np.diagonal(np.dot(x, x.T))
array([  5,  50, 149])
>>> np.square(x).sum(axis=1)
array([  5,  50, 149])

CodePudding user response:

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]
  •  Tags:  
  • Related