How does the transpose of high-dimensional arrays work?

Viewed 32

It's easy to understand the concept of Transpose in 2-D array. I reall can not understand How the transpose of high-dimensional arrays works. For example

c = np.indices([4,5]).T.reshape(20,1,2)
d = np.indices([4,5]).reshape(20,1,2)
np.all(c==d) # output is False 

Why are the outputs of C and D inconsistent?

1 Answers
In [143]: c = np.indices([4,5])
In [144]: c
Out[144]: 
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3]],

       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]])

In [145]: c.shape
Out[145]: (2, 4, 5)

In [146]: c.T.shape
Out[146]: (5, 4, 2)

Look at one 2d array from the size 2 dimension:

In [150]: c[0,:,:]
Out[150]: 
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3]])

In [151]: c.T[:,:,0]
Out[151]: 
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])

The 2nd is the usual 2d transpose, a (5,4) array.

MATLAB doesn't do transpose on 3d arrays, at least it doesn't call it such. It may have a way making such a change. numpy, using a general shape/strides multidimensional implementation, easily generalizes the 2d transpose - to 1d or 3d or more.

Related