2
\$\begingroup\$

I have a list of N dimensional NumPy arrays.

num_vecs = 10
dims = 2
vecs = np.random.normal(size=(num_vecs, dims))

I want to normalize them, so the magnitude/length of each vector is 1. I can easily do this with a for-loop.

norm = np.linalg.norm(vecs, axis=1)
for dd in range(dims):
 vecs[:, dd] /= norm
assert np.allclose(np.linalg.norm(vecs, axis=1), 1.)

But how do I get rid of the for-loop?

asked Jan 23, 2018 at 0:49
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

The trick is to use the keepdims parameter.

import numpy as np
num_vecs = 10
dims = 2
vecs = np.random.normal(size=(num_vecs, dims))
vecs /= np.linalg.norm(vecs, axis=1, keepdims=True)
assert np.allclose(np.linalg.norm(vecs, axis=1), 1.)
answered Jan 23, 2018 at 0:56
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.