gpt4 book ai didi

python - 创建 numpy 转换矩阵数组的正确方法是什么

转载 作者:太空狗 更新时间:2023-10-30 02:43:37 26 4
gpt4 key购买 nike

给定旋转角度列表(假设是 X 轴):

import numpy as np
x_axis_rotations = np.radians([0,10,32,44,165])

我可以通过这样做创建一个匹配这些角度的矩阵数组:

matrices = []
for angle in x_axis_rotations:
matrices.append(np.asarray([[1 , 0 , 0],[0, np.cos(angle), -np.sin(angle)], [0, np.sin(angle), np.cos(angle)]]))
matrices = np.array(matrices)

这会起作用,但它没有利用 numpy 处理大型数组的优势...因此,如果我的角度数组数以百万计,这样做的速度不会很快。

是否有更好(更快)的方法从输入数组创建转换矩阵数组?

最佳答案

这是一个直接而简单的方法:

c = np.cos(x_axis_rotations)
s = np.sin(x_axis_rotations)
matrices = np.zeros((len(x_axis_rotations), 3, 3))
matrices[:, 0, 0] = 1
matrices[:, 1, 1] = c
matrices[:, 1, 2] = -s
matrices[:, 2, 1] = s
matrices[:, 2, 2] = c

时间,对于好奇的人:

In [30]: angles = 2 * np.pi * np.random.rand(1000)

In [31]: timeit OP(angles)
100 loops, best of 3: 5.46 ms per loop

In [32]: timeit askewchan(angles)
10000 loops, best of 3: 39.6 µs per loop

In [33]: timeit divakar(angles)
10000 loops, best of 3: 93.8 µs per loop

In [34]: timeit divakar_oneline(angles)
10000 loops, best of 3: 56.1 µs per loop

In [35]: timeit divakar_combine(angles)
10000 loops, best of 3: 43.9 µs per loop

所有都比你的循环快得多,所以使用你最喜欢的:)

关于python - 创建 numpy 转换矩阵数组的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32573868/

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