I am trying to put an algorithm and a tikz' drawing side-by-side inside a figure environment. I am aware of this question but I would like to have a single caption for them. For instance, in the text, Figure 1a would refer to the algorithm while Figure 1b would refer to the tikz' drawing.

  • How do you set the algorithm? – egreg Jan 6 '12 at 16:12
  • Use the package subcaption. – Marco Daniel Jan 6 '12 at 16:13
  • @egreg: I have tried using nested \minipage...\begin{algorithm}...\begin{algorithmic}<algorithm here>...\end..\end..\end, nested \minipage...\begin{algorithmic}<algorithm here>...\end..\end and just \begin{algorithmic}<algorithm here>...\end directly inside the \subfloat (obviously with the correct syntax) but none of them worked out. – freitass Jan 6 '12 at 16:16
  • @MarcoDaniel: I have already looked at it, but couldn't figure out how to make that work. – freitass Jan 6 '12 at 16:19
  • @freitass: I edited slightly the title to make it more generic. I hope that's ok with you. – Count Zero Jan 6 '12 at 17:44

I recommend the using of the subcaption package. It works well with caption (same author, thanks Axel).

\usepackage{algorithm}% http://ctan.org/pkg/algorithm
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx


  \Procedure{Euclid}{$a,b$}\Comment{The g.c.d. of a and b}
    \State $r\gets a\bmod b$
    \While{$r\not=0$}\Comment{We have the answer if r is 0}
      \State $a\gets b$
      \State $b\gets r$
      \State $r\gets a\bmod b$
    \State \textbf{return} $b$\Comment{The gcd is b}

\tikz\draw [fill=red!20] (0,0) rectangle (3,2);

Text \ref{fig:alg} and \ref{fig:tikz} and \ref{fig:both}


enter image description here

  • That is just what I needed. Thank you very much! Thank also to the algpseudocode package. I tried the same with the algorithmic package and it didn't work. – freitass Jan 6 '12 at 17:04

Just don't enclose algorithmic in the algorithm environment, but rather in a minipage; here I've used varwidth to get the exact width.

\REQUIRE $n \geq 0 \vee x \neq 0$ 
\ENSURE $y = x^n$ 
\STATE $y \leftarrow 1$ 
\IF{$n < 0$} 
\STATE $X \leftarrow 1 / x$ 
\STATE $N \leftarrow -n$ 
\STATE $X \leftarrow x$ 
\STATE $N \leftarrow n$ 
\WHILE{$N \neq 0$} 
\IF{$N$ is even} 
\STATE $X \leftarrow X \times X$ 
\STATE $N \leftarrow N / 2$ 
\ELSE[$N$ is odd] 
\STATE $y \leftarrow y \times X$ 
\STATE $N \leftarrow N - 1$ 
\caption{A caption}

enter image description here

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.