# How can I connect centers of nodes defined using let in a foreach loop?

I want to create a star polygon using a \foreach loop to make nodes for the vertices and another \foreach loop connecting, say, every 4th node.

\documentclass[12pt]{amsart}

\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{shapes.symbols}
\usetikzlibrary{positioning}
\usetikzlibrary{decorations.shapes}

\begin{document}

\begin{tikzpicture}
\foreach \i in {0,1,2,...,9}
{
\node[draw, circle, fill=red, inner sep = 20 pt] (a\i) at (360*\i/10:4) {};
\draw[fill=black] (a\i.center) circle (.5 mm);
}
\foreach \j in {0,1,...,9}
{
\draw[blue, align=center] let \n1={mod(\j+4,10)} in (a\n1)--(a\j.center);
}
\end{tikzpicture}

\end{document}


When I do this, the connections to the nodes (a\n1) are not to the center of the node. If I try (a\n1.center) it gives me a PGF math error. But using ({a\n1}.center) says no shape named a4.0 is known.

What's the secret escape thing that needs to happen to make this work? Is there a better way?

(Everything's fine if I use coordinate instead of node, but then I have to run a final loop on top of the coordinate just to draw the nodes, which is sort of annoying.)

• What is \n used? – Sigur Jun 27 '14 at 1:20

I think the problem is that the PGF maths functions return their result with a decimal point by default even if the result is an integer. So you get 4.0 rather than 4 from the modulo operation.

The math library offers a way to avoid this. However, note that I have never used this library before and I've never really used PGF maths either. Caveat emptor...

\documentclass[12pt]{amsart}

\usepackage{tikz}
\usetikzlibrary{calc, math}
\usetikzlibrary{shapes.symbols}
\usetikzlibrary{positioning}
\usetikzlibrary{decorations.shapes}

\begin{document}

\begin{tikzpicture}
\foreach \i in {0,1,2,...,9}
{
\node[draw, circle, fill=red, inner sep = 20 pt] (a\i) at (360*\i/10:4) {};
\draw[fill=black] (a\i.center) circle (.5 mm);
}
\foreach \j in {0,1,...,9}
{
\tikzmath{
integer \x;
\x = mod(\j+4,10);
}
\draw[blue, align=center] (a\x.center)--(a\j.center);
}
\end{tikzpicture}

\end{document}


• Thanks, that fixes it. You can even set let \n1 = {int(mod(\j+4, 10))} in ... and have it work. – Leah Wrenn Berman Jun 27 '14 at 2:55
• You can also say \foreach \j [evaluate={\x=int(mod(\j+4,10));}] in ... – Mark Wibrow Jun 27 '14 at 6:40