简体   繁体   中英

The error “only length-1 arrays can be converted to Python scalars” when trying to multiply matrix elements within a loop?

The function alpha_j should return a 3x3 matrix. The input A, is a block diagonal matrix and a is a scalar, (V_0 * 3 * chi)/(chi + 3). Rho is a random 3x1 matrix.

I am trying to create this 3x3 matrix by multiplying rho, the scalar alpha, and the matrix A together.

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    rho = np.random.rand(3,1)
    for i in range(0, 2):
        for j in range(0, 2):
            alph[i][j] = (rho[i] * a * A[i][j])
    return alph

chi = 10 + 1j
V_0 = (0.05)**3
alpha = (V_0 * 3 * chi)/(chi + 3)
A = np.matlib.identity(3)

test = alpha_j(alpha, A)
print(test)

I keep getting thrown the error "only length-1 arrays can be converted to Python scalars." I don't understand what is wrong. pls help :/

Your indexing seems to be incorrect. You're using [i][j] when you need to use [i,j] for numpy arrays.

>> A = np.matlib.identity(3)
>> A
matrix([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])

>> A[0][0]
matrix([[1., 0., 0.]])
>> A[0,0]
1.0

Thus, you're getting a row vector when you're expecting a scalar.

I should mention that a Google search on your error message turned up TypeError: only length-1 arrays can be converted to Python scalars while plot showing , which was helpful.

It's also good practice to print(type(suspect_thing)) or set breakpoints and use the debugger to inspect variables as you go. That can bubble these problems up right where you can see them. I, for example, copied your code into my editor and ran it, noting the line number where things went wrong. I was then able to see which variables needed checking out.

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