0

I am trying to get the output of a nested for loop into an array or matrix. For instance, in the code example below, I want to have a (3 by 2)-matrix of the form:

[[5 6],
 [6 7],
 [7 8]]

But my code is giving out of bound error.

import numpy as np

num = [1,2,3]
sep = [4, 5]
M = np.zeros((3,2))
for i in num:
    for j in sep:
        M[i, j] = i + j
M

However, I realized that changing the initialization to np.zeros((4,6)) seems to work but with some irrelevant cells. Can someone explain how this works or possibly how I can achieve this (3 by 2)-matrix.Nested_Loop

1
  • for j in sep: with sep = [4, 5] results in that j becomes 4 in first iteration and 5 in second. So, this results in M[i, 4] or M[i, 5] which is an out of bound access for a 3x2 matrix, isn't it. Somehow, you confused the iteration "index" with the value picked from given list in iteration. Commented Oct 24, 2020 at 12:06

1 Answer 1

2

You are using the values in your num and sep lists as indexes. You need to use indexes instead:

import numpy as np

num = [1,2,3]
sep = [4, 5]
M = np.zeros((3,2))
for i_i,i in enumerate(num):
    for i_j,j in enumerate(sep):
        M[i_i, i_j] = i + j

print(M)

Output as required.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.