tikz-pgf – How to Use Values from a 2D Array in a TikZ Picture without Out of Bounds Error

arraystikz-pgf

I would like to use a list of values from a 2d array in a Tikz picture.

The code bellow works while using a random number :

\pgfmathtruncatemacro{\r}{round(rnd*20)}

But when I replace it with the following lines, it produces an "array out of bounds" errors (but indexes are right) :

\pgfmathtruncatemacro\a{\x-1}
\pgfmathtruncatemacro\b{\y-1}
\pgfmathparse{\myNotes[\b][\a]} \let\r\pgfmathresult <<<<< ***** problem...

Thanks for help.

Code that works :

\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usetheme{CambridgeUS}
\usepackage{tikz} 

% list of numbers : 2d array
\def \myNotes {{12,6,13,15}{16,11,15,13} {14,8,10,9}{16,13,10,5}{7,11,15,12}}

\begin{document}

\begin{frame}
  \frametitle{Array}

   \newcommand{\Depth}{1}
   \newcommand{\Height}{0.9}
   \newcommand{\Width}{1}
    \pgfmathsetseed{1} % for random
   \begin{tikzpicture}[scale = 0.80]
    \foreach \y in {5,4,3,2,1}
      {
       \node at (0,\y*-1) {t} ;
       \node at (0.25,\y*-1) {\y};
       \foreach \x in {1,2,3,4}
        {
        \begin{scope}[shift={(\x,\y*-1)}]
          \pgfmathtruncatemacro\a{\x-1}
          \pgfmathtruncatemacro\b{\y-1}
           % following ligne produce "array out of bounds" for each b and a
           % *******************************************************
           %\pgfmathparse{\myNotes[\b][\a]} \let\r\pgfmathresult
          \pgfmathtruncatemacro{\r}{round(rnd*20)}%
          \coordinate (C) at (0,0,0);
          \node[black,fill=yellow] (C) {\r};
         \end{scope}
     }
 }
  \end{tikzpicture}
 \end{frame}
\end{document}

** EDIT : update code that works the way I wanted (from percusse) :

(unnecessary lines have been removed…)

\documentclass{beamer}
\usepackage[utf8]{inputenc}
\usetheme{CambridgeUS}
\usepackage{tikz} 
% **** declare a 2d array *********************************** OK
\def\myNotes{{{12,6,13,15},{16,11,15,13},{14,8,10,9},{16,13,10,5},{7,11,15,12}}} 
\begin{document}

\begin{frame}
  \frametitle{Array}
\begin{tikzpicture}[scale = 0.80]
 \foreach \y in {5,4,3,2,1}{
    \node at (0,\y*-1) {t} ;
   \node at (0.25,\y*-1) {\y};
   \foreach \x in {1,2,3,4}
    {
    \begin{scope}[shift={(\x,\y*-1)}]
        % get the value at index y-1 and x-1 ************************ OK 
        \pgfmathtruncatemacro{\r}{int(\myNotes[\y-1][\x-1])}
        \coordinate (C) at (0,0,0);
        \node[black,fill=yellow] (C) {\r};
        \end{scope}
    }
}
\end{tikzpicture}
\end{frame}
\end{document}

Best Answer

You are missing a set of braces and commas in your array. It should work if you write

\def\myNotes{{{12,6,13,15},{16,11,15,13},{14,8,10,9},{16,13,10,5},{7,11,15,12}}}

Also, you can directly set r with

\pgfmathtruncatemacro{\r}{\myNotes[\y-1][\x-1]}

or manually converting to integer

\pgfmathsetmacro{\r}{int(\myNotes[\y-1][\x-1])}