32

I have a 3d matrix like this

np.arange(16).reshape((4,2,2))

array([[[ 0,  1],
        [ 2,  3]],

        [[ 4,  5],
        [ 6,  7]],

        [[ 8,  9],
        [10, 11]],

        [[12, 13],
        [14, 15]]])

and would like to stack them in grid format, ending up with

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

Is there a way of doing without explicitly hstacking (and/or vstacking) them or adding an extra dimension and reshaping?

cottontail
  • 10,268
  • 18
  • 50
  • 51
poeticcapybara
  • 555
  • 1
  • 5
  • 15

2 Answers2

44
In [27]: x = np.arange(16).reshape((4,2,2))

In [28]: x.reshape(2,2,2,2).swapaxes(1,2).reshape(4,-1)
Out[28]: 
array([[ 0,  1,  4,  5],
       [ 2,  3,  6,  7],
       [ 8,  9, 12, 13],
       [10, 11, 14, 15]])

I've posted more general functions for reshaping/unshaping arrays into blocks, here.

Community
  • 1
  • 1
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 2
    Ok, so considering I have N block matrices with `bm x bn` dimension and want to stack them in a `m x n` matrix, provided `N = m x n`, I would then have `x.reshape(m,n,bm,bn).swapaxes(1,2).reshape(bm*m,-1)` Just wanted to know if there was any numpy function for this purpose. Thanks @unutbu once again. – poeticcapybara Dec 21 '12 at 13:18
0

The convert a 3d array to a 2d one, transpose() is a very useful function. For example, to derive the expected result in the OP, after reshaping by adding an extra dimension, the second and third axes could be swapped using transpose().

arr = np.arange(16).reshape(4,2,2)
reshaped_arr = arr.reshape(2,2,2,2).transpose(0,2,1,3).reshape(4,-1)

result1


On the surface, it does the same job as swapaxes() but since transpose() allows any permutation of axes, it's more flexible. For example, to make the following transformation, two axes must be swapped, so swapaxes() will have to called twice but it can be handled with a single transpose() call.

result2

reshaped_arr = arr.reshape(2,2,2,2).transpose(1,2,0,3).reshape(4,-1)
cottontail
  • 10,268
  • 18
  • 50
  • 51