Graphics, Figures & TablestikZ | '\foreach' Problem

Information and discussion about graphics, figures & tables in LaTeX documents.
Post Reply
jhapk
Posts: 81
Joined: Tue Apr 20, 2010 9:33 pm

tikZ | '\foreach' Problem

Post by jhapk »

Hi,

can anyone please explain why is the following code not working?

Code: Select all

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}

  \def\width{2.5}
  \def\unit{0.5*\width}
  
  \foreach \p in {0,\unit,...,\width}
  \draw (\p,0) -- (\p,1);

\end{tikzpicture}
\end{document}
I get the following error message:

Code: Select all

! Illegal unit of measure (pt inserted).
<to be read again> 
                   *
l.13   \draw (\p,0) -- (\p,1);
                              
? x

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

frederic
Posts: 9
Joined: Mon Jun 27, 2011 7:25 pm

tikZ | '\foreach' Problem

Post by frederic »

I find \foreach a little buggy when not looping over integers. For this reason I suggest the following code. I also modified the relationship between

Code: Select all

\width
and

Code: Select all

\unit
.

Code: Select all

\begin{tikzpicture}

  \def\width{2.5}
  \def\unit{0.3}
  \pgfmathtruncatemacro{\kmax}{div(\width,\unit)}
  
  \foreach \k [evaluate=\k as \x using \k*\unit] in {0,...,\kmax}{
    \draw (\x,0) -- (\x,1);
  }
 
\end{tikzpicture}
User avatar
shadgrind
Posts: 140
Joined: Thu Jul 16, 2009 12:39 am

tikZ | '\foreach' Problem

Post by shadgrind »

I tried this to see why you're getting that error:

Code: Select all

\documentclass{minimal}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
    \def\width{2.5}
    \def\unit{0.5*\width}
    \foreach \p in {0,\unit,\width}
       \draw (\p,0) -- (\p,1) node[above] {\p};
\end{tikzpicture}
\end{document}
It compiles, and the second line will have the node "0.5*2.5" above it. So maybe TikZ is getting confused about whether to treat the value of \unit as the numeric value 1.25 or as the string "0.5*2.5". Because if you replace \unit with its numeric value 1.25 in the \foreach command in your original example, it works. So I would say ditch \unit.
System: TeX Live 2012, Fedora 18 x86_64, GNU Emacs 24.2
Post Reply