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
Run Code Online (Sandbox Code Playgroud)
我的代码打开一个包含矩阵的文本文件:
1 2
3 4
并将其作为整数放在列表"x"中.然后将列表"x"转换为数组"a"."a"的特征值放在"l"中,特征向量放在"v"中.然后我想把exp(a)放在另一个数组"exponent"中.然后我创建一个长度为"l"的单位矩阵,并调用矩阵"L".我的for循环假设采用"exponent"的值并在单位矩阵的对角线上替换1,但是我得到一个错误,说"标量变量的索引无效".我的代码出了什么问题?
NPE*_*NPE 23
exponent是一维数组.这意味着它exponent[0]是一个标量,并且exponent[0][i]正在尝试访问它,就像它是一个数组一样.
你的意思是说:
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = exponent[i]
Run Code Online (Sandbox Code Playgroud)
甚至
L = diag(exponent)
Run Code Online (Sandbox Code Playgroud)
?
IndexError: invalid index to scalar variable当您尝试索引numpy标量(例如numpy.int64或)时会发生numpy.float64.它与TypeError: 'int' object has no attribute '__getitem__'您尝试索引时非常相似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__'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
110806 次 |
| 最近记录: |