[Tex/LaTex] Why does the \LinesNumbered command not work of the algorithm2e package in beamer frame

algorithm2ebeamerline-numbering

I want to add line number from the fourth line, but the \LinesNumbered command doesn't work at all.

\documentclass{beamer}
\usepackage{algorithm2e}
\begin{document}
\begin{frame}
  \begin{algorithm}[H]
    \DontPrintSemicolon
    \KwSty{type} val : \KwSty{real}$[k]$\;
    \KwSty{type} ind : \KwSty{int}$[k]$\;
    \KwSty{type} ptr : \KwSty{int}$[m+1]$\;
    \LinesNumbered
    \ForEach{row $i$}{
      \For{$l=ptr[i]$ \KwTo $prt[i+1]-1$}{
     $ y[i] \leftarrow y[i]+val[l] \cdot x[ind[l]]$ \;
      }
    }
  \end{algorithm}
\end{frame}

\end{document}

Its output is:

enter image description here

But I want it looks like this:(And how can I add the red color for ind[l]?)

enter image description here

Best Answer

It's not a problem of the frame environment... \LinesNumbered works only if issued outside the algorithm environment.

But you can use

\everypar={\nl}

instead.

MWE (I've also added red text coloring for ind[l] and improvements for math operators)

\documentclass{beamer}
\usepackage{algorithm2e}

\DeclareMathOperator{\ind}{ind}
\DeclareMathOperator{\val}{val}
\DeclareMathOperator{\ptr}{ptr}
\DeclareMathOperator{\row}{row}

\begin{document}
\begin{frame}
  \begin{algorithm}[H]
    \DontPrintSemicolon
    \KwSty{type} val : \KwSty{real}$[k]$\;
    \KwSty{type} ind : \KwSty{int}$[k]$\;
    \KwSty{type} ptr : \KwSty{int}$[m+1]$\;
    \everypar={\nl}
    \ForEach{$\row i$}{
      \For{$l=\ptr[i]$ \KwTo $\ptr[i+1]-1$}{
     $ y[i] \leftarrow y[i]+\val[l] \cdot x[\textcolor{red}{\ind[l]}]$ \;
      }
    }
  \end{algorithm}
\end{frame}
\end{document} 

enter image description here