[Tex/LaTex] Rectangle box around elements of matrix

matrices

Here, I wish to draw a rectangle around the principal diagonal elements (red colored) of the below matrix.

MWE:

\documentclass{article}

\usepackage{amsmath,xcolor}

\begin{document}

Here, I wish to draw a rectangle around the principal diagonal elements 
(red colored) of the below matrix.
\[
  A = \begin{bmatrix} 
    \textcolor{red}{1} & 2 & 3 & 4\\
    1 & \textcolor{red}{2} & 3 & 4\\
    1 & 2 & \textcolor{red}{3} & 4\\
    1 & 2 & 3 & \textcolor{red}{4}
  \end{bmatrix}
\]

\end{document}

Best Answer

Like this?

Output of the first code

With use of nicematrix package you obtain above result after two compilation ot he following MWE:

\documentclass{article}
\usepackage{nicematrix}

\begin{document}
\[
\begin{bNiceArray}{>{\strut}llll}[margin=3mm]
\Block[draw=red]{}{1} & 2 & 3 & 4 \\
1 & \Block[draw=red]{}{2} & 3 & 4 \\
1 & 2 & \Block[draw=red]{}{3} & 4 \\
1 & 2 & 3 & \Block[draw=red]{}{4} \\
\end{bNiceArray}
\]
\end{document}

or like this:

enter image description here

\documentclass{article}
\usepackage{nicematrix,tikz}
\usetikzlibrary{fit}

\begin{document}
\[
\begin{bNiceArray}{>{\strut}cccc}[margin,extra-margin = 1pt]
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
\CodeAfter
  \begin{tikzpicture}
  \node [draw=red, rounded corners=2pt, inner ysep = 0pt,
       rotate fit=-38, fit = (1-1) (4-4) ] {} ;
  \end{tikzpicture}
\end{bNiceArray}
\]
\end{document}