36
import numpy as np

with open('matrix.txt', 'r') as f:
    x = []
    for line in f:
        x.append(map(int, line.split()))
f.close()

a = array(x)

l, v = eig(a)

exponent = array(exp(l))

L = identity(len(l))

for i in xrange(len(l)):
    L[i][i] = exponent[0][i]

print L
  1. My code opens up a text file containing a matrix:
    1 2
    3 4
    and places it in list x as integers.

  2. The list x is then converted into an array a.

  3. The eigenvalues of a are placed in l and the eigenvectors are placed in v.

  4. I then want to take the exp(a) and place it in another array exponent.

  5. Then I create an identity matrix L of whatever length l is.

  6. My for loop is supposed to take the values of exponent and replace the 1's across the diagonal of the identity matrix but I get an error saying

    invalid index to scalar variable.

What is wrong with my code?

1
  • 3
    post the traceback please :) Commented Nov 27, 2012 at 22:43

3 Answers 3

31

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

Sign up to request clarification or add additional context in comments.

Comments

9

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

1 Comment

@hoangtran, to fix it you have to fix your code. There is no meaningful result that 5[2] can give you. Somewhere, you think that an array has 1 more dimension than it really does.
2

In my case, I was getting this error because I had an input named x and I was creating (without realizing it) a local variable called x. I thought I was trying to access an element of the input x (which was an array), while I was actually trying to access an element of the local variable x (which was a scalar).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.