7

This seems like it should be simple but I can't get it to work. I simply want to draw a circle and the x coordinate of the center to be specified by an entry in a given array. For example suppose I want to draw circles centered at (1,1), (1,2)

\def\testarray{1,2}
\def\circleHeights{1,2}

\foreach \y in circleHeights {

\filldraw [black] (\testarray[1],\y) circle (1pt);

Doesn't work. But it does work replacing \testarray[1] with just 1. How to you properly access an array? I've done a bit of searching and I've tried using \pgfmathparse and \pgfmathsetmacro: For example as

\foreach \y in circleHeights {
\pgfmathsetmacro{\x}{\testarray[1]}
\filldraw [black] (\x,\y) circle (1pt);

I've also tried the array defined like \def\testarray{{1,2}} since I saw some examples like that as well. I realize that I could do the above task easily without needing to access the array, but in my actual situation I need to do something like this. So I'd like to find a way to make this approach work

Herr K.
  • 17,946
  • 4
  • 61
  • 118
Fractal20
  • 255
  • 2
    After \def\testarray{1,2}, if you feed \testarray[1] you simply obtain 1,2[1]. TeX just expands the macro; it has no concept of arrays (unless you teach it to). – egreg Feb 10 '15 at 19:03

2 Answers2

12

If you define a macro to store an array (for use with pgfmath) you have to use surrounding braces:

\def\testarray{{1,2}}

Note that indexing starts with zero.

\documentclass[tikz,margin=10pt]{standalone}
\begin{document}
\def\testarray{{1,2}}
\def\circleHeights{{0.5,2}}
\begin{tikzpicture}
\draw[help lines,step=.5](0,0)grid(3,3);
\foreach \i in {0,1}
  \filldraw[black] (\testarray[\i],\circleHeights[\i]) circle[radius=1pt];
\end{tikzpicture}
\end{document}

enter image description here

esdd
  • 85,675
2

Just to extend @esdd's answer you can use a 2-dimensional array instead:

\documentclass[tikz,margin=10pt]{standalone}
\begin{document}
\def\testarray{{{1,0.5},{2,2}}}
\begin{tikzpicture}
\draw[help lines,step=.5](0,0)grid(3,3);
\foreach \i in {0,1}
  \filldraw[black] (\testarray[\i][0],\testarray[\i][1]) circle[radius=1pt];
\end{tikzpicture}
\end{document}

As you can see, there is only one array containing the coordinates as pairs.

qwerty_so
  • 135