2
$\begingroup$

I am using Mathematica to generate some Matlab code. In order to have a bit of documentation I would like to have a commented line in the Matlab file which holds the Latex form of the original expression. However, there is an issue with linebreaking.

An example:

test = TeXForm[{{a, b, c}, {d, e, f}}]

Looking at test and also ToString@test reveals a couple of linebreaks which are nice for formatting and export to actual Latex documents but not for my purpose. The reason is that I would like to use a string (one line - which may be very long) like "% Expression: " <> ToString@TeXForm@test in the Matlab file ("%" creates comments in Matlab code), which fails because of the linebreaks (only the first row appears as a comment).

So I thought of operating on

test2 = ToString@FullForm@ToString@test
(* "\\left(\n\\begin{array}{ccc}\n a & b & c \\\\\n d & e & f \\\\\n\\\end{array}\n\\right)" *)

where I would then easily replace/delete the \n. Yet, to no avail - see:

StringDelete[test2, "\n"]
(* "\\left(\n\\begin{array}{ccc}\n a & b & c \\\\\n d & e & f \\\\\n\\\end{array}\n\\right)" *)
StringPosition[test2, "\n"]
{}

So I wonder how can I remove the linebreaks from TeXForm and ideally also replace the \\ with \ in the final string. This also seems to be a bit tricky because of Mathematica's special characters in strings.

The final result of something like customTeXForm[test] should be the string \left(\begin{array}{ccc}a & b & c \\d & e & f\\\end{array}\right)

$\endgroup$
  • 1
    $\begingroup$ does StringReplace[ToString[test], { "\n" -> ""}] work? $\endgroup$ – kglr Jul 17 '17 at 10:46
  • $\begingroup$ @kglr In fact, it does. I would bet that I tried it before I asked the question here - but anyway... Thank you very much :) $\endgroup$ – Lukas Jul 17 '17 at 10:49
  • $\begingroup$ in case you decide to keep the question, i posted the comment as an answer. $\endgroup$ – kglr Jul 17 '17 at 10:54
  • $\begingroup$ @kglr Am I missing something or does StringDelete[ToString[test], "\n"] work as well? This whole things seems like a simple mistake. $\endgroup$ – Mr.Wizard Jul 17 '17 at 12:50
  • $\begingroup$ @MrWizard, yes it does! Just didn't occur to me:( $\endgroup$ – kglr Jul 17 '17 at 12:54
4
$\begingroup$
StringReplace[ToString[test], { "\n" -> ""}]

enter image description here

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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