I have an array full of zeros created as A = np.zeros(m,m) and m = 6. I want to fill this array with specific numbers that each equals sum of it's row and column number; such as A(x,y) = x y. How can i do this using for loop and while loop?
CodePudding user response:
A = np.zeros((6,6))
for i in range(0,A.shape[0]):
for j in range(0, A.shape[1]):
A[i][j] = i j 2
If you want the rows and columns to be starting from 1, you can directly use this code, but if you want them to be starting from 0 you can surely remove the " 2" in line-4.
Explanation: I am first traversing the row in a loop when, then traversing the columns in loop 2, and then I am accessing the cell value using A[i][j]. and assigning it to i j 2 (or just i j). This way the original array will fill your new values.
CodePudding user response:
Have you tried this?
for y in range(len(A)):
for x in range(len(A[Y]):
A[y][x] = x y
CodePudding user response:
Method that avoids a loop with rather significant performance improvement on a large ndarray:
A = np.zeros((6,6))
m = A.shape[0]
n = A.shape[1]
x = np.transpose(np.array([*range(1,m 1)]*n).reshape(n,m))
y = np.array([*range(1,n 1)]*m).reshape(m,n)
A = x y
print(A)
[[ 2 3 4 5 6 7]
[ 3 4 5 6 7 8]
[ 4 5 6 7 8 9]
[ 5 6 7 8 9 10]
[ 6 7 8 9 10 11]
[ 7 8 9 10 11 12]]