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 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}{
read current\;
\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!

share|improve this question
    
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 Mar 25 '12 at 0:48

1 Answer 1

up vote 3 down vote accepted

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}{
read current\;
\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}

enter image description here

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.