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).

采纳的回答

Stephen23
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
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
Joan Vazquez
Joan Vazquez 2018-8-9
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.

请先登录,再进行评论。

更多回答(1 个)

Christian Heigele
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.

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by