Let's say that I have these 4 submatrices:
print(A[0])
print(A[1])
print(A[2])
print(A[3])
[[ 0. 1. 2.]
[ 6. 7. 8.]
[ 12. 13. 14.]]
[[ 3. 4. 5.]
[ 9. 10. 11.]
[ 15. 16. 17.]]
[[ 18. 19. 20.]
[ 24. 25. 26.]
[ 30. 31. 32.]]
[[ 21. 22. 23.]
[ 27. 28. 29.]
[ 33. 34. 35.]]
From this matrix:
[[ 0 1 2 3 4 5]
[ 6 7 8 9 10 11]
[12 13 14 15 16 17]
[18 19 20 21 22 23]
[24 25 26 27 28 29]
[30 31 32 33 34 35]]
How can I manage the submatrix to reproduce the original one?
With A
as the input array containing those sub-matrices, you could use some reshaping
and permute dimensions with np.transpose
, like so -
A.reshape(2,2,3,3).transpose(0,2,1,3).reshape(-1,6)
Explanation -
- Cut the first axis into two parts :
A.reshape(2,2,3,3)
.
- Swap the second and third axes :
.transpose(0,2,1,3)
.
- Finally, reshape to have
6
columns : .reshape(-1,6)
.
Thus, the solution could be generalized like so -
m,n,r = A.shape
out = A.reshape(-1,2,n,r).transpose(0,2,1,3).reshape(-1,2*r)
Sample run
Let's re-create your A
-
In [54]: A = np.arange(36).reshape(-1,3,2,3). transpose(0,2,1,3).reshape(4,3,3)
In [55]: A
Out[55]:
array([[[ 0, 1, 2],
[ 6, 7, 8],
[12, 13, 14]],
[[ 3, 4, 5],
[ 9, 10, 11],
[15, 16, 17]],
[[18, 19, 20],
[24, 25, 26],
[30, 31, 32]],
[[21, 22, 23],
[27, 28, 29],
[33, 34, 35]]])
Then, run our code -
In [56]: A.reshape(2,2,3,3).transpose(0,2,1,3).reshape(-1,6)
Out[56]:
array([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]])