You're right, it's a bit of a shame that the expressions aren't evaluated before the loop is started.
Three approaches:
Use the count=\xi
expression to make the outer loop counter accessible. In this case, the outer loop only has to run from 2 to 4, while the counter will run from 1 to 3, which happens to be the starting point of the inner loop. This solution only works in this special case, though, as soon as you need the inner loop to be larger by a different value, you'll have to resort to something else.
Alternatively, you can parse the expression at the start of the outer loop using \pgfmathtruncatemacro
, which will save the result as an integer, or using the evaluate=\x as \result using <expression>
syntax.
Note that the outer loop actually only needs to run from 1 to 3.
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x [count=\xi] in {2,...,4} {
\foreach \y in {\x,...,4} {
\node at (\xi,\y) {(\xi,\y)};
}
}
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x in {1,...,3} {
\pgfmathtruncatemacro\ystart{\x+1}
\foreach \y in {\ystart,...,4} {
\node at (\x,\y) {(\x,\y)};
}
}
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x [evaluate=\x as \ystart using int(\x+1)] in {1,...,3} {
\foreach \y in {\ystart,...,4} {
\node at (\x,\y) {(\x,\y)};
}
}
\end{tikzpicture}
\end{document}
Apparently \lastx
is not evaluated correctly, it is always A. Unfortunately, I also don't know why, but here are some suggestions:
\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes}
\begin{document}
\verb! apparantly `\lastx` is not increased: !
\begin{tikzpicture}[every node/.style={draw}]
\node (A) at (1,0) [rectangle] {A};
\foreach \x/\y [remember=\x as \lastx (initially A)] in {B/2,C/3,D/4,E/5}
{ \node[rectangle] (\x) at (\y,0) {\lastx \x};
}
\end{tikzpicture}
\verb! you could use `\xdef` to do it yourself !
\begin{tikzpicture}[every node/.style={draw}]
\node (A) [rectangle] {};
\xdef\lastx{A}
\foreach \x in {B,C,D,E}
{ \node (\x) [rectangle,right=of \lastx] {};
\xdef\lastx{\x}
}
\end{tikzpicture}
\verb! or you could use absolute positions: !
\begin{tikzpicture}[every node/.style={draw}]
\pgfmathsetmacro{\multi}{1.245}
\foreach \x in {1,...,5}
{ \node at (\multi*\x,0) {};
}
\end{tikzpicture}
\verb! this also works for multiple variables !
\begin{tikzpicture}[every node/.style={draw}]
\pgfmathsetmacro{\multi}{1.245}
\foreach \x/\shp/\clr in {1/rectangle/green,2/circle/blue,3/diamond/red,4/ellipse/yellow,5/trapezium/orange}
{ \node[shape=\shp,fill=\clr] at (\multi*\x,0) {};
}
\end{tikzpicture}
\end{document}
Best Answer
You're redefining
\end
at the same grouping level as the\end{tikzpicture}
instruction. So when TeX sees\end{tikzpicture}
it will obey your redefinition and replace it withCan you see why your choice isn't really good?
Use a different name, there's plenty of them, for instance
\END
. But it should really beotherwise you will get
2.0
and the loop would use floating point numbers.Example: