How to load variable in a nested structure from file

17 views (last 30 days)
I have .mat files with data stored as nested structures and I would like to read some of the variables. Here is a MWE:
% Save a nested structure for a MWE
s(1).n(1).a = 1:10;
s(1).n(1).b = 11:20;
s(1).n(2).a = 21:30;
s(1).n(2).b = 31:40;
s(2).n(1).a = 41:50;
s(2).n(1).b = 51:60;
s(2).n(2).a = 61:70;
s(2).n(2).b = 71:80;
save('s.mat', 's');
In reality, the filename is a variable that the user defines. Here, let's say I have it as:
filename = 's.mat';
How do I load the data 1:10 stored in s(1).n(1).a?
Of course this works:
load(filename)
data = s(1).n(1).a;
But the point is avoiding to manually hardcode the s.
The following obviously does not work:
data2 = filename(1).n(1).a;
% Nor something like this:
data3 = load(filename,'????');
But it points in the direction of what I would like to do.
I have read the documentation on nested structures, the load function, etc.
Note: my files actually come from ControlDesk and the name of the file (s) always corresponds to the outer structure (s).

Accepted Answer

Stephen23
Stephen23 on 9 Aug 2018
Edited: Stephen23 on 9 Aug 2018
Accessing the data without knowing the name of the variable is easy, as long as there is only one variable saved in the .mat file: just use struct2cell like this:
>> filename = 's.mat';
>> T = load(filename);
>> C = struct2cell(T);
>> C{1}
ans =
1x2 struct array containing the fields:
n
>> C{1}(1).n(1).a
ans =
1 2 3 4 5 6 7 8 9 10
You could avoid the intermediate variable T, I just used it for clarity:
>> C = struct2cell(load(filename));
You should read this as well:
  3 Comments
Stephen23
Stephen23 on 9 Aug 2018
@Joan Vazquez: both struct2cell and cell2struct are quite handy when saving/loading structures, in situations like you have. Another option is to obtain the fieldname and use it as a dynamic fieldname:
>> filename = 's.mat';
>> T = load(filename);
>> F = fieldnames(T);
>> T.(F{1})(1).n(1).a
ans =
1 2 3 4 5 6 7 8 9 10
Joan Vazquez
Joan Vazquez on 9 Aug 2018
While your previous solution worked in my case, dynamic fieldnames are what is needed in the general case, I was not aware of this. Now, I can use a variable as a structure name! Thanks again.

Sign in to comment.

More Answers (1)

Christian Heigele
Christian Heigele on 9 Aug 2018
We use for data like this either xml-files or yaml-files. A good xml-parser is that one here: https://ch.mathworks.com/matlabcentral/fileexchange/12907-xml_io_tools?focused=5171820&tab=function
With this you can serialize your data into a file and reconstruct it later into another item: xml_write('out.xml', s); f = xml_read('out.xml');
If this is what you asked.

Categories

Find more on Structures in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!