Markdown中显示矩阵运算过程

发现这个神奇的用法,以后写博客就可以很好的演示矩阵乘法了
原文知乎
这里再分享一个可以把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))

[0123456789101112131415161718192021222324][1.373281.419540.275550.093141.667081.816800.655180.771330.329181.37744]=[3.707434.097015.4286612.388867.1499020.680728.8711328.9725810.5923737.26443]

基于以上代码,我修改了部分,让其能够显示一层嵌套的矩阵,或者显示矩阵代表的符号,这样方便写博客演示

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))

效果如下
AB=C[0123456789101112131415][0123456789101112131415]=[56626874152174196218248286324362344398452506]

阅读更多
文章标签: markdown python latex
个人分类: 技巧
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭