Last active
February 21, 2021 07:05
-
-
Save noppoMan/49817c80efbe81de551dd08b687ea117 to your computer and use it in GitHub Desktop.
Convenient conversion code from numpy to tex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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