Search code examples
pythonnumpylinear-algebramatrix-multiplication

Calculating norm of columns as vectors in a matrix


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.


Solution

  • You can calculate the norm by using ufuncs:

    np.sqrt(np.sum(a*a, axis=0))