[Tex/LaTex] Parse WolframAlpha’s matrices into LaTeX

amsmathmacrosmatriceswolfram-mathematica

I sort of have the same issue as this question, but the reverse.

It is often the case that I need to write out a matrix in LaTeX, one resulting from a computation of some sort. Of course, the computation itself is often most easily performed in WolframAlpha, or other such software.

Consider, for instance, the operation of squaring a matrix here. I also will want the third, fourth, and fifth powers of this matrix.

Writing this in LaTeX is quite time-consuming and cumbersome. WolframAlpha does however provide a sort of formatting for the answer: a "copyable plain text" option, and a "Wolfram Language plain text output:"

enter image description here

If I could somehow convert either of these outputs into the resulting matrix, given by

   \begin{pmatrix}
   1/4 & 0 & 1/2 & 1/4 \\
   0 & 0 & 0 & 1 \\
   1/2 & 0 & 0 & 1/2 \\
   1/4 & 1/4 & 0 & 1/2
   \end{pmatrix}

that would reduce quite a bit of (in my opinion) unnecessary work.

That is, I would hypothetically like some macro, say \wamatrix such that using

 \wamtrix{ 1/4(1 | 0 | 2 | 1
 0 | 0 | 0 | 4
 2 | 0 | 0 | 2
 1 | 1 | 0 | 2) }

or

 \wamatrix{ {{1/4, 0, 1/2, 1/4}, {0, 0, 0, 1}, {1/2, 0, 0, 1/2}, {1/4, 1/4, 0, 1/2}} }

would give me the same result as using

   \begin{pmatrix}
   1/4 & 0 & 1/2 & 1 \\
   0 & 0 & 0 & 1 \\
   1/2 & 0 & 0 & 1/2 \\
   1/4 & 1/4 & 0 & 1/2
   \end{pmatrix}

(And, of course, the matrix should not necessarily be this specific one, or even one of the same size, ideally.)

I don't know how feasible this is, but if anyone could help, it would be greatly appreciated!

Best Answer

It might not be the easiest way to do this, but you could use the xstring package to do some reformatting of the code:

\documentclass{article}
\usepackage{amsmath}
\usepackage{xstring}

\newcommand{\wamatrix}[1]{%
  \StrRemoveBraces{#1}[\waouterraw]%
  \StrSubstitute{\waouterraw}{,}{\\}[\waouter]%
  \StrRemoveBraces{\waouter}[\wainnerraw]%
  \StrSubstitute{\wainnerraw}{,}{&}[\wainner]%
  \begin{pmatrix}
    \wainner
  \end{pmatrix}%
}

\begin{document}

\[
\wamatrix{ {{1/4, 0, 1/2, 1/4}, {0, 0, 0, 1}, {1/2, 0, 0, 1/2}, {1/4, 1/4, 0, 1/2}} }
\]

\end{document}

enter image description here

Note that xstring macros by default only process the characters in a string up to the next grouping level. For example \StrSubstitute{aaa{a}a}{a}{b} would result in bbb{a}b (while the braces are not printed in the output). Similarly, \StrRemoveBraces by default only removes the outermost pair of braces. This behaviour was used here to first split the string (which conveniently contains braces to group the items) into lines and then into cells.