Sample code in flattening post doesn't run

@paulinpaloalto

I have seen your post about flattening an image. I want to play around with the code snippet that you provided in this thread:

If I try to run a cell like this one:

import numpy as np

# routine to generate a telltale 4D array to play with
def testarray(shape):
     (d1,d2,d3,d4) = shape
     A = np.zeros(shape)

for ii1 in range(d1):
    for ii2 in range(d2):
        for ii3 in range(d3):
            for ii4 in range(d4):
                A[ii1,ii2,ii3,ii4] = ii1 * 1000 + ii2 * 100 + ii3 * 10 + ii4 

return A

A = testarray((3,2,2,3))
Ashape1 = A.reshape(A.shape[0],-1).T
Ashape2 = A.reshape(-1,A.shape[0])
np.set_printoptions(suppress=True)
print("A.shape = " + str(A.shape))
print(A)
print("Ashape1.shape = " + str(Ashape1.shape))
print(Ashape1)
print("Ashape2.shape = " + str(Ashape2.shape))
print(Ashape2)

I get the following error:

NameError                                 Traceback (most recent call last)
<ipython-input-1-06a7c2dc17c6> in <module>
      6      A = np.zeros(shape)
      7 
----> 8 for ii1 in range(d1):
      9     for ii2 in range(d2):
     10         for ii3 in range(d3):

NameError: name 'd1' is not defined

Can you please help me get your code to run? Many thanks.

The indentation is wrong so that the “for” statement that is throwing the error is not part of the function. Indentation matters in python.

Oh, sorry, I just realized that this is my mistake! I didn’t copy/paste it correctly in the original post. I will fix it right now. Here is the correct version:

# routine to generate a telltale 4D array to play with
def testarray(shape):
    (d1,d2,d3,d4) = shape
    A = np.zeros(shape)

    for ii1 in range(d1):
        for ii2 in range(d2):
            for ii3 in range(d3):
                for ii4 in range(d4):
                    A[ii1,ii2,ii3,ii4] = ii1 * 1000 + ii2 * 100 + ii3 * 10 + ii4 

    return A

Thank you for pointing out my error so that I could correct it!

Many thanks for the fast reply. Now it worked.