简体   繁体   English

通过向量的差异对矩阵创建进行向量化(例如,对于 numpy)

[英]Vectorization of matrix creation by difference of vectors (e.g. for numpy)

i often need to calculate a matrix A[i,j] based on a given vector v[i] by:我经常需要根据给定的向量v[i]通过以下方式计算矩阵A[i,j]

A[i, j] = v[j] - v[i]

This is straightforward in a nested loop, but I'd like to vectorize it.这在嵌套循环中很简单,但我想对其进行矢量化。 So far I've only come up with the rather ugly solution of creating two matrizes additional, where v is repeated in each row/column and I therefore can use simple element-wise matrix addition.到目前为止,我只提出了另外创建两个矩阵的相当丑陋的解决方案,其中 v 在每一行/列中重复,因此我可以使用简单的逐元素矩阵加法。

Here a numpy example:这是一个 numpy 示例:

import numpy as np
length = 10
v = np.random.random(length)
vjMatrix = np.broadcast_to(v, (length, length))
viMatrix = np.transpose(vjMatrix)

A = vjMatrix - viMatrix
print(A)

However, I hope there is a more elegant solution, that I just fail to see.但是,我希望有一个更优雅的解决方案,我只是看不到。 I was looking through a lot of threads, but haven't found anything particularly suitable.我浏览了很多线程,但没有找到特别合适的东西。

Thanks!谢谢!

If I understand you question correctly, you currently fill array A like:如果我正确理解您的问题,您目前填写数组A如下:

import numpy as np

length = 100
np.random.seed(123)
v = np.random.rand(length)

vjMatrix = np.broadcast_to(v, (length, length))
viMatrix = np.transpose(vjMatrix)

A = vjMatrix - viMatrix

If this is what you want, you can replace the loop and the explicit creation of the v -matrices by broadcasting the vector v :如果这是您想要的,您可以通过广播向量v来替换循环和显式创建v矩阵:

A_new = v - v[:, None]
print(np.all(A == A_new))
# Out: True

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

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