How to create an anti-diagonal identity matrix (where the diagonal is flipped left to right) in numpy How to create an anti-diagonal identity matrix (where the diagonal is flipped left to right) in numpy numpy numpy

How to create an anti-diagonal identity matrix (where the diagonal is flipped left to right) in numpy


Use np.eye(n)[::-1] which will produce:

array([[ 0.,  0.,  0.,  0.,  1.],       [ 0.,  0.,  0.,  1.,  0.],       [ 0.,  0.,  1.,  0.,  0.],       [ 0.,  1.,  0.,  0.,  0.],       [ 1.,  0.,  0.,  0.,  0.]])

for n=5


One way is to flip the matrix, calculate the diagonal and then flip it once again.

The np.diag() function in numpy either extracts the diagonal from a matrix, or builds a diagonal matrix from an array. You can use it twice to get the diagonal matrix.

So you would have something like this:

import numpy as npa = np.arange(25).reshape(5,5)>>> a[[ 0  1  2  3  4] [ 5  6  7  8  9] [10 11 12 13 14] [15 16 17 18 19] [20 21 22 23 24]]b = np.fliplr(np.diag(np.diag(np.fliplr(a))))>>> b[[ 0  0  0  0  4] [ 0  0  0  8  0] [ 0  0 12  0  0] [ 0 16  0  0  0] [20  0  0  0  0]]

I'm not sure how efficient doing all this will be though.

This makes an anti diagonal matrix, not a flipped version of the identity matrix.

If you wanted a flipped version of the identity matrix, you could simply call np.fliplr() on the output of np.eye(n). For example:

>>> np.fliplr(np.eye(5))array([[ 0.,  0.,  0.,  0.,  1.],       [ 0.,  0.,  0.,  1.,  0.],       [ 0.,  0.,  1.,  0.,  0.],       [ 0.,  1.,  0.,  0.,  0.],       [ 1.,  0.,  0.,  0.,  0.]])