即使缺少某些变量,如何对齐数学方程式?

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

我希望变量和符号在一组方程式中对齐。

期望的输出:

我在 Mathjax 中的尝试:

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

我得到的:

那么,我需要做什么才能使对齐方式与“所需输出”图像中的对齐方式相同?

有多种方法可以实现这一点。下面我使用 array(具有适当的拉伸和间距)、alignatalign 以及 eqparbox 来测量类似标记的框(后一种方法需要两次编译每个与每个 <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}

全部产生相似的输出: