Dynamic fieldnames

64 vues (au cours des 30 derniers jours)
Andre
Andre le 27 Avr 2011
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.

Réponse acceptée

Matt Fig
Matt Fig le 27 Avr 2011
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 commentaire
Andre
Andre le 28 Avr 2011
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.

Connectez-vous pour commenter.

Plus de réponses (1)

Walter Roberson
Walter Roberson le 27 Avr 2011
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}) = [];

Catégories

En savoir plus sur Variables dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by