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!