Skip to content Skip to sidebar Skip to footer

Fill Two-dimensional List With Values Instead Of Initializing It First With Zeros

I have a two-dimensional array that I want to fill up with values that represent powers but my problem lies in the speed of the code because the two-dimensional array is 100x100 si

Solution 1:

OK, first, you want to create a NumPy array, not a list of lists. This is almost always going to be significantly smaller, and a little faster to work on. And, more importantly, it opens the door to vectorizing your loops, which makes them a lot faster to work on. So, instead of this:

Z_old = [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0]]

… do this:

Z_old = np.zeros((3, 5))

But now let's see whether we can vectorize your loop instead of modifying the values:

for each_axes in range(len(Z_old)):
    for each_point in range(len(Z_old[each_axes])):
        Z_old[len(Z_old)-1-each_axes][each_point] = each_point**2 + each_axes**2

The initial values of Z[…] aren't being used at all here, so we don't need to pre-fill them with 0, just as you suspected. What is being used at each point is r and c. (I'm going to rename your Z_old, each_axes, and each_point to Z, r, and c for brevity.) In particular, you're trying to set each Z[len(Z)-1-r, c] to r**2 + c**2.

First, let's reverse the negatives so you're setting each Z[r, c] to something—in this case, to (len(Z)-1-r)**2 + c**2.

That "something" is just a function on r and c values. Which we can get by creating aranges. In particular, arange(5) is just an array of the numbers 0, 1, 2, 3, 4, and arange(5)**2 is an array of the squares 0, 1, 4, 9, 16.

The only problem is that to get a 3x5 array out of this, we have to elementwise add two 2D arrays, a 3x1 array and a 1x5 array, vice-versa, but we've got two 1D arrays from arange. Well, we can reshape one of them:

Z_old = (3 - 1 - np.arange(3))**2 + (np.arange(5)**2).reshape((5, 1))

You can, of course, simplify this further (you obviously don't need 3 - 1, and you can just add a new axis without reshape), but hopefully this shows directly how it corresponds to your original code.

Post a Comment for "Fill Two-dimensional List With Values Instead Of Initializing It First With Zeros"