import numpy as np
def readMatrix(filename):
rows = []
for line in open(filename):
columns = []
for number in string.split(line):
columns.append(float(number))
rows.append(columns)
return numpy.array(rows)
def writeMatrix(a, filename):
f = open(filename, 'w')
for row in a:
for number in row:
f.write(str(number) + ' ')
f.write('\n')
f.close()
def TaylorMatrixExp(A):
I = identity(len(A))
return (I + A + (1./2.)*(dot(A,A)) + (1./6.)*(dot(dot(A,A),A)) + (1./24.)*(dot(dot(A,A),dot(A,A))))
A = readMatrix('matrix.txt')
l, v = eig(A)
L = identity(len(l))
for i in xrange(len(l)):
L[i][i] = array(exp(l))[i]
VLV = dot(dot(v,L),inv(v))
writeMatrix(VLV,'expA.txt')
ExponentA = TaylorMatrixExp(A)
writeMatrix(ExponentA,'expA.txt')
它读取的矩阵是:
2 2
16 6
我已经定义了两个3个函数,readMatrix(从文本文件中读取矩阵),writeMatrix(将矩阵写入文件)和TaylorMatrixExp(接受数组并扩展它)。我最初使用readMatrix读取包含上述矩阵的文本文件并将其放在数组A中。我取A的特征值并将其放在数组l中以及A的特征向量并将其放在数组v中。我最终放置值在单位矩阵的对角线上的数组l的然后我调用writeMatrix函数并将指数写入'expA.txt'然后再次调用writeMatrix函数并将矩阵ExponentA写入'expA.txt'。但是,它取代了原始矩阵,我不希望它这样做。
我希望它写入文件
some# some#
some# some#
some#2 some#2
some#2 some#2
但它取代了第一个矩阵
some#2 some#2
some#2 some#2