计算列的范数作为矩阵中的向量

问题描述 投票:3回答: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.        ]

谢谢。

python numpy linear-algebra matrix-multiplication
2个回答
4
投票

您可以使用ufuncs计算规范:

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

1
投票

使用numpy的直接解决方案:

x = np.linalg.norm(a, axis=0)
© www.soinside.com 2019 - 2024. All rights reserved.