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?
To solve the invalid index to scalar variable error, programmers must keep a close eye at writing the index value and number of square brackets.
A variable containing a single value is a scalar variable. Other times, it is convenient to assign more than one related value to a single variable. Then you can create a variable that can contain a series of values. This is called an list variable.
Scalar variables are used to represent individual fixed-size data objects, such as integers and pointers. Scalar variables can also be used for fixed-size objects that are composed of one or more primitive or composite types. D provides the ability to create both arrays of objects as well as composite structures.
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)
?
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__'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With