5

I'm trying to write a macro that given some coordinates colors the corresponding cells in a matrix black. This is related to this question. I fail at adapting one of the answers from that question. Here is some code:

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}


\begin{document}
\begin{tikzpicture}
\tikzstyle{mymatrix}=[draw]  
\foreach \i in {1,2,3} {
    \globaldefs=1 
    \edef\dotikzset{
        \noexpand\tikzset{
            mymatrix/.append style={
                row \i column \i/.style={
                    nodes={fill=black}
                }
            }
        }
    }
    \dotikzset
}

  \matrix [matrix of nodes, mymatrix, nodes in empty cells, nodes={draw, minimum size=5mm}]
  {
     &  &  \\
     &  &  \\
     &  &  \\
  };
\end{tikzpicture}

\end{document}

I expect it to color the diagonal black, but it only produces white cells. If I replace one of the \i in the row \i column \i line with a constant, it works just fine. I don't understand why it doesn't work with two references to \i.

2 Answers 2

5

When TeX expands row \i column \i/.style the space after the \i is removed. So when \i is 1 the result is row 1column 1.

One way around this is to use \space after the first \i: row \i\space column \i/.style

5

You can also use the list handler

\documentclass[tikz]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[mymatrix/.style={draw}]  
\tikzset{
  mymatrix/.append style={row #1 column #1/.style={nodes={fill=black}}},
  mymatrix/.list={1,2,3}
}
  \matrix [matrix of nodes, mymatrix, nodes in empty cells, nodes={draw, minimum size=5mm}]
  {
     &  &  \\
     &  &  \\
     &  &  \\
  };
\end{tikzpicture}
\end{document}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .