Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

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?

share|improve this question
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
add comment

3 Answers 3

up vote 12 down vote accepted

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} 
share|improve this answer
    
I would have never thought of ... + 1 :) –  Mariano Suárez-Alvarez Nov 30 '11 at 20:46
    
This one is minimally disruptive, so far. –  Mariano Suárez-Alvarez Nov 30 '11 at 21:00
add comment

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}
share|improve this answer
add comment

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}
share|improve this answer
    
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 –  Mariano Suárez-Alvarez Nov 30 '11 at 20:22
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.