发现这个神奇的用法,以后写博客就可以很好的演示矩阵乘法了
原文知乎
这里再分享一个可以把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))
⎡⎣⎢⎢⎢⎢⎢⎢0510152016111621271217223813182349141924⎤⎦⎥⎥⎥⎥⎥⎥∗⎡⎣⎢⎢⎢⎢⎢⎢1.373280.27555−1.66708−0.655180.329181.41954−0.09314−1.816800.771331.37744⎤⎦⎥⎥⎥⎥⎥⎥=⎡⎣⎢⎢⎢⎢⎢⎢−3.70743−5.42866−7.14990−8.87113−10.592374.0970112.3888620.6807228.9725837.26443⎤⎦⎥⎥⎥⎥⎥⎥
[
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
]
∗
[
1.37328
1.41954
0.27555
−
0.09314
−
1.66708
−
1.81680
−
0.65518
0.77133
0.32918
1.37744
]
=
[
−
3.70743
4.09701
−
5.42866
12.38886
−
7.14990
20.68072
−
8.87113
28.97258
−
10.59237
37.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))
效果如下
A⎡⎣⎢⎢⎢0481215913261014371115⎤⎦⎥⎥⎥∗∗B⎡⎣⎢⎢⎢0481215913261014371115⎤⎦⎥⎥⎥==C⎡⎣⎢⎢⎢56152248344621742863986819632445274218362506⎤⎦⎥⎥⎥
A
∗
B
=
C
[
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
]
∗
[
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
]
=
[
56
62
68
74
152
174
196
218
248
286
324
362
344
398
452
506
]