84

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}
David Carlisle
  • 757,742

2 Answers2

108

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}
David Carlisle
  • 757,742
Caramdir
  • 89,023
  • 26
  • 255
  • 291
  • 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. –  Apr 06 '11 at 02:52
  • 1
    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? – MaxAxeHax Jun 10 '13 at 14:37
  • 1
    @MHaaZ: See http://tex.stackexchange.com/questions/16410/what-are-category-codes – Caramdir Jun 10 '13 at 14:58
  • @Caramdir Why there is a problem with beamer? The \matrix is not used as an argument of a macro and also the nodes don't contain {tabular} environments. – ado sar Nov 10 '22 at 21:01
44

Simply add the fragile option to the frame:

\begin{frame}[fragile]
...
\end{frame}
Gonzalo Medina
  • 505,128