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”。但是,它替换了原始矩阵,我不希望它这样做。
and I want it to write to a file
some# some#
some# some#
some#2 some#2
some#2 some#2
but instead it replaces the first matrix
some#2 some#2
some#2 some#2