How to load variable in a nested structure from file
12 次查看(过去 30 天)
显示 更早的评论
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).
0 个评论
采纳的回答
Stephen23
2018-8-9
编辑:Stephen23
2018-8-9
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 个评论
Stephen23
2018-8-9
@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
更多回答(1 个)
Christian Heigele
2018-8-9
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.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!