alignat not correctly aligning

I have the following code:

\begin{alignat}{4}
\sum_{r}\sum_{p} & X_{i,m,r,p}       & = d_m                          \quad & \forall i, m\\
\sum_{q=0}^{d_{m}-1} & X_{i,m,r,(p+q)}   & = d_m \times \hat{X}_{i,m,r,p} \quad & \forall i, m, r, p\\
\sum_{p} & \hat{X}_{i,m,r,p} & \leq 1                         \quad & \forall i, m, r
\end{alignat}


Which should show three lines with the X's aligned, the RHS aligned, and the \forall conditions on the right aligned.

What I'm getting, instead, is something like this:

I use alignat in my other LaTeX document, and it works perfectly. I have no idea what I've done wrong, but I can't find anything different in the way I've used alignat in this document compared to my other one.

-
The rule for alignment is rlrlrl…. If you want to have two columns aligned left or right use && between them. –  Qrrbrbirlbel Mar 3 '13 at 23:43

You're short some alignment tabs, as mentioned in comment by Qrrbrbirlbel. Here's the proper usage:

\documentclass{article}
\usepackage{amsmath}% http://ctan.org/pkg/amsmath
\begin{document}
\begin{alignat}{4}
\sum_{r}\sum_{p} & X_{i,m,r,p}       & = d_m                          \quad & \forall i, m\\
\sum_{q=0}^{d_{m}-1} & X_{i,m,r,(p+q)}   & = d_m \times \hat{X}_{i,m,r,p} \quad & \forall i, m, r, p\\
\sum_{p} & \hat{X}_{i,m,r,p} & \leq 1                         \quad & \forall i, m, r
\end{alignat}

\begin{alignat}{4}
\sum_{r}\sum_{p} & X_{i,m,r,p}       && = d_m                          \quad && \forall i, m\\
\sum_{q=0}^{d_{m}-1} & X_{i,m,r,(p+q)}   && = d_m \times \hat{X}_{i,m,r,p} \quad && \forall i, m, r, p\\
\sum_{p} & \hat{X}_{i,m,r,p} && \leq 1                         \quad && \forall i, m, r
\end{alignat}
\end{document}


Consider reading about the AMS alignment environments in Herbert's mathmode document. Specifically, section 25 align environments (p 43 onwards).

-