Rectangle box around elements of matrix

Like this?

enter image description here

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}%
[create-extra-nodes,margin,extra-margin = 2pt ,
code-after = {\begin{tikzpicture}
[name suffix = -large,
every node/.style = {draw=red,
inner sep = -\pgflinewidth/2}]
\node [fit = (1-1)] {} ;
\node [fit = (2-2)] {} ;
\node [fit = (3-3)] {} ;
\node [fit = (4-4)] {} ;
\end{tikzpicture}}]
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
1 & 2 & 3 & 4 \\
    \end{bNiceArray}
\]
\end{document}

or like this:

enter image description here

\documentclass{article}
\usepackage{nicematrix}

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

Two solutions with pstricks: one with a simple frame around the diagonal elements and another which adds a coloured background. The pst-node module has a dedicated command for that – \ncbox:

    \documentclass[svgnames]{article}

    \usepackage{amsmath, xcolor}
    \usepackage{pst-node}
    \usepackage{auto-pst-pdf}

    \begin{document}

    \[
      A = \begin{bmatrix}
       \rnode{B}{\color{red}{1}} & 2 & 3 & 4\\
        1 & \color{red}{2} & 3 & 4\\
        1 & 2 & \textcolor{red}{3} & 4\\
        1 & 2 & 3 & \rnode{E}{\color{red}{4}}
      \end{bmatrix}
    \ncbox[linecolor =VioletRed, boxsize=5pt, linearc=0.05]{B}{E}
    \]
    \[
      A = \begin{bmatrix}
       \rnode{B}{\color{red}{1}} & 2 & 3 & 4\\
        1 & \color{red}{2} & 3 & 4\\
        1 & 2 & \textcolor{red}{3} & 4\\
        1 & 2 & 3 & \rnode{E}{\color{red}{4}}
      \end{bmatrix}
    \ncbox[linecolor =IndianRed, fillstyle=solid, fillcolor=MistyRose, opacity=0.2, boxsize=5pt, linearc=0.05, nodesep=0.8pt]{B}{E}
    \]

    \end{document} 

enter image description here

Edit:

If you do no want the diagonal frame to touch the brackets, you can, omong other possibilities, change the value of the \ncbox parameter linearc=0.18to have round extremities, or nest a simple matrix in bmatrix and add some spacingon each side, like this:

      \[
      A = \begin{bmatrix}
        \:\begin{matrix}
       \rnode{B}{\color{red}{1}} & 2 & 3 & 4\\
        1 & \color{red}{2} & 3 & 4\\
        1 & 2 & \textcolor{red}{3} & 4\\
        1 & 2 & 3 & \rnode{E}{\color{red}{4}}
        \end{matrix}\:
      \end{bmatrix}
    \ncbox[linecolor =IndianRed, fillstyle=solid, fillcolor=MistyRose, opacity=0.2, boxsize=5pt, linearc=0.05, nodesep=0.8pt]{B}{E}
    \]

enter image description here

Tags:

Matrices