Home > Blockchain >  How do I create a binary matrix with a specific repeating pattern of 1s and 0s?
How do I create a binary matrix with a specific repeating pattern of 1s and 0s?

Time:08-24

I want to efficiently print a matrix in Python that follows a repeating specific pattern in the columns of 3 1s in a column, the rest of the columns 0s then the column 1s switch and so on for 1000 rows as shown below:

100000
100000
100000
010000
010000
010000
001000
001000
001000
000100
000100
000100
000010
000010
000010
000001
000001
000001
100000
100000
100000
010000
010000
010000
 ...

CodePudding user response:

First, you can create a diagonal matrix of size (6, 6) with only ones on the diagonal:

>>> arr = np.diag(np.ones(6))

Then, you can repeat each rows of that matrix 3times:

>>> arr = np.repeat(arr, repeats=3, axis=0)
>>> arr
[[1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 1.]]

Finally, use np.tile to tile this matrix the number of times you want. In your case, as you want 1000 rows, you can repeat the array 1000 // 18 1 = 56 times, and only keep the first 1000 rows.

>>> arr = np.tile(arr, (56, 1))[:1000]

CodePudding user response:

Build an identity matrix, and then take out the matrix you need by generating the row indices (elegant but inefficient):

>>> np.eye(6, dtype=int)[np.arange(1000) // 3 % 6]
array([[1, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0],
       [1, 0, 0, 0, 0, 0],
       ...,
       [0, 0, 1, 0, 0, 0],
       [0, 0, 1, 0, 0, 0],
       [0, 0, 0, 1, 0, 0]])
  • Related