Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy turn hierarchy of matrices into concatenation

I have the following 4 matrices:

>>> a
array([[0., 0.],
       [0., 0.]])
>>> b
array([[1., 1.],
       [1., 1.]])
>>> c
array([[2., 2.],
       [2., 2.]])
>>> d
array([[3., 3.],
       [3., 3.]])

I’m creating another matrix that will contain them:

>>> e = np.array([[a,b], [c,d]])
>>> e.shape
(2, 2, 2, 2)

I want to "cancel the hierarchy" and reshape e into a 4×4 matrix that will look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0 0 1 1
0 0 1 1
2 2 3 3
2 2 3 3

However, when I run e.reshape((4,4)), I get the following matrix:

>>> e.reshape((4,4))
array([[0., 0., 0., 0.],
       [1., 1., 1., 1.],
       [2., 2., 2., 2.],
       [3., 3., 3., 3.]])

Is there a way to reshape my (2,2,2,2) matrix into a (4,4) matrix by cancelling the hierarchy, rather than the the by the indexing I’m currently getting?

>Solution :

Yes you can do it with the .concatenate function of numpy:

np.concatenate(np.concatenate(e, axis=1), axis=1)

There you get the following matrix as result:

array([[0., 0., 1., 1.],
       [0., 0., 1., 1.],
       [2., 2., 3., 3.],
       [2., 2., 3., 3.]])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading