Reputation: 103
I am using for loops to iterate through the indices in a NumPy zeros array and assign some indices with the value 0.5. At the moment, my code returns the error message:
IndexError: index 1 is out of bounds for axis 0 with size 1
Below is a simplified version of my code which reproduces the error.
import numpy as np
Z = np.zeros((1560, 1560))
linestart = {1: [175], 2: [865]}
noycuts = 2
cutno = int(0)
for i in range(noycuts):
cutno = cutno + 1
xstart = linestart[cutno]
ystart = 0
for j in range(1560):
Z[xstart][ystart] = 0.5
ystart = ystart + 1
I've checked questions from people with the same error code, although these issues seem to stem from how the array was originally called; I don't think this is my problem.
Can anyone see the flaw in my code that is causing the error message?
I hope I have provided enough information.
Thanks in advance.
Upvotes: 1
Views: 3398
Reputation: 1096
With linestart = {1: [175], 2: [865]}
you define a dict containing lists with single entrys. I belive you actually want the dict to contain ints. Also ystart should start with zero. Does the following do what you want:
import numpy as np
Z = np.zeros((1560, 1560))
linestart = {1: 175, 2: 865}
noycuts = 2
cutno = 0
for i in range(noycuts):
cutno += 1
xstart = linestart[cutno]
ystart = 0
for j in range(1560):
Z[xstart][ystart] = 0.5
ystart = ystart + 1
Also consider the following which is a shorter version:
for cutno,xstart in linestart.items():
for ystart in range(Z.shape[1]):
Z[xstart][ystart] = 0.5
Upvotes: 0
Reputation: 2306
Edit:
My original answer was:
Replace
Z[xstart][ystart] = 0.5
with
Z[xstart, ystart] = 0.5
But actually, the problem is, that your xstart is an array. Leave your original code, but replace
linestart = {1: [175], 2: [865]}
with
linestart = {1: 175, 2: 865}
or, better:
linestart = [175, 865]
Upvotes: 1