4

I would like to draw with \foreach command but in below example, the first tikzpicture works fine, the second one doesn't.

But I think the second one should be the same as the first one. Why doesn't it work?

\documentclass[border=10mm]{standalone}
\usepackage{tikz}

\begin{document}
% This one works
\begin{tikzpicture}
\draw[black]  (0,0) \foreach \x/\y in {1/1,1/1.732}  {
    -- (\x,\y)
} -- cycle;
\end{tikzpicture}
% This one doesn't work
\begin{tikzpicture}
\draw[black]  \foreach \x/\y in {0/0,1/1,1/1.732}  {
    (\x,\y) --
} cycle;      
\end{tikzpicture}

\end{document}
  • 1
    Try \draw[black] (0,0) \foreach \x/\y [remember=\x as \xold (initially 0),remember=\y as \yold (initially 0)] in {1/1,1/1.732} {% -- (\x,\y) -- (\xold,\yold) }; – user31729 Dec 31 '16 at 22:23
1
\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\begin{document}

% This one works
\begin{tikzpicture}
\draw[black]  (0,0) \foreach \x/\y in {1/1,1/1.732}  {
    -- (\x,\y)
    } -- cycle;
\end{tikzpicture}

% And this also now works
\begin{tikzpicture}
\draw[black] \foreach \x/\y [count=\i]in {1/1, 1/1.732} {%
   \ifnum\i=1(0,0)\else\fi -- (\x,\y)
   } -- cycle;      
\end{tikzpicture}

\end{document}

enter image description here

  • 1
    My idea is keep every point in the foreach loop, so don't wish to add another point in the code block. – beetlej Dec 31 '16 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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