Skip to content

Commit 90144f6

Browse files
committed
add to_matrix method
1 parent 7a947f3 commit 90144f6

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

src/arraytex/api.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
"""Main package API."""
2+
3+
from typing import Any
4+
5+
import numpy as np
6+
from numpy.typing import NDArray
7+
8+
9+
def to_matrix(arr: NDArray[Any]) -> str:
10+
"""Convert a numpy.NDArray to LaTeX matrix.
11+
12+
Args:
13+
arr: the array to be converted
14+
15+
Returns:
16+
the string representation of the array
17+
"""
18+
environment = "bmatrix"
19+
lines = (
20+
np.array2string(arr, max_line_width=np.inf) # type: ignore # noqa
21+
.replace("[", "")
22+
.replace("]", "")
23+
.splitlines()
24+
)
25+
rv = [f"\\begin{{{environment}}}"]
26+
rv += [" " + " & ".join(line.split()) + r" \\" for line in lines]
27+
rv += [f"\\end{{{environment}}}"]
28+
return "\n".join(rv)

tests/test_api.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""Tests for the main API."""
2+
import numpy as np
3+
4+
from arraytex.api import to_matrix
5+
6+
7+
class TestToMatrix:
8+
"""Tests for the `to_matrix` function."""
9+
10+
def test_success(self) -> None:
11+
"""A formatted matrix is returned."""
12+
mat = np.array(
13+
[
14+
[1, 2, 3],
15+
[4, 5, 6],
16+
]
17+
)
18+
19+
out = to_matrix(mat)
20+
21+
assert (
22+
out
23+
== r"""\begin{bmatrix}
24+
1 & 2 & 3 \\
25+
4 & 5 & 6 \\
26+
\end{bmatrix}"""
27+
)

0 commit comments

Comments
 (0)