I am trying to color just a portion of rows of a bmatrix. How would I achieve this? Here is what I have so far:
\documentclass{article}
\usepackage{amsmath,mathtools}
\begin{document}
\[
\begin{bmatrix*}[r]
3 & 1 & -3 & 0 & 4 & 1 \\
0 & 1 & -1 & 2 & -2 & 5 \\
-2 & -3 & 1 & 1 & 0 & 1
\end{bmatrix*}
\]
\end{document}
In the following matrix, I've highlighted row 1 and columns 3 through 5 in blue. Also, I've highlighted row 3 and columns 1 through 6 in green.
This is what I would like to achieve:
I would like a solution that uses the bmatrix environment.
Best Answer
For consistency purposes, I do not recommend using a regular TikZ matrix, but rather, I will stick to the
amsmath
/amsmathtools
. This will make the matrix at-hand have the same look and feel of other matrices in the document. Shading and marking tasks, however, are exactly where TikZ comes in.I define two
\newcommand
s; the first is for calculating the coordinates of the shaded parts and the second is for performing the shading as follows:and
Here is the full code:
Important Remarks
As we see in the above code, the matrix entries
-3
and-2
are written in quite a strange way as{-}3
and{-}2
, respectively. The intuitive question here is: What are these extra parentheses used for? Well, the minus sign by default is a binary operator and will have additional spacing, but this will depend on adjacent atoms. So, for example,${}-2$
will have space added, but$-2$
(the-
is assumed to be a prefix unary minus and) will not have any extra space.If you want to use
-
as an ordinary symbol, you want a\mathord
for the-
, or the simplest way is to use{-}
, where the additional brace group is enough to force the\mathord
behaviour.EDIT: Another alternative which seems more elegant is to enclose the whole negative number by a pair of parentheses as suggested by @PeterGrill in a comment. So, instead of
{-}2
and{-}3
, we could've written it as{-2}
and{-3}
, respectively. This way, the-
sign will not be treated as a binary operator, but as a\mathord
symbol with correct spacing.