# labeling lines of algorithms inside figure environment

I am having trouble labeling lines of algorithms that are inside the figure environment. For example, in the following code the label "\lnl{loop}" gives compilation error. This works perfectly in algorithms outside the figure environment.

\documentclass{article}
\usepackage{algorithm2e}
\usepackage{caption}
\usepackage{subcaption}

\newcommand{\myalgorithm}{%
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\lnl{loop} \While{not at end of this document}{
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}}
\begin{document}

\begin{figure}
\begin{subfigure}{.5\textwidth}
\myalgorithm
\caption{How to write algorithms}
\end{subfigure}% need this comment symbol to avoid overfull hbox
\caption{Main caption}
\end{figure}

\end{document}


This is the error I get with the latex command:

[1
! Undefined control sequence.
<write> \newlabel{sub@loop}{{\thesubalgocf
}{\thepage }}
l.33 \end{document}


Thanks for your help!

-
Why do you want to place an algorithm environment inside a (sub)figure environment? –  Gonzalo Medina Mar 25 '12 at 0:43
I have space problems, so I put two of my algoritms in two columns. I took the idea from here tex.stackexchange.com/questions/40365/… –  Rafael Angarita Mar 25 '12 at 0:48

Instead of using a figure environment, you could use minipages and \captionof, but now your object won't float:

\documentclass{article}
\usepackage{algorithm2e}
\usepackage{caption}
\usepackage{subcaption}

\newcommand{\myalgorithm}{%
\begin{algorithm}[H]
\SetAlgoLined
\KwData{this text}
\KwResult{how to write algorithm with \LaTeX2e }
initialization\;
\lnl{loop} \While{not at end of this document}{
\eIf{understand}{
go to next section\;
current section becomes this one\;
}{
go back to the beginning of current section\;
}
}
\end{algorithm}}

\begin{document}

\begin{center}
\begin{minipage}{.5\textwidth}
\centering
\myalgorithm
\captionof{subfigure}{How to write algorithms}
\end{minipage}%
\begin{minipage}{.5\textwidth}
\centering
\myalgorithm
\captionof{subfigure}{How to write algorithms}
\end{minipage}%
\captionof{figure}{Main caption}
\end{center}

\end{document}


-