# TikZ: Rectangle spanning a submatrix, as a node

I specify the corners of a rectangle, spanning a certain submatrix of a matrix, and want this rectangle to be a node. The minimal example is:

\documentclass{standalone}

\usepackage{tikz,pgf}

\usetikzlibrary{scopes,arrows,calc,shapes.misc,shapes.arrows,chains,matrix,positioning,decorations.pathmorphing,shapes}

\begin{document}

\newcommand{\bbrect}[2]{\draw (B-#1-2.north west) rectangle (B-#2-2.south east)}

\begin{tikzpicture}
\ttfamily
\matrix (B) [matrix of nodes, ampersand replacement = \&] {
\hline
{0} \& {12}\\
{1} \& {7}\\
{2} \& {2}\\
{3} \& {2}\\
{} \& {2}\\
{} \& {2}\\
{} \& {2}\\
{} \& {2}\\
};
\bbrect{1}{1};
\bbrect{2}{2};
\bbrect{3}{8};
\end{tikzpicture}

\end{document}

How to achieve this?

-
Possibly duplicate of problem in: tex.stackexchange.com/a/15148/7049. Answer is equivalent. –  zeroth Jan 7 '12 at 13:06
Is it possible to give the reason why you want it to be a node? Since matrix is filled with nodes it is relatively easy to access the to-be-drawn rectangle coordinates with matrix entry anchors. –  percusse Jan 7 '12 at 13:57
Nodes in a submatrix can be very useful for later use, for example for arrows and annotations. Like here: Highlighting while transposing a matrix. –  Stefan Kottwitz Jan 7 '12 at 14:28
@percusse: it is to convey the idea that the contiguous group of "2"s collapse into one group, etc. I'll have another, "merged" version on the left. –  Ilonpilaaja Jan 7 '12 at 14:49

You could use the fit library. Specify rectangle and draw option, the points spanning the rectangle, and inner sep=0 for tight fitting:

\newcommand{\bbrect}[2]{%
\node[rectangle, draw, fit=(B-#1-2.north west) (B-#2-2.south east),
inner sep=0pt] {}}