# How to draw a nice diagonal matrix?

How to typeset a nice looking diagonal matrix? I find myself, once again, fiddling with phantoms and running raiseboxes to get an aesthetic result. This kind of micromanagement is bad practice, but why does the default look so bad and is there a better way?

\documentclass{article}
\usepackage{mathtools}
\begin{document}

\begin{align*}
\operatorname{diag} x &=
\begin{bmatrix}
x_1 & 0 & 0\\
0 & \ddots & 0 \\
0 & 0 & x_n
\end{bmatrix}
&
\operatorname{diag} x &=
\begin{bmatrix}
x_1 & 0 & 0\\
0 & \raisebox{-0.4ex}{$$\ddots$$}\rule[3.4ex]{0pt}{0pt} & 0 \\
0 & 0 & x_n \rule[3.4ex]{0pt}{0pt}
\end{bmatrix}
\end{align*}

\end{document}

• First, use \DeclareMathOperator if you use "diag" many times in the document. – user156344 Apr 17 at 11:34
• Hmm, the problem is not with bmatrix, but with \ddots. – user156344 Apr 17 at 11:39
• \def\arraystretch{1.5}% outside align or inside equation – John Kormylo Apr 17 at 15:17

A TABstack alternative.

\documentclass{article}
\usepackage{mathtools,tabstackengine}
\TABstackMath% STACK MATRIX IN MATH MODE
\setstacktabbedgap{10pt}% INTER-COLUMN GAP SIZE
\setstackgap{L}{1.5\baselineskip}% INTER-ROW BASELINESKIP
\newcommand\cddots{\raisebox{-1pt}{$\ddots$}}
\begin{document}
$\operatorname{diag} x = \bracketMatrixstack{ x_1 & 0 & 0\\ 0 & \cddots & 0 \\ 0 & 0 & x_n }$
\end{document}


While not needed for diagonal matrices of the type portrayed by the OP, the package has a \fixTABwidth{<T or F>} declaration to fix all column widths to the largest found in the matrix. That can be helpful if there are wide matrix entries:

\documentclass{article}
\usepackage{mathtools,tabstackengine}
\TABstackMath% STACK MATRIX IN MATH MODE
\setstacktabbedgap{10pt}% INTER-COLUMN GAP SIZE
\setstackgap{L}{1.5\baselineskip}% INTER-ROW BASELINESKIP
\newcommand\cddots{\raisebox{-1pt}{$\ddots$}}
\begin{document}
\fixTABwidth{T}
$\operatorname{diag} x = \bracketMatrixstack{ x_1 & 0 & 12345\\ 0 & \cddots & 0 \\ 0 & 0 & x_n }$
\end{document}


You could if you liked to use the package nicematrix. Between the many options defined by nicematrix there is columns-width, where you can fit the two brackets of the matrix in function of the values into it.

\documentclass{article}
\usepackage{mathtools}
\usepackage{nicematrix}
\NiceMatrixOptions{transparent,nullify-dots}
\begin{document}
$\operatorname{diag} x =\begin{bmatrix}[columns-width = 3mm] x_1 & 0 & 0\\ 0 & \ddots & 0 \\ 0 & 0 & x_n \end{bmatrix}$
\end{document}


Another possibility using columns-width = auto:

\documentclass{article}
\usepackage{mathtools}
\usepackage{nicematrix}
\NiceMatrixOptions{transparent,nullify-dots}
\begin{document}

$\operatorname{diag} x =\begin{bmatrix}[columns-width = auto] x_1 & 436436 & 67676\\ 0 & \ddots & 0 \\ 8778 & 0 & x_n \end{bmatrix}$

\end{document}