Home > Blockchain >  python - matrix of zeros with X shaped ones in one line
python - matrix of zeros with X shaped ones in one line

Time:11-16

The code below returns a matrix that is filled with zeros, and both diagonals are ones, which creates an X shape. I want to make a one-liner for the code between the lines, anybody knows how to do that?

def mat(size):
# --------------------------------
m = np.zeros((size, size))
for i in range(size):
    for j in range(size):
        if i == j:
            m[i, j] = 1

for i in range(size):
    m[i, size - i - 1] = 1
# --------------------------------
return m

What i have come up with is the code below, but that's 2 lines. The reason for m[m > 1] = 1 is when the size is an odd number the middle number becomes 2.

def mat(size):
    m = np.eye(size)   np.flip(np.eye(size), axis=1)
    m[m > 1] = 1
    return m

example matrix:

[[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]]

Thank you

CodePudding user response:

You can use np.bool_:

def mat(size):
    return 1 * np.bool_(np.eye(size)   np.flip(np.eye(size), 1))

OR, proposed by user3483203

def mat(size):
    return (np.eye(5)   np.flip(np.eye(5), axis=1) > 0).view('i1')

Output:

>>> mat(5)
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]])

CodePudding user response:

How about this?

def mat(size):
    return np.minimum(np.eye(size) np.eye(size)[::-1], 1)
  • Related