我正在寻找一种将numpy数组迁移到latex bmatrix的简洁方法。它应该适用于2d阵列和水平和垂直1d阵列。
示例
A = array([[12, 5, 2],
[20, 4, 8],
[ 2, 4, 3],
[ 7, 1,10]])
print A #2d array
print A[0] #horizontal array
print A[:,0, None] #vertical array
array_to_bmatrix(A)
array_to_bmatrix(A[0])
array_to_bmatrix(A[:,0, None])
输出:
[[12 5 2]
[20 4 8]
[ 2 4 3]
[ 7 1 10]]
[12 5 2]
[[12]
[20]
[ 2]
[ 7]]
\begin{bmatrix}
12.000 & 5.000 & 2.000 & \\
20.000 & 4.000 & 8.000 & \\
2.000 & 4.000 & 3.000 & \\
7.000 & 1.000 & 10.000 & \\
\end{bmatrix}
\begin{bmatrix}
12.000 & 5.000 & 2.000
\end{bmatrix}
\begin{bmatrix}
12.000 & \\
20.000 & \\
2.000 & \\
7.000 & \\
\end{bmatrix}
尝试解决方案
def array_to_bmatrix(array):
begin = '\\begin{bmatrix} \n'
data = ''
for line in array:
if line.size == 1:
data = data + ' %.3f &'%line
data = data + r' \\'
data = data + '\n'
continue
for element in line:
data = data + ' %.3f &'%element
data = data + r' \\'
data = data + '\n'
end = '\end{bmatrix}'
print begin + data + end
此解决方案适用于垂直和二维数组,但它将水平数组输出为垂直数组。
array_to_bmatrix(A[0])
输出:
\begin{bmatrix}
12.000 & \\
5.000 & \\
2.000 & \\
\end{bmatrix}
答案 0 :(得分:16)
numpy数组的__str__
方法已经为您完成了大部分格式化操作。让我们利用它;
import numpy as np
def bmatrix(a):
"""Returns a LaTeX bmatrix
:a: numpy array
:returns: LaTeX bmatrix as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most display two dimensions')
lines = str(a).replace('[', '').replace(']', '').splitlines()
rv = [r'\begin{bmatrix}']
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines]
rv += [r'\end{bmatrix}']
return '\n'.join(rv)
A = np.array([[12, 5, 2], [20, 4, 8], [ 2, 4, 3], [ 7, 1, 10]])
print bmatrix(A) + '\n'
B = np.array([[1.2], [3.7], [0.2]])
print bmatrix(B) + '\n'
C = np.array([1.2, 9.3, 0.6, -2.1])
print bmatrix(C) + '\n'
返回:
\begin{bmatrix}
12 & 5 & 2\\
20 & 4 & 8\\
2 & 4 & 3\\
7 & 1 & 10\\
\end{bmatrix}
\begin{bmatrix}
1.2\\
3.7\\
0.2\\
\end{bmatrix}
\begin{bmatrix}
1.2 & 9.3 & 0.6 & -2.1\\
\end{bmatrix}
答案 1 :(得分:1)
另一个,灵感来自罗兰史密斯的回答 支持科学记数法
def bmatrix(a):
"""Returns a LaTeX bmatrix
:a: numpy array
:returns: LaTeX bmatrix as a string
"""
if len(a.shape) > 2:
raise ValueError('bmatrix can at most display two dimensions')
temp_string = np.array2string(a, formatter={'float_kind':lambda x: "{:.2e}".format(x)})
lines = temp_string.replace('[', '').replace(']', '').splitlines()
rv = [r'\begin{bmatrix}']
rv += [' ' + ' & '.join(l.split()) + r'\\' for l in lines]
rv += [r'\end{bmatrix}']
return '\n'.join(rv)
结果:
\begin{bmatrix}
7.53e-04 & -2.93e-04 & 2.04e-04 & 5.30e-05 & 1.84e-01 & -2.43e-05\\
-2.93e-04 & 1.19e-01 & 2.96e-01 & 2.19e-01 & 1.98e+01 & 8.61e-03\\
2.04e-04 & 2.96e-01 & 9.60e-01 & 7.42e-01 & 4.03e+01 & 2.45e-02\\
5.30e-05 & 2.19e-01 & 7.42e-01 & 6.49e-01 & 2.82e+01 & 1.71e-02\\
1.84e-01 & 1.98e+01 & 4.03e+01 & 2.82e+01 & 5.75e+03 & 1.61e+00\\
-2.43e-05 & 8.61e-03 & 2.45e-02 & 1.71e-02 & 1.61e+00 & 7.04e-03\\
\end{bmatrix}
答案 2 :(得分:0)
执行此操作时:
for line in array:
您正在迭代array
的第一维。当数组是1-D时,最终会迭代值。在进行此迭代之前,您需要确保array
确实是2-D。一种方法是通过numpy.atleast_2d
传递参数:
import numpy as np
def array_to_bmatrix(array):
array = np.atleast_2d(array)
begin = '\\begin{bmatrix} \n'
data = ''
for line in array:
等
答案 3 :(得分:0)
我对使用Python的打印输出不满意。矩阵可能太大,导致包裹。 这是用于打印2d矩阵的LaTeX文本的代码。
def bmatrix(a):
text = r'$\left[\begin{array}{*{'
text += str(len(a[0]))
text += r'}c}'
text += '\n'
for x in range(len(a)):
for y in range(len(a[x])):
text += str(a[x][y])
text += r' & '
text = text[:-2]
text += r'\\'
text += '\n'
text += r'\end{array}\right]$'
print text
这给出了这个
$\left[\begin{array}{*{16}c}
2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 \\
0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 \\
0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 \\
-1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 & 0 \\
0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 & -1 \\
-1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 & 0 \\
0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 & 0 \\
0 & 0 & -1 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & 0 & -1 & 0 & 0 & 2.01 \\
\end{array}\right]$
答案 4 :(得分:0)
我已经尝试了一个全面的解决方案,以便个人甚至不需要编写一个最小的脚本就可以完成它。我为浮动,格式化,复杂和Pandas数组增加了灵活性。请使用(array_to_latex)[https://pypi.org/project/array-to-latex/]并提供反馈。
答案 5 :(得分:0)
此外,除了前面的答案外,您还可以通过这种方式从阵列中生成乳胶
from IPython.display import *
from numpy import *
A = array([[12, 5, 2],
[20, 4, 8],
[ 2, 4, 3],
[ 7, 1,10]])
list=A
str1 ='$$' +'\\begin{bmatrix}'+ '&\\\\'.join(str(e) for e in list)+ '\\end{bmatrix}'+'$$'
print(str1 )
str1 = str1.replace('[', ' ')
str1 = str1.replace(']', ' ')
display(Latex(str1))
答案 6 :(得分:0)
另一个选择是使用sympy:首先将数组转换为sympy.Matrix,然后使用sympy.latex函数。
答案 7 :(得分:0)
进一步的答案,灵感来自罗兰·史密斯(Roland Smith)的答案:
def matToTex(a, roundn=2, matrixType = "b",rowVector = False):
if type(a) != np.ndarray:
raise ValueError("Input must be np array")
if len(a.shape) > 2:
raise ValueError("matrix can at most display two dimensions")
if matrixType not in ["b","p"]:
raise ValueError("matrix can be either type \"b\" or type \"p\"")
if rowVector:
if not (len(a.shape) != 1 or a.shape[0] != 1):
raise ValueError("Cannot rowVector this bad boi, it is not a vector!")
lines = str(a).splitlines()
ret = "\n\\begin{"+matrixType+"matrix}\n"
for line in lines:
line = re.sub("\s+",",",re.sub("\[|\]","",line).strip())
nums = line.split(",");
if roundn != -1:
nums = [str(round(float(num),roundn)) for num in nums]
if rowVector:
ret += " \\\\\n".join(nums)
else:
ret += " & ".join(nums)+" \\\\ \n"
ret += "\n\\end{"+matrixType+"matrix}\n"
ret = re.sub("(\-){0,1}0.[0]* ","0 ",ret)
print(ret)
答案 8 :(得分:-1)
尝试array_to_latex (pip install)
。我正是出于这个原因写的。请提供您的反馈意见。
它具有默认值,但还允许您自定义格式(指数,小数位数)并处理复数,并且可以将结果“弹出”到剪贴板中(无需复制转储到屏幕上的文本)。
github存储库中的一些示例。 https://github.com/josephcslater/array_to_latex