Is there a way to define new command in algpseudocode
based on existing one? In particular, in my document I need to use both \ForAll
and \ForEach
commands. It turns out that just renaming \ForAll
doesn't work for me. I would like to define a new command \ForEach
in such a way that it keeps all the functionalities of \ForAll
(including typesetting "do" and "end for", and indenting all states inside the loop).
The code below shows what I've tried so far, but obviously that's not the way to go. I need lines 3,4,5 to be shifted together with the new command, and "end for" to be typeset.
\documentclass{article} % Specifies the document class
\usepackage{amsmath}
\usepackage{algpseudocode}
\usepackage{algorithm}
\algnewcommand\algorithmicforeach{\textbf{for each:}}
\algnewcommand\ForEach{\item[ \algorithmicforeach]}
\begin{document}
\begin{algorithm} \caption{Iterative Policy Evaluation Algorithm}
\begin{algorithmic}[1]
\Require $\pi$, the policy to be evaluated
\State Initilize $V(s) = 0$, for all $s \in \mathcal S^+$
\Repeat
\ForEach {$s \in \mathcal S $}
\State $v \gets V(s)$
\State $V(s) \gets \sum_a \pi(s,a) \sum_{s'} \mathcal P_{ss'}^a [ \mathcal R_{ss'}^a + \gamma V(s')$
\State $\Delta \gets \max(\Delta, |v- V(s)|)$
%\EndFor
\Until {$\Delta < \theta \text{ (a small positive number)}$}
\Ensure $V \approx V^\pi$
\end{algorithmic}
\end{algorithm}
\end{document}
Best Answer
In the
algpseudocode
package, theForAll
loop is defined as follows:You can simply define a
ForEach
loop that mimicks aForAll
one as follows: