[Tex/LaTex] Highlight the upper or lower triangular portion of a matrix

highlightingmatrices

I previously asked this question here, but now would like to achieve the same goal with a matrix under a different construction. More specifically, how can I highlight or shade the upper or lower triangular part of the following matrix?

enter image description here

The corresponding Latex code is this:

\documentclass{article}
\usepackage{blkarray}
\begin{document}
$R = 
\begin{blockarray}{cccccc}
& S_1 & S_2 &  S_3 & ... & S_n \\
\begin{block}{c(ccccc)}
S_1 &  1 & r_{12} & r_{13} & ... & r_{1n} \\
S_2 &  r_{21} & 1 & r_{23} & ... & r_{2n} \\
S_3 &  r_{31} & r_{32} & 1 & ... & r_{3n} \\
\vdots &  \vdots & \vdots &\vdots & \vdots & \vdots\\
S_n &  r_{n1} & r_{n2} & r_{n3} & ... & 1 \\
\end{block}
\end{blockarray},$
\end{document}

Thanks!

Best Answer

You can get the desired effect with TikZ(mark). I define the following variant of TikZmark:

\newcommand\tm[2][]{\tikz[overlay,remember picture,baseline=(#1.base),inner sep=0pt]\node(#1){$#2$};}

It takes two arguments: the first sets the name and the second specifies the content. If you want to highlight the lower triangle of the matrix, use \tm at the top left, bottom left and bottom right element of the matrix. Then fit two nodes to these three elements and \filldraw the shaded triangle.

Code

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{fit}
\newcommand\tm[2][]{\tikz[overlay,remember picture,baseline=(#1.base),inner sep=0pt]\node(#1){$#2$};}
\usepackage{blkarray}
\begin{document}
$R = 
\begin{blockarray}{cccccc}
& S_1 & S_2 &  S_3 & ... & S_n \\
\begin{block}{c(ccccc)}
S_1 &  \tm[a]{1} & r_{12} & r_{13} & ... & r_{1n} \\
S_2 &  r_{21} & 1 & r_{23} & ... & r_{2n} \\
S_3 &  r_{31} & r_{32} & 1 & ... & r_{3n} \\
\vdots &  \vdots & \vdots &\vdots & \vdots & \vdots\\
S_n &  \tm[b]{r_{n1}} & r_{n2} & r_{n3} & ... & \tm[c]{1} \\
\end{block}
\end{blockarray},$
\begin{tikzpicture}[overlay, remember picture]
  \node(x)[fit=(a) (b),inner sep=0pt]{};
  \node(y)[fit=(b) (c),inner sep=0pt]{};
  \filldraw[rounded corners,opacity=.2,green](x.north west)--(x.south west)--(y.south east)--(y.north east)--(x.north east)--cycle;
\end{tikzpicture}
\end{document}

Output

enter image description here