2

My goal is to draw an array of shapes in the following fashion: square, square, triangle, square, square, triangle ...

I use a \foreach loop in which I use modular arithmetic to determine when to draw a triangle. Here is my MWE:

\documentclass{article}
\usepackage{pgfplots,tikz,tikz-3dplot}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture} [scale=0.35,
triangle/.style = {regular polygon, regular polygon sides=3, scale=2.5},
square/.style = {regular polygon, regular polygon sides=4, scale=2}]
\foreach \i in {1,...,9}
{
    \ifthenelse{mod(\i,3) = 0}
    {
        \node[triangle] (\i) at (\i,0) {};
    }
    {
        \node[square] (\i) at (\i,0) {};
    }
}
\end{tikzpicture}
\end{figure}
\end{document}

I get the errors:

! Missing number, treated as zero.
! Missing = inserted for \ifnum.

The most related question about these error is this but it considers decimal numbers, which is not my case. What am I missing?

5

If you look at the log file you'll see the entire error, where you can see it complains about m, so I take it m is what is not a number. Here m is the m in mod.

Point being, \ifthenelse doesn't know about pgfs math functions, and mod isn't parsed in that location. You can do the calculation with \foreach [evaluate={\j=int(mod(\i,3));}] and do the comparison against \j.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture} [scale=0.35,
triangle/.style = {draw, regular polygon, regular polygon sides=3, scale=2.5},
square/.style = {draw, regular polygon, regular polygon sides=4, scale=2}]
\foreach [evaluate={\j=int(mod(\i,3));}] \i in {1,...,9}
{
    \ifthenelse{\j = 0}
    {
        \node[triangle] (\i) at (\i,0) {};
    }
    {
        \node[square] (\i) at (\i,0) {};
    }
}
\end{tikzpicture}
\end{figure}
\end{document}
| improve this answer | |
  • 1
    Thanks for the detailed explanation. This answer is more than I expected! – padawan Sep 19 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.