Skip to content

Instantly share code, notes, and snippets.

@noppoMan
Last active February 21, 2021 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noppoMan/49817c80efbe81de551dd08b687ea117 to your computer and use it in GitHub Desktop.
Save noppoMan/49817c80efbe81de551dd08b687ea117 to your computer and use it in GitHub Desktop.
Convenient conversion code from numpy to tex
import numpy as np
def np_array_to_tex(A):
if A.ndim != 2:
raise Exception("ndim should be 2")
B = np.asarray(A)
rows = list(map(lambda row: " & ".join(map(str, row)), B))
return "\n".join([
"\\begin{pmatrix}",
" \\\\ \n".join(rows),
"\\end{pmatrix}"
])
def np_array_operation_to_tex(A, B, operator: str):
"""
operator: +, -, *
"""
R = eval(f"A {operator} B")
op = " " if operator == "*" else f" {operator} "
return np_array_to_tex(A) + op + np_array_to_tex(B) + " = " + np_array_to_tex(R)
if __name__ == "__main__":
A = np.array([
[1, 2, 3, 4]
[5, 6, 7, 8]
])
print(np_array_operation_to_tex(A, A, "*"))
# => Output
"""
\begin{pmatrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8
\end{pmatrix} \begin{pmatrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8
\end{pmatrix} = \begin{pmatrix}
1 & 4 & 9 & 16 \\
25 & 36 & 49 & 64
\end{pmatrix}
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment