How can a list of vectors be elegantly normalized, in NumPy?
Here is an example that does not work:
from numpy import *
vectors = array([arange
For the two-dimensional case, using np.hypot(vectors[:,0],vectors[:,1])
looks to be faster than Freddie Witherden's np.sqrt(np.einsum('...i,...i', vectors, vectors))
for calculating the magnitudes. (Referencing answer by Geoff)
import numpy as np
# Generate array of 2D vectors.
vectors = np.random.random((1000,2))
# Using Freddie's
%timeit np.sqrt(np.einsum('...i,...i', vectors, vectors))
# Output: 11.1 µs ± 173 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
# Using numpy.hypot()
%timeit np.hypot(vectors[:,0], vectors[:,1])
# Output: 6.81 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
To get the normalised vectors then do:
vectors /= np.hypot(vectors[:,0], vectors[:,1])