|
| 1 | +import re |
1 | 2 | import numpy as np
|
2 | 3 | from spatialmath import base
|
3 | 4 | from spatialmath.base.types import *
|
@@ -136,6 +137,17 @@ def array2str(
|
136 | 137 | :rtype: str
|
137 | 138 |
|
138 | 139 | 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` |
139 | 151 | """
|
140 | 152 | # convert to ndarray if not already
|
141 | 153 | if isinstance(X, (list, tuple)):
|
@@ -166,6 +178,38 @@ def format_row(x):
|
166 | 178 | s = brackets[0] + s + brackets[1]
|
167 | 179 | return s
|
168 | 180 |
|
| 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) |
169 | 213 |
|
170 | 214 | def bresenham(p0: ArrayLike2, p1: ArrayLike2) -> Tuple[NDArray, NDArray]:
|
171 | 215 | """
|
|
0 commit comments