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 want to describe parts of an algorithm, by linking to specific lines. I found that the package algorithm2e is great for typesetting algorithms, and it seems it is also able to handle labels.

However, it doesn't seem to work as expected. Do I miss something in the correct syntax?

As an example, see the MWE below, with its output. First and third attempts show that the \ref links to the line above the one I want to label. The second attempt is correct, except it skips a line. However, I assume it is normal, since this syntax is supposed to manually number a line when automatic numbering is disabled. I just included it here for completeness.

Please note that the issue appears at least with \For, \ForEach and \If so I assumed it is the same for all keywords, that may of course be wrong.

Code:

\documentclass{article}

\usepackage[linesnumbered]{algorithm2e}

\begin{document}

\begin{algorithm}
  \caption{Algorithm 1}
  First line \;
  \label{line1}\For{Condition}{
    Third line\;
  }
\end{algorithm}

I want to refer to line 2: \ref{line1}.

\begin{algorithm}
  \caption{Algorithm 2}
  First line \;
  \nl\label{line2}\For{Condition}{
    Third line\;
  }
\end{algorithm}

I want to refer to line 2: \ref{line2}.

\begin{algorithm}
  \caption{Algorithm 3}
  First line \;
  \nllabel{line3}\For{Condition}{
    Third line\;
  }
\end{algorithm}

I want to refer to line 2: \ref{line3}.

\end{document}

Result:

Output

share|improve this question

2 Answers 2

up vote 2 down vote accepted

This seems to do the trick (putting the label in the condition) :

\documentclass{article}

\usepackage[linesnumbered]{algorithm2e}


\begin{document}

\begin{algorithm}
  \caption{Algorithm 1}
  First line \;
  \For{\label{line} Condition}{
    Third line\;
  }
\end{algorithm}

I want to refer to line 2: \ref{line}.

\end{document}

enter image description here

share|improve this answer
    
Interesting... I got tricked in all these "\nl must start the line", and didn't notice nothing like that was said about plain \labels. Thanks! –  T. Verron Nov 13 '12 at 16:50

I think if you want to refer to the line with the condition you can go

 \For{Condition\label{line1}}{
share|improve this answer

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.