2012-11-27 33 views
16
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 2
3 4
,並將其放置在列表中的「x」爲整數。列表「x」然後被轉換成數組「a」。 「a」的特徵值置於「l」中,特徵向量置於「v」中。然後我想把exp(a)放到另一個數組「exponent」中。然後我創建一個任意長度爲「l」的單位矩陣,並稱之爲矩陣「L」。我的for循環假設採用「指數」的值並將1代入單位矩陣的對角線,但我得到一個錯誤,說「無效的標量變量索引」。我的代碼有什麼問題?有一個標量變量錯誤的索引是什麼意思?蟒蛇

+2

請回復追蹤:) –

回答

12

exponent是一維數組。這意味着是一個標量,而exponent[0][i]正在嘗試訪問它,就好像它是一個數組。

你的意思是說:

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

甚至

L = diag(exponent) 

+0

謝謝soooo多!解決了我的問題!這正是我的意思。 – Randy

6

IndexError: invalid index to scalar variable發生在您嘗試索引numpy標量(例如numpy.int64numpy.float64)時。當您嘗試索引int時,它與TypeError: 'int' object has no attribute '__getitem__'非常相似。

>>> 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__' 
+0

以及如何解決此錯誤?謝謝! –

+2

@hoangtran,要解決它,你必須修復你的代碼。 '5 [2]'可以給你沒有意義的結果。在某個地方,你認爲一個數組的維數比實際多一維。 – Akavall

相關問題