5

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.

jpp
  • 159,742
  • 34
  • 281
  • 339
user1700890
  • 7,144
  • 18
  • 87
  • 183

2 Answers2

7

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

pault
  • 41,343
  • 15
  • 107
  • 149
jpp
  • 159,742
  • 34
  • 281
  • 339
2

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 np
a = 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.]])
pault
  • 41,343
  • 15
  • 107
  • 149
Grant Williams
  • 1,469
  • 1
  • 12
  • 24
  • I'll leave this up for people who may need an anti diagonal matrix in numpy, but @jpp answered the questions that is actually being asked – Grant Williams May 23 '18 at 15:03
  • You could simply use `np.fliplr(np.eye(n))` to answer the question. – pault May 23 '18 at 15:05
  • 1
    @pault well thats a flipped version of the identity matrix. The original question, before the OP edited it, was how do you make an anti diagonal matrix. An anti diagonal matrix is not guaranteed to be ones along the diagonal, so i left mine up for posterities sake. – Grant Williams May 23 '18 at 15:08
  • 1
    @pault Well it is an anti diagonal matrix, but its simply a subset. The flipped identity matrix is an anti diagonal matrix of the identity matrix, where as my solution i initially provided works for any matrix that may or may not already be a diagonal matrix. – Grant Williams May 23 '18 at 15:11