I would like to create a 2D array look something like this using a loop in python:
[[1,0,0,0,0,0]
[0,1,0,0,0,0]
[0,0,1,0,0,0]
[0,0,0,1,0,0]
[0,0,0,0,1,0]
[0,0,0,0,0,1]]
1's index increase by 1 next row and rest of elements in array is filled 0.
I would like to create a 2D array look something like this using a loop in python:
[[1,0,0,0,0,0]
[0,1,0,0,0,0]
[0,0,1,0,0,0]
[0,0,0,1,0,0]
[0,0,0,0,1,0]
[0,0,0,0,0,1]]
1's index increase by 1 next row and rest of elements in array is filled 0.
P.S: There are several ways to construct such a matrix. This is one way of doing it using for loops as you asked. The matrix you need is called an identity matrix
size = 6
arr = [[0]*size for _ in range(size)] # Initialize 6 lists all with zeros
# Now change the value to 1 on the diagonal enteries
for i in range(size):
arr[i][i] = 1
print (arr)
# [[1 0 0 0 0 0]
# [0 1 0 0 0 0]
# [0 0 1 0 0 0]
# [0 0 0 1 0 0]
# [0 0 0 0 1 0]
# [0 0 0 0 0 1]]
Alternative 1 using NumPy: Similar to the above case, initialize a 6x6 matrix of zeros using NumPy and then just replace 0 by 1 on the diagonal.
import numpy as np
size = 6
arr = np.zeros((size, size))
for i in range(size):
arr[i][i] = 1
print (arr)
Alternative 2
import numpy as np
size = 6
arr = np.eye(size)
Alternative 3
np.identity(6)
for i in range(size): arr[i][i] = 1 would be enough.