2
$\begingroup$

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

$\endgroup$
1
  • 1
    $\begingroup$ It would help to know what you have tried. $\endgroup$
    – C. E.
    May 19, 2020 at 16:24

1 Answer 1

4
$\begingroup$

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.

$\endgroup$
4
  • $\begingroup$ 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"? $\endgroup$
    – user191919
    May 19, 2020 at 16:37
  • 3
    $\begingroup$ Please edit your questions so that it actually contains what you want to know... I can edit my answer accordingly. $\endgroup$ May 19, 2020 at 17:00
  • $\begingroup$ Yes, I have edited it. Many thanks. $\endgroup$
    – user191919
    May 19, 2020 at 18:11
  • $\begingroup$ Please see my edit. $\endgroup$ May 19, 2020 at 20:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.