Isaac
Isaac

Reputation: 925

IndexError: invalid index to scalar variable for double 'for' statement

My purpose is to calculate the list of certain variable repetitively using for statement inside of for statement.

My code is as follows.

for b in range(0,1487):
    c = 18000*b
    alpha = np.arctan(np.mean(v[c:c+18000])/np.mean(u[c:c+18000]))
    beta = np.arctan(np.mean(w[c:c+18000])/np.mean(u[c:c+18000]))
    R01 = R01.reshape((3,3))

    for c1 in range(c,c+18000):
            windvector = np.array([u[c1],v[c1],w[c1]])
            WV = windvector.reshape((3,1))
            m = np.dot(R01,WV)
            m = m.reshape((1,3))
            m = list(m)
            M = M + m
    for c2 in range(0,18000):
            u = M[c2][0]

            A = A + [u]
    m1 = np.mean(A[0:3000])
    m2 = np.mean(A[3000:3000*2])
    m3 = np.mean(A[3000*2:3000*3])
    m4 = np.mean(A[3000*3:3000*4])
    m5 = np.mean(A[3000*4:3000*5])
    m6 = np.mean(A[3000*5:3000*6])

    M = [m1,m2,m3,m4,m5,m6]

    s1 = np.std(A[0:3000])
    s2 = np.std(A[3000:3000*2])
    s3 = np.std(A[3000*2:3000*3])
    s4 = np.std(A[3000*3:3000*4])
    s5 = np.std(A[3000*4:3000*5])
    s6 = np.std(A[3000*5:3000*6])

    S = [s1,s2,s3,s4,s5,s6]

    RN = fabs((np.mean(S)-np.std(A))/np.std(A))

    RNT = RNT + [RN]

As shown in the code, I would like to get 1487 RN values repetitively, but when I ran this code, this stopped just after 1 rotation among expected 1487, showing the error message of "File "RN_stationarity.py", line 25, in alpha = np.arctan(np.mean(v[c:c+18000])/np.mean(u[c:c+18000])) IndexError: invalid index to scalar variable."

I am not sure why I got this kind of error. I tried few solution in stackoverflow, but it didn't work.

Would you please give some idea or help?

It will be really appreciated.

Thank you,

Isaac

Upvotes: 2

Views: 21050

Answers (1)

abarnert
abarnert

Reputation: 365777

Your problem is that you use the name u for two completely different values. At the start of this loop, it's a nice big array, but in the middle of the loop you reassign it to a scalar, hence the IndexError when you try to index it the next time through the loop.


From the comments:

u should have total 1487*18000 numbers which I already checked

So, that's how I know it starts off valid.

But then in the middle of the loop:

for c2 in range(0,18000):
        u = M[c2][0]

        A = A + [u]

From other comments, M is a 2D array. So, after this loop, u is a 0D array (that is, a scalar).


The solution is to just not use the name u for two unrelated things. Rename one of them to something else.

More generally, the solution is to not use meaningless one-letter variable names, because when you do that, it's very hard to avoid accidentally reusing one, and also hard to tell when you've done so.

Upvotes: 3

Related Questions