未定义控制序列 \State \For \While

未定义控制序列 \State \For \While

我正在尝试用 MiKTeX 编写伪代码。我已经使用过,\usepackage{algorithm} \usepackage{algorithmic}但我得到了:

对于每个结构 (\State、\While、\For、\If),均存在未定义的控制序列。

\begin{algorithm}
\caption{PSO}
\label{pseudoPSO}
\begin{algorithmic}[1]
\State Initialize a population of particles with random values positions and velocities from \textit{D} dimensions in the search space
\WHILE{Termination condition not reached} 
\For{ Each particle \textit{i}}
    \State Adapt velocity of the particle using Equation \ref{eq:1}
    \State Update the position of the particle using Equation \ref{eq:2}
    \State Evaluate the fitness {$f(\overrightarrow{X}_i)$}
    \If{\begin{equation}f(\overrightarrow{X}_i)<f(\overrightarrow{P}_i)\end    {equation} 
        \begin{equation}\overrightarrow{P}_i \gets \overrightarrow{X}_i\end{equation}
    \EndIf
    \If{\begin{equation}f(\overrightarrow{X}_i)<f(\overrightarrow{P}_g)\end{equation} 
        \begin{equation}\overrightarrow{P}_g \gets \overrightarrow{X}_i\end{equation}
    \EndIf
\EndFor
\ENDWHILE
\end{algorithmic}
\end{algorithm}

答案1

您正在加载algorithmic,但使用 的语法algpseudocode

\documentclass{article}
\usepackage{algorithm,algpseudocode}
\begin{document}
\begin{algorithm}
\caption{PSO}
\label{pseudoPSO}
\begin{algorithmic}[1]
\State Initialize a population of particles with random values positions
       and velocities from \textit{D} dimensions in the search space
\While{Termination condition not reached}
\For{Each particle $i$}
    \State Adapt velocity of the particle using Equation \ref{eq:1}
    \State Update the position of the particle using Equation \ref{eq:2}
    \State Evaluate the fitness {$f(\overrightarrow{X}_i)$}
    \If{$f(\overrightarrow{X}_i)<f(\overrightarrow{P}_i)$}
       \State $\overrightarrow{P}_i \gets \overrightarrow{X}_i$
    \EndIf
    \If{$f(\overrightarrow{X}_i)<f(\overrightarrow{P}_g)$}
       \State $\overrightarrow{P}_g \gets \overrightarrow{X}_i$
    \EndIf
\EndFor
\EndWhile
\end{algorithmic}
\end{algorithm}
\end{document}

equation在算法中使用没有多大意义,特别是在的论证中\If。请注意\WHILE\ENDWHILE应该是\While\EndWhile

在此处输入图片描述

相关内容