6

As far as I know, the following example is incorrect because I can't subtract inside the \foreach list.

\documentclass[border=10pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\centering
\begin{tikzpicture}

  \pgfmathsetmacro{\Width}{32}

  \foreach \i in {1,...,\Width-1}{
    % ...
  }

\end{tikzpicture}
\end{document}

What would be the best approach for subtracting from \Width? Using \pgfmathsetmacro again like so?

  \pgfmathsetmacro{\WidthMinusOne}{\Width-1}
  \foreach \i in {1,...,\WidthMinusOne}{
    % ...
  }

Thanks.

3
  • 3
    See the pgf manual section 88, especially about evaluate (page 1004-5)
    – daleif
    Commented Nov 8 at 13:09
  • 1
    See also tex.stackexchange.com/q/730336/117050 in case you need calculations on other list elements than the last as well.
    – Skillmon
    Commented Nov 8 at 16:02
  • @daleif i did not see your comment :/
    – JeT
    Commented Nov 8 at 23:04

3 Answers 3

6

For this simple case, you can use \numexpr:

\documentclass[border=10pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}
\centering
\begin{tikzpicture}

  \pgfmathsetmacro{\Width}{32}

  \foreach \i in {1,...,\numexpr\Width-1}{
    \node at (\i,\i) {\i};
  }

\end{tikzpicture}
\end{document}
7

You can make TikZ into evaluating the last item by using parse=true.

\documentclass[border=10pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{calc}

\begin{document}

\begin{tikzpicture}
  \pgfmathsetmacro{\Width}{4}
  \foreach[parse=true] \i in {1,...,\Width-1}{
    \node at (\i,0) {\i};
  }
\end{tikzpicture}

\end{document}

example

3

What about evaluate ?

enter image description here

\documentclass[border=10pt]{standalone}

\usepackage{tikz}
%\usetikzlibrary{calc}

\begin{document}
\centering
\begin{tikzpicture}

  \pgfmathsetmacro{\Width}{32}

  \foreach \i [evaluate=\i as \j using int(\i-1)] in {1,...,\Width}{
    \node at (\i, \j) {\j};
  }

\end{tikzpicture}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .