4

I'm trying to apply a style for a submatrix of a matrix and ended up by passing arguments through two .list-handlers. Things don't work as I expected, again I'm just able to set either rows or columns but not both.

What's the problem? Do you have another idea?

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

\tikzset{
  rows/.style 2 args={
    @/.style={row ##1 column #2/.style={nodes={rectangle,draw=black}}},
    @/.list={#1}
  },
  box/.style 2 args={
    @/.style={rows={#1}{##1}},
    @/.list={#2}
  }
}
\tikzset{square matrix/.style={
    matrix of nodes,
    column sep=-\pgflinewidth, row sep=-\pgflinewidth,
    nodes={
      minimum height=#1,
      anchor=center,
      text width=#1,
      align=center,
      inner sep=0pt
    },
  },
  square matrix/.default=1.2cm
}


\begin{document}

\begin{tikzpicture}[]
\matrix[square matrix,
  box={1,...,3}{3,2} % apply the style to cells {1,3},{2,3},{3,3},{1,2},{2,2},{3,2}
]
{
   & x & x &   &   &   \\
   &   & x &   & x &   \\
 x & x & x & x & x &   \\
   &   & x &   &   &   \\
};
\end{tikzpicture}
\end{document}
1

1 Answer 1

3

Your code is almost ok. You have just to not use the same style @ in rows and box.

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

\tikzset{
  rows/.style 2 args={
    sub@rows/.style={row ##1 column #2/.style={nodes={rectangle,draw=red}}},
    sub@rows/.list={#1}
  },
  box/.style 2 args={
    sub@box/.style={rows={#1}{##1}},
    sub@box/.list={#2}
  }
}
\tikzset{square matrix/.style={
    matrix of nodes,nodes in empty cells,
    column sep=-\pgflinewidth, row sep=-\pgflinewidth,
    nodes={
      minimum height=#1,
      anchor=center,
      text width=#1,
      align=center,
      inner sep=0pt
    },
  },
  square matrix/.default=1.2cm
}


\begin{document}

\begin{tikzpicture}[]
\matrix[square matrix,
  box={1,...,3}{3,2} % apply the style to cells {1,3},{2,3},{3,3},{1,2},{2,2},{3,2}
]
{
   & x & x &   &   &   \\
   &   & x &   & x &   \\
 x & x & x & x & x &   \\
   &   & x &   &   &   \\
};
\end{tikzpicture}
\end{document}

enter image description here

2
  • Why does it makes a difference, that I used the same style name? Is a latter style assignment not able to redefine already assigned styles? Also thanks for the code clean-up, plus specifying nodes in empty cells :)
    – user92995
    Commented Nov 29, 2015 at 14:56
  • The style name is not locally scoped. So when you apply row inside box it was redefining the @ style.
    – Kpym
    Commented Nov 29, 2015 at 15:16

You must log in to answer this question.