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)?
Well, unless I missed something, this does work:
The problem in your suggestion is the broadcasting rules.
The shape do not have the same length! So the rule is to first extend the small shape by one on the left:
You can do that manually by calling:
If you wanted to compute
vectors.T/norms, you would have to do the reshaping manually, as follows: