英文:
How do I turn 2 equal sized vectors into a matrix that's the pairwise product of the two vectors in Python?
问题
惊讶的是我找不到这个答案,但我想要基本上创建一个协方差矩阵,但是每个值都不是协方差,我希望每个单元格都是两个向量的乘积。所以如果我有一个1x5的向量,我想得到一个5x5的矩阵。
例如:
输入:
[1, 2, 3, 4, 5]
输出:
[[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]]
有没有一种快速的方法而不需要构建循环?
英文:
Surprised I can't find this answer, but I am looking to basically create a covariance matrix, but instead of each value being a covariance, I want each cell to be the product of the two vectors. So if I have 1x5 vector, I want to end up with a 5x5 matrix.
For example:
Input:
[1, 2, 3, 4, 5]
Output:
[[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]]
Is there a fast way without building a loop?
答案1
得分: 2
只需使用 numpy.outer
。它计算两个向量的外积。
a = np.array([1, 2, 3, 4, 5])
res = np.outer(a,a)
print(res)
array([[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]])
或者如果你愿意使用 broadcasting:
res = a[:,None]*a
print(res)
array([[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]])
英文:
Simply use numpy.outer
. It computes the outer product of two vectors.
a = np.array([1, 2, 3, 4, 5])
res = np.outer(a,a)
print(res)
array([[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]])
Or if you are ok with broadcasting then :
res = a[:,None]*a
print(res)
array([[ 1, 2, 3, 4, 5],
[ 2, 4, 6, 8, 10],
[ 3, 6, 9, 12, 15],
[ 4, 8, 12, 16, 20],
[ 5, 10, 15, 20, 25]])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论