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
My code opens up a text file containing a matrix:
1 2
3 4
and places it in list x
as integers.
The list x
is then converted into an array a
.
The eigenvalues of a
are placed in l
and the eigenvectors are placed in v
.
I then want to take the exp(a) and place it in another array exponent
.
Then I create an identity matrix L
of whatever length l
is.
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?
This question is related to
python
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)
?
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).
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__'
Source: Stackoverflow.com