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.

4

2 回答 2

5

You can calculate the norm by using ufuncs:

np.sqrt(np.sum(a*a, axis=0))
于 2013-03-31T02:14:30.380 回答
3

Direct solution using numpy:

x = np.linalg.norm(a, axis=0)
于 2017-12-23T15:15:52.047 回答