10000 add function to input 2D array in MATLAB style, updated doco · rocsys/spatialmath-python@e3e95f9 · GitHub
[go: up one dir, main page]

Skip to content

Commit e3e95f9

Browse files
committed
add function to input 2D array in MATLAB style, updated doco
1 parent 841032f commit e3e95f9

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

spatialmath/base/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -341,6 +341,7 @@
341341
"numjac",
342342
"numhess",
343343
"array2str",
344+
"str2array",
344345
"bresenham",
345346
"mpq_point",
346347
"gauss1d",

spatialmath/base/numeric.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import re
12
import numpy as np
23
from spatialmath import base
34
from spatialmath.base.types import *
@@ -136,6 +137,17 @@ def array2str(
136137
:rtype: str
137138
138139
Converts a small array to a compact single line representation.
140+
141+
142+
.. runblock:: pycon
143+
144+
>>> array2str(np.random.rand(2,2))
145+
>>> array2str(np.random.rand(2,2), rowsep="; ") # MATLAB-like
146+
>>> array2str(np.random.rand(3,))
147+
>>> array2str(np.random.rand(3,1))
148+
149+
150+
:seealso: :func:`array2str`
139151
"""
140152
# convert to ndarray if not already
141153
if isinstance(X, (list, tuple)):
@@ -166,6 +178,38 @@ def format_row(x):
166178
s = brackets[0] + s + brackets[1]
167179
return s
168180

181+
def str2array(s: str) -> NDArray:
182+
"""
183+
Convert compact single line string to array
184+
185+
:param s: string to convert
186+
:type s: str
187+
:return: array
188+
:rtype: ndarray
189+
190+
Convert a string containing a "MATLAB-like" matrix definition to a NumPy
191+
array. A scalar has no delimiting square brackets and becomes a 1x1 array.
192+
A 2D array is delimited by square brackets, elements are separated by a comma,
193+
and rows are separated by a semicolon. Extra white spaces are ignored.
194+
195+
196+
.. runblock:: pycon
197+
198+
>>> str2array("5")
199+
>>> str2array("[1 2 3]")
200+
>>> str2array("[1 2; 3 4]")
201+
>>> str2array(" [ 1 , 2 ; 3 4 ] ")
202+
>>> str2array("[1; 2; 3]")
203+
204+
:seealso: :func:`array2str`
205+
"""
206+
207+
s = s.lstrip(" [")
208+
s = s.rstrip(" ]")
209+
values = []
210+
for row in s.split(";"):
211+
values.append([float(x) for x in re.split("[, ]+", row.strip())])
212+
return np.array(values)
169213

170214
def bresenham(p0: ArrayLike2, p1: ArrayLike2) -> Tuple[NDArray, NDArray]:
171215
"""

0 commit comments

Comments
 (0)
0