You can add the following print statement, and the loop will explain itself at each iteration:
n=4
matrix=np.zeros((n,n))
for i in range (0,n):
for j in range(0,i+1):
print(f'inserting {i-j+1} into the matrix at row index {i}, columns index {j}')
matrix[i,j]=i-j+1
When you run it, you get this output:
inserting 1 into the matrix at row index 0, columns index 0
inserting 2 into the matrix at row index 1, columns index 0
inserting 1 into the matrix at row index 1, columns index 1
...
inserting 3 into the matrix at row index 3, columns index 1
inserting 2 into the matrix at row index 3, columns index 2
inserting 1 into the matrix at row index 3, columns index 3
And your matrix is populated as before:
>>> matrix
array([[1., 0., 0., 0.],
[2., 1., 0., 0.],
[3., 2., 1., 0.],
[4., 3., 2., 1.]])
Just for reference:
>>> matrix
array([[1., 0., 0., 0.], #<- "row" index 0
[2., 1., 0., 0.], #<- "row" index 1
[3., 2., 1., 0.], #<- "row" index 2
[4., 3., 2., 1.]]) #<- "row" index 3
# ^ ... ^
# "col" 0 "col" 3
i - j + 1whereiis the row index andjis the column index. You need to be more specific about what you don't understand if that does not solve the issue.forloop iterates over the row indices. The innerforloop iterates over the columns, but only up to the column number that is equal to the current row number.