Setfield vs dot indexing for deeply nested struct
2 次查看(过去 30 天)
显示 更早的评论
Supose i have the following struct and an associated string:
s.f1.f2.f3.f4.f5 = data;
tmp_string = 's.f1.f2.f3.f4.f5';
So, just to be clear, eval(tmp_string) yields data, But eval is bad and i dont use it.
Now suppose I wish to programmatically replace data with newdata. Currently I do this by
sparts = strsplit(tmp_string,'.'); % yields sparts = [{s},{f1},{f2},{f3},{f4},{f5}];
s = setfield(s,sparts{2:end}) = newdata;
However, Matalb suggests I use dot notation and dynamic fieldnames instead of setfield and getfield whenever possible. I think this is a situation where setfield and getfield actually are prefereable, but I'm not sure. Can I do this more cleanly and efficiently with dot notation?
0 个评论
采纳的回答
Stephen23
2022-4-25
编辑:Stephen23
2022-4-25
"However, Matalb suggests I use dot notation and dynamic fieldnames instead of setfield and getfield whenever possible."
Ignore it, it is just a suggestion. The static code analyzer cannot understand the entire context of why particular code is being used, it just follows relatively simple rules. Disable the warning on that line (right click, "Supress... on this line").
"I think this is a situation where setfield and getfield actually are prefereable.."
Yes, that seems reasonable.
"Can I do this more cleanly and efficiently with dot notation?"
No.
1 个评论
Walter Roberson
2022-4-25
Though it is not immediately obvious to me that you should permit such a situation to arise.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!