Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Hello, @geroyx! A little bit of string processing can help you to cope with this. Let us define the following function:

def mat2str(m):
    mat = [] # a list of the rows
    for i in range(m.nrows()):
        row = [] # list of the elements of a row
        for j in range(m.ncols()):
            row.append(str(m[i,j])) # convert element j in row i to str and append it to "row"
        mat.append(', '.join(row)) # use ", " between two elements in "row" and append to "mat"
    return '\n'.join(mat) # add a new line character between each row in "mat" and return

Then, you can write

m = matrix([[0,0,1], [1,0,0]])
print mat2str(m)

in order to obtain

0, 0, 1
1, 0, 0

Alternatively, here is another approach to defining str2mat:

def mat2str(m):
    mat = '\n'.join([', '.join([str(m[i,j]) for j in range(m.ncols())]) for i in range(m.nrows())])
    return mat

This is more direct, but far less difficult to read.

I hope this helps!