How to load variable in a nested structure from file

조회 수: 10 (최근 30일)
Joan Vazquez
Joan Vazquez 2018년 8월 9일
댓글: Joan Vazquez 2018년 8월 9일
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
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.

카테고리

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