0

Right now, I have the code below that makes this

enter image description here

However, I'd like to illustrate that a 2D array is an array of arrays.I'd like to put a unique string inside the boxes such as "[3, 1, 4, 1, 5]", "[2, 4, 6, 8, 10]", etc. I want to have full control of the strings inside the boxes.

Any help is appreciated!

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}

\newcounter{index}

\begin{document}

\begin{figure}
\centering
  \begin{tikzpicture}
    \setcounter{index}{0}
    \coordinate (s) at (0,0);
    \foreach \num in {3, 1, 4, 1, 5}{
      \node[minimum size=6mm, draw, rectangle] at (s) {\num};
      \node at ($(s)-(0,0.5)$) {\theindex};
      \stepcounter{index}
      \coordinate (s) at ($(s) + (1,0)$);
    }
  \end{tikzpicture}
  \label{fig:testArray}
\end{figure}

\end{document}
1
2

Is this what you mean? I used the second option you stated in the question, that is, I put the string "[3, 1, 4, 1, 5]" inside the boxes. You don't actually need a \newcounter{index} since you are using a loop counter.

Edit

The updated answer below deals with different entries inside the boxes.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}

\begin{figure}
\centering
  \begin{tikzpicture}[subarray/.style={minimum size=6mm, draw, anchor=west,xshift=1ex}]
    \node (s0) {};
    \foreach \subarray[count = \num from 0, 
      evaluate=\num as\n using int(\num+1)] in {{[3, 1, 4, 1, 5] },
                                                {[2, 4, 6, 8, 10]},
                                                {[1, 3, 5, 4, 9] },
                                                {[2, 4, 6, 8, 10]},
                                                {[5, 2, 7, 3, 8] }}
      \node (s\n) [subarray] at (s\num.east) {\subarray} node[below=1ex of s\n]{\num};
  \end{tikzpicture}
  \label{fig:testArray}
\end{figure}

\end{document}

enter image description here

3
  • Hi AboAmmar. Thank you for your response! I was just wondering if you knew how to make it so that each array in each box was different?
    – jmacuna
    Aug 14 '17 at 17:36
  • @jmacuna - If the entries are totally different, one can add another counter to carry these entries. If, hopefully, there is some kind of relation between these arrays, the code can be more concise. Feel free to edit your question adding an example of different entries and I will update my answer accordingly.
    – AboAmmar
    Aug 14 '17 at 17:47
  • thanks for message. I updated the question. Unfortunately, I would like to put arbitrary arrays in the boxes with no relation. Thank you so much for your help!
    – jmacuna
    Aug 14 '17 at 17:52

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.