-4

I need to create a diagonal matrix with its diagonal displaced left or right from the center any help?

Edsson
  • 3
  • 1

1 Answers1

1

As the down-votes of your question suggest, you should try to explain your question in a better way. That being said, my best guess is that you're looking for superdiagonal and subdiagonal matrices; i.e.:

Superdiagonal:

0 1 0 0
0 0 1 0
0 0 0 1
0 0 0 0

Subdiagonal:

0 0 0 0
1 0 0 0
0 1 0 0
0 0 1 0

If that's the case, then you can use Numpy's indices:

import numpy as np
superdiagonal = np.zeros((4, 4))
i, j = np.indices(superdiagonal.shape)
superdiagonal[i == j-1] = 1
print(superdiagonal)

This will give you:

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

For subdiagonal, you just have to change the i == j-1 part to i == j+1.

bbkglb
  • 769
  • 1
  • 7
  • 16