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')
The matrix it reads is:
2 2
16 6
I’ve defined two 3 functions, readMatrix(reads a matrix from a textfile), writeMatrix(writes matrix to a file), and TaylorMatrixExp(takes array and expands it). I initially use readMatrix to read a text file containing the above matrix and place it in array A. I take the eigenvalues of A and place it in array l as well as eigenvectors of A and place it in array v. I eventually place the values of array l across the diagonal of an identity matrix. Then I call the writeMatrix function and write exponent to ‘expA.txt’ and then call writeMatrix function again and write matrix ExponentA to ‘expA.txt’. However, it replaces the original matrix and I don’t want it to do that.
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
Lets you append to the file rather than rewrite it, which is what you’re currently doing with the
'w'argument, which is why that matrix is replaced.