10

I try to draw some nodes in tikz, and as they are very simple I wanted to "shorten" this using a \foreach command:

\foreach \xnum in {1,2,3,4,5}
{
    \node at (X\xnum center) {$x_\xnum$};
}

You can insert this into any MWE with a tikzpicture environement which has some nodes X1, X2, ... defined. (In my case, this are rectangles, using this: https://tex.stackexchange.com/a/47797/22276 )

The problem with this is, that the space after \xnum is not preserved, which is why I get the following error on running pdflatex:

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

Any idea how to solve this?

2 Answers2

18

Use \space to get a literal space.

The active character ~ does not only produce a space, it produces a non-breakable space, saved in the macro \nobreakspace that expands to \leavevmode\nobreak\␣ (LaTeX).

The \xnum{} trick to end the macro does not work because TikZ performs at some point a \csname pgf@sh@ma@#1\endcsname (where #1 is our coordinate/node name) and at that point {} will become their actual characters: No shape named X1{} center is known.

The macro \␣ is not good for csname either: The control sequence \␣ should not appear between \csname and \endcsname. (Freely adapted from the original error message.)

Code

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}
\coordinate (X1 center) at (0,0);
\coordinate (X2 center) at (1,0);
\coordinate (X3 center) at (2,0);
\coordinate (X4 center) at (3,0);
\coordinate (X5 center) at (4,0);

\foreach \xnum in {1,2,3,4,5}
{
    \node at (X\xnum\space center) {$x_\xnum$};
}
\end{tikzpicture}
\end{document}

Output

enter image description here

Qrrbrbirlbel
  • 119,821
5

Here is another approach, which may be used in other circumstances (e.g., where the content of the holder macro \xnum is needed directly without expansion).

\documentclass[tikz]{standalone}
\usepackage{tikz,loops}

\begin{document}
\begin{tikzpicture}
\coordinate (X1 center) at (0,0);
\coordinate (X2 center) at (1,0);
\coordinate (X3 center) at (2,0);
\coordinate (X4 center) at (3,0);
\coordinate (X5 center) at (4,0);

\newforeach \xnum in {1,...,5} {\node at (X#1 center) {$x_\xnum$};}

% Or
% \foreachfox {1,...,5} {\node at (X#1 center) {$x_#1$};}
\end{tikzpicture}
\end{document} 
Ahmed Musa
  • 11,742