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!

 採用された回答

Walter Roberson
Walter Roberson 2021 年 12 月 23 日

1 投票

Use setfield https://www.mathworks.com/matlabcentral/answers/1612735-have-an-error-with-dot-while-searching-value-in-struct#answer_856880

1 件のコメント

Cheng-Yu Lin
Cheng-Yu Lin 2021 年 12 月 24 日
It works! Thank you very much!

サインインしてコメントする。

その他の回答 (2 件)

Cris LaPierre
Cris LaPierre 2021 年 12 月 23 日

1 投票

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",".")
str = 3×1 string array
"TestParameter" "Measurement" "OutputValue"
TestParameter.(str(2)).(str(3)) = 3
TestParameter = struct with fields:
Measurement: [1×1 struct]

2 件のコメント

Cheng-Yu Lin
Cheng-Yu Lin 2021 年 12 月 24 日
Thank you very much!
Stephen23
Stephen23 2021 年 12 月 24 日
"but I don't believe you can add multiple levels at once"
Actually this is quite easy... see my answer.

サインインしてコメントする。

Stephen23
Stephen23 2021 年 12 月 23 日
編集済み: Stephen23 2021 年 12 月 23 日

1 投票

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)
S = struct with fields:
Measurement: [1×1 struct]
Checking:
S.Measurement.OutputValue
ans = 3
More robust code would not store those nested fieldnames as one string/charvector, but as separate fieldnames.

1 件のコメント

Cheng-Yu Lin
Cheng-Yu Lin 2021 年 12 月 24 日
It works! Thank you very much!

サインインしてコメントする。

カテゴリ

ヘルプ センター および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by