Simultaneous matrix transpose for a large array of matrices

I have an image with dimensions rows x cols x deps. Each voxel of the image is a matrix of 3x3, so the shape of my array numpy: (rows, cols, deps, 3, 3).

I know that I can invert all of these matrices at the same time using the version numpy.linalg.inv(); which is pretty awesome.

However, how can I transfer all 3x3 matrices at the same time?

+4
source share
1 answer

You can use the method swapaxesto replace the last two dimensions:

In [17]: x = np.random.randint(0, 99, (4,4,4,3,3))

In [18]: x[0,0,0]
Out[18]: 
array([[21, 93, 83],
       [57,  0, 96],
       [43, 37, 22]])

In [19]: x[1,1,2]
Out[19]: 
array([[59,  0, 27],
       [85, 97, 19],
       [91, 52, 68]])

In [20]: y = x.swapaxes(-1,-2)

In [21]: y[0,0,0]
Out[21]: 
array([[21, 57, 43],
       [93,  0, 37],
       [83, 96, 22]])

In [22]: y[1,1,2]
Out[22]: 
array([[59, 85, 91],
       [ 0, 97, 52],
       [27, 19, 68]])
+4
source

All Articles