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.
您可以使用ufuncs计算规范:
np.sqrt(np.sum(a*a, axis=0))
使用numpy的直接解决方案:
x = np.linalg.norm(a, axis=0)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.