# “Single ampersand used with wrong catcode” error using tikz matrix in beamer

I am having trouble getting a basic example of a matrix of notes to show up in my beamer presentation. I am using the code copied from the pgf manual. Here is a complete working example. The error I get upon compilation is: "Package pgfbasematrix Error: Single ampersand used with wrong catcode."

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{arrows,decorations.pathmorphing,backgrounds,fit,petri,positioning,matrix}

\begin{document}

\begin{frame}

\begin{tikzpicture}
\matrix (magic) [matrix of nodes]
{
8 & 1 & 6 \\
3 & 5 & 7 \\
4 & 9 & 2 \\
};
\draw[thick,red,->] (magic-1-1) |- (magic-2-3);
\end{tikzpicture}

\end{frame}
\end{document}

-

Simply add the fragile option to the frame:

\begin{frame}[fragile]
...
\end{frame}

-
Note that for this to work \end{frame} must be alone on a single line. – Caramdir Apr 6 '11 at 2:04
This works for me, but is there a downside? I mean, is fragile likely to break anything else? – mrbrich Oct 10 '14 at 17:22

Beamer messes around with catcodes a lot. From the TkiZ manual:

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〉


If a macro name is provided, this macro will be defined to be equal to \pgfmatrixnextcell inside matrices and & will not be made active. For instance, you could say ampersand replacement=\& and then use \& to separate columns.

\documentclass{beamer}
\usepackage{tikz}
\usetikzlibrary{matrix}

\begin{document}

\begin{frame}

\begin{tikzpicture}
\matrix (magic) [matrix of nodes,ampersand replacement=\&]
{
8 \& 1 \& 6 \\
3 \& 5 \& 7 \\
4 \& 9 \& 2 \\
};
\draw[thick,red,->] (magic-1-1) |- (magic-2-3);
\end{tikzpicture}

\end{frame}
\end{document}

-
Absolutely wonderful. Thank you! I just started to learn TikZ last night and I foresee using it a -lot-. Thank you for helping me to understand some of the inner workings. – user4692 Apr 6 '11 at 2:52
This also fixed my problem, but I still have no clue of what was happening: what exactly is an "active character" and why did it cause an error? What is a catcode? Does this always happen when using tikz-matrices in a beamer document? – MHaaZ Jun 10 '13 at 14:37
– Caramdir Jun 10 '13 at 14:58