Dynamic fieldnames

조회 수: 57 (최근 30일)
Andre
Andre 2011년 4월 27일
hey all,
Im trying to create a new structure from an already existing structure using dynamic fieldnames - no joy however! I also tried using eval but I cant seem to get the syntax right.
struct1 has many sub structs but lets just assume that im trying to create a new structure using the character values from one of the fields of the old structure.
names = fieldnames(struct1.names)
field = fieldnames(struct1.field )
names = 'danny' 'edgar' 'larry'
field = 'one' 'two' 'three'
for i =1:length(names)
create = ('Newstruct.' names(i) . 'substruct' field(i))
eval (create )
end
in other words how do I use the character values from an already existing field as fieldnames in a loop?
I am able to use dynamic fieldnames and the eval statement to change the numeric parts of fieldnames but I cant seem to get them to work with all character fieldnames.
regards.

채택된 답변

Matt Fig
Matt Fig 2011년 4월 27일
Your code is a little confusing because it doesn't appear that you are assigning anything to the structure. Here is code that does assign values to the structure:
names = {'danny';'edgar';'larry'};
field = {'one';'two';'three'};
for ii =1:length(names)
Newstruct.(names{ii}).(field{ii}) = ii;
end
This is how I am interpreting your code. It could be that you mean this instead (or switch names and field...):
names = {'danny';'edgar';'larry'};
field = {'one';'two';'three'};
for ii =1:length(names)
Newstruct.(names{ii}) = field{ii};
end
If these aren't what you mean, please create one top level of the new structure by hand and show the code. Then perhaps we can figure out how to make it from names and values.
  댓글 수: 1
Andre
Andre 2011년 4월 28일
Thanks a bunch. your first for loop fixed things right up. the structure declaration bit was only representative of the real thing which is way more complicated.

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

추가 답변 (1개)

Walter Roberson
Walter Roberson 2011년 4월 27일
The closest I can seem to get to your existing code is that you seem want to execute:
Newstruct.(names{i}).substruct.(field{i})
which isn't going to do you much good as you that structure with those fields will not exist until you assign values there. Perhaps
Newstruct.(names{i}).substruct.(field{i}) = [];

카테고리

Help CenterFile Exchange에서 Variables에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by