Search code examples
latexmathjaxtext-alignment

How to align math equations even when some variables are missing?


I want the variables and signs aligned in a set of equations.

Desired output:

enter image description here

What I am trying in Mathjax:

\[
\begin{align}
2&x_1 - x_2 &+ 1.5&x_3 &= 8 \\
&x_1 &- 4&x_3 &= -1
\end{align}
\]

What I got:

enter image description here

So, what do I have to do to have the same alignment as in the "desired output" image?


Solution

  • There are a number of ways to achieve this. Below I use an array (with appropriate stretch and spacing), alignat and align coupled with eqparbox for measuring similarly-tagged boxes (this latter approach requires two compilations with every change in the largest element associated with every <tag>):

    \documentclass{article}
    
    \usepackage{amsmath,eqparbox}
    
    %\usepackage{xparse}% If you have LaTeX2e < 2020-10-01
    
    % https://tex.stackexchange.com/a/34412/5764
    \makeatletter
    % \eqmathbox[<tag>][<align>]{<math>}
    \NewDocumentCommand{\eqmathbox}{o O{c} m}{%
      \IfValueTF{#1}
        {\def\eqmathbox@##1##2{\eqmakebox[#1][#2]{$##1##2$}}}
        {\def\eqmathbox@##1##2{\eqmakebox{$##1##2$}}}
      \mathpalette\eqmathbox@{#3}
    }
    \makeatother
    
    
    \begin{document}
    
    \[
      \renewcommand{\arraystretch}{1.2}
      \setlength{\arraycolsep}{0pt}
      \begin{array}{ r c r c r c r }
        2 x_1 & {}-{} & x_2 & {}+{} & 1.5 x_3 & {}={} &  8 \\
          x_1 &       &     & {}-{} &   4 x_3 & {}={} & -7
      \end{array}
    \]
    
    \begin{alignat*}{4}
      2 x_1 & {}-{} & x_2 & {}+{} & 1.5 x_3 = {} &&  8 \\
        x_1 &       &     & {}-{} &   4 x_3 = {} && -7
    \end{alignat*}
    
    \begin{align*}
      \eqmathbox[x1][r]{2 x_1}         -       \eqmathbox[x2][r]{x_2} + \eqmathbox[x3][r]{1.5 x_3} &= \eqmathbox[c][r]{8} \\
      \eqmathbox[x1][r]{  x_1} \phantom{{}-{}} \eqmathbox[x2][r]{} - \eqmathbox[x3][r]{4 x_3} &= \eqmathbox[c][r]{-7}
    \end{align*}
    
    \end{document}
    

    All yield similar output:

    enter image description here