Cupitor
Cupitor

Reputation: 11637

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.

Upvotes: 3

Views: 5725

Answers (2)

Miguel
Miguel

Reputation: 796

Direct solution using numpy:

x = np.linalg.norm(a, axis=0)

Upvotes: 3

HYRY
HYRY

Reputation: 97271

You can calculate the norm by using ufuncs:

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

Upvotes: 5

Related Questions