Use string name as variable name for struct
조회 수: 12 (최근 30일)
이전 댓글 표시
I've got field names of a struct that are:
data.A__B__C
data.A__B__D
I want to make a new struct as such:
newData.A.B.C. = data.A__B__C
newData.A.B.D = data.A__B__D
I want to make new fields for my structs as follows:
names = fieldnames(data)
newNames = strrep(names,'__', '.')
for k = 1:length(names)
newData.(newNames{k,1}) = (data.(names{k,1}));
end
but I can't use the strings as fields for a new struct. I have to type every new variable by hand, of which I have over 100.
Is there some way that I can use the "newNames" variable to define a new struct with proper fields, instead of just 1 field with underscores?
댓글 수: 2
KSSV
2022년 2월 14일
Note that in the line:
newData.A.B.C.
A.B.C. is not a filed name, it is a structure again.
채택된 답변
Stephen23
2022년 2월 14일
편집: Stephen23
2022년 2월 14일
D.A__B__C = 0.5;
D.A__B__D = pi
F = fieldnames(D);
C = regexp(F,'_+','split');
Z = struct();
for k = 1:numel(F)
Z = setfield(Z,C{k}{:},D.(F{k}));
end
Z.A.B
KSSV's comment here is very important to understand, and explains why your approach does not work:
You incorrectly tried to create one long fieldname with dots in it. But in reality, you are trying to define nested structures, and each structure has its own fieldnames, they do not "share" one fieldname as you were attempting. The dots are not part of a fieldname.
추가 답변 (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!