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 ?

Suever
  • 64,497
  • 14
  • 82
  • 101
NeuronGeek
  • 47
  • 5
  • 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. – gariepy Apr 14 '16 at 18:00
  • Also, I think you mean `tree = data['tree1']` (no dot between `data` and `[`) – gariepy Apr 14 '16 at 18:02

1 Answers1

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
Suever
  • 64,497
  • 14
  • 82
  • 101