1

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? Commented Feb 8, 2020 at 22:10

1 Answer 1

1

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]])
Sign up to request clarification or add additional context in comments.

6 Comments

Wow! That's impressive! Thank you so much! Now I just have to learn and understand this swapaxes method I didn't know :)
Finaly I couldn't apply it to my problem... I had Q.shape = (10,10,784), and I wanted, in the same way as in my example to find a (280,280) shaped matrix ; I ended up to use data = np.array([]) for l in Q: ligne = np.array([]) for s in l: if ligne.shape == (0,) : ligne = s.reshape((28,28)) else: ligne = np.concatenate((ligne, s.reshape((28,28))), axis=1) if data.shape == (0,) : data = ligne else: data = np.concatenate((data, ligne), axis=0)
What are, in this case, a,b,c,d,e for np.concatenate(Q.reshape(a, b, c, -1).swapaxes(d,e).reshape(Q.shape)) ?
My bad I hardcoded the two first axes, try now @Netchaiev
Still not working (I obtain at the end a 100x784 matrix...), since in my matrix of interest Q, Q.shape[0] and Q.shape[1] will be 10 and, at some point I guess one must to turn the 784 long lists into 28x28 matrices...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.