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

Viewed 56

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!

1 Answers

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
Related