optimal_transport_fan
optimal_transport_fan

Reputation: 369

Numpy vectorized implementation of term-by-term division in a matrix

I have one matrix and one vector, of dimensions (N, d) and (N,) respectively. For each row, I want to divide each element by the corresponding value in the vector. I was wondering if there was a vectorized implementation (to save computation time). (I'm trying to create points on the surface of a d-dimensional sphere.) Right now I'm doing this:

x = np.random.randn(N,d) 
norm = np.linalg.norm(x, axis=1)

for i in range(N):
    for j in range(d):
        x[i][j] = x[i][j] / norm[i]

Upvotes: 1

Views: 75

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114230

np.linalg.norm has a keepdims argument just for this:

x /= np.linalg.norm(x, axis=1, keepdims=True)

Upvotes: 2

Related Questions