3

I am trying to use labels defined in an array using tikz for drawing a path between two shapes. I have tried to use pgfmathparse but it seems not well defined for string. My syntax is probably wrong.

MWE:

\documentclass[]{standalone}
\usepackage{tikz}

\begin{document}
\def\stA {AA}
\def\stB {BB}
\def\stC{{"AA","BB"}}
\begin{tikzpicture}
\node at (0,0) (AA){coucou};
\node at (2,0) (BB){ahah};

\draw (\stA)--(\stB);

\draw (\pgfmathparse{\stC[2]}\pgfmathresult)--(\pgfmathparse{\stC[1]}\pgfmathresult);
\end{tikzpicture}
\end{document}
Guuk
  • 1,495
  • I can not understand, what you like to achieve. For connecting two shapes it is sufficient to say: \node (AA) at (0,0) {coucou}; \node (BB) at (2,0) {ahah}; \draw (AA) -- (BB); Syntax of this lines in your MWE is wrong as well second line with \draw, where you use TikZ math engine. What is purpose of this line? – Zarko Jun 21 '15 at 20:02
  • I use an external script based on MATLAB for generating the connections of my graph. Thus I define an array of the connections. – Guuk Jun 21 '15 at 21:27
  • Meanwhile I seen from both answers, what is the intention of question. Thank you for comment. – Zarko Jun 21 '15 at 21:51

2 Answers2

4

Here are two methods. The first one use \pgfextra to evaluate the array before to use \pgfmathresult. The second use math library to evaluate the array.

\documentclass[tikz]{standalone}
\usetikzlibrary{math}

\begin{document}
  \def\stC{{"AA","BB"}}

  \begin{tikzpicture}
    \node at (0,0) (AA){coucou};
    \node at (2,0) (BB){ahah};
    \draw (AA)--(BB);

    % method one
    \draw[red,bend left] \pgfextra{\pgfmathparse{\stC[0]}}(\pgfmathresult)
                         \pgfextra{\pgfmathparse{\stC[1]}} to (\pgfmathresult);

    % method two
    \tikzmath{\first= \stC[0]; \second = \stC[1];}
    \draw[blue, bend right] (\first) to (\second);
  \end{tikzpicture}
\end{document}

enter image description here

Note: The array index starts with 0.

Kpym
  • 23,002
3

TikZ expects fully expandable input in coordinates and such things.
See for example (there are probably more):


With the .evaluated key handler and the node coordinate system used explicitly you can do:

\draw (node cs: name/.evaluated=\stC[1])
   -- (node cs: name/.evaluated=\stC[0]);

For actual coordinates (i.e. no node names), TikZ throws everything in PGFmath anyway, and you can just do

\newcommand*\stDA{{.5,2,3.4,-1.5}}
\newcommand*\stDB{{2,1.5,3,-1}}
\foreach \da in {0,2}
  \foreach \db in {0,2}
    \draw (\stDA[\da], \stDB[\db]) -- (\stDA[\da+1], \stDB[\db+1]);
Qrrbrbirlbel
  • 119,821
  • 2
    By the way, \pgfmathparse{<stuff>}\pgfmathresult can otherwise shortened to \pgfmathprint{<stuff>}. (There's also \pgfmathprintnumber.) – Qrrbrbirlbel Jun 21 '15 at 20:48
  • Since 2019, PGFkeys comes with its own .evaluated key that uses the same definition (apart from some checks that PGFmath is actually loaded) as .pgfmath from my previous answer. – Qrrbrbirlbel Sep 26 '22 at 15:32