4

I am using TikZ and would like to draw a path from one node to another if a condition is met. Here is my code:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}

\begin{document}

\def\hsep{5cm}
\def\ilsize{6}
\def\hlsize{6}

\begin{figure}
\centering

\begin{tikzpicture}

\tikzstyle{neuron}=[circle, draw]
\tikzstyle{input neuron}=[neuron]
\tikzstyle{hidden neuron}=[neuron]

\foreach \name / \y in {1,...,\ilsize}
    \node[input neuron] (In-\name) at (0.0cm,-\y cm) {};

\foreach \name / \y in {1,...,\hlsize}
    \node[hidden neuron] (H0-\name) at (1.5cm+\hsep,-\y cm) {};
    
\def\array{{1,0,1,1,1,1}}
\foreach \i in {1,...,\ilsize}
    \foreach \j in {1,...,\hlsize}
        {
        %\ifnum\array[\i]=1
            \path (In-\i) edge (H0-\j);
        %\fi
        }

\end{tikzpicture}
\end{figure}

\end{document}

Which produces the following output:

enter image description here

However, the document does not compile if I use the if-condition

\ifnum\array[\i]=1
    \path (In-\i) edge (H0-\j);
\fi

Does someone see what I do wrong here?

3
  • Your code is not compilable. ! Missing number, treated as zero. <to be read again> {l.33 }
    – AndréC
    Jul 12, 2020 at 11:40
  • @AndréC I know :) I mentioned it in my question. This is why I asked for help.
    – Gilfoyle
    Jul 12, 2020 at 12:12
  • Since you edited your question, it's clearer.
    – AndréC
    Jul 12, 2020 at 16:48

1 Answer 1

7

The reason for the error is that the array does not contain integers but ifnum requires an integer.

You can use pgfmathparse to parse the entry from the array and pgfmathresult in the ifnum statement. Also you need to use i-1 otherwise the last array index is out of bounds, because arrays are indexed starting with 0.

\def\array{{1,0,1,1,1,1}}
\foreach \i in {1,...,\ilsize}
    \foreach \j in {1,...,\hlsize}
        {
        \pgfmathparse{\array[\i-1]}
        \ifnum\pgfmathresult=1
            \path (In-\i) edge (H0-\j);
        \fi
        }

Since i is a simple incremental counter, you could also use the count option of the foreach command and write the array directly in foreach statement. You would also not have any problems with indices of arrays and the maximum number of i would be determined by the length of the array instead of ilsize.

%\def\array{{1,0,1,1,1,1}}
\foreach [count = \i] \a in {1,0,1,1,1,1}
    \foreach \j in {1,...,\hlsize}
        {
        \ifnum\a=1
            \path (In-\i) edge (H0-\j);
        \fi
        }

Both solutions yield the same result:

enter image description here

2
  • 1
    I don't understand what you are asking, the first approach using pgfmathparse and pgfmathresult still uses your original definition of array. Jul 12, 2020 at 21:09
  • The comment above related to a follow-up question that was posted as a comment which was later deleted. Jul 12, 2020 at 21:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .