如何增強現有的數學環境

如何增強現有的數學環境

我正在進一步學習 LaTeX,並開始探索創建自訂環境的可能性;但是,我查閱的資源沒有提到如何建立一個像bmatrix沒有預先定義參數數量的環境這樣的環境。

特別是,我想定義一個bmatrix(和類似的)變體,它允許我為行/列著色。

理想情況下,我想找到定義環境的方法,以便我可以:

  • 指定環境開口處(或行/列的第一個元素)的每行/列的顏色。例如,如果\ca\cb\cc是不同顏色的宏,那麼類似的東西\begin{cbmatrix}{\ca \ca \cb}將啟動一個bmatrix環境,​​其中第一行中的條目將分別包裝在 中\ca,第二行類似,第三行的條目將包裝在 中cb

即所需的輸出相當於:

\begin{bmatrix}
\ca{e1} & \ca{e2} & \ca{e3} & \ca{e4} \\
\ca{e5} & \ca{e6} & \ca{e7} & \ca{e8} \\
\cb{e9}& \cb{e10} & \cb{e11} & \cb{e12} \\
e13 & e14 & e15 & e16
\end{bmatrix}
  • 輕鬆切換將顏色命令套用到行或列(可能使用帶有星號的環境版本)?

我意識到這是一個非常具體的最終結果,但我通常很想知道從哪裡開始能夠定義這種類型的環境,其中輸入/參數的數量沒有預先定義?

答案1

arraycollcell和一些內部宏的非常脆弱的混合。

\documentclass{article}
\usepackage{amsmath}
\usepackage{array}
\usepackage{collcell}
\usepackage{xcolor}

\newcommand\ca{\textcolor{red}}
\newcommand\cb{\textcolor{green}}
\newcommand\cc{\textcolor{blue}}

\newcounter{row}
\newcounter{col}
\makeatletter
\newenvironment{triplecolorbmatrix}[1]
  {\setcounter{row}{1}%
   \@for\name:=#1\do{%
       \expandafter\def\csname rowcolor\number\value{row}\expandafter\endcsname\expandafter{\name}%
       \stepcounter{row}%
   }%
   \setcounter{row}{0}%
   \setcounter{col}{0}%
   \newcommand\colorrow{\csname rowcolor\number\value{row}\endcsname}%
   \let\@arraycrnormal\@arraycr
   \def\@arraycr{\setcounter{col}{0}\@arraycrnormal}%
   \left[\hspace{-\tabcolsep}\array{*{10}{>{\ifnum\value{col}=0\stepcounter{row}\fi\stepcounter{col}\collectcell\colorrow}c<{\endcollectcell}}}}
  {\endmatrix\right]}
\makeatother

\begin{document}
\begin{equation*}
  \begin{triplecolorbmatrix}{\ca,\cb,\cc}
    e1  & e2  & e3  & e4  \\
    e5  & e6  & e7  & e8  \\
    e9  & e10 & e11 & e12 \\
    e13 & e14 & e15 & e16 \\
  \end{triplecolorbmatrix}
\end{equation*}
\end{document}

在此輸入影像描述

相關內容