# Error when naming nodes using \foreach command

If I try the following code:

\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{calc, positioning, decorations.pathmorphing}

\begin{document}
\begin{tikzpicture}

\foreach \x/\y  in {1/1, 2/2, 3/1, 4/2, 5/1}
\node[fill=black!30, circle] (m\x) {$m_{\y}$} at (1.5*{\x}, 0);

\foreach \x in {1,2,3,4}
\draw[decorate, decoration={coil}] (m\x) -- node[above] {$K$} (m{\x+1});

\end{tikzpicture}
\end{document}


then I get an error. How can I solve this problem?

• I don't think arithmetic is performed in node names, so you get the node named m{1+1}, which is not m2 – egreg Mar 1 '17 at 8:17
• @egreg That's a good point. I haven't thought about it. Then is there any way to make TikZ calculate this arithmetic? – eigenvalue Mar 1 '17 at 8:20

Macros are expanded in node names, but arithmetic is not performed. You can use \the\numexpr\x+1\relax.

I also fixed a couple of mistakes.

\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{calc, positioning, decorations.pathmorphing}

\begin{document}

\begin{tikzpicture}

\foreach \x/\y  in {1/1, 2/2, 3/1, 4/2, 5/1}
\node[fill=black!30, circle] (m\x) at ({1.5*\x}, 0) {$m_{\y}$};

\foreach \x in {1,2,3,4}
\draw[decorate, decoration={coil}] (m\x) -- node[above] {$K$} (m\the\numexpr\x+1\relax);

\end{tikzpicture}

\end{document}


A more TikZ-ish way of doing the same is to use evaluate. While I was at it, I demonstrate a different way of writing the first loop. Output is same as in egreg's answer.

Note that you need to use int, otherwise \x+1 will be a decimal, e.g. 2.0 for \x=1.

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{calc, positioning, decorations.pathmorphing}
\begin{document}
\begin{tikzpicture}

\foreach [evaluate=\x as \y using {int(2-mod(\x,2))}] \x in {1,...,5}
%\x/\y  in {1/1, 2/2, 3/1, 4/2, 5/1}
\node[fill=black!30, circle] (m\x) at (1.5*\x, 0) {$m_{\y}$};

\foreach [evaluate=\x as \y using int(\x+1)] \x in {1,...,4}
\draw[decorate, decoration={coil}] (m\x) -- node[above] {$K$} (m\y);
\end{tikzpicture}
\end{document}

• Thank you. I also learn a tip of using mod command to make the code more simple. – eigenvalue Mar 1 '17 at 8:52

Just two more options: count for the first loop and remember for the second.

\documentclass{standalone}
\usepackage{tikz}

\usetikzlibrary{calc, positioning, decorations.pathmorphing}

\begin{document}
\begin{tikzpicture}

\foreach \y [count=\x] in {1, 2, 1, 2, 1}
\node[fill=black!30, circle] (m\x) at (1.5*\x, 0) {$m_{\y}$} ;

\foreach \x [remember=\x as \lastx (initially 1)] in {2,...,5}
\draw[decorate, decoration={coil}] (m\lastx) -- node[above] {$K$} (m\x);

\end{tikzpicture}
\end{document}