3

I would like to color the diagonal and off diagonal elements of a matrix:

I have:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amssymb,amsmath,amsthm,enumitem}
\usepackage[a4paper, total={6in, 8in}]{geometry}
\usepackage{hyperref}


\usepackage{tikz}

\newcommand{\tikzmark}[2]{
    \tikz[overlay,remember picture,baseline] 
    \node[anchor=base] (#1) {$#2$};
}
\begin{document}

\begin{equation}
    \begin{pmatrix}
        \tikzmark{top}{A_{11}} & A_{12} & A_{13} & \cdots  & A_{1n} \\ 
        A_{21} & A_{22} & A_{23} & \cdots  & A_{2n} \\ 
        A_{31} & A_{32} & A_{33} & \cdots  & A_{3n} \\ 
        \vdots  & \vdots   & \vdots  & \vdots  & \vdots  \\ 
        A_{n1} & A_{n2} & A_{n3} & \cdots  & \tikzmark{bottom}{A_{nn}} \\ 
    \end{pmatrix}
\end{equation}
\begin{tikzpicture}[overlay,remember picture]
     \draw[opacity=.5,line width=4mm,] (top.center) -- (bottom.center);
\end{tikzpicture}

\end{document}

The end result is:

enter image description here

However, I would like to make all the variables colored and not start and end at the middle. How can I do this?

Best regards

3

3 Answers 3

4
\documentclass{article}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{tikzmark}
\begin{document}
\begin{equation}
\begin{pmatrix}
\tikzmarknode{top}{A_{11}} & A_{12} & A_{13} & \cdots  & A_{1n} \\ 
A_{21} & A_{22} & A_{23} & \cdots  & A_{2n} \\ 
A_{31} & A_{32} & A_{33} & \cdots  & A_{3n} \\ 
\vdots  & \vdots   & \vdots  & \vdots  & \vdots  \\ 
A_{n1} & A_{n2} & A_{n3} & \cdots  & \tikzmarknode{bottom}{A_{nn}} \\ 
\end{pmatrix}
\end{equation}
\begin{tikzpicture}[overlay, remember picture]
\draw[red, opacity=.5, line width=5mm, line cap=round] (top.north west) -- (bottom.south east);
\end{tikzpicture}
\end{document}

Matrix with red diagonal

2

You could specify an anchor for the beginning and end of the line :

(top.north west) -- (bottom.south east)

Failing that, you could also shift the position of the beginning and end of your drawing with xshift and yshift :

([xshift=-3pt, yshift=3pt]top.center) -- ([xshift=3pt, yshift=-3pt]bottom.center)
0
2

For information, here is what you can do with {pNiceArray} of nicematrix.

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

\begin{document}

$\begin{pNiceArray}{cccw{c}{9mm}c}
\CodeBefore 
  \tikz \draw [red!30,line width=4.5mm] 
              (1-|1) -- (last-|last) ;
\Body
    A_{11} & A_{12} & A_{13} & \cdots  & A_{1n} \\ 
    A_{21} & A_{22} & A_{23} & \cdots  & A_{2n} \\ 
    A_{31} & A_{32} & A_{33} & \cdots  & A_{3n} \\ 
    \vdots  & \vdots   & \vdots  & \vdots  & \vdots  \\ 
    A_{n1} & A_{n2} & A_{n3} & \cdots  & A_{nn} \\ 
\end{pNiceArray}$

\end{document}

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

Output of the above code

You must log in to answer this question.