I don't like how there is often a slight misalignment between assignment statements in an algorithmic
environment. For example, the first version of the algorithm given below looks strange to me. I would like to be able to align the two statements, but the commented version in my example fails to even compile. I could always manually add some space to make things line up (see the last version below), but this is obviously not a good way to go about doing things for a number of reasons. Does anyone have a good way of making the assignment statements to line up?
\documentclass{article}
\usepackage{algorithm}
\usepackage{algorithmicx}
\usepackage{amsmath}
\begin{document}
\begin{algorithm}
\caption{Compute some stuff}
\begin{algorithmic}
\State \( x \gets 1 \)
\State \( m \gets 2 \)
\end{algorithmic}
\end{algorithm}
%\begin{algorithm}
% \caption{Compute some stuff}
% \begin{algorithmic}
% \begin{align*}
% x & \gets 1 \\
% m & \gets 2
% \end{align*}
% \end{algorithmic}
%\end{algorithm}
\begin{algorithm}
\caption{Compute some stuff}
\begin{algorithmic}
\State \( \hspace{3pt} x \gets 1 \)
\State \( m \gets 2 \)
\end{algorithmic}
\end{algorithm}
\end{document}
Best Answer
You need to use some "box manipulation":
I insert a box that has the width of the widest element (
m
in this case) using\phantom
. This pushes the setting as deep is as necessary. Then I insertx
using al
eft overlap
(inmath
-mode; via\mathllap
frommathtools
). It takes up zero width, so it doesn't affect the spacing or "move the cursor" so to speak. The rest is set as usual.