简体   繁体   中英

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:

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.

Here a numpy example:

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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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