NLi10Me
NLi10Me

Reputation: 3292

Simultaneous matrix transpose for large array of matrices

I have an image with dimensions rows x cols x deps. In every voxel of this image, there is a 3x3 matrix, hence the shape of my numpy array is: (rows, cols, deps, 3, 3).

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

However, how can I simultaneously transpose all the 3x3 matrices?

Upvotes: 4

Views: 99

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114831

You can use the swapaxes method to swap 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]])

Upvotes: 4

Related Questions