gpt4 book ai didi

python - 通过 NumPy 归一化矢量场

转载 作者:行者123 更新时间:2023-11-28 22:45:50 25 4
gpt4 key购买 nike

我有形状为 [height width 2] 的数组 field我想让每个 [i, j] 的长度小于或等于 1我使用以下程序来做

def projectionOntoDisc(var):
res = np.zeros_like(var)
for i in xrange(var.shape[0]):
for j in xrange(var.shape[1]):
norm = max(1.0, np.linalg.norm(var[i, j]))
res[i, j] = var[i, j] / norm
return res

有什么方法可以更快吗?

PS 抱歉我的英语不好

最佳答案

您可以向量化此操作,这应该会提高执行速度几个数量级:

norm = numpy.fmax(1.0, numpy.linalg.norm(var, axis=2))
res = var / norm[:, :, numpy.newaxis]

关于python - 通过 NumPy 归一化矢量场,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28109159/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com