[Tex/LaTex] Using Condition (If/Else) Inside Loop (For) In Tikz

conditionalsgridstikz-pgf

In my previous post, I have asked how to use two loops to construct a grid with values inside it. A wonderful answer was given by Andrew Swann .

\documentclass{article}

\usepackage{tikz}

\begin{document}

\def\n{6}
\def\m{8}
\def\s{1.5cm}
\tikz\draw grid[step=\s](\n*\s,\m*\s) foreach[evaluate] \x  in {1,...,\n}
  { foreach[evaluate={\z = int(min(\x,\n+1-\x)+\n*min(\y-1,\m-\y)/2)}] \y in {1,...,\m}
  {({\s*(.5+(\x-1))},{\s*(\m+.5-\y)}) node{$a=\z$}}};

\end{document}

he has provided a formula \z which can be modified for different arrangement of values.

For example, I did-

[evaluate= {\z = int(\x+\n*min(\y-1,\m+\y))}]

which gives-

1 2 3 4

5 6 7 8

9 10 11 12

for 3*4 grid. But if I want –

1 2 2 1

3 4 4 3

5 6 6 5

7 8 8 7

and ,

1 2 3 4

5 6 7 8

0 9 10 0

0 11 12 0

0 13 14 0

I could not do it! I am really having hard time to use loop and if else condition. Probably , I am too much used to C++ and similar things where I can easily do a=a+1 or write if condition. I can think of an way to print above value-arrangements, using Condition (if/else), but I don't know where to put it (I have tried, but all were wrong).

So,my question is, how to put Condition (if/else) before \z so that I can print output as I have shown above?

Best Answer

You could easily use ifthenelse in the tikz node:

\documentclass{minimal}
\usepackage{tikz}
\usepackage{ifthen}

\begin{document}

\def\n{4}
\def\m{4}
\def\s{1.5cm}
\tikz\draw grid[step=\s](\n*\s,\m*\s) 
  foreach[evaluate] \x  in {1,...,\n} { 
    foreach[evaluate={
      \zt = int(\x+\n*min(\y-1,\m+\y));
      \zb = int(\x+(\n-2)*min(\y-1,\m+\y)+3)
    }] \y in {1,...,\m} {
      ({\s*(.5+(\x-1))},{\s*(\m+.5-\y)}) node{$a=\ifthenelse{\y>2}{\ifthenelse{\x=1 \OR \x>3}{0}{\zb}}{\zt}$}
    }
  };

\end{document}

This should create the third grid you wanted.

Also see the answer to the following question for more examples with ifthenelse and loops: If-then-else inside TikZ graph?