30

I have a 3d matrix like this

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 (not sure this would work)?

Thanks,

poeticcapybara
  • 535
  • 1
  • 5
  • 13

1 Answers1

43
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
  • 777,569
  • 165
  • 1,697
  • 1,613
  • 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
  • @unutbu: Well, I agree with EOL that this is a very elegant trick, swapping axes in 4D is a pretty cool way of getting things done! – Jaime Dec 21 '12 at 15:18
  • @unutbu: It's good to know that such a solution requires some thinking. :) I did notice that your solution was your 27th shell input, so I had guessed it had not been so easy to get it. :) Good to have a confirmation. – Eric O Lebigot Dec 22 '12 at 03:28
  • @unutbu: I have a similar question here, http://stackoverflow.com/questions/35302361/reshape-an-array-of-images – ajfbiw.s Feb 10 '16 at 04:11
  • Might you take a look? Thanks. – ajfbiw.s Feb 10 '16 at 04:12