19

If I say something along the lines of

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\def\I{2}
\foreach \i in { \I+1, ..., 20 }
  \node at (\i,10) {+};
\end{tikzpicture}
\end{document}

I get the message

! Illegal unit of measure (pt inserted).
<to be read again> 
                   +
l.560     \node[anchor=center] at (\i,10) {$+$};

How can I do arithmetic in the bounds of a foreach ... range?

1
  • 1
    While code snippets are useful in explanations, it is always best to compose a fully compilable MWE that illustrates the problem including the \documentclass and the appropriate packages so that those trying to help don't have to recreate it. Commented Nov 30, 2011 at 20:15

3 Answers 3

18

Some possibilities with foreach. In your case, you can try the first one

\documentclass[11pt]{scrartcl}
\usepackage{tikz}


\begin{document} 
  \def\I{2}   
\begin{tikzpicture}
\foreach \i   [evaluate=\i] in {\I+1,...+1,19+1}
  \node[anchor=center] at (\i,0) {$\i$};
\end{tikzpicture} 

\begin{tikzpicture}
\foreach \i   [evaluate=\i as \j using \i+1] in {\I,...,10}
  \node[anchor=center] at (\j,0) {$\j$};
\end{tikzpicture} 

\begin{tikzpicture}
\foreach \i   [evaluate=\i as \j using \i*\i] in {\I,...,4}
  \node[anchor=center] at (\j,0) {$\j$};
\end{tikzpicture}   
\end{document} 
4
  • 2
    I would have never thought of ... + 1 :) Commented Nov 30, 2011 at 20:46
  • This one is minimally disruptive, so far. Commented Nov 30, 2011 at 21:00
  • 1
    Hi Alain, how can I do this with non integer steps? I have tried with ...+0.1 but it does not work. I am using two arguments of newcommand to define the start and end point of the iteration list, so I do this: \foreach \x in {#1+0.1,...+0.1,#2+0.1} Commented Mar 15, 2017 at 21:31
  • What does ...+1 mean? Commented Dec 20, 2019 at 11:11
4

With eTeX, you can use \numexpr:

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
  \def\I{2}
  \foreach \i in {\number\numexpr\I + 1\relax, ..., 20 }
  \node[anchor=center] at (\i,10) {$+$};
\end{tikzpicture}
\end{document}
3

Yo can use \pgfmathsetmacro{\Start}{\I+1} to compute the start point and then use \Start in the \foreach:

\documentclass{article}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\def\I{2}
\pgfmathsetmacro{\Start}{\I+1}
\foreach \i in { \Start, ..., 20 }
  \node[anchor=center] at (\i,10) {$+$};
\end{tikzpicture}
\end{document}
1
  • Yup, I know that, and that is how I am doing it currently. But I have many such loops and the resulting construct is remarkably inelegant! :D Commented Nov 30, 2011 at 20:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.