convert list to str and write in new .mtx file

Viewed 58

I have this code, that would prompt the user for an .mtx file (e.g. Mydata.mtx) that contain a matrix of integers. the program would take this matrix, transpose it, then create a new file with the transposed matrix. the file is a simple .mtx file. the original file (Mydata.mtx):

1 2 3 4 5
6 7 8 9 10
11 12 13 14 15 #separated by a tap "\t" to be a matrix

here is the code:

def readMatrix(filename):
    listOfLists = []
    file = open(filename)
    for i in file:
        listOfLists.append(i.split())
    return listOfLists


def transpose(M):
    mtranspose = [list(i) for i in zip(*M)]
    return mtranspose


def writeMatrix(M, filename):
    for i in M:
        convertListToStr = str(i)
    newFile = open("T_" + filename, "w")
    newFile.write(convertListToStr)
    newFile.close()


callFile = input("Enter the file name: ")
toReadFile = readMatrix(callFile)
toTranspose = transpose(toReadFile)
ToWriteMatrix = writeMatrix(toTranspose, callFile)

the code functions, in that it transposes the matrix and creates a new file. so the problems is in the third function writeMatrix in for i in M as it does not print out the whole matrix but only last line in list form. I need it in a string form.

my output (in the new file): T_Mydata.mtx

['5', '10', '15']

desired output:

1 6 11
2 7 12 
3 8 13 
4 9 14 
5 10 15

can anyone help?

1 Answers

You need to write each row in the matrix as you loop over them, you also need to join each element in the row instead of converting the entire row to a string

def writeMatrix(M, filename):
    with open("T_" + filename, "w") as f:
        for row in M:
            f.write(" ".join(row) + "\n")
Related