# Parse WolframAlpha's matrices into LaTeX

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:"

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!

• If you don't require Wolfram, this sort of thing is easily handled with the sagetex package. It relies on the open source CAS, called Sage, which will do the math. See my answer for getting the transpose of a matrix. Sage documentation here. Access through free Cocalc account.
– DJP
Oct 26 at 21:24
• I don't strictly require Wolfram; I just use it since it's fairly accessible to me. Your sagetex idea seems really powerful, with uses far beyond my limited use case, so I really appreciate the pointer! Oct 26 at 21:36
• Would you prefer that the Wolfram Language plain text output be read from a separate file, or would you prefer to just paste it into the LaTeX document? Oct 26 at 22:04
• At least for how I intend to use it, it's simplest if I can just put it into the document directly. Oct 26 at 22:07
• Unfortunately because the engine doesn't have any good way to do it, there are too many packages that does it (and there isn't any expl3 answer yet) Oct 27 at 3:20

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}


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.

• Using the code you've given (like, alone in a *.tex file) gives an error message for me in MikTeX (picture), though it renders fine in Overleaf, even though the code is the exact same. Might be asking a bit much, but would you be able to offer some insight as to why this occurs? Oct 26 at 21:50
• This is most probably due to an old TeX installation. The above code should work as of TeX Live 2020 (or equivalent). Oct 26 at 21:53
• Note: \wamatrix{ {{1, 2},{*3, 4}} } will make the * disappear because \\* is valid in LaTeX (fortunately adding a space would fix the issue) Nov 9 at 10:44
• \ensuremath does not do what you think it does. Remove it. Nov 18 at 12:18
• Indeed. Thanks! Nov 18 at 15:46

Here, I digest the matrix with a token cycle and typeset it with a TAB stack. The token cycle echoes the input tokens except for commas. In the case of commas, they are replaced with either a & or a \\, depending on the grouping depth within the input. The TAB stack typesets this revised token stream.

Note that row spacing and column gap are settable parameters.

\documentclass{article}
\usepackage{tabstackengine,tokcycle}
\Characterdirective{\tctestifx{,#1}
}
\stripgroupingtrue
\setstacktabbedgap{1.5ex}% INTERCOLUMN GAP
\setstackgap{L}{1.2\normalbaselineskip}% INTERROW BASELINESKIP
\newcommand\wamatrix[1]{%
\tokcyclexpress{#1}%
\expandafter\parenMatrixstack\expandafter{\the\cytoks}
}
\begin{document}
$\mathbf{X} = \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}


If one really wanted to enter the \wamatrix call with the extra set of braces that the OP showed,

\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}} }


then one would merely need to change the \tcdepth check from <1 to <2, in the \Characterdirective, as in

\Characterdirective{\tctestifx{,#1}
}


Here is a sagetex implementation:

\documentclass{article}
\usepackage{amsmath,amsfonts,amssymb,sagetex,setspace}
\doublespacing
\begin{document}
\begin{sagesilent}
latex.matrix_delimiters(left='[', right=']')
A = Matrix([[0,1/2,0,1/2],[0,0,1,0],[0,0,0,1],[1/2,0,0,1/2]])
\end{sagesilent}
If I start with $A = \sage{A}$ then it is easy to   calculate\\
$A^2=\sage{A^2}$, $A^3=\sage{A^3}$,$A^4=\sage{A^4}$, $A^5=\sage{A^5}$.
\end{document}


The output from Cocalc is:

The setspace package is used to change the spacing between the lines to doublespace so it isn't as crowded. \sage{} is used to get a mathematical calculation from Sage. The beauty of using a CAS is all you need to do is input the matrix properly and Sage will get the answer without mistakes.

• Thank you for (re-)introducing us all to \sage. One (admittedly uglier, but potentially also useful depending on the OP's original needs) similar alternative may be Knittr with the symbolic math package caracas and its latex output. Oct 27 at 20:56

Not sure if this is simple or qualitatively different from some of the other answers, but one can also use pgf to loop over the nested lists and build the matrix contents. Notice that this does not explicitly use global macros, and also works if some entries are "not expandable" macros.

\documentclass{article}
\usepackage{amsmath}
\usepackage{pgffor}
\newtoks\wamatrixtoks
\newif\ifwamatrixfirstcol
\wamatrixfirstcoltrue
\newif\ifwamatrixfirstrow
\wamatrixfirstrowtrue
\pgfkeys{wamatrix/warow/.code={%
\ifwamatrixfirstcol
\wamatrixfirstcolfalse
\wamatrixtoks=\expandafter{\the\expandafter\wamatrixtoks#1}%
\else
\wamatrixtoks=\expandafter{\the\expandafter\wamatrixtoks\expandafter&#1}%
\fi
},wamatrix/warows/.code={%
\ifwamatrixfirstrow
\wamatrixtoks{}%
\wamatrixfirstrowfalse
\else
\wamatrixtoks=\expandafter{\the\expandafter\wamatrixtoks\expandafter\\}%
\fi
\wamatrixfirstcoltrue
\pgfkeys{wamatrix/warow/.list={#1}}%
}}
\newcommand\wamatrix[1]{\wamatrixfirstrowtrue
\pgfkeys{wamatrix/warows/.list={#1}}%
\begin{pmatrix}
\the\wamatrixtoks\\
\end{pmatrix}}
\begin{document}
$A=\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}} }$

$B=\wamatrix{ {{\frac{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}


Append // TeXForm to your WolframAlpha query. Then under the "Exact result" panel, click "Plain text" and copy. Try your example here.

TeXForm is a built-in function in the Wolfram Language, which underlies WolframAlpha and Mathematica.

• Oh wow, I had no clue that was a possible thing to do! Oct 30 at 5:54

Calc is a great feature from Emacs to deal with matrix calculus. For example, if you want to type a matrix raised to the fifth power , just type in your LaTeX document :

% [calc-mode: fractions: t]
$((1/4)[[1 0 2 1] [0 0 0 4] [ 2 0 0 2] [1 1 0 2]])^5=>$}


The preamble is necessary since fractions mode is not a default mode.

Then assuming the point (cursor) whithin the matrix code, activate calc-embedded-mode (M-x calc-embedded-mode or C-x * e). Instantanely, The calculus is proceded and display (after formatting using some Emacs features):

 % [calc-mode: fractions: t]
$\evalto \left( \frac{1}{4} \begin{pmatrix} 1 & 0 & 2 & 1 \\ 0 & 0 & 0 & 4 \\ 2 & 0 & 0 & 2 \\ 1 & 1 & 0 & 2 \end{pmatrix} \right) ^5 \to \begin{pmatrix} \frac{131}{512} & \frac{125}{1024} & \frac{69}{512} & \frac{499}{1024} \\ \frac{61}{256} & \frac{33}{256} & \frac{1}{8} & \frac{65}{128} \\ \frac{65}{256} & \frac{61}{512} & \frac{33}{256} & \frac{255}{512} \\ \frac{255}{1024} & \frac{65}{512} & \frac{61}{512} & \frac{517}{1024} \end{pmatrix}$
}%


which render (you have to activate calc-embedded-mode again to return to latex-mode):