5

I am trying to typeset a sparse matrix:

\documentclass{article}
\usepackage{amsmath}

\newcommand{\z}{0} % Zero entry

\begin{document}
$$
 \begin{pmatrix}
 \dot{\mathit{vx}} & \dot{\mathit{vy}} & \dot{x} & \dot{y} & F \\
 \hline \\
\z & \z & -1 & \z & \\
\z & \z & \z & -1 & \z \\
 1 & \z & \z & \z & -x \\
\z & 1  & \z & \z & -gy \\
\z & \z & \z & \z & \z 
 \end{pmatrix}
$$
\end{document}

In order to enhance readability, I can set \z to use a light grey. But I'd also like to test different options (or reuse the code in slides etc.) like setting every non-zero cell in boldface.

Except from defining a nonzero command (which would be somewhat tedious), is there a simple way to set every entry in boldface but \z?

Jagath
  • 4,287
choeger
  • 915

2 Answers2

3

You can \boldmath but apply \unboldmath to \z:

\documentclass{article}
\usepackage{amsmath}
\usepackage{booktabs}

\newcommand{\z}{\mbox{\unboldmath$0$}}

\begin{document}

\[
\mbox{\boldmath
$ \begin{pmatrix}
 \dot{\mathit{vx}} & \dot{\mathit{vy}} & \dot{x} & \dot{y} & F \\
 \cmidrule(lr){1-5}
\z & \z & -1 & \z & \\
\z & \z & \z & -1 & \z \\
 1 & \z & \z & \z & -x \\
\z & 1  & \z & \z & -gy \\
\z & \z & \z & \z & \z
 \end{pmatrix}$%
}
\]
\end{document}

enter image description here

egreg
  • 1,121,712
1

Since we know \z expands to 0, we can collect every cell and compare its contents to 0 (using a string comparison - \pdfstrcmp):

enter image description here

\documentclass{article}

\usepackage{amsmath,collcell}

\newcommand{\z}{0} % Zero entry

\newcommand{\nonzero}[1]{\ifnum\pdfstrcmp{\z}{#1}=0 \z\else\mathbf{#1}\fi}
\newcommand{\hdr}{\multicolumn{1}{c}}

\newcolumntype{B}{>{\collectcell\nonzero}c<{\endcollectcell}}

\begin{document}

\[
  \left(\begin{array}{ *{5}{B} }
    \hdr{\dot{\mathit{vx}}} & \hdr{\dot{\mathit{vy}}} & \hdr{\dot{x}} & \hdr{\dot{y}} & \hdr{F} \\
    \hline
    \z & \z & -1 & \z &     \\
    \z & \z & \z & -1 & \z  \\
     1 & \z & \z & \z & -x  \\
    \z & 1  & \z & \z & -gy \\
    \z & \z & \z & \z & \z 
  \end{array}\right)
\]

\end{document}

Since we need access to the column types in order to apply \nonzero to each element within a column, we define a new column type B and use a \left(\begin{array}...\end{array}\right) construction rather than a pmatrix environment. Also, header elements that should not be bolded has to be set inside a \multicolumn to escape being formatted by \nonzero. For ease of coding, I've made this possible via \hdr.

Werner
  • 603,163