How to import $\LaTeX$ matrices into Mathematica?
I'm assuming the OP wants "\\sqrt{2}"
to turn into the equivalent of $\sqrt{2}$
or $\sqrt{2}$, which would Sqrt[2]
in Mathematica. The command ToExpression[s, TeXForm]
does not seem to handle the square roots, when they are embedded in a matrix, as in the OP's string. The matrix format of TeX is so straightforward that one can split it up into a list of lists almost on the fly:
stripLaTeXCommand[cmd_] := StringDelete[cmd ~~ "{" ~~ Except["}"] ... ~~ "}"];
split[pat_] := StringSplit[#, pat] &;
texToExp = Function[s, ToExpression[s, TeXForm], Listable];
"\\begin{matrix}{0} & {0} & {0}\\\\
{\\sqrt{2}} & {0} & {0}\\\\
{0} & {\\sqrt{2}} & {0}
\\end{matrix}" //
stripLaTeXCommand["\\begin" | "\\end"] //
StringTrim //
split["\\\\"] //
split["&"] //
texToExp
(* {{0, 0, 0}, {Sqrt[2], 0, 0}, {0, Sqrt[2], 0}} *)
Remarks: (1) I'd say mishandling the square roots in a matrix is a bug. (2) Caveat: ToExpression["\\begin{matrix}{0}", TeXForm]
and texToExp["\\begin{matrix}{0}"]
would sometimes return $Failed
(good) and sometimes seemingly get stuck in an infinite loop (bad). I had to kill the kernel (but not the front end) to get back control of Mathematica.
From your InputForm
example, we can see that each row has the same structure. Namely each row has the form
TextCell[Row[List[" ", TextCell[element_, "InlineFormula"], " "]]]
or
TextCell[Row[List[" ", ExpressionCell[element_, "InlineFormula"], " "]]]
where element
is the number in that entry of the matrix.
Then we can take advantage of this and simply replace each outermost TextCell
with the non-string element itself with
TextCell[Row[List[" ", (TextCell | ExpressionCell)[element_, "InlineFormula"], " "]]] :> ToExpression@element
Then we still have the pesky ExpressionCell[TraditionalForm[...]]
to take care of with a simple part specification.
In the case of your example, this turns out to be
mat = ToExpression["\\begin{matrix}{0} & {0} & {0}\\\\
{\\sqrt{2}} & {0} & {0}\\\\
{0} & {\\sqrt{2}} & {0}
\\end{matrix}", TeXForm]
mat /. TextCell[Row[List[" ", (TextCell | ExpressionCell)[element_, "InlineFormula"], " "]]] :> ToExpression@element
%[[1, 1]]
FullForm@%
{{0,0,0},{2,0,0},{0,2,0}}
List[List[0,0,0],List[2,0,0],List[0,2,0]]
And the beauty of this approach is that it readily generalizes (as far as I can tell). For example
ToExpression["\\begin{matrix}{0} & {0} & {0} & {2} \\\\
{\\sqrt{2}} & {0} & {0} & {0} \\\\
{0} & {\\sqrt{2}} & {0} & {7}
\\end{matrix}", TeXForm]
% /. TextCell[Row[List[" ", (TextCell | ExpressionCell)[element_, "InlineFormula"], " "]]] :> ToExpression@element
%[[1, 1]]//FullForm
List[List[0,0,0,2],List[2,0,0,0],List[0,2,0,7]]
Here's my solution:
SetAttributes[toexpr, Listable];
toexpr[str_] := ToExpression[str, TeXForm]
importlatexmat[str_] :=
toexpr@ImportString[str, "Table", "FieldSeparators" -> {"\\\\", "&"},
"Numeric" -> False]
importlatexmat@"{0} & {0} & {0}\\\\
{\\sqrt{2}} & {0} & {0}\\\\
{0} & {\\sqrt{2}} & {0}"