[Tex/LaTex] Print zeroes in a sparse matrix in a lighter color

colormatrices

For a report I need to print some sparse matrices as full matrices, so that means that there are a lot of zeroes. If I print them in the same color as the meaningful entries, it doesn't look very organized. And when I don't print the zeroes at all, it also doesn't look that good. So I'd like to print the zeroes in a lighter color.

Of course I could define a color (e.g. \definecolor{lightgrey}{RGB}{200,200,200}, and then for each 0 write \textcolor{lightgrey}{0}. But this is not very efficient. It is also possible to define a new command, preferably with a short name, that just inserts the grey colored 0. But I wonder, is there another, cleaner way to accomplish this?

MWE for a relatively small matrix:

\documentclass[10pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\begin{document}

\begin{align}
\left(\begin{array}{ccccccccc} 
1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 
0 & 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 
0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 & 0 & 0 & 0\\ 
0 & 0 & 0 & 1 & 0 & 0 & 0 & 0 & 0\\ 
0 & 0 & 0 & 0 & 1 & 0 & 0 & 0 & 0\\ 
0 & 0 & 0 & 0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0\\ 
0 & 0 & 0 & \frac{1}{2} & 0 & 0 & \frac{1}{2} & 0 & 0\\ 
0 & 0 & 0 & 0 & \frac{1}{2} & 0 & 0 & \frac{1}{2} & 0\\ 
0 & 0 & 0 & 0 & \frac{1}{4} & \frac{1}{4} & 0 & \frac{1}{4} & \frac{1}{4} 
\end{array}\right)
\end{align}

\end{document}

Best Answer

I basically type too many matrices with lots of figures etc. so it's kind of natural to me to use TikZ for this, but understandably, you might not want to use this. However, there is a particular option in matrix library that you can decide on what to do when a particular entry is empty. Here is an example

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}

I like lower triangular matrices so does Gauss while eliminating.
\[
\begin{tikzpicture}[baseline=(current bounding box.center)]% To center the matrix in the equation
\matrix[matrix of math nodes,execute at empty cell={\node[black!20]{0};},%Node color and text "0"
        every left delimiter/.style={xshift=1ex},%tighter delimiter spacing
        every right delimiter/.style={xshift=-1ex},
                left delimiter={(},right delimiter={)}
                ] {
1 &  &  &  &  &  &  &  & \\ 
 & 1 &  &  &  &  &  &  & \\ 
 & \frac{1}{2} & \frac{1}{2} &  &  &  &  &  & \\ 
 &  &  & 1 &  &  &  &  & \\ 
 &  &  &  & 1 &  &  &  & \\ 
 &  &  &  & \frac{1}{2} & \frac{1}{2} &  &  &\\ 
 &  &  & \frac{1}{2} &  &  & \frac{1}{2} &  & \\ 
 &  &  &  & \frac{1}{2} &  &  & \frac{1}{2} & \\ 
 &  &  &  & \frac{1}{4} & \frac{1}{4} &  & \frac{1}{4} & \frac{1}{4} \\
};
\end{tikzpicture}
\]
\end{document}

enter image description here