Setfield vs dot indexing for deeply nested struct

10 次查看(过去 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?

采纳的回答

Stephen23
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by