Ask Your Question

Add commas after matrix-elements in matrix()

asked 2019-12-25 20:06:27 +0200

geroyx gravatar image

updated 2019-12-25 23:21:51 +0200

I want to replace the brackets, but to add commas after each matrix-element, except the last ones in the rows.

I get only the first part.

Is there an elementary way to add commas to the sage-matrix?
Because matrix() has the great advantage that the elements are aligned in all cases.

m = matrix([[2222,333,44444], [1,0,0]])
mymatrix =  m.str().replace('[', '').replace(']', '') # replace [, ]
#....  # add commas
print mymatrix

Out Actual:

 2222   333 44444
    1     0     0

Out Target:

 2222,   333, 44444
    1,     0,     0
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2019-12-31 06:24:09 +0200

updated 2020-01-01 05:32:21 +0200

I think you should continue to manipulate m.str(), but using regular expressions, since m.str() already has the correct spacing. The following will work if you know that the matrix entries will be numbers (plus a possible decimal point and/or minus sign), no letters:

import re
m = matrix([[2222,333,44444], [1,0,0]])
no_brackets =  m.str().replace('[', '').replace(']', '') # replace [, ]
add_commas = re.sub("([-.0-9]+) ", "\\1, ", no_brackets)


 2222,   333, 44444
    1,     0,     0
edit flag offensive delete link more


@JohnPalmieri And this runs for you? I get NameError: name 're' is not defined

geroyx gravatar imagegeroyx ( 2019-12-31 15:16:30 +0200 )edit

Sorry, I forgot to add import re. I will edit the answer.

John Palmieri gravatar imageJohn Palmieri ( 2020-01-01 05:32:10 +0200 )edit

Alternatively, this should work for more general matrix entries: m.str(rep_mapping=lambda a: str(a) + ",").replace('[', '').replace(',]', '')

mwageringel gravatar imagemwageringel ( 2020-01-01 18:16:46 +0200 )edit

answered 2019-12-25 20:46:38 +0200

dsejas gravatar image

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!

edit flag offensive delete link more


@dsejas Thank you for your answer, and that's a good explanation too! However, I wonder if there is a way to "hack" the Sage matrix with commas. Because matrix() has the great advantage that the elements are "aligned" in all cases (this is not the case with the string method as far as I know); my numerical example was not well chosen; I will edit a better one.

geroyx gravatar imagegeroyx ( 2019-12-25 23:15:47 +0200 )edit

Hello, @geroyx! I'm sorry I didn't understand the purpose of your question. There are two things you can do:

  • You can define a new function like in this code. By overwriting sage.typeset.symbols.ascii_left_square_bracket and sage.typeset.symbols.ascii_right_square_bracket, you force Sage to not show the brackets. The comma separation is tricky; the only way to cope with that without re-coding Sage is to use a function like this.
  • Next comment.
dsejas gravatar imagedsejas ( 2019-12-26 04:59:15 +0200 )edit
  • If you really want Sage to automatically do what the function in point 1 does, you have to re-code or hack a part of Sage tself. I can help with that, actually. I have modified the file <SAGE>/src/sage/matrix/matrix0.pyx, which is a Cython file, in order to handle the representation of matrices in Sage. The function str is the responsible for that. So, I rewrote it to avoid using delimiters around matrices, and add a comma between elements. You can find the modified code here. Find the mentioned file (<SAGE>/src/sage/matrix/matrix0.pyx, where <SAGE> indicates the folder where you installed or decompressed Sage), go to line 1758, delete the str function, and replace it with my code. Finally, execute sage -b so the new code is compiled.
dsejas gravatar imagedsejas ( 2019-12-26 05:18:24 +0200 )edit

Please, let me know which of these approaches is what you want, so I can update my answer. Feel free to ask if you have any question.

dsejas gravatar imagedsejas ( 2019-12-26 05:38:17 +0200 )edit

what about simply:

list(m)  ?
ortollj gravatar imageortollj ( 2019-12-26 10:31:26 +0200 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2019-12-25 20:06:27 +0200

Seen: 913 times

Last updated: Jan 01 '20