11

I have a LaTeX code which looks similar to the following example.

\documentclass{article}
\usepackage{amsmath,algorithm,algpseudocode}
\begin{document}
\begin{algorithm}
\caption{My Algo.}
\label{alg:myalgo}
\begin{algorithmic}[1]
\Function{CallA}{$a$} \label{alg:a}
    \State \Call{CalcSquare}{$a$}
\EndFunction
\Statex
\Function{CalcSquare}{$b$} \label{alg:b}
    \State \Return $b\times b$
\EndFunction
\end{algorithmic}
\end{algorithm}
The \ref{alg:a} function calls \ref{alg:b} inside.
\end{document}

How can I make \ref{alg:a} show the name of function instead of line number?

It is desired to appear "The CallA function calls CalcSquare inside", but what it actually looks like is "The 1 function calls 4 inside".

1
  • Yes, I meant "CallA".
    – Jayden
    Apr 29, 2013 at 21:40

1 Answer 1

7

You can define a new command, say \funclabel for storing the function name. Then you can retrieve it with the usual \ref.

\documentclass{article}
\usepackage{amsmath,algorithm,algpseudocode}

\makeatletter
\renewcommand{\Function}[2]{%
  \csname ALG@cmd@\ALG@L @Function\endcsname{#1}{#2}%
  \def\jayden@currentfunction{#1}%
}
\newcommand{\funclabel}[1]{%
  \@bsphack
  \protected@write\@auxout{}{%
    \string\newlabel{#1}{{\jayden@currentfunction}{\thepage}}%
  }%
  \@esphack
}
\makeatother


\begin{document}
\begin{algorithm}
\caption{My Algo.}
\label{alg:myalgo}
\begin{algorithmic}[1]
\Function{CallA}{$a$} \funclabel{alg:a} \label{alg:a-line}
    \State \Call{CalcSquare}{$a$}
\EndFunction
\Statex
\Function{CalcSquare}{$b$} \funclabel{alg:b}
    \State \Return $b\times b$
\EndFunction
\end{algorithmic}
\end{algorithm}
The \ref{alg:a} function at line~\ref{alg:a-line} calls \ref{alg:b} inside.
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .