\newcommand 中的 LaTeX 循環

\newcommand 中的 LaTeX 循環

我已經使用 LaTeX 大約一年了,每次寫論文時我都會嘗試提高我的知識,所以最近我一直在創建自己的命令來幫助節省時間。我很感興趣是否可以在 LaTeX 中使用“for-loops”\newcommand以以下方式建立:

\newcommand{idmatrix}[1]

我的參數是大小n,然後它將列印一個nxn單位矩陣。這對於我想要顯示矩陣計算但不必\bmatrix每次都使用 etc 並創建 3x3 或 2x2 矩陣的平凡工作的方程式很有用。

答案1

這是一個具有 LaTeX3 功能的實作。什麼時候\idmatrix{n}第一次呼叫時,會設定一個新的標記清單變量,其中包含用於生成矩陣的程式碼,以便可以重複使用它,而無需每次都建置。

因此,\idmatrix{2}將建立令牌列表變數\g_julian_idmatrix_1_tl並使用它;的後續呼叫\idmatrix{2}將僅使用該變數。

\documentclass{article}
\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\idmatrix}{ m }
 {
  \justin_idmatrix:n { #1 }
 }

\cs_new_protected:Npn \justin_idmatrix:n #1
 {
  \tl_if_exist:cF { g_justin_idmatrix_#1_tl }
   {
    \justin_make_idmatrix:n { #1 }
   }
  \tl_use:c { g_justin_idmatrix_#1_tl }
 }

\cs_new_protected:Npn \justin_make_idmatrix:n #1
 {
  \tl_new:c { g_justin_idmatrix_#1_tl }
  \tl_gput_right:cn { g_justin_idmatrix_#1_tl }
   {
    \left[ % or the delimiter you like best
    % there's a column more for accommodating the empty value after the last 0& (or 1&)
    \begin{array}{ @{} *{#1}{c} @{} c @{} }
   }
  \int_step_inline:nnnn { 1 } { 1 } { #1 }
   {
    % At step k add k-1 zeroes
    \prg_replicate:nn { ##1 - 1 }
     {
      \tl_gput_right:cn { g_justin_idmatrix_#1_tl } { 0 & }
     }
    % Add a 1
    \tl_gput_right:cn { g_justin_idmatrix_#1_tl } { 1 & }
    % Add n - k zeroes
    \prg_replicate:nn { #1 - ##1 }
     {
      \tl_gput_right:cn { g_justin_idmatrix_#1_tl } { 0 & }
     }
    % End the line
    \tl_gput_right:cn { g_justin_idmatrix_#1_tl } { \\ }
   }
  \tl_gput_right:cn { g_justin_idmatrix_#1_tl }
   {
    \end{array}
    \right] % or the delimiter you like best
   }
 }

\ExplSyntaxOff

\begin{document}
\[
\idmatrix{1}\quad
\idmatrix{2}\quad
\idmatrix{3}\quad
\idmatrix{4}
\]
\[
\idmatrix{12}
\]
\end{document}

在此輸入影像描述

答案2

要回答您的問題,您只需稍微修改內容即可這裡

\documentclass{article}

\usepackage{amsmath,amssymb,mathtools}
\usepackage{ifthen}

\newcommand{\forLoop}[5][1]
{%
\setcounter{#4}{#2}%
\ifthenelse{ \value{#4} < #3 }%
{%
#5%
\addtocounter{#4}{#1}%
\forLoop[#1]{\value{#4}}{#3}{#4}{#5}%
}%
% Else
{%
\ifthenelse{\value{#4} = #3}%
    {%
    #5%
    }%
% Else
    {}%
}%
}

\newcounter{identRow}
\newcounter{identCol}
\newcommand{\idmatrixn}[1]
{
\begin{bmatrix}
\forLoop{1}{#1}{identRow}
    {
    \forLoop{1}{#1}{identCol}
        {
        \ifthenelse{\equal{\value{identRow}}{\value{identCol}}}{1}{0}
        \ifthenelse{\equal{\value{identCol}}{#1}}{}{&}
        }
    \\
    }
\end{bmatrix}
}

\begin{document}
\idmatrixn{10}
\end{document}

請小心,因為我注意到 bmatrix 環境不支援大於 10x mm x 10where 的矩陣0<m<11。如果您需要更大的矩陣,可以array以下方式使用:

\newcounter{identRow}
\newcounter{identCol}
\newcommand{\idmatrixn}[1]
{
\left[\begin{array}{*{#1}c}
\forLoop{1}{#1}{identRow}
    {
    \forLoop{1}{#1}{identCol}
        {
        \ifthenelse{\equal{\value{identRow}}{\value{identCol}}}{1}{0}
        \ifthenelse{\equal{\value{identCol}}{#1}}{}{&}
        }
    \\
    }
\end{array}\right]
}

相關內容