答案1
我从@David Carlisle 的回答中借用了代码这个问题。它定义了数组的行和列的计数器,我只需测试这些计数器的总和即可选择给定单元格的颜色。我定义了一种新的列类型来简化表格的输入:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{fourier, erewhon}
\usepackage{blkarray}%
\usepackage[table]{xcolor}
\colorlet{ccol1}{red}
\colorlet{ccol2}{yellow}
\colorlet{ccol3}{cyan}
\colorlet{ccol4}{green}
\colorlet{ccol5}{brown}
\colorlet{ccol6}{magenta}
\colorlet{ccol7}{orange}
\colorlet{ccol8}{lime!80!}
\colorlet{ccol9}{pink}
\colorlet{ccol10}{violet!50!}
\colorlet{ccol11}{olive!50!}
%%%% Code by David Carlisle
\makeatletter
\def\insert@column{%
\the@toks \the \@tempcnta
\global\advance\c@tabcol\@ne
\ignorespaces \@sharp \unskip
\the@toks \the \count@ \relax}
\let\old@arraycr\@arraycr
\def\@arraycr{\global\c@tabcol\z@\global\advance\c@tabrow\@ne\old@arraycr}
\let\old@tabarray\@tabarray
\def\@tabarray{\global\c@tabrow\@ne\global\c@tabcol\z@\old@tabarray}
\makeatother
\newcounter{tabcol}\newcounter{tabrow}
%%%%%%%%%%%%%%%
\newcounter{diagctr}
\newcolumntype{C}{>{\setcounter{diagctr}{\numexpr \value{tabrow} + \value{tabcol}\relax}\cellcolor{ccol\arabic{diagctr}}}c}
\begin{document}
\[\renewcommand\arraystretch{1.5}
\begin{array}{*{6}{C}}%
e & a & a^2 & a^3 & a^4 & a^5 \\
a & a^2 & a^ 3 & a^4 & a^5 & e \\
a^2 & a^3 & a^4 & a^5 & e & a \\
a^3 & a^4 & a^5 & e & a & a^2 \\
a^4 & a^5 & e & a & a^2 & a^3 \\
a^5 & e & a & a^2 & a^3 & a^4
\end{array}
\]
\end{document}
如果想要在上方添加无色行,或在左侧添加一列或两者,则必须更改定义颜色索引的公式,并添加测试以确定是否\cellcolor
必须在进入单元格时添加。这可以通过以下方法完成etoolbox
:
\usepackage{etoolbox}
\newcounter{diagctr}
\newcolumntype{C}{>{\setcounter{diagctr}{\numexpr \value{tabrow} + \value{tabcol}-2\relax}%
\ifboolexpr{test {\ifnumequal{\value{tabcol}}{0}} or test {\ifnumequal{\value{tabrow}}{1}}}{\relax}{\cellcolor{ccol\arabic{diagctr}}}}%
c}
\[\renewcommand\arraystretch{1.5}
\renewcommand\arrayrulewidth{2pt}
\begin{array}{C*{6}{C}}
& e & a & a^2 & a^3 & a^4 & a^5\\
\cline {2-7}\noalign{\vskip2pt}
e & e & a & a^2 & a^3 & a^4 & a^5 \\
a & a & a^2 & a^ 3 & a^4 & a^5 & e \\
a^2 & a^2 & a^3 & a^4 & a^5 & e & a \\
a^3 & a^3 & a^4 & a^5 & e & a & a^2 \\
a^4 & a^4 & a^5 & e & a & a^2 & a^3 \\
a^5 & a^5 & e & a & a^2 & a^3 & a^4\\
\cline {2-7}
\end{array}
\]
\end{document}
答案2
以下是使用 来实现这一{NiceArray}
目的的一种方法nicematrix
。
\documentclass{article}
\usepackage{nicematrix}
\usepackage{tikz}
\begin{document}
\[\renewcommand\arraystretch{1.5}
\begin{NiceArray}{*{6}{c}}[first-row,first-col,hvlines,rules={width=0.2pt,color=white}]
\CodeBefore
\foreach \x in {1,...,\arabic{iRow}}
\foreach \y in {1,...,\arabic{jCol}}
{
\pgfmathsetmacro\z{(\x+\y)/(\arabic{iRow}+\arabic{jCol})*100}
\cellcolor{cyan!\z!magenta}{\x-\y}
}
\Body
& e & a & a^2 & a^3 & a^4 & a^5 \\
e & e & a & a^2 & a^3 & a^4 & a^5 \\
a & a & a^2 & a^ 3 & a^4 & a^5 & e \\
a^2 & a^2 & a^3 & a^4 & a^5 & e & a \\
a^3 & a^3 & a^4 & a^5 & e & a & a^2 \\
a^4 & a^4 & a^5 & e & a & a^2 & a^3 \\
a^6 & a^5 & e & a & a^2 & a^3 & a^4
\end{NiceArray}
\]
\end{document}
您需要多次编译(因为nicematrix
使用 PGF/Tikz 节点)。