I would like to loop over an array and access each x- and y-coordinate separately, because I want to modify the coordinates before using them on a node.

Currently it is only working when inserting the coordinates directly in the foreach loop, but my second example using an array is not working.

\documentclass{minimal}
\usepackage{tikz}

\begin{document}
    \begin{tikzpicture}

         \def\myarr {
          (1.0, 1.1),
           (0.5, 1.5),
           (1.5, 2)
         }

        \foreach \x/\y in {1/3, 2/7, 3/8} {
            \node () at (\x,\y) {\x and \y};
        }

        % Not working
        %\foreach \x/\y in {\myarr} {
        %    \node () at (\x,\y) {mynode};
        %}

    \end{tikzpicture}
\end{document}

How can I use an array to achieve the same result?

  • 1
    Welcome to TeX.SE. Would you please provide a complete and compilable example we can immediately start working with? Adding the boilerplate code is tedious work, but could have already been done by the asker. – AlexG Oct 12 at 11:03
  • Thanks. I have updated my question. – JoJota Oct 12 at 11:14
  • Would redefining \def\myarr {1.0/1.1,0.5/1.5,1.5/2} be acceptable? – Bordaigorl Oct 12 at 11:18
  • Ups, now there is less code than before. Minimal compilable means it starts with \documentclass{... and ends with \end{document}. – AlexG Oct 12 at 11:18
  • 1
    @AlexG Sorry, I hope it's fine now. – JoJota Oct 12 at 11:38
up vote 2 down vote accepted

You can loop over coordinates, i.e. \foreach \X in \myarr { \node () at \X {mynode}; } works in your example. If you want to read out the x and y coordinates, you may do

\documentclass{minimal}
\usepackage{tikz}
\def\GetX(#1,#2)#3{\def#3{#1}}
\def\GetY(#1,#2)#3{\def#3{#2}}
\begin{document}
    \begin{tikzpicture}

         \def\myarr {
          (1.0, 1.1),
           (0.5, 1.5),
           (1.5, 2)
         }

        \foreach \X in \myarr {
            \edef\temp{\noexpand\GetX\X\noexpand\myx
            \noexpand\GetY\X\noexpand\myy}
            \temp
            \node () at \X {\myx\ and \myy};
        }

    \end{tikzpicture}
\end{document}

enter image description here

This shows how \myarr is parsed. Actually, the first parenthesis are ignores, then the commas inside the parenthesis are ignored.

\documentclass{minimal}
\usepackage{tikz}

\begin{document}
   \def\myarr {{
          (1.0, 1.1),
           (0.5, 1.5),
           (1.5, 2)
         }}
  \verb|\myarr[0]| = \myarr[0] 

  \pgfmathparse{\myarr[0]}\pgfmathresult

  \pgfmathparse{\myarr[1]}\pgfmathresult

  \pgfmathparse{\myarr[2]}\pgfmathresult

  \pgfmathparse{\myarr[3]}\pgfmathresult
\end{document}

produces

demo

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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