[Tex/LaTex] Equal matrix column width and draw vertical line

amsmathmath-modematricesspacing

I want to write a matrix with equal column widths, plus have a vertical line down the matrix. By using the solutions given here and here, I have

\documentclass{article}
\usepackage{geometry}
\usepackage{amsmath}
\usepackage{graphicx}

% draw vertical line down matrix
\makeatletter
\renewcommand*\env@matrix[1][*\c@MaxMatrixCols c]{%
  \hskip -\arraycolsep
  \let\@ifnextchar\new@ifnextchar
  \array{#1}}
\makeatother

\begin{document}

\resizebox{\linewidth}{!}{%
\begin{equation}
\begin{pmatrix}[cc|cc]
 C1 & Column2 & C3 & C4 \\ \hline
 C5 & C6 & C7 & Column8
\end{pmatrix}$%
\end{equation}
}

\end{document}

The output matrix does not have equal column widths, and I get an error Missing $ inserted. How can I solve this problem?

Best Answer

Notes:

  1. The error Missing $ inserted is because of the single $ sign at \end{pmatrix}$%.
  2. You can use \resizebox{.9\hsize}{!}{% inside the equation (see Scale an equation to fit exact page width).
  3. I used tabularx to define a new columntype C, witch allows you to set the width of a centered entry by using C{<width>}.

Code:

\documentclass{article}
\usepackage{geometry}
\usepackage{amsmath}
\usepackage{graphicx}

% draw vertical line down matrix
\makeatletter
\renewcommand*\env@matrix[1][*\c@MaxMatrixCols c]{%
  \hskip -\arraycolsep
  \let\@ifnextchar\new@ifnextchar
  \array{#1}}
\makeatother

\usepackage{tabularx}
\newcolumntype{C}[1]{>{\hspace{0pt}\centering\arraybackslash}p{#1}}

\begin{document}

\begin{equation}
    \resizebox{.9\hsize}{!}{\ensuremath{
        \begin{pmatrix}[*2{C{15mm}}|*2{C{15mm}}]
            C1 & Column2 & C3 & C4 \\ \hline
            C5 & C6 & C7 & Column8
        \end{pmatrix}%
    }}
\end{equation}

\end{document}

Result:

enter image description here

Related Question