[Tex/LaTex] tikz pgf – Add background color to specific cells of a Matrix

backgroundsmatricestikz-pgf

Hi i'm interested in how to add background to specific cells of a matrix.

I already know a bit about how to build a matrix, my given code looks like:

\usepackage{tikz}
\usetikzlibrary{arrows, fit, matrix, positioning, shapes}

\begin{tikzpicture}[>=latex]
    \node (B) {$B^\prime=$};
    \matrix (M) [matrix of math nodes,left delimiter={[}, right delimiter={]},
    matrix anchor=west, right=0.5em of B, 
    column 1/.style={anchor=base east},
    column 2/.style={anchor=base east},
    column 3/.style={anchor=base east}]
    {
      a & b & c\\
      b & d & e\\
      c & e & a+b+1\\
    };
    \node  [fit=(M-1-1) (M-1-3), draw, rectangle, blue]{};    
    \node  [fit=(M-2-2) (M-2-3), draw, rectangle, blue]{};
    \node  [fit=(M-3-3) (M-3-3), draw, rectangle, blue]{};
\end{tikzpicture}

As you can see im creating a right-aligned matrix, because my element at cell(3,3) is very long. To point out that my matrix is quadratic, I thought about highlighting row elements 1-1 to 1-3, 2-2 to 2-3, and element 3-3.

I would want to give them a background color, lets say some sort of blue. I didn't manage to fill out the rectangles without covering the matrix elements below.

I would be greatful for any hints or solutions 🙂

Best Answer

i finally managed to find my desired answer.

\usepackage{tikz}
\usetikzlibrary{arrows, fit, matrix, positioning, shapes, backgrounds,
}

\begin{tikzpicture}[>=latex]
    \node (B) {$B^\prime=$};
    \matrix (M) [matrix of math nodes,left delimiter={[}, right delimiter={]},
    matrix anchor=west, right=0.5em of B, 
    column 1/.style={anchor=base east},
    column 2/.style={anchor=base east},
    column 3/.style={anchor=base east}]
    {
      a & b & c\\
      b & d & e\\
      c & e & a+b+1\\
    };
    \scoped[on background layer]
    {
    \node[fill=pink!50, fit=(M-1-1)(M-1-3) ]   {};
    \node[fill=pink!50, fit=(M-2-2)(M-2-3) ]   {};
    \node[fill=pink!50, fit=(M-3-3)(M-3-3) ]   {};
    }
\end{tikzpicture}

it's not super perfect, but i'll take it. Thanks for your suggestions.

enter image description here

Related Question