# Passing a TikZ matrix to a TeX macro

When I pass code containing a TikZ matrix to a TeX macro it prints the following error message: ! Package pgfbasematrix Error: Single ampersand used with wrong catcode.

\documentclass{article}
\usepackage{tikz}

\def\identity#1{#1}

\begin{document}
\begin{tikzpicture}
\identity{
\matrix {
\node {1}; & \node{2};\\
\node {3}; & \node{4};\\
};
}
\end{tikzpicture}
\end{document}


Why does this happen? Is there any way to make this work?

Rationale:

I use such macros to create exercise sheets for my students. I like the answers to be embedded in the source code but naturally do not want them to show up on the exercise sheet. Thus I mark up my code with macros like \problem{} and \answer{} which are then suitably defined in the document header depending on whether I want to compile the exercise sheet or the reference solution.

The probably best way (I guess) would be to replace my markup macros with environments that use \iftrue or \iffalse to include or skip parts of the document, but currently I'm not ready to convert all my files. That's why I'm looking for a short term solution to that problem (that, and I'm curious).

-
–  Martin Scharrer May 6 '12 at 18:57
Thanks for the links. Obviously I failed quite horribly at googling. :( –  Fritz May 6 '12 at 20:41

From the pgf manual:

17.5 Considerations Concerning Active Characters

Even though TikZ seems to use & to separate cells, pgf actually uses a different command to separate cells, namely the command \pgfmatrixnextcell and using a normal & character will normally fail. What happens is that, TikZ makes & an active character and then defines this character to be equal to \pgfmatrixnextcell. In most situations this will work nicely, but sometimes & cannot be made active; for instance because the matrix is used in an argument of some macro or the matrix contains nodes that contain normal tabular environments. In this case you can use the following option to avoid having to type \pgfmatrixnextcell each time:

/tikz/ampersand replacement= <macro name or empty>

So the solution is to use \pgfmatrixnextcell instead of the usual & or to use an ampersand replacement:

\documentclass{article}
\usepackage{tikz}

\def\identity#1{#1}

\begin{document}
\begin{tikzpicture}
\identity{
\matrix[ampersand replacement=\&] {
\node {1}; \& \node{2};\\
\node {3}; \& \node{4};\\
};
}
\end{tikzpicture}
\end{document}

-