becs
becs

Reputation: 83

I keep getting the error "index 2 is out of bounds for axis 0 with size 2" in my loop

I'm basically trying to sum a gradient here, see the screenshots I have attached for a better idea. Rho is an nx1 input vector, the screenshot I have attached shows the idea for a 3x1 rho vector but it really has an undefined length.

enter image description here enter image description here

# JACOBIAN 

def derivative(rho, a, A, tilde_k, x, y, vecinc, chi):
    n = rho.shape[0]
    result1 = np.array([n,1],complex)
    result2 = np.array([n,1],complex)
    result = np.array([n,1],complex)
    u = np.zeros((n, 3))
    W_tilde = np.array([3,3],complex)

    loop1 = 0
    loop2 = 0
    for i in range(n):
        for j in range(n):
            u[i] = x[i] - y[j] # n x 3
            W_tilde = A_matrix * chi.imag * A_matrix * G(u[i],k) * A_matrix # 3 x 3

            ei_block = np.exp(1j * np.vdot(x[i], tilde_k)) * vecinc # 3 x 1
            ej_block = np.exp(1j * np.vdot(x[j], tilde_k)) * vecinc # 3 x 1
            eiT_block = np.matrix.getH(ei_block) # 1 x 3
            mm = np.matmul(W_tilde, ej_block) # (3 x 3)(3 x 1) = 3 x 1
            alpha_tilde = np.dot(eiT_block, mm) # (1 x 3)(3 x 1) = 1 x 1 = scalar

            loop1 = loop1 + (2 * rho[i] * alpha_tilde * rho[j]) # scalar 

            if (i != j):  
                loop2 = loop2 + ((rho[j]**2) * alpha_tilde) # scalar
        result1[i] = loop1 
        result2[i] = loop2

    result = result1 + result2 # (n x 1) + (n x 1) = n x 1 vector

    return result

I am getting "IndexError: index 2 is out of bounds for axis 0 with size 2" for the line, result1[i] = loop1. Pls help :(

Upvotes: 2

Views: 3069

Answers (1)

Michael
Michael

Reputation: 2414

That error means that you are attempting to access the third element (index 2) of an array with only two elements (size 2).

It looks like you're defining your arrays in a funny way; np.array([n,1],complex) creates an array of length 2, not n. What you want is probably np.zeros(n,complex), which will create an n-length array filled with 0s.

Upvotes: 1

Related Questions