Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I use the following code to draw a line to connect two nodes in my graphic:

\draw ( p-\prow-\col) -- (p-\row-\col);

At the edge of the figure, however, not every node will have a predecessor from which the line can originate.

What I would like to do is only draw the line conditionally, depending on whether the node ( p-\prow-\col) already exists or not.

I have seen this question, but the implementation and usage aren't clear to me (and it also seems to be handling the opposite case, executing when the node is undefined).

I'm simply looking for the correct syntax for the command if node is defined: do this

share|improve this question

1 Answer 1

up vote 11 down vote accepted

The definition of \@nodedefined in Martin Scharrer's answer to the question you linked to seems to do exactly what you ask: The command takes three arguments: The first is the node name to check, the second is the code that's executed if the node exists, and the third is the code that's executed if it doesn't exist (in this case, you'd just leave it empty).

\documentclass{article}

\usepackage{tikz}
\makeatletter
\long\def\ifnodedefined#1#2#3{%
    \@ifundefined{pgf@sh@ns@#1}{#3}{#2}%
}
\makeatother

\begin{document}

\begin{tikzpicture}
\node (p-1-1) {P-1-1};
\node (p-2-2) at (2,2) {P-2-2};
\ifnodedefined{p-1-1}{
    \draw (p-1-1) -- (p-2-2);
}{}

\ifnodedefined{p-1-2}{
    \draw (p-1-2) -- (p-2-2);
}{}
\end{tikzpicture}
\end{document}
share|improve this answer
    
Thanks for your answer Jake. When I do this, I still get an error Package pgf Error: No shape named p-2-1 is known. –  nbrooks Dec 4 '12 at 19:56
    
Sorry, typo in the error message. I meant p-1-2, I simply ran the code from your answer. The error message comes from the draw line, so the conditional seems not to work. I'm not sure how to check the versions of TikZ or PGF...I'm using version 2.43 of TexShop as my editor, if that helps. –  nbrooks Dec 4 '12 at 20:05
    
There's an error there, 'at's for sure. –  Loop Space Dec 4 '12 at 20:12
    
Ah, ok thanks. It's version 2.10 of PGF –  nbrooks Dec 4 '12 at 20:12
1  
@AndrewStacey Yes. Hopefully, one day I'll read what I'm writing. Thanks for the correction –  percusse Dec 4 '12 at 21:09

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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