[Tex/LaTex] How to have a specific style for empty cells in a tikz matrix

tikz-matrixtikz-pgftikz-styles

I have a tikz matrix as the one in the code below which contains some empty cells. (Don't care about issues with column and row separations. I left that out for the sake of simplicity.)

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

\begin{document}
    \begin{tikzpicture}[
            table/.style={
                matrix of nodes,
                nodes in empty cells,
                nodes = {fill=gray, draw = black},
            }
        ]
        \matrix (test) [table] {
            1 & 2 & 3 \\
            4 &   & 5 \\
        };
    \end{tikzpicture}
\end{document}

I use the nodes in empty cells option since I want the cells to be adressable by the matrix name and column/row number. One implication of this option is that every empty cell contais a node without content which, however, has the same style applied as all other nodes.

I am searching for a way to give the empty cells a different style (different fill color and no border) without

  1. losing the adressability of the single cells
  2. having to manually add a style to every empty cell.

Is there such an option that I did not find yet or do I have to "mimic" the nodes in empty cells option myself to plug in some different style?

Best Answer

The macro in the matrix library that adds nodes in empty cells seem to be \tikz@lib@matrix@empty@cell, defined on line 24 of tikzlibrarymatrix.code.tex. You can perhaps make a new style for the empty cells, and redefine that macro from the matrix library to include the new style in the node found in the definition of the macro.

output of code

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\tikzset{empty node/.style={draw=none,fill=none}}
\makeatletter
\def\tikz@lib@matrix@empty@cell{\iftikz@lib@matrix@empty\node[name=\tikzmatrixname-\the\pgfmatrixcurrentrow-\the\pgfmatrixcurrentcolumn,empty node]{};\fi}
\makeatother
\begin{document}
    \begin{tikzpicture}[
            table/.style={
                matrix of nodes,
                nodes in empty cells,
                nodes = {fill=gray, draw = black},
            }
        ]
        \matrix (test) [table] {
            1 & 2 & 3 \\
            4 &   & 5 \\
        };

     \draw [red] (test-2-2.center) -- (test-1-3.center);
    \end{tikzpicture}
\end{document}