Número faltante, tratado como error cero cuando se usan bucles for y condicionales en tikz

Número faltante, tratado como error cero cuando se usan bucles for y condicionales en tikz

Sería bueno poder tener un código que, al modificar ciertos parámetros como el alto y el ancho y las celdas para que sean de color rojo o verde, genere una tabla para mí. El código que tengo ya es una modificación de algo que encontré, pero no consigo que funcionen las celdas coloreadas. El error es "Falta un número, tratado como cero". Estoy empezando en tikz y no entiendo mucho.

\begin{figure}[H]
\centering
 \begin{tikzpicture}
[
    square/.style = {
        draw, 
        rectangle, 
        minimum size=\m, 
        outer sep=0, 
        inner sep=0, 
        font=\normalsize\bfseries,
        label={[anchor=north,yshift=1.1em,opacity=0.7]south:\scriptsize\label}
    },
]
\def\m{35pt}
\def\w{4}
\def\h{4}

% Array of personalized messages
\def\content{{
    {1, 0, 1, 1},
    {1, 1, 0, 0},
    {0, 0, 1, 0},
    {0, 1, 1, 1}
}}

% Separate arrays for x and y coordinates in greenCoords
\def\greenXCoords{{1, 1, 1, 1}} % x-coordinates
\def\greenYCoords{{1, 2, 3, 4}} % y-coordinates

% Y
\foreach \x in {1,...,\w}
    \foreach \y in {1,...,\h}
    {   
        % Check if the current coordinates match any green cells
        \foreach \i in {1,...,4}
        {
            \ifthenelse{\x=\greenXCoords[\i] \AND \y=\greenYCoords[\i]}
                {\def\fillColor{green!30}\break}
                {\def\fillColor{black!5}}
        }
        
        \pgfmathtruncatemacro{\label}{(\y-1) * \w + \x}
        \node [square, fill=\fillColor]  (Y\x,\y) at (\x*\m,-\y*\m) {\pgfmathparse{\content[\y-1][\x-1]}\pgfmathresult};
    }
\end{tikzpicture}
    \caption{Caption}
    \label{fig:enter-label}
\end{figure}

Tabla obtenida

Respuesta1

La sintaxis de la matriz\greenXCoords[\i] es unaSintaxis de PGFMathy no entendido por \ifthenelse.

Deberá evaluarlos de antemano, digamos

\pgfmathsetmacro\xTest{\greenXCoords[\i]}
\pgfmathsetmacro\yTest{\greenYCoords[\i]}
\ifthenelse{\x=\xTest \AND \y=\yTest}

o utilizar el propio de PGFMathifthenelsefuncióno utilice un enfoque completamente diferente para matrices y condicionales.

O construye su tabla sin tener que recorrer tantas matrices y bucles. (Una matriz PGFMath no es la mejor estructura de datos).


Aquí hay una solución que recorre el contentvalor directamente usando su propia estructura (ya está formada por filas y columnas).

Unos pocos estilos y claves y podrá construir una tabla con cualquier contenido, cualquier tamaño y cualquier combinación de celdas verdes.

Aquí, es necesario proporcionar el número de columnas (para el cálculo de la etiqueta), pero podría haber soluciones que lo determinen automáticamente (¿desde la primera fila/la más larga?) o simplemente contar para cada elemento que no crearía agujeros si las filas no tienen todas el mismo número de columnas.

Código

\documentclass[tikz]{standalone}
\tikzset{
  % let's do this in our own namespace
  my table/.cd,
  % initial values and settings
  content/.initial={{1, 0, 1, 1},
                    {1, 1, 0, 0},
                    {0, 0, 1, 0},
                    {0, 1, 1, 1}},
  size/.initial=35pt,
  columns/.initial=4,
  square/.style={
    shape=rectangle, draw, minimum size=\pgfkeysvalueof{/tikz/my table/size},
    outer sep=+0pt, inner sep=+0pt, fill=black!5, font=\normalsize\bfseries},
  label/.style={
    label={[anchor=south, font=\scriptsize, lightgray]south:{#1}}},
  % styles to set which rows, cols and cells should be green!30
  green rows/.style={green row/.list={#1}},
  green cols/.style={green col/.list={#1}},
  green cells/.style={green cell/.list={#1}},
  green row/.style={/tikz/my table/rowstyle #1/.append style={fill=green!30}},
  green col/.style={/tikz/my table/colstyle #1/.append style={fill=green!30}},
  green cell/.style={/tikz/my table/style #1/.append style={fill=green!30}}}

% the macro with one optional (!) argument
\newcommand*\PrintTable[1][]{%
  \tikz[
    my table/.cd,#1,content/.get=\myTableContent,
    % make the xyz coordinate system dependent on the size of your squares
    /tikz/x=\pgfkeysvalueof{/tikz/my table/size},
    /tikz/y=\pgfkeysvalueof{/tikz/my table/size}]
  \foreach[count=\myTableY from 0,
           count=\myTableYY from 1]\myTableRow in \myTableContent
    \foreach[count=\myTableX]\myTableCol in \myTableRow
      \node[
        my table/square,
        my table/label=\inteval{\myTableY*
          \pgfkeysvalueof{/tikz/my table/columns}+\myTableX},
        my table/rowstyle \myTableYY/.try,        % 1. row style
        my table/colstyle \myTableX/.try,         % 2. col style
        my table/style \myTableYY-\myTableX/.try, % 3. cell style
      ] at (\myTableX,-\myTableY) {\myTableCol};%
}
\begin{document}
\PrintTable[green cells={1-1, 1-2, 1-3, 1-4}]
\PrintTable[green row=1, columns=3, content={{  1,   2,   3},
                                             { 19,  20,  21},
                                             {123, 456, 789}}]
\end{document}

Producción

ingrese la descripción de la imagen aquí ingrese la descripción de la imagen aquí

información relacionada