Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

When I take a part of a tikz picture out and put it into a macro, the code stops working. So, why does the following not work?

\documentclass{article}
\usepackage{tikz}\usetikzlibrary{matrix}
\begin{document}

\newcommand{\emptymatrix}{%
  \matrix[matrix of nodes,
          inner sep=0pt,
          left delimiter={[},
          right delimiter={]},
          nodes={circle,inner sep=0pt}] (A) {%
    \strut & \strut & \strut & \strut \\
    \strut & \strut & \strut & \strut \\
    \strut & \strut & \strut & \strut \\
    \strut & \strut & \strut & \strut \\
  };
}

\begin{tikzpicture}
  \emptymatrix
  \draw (A-1-1.center) -- (A-4-4.center);
\end{tikzpicture}

\end{document}

Intended result:

enter image description here

Instead, an Undefined control sequence error occurs.

ERROR: Undefined control sequence.

--- TeX said ---
<argument> \pgf@matrix@last@nextcell@options 

l.22   \emptymatrix
share|improve this question

1 Answer 1

up vote 4 down vote accepted

Using an ampersand & inside a macro is not advised since it ends a group. Below is a workaround that replaces ampersands by control sequences, and then \& evaluates to the ampersand retro-actively. LaTeX then already evaluated the structure of your matrix to evaluate where the groups end afterwards. That way the structure defined by your macro doesn't break so early in the process.

The output shows this (I hope that's what you want):

http://i.imgur.com/k4bbhcL.png?1

Code:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}

\newcommand{\emptymatrix}{%
  \matrix (A) [ampersand replacement=\&,
          matrix of nodes,
          inner sep=0pt,
          left delimiter={[},
          right delimiter={]},
          nodes={circle,inner sep=0pt}] {%
    \strut \& \strut \& \strut \& \strut \\
    \strut \& \strut \& \strut \& \strut \\
    \strut \& \strut \& \strut \& \strut \\
    \strut \& \strut \& \strut \& \strut \\
  };
}

\begin{tikzpicture}
  \emptymatrix
  \draw (A-1-1.center) -- (A-4-4.center);
\end{tikzpicture}

\end{document}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.