15

Consider the following code:

\documentclass{article}
\usepackage{tikz}
\begin{document}
 \begin{tikzpicture}
  \newcommand{\MA}{4}
  \pgfmathsetmacro{\MB}{4};
  \coordinate (V11) at (0,0);
  \coordinate (V44) at (4,4);
  \draw[black] (V11) rectangle (V\MA\MA);
 \end{tikzpicture}
\end{document}

This works. However changing the \draw command to:

   \draw[black] (V11) rectangle (V\MB\MB);

produces the following error:

! Package pgf Error: No shape named V4 is known .

Why is \newcommand working here, when \pgfmathsetmacro fails?

20

The reason is that \pgfmathsetmacro{\MB}{4} (there is no ; required) sets \MB to the arithmetic result of 4.0 not 4. Therefore you get V4.04.0 as node expression. Everything after a dot is taken as node anchor, i.e. TikZ looks for a node V4 with the anchor 04.0, which leads to the error you get. (Numeric anchors are also taken as angle (in degrees), so V\MB would be node V4 with the angle node at 0 degrees.)

To fix this use \pgfmathtruncatemacro{\MB}{4} which will give you 4.

See also the related questions How to draw lines between nodes that point at the node center, but stop at the nodes edge and Referring to tikz matrix coordinates using pgf mathematics operations, which where caused from the same behaviour of \pgfmathsetmacro.

  • Thank you :-) This was exactly what I was looking for. Great answer! – Håkon Hægland Jan 22 '13 at 8:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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