How to load variable in a nested structure from file
Show older comments
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
More Answers (1)
Christian Heigele
on 9 Aug 2018
0 votes
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
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!