Change color of indices and elements of an array?

\num is a pretty often used macro in TeX packages. Try to avoid using straight words for macro names or prefix them with my such \mynum

\documentclass[tikz]{standalone}
\begin{document}
  \begin{tikzpicture}
    \foreach \x\xc\xb[count=\xi from 0] in {3/red/blue, 1/red/blue, 4/blue/red, 1/yellow/black, 5/blue/green}{
    \node[draw=\xc,text=\xb,label=-90:\xi] (s-\xi) at (\xi,0) {\x}; 
    }
  \end{tikzpicture}
\end{document}

enter image description here


You can use \foreach[count=\i] to have an extra variable that represents the current index in the loop. To iterate over pairs of values (in this case an index and a color) you can say \foreach \n/\thecolor in {1/red,2/black}{do stuff}. If you don't provide a second element of the pair like {1/red,2} then the second variable will default to the same value as the first, so you can test whether the two variables are equal and provide a default. To do this check, I say \ifx\n\thecolor \def\thecolor{black} \fi.

\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[cell/.style={minimum size=6mm, draw, rectangle}]
    \foreach[count=\i] \n/\thecolor in {3, 1/red, 4/red, 1, 5}{
        \ifx\n\thecolor \def\thecolor{black}\fi % make color default to black
        \draw (\i,0) 
           node[cell,text=\thecolor] {\n} 
           node[below=0.5cm] {\i};
    }
\end{tikzpicture}

\begin{tikzpicture}
    \foreach[count=\i] \n/\thecolor in {3, 1/red, 4/red, 1, 5}{
      \ifx\n\thecolor \def\thecolor{black}\fi 
       \draw (\i,0) 
           node[cell] {\n} 
           node[below=0.5cm,text=\thecolor] {\i};
    }
\end{tikzpicture}
\end{document} 

You can specify the array like

\acunaarray{3,1,[red]4,*[blue]1,5}

where [red]4 will only make the cell's contents red; adding a *, also the index will be colored.

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

\ExplSyntaxOn
\NewDocumentCommand{\arrayelement}{sou\q_stop}
 {
  \node[minimum~size=6mm, draw, rectangle]~at~(s)~
    { \IfValueT{#2}{\color{#2}} #3 };
  \node at~($(s)-(0,0.5)$)~
    { \IfBooleanT{#1}{\color{#2}}\int_to_arabic:n { \l_acuna_index_int } };
  \int_incr:N \l_acuna_index_int
  \coordinate (s)~at~($(s) + (1,0)$);
 }
\NewDocumentCommand{\acunaarray}{m}
 {
  \begin{tikzpicture}
  \int_zero:N \l_acuna_index_int
  \coordinate (s)~at~(0,0);
  \clist_map_inline:nn { #1 }
   {
    \arrayelement##1\q_stop
   }
  \end{tikzpicture}
 }
\int_new:N \l_acuna_index_int
\ExplSyntaxOff

\begin{document}

\acunaarray{3,1,[red]4,*[blue]1,5}

\end{document}

enter image description here

Tags:

Color

Tikz Pgf