You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为IPython.display.Latex输出添加换行并对齐矩阵?

问题分析与解决

你的问题出在仅用\\实现换行,但没有使用LaTeX的对齐环境指定对齐位置,导致两个矩阵只是单纯换行,无法按等号对齐。

要实现矩阵对齐,需要用LaTeX的align*(无编号对齐环境),通过&标记对齐点(通常是等号位置)。

修改后的代码如下:

from IPython.display import display, Latex

s = r"$$\begin{align*} \text{A } &= \left[\begin{matrix}1 & 2 & 3\\1 & 1 & 1\\0 & 0 & 0\\3 & 3 & 3\end{matrix}\right] \\  \text{B } &= \left[\begin{matrix}1 & 2 & 3 & 4\\1 & 1 & 1 & 2\\0 & 0 & 0 & 1\\3 & 3 & 3 & 1\end{matrix}\right] \end{align*}$$"

display(Latex(s))

关键修改说明

  • 用\begin{align*}和\end{align*}包裹公式内容,启用对齐排版环境
  • 在每个等号前添加&,标记对齐基准点,让两个矩阵的等号自动对齐
  • 保留raw字符串(r"")格式,避免LaTeX转义字符被Python错误解析

内容的提问来源于stack exchange,提问作者Ray Ronnaret

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 23:05:57