Setfield vs dot indexing for deeply nested struct

2 visualizzazioni (ultimi 30 giorni)
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?

Risposta accettata

Stephen23
Stephen23 il 25 Apr 2022
Modificato: Stephen23 il 25 Apr 2022
"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 Commento
Walter Roberson
Walter Roberson il 25 Apr 2022
Though it is not immediately obvious to me that you should permit such a situation to arise.

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti


Release

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by