Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to have an index to scalar variable error? python

Tags:

python

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?

like image 818
Randy Avatar asked Nov 27 '12 22:11

Randy


People also ask

How do you fix an invalid index and a scalar variable?

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.

What is scalar variable in Python?

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.

What do you mean by scalar 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.


2 Answers

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) 

?

like image 175
NPE Avatar answered Sep 28 '22 16:09

NPE


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__'
like image 44
Akavall Avatar answered Sep 28 '22 18:09

Akavall