Take the 2-minute tour ×

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:





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

    \matrix (B) [matrix of nodes, ampersand replacement = \&] {
        {0} \& {12}\\
        {1} \& {7}\\
        {2} \& {2}\\
        {3} \& {2}\\
        {} \& {2}\\
        {} \& {2}\\
        {} \& {2}\\
        {} \& {2}\\


How to achieve this?

share|improve this question
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
add comment

1 Answer

up vote 4 down vote accepted

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

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

With your code, this adds to your \hline the desired rectangles:

fitting rectangles in matrix

share|improve this answer
That will not work, though, if one of the nodes in the middle is wider. For example, if the 2 on the right of 3 is changed into 222, it will stick out of the rectangle. –  Jan Hlavacek Jan 7 '12 at 15:45
@JanHlavacek: That's true, in this case that node can be added to the fitting. However, the point of the question was turning the rectangle into a node, this has been answered. –  Stefan Kottwitz Jan 7 '12 at 16:02
Yes, there are at most 2-digit number is my matrix :) Now how to put another "merged" matrix to the right of the existing one? so that to show how the contiguous groups collapsed into one-element entries... –  Ilonpilaaja Jan 7 '12 at 16:35
@Ilonpilaaja: I suggest, write a new question on the site for the new question. Otherwise it's hard to put answers and code into comments, and it would mix topics. This is a Q&A site, other readers shall benefit too, that's why the strict Question & Answer structure, no topic discussions in comments. –  Stefan Kottwitz Jan 7 '12 at 16:55
Thanks all. This site is good at preserving the succinctness on the web; I was able to find the answer in one of the prompts that the Exchange suggested: the scopes + [xshift = 3cm] is the way to go. –  Ilonpilaaja Jan 7 '12 at 21:26
add comment

Your Answer


