2013-03-31 183 views
2

我正在寻找计算列的范数作为矩阵中向量的最佳方法。 我的代码现在的问题是这样的,但我相信它可以变得更好(与也许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) 

将返回:

[ 2.23606798 5.  ] 

感谢。

+0

http://stackoverflow.com/questions/7741878/how-to-apply的重复-numpy-linalg-norm-to-each-row-of-a-matrix可以用np.linalg.norm(a,axis = 0)完成。 – DocLP

回答

3

您可以通过使用ufuncs计算标准:

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

直接的解决方案使用numpy的:

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