I have a list of coordinates, and a map. For each of these coordinates, I would like to add 10 to the map. If I try to use the plus equal operator, however, it only seems to add once, and then never again. The same behavior happens if I pull it out and add 10 to it, both ways shown below:
coordinates = np.asarray(np.random.randint(0,10,(1000,2)))
map_array = np.zeros((10,10))
map_array[coordinates[:,0], coordinates[:,1]] += 10 #If a coordinate is repeated, it doesn't add 10 to it again
#map_array[coordinates[:,0], coordinates[:,1]] = map_array[coordinates[:,0], coordinates[:,1]] + 10 #same as above
Output of map_array:
[[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.],
[10., 10., 10., 10., 10., 10., 10., 10., 10., 10.]
However, when I iterate through each of the coordinates and add 10 to each one that way, it seems to work fine.
for i in coordinates[:]:
map_array[i[0], i[1]] +=10
Output of map_array:
[[110., 90., 160., 90., 70., 70., 140., 110., 70., 90.],
[ 90., 130., 90., 70., 130., 110., 130., 100., 120., 90.],
[140., 100., 110., 110., 120., 60., 140., 110., 90., 70.],
[120., 90., 130., 110., 120., 90., 100., 170., 100., 100.],
[160., 120., 130., 110., 130., 80., 140., 80., 180., 70.],
[160., 160., 120., 100., 110., 90., 90., 80., 120., 110.],
[120., 100., 120., 80., 90., 130., 130., 60., 90., 90.],
[120., 80., 160., 110., 100., 150., 130., 150., 120., 160.],
[160., 80., 90., 30., 90., 80., 40., 80., 120., 160.],
[130., 120., 80., 90., 80., 160., 130., 180., 100., 130.]]
I think the problem lies with numpy not wanting to select the same index more than once, because if I do this:
coordinates = np.asarray(np.random.randint(0,10,(10,2)))
map_array = np.zeros((10,10))
map_array[coordinates[:,0], coordinates[:,1]] += 10 #only adds once
Output of coordinates :
[[6, 1],
[1, 7],
[5, 5],
[5, 0],
[5, 4],
[7, 3],
[5, 6],
[6, 3],
[3, 2],
[0, 7]]
Output of map:
[[ 0., 0., 0., 0., 0., 0., 0., 10., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 10., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 10., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[10., 0., 0., 0., 10., 10., 10., 0., 0., 0.],
[ 0., 10., 0., 10., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 10., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]
We see that it's not blanket setting all of the elements to 10. Is there a way to not iterate through each element? I would like to use a Numpy builtin for speed.