# Nested foreach loop in TikZ

I would like to draw some vector fields on a triangle, and I am using nested \foreach loop to do that, however in the inner loop, you can't use the outer loop variable as the numeric range. For e.g. The following code does not work:

\begin{tikzpicture}
{\draw (0,0) -- ++(1,0) -- ++(-1,1) -- cycle;}
\foreach \x in {0,0.1,...,1}
\foreach \y in {0,0.1,...,1-\x}
{
\draw [->] (\x,\y)--(-1 + \x + 2*\y,-\y);
}
\end{tikzpicture}


Is there a way to do nested loop like this? Or I have to manually go through the loop for each \y which is \x dependent?

• Could you point out more clearly what doesn't work for you, because, as for me, your code snippet at least gets compiled. There's some issues with loop-variables, but it works. – Dmitry Volosnykh Apr 22 '11 at 18:37
• The nested loops work fine for me. Except when \x is 0 the inner loop is {0,0.1,...,0} and then processes the 0.1 as well. Your drawing code seems just not right. You might also want to use integers instead, i.e. {0,1,...,10} and then use \x/10 to avoid rounding issues with the loop variables. – Martin Scharrer Apr 22 '11 at 18:48
• I copied the wrong codes above, what didn't compile was if the inner loop range is an operation of \x, for e.g., 1-\x, sorry for the confusion – Shuhao Cao Apr 22 '11 at 19:07

I assume that vector should come out from inside of triangle (in your post it is not true). I think you stuck because of imprecise float arithmetic, so you'd better switch to integers:

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- ++(1,0) -- ++(-1,1) -- cycle;

\foreach \x in {0, ..., 10}
\foreach \y in {0, ..., \x} {
\draw[->] (1 - 0.1*\x,0.1*\y) -- (-0.1*\x + 0.2*\y,-0.1*\y);
}
\end{tikzpicture}
\end{document}


• @MathChief: Note that I've updated my solution according to your fixes. – Dmitry Volosnykh Apr 22 '11 at 19:28
• Updated solution, using Andrew's hint about default step. – Dmitry Volosnykh Apr 23 '11 at 2:48

I find that \foreach can be a little fussy over what it accepts as endpoints of a range. Whilst I don't know the details of what does and doesn't work, I do know how to get your example (with the 1-\x) to work: do the computation before the \foreach and save the result in a new macro. Thus:

\documentclass{article}
% http://tex.stackexchange.com/q/16411/86
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\draw (0,0) -- ++(1,0) -- ++(-1,1) -- cycle;
\foreach \x in {0,.1,...,1}
{
\pgfmathsetmacro{\z}{1-\x}
\foreach \y in {0,.1,...,\z}
{
\draw [->] (\x,\y)--(-1 + \x + 2*\y,-\y);
}
}
\end{tikzpicture}

\end{document}


(Note that I haven't corrected the other issues: even when \x is 1 then the loop is executed for \y being 0.1. Using integers gets round this as then the range can be specified as 0,...,\z since the default step-size is 1.)