1
votes

I wanted to know if it exists an easy way to transform such a matrix :

[[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]]

into

[[1 ,2 ,5 ,6 ],
 [3 ,4 ,7 ,8 ],
 [9 ,10,13,14],
 [11,12,15,16]]

Which is equivalent to reshape each initial list into 2x2 matrices, and then concatenate them; for instance np.array([1,2,3,4]).reshape((2,2)) gives [[1,2],[3,4]]

np.array([5, 6, 7, 8]).reshape((2,2)) gives [[5,6],[7,8]]

so

np.concatenate((np.array([1,2,3,4]).reshape((2,2)), np.array([5, 6, 7, 8]).reshape((2,2))), axis=1)

will give

array([[1 ,2 ,5 ,6 ],
       [3 ,4 ,7 ,8 ]])

etc...

It is indeed a dummy example since I need to deal with more (and bigger) matrices, I have to find a more straightforward method.

1
If I understand it correctly, you want to "drop" the second dimension? - Willem Van Onsem

1 Answers

1
votes

We can use reshape with swapaxes and a concatenate along the first axis:

np.concatenate(a.reshape(a.shape[0], a.shape[1], 2, -1)
                 .swapaxes(1,2)
                 .reshape(a.shape))

array([[ 1,  2,  5,  6],
       [ 3,  4,  7,  8],
       [ 9, 10, 13, 14],
       [11, 12, 15, 16]])