3

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

2

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

  • 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
2

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

 \For{Condition\label{line1}}{

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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