0

I have MATLAB data files which contain multiple structs within struct that i want to import into python. In MATLAB, if main_struct is the main file, I can get down to the data I need by -

leaf1 = main_struct.tree1.leaf1

leaf2 = main_struct.tree1.leaf2

and so on. Now I want to import the .mat file containing struct in python and access leaf1 and leaf2. In python, I can load the mat files -

import scipy.io as sio

data = sio.loadmat("main_struct.mat",squeeze_me=True, struct_as_record=False);
tree1 = data.['tree1'];

How do I access the second struct in tree1 ?

2
  • a couple of handy functions in python are type() - which tells you what kind of object you have (dict, list, etc.) and dir() - which shows you the attributes, both built-in and user-defined. These two functions can help you "explore" an imported object and figure out exactly how to dereference it. Commented Apr 14, 2016 at 18:00
  • Also, I think you mean tree = data['tree1'] (no dot between data and [) Commented Apr 14, 2016 at 18:02

1 Answer 1

4

If in MATLAB you have the following

S = struct('tree1', struct('leaf1', {1}, 'leaf2', {2}));
save('filename.mat', '-struct', 'S')

If you use loadmat with struct_as_record = False, the result of data['tree1'] is a scipy.io.matlab.mio5_params.mat_struct object which can be used to access the nested structures.

You access the underlying data in the following way:

from scipy.io import loadmat

data = loadmat('filename.mat', squeeze_me=True, struct_as_record=False)

leaf1 = data['tree1'].leaf1
# 1

leaf2 = data['tree1'].leaf2
# 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.