Setfield vs dot indexing for deeply nested struct

조회 수: 10 (최근 30일)
Michael Van de Graaff
Michael Van de Graaff 2022년 4월 25일
댓글: Walter Roberson 2022년 4월 25일
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.
  댓글 수: 1
Walter Roberson
Walter Roberson 2022년 4월 25일
Though it is not immediately obvious to me that you should permit such a situation to arise.

댓글을 달려면 로그인하십시오.

추가 답변 (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