Rename a struct with a fieldname of another struct

조회 수: 6 (최근 30일)
Jan
Jan 2022년 8월 25일
댓글: Jan 2022년 8월 25일
Hi, I want to load a struct and the name of the struct is for example 'abc' and after that i want to load some fields of the struct like
data_array(1) = abc.data_1
data_array(2) = abc.data_2
but now my problem is that the struct isn't allways called abc...
so i want to use the name of the struct however it's called to load data_1 and data_2 in this case
  댓글 수: 2
Stephen23
Stephen23 2022년 8월 25일
편집: Stephen23 2022년 8월 25일
"but now my problem is that the struct isn't allways called abc..."
And that is the cause of your difficulties, which will force you into writing slow, complex, inefficient code just to access your data: https://www.mathworks.com/matlabcentral/answers/304528-tutorial-why-variables-should-not-be-named-dynamically-eval
You forgot to tell us the most important information: how did you get all of these differently-named structures into the workspace? For example, if you LOADed them, then you can avoid the issue by LOADing into an output variable:
S = load(..)
Jan
Jan 2022년 8월 25일
Yes, with S = load(...)

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

답변 (1개)

Robert U
Robert U 2022년 8월 25일
Hi Jan,
it is good practice to load external data into a structure array such that the variable name is connected to the actual function/script whereas the top fieldname is the name of the saved struct. Then, you can use fieldnames()-command to retrieve the name of the loaded struct and continue work on that.
inputStruct = load(myFilename) % load file
fieldsInputStruct = fieldnames(inputStruct) % retrieve the name of the saved struct
inputStruct.(fieldsInputStruct{1}) % use dynamic expressions to address the fieldnames
See for more information:
Kind regards,
Robert
  댓글 수: 2
Jan
Jan 2022년 8월 25일
Thank you, its a very nice solution!
Stephen23
Stephen23 2022년 8월 25일
Assuming only one variable per MAT file:
C = struct2cell(load(..))
M = C{1}

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

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by