Home > database >  how do i create this specific diagonal array with eye() in numpy
how do i create this specific diagonal array with eye() in numpy

Time:10-07

How can I create an array below using eye() function? I thought eye() only produced 0 and 1

[[2, 1, 0],
[1, 2, 1],
[0, 1, 2]]

Thank You.

CodePudding user response:

Here is one way using broadcasting:

n = 3
v = np.arange(n)

out = n-1-abs(v[:,None]-v) # or n-1-abs(np.subtract.outer(v, v))

output:

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

with n=7:

array([[6, 5, 4, 3, 2, 1, 0],
       [5, 6, 5, 4, 3, 2, 1],
       [4, 5, 6, 5, 4, 3, 2],
       [3, 4, 5, 6, 5, 4, 3],
       [2, 3, 4, 5, 6, 5, 4],
       [1, 2, 3, 4, 5, 6, 5],
       [0, 1, 2, 3, 4, 5, 6]])

CodePudding user response:

import numpy as np

a = np.eye(3,3)
b = np.eye(3,3,k=1)
c = np.eye(3,3,k=-1)

diagonal_array = 2*a b c

print(diagonal_array)

Or

diagonal_array = 2*np.eye(3,3)   np.eye(3,3,k=1)   np.eye(3,3,k=-1)
print(diagonal_array)
  • Related