Mark pivot positions in a matrix
I would like to annotate the LaTeX output of a matrix by marking its pivot entries (perhaps with \boxed{}
). Is this possible?
add a comment
I would like to annotate the LaTeX output of a matrix by marking its pivot entries (perhaps with \boxed{}
). Is this possible?
Each matrix m
has a method m._latex_
that gives its LaTeX form.
Having defined a matrix m
, we can use m._latex_?
or m._latex_??
to get the documentation or the source code for that method.
This can provide inspiration for preparing a version that boxes pivots.
Here is an attempt:
def latex_pivots(m):
r"""
Return latex representation of this matrix, with pivots boxed.
The matrix is enclosed in parentheses by default, but the delimiters
can be changed using the command ``latex.matrix_delimiters(...)``.
EXAMPLES::
sage: a = identity_matrix(3)
sage: print(latex_pivots(a))
\left(\begin{array}rrr
\boxed{1} & 0 & 0 \\
0 & \boxed{1} & 0 \\
0 & 0 & \boxed{1}
\end{array}\right)
Pivots are meaningless if not in echelon form::
sage: R = PolynomialRing(QQ, 4, 'z')
sage: a = matrix(2, 2, R.gens())
sage: b = a * a
sage: print(latex_pivots(b))
\left(\begin{array}rr
\boxed{z_{0}^{2} + z_{1} z_{2}} & z_{0} z_{1} + z_{1} z_{3} \\
\boxed{z_{0} z_{2} + z_{2} z_{3}} & z_{1} z_{2} + z_{3}^{2}
\end{array}\right)
Block matrix::
sage: B = matrix(3, 4, [0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
sage: B.subdivide([2, 2], [3])
sage: print(latex_pivots(B))
\left(\begin{array}rrr|r
0 & \boxed{1} & 0 & 0 \\
0 & 0 & 0 & \boxed{1} \\
\hline\hline
0 & 0 & 0 & 0
\end{array}\right)
"""
latex = sage.misc.latex.latex
boxed = lambda latex_expr: f"\\boxed{{{latex_expr}}}"
left, right = latex.matrix_delimiters()
align = latex.matrix_column_alignment()
nr = m.nrows()
nc = m.ncols()
if nr == 0 or nc == 0:
return left + right
S = m.list()
rows = []
row_divs, col_divs = m.subdivisions()
# construct one large array, using \hline and vertical
# bars | in the array descriptor to indicate subdivisions.
for r in range(nr):
s = "\\hline" * row_divs.count(r) + "\n" if r in row_divs else ""
zero_so_far = True
for c in range(nc):
aij = S[r*nc+c]
entry = latex(aij)
if zero_so_far and aij:
zero_so_far = False
entry = boxed(entry)
s += (" & " + entry) if c else entry
rows.append(s)
# Put brackets around in a single string
s = " \\\\\n".join(rows)
tmp = [align*(b-a) for a, b in zip([0] + col_divs, col_divs + [nc])]
array = f"\\begin{{array}}{'|'.join(tmp)}\n{s}\n\\end{{array}}"
return f"\\left{left}{array}\\right{right}"
Usage example:
sage: a = identity_matrix(3)
sage: print(latex_pivots(a))
\left(\begin{array}rrr
\boxed{1} & 0 & 0 \\
0 & \boxed{1} & 0 \\
0 & 0 & \boxed{1}
\end{array}\right)
Please start posting anonymously - your entry will be published after you log in or create a new account.
Asked: 2024-12-18 02:05:15 +0100
Seen: 66 times
Last updated: yesterday