You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

LaTeX表格复刻需求:设置文本宽度并添加指定竖线

解决方案:适配文本宽度并添加“for”下方竖线

我来帮你搞定这个LaTeX表格的问题!要实现表格和页面文本宽度一致,同时在“for”下方添加竖线,我们可以通过调整表格环境和宏包来实现,下面分两种方式给出方案:

方式一:基于tabularx调整现有表格结构

首先在导言区添加必要的宏包:

\usepackage{booktabs}
\usepackage{tabularx} % 用于让表格适配文本宽度
\usepackage{array}    % 辅助自定义列格式

然后修改你的表格代码,用tabularx替代普通tabular,并手动添加竖线:

\begin{table}[h]
    \centering
    \label{my-label}
    % 设置表格宽度等于文本宽度,@{}去除左右边距
    \begin{tabularx}{\linewidth}{@{}X@{}}
        \toprule
        \textbf{Algorithm 2:} The Forward algorithm \\
        \midrule
        \textbf{Initialization:} \\
        \quad $\alpha_1(i) = \pi_i b_i(O_1), \ 1 \leq i \leq K$ \\
        \\
        \textbf{Recursion:} \\
        \quad \textbf{For} $t = 1$ \textbf{to} $T-1$: \\
        % 这里添加竖线,对齐for的缩进,调整竖线高度和位置
        \quad \multicolumn{1}{@{}l@{}}{\hspace{1em}\rule[-0.5ex]{0.4pt}{2.5ex}\hspace{0.5em}}$\alpha_{t+1}(j) = \left( \sum_{i=1}^K \alpha_t(i) a_{ij} \right) b_j(O_{t+1}), \ 1 \leq j \leq K$ \\
        \\
        \textbf{Termination:} \\
        \quad $P(O \mid \lambda) = \sum_{i=1}^K \alpha_T(i)$ \\
        \bottomrule
    \end{tabularx}
\end{table}
  • tabularx{\linewidth}{@{}X@{}}让表格自动填充整个文本宽度,X列会根据内容自动换行;
  • \rule[-0.5ex]{0.4pt}{2.5ex}是自定义竖线,-0.5ex是向下偏移,2.5ex是竖线高度,0.4pt是线宽,你可以根据需求调整这些参数。

方式二:使用专业算法环境(更推荐)

如果是写算法伪代码,更推荐用algorithmalgpseudocode宏包,它会自动处理循环的竖线,且格式更规范,默认适配文本宽度:
导言区添加宏包:

\usepackage{algorithm}
\usepackage{algpseudocode}

然后编写算法:

\begin{algorithm}[h]
    \caption{The Forward algorithm}
    \label{my-label}
    \begin{algorithmic}[1]
        \State \textbf{Initialization:}
        \State \quad $\alpha_1(i) = \pi_i b_i(O_1), \ 1 \leq i \leq K$
        \State
        \State \textbf{Recursion:}
        \For{$t = 1$ \textbf{to} $T-1$}
            \State $\alpha_{t+1}(j) = \left( \sum_{i=1}^K \alpha_t(i) a_{ij} \right) b_j(O_{t+1}), \ 1 \leq j \leq K$
        \EndFor
        \State
        \State \textbf{Termination:}
        \State \quad $P(O \mid \lambda) = \sum_{i=1}^K \alpha_T(i)$
    \end{algorithmic}
\end{algorithm}

这个环境会自动在For循环的内容前添加竖线,不需要手动绘制,而且支持行号、caption等专业格式,非常适合算法展示。

内容的提问来源于stack exchange,提问作者Rafael Díaz

火山引擎 最新活动