Newlearner
Newlearner

Reputation: 33

Create a NxN array for all diagonals

Given an integer n, create nxn nummy array such that all of the elements present in both its diagonals are 1 and all others are 0

Input: 4

Output

  *[[1, 0, 0, 1],
    [0, 1, 1, 0],
    [0, 1, 1, 0],
    [1, 0, 0, 1]]*

how do i achieve this array?

Upvotes: 1

Views: 1351

Answers (3)

Daweo
Daweo

Reputation: 36390

I would do (assuming n=5):

import numpy as np
d = np.diagflat(np.ones(5,int))
a = d | np.rot90(d)
print(a)

Output:

[[1 0 0 0 1]
 [0 1 0 1 0]
 [0 0 1 0 0]
 [0 1 0 1 0]
 [1 0 0 0 1]]

I harness fact that we could use | (binary OR) here for getting same effect as max, because arrays holds solely 0s and 1s.

Upvotes: 0

DYZ
DYZ

Reputation: 57033

Create an identity matrix and its flipped view, then take the maximum of the two:

np.maximum(np.eye(5, dtype=int), np.fliplr(np.eye(5, dtype=int)))
#array([[1, 0, 0, 0, 1],
#       [0, 1, 0, 1, 0],
#       [0, 0, 1, 0, 0],
#       [0, 1, 0, 1, 0],
#       [1, 0, 0, 0, 1]])

Edited: changed [::-1] to np.fliplr (for better performance).

Upvotes: 2

Suraj
Suraj

Reputation: 2477

You can use the fill_diagonal to fill the elements in the principal diagonal and use it with np.fliplr to fill elements across the other diagonal. Refer link

import numpy as np
a = np.zeros((4, 4), int)
np.fill_diagonal(a, 1)
np.fill_diagonal(np.fliplr(a), 1)

Output :

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

Upvotes: 2

Related Questions