# \numexpr behavior in math mode and/or TikZ

I am attempting to create a triangular grid of numbers like shown below:

This was created in TikZ by hard-coding each point, but I would like to generate the grid procedurally so I can make adjustments easily with a large number of points. The following code is how I have approached the problem:

\documentclass{article}
\usepackage{tikz}

\begin{tikzpicture}[scale=1.5]
\foreach \s in {2,...,4} {
\foreach \m in {1,...,\numexpr\s-1} {
\def\n{\s-\m}
\draw (\n,-\m) node {$a_{\m\n}$};
}
}
\end{tikzpicture}


However this produces the following undesired result:

My thought to resolve this issue was to add \numexpr in the \n definition or prior to \n in the nodes. However this produces the error you can't use '\numexpr' in math mode.

I'm at a loss as to what to do next. How can I evaluate variables like this in math mode in a TikZ picture?

As a further note, if I for testing purposes ignore my need for math mode and simply put \numexpr\n in the node text I instead receive the similar error message you can't use '\numexpr' in restricted horizontal mode.

Also, if possible I would like to preserve this \foreach iteration structure as it is ideal for other annotations I am using in my full application.

• Probably \the\numexpr\s-1\relax – Henri Menke Apr 4 '19 at 8:38

You could use \edef\n{\the\numexpr\s-\m}, or just use it in the subscript:

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[scale=1.5]
\foreach \s in {2,...,4}{
\foreach \m in {1,...,\numexpr\s-1}{
\draw (\s-\m,-\m) node {$a_{\m\the\numexpr\s-\m}$};
}
}
\end{tikzpicture}

\end{document}


There is already one answer how to use \numexpr, one how to rewrite your loop to avoid it, and here is another possibility : you can use the tools provided by foreach to make calculations. You can use count and evaluate:

\documentclass[tikz,border=7pt]{standalone}
\begin{document}
\begin{tikzpicture}[scale=1.5]
\foreach[count=\t from 1] \s in {2,...,4} {
\foreach[evaluate={\n=int(\s-\m)}] \m in {1,...,\t} {
\draw (\n,-\m) node {$a_{\m\n}$};
}
}
\end{tikzpicture}
\end{document}


Avoid additional calculations. Try to think of another way of using nested \foreachs.

\documentclass[tikz]{standalone}
\begin{document}
\begin{tikzpicture}[scale=1.5]
\foreach \y in {1,...,3} {
\foreach \x in {1,...,\numexpr4-\y} {
\draw (\x,-\y) node {$a_{\y\x}$};
}
}
\end{tikzpicture}
\end{document}


• Like I said in the post, due to the way I other annotations are drawn I would like to keep the same loop structure I used. – PGmath Apr 4 '19 at 19:51
• @PGmath Of course you can always keep the loop structure. However, that means you are making your problem unnecessarily complicated. – user156344 Apr 5 '19 at 5:35
• It's not unnecessarily complicated if I necessarily need that structure though. – PGmath Apr 5 '19 at 5:36