Skip to content

Commit 22fe815

Browse files
committed
From a mat file, structs are converted to namedtuples
1 parent fa1162d commit 22fe815

File tree

1 file changed

+18
-2
lines changed

1 file changed

+18
-2
lines changed

roboticstoolbox/tools/data.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,27 @@ def rtb_load_matfile(filename):
2121
- Uses SciPy ``io.loadmat`` to do the work.
2222
- If the filename has no path component, eg. ``map1.mat`, it will be
2323
first be looked for in the folder ``roboticstoolbox/data``.
24+
- MATLAB structs are converted to Python named tuples, so the elements
25+
can be accessed using dot notation.
2426
2527
:seealso: :func:`path_to_datafile`
2628
"""
2729
from scipy.io import loadmat
28-
29-
return rtb_load_data(filename, loadmat, squeeze_me=True, struct_as_record=False)
30+
from scipy.io.matlab.mio5_params import mat_struct
31+
from collections import namedtuple
32+
33+
# get results as a dict
34+
data = rtb_load_data(filename, loadmat, squeeze_me=True, struct_as_record=False)
35+
36+
# if elements are a scipy.io.matlab.mio5_params.mat_struct, that is, they
37+
# were a MATLAB struct, convert them to a namedtuple
38+
for key, value in data.items():
39+
if isinstance(value, mat_struct):
40+
print('fixing')
41+
nt = namedtuple("matstruct", value._fieldnames)
42+
data[key] = nt(*[getattr(value, n) for n in value._fieldnames])
43+
44+
return data
3045

3146
def rtb_load_jsonfile(filename):
3247
"""
@@ -131,6 +146,7 @@ def rtb_path_to_datafile(*filename, local=True):
131146

132147
if __name__ == "__main__":
133148

149+
house = rtb_load_matfile("data/house.mat");
134150
a = rtb_loadmat("map1.mat")
135151
print(a)
136152
a = rtb_loadmat("data/map1.mat")

0 commit comments

Comments
 (0)