1

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?

1
  • could you post the code of what you have tried? Commented Jun 14, 2022 at 12:03

3 Answers 3

2

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]]
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

1

Have you tried this?

for y in range(len(A)):
  for x in range(len(A[Y]):
    A[y][x] = x + y

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.