Fno*_*ord 5 python arrays performance numpy matrix
给定一个旋转角度列表(让我们说一下 X 轴):
import numpy as np
x_axis_rotations = np.radians([0,10,32,44,165])
Run Code Online (Sandbox Code Playgroud)
我可以通过这样做创建匹配这些角度的矩阵数组:
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)
Run Code Online (Sandbox Code Playgroud)
这会起作用,但它没有利用 numpy 处理大型数组的优势......所以如果我的角度数组是数百万,那么这样做不会很快。
有没有更好(更快)的方法来从输入数组创建变换矩阵数组?
这是一个直接而简单的方法:
\n\nc = np.cos(x_axis_rotations)\ns = np.sin(x_axis_rotations)\nmatrices = np.zeros((len(x_axis_rotations), 3, 3))\nmatrices[:, 0, 0] = 1\nmatrices[:, 1, 1] = c\nmatrices[:, 1, 2] = -s\nmatrices[:, 2, 1] = s\nmatrices[:, 2, 2] = c\nRun Code Online (Sandbox Code Playgroud)\n\n对于好奇的人来说,时间安排:
\n\nIn [30]: angles = 2 * np.pi * np.random.rand(1000)\n\nIn [31]: timeit OP(angles)\n100 loops, best of 3: 5.46 ms per loop\n\nIn [32]: timeit askewchan(angles)\n10000 loops, best of 3: 39.6 \xc2\xb5s per loop\n\nIn [33]: timeit divakar(angles)\n10000 loops, best of 3: 93.8 \xc2\xb5s per loop\n\nIn [34]: timeit divakar_oneline(angles)\n10000 loops, best of 3: 56.1 \xc2\xb5s per loop\n\nIn [35]: timeit divakar_combine(angles)\n10000 loops, best of 3: 43.9 \xc2\xb5s per loop\nRun Code Online (Sandbox Code Playgroud)\n\n所有的都比你的循环快得多,所以使用你最喜欢的:)
\n| 归档时间: |
|
| 查看次数: |
1160 次 |
| 最近记录: |