MathJax - coloring sparse arrays

It's easier to read sparse matrices if the zero values are greyed out. This page demonstrates one way to achieve that when processing the math with MathJax.

$$\begin{align} \left(\begin{array}{*{9}{c}} 1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 10 & 0 & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & \frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0.42 & 1 & 0 & 0 & 0 & 0 & 0\\ 0 & 0 & 0 & 0 & 1.20 & 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}$$

Now for a 4×4 unit matrix:

$$\begin{align} \left(\begin{array}{*{4}{c}} 1 & 0 & 0 & 0\\ 0 & 1 & 0 & 0\\ 0 & 0 & 1 & 0\\ 0 & 0 & 0 & 1 \end{array}\right) \end{align}$$

Technique summary

  1. Wrap the LaTeX for each sparse matrix in a div with class "sparseArr"
  2. Before loading MathJax, set startup: {typeset: false} so that it doesn't start processing immediately
  3. Pre-process the LaTeX by replacing each & 0 with & \color{#999}0 (which targets all the middle columns)
  4. Do replaceAll for the first and last columns as well.
  5. Finally, tell MathJax to go ahead and process the page.

Of course, this relies on the original LaTeX being written carefully with consistent spacing.