How to use strings to access a multi-level structure?
이전 댓글 표시
I have some strings look like "TestParameter.Measurement.OutputValue" and values corresponding to each string. I want to creat a structure with the strings and assign the values to the structure.
For example, if the input string is "TestParameter.Measurement.OutputValue" and the corresponding value is 3, I hope do the thing as follow through a function:
TestParameter = struct;
TestParameter.Measurement.OutputValue = 3;
Also, the level of the structure is not fixed. How can I do what I want?
Thank you!
채택된 답변
추가 답변 (2개)
You can use strings to build a structure, but I don't believe you can add multiple levels at once, and I don't believe you can dynamically create the first level.
str = split("TestParameter.Measurement.OutputValue",".")
TestParameter.(str(2)).(str(3)) = 3
댓글 수: 2
Cheng-Yu Lin
2021년 12월 24일
Stephen23
2021년 12월 24일
"but I don't believe you can add multiple levels at once"
Actually this is quite easy... see my answer.
The variable name should not be dynamically accessed:
Arbitrarily nested fieldnames can be accessed at once using SETFIELD and GETFIELD, for example:
S = struct();
T = 'ignorethis.Measurement.OutputValue';
F = regexp(T,'[^.]+','match'); % or SPLIT()
S = setfield(S,F{2:end},3)
Checking:
S.Measurement.OutputValue
More robust code would not store those nested fieldnames as one string/charvector, but as separate fieldnames.
카테고리
도움말 센터 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!