简体   繁体   中英

IndexError: list index out of range in for loop python

I am trying to run a for loop which is below, unfortunately it throws me an error in the first time itself. i managed to assigned a zero value to the variable but then have this error xest[i] = xprediction + K * y[i] - np.multiply(H, xprediction) ValueError: could not broadcast input array from shape (2,2) into shape (1,1)

x1 = np.zeros(len(t))
x2 = np.zeros(len(t))
K = np.zeros(len(t))
x1p_1 = np.zeros(len(t))
x2p_1 = np.zeros(len(t))
x1e = np.zeros(len(t))
x2e = np.zeros(len(t)) 
y = np.zeros(len(t))

for i in range (1,25):
    print("",i)
    if i < 10:
        u = 0.25
    else:
        u = 0.0

    x1[i] = x1[i] + (dt*x2[i]) + (dt**2/2)*u
    x2[i] = x2[i] + dt*u + math.sqrt(Q)*np.random.normal()

    y[i] = x1[i] + math.sqrt(R) * np.random.normal()

    PP = (A.dot(PE).dot(A_trans)) + (G.dot(Q).dot(G_trans))
    K = (PP.dot(H_trans)).dot(np.linalg.inv(H.dot(PP.dot(H_trans) + R)))
    ident = np.identity(2)
    PE = (ident - K.dot(H)).dot(PP)

    xprediction = A.dot(xest) + B.dot(u)
       xest[i] = xprediction + K * y[i] - np.multiply(H, xprediction)

    """This equations are basically   
    x1e(i+1) = [1 0] * xest
    x2e(i+1) = [0 1] * xest"""

    sol_1 = np.matrix('%s %s' % (1, 0))
    sol_2 = np.matrix('%s %s' % (0, 1))
    x1e[i] = np.multiply(sol_1, xest[i])
    x2e[i] = np.multiply(sol_2, xest[i])


    print("",x1[i])
  1
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-74-6ccc7c6deb33> in <module>
      6         u = 0.0
      7 
----> 8     x1[i] = x1[i] + (dt*x2[i]) + (dt**2/2)*u
      9     x2[i] = x2[i] + dt*u + math.sqrt(Q)*np.random.normal()
     10 

IndexError: list index out of range

Can somebody explain this to me, I really appreciate that.

Since the error is being thrown in the first run of the for loop, it seems like x1 and x2 have yet to be assigned values. You can fix this error by appending the arrays instead of using an assignment operator which can be done by writing the following

for i in range (1,25):
    print("",i)
    if i < 10:
        u = 0.25
    else:
        u = 0.0

    x1.append((dt*x2[i]) + (dt**2/2)*u)
    x2.append(dt*u + math.sqrt(Q)*np.random.normal())

    y.append(math.sqrt(R) * np.random.normal())

There isn't much more I can provide in terms of help, unless you edit your answer to include the declaration and assignment of x1 and x2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM