3

I am looking for the best way of calculating the norm of columns as vectors in a matrix. My code right now is like this but I am sure it can be made better(with maybe numpy?):

import numpy as np
def norm(a):
    ret=np.zeros(a.shape[1])
    for i in range(a.shape[1]):
        ret[i]=np.linalg.norm(a[:,i])
    return ret

a=np.array([[1,3],[2,4]])
print norm(a)

Which returns:

[ 2.23606798  5.        ]

Thanks.

Cupitor
  • 11,007
  • 19
  • 65
  • 91
  • Duplicate of http://stackoverflow.com/questions/7741878/how-to-apply-numpy-linalg-norm-to-each-row-of-a-matrix Can be done with np.linalg.norm(a, axis=0). – Remi LP Jan 07 '17 at 20:17

2 Answers2

5

You can calculate the norm by using ufuncs:

np.sqrt(np.sum(a*a, axis=0))
HYRY
  • 94,853
  • 25
  • 187
  • 187
3

Direct solution using numpy:

x = np.linalg.norm(a, axis=0)
Miguel
  • 658
  • 1
  • 6
  • 19
  • this method does not exist with my numy install, and I can't find any documentation about it online. Could you provide some reference ? – Matthias Beaupère Apr 23 '19 at 08:55
  • @mattiasbe see [https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html](https://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html) – Miguel Apr 24 '19 at 14:08