Home > OS >  How to make a matrix with a size of 2 cells?
How to make a matrix with a size of 2 cells?

Time:05-03

How to make a matrix with a size of 2 cells?

I need a matrix like a chessboard but with two cells in one place

the matrix should have size n X m, cells size 2 X 2 I wrote this code: [In]:

def mat(n, m):
    sq = np.zeros((n, m))
    sq[::2, 1::2] = 1
    sq[1::2, ::2] = 1
    a = str(sq).replace('.', '')
    print(a)
mat(10, 10)

[Out]:

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

but I need it like this:

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

CodePudding user response:

You've got the right idea; you just need to fix up the indexing a little bit. Instead of using a step of 2, you need to use two slices with steps of four to create a "take two, skip two" pattern:

sq[::4, 2::4] = 1
sq[::4, 3::4] = 1
sq[1::4, 2::4] = 1
sq[1::4, 3::4] = 1

sq[2::4, ::4] = 1
sq[2::4, 1::4] = 1
sq[3::4, ::4] = 1
sq[3::4, 1::4] = 1

This outputs:

[[0 0 1 1 0 0 1 1 0 0]
 [0 0 1 1 0 0 1 1 0 0]
 [1 1 0 0 1 1 0 0 1 1]
 [1 1 0 0 1 1 0 0 1 1]
 [0 0 1 1 0 0 1 1 0 0]
 [0 0 1 1 0 0 1 1 0 0]
 [1 1 0 0 1 1 0 0 1 1]
 [1 1 0 0 1 1 0 0 1 1]
 [0 0 1 1 0 0 1 1 0 0]
 [0 0 1 1 0 0 1 1 0 0]]
  • Related