18

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
    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. – Peter Grill Nov 30 '11 at 20:15

3 Answers3

17

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} 
Alain Matthes
  • 95,075
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}
cjorssen
  • 10,032
  • 4
  • 36
  • 126
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}
Peter Grill
  • 223,288