Skip to content
Advertisement

Updating a 2D Array with the output results of a nested loop in Python

I have a nested loop where I calculate 10 distances, and store them in an array b_array. Then into a_array another array which will is to keep the results for every image. The problem is that my code overwrites a_array for every iteration even when it is outside the main function when I checked with print. Therefore, I end up with the exact same result of the last executed file in the loop for all 4 images.

distances = np.linspace(min_distance, max_distance, 10)
a_array = np.zeros((4,10))
  
    for x in range (0, 4):
        b_array = np.zeros(10)
        for y in range(0,10):
            b_array[y] = mean_intensity(distances)#local function
        a_array[x] = b_array
        print(a_array)

Advertisement

Answer

If you want a (4,10) array with each row as evenly spaced numbers, then you could do: np.linspace([min_distance]*4, [max_distance]*4, 10, axis=1), which would have the same effect as:

min_distance = 0
max_distance = 10
a_array = np.zeros((4,10))

for x in range (0, 4):
    b_array = np.linspace(min_distance, max_distance, 10)
    a_array[x] = b_array
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement