Print zeroes in a sparse matrix in a lighter color

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


If you want to avoid recoding your document, then you can use array package to drop in the colour change:

enter image description here

\documentclass[10pt,a4paper]{article}
\usepackage[latin1]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{color,array}
\def\zerotest{0}
\newcommand\greytest[2]{%
  \def\test{#2}%
  \ifx\test\zerotest
     \def\next{\textcolor[gray]{0.7}{0}}%
  \else
     \def\next{#1#2}%
  \fi
  \next}

\begin{document}

\begin{align}
\left(\begin{array}{*{9}{>{\greytest}c}} 
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}

Tags:

Color

Matrices