[Tex/LaTex] Nested foreach loop in TikZ

foreachtikz-pgf

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?

Best Answer

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}

enter image description here

Related Question