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]]]
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]]]
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.
One approach would be to stack those in columns with
np.column_stack
and reshape withnp.reshape
-Concatenating with
np.concatenate
is known to be much faster, so using it with2D transpose
and reshaping -Another with
np.concatenate
,3D transpose
and reshaping -Runtime tests -