Setfield vs dot indexing for deeply nested struct
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Michael Van de Graaff
el 25 de Abr. de 2022
Comentada: Walter Roberson
el 25 de Abr. de 2022
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 comentarios
Respuesta aceptada
Stephen23
el 25 de Abr. de 2022
Editada: Stephen23
el 25 de Abr. de 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 comentario
Walter Roberson
el 25 de Abr. de 2022
Though it is not immediately obvious to me that you should permit such a situation to arise.
Más respuestas (0)
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!