Search code examples
pythonnumpyreshape

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 4x4 matrix that will look like this:

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

  • Try

    np.block([[a,b],[c,d]])
    

    This concatenates the inner lists horizontally, and does a vertical stack.

    Alternatively you could swap 2 axes of e and then reshape.

    In [41]: np.block([[a,b],[c,d]])
    Out[41]: 
    array([[0., 0., 1., 1.],
           [0., 0., 1., 1.],
           [2., 2., 3., 3.],
           [2., 2., 3., 3.]])
    
    In [45]: e.transpose(0,2,1,3).reshape(4,4)
    Out[45]: 
    array([[0., 0., 1., 1.],
           [0., 0., 1., 1.],
           [2., 2., 3., 3.],
           [2., 2., 3., 3.]])
    

    block is doing the equivalent of:

    In [47]: np.vstack([np.hstack([a,b]),np.hstack([c,d])])
    Out[47]: 
    array([[0., 0., 1., 1.],
           [0., 0., 1., 1.],
           [2., 2., 3., 3.],
           [2., 2., 3., 3.]])