17

I'll start with a simple, minimal non-working example:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach \x/\y in {1/20,2/18,...,10/2}
  \node at (\x,0) {\y};
\end{tikzicture}
\end{document}

The point, as you probably understand from the example, is to iterate over two variables at the same time that change by the same amount for each run, without having to write out all the x/y pairs explicitly. Had this worked, the expected output would be

enter image description here

but the compilation halts with an Illegal unit of measure ... error. I know the manual doesn't say anything about it, so I'm kind of expecting the answer to simply be "no, not possible". Am I missing something obvious, or is this something that TikZ can't do?

(By the way, I haven't come across a situation where I've needed this, it's just something that I came to wonder about. And I could do the loop with something else, e.g., Lua, anyway.)

Torbjørn T.
  • 206,688
  • I have no answer, but I do want to express my enthusiasm for the question. I tried to look this up recently and found nothing as well. It may not be possible. – Ryan Reich Dec 08 '11 at 17:34
  • @RyanReich If nothing else pops up, I'll post a Lua workaround. It doesn't answer the question, but it is way around the problem. Well, if one can use lualatex, anyways. – Torbjørn T. Dec 08 '11 at 17:49
  • This has come up implicitly a few times in some questions but couldn't find one yet. The problem is that the list elements are now assumed to be mathematical operations and same issue happens if you just use one variable such as \foreach \x in {1,2,...,10-1}{ \node at (\x,0) {\x};}. I am not sure about the cause of it yet there must be a way which also I don't know now,to escape from it . – percusse Dec 08 '11 at 17:53

1 Answers1

19
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\foreach[count=\i] \txt in {20,18,...,2}
  \node at (\i,0) {\txt};
\end{tikzpicture}
\end{document}

Note: It is always possible to cauculate one variable using the other one. Or you can't use ... in pgffor. So you can also use:

\begin{tikzpicture}
\foreach[evaluate=\y using int(22-2*\x)] \x in {1,...,10}
  \node at (\x,0) {\y};
\end{tikzpicture}
Leo Liu
  • 77,365
  • Clever. I'd forgotten evaluate, and combining count with let opens up more possibilities as well. – Torbjørn T. Dec 08 '11 at 18:21
  • in case there are several quantities need to be computed via variable \x, then just calculate them seperately: \documentclass{article} \usepackage{tikz} \begin{document} \begin{tikzpicture} \foreach \x in {1,...,10}{ \pgfmathsetmacro{\y}{int(22-2*\x)} \path (\x,0) node{$\y$}; } \end{tikzpicture} \end{document} – Black Mild Aug 25 '19 at 00:41