Matrix with external elements and dashed separation lines

matrices

I am trying to make a matrix with external elements and dashed separation lines for clarification. I have gotten pretty far using the blkarray package. However, I have failed to add a horizontal separation line between rows f and g, only inside the matrix. Also, I would like the separation lines to be dashed.

EDIT:
Sorry, I should have been more explicit. I would like both separation lines to be dashed. Will try no if this works with any of the provided answers.

enter image description here

\documentclass{article}
\usepackage{amsmath}
\usepackage{blkarray}
\begin{document}
\begin{equation}
 H =
 \begin{blockarray}{ccccc}
  & a & b & c & d\\
  \begin{block}{c(cc|cc)}
   e & 1 & 2 & 3 & 4\\
   f & 5 & 6 & 7 & 8\\ 
   g & 9 & 0 & 1 & 2\\
   h & 3 & 4 & 5 & 7\\
  \end{block}
 \end{blockarray}
\end{equation}
\end{document}

Best Answer

With {pNiceArray} of nicematrix.

\documentclass{article}
\usepackage{nicematrix}
\begin{document}
\begin{equation}
 H =
 \begin{pNiceArray}{cc|cc}[first-row,first-col]
  & a & b & c & d\\
   e & 1 & 2 & 3 & 4\\
   f & 5 & 6 & 7 & 8\\
   \hdottedline
   g & 9 & 0 & 1 & 2\\
   h & 3 & 4 & 5 & 7\\
 \end{pNiceArray}
\end{equation}
\end{document}

You need several compilations (because nicematrix uses PGF/Tikz nodes under the hood).

Ouput of the above code

If you want dashed lines, you can draw them with Tikz, you can define a custom type of line with custom-line which provides a way to use whatever Tikz style of line you want. You need at least nicematrix version 6.10a (2022-06-26).

\documentclass{article}
\usepackage{nicematrix,tikz}
\begin{document}

\NiceMatrixOptions
  {
    custom-line = 
     {
       letter = I ,            % <- for the vertical rules
       command = hdashedline , % <- for the horizontal rules
       tikz = dashed ,
       total-width = \pgflinewidth   % <- optional
     }
  }

\begin{equation}
 H =
 \begin{pNiceArray}{ccIcc}[first-row,first-col]
  & a & b & c & d\\
   e & 1 & 2 & 3 & 4\\
   f & 5 & 6 & 7 & 8\\
 \hdashedline
   g & 9 & 0 & 1 & 2\\
   h & 3 & 4 & 5 & 7\\
 \end{pNiceArray}
\end{equation}
\end{document}

Output of the above code