# Saving Matrices/Lists as Strings

I would like to save .txt file with string matrices, possibly doing some string replacement the matrices delimiters and arranging output for symbolic expressions. For example:

matrix = {{a,b1 b2},{c1/c2,d}}


And I would like to output this to a txt file in the format

"((a,b1*b2),(c1/c2,d))"


Output is more crucial here since I can replace it later using some other tool, but I would assume replacing such strings would also be easy from within Mathematica? Also I reckon that the "space" representation of multiplicatoin might be a bit tricky?

Thanks

• It would help to know what you have tried. May 19 '20 at 16:24

The essence of this method is to realize that InputForm matches quite well your desired format. This format is supported by ToString, so both

ToString[b1 b2, InputForm]


b1*b2

and

ToString[c1/c2, InputForm]


c1/c2

work as desired. Hence one way is:

matrix = {{a,b1 b2},{c1/c2,d}};
stringmatrix =
StringReplace[ToString[matrix, InputForm], {"{" -> "(", "}" -> ")"}]


((a, b1*b2), (c1/c2, d))

Export["matrix.txt", stringmatrix]


Note that this will contain whitespaces, so you might want to delete those. You can do this by adding Whitespace -> "" to the list of replacement rules in StringReplace.

• Ok thanks, this works but I guess my example wasnt general enough...what if I have symbolic fractions in my expressions and I would like those to display with forward slash, say "a/b"? May 19 '20 at 16:37
• Please edit your questions so that it actually contains what you want to know... I can edit my answer accordingly. May 19 '20 at 17:00
• Yes, I have edited it. Many thanks. May 19 '20 at 18:11
• Please see my edit. May 19 '20 at 20:22