Reputation: 844
Get a problem There is a double cycle, on the secondary loop we get an array of 10 elements. Then, after each cycle (first), you need to add these elements to the array. At the output, you need to get an array of the form:
result_array = [[inter2d_resultFIRST],[inter2d_resultSECOND],[inter2d_resultTHIRD]]
CODE:
points = np.array([[-100, 0], [100, 0], [100, 300],[-100,300]])
density = 1000
result_array = np.array([])
visual_x = np.array([])
for h in range(3):
points = np.array([[-100, 0], [100, 0], [100, 300],[-100,300]])
inter_result = np.array([])
inter2d_result = np.array([])
poly = [mesher.Polygon(points,{'density': density})]
xp = np.arange(-10000, 10000, 10.0)
zp = np.zeros_like(xp)
for i in range(10):
poly = [mesher.Polygon(points,{'density': density})]
xp = np.arange(-10000, 10000, 10.0)
zp = np.zeros_like(xp)
gz = talwani.gz(xp, zp, poly)
inter_result = np.append(inter_result, np.nanmax(gz))
visual_x = np.append(visual_x, points[1][0]*2)
points[0][0] = points[0][0] - 10
points[1][0] = points[1][0] + 10
points[2][0] = points[2][0] + 10
points[3][0] = points[3][0] - 10
inter2d_result = np.append(inter2d_result,inter_result)
result_array = np.append(result_array[h], inter2d_result)
Get the error:
IndexError Traceback (most recent call last)
<ipython-input-87-c3ef6fe1381b> in <module>()
40
41 inter2d_result = np.append(inter2d_result,inter_result)
---> 42 result_array = np.append(result_array[h], inter2d_result)
43
44
IndexError: index 0 is out of bounds for axis 0 with size 0
Upvotes: 0
Views: 3291
Reputation: 2515
First lets focus on the append operation,
import numpy as np
a = np.array( [1,2,3] )
b = np.array( [4,5,6] )
np.append( a, b )
produces
array( [1, 2, 3, 4, 5, 6] )
What you might want is
np.append( [a], [b], 0 )
which produces
array([ [1, 2, 3], [4, 5, 6] ])
Note that here a 0 appears in the third parameter to specify the axis for the append operation.
Regarding the error, the index h, tells numpy to append to the 'h'-th element. That's probably not what you intended. Also, the index is not correct since 'h' is always one more than the number of elements in the array at the point where the call occurs.
Upvotes: 2
Reputation: 929
I think you're trying to append a value to result_array. You should try without the (h) because what that will do is try to index the value already existing in result_array at index h. But since the array is empty to start so there is no 0th value, and h=0 for the first iteration, so that's why you're getting the error.
Maybe try np.append(result_array, inter2d_result)
Upvotes: 0