How to modify field any levels deep in a structure with a string

Ive been trying to dynamically modify the value of a field in a struct that can be any number of levels deep and was hoping to build a string that led to it, for example str = "x.y.z" and then use app.(str) to change its value. But it seems that matlab only lets you use strings to go into a maximum of 1 field deep, so app.(str) would work for str = "x" , but not for str = 'x.y.z'. Adding more periods to go deeper gives errors.
Because i cant know how deep any field will be, i cant break the string into its fields and use something like app.(str1).(str2).str(3), hence the need to have been able to build the string and call it at once with app.(longStr)
Any suggestions?

 採用された回答

Stephen23
Stephen23 2020 年 10 月 12 日
編集済み: Stephen23 2020 年 10 月 12 日

0 投票

"i cant break the string into its fields and use something like app.(str1).(str2).str(3)..."
You cannot use dynamic fieldnames like that, but you can easily use getfield to do exactly what you want:
>> S.A.B.C = 123;
>> str = 'A.B.C';
>> spl = regexp(str,'\.','split');
>> val = getfield(S,spl{:})
val = 123
And of course setfield does the same for assigning a value. If you have control over the data design, it might be better to store the fieldnames separately anyway (i.e. like spl above).
See also:

4 件のコメント

Sergio Huerta
Sergio Huerta 2020 年 10 月 12 日
Sorry but im not following, how does getfield help me to modify a field any number of levels deep? Reading the value is a breeze, the problem is modifying it
Sergio Huerta
Sergio Huerta 2020 年 10 月 12 日
Thanks so much, i was testing out passing cells, string arrays, etc with setfield, but im new to matlab and would never have known about spl{:}.
Stephen23
Stephen23 2020 年 10 月 12 日
編集済み: Stephen23 2020 年 10 月 12 日
"Reading the value is a breeze, the problem is modifying it"
As I wrote in my answer: "And of course setfield does the same for assigning a value". Using the example data from my answer:
>> S = setfield(S,spl{:},'cat');
>> S.A.B.C % checking
ans = cat
It works for me. Give it a try!
Stephen23
Stephen23 2020 年 10 月 12 日
"...would never have known about spl{:}"
That is why I gave the links: read them to know how useful comma-separated lists are!

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

その他の回答 (0 件)

カテゴリ

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

質問済み:

2020 年 10 月 12 日

コメント済み:

2020 年 10 月 12 日

Community Treasure Hunt

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

Start Hunting!

Translated by