NumPy: how to quickly normalize many vectors?
- by EOL
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(10), arange(10)]) # All x's, then all y's
norms = apply_along_axis(linalg.norm, 0, vectors)
# Now, what I was expecting would work:
print vectors.T / norms # vectors.T has 10 elements, as does norms, but this does not work
The last operation yields "shape mismatch: objects cannot be broadcast to a single shape".
How can the normalization of the 2D vectors in vectors be elegantly done, with NumPy?
Edit: Why does the above not work while adding a dimension to norms does work (as per my answer below)?