Search code examples
pythonarraysnumpymatrixdiagonal

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


How can I create anti-diagonal matrix in numpy? I can surely do it manually, but curious if there is a function for it.

I am looking for a Matrix with the ones going from the bottom left to the upper right and zeros everywhere else.


Solution

  • 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