Produce a table with numbers given by another macro

Here's a more generic macro using expl3. First we build the table and then output it in one swoop: it's usually complicated to have loops in table cells.

\documentclass{article}
\usepackage[landscape]{geometry}
\usepackage{amsmath,xparse,xfp}

\ExplSyntaxOn
\NewDocumentCommand{\lowertriangular}{mm}
 {
  \group_begin:
  \brooks_lowertriangular:nn { #1 } { #2 }
 }

\tl_new:N \l__brooks_body_tl

\cs_new_protected:Nn \brooks_lowertriangular:nn
 {
  % a temporary function for massaging the entries
  \cs_set:Nn \__brooks_inner:nn { #2 }
  % clear the table body
  \tl_clear:N \l__brooks_body_tl
  % outer cycle, #1 rows
  \int_step_inline:nnnn { 1 } { 1 } { #1 }
   {
    % inner cycle, ##1 columns
    \int_step_inline:nnnn { 1 } { 1 } { ##1 }
     {
      % add the entry for row ##1 (outer cycle) and column ####1 (inner)
      \tl_put_right:Nn \l__brooks_body_tl
       { \__brooks_inner:nn { ##1 } { ####1 } }
      % if ##1 = ####1 end the row, otherwise end the cell
      \tl_put_right:Nx \l__brooks_body_tl
       { \int_compare:nTF { ##1 = ####1 } { \exp_not:N \\ } { & } }
     }
   }
  % output the table
  \begin{array}{*{#1}{c}} \l__brooks_body_tl \end{array}
  \group_end:
 }
\ExplSyntaxOff

\begin{document}

\[
\lowertriangular{9}{#1\times #2}
\]

\[
\lowertriangular{9}{#1\times #2=\inteval{#1*#2}}
\]

\[
\begin{bmatrix}
\lowertriangular{5}{a_{#1#2}}
\end{bmatrix}
\]

\end{document}

enter image description here


You can use an expandable loop from the LaTeX kernel.

\documentclass{article}
\usepackage{geometry}
\geometry{a4paper,scale=0.8}

\newcount\loopi \newcount\loopj \newcount\ans

\begin{document}\thispagestyle{empty}

\makeatletter

\global\loopi 0
\global\loopj 0

\[\begin{array}{*{9}{l}}
\@whilesw{\ifnum\loopi<9 }\fi
         {\global\advance\loopi 1
          \global\loopj 0
          \@whilesw{\ifnum\loopj<\loopi}\fi
                   {\global\advance\loopj 1
%               
    \ifnum\loopj>1 \@firstofone{&}\fi
    \ans=1
    \multiply\ans by \loopi
    \multiply\ans by \loopj
    \number\loopj\times\number\loopi = \number\ans
%
                   }\\
         }
\end{array}\]

\makeatother

\end{document}

enter image description here

Tags:

Loops

Tables