Dynamic fieldnames
68 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
0 Kommentare
Akzeptierte Antwort
Matt Fig
am 27 Apr. 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.
Weitere Antworten (1)
Walter Roberson
am 27 Apr. 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}) = [];
0 Kommentare
Siehe auch
Kategorien
Mehr zu Variables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!