[Tex/LaTex] How to define frequently used variables in pseudocode

algorithmicxpseudocode

alg_pic

To generate the above pseudocode, I used the following code:

\begin{algorithm}
\caption{sample}\label{sample}
\begin{algorithmic}[1]
\Require $\mathbf{D} \in \mathbb{R}^{M \times N}$
\State $\mathbf{V}^{(0)} \in \mathbb{R}^{K \times N} \gets $ random matrix
\For {$t= 1:T$}
    \State $\mathbf{U}^{(t)} \gets Update\mathbf{U}(\mathbf{D},\mathbf{V}^{t-1})$
    \State $\mathbf{V}^{(t)} \gets Update\mathbf{V}(\mathbf{D},\mathbf{U}^{t})$
\EndFor 
\State \Return $\mathbf{U}^{(T)},\mathbf{V}^{(T)}$
\end{algorithmic}
\end{algorithm}

The problem is I have to use \mathbf for all D,UandV to represent them as matrix or vector. Is there other way to define these variables once and no need to use \mathbf for all?

Best Answer

Yes, the typical approach here is to follow the advice in Consistent typoraphy. That is, create a macro that defines the concept and use it throughout your document.

enter image description here

\documentclass{article}

\usepackage{algorithm,algpseudocode,amsfonts}

\newcommand{\sampleset}{\mathbf{D}}
\newcommand{\universe}[1]{\mathbb{R}^{#1}}
\newcommand{\setA}{\mathbf{U}}
\newcommand{\setB}{\mathbf{V}}

\begin{document}

\begin{algorithm}
  \caption{sample}\label{sample}
  \begin{algorithmic}[1]
  \Require $\sampleset \in \universe{M \times N}$
  \State $\setB^{(0)} \in \universe{K \times N} \gets $ random matrix
  \For {$t= 1:T$}
    \State $\setA^{(t)} \gets Update\setA(\mathbf{D},\setA^{t-1})$
    \State $\setB^{(t)} \gets Update\setB(\mathbf{D},\setB^{t})$
  \EndFor 
  \State \Return $\setA^{(T)},\setB^{(T)}$
  \end{algorithmic}
\end{algorithm}

\end{document}

Above I've defined some variables, but you can do the same with functions inside your algorithm.