3

I want to create a new command to do a certain diagram using tikz. The code looks like this:

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\newcommand{\D}[4]{
\begin{tikzpicture}
  \matrix (m) [matrix of math nodes,row sep=1.5em,column
    sep=1.5em,minimum width=2em]
          {
            &#1&\\
            #2& &#3\\
            &#4&\\};
           \path[thick]
           (m-1-2) edge (m-2-1)
           edge (m-2-3)
           (m-3-2) edge (m-2-1)
           edge (m-2-3);
\end{tikzpicture}
}
\begin{document}
\D{a}{b}{c}{d}
\end{document}

But I get this message:

! Undefined control sequence.
<argument> \pgf@matrix@last@nextcell@options 

l.23 \D{a}{b}{c}{d}

How can I solve it?

  • 2
    The & character has special catcode and this will not work. See, for example, questions on this site that tries to wrap tabular/array/align/matrix in a command. – Symbol 1 May 08 '17 at 18:06
  • Welcome to TeX.SX! You can have a look at our starter guide to familiarize yourself further with our format. – jjdb May 08 '17 at 18:07

1 Answers1

3

As Symbol 1 mentioned in a comment, this is because of the &, but you can use ampersand replacement=\& in the matrix options, and use \& instead of &.

\documentclass[12pt]{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\newcommand{\D}[4]{
\begin{tikzpicture}
  \matrix (m) [matrix of math nodes,row sep=1.5em,column
    sep=1.5em,minimum width=2em,ampersand replacement=\&]
          {
            \&#1\&\\
            #2\& \&#3\\
            \&#4\&\\};
           \path[thick]
           (m-1-2) edge (m-2-1)
           edge (m-2-3)
           (m-3-2) edge (m-2-1)
           edge (m-2-3);
\end{tikzpicture}
}
\begin{document}
\D{a}{b}{c}{d}
\end{document}
Torbjørn T.
  • 206,688
  • I was about to complain that you were 'stealing' the answer from the comment, but the temporal distance between the comment and your answer was too short for you not posting this independently. So good timing ;) – jjdb May 08 '17 at 18:09
  • @jjdb Symbol 1 only identified the problem, without suggesting the solution directly, though I wouldn't be the least bit surprised if (s)he knows about ampersand replacement as well. I saw the comment before I posted, but I think I had the code ready at that time. – Torbjørn T. May 08 '17 at 18:12
  • Yes I thought so. It was really a close race. I watched cheerfully ;) and upvoted your answer… oh I forgot to upvote the comment. I'll do it immediately… – jjdb May 08 '17 at 18:24
  • Thank you very much for your fast and precise answer. Thanks to @Symbol1 as well. – Elias Mochan May 08 '17 at 18:44