# [Tex/LaTex] How to color a portion of a row in bmatrix

matricesrowcolor

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.

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 \newcommands; the first is for calculating the coordinates of the shaded parts and the second is for performing the shading as follows:

\newcommand{\DoTikzmark}[1]{%
\tikz[remember picture] \coordinate[shift={(0,.7ex)}](#1);%
}


and

\newcommand{\colrow}[3][]{%
\tikz[overlay,remember picture, line width=10pt]
\draw[shorten >=-.1em, shorten <=-.1em, #1] (#2)--(#3);
}


Here is the full code:

\documentclass{article}
\usepackage{mathtools}
\usepackage{tikz}

\newcommand{\DoTikzmark}[1]{%
\tikz[remember picture] \coordinate[shift={(0,.7ex)}](#1);%
}
\newcommand{\colrow}[3][]{%
\tikz[overlay,remember picture, line width=10pt]
\draw[shorten >=-.1em, shorten <=-.1em, #1] (#2)--(#3);
}

\begin{document}
$\begin{bmatrix*}[r] 3 & 1 & \DoTikzmark{num-3}{-}3 & 0 & {4}\DoTikzmark{num4} & 1 \\ 0 & 1 & -1 & 2 & -2 & 5 \\ \DoTikzmark{num-2}{-}2 & -3 & 1 & 1 & 0&{1}\DoTikzmark{num1} \\ \end{bmatrix*}$
\colrow[blue ,opacity=.5]{num-3}{num4}
\colrow[green,opacity=.5]{num-2}{num1}
\end{document}


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.