[Tex/LaTex] Problem with defining shortcuts for TikZ matrices

ampersandmacrosmatricestikz-pgf

For answering a question yesterday I wanted to define a shortcut for creating a matrix inside a tikzpicture. As a minimal example, consider

\newcommand\mymatrix[1]{
    \begin{tikzpicture}
        \matrix[matrix of math nodes] {#1};
    \end{tikzpicture}%
}

which would then be used as

\mymatrix{
    a & b \\
    e & f \\
}

But LaTeX complains about Package pgfbasematrix Error: Single ampersand used with wrong catcode at the line with the closing brace of \amatrix{}. Why does it do that and how can I avoid it?

Best Answer

TikZ cannot make the ampersand given in the argument to an active character. You could

use \pgfmatrixnextcell instead of & and perhaps define a shortcut for it,

or use the ampersand replacement option:

\newcommand\mymatrix[1]{
    \begin{tikzpicture}
        \matrix[ampersand replacement=\&,matrix of math nodes] {#1};
    \end{tikzpicture}%
}
\mymatrix{
    a \& b \\
    e \& f \\
}