6

My problem is pretty much complicated than this one, but the point is pretty similar.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\foreach \x in {2,3,4} {\draw (A\x) -- (A\x-1);}
\end{tikzpicture}
\end{document}

The thing is that I need to use the variable \x to be increased or decreased (or calculated) and to remain attached to the A. A\x works nice but I cannot get A\x-1 to work.

6

Use (A\the\numexpr\x-1\relax) to perform the operation inline.

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\foreach \x in {2,3,4} {\draw (A\x) -- (A\the\numexpr\x-1\relax);}
\end{tikzpicture}
\end{document}

enter image description here

  • Is there a function difference to the solution of wang ki wun? Just curious, it's no critics. – Dr. Manuel Kuehner Aug 23 at 17:39
  • 1
    @Dr.ManuelKuehner Wang's solution is arguably better for this simple MWE. However, the actual question was how to subtract 1 from \x inside a tikz loop, which my answer provides. – Steven B. Segletes Aug 23 at 17:42
  • 1
    That's right. The issue was not how to plot the picture but how to deal with increasing the variable. – Aweraka Aug 23 at 17:44
5

It is not a good idea to split the path in single \draw commands, the line joins won't look good. Rather, I'd suggest

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);
\draw plot[samples at={1,2,3,4}] (A\x);
\end{tikzpicture}
\end{document}
5

You only need one coordinate and draw the line in one go:

\documentclass{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\coordinate (A1) at (0,0);
\coordinate (A2) at (1,3);
\coordinate (A3) at (5,1);
\coordinate (A4) at (2,-1);

\draw (A1) \foreach \x in {2,3,4} {-- (A\x)};
\end{tikzpicture}
\end{document}

Will also give better joints as shrodingers cat noted

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.