[Tex/LaTex] Aligning polynomial terms

alignamsmathhorizontal alignmentmath-mode

In LaTeX align, I'm struggling to align polynomial terms and assume there's an easy way to do it. But I cannot find the simple/elegant solution. What I would like is something like this:

x1 + x2 ______________ = 3

x1_______________+ x3 = 4

etc with more lines and variables (the underlines are just for space/alignment). Any help appreciated.

UPDATE Here is the solution I found:

\begin{alignat*}{7}
8x_1 &{}+ 4x_2 &{}+ y_1   &        &        &        &= 160     \\
4x_1 &{}+ 6x_2 &          &{}+ y_2 &        &        &= 120     \\
x_1  &         &          &        &{}+ y_3 &        &= 34      \\
\phantom{{}+{}x_1}&{}+x_2&&        &        &{}+ y_4 &= 14      \\
x_1\geq0&x_2\geq0&y_1\geq0&y_2\geq0&y_3\geq0& y_4\geq0
\end{alignat*}

with result:

linear system

Best Answer

You could also use the alignat* environment from the amsmath package- see page 5 of the documentation for details and other examples.

Note that without the {} you don't get correct spacing after the + sign.

\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{alignat*}{4} % 4 is the number of equation columns
  x_1&+x_2&     & =3\\
  x_1&    &{}+x_3 &= 4
\end{alignat*}
\end{document}

enter image description here

EDIT Following mforbes' comment, and a few extra test cases, it is probably more robust to make extra columns for the + and =. For example, say that you wanted to put some coefficients in front of some of the terms.

\begin{alignat*}{4}
     x_1 &{}+{}&x_2    &      &     &{}={}&3\\
     x_1 &     &       &{}+{} & x_3 &{}={}&4
\end{alignat*}

As mforbes pointed out, the amsmath documentation says 'count the maximum number of &s in any row, add 1 and divide by 2'; I've found that if you get a fraction, then you should round up, hence {4} and not {3}.

Related Question