简体   繁体   English

矩阵中自向量的点积

[英]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我想得到矩阵 xi 中自向量 xi 的点积是矩阵 X 中的第 i 行向量

在此处输入图像描述

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因为有很多不必要的计算

How about using np.einsum ?使用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]

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM