Automatically load a struct from a struct with a variable name

조회 수: 54 (최근 30일)
Martin Möhring
Martin Möhring 2022년 11월 29일
댓글: Martin Möhring 2022년 11월 29일
Hi,
I am struggeling with hopefully only a small problem.
Maybe one of you could help me.
Problem:
I want to load automatically *.mat files with a variable name and get only a defined sub-struct out of it.
The loaded file is a struct and in this struct is a struct with a variable name according to the file-name.
And in this struct is another struct, which I need of course, with a fix fieldname.
Example:
  1. values = load (test1.mat) , result in workspace = values (struct)
  2. Content of values = struct with the name test1
  3. Content of test1 = 4 structs with fix field names (a, b, c, d)
Command for a file with a fix name is:
s = values.test1.a; % or .b, .c, .d
I am searching for a command to get only the contect of one sub-struct with the fix field name from a struct with a variable file-name.
And this should work without any further user input. (The path to the sub-struct should be generated automatically.)
Thank you.
  댓글 수: 2
Jan
Jan 2022년 11월 29일
"content of one sub-struct with the fix field name from a struct with a variable file-name" - which of the mentioned field names is fixed und which is variable? Is "test1" variable? If so, does it equal the file name?
Martin Möhring
Martin Möhring 2022년 11월 29일
Hi Jan,
yes "test1" is variable.
And yes this is the file name.

댓글을 달려면 로그인하십시오.

채택된 답변

Stephen23
Stephen23 2022년 11월 29일
편집: Stephen23 2022년 11월 29일
"The path to the sub-struct should be generated automatically"
Assuming that the MAT file contains exactly one variable (your structure), here is one simple approach that uses an intermediate cell array (the alternative is to fiddle around with fieldnames):
F = 'whateverfilename.mat'; % absolute/relative filename
C = struct2cell(load(F));
assert(isscalar(C),'Only one variable allowed!')
S = C{1}; % your structure
S.a
S.b
S.c
S.d
Note that accessing the data would be simpler and more robust if the structure name did not change with the filename. If you have the chance to redesign this data, just use a fixed variable name for the structure.

추가 답변 (1개)

Jan
Jan 2022년 11월 29일
file = 'test1.mat'
[~, name] = fileparts(file);
values = load(file);
subStruct = values.(name);
a = subStruct.a;
etc.

카테고리

Help CenterFile Exchange에서 Structures에 대해 자세히 알아보기

태그

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by