Markdown中顯示矩陣運算過程
阿新 • • 發佈:2019-01-18
發現這個神奇的用法,以後寫部落格就可以很好的演示矩陣乘法了
原文知乎
這裡再分享一個可以把latex轉成圖片的線上網站quicklatex
markdown 顯示矩陣
from IPython.display import display,Latex,Math
%matplotlib inline
import numpy as np
from IPython.core.interactiveshell import InteractiveShell
sh = InteractiveShell.instance()
def number_to_str(n,cut=5):
ns=str(n)
format_='{0:.' +str(cut)+'f}'
if 'e' in ns or ('.' in ns and len(ns)>cut+1):
return format_.format(n)
else:
return str(n)
def matrix_to_latex(mat,style='bmatrix'):
if type(mat)==np.matrixlib.defmatrix.matrix:
mat=mat.A
head=r'\begin{'+style+'}'
tail=r'\end{'+style+'}'
if len(mat.shape)==1:
body=r'\\'.join([str(el) for el in mat])
return head+body+tail
elif len(mat.shape)==2:
lines=[]
for row in mat:
lines.append('&'.join([number_to_str(el) for el in row])+r'\\')
s=head+' '.join(lines)+tail
return s
return None
sh.display_formatter.formatters['text/latex'].type_printers[np.ndarray]=matrix_to_latex
def show_decomposition(*args):
latex=''
for arg in args:
if type(arg)==str:
latex+=arg
else:
latex+=matrix_to_latex(arg)
latex='$'+latex+'$'
display(Math(latex))
效果如下
A = arange(25).reshape(5, 5)
omega = random.randn(5, 2)
show_decomposition(A,"*",omega,"=", np.dot(A,omega))
基於以上程式碼,我修改了部分,讓其能夠顯示一層巢狀的矩陣,或者顯示矩陣代表的符號,這樣方便寫部落格演示
def matrix_object_to_latex(col, *args):
latex='$ \\begin{matrix} '
i = 0
for arg in args:
i = i + 1
latex += " & "
if type(arg)==str:
latex+=arg
else:
latex+=matrix_to_latex(arg)
if i % col == 0:
latex += " \\\\ "
latex += "\end{matrix} $"
print(latex)
display(Math(latex))
return latex
測試程式碼
d = 4
matrix_a = np.arange(d*d).reshape(d,d)
matrix_b = np.arange(d*d).reshape(d,d)
tex = matrix_object_to_latex(5, "A","*","B","=","C",matrix_a,"*",
matrix_b,"=",np.dot(matrix_a,matrix_b))
效果如下