TikZ-PGF – How to Access an Entry in an Array within TikZ

tikz-pgf

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

Best Answer

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