如何迅速地从大小为N 9阵列创建n个3×3矩阵排列? [英] How to rapidly create array of N 3x3 matrices from 9 arrays of size N?
问题描述
假设我有大小N. 9阵列(A,B,C,... J),我想创建n个3×3矩阵的一个新的阵列,使得例如
Assume that I have 9 arrays (A, B, C, .. J) of size N. I want to create a new array of N 3x3 matrices such that e.g.
matrices[i] = [[A[i], B[i], C[i]],
[D[i], E[i], F[i]],
[G[i], H[i], J[i]]]
有一个简单的解决方案是增加每次进入阵列矩阵
在for循环为:
A simple solution is to add each entry to the array matrices
in a for-loop as:
for i in range(len(matrices)):
matrices[i] = [[A[i], B[i], C[i]],
[D[i], E[i], F[i]],
[G[i], H[i], J[i]]]
任何人有关于如何能够以更快,量化的方式避免for循环做一些建议吗?如果存在一些聪明的索引操作什么的。
Anybody got some tips on how this can be done in a faster, vectorized way avoiding the for-loop? If there exists some smart indexing operations or something.
推荐答案
一个办法是堆放在那些柱的 np.column_stack
和的 np.reshape
-
One approach would be to stack those in columns with np.column_stack
and reshape with np.reshape
-
np.column_stack((A,B,C,D,E,F,G,H,J)).reshape(-1,3,3)
串联使用 np.concatenate
被称为是更快,所以使用它与 2D转置
与重塑 -
np.concatenate((A,B,C,D,E,F,G,H,J)).reshape(9,-1).T.reshape(-1,3,3)
另一个与 np.concatenate
, 3D转置
与重塑 -
np.concatenate((A,B,C,D,E,F,G,H,J)).reshape(3,3,-1).transpose(2,0,1)
运行测试 -
Runtime tests -
In [59]: # Setup input arrays
...: N = 1000
...: A = np.random.randint(0,9,(N,))
...: B = np.random.randint(0,9,(N,))
...: C = np.random.randint(0,9,(N,))
...: D = np.random.randint(0,9,(N,))
...: E = np.random.randint(0,9,(N,))
...: F = np.random.randint(0,9,(N,))
...: G = np.random.randint(0,9,(N,))
...: H = np.random.randint(0,9,(N,))
...: J = np.random.randint(0,9,(N,))
...:
In [60]: %timeit np.column_stack((A,B,C,D,E,F,G,H,J)).reshape(-1,3,3)
10000 loops, best of 3: 84.4 µs per loop
In [61]: %timeit np.concatenate((A,B,C,D,E,F,G,H,J)).reshape(9,-1).T.reshape(-1,3,3)
100000 loops, best of 3: 15.8 µs per loop
In [62]: %timeit np.concatenate((A,B,C,D,E,F,G,H,J)).reshape(3,3,-1).transpose(2,0,1)
100000 loops, best of 3: 14.8 µs per loop
这篇关于如何迅速地从大小为N 9阵列创建n个3×3矩阵排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!