[Tex/LaTex] “Single ampersand used with wrong catcode” error using tikz matrix in beamer

beamermatricestikz-pgf

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}

Best Answer

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.

For your example this means:

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