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.
for j in sep:withsep = [4, 5]results in thatjbecomes4in first iteration and5in second. So, this results inM[i, 4]orM[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.