Extracting everything from a structure

45 visualizzazioni (ultimi 30 giorni)
Jeff
Jeff il 3 Giu 2011
Is there a built in function to extract everything from a structure?
For example if I have a structure:
struct_name.struct_element1 = 7;
struct_name.struct_element2 = 'abc';
Then later I want create variables for every element of struct_name but I'm unaware of how many elements are in "struct_name" and what their names are. I wrote the following code to solve my problem but I feel there might be a more elegant solution or a built in function:
struct_field_names = fieldnames(struct_name);
for k = 1:length(struct_field_names)
eval([struct_field_names{k}, ' =...
struct_name.',struct_field_names{k}, ';']);
end

Risposta accettata

Jeff
Jeff il 3 Giu 2011
Ahh I searched more rigorously and found this discussion:

Più risposte (3)

Jan
Jan il 3 Giu 2011
Take this into account:
struct_name.struct_name = 1;
struct_name.data2 = 2;
Now the result of the creation of variables depends on the order of fields - a dangerous programming method.
So follow Oleg's link and avoid the dynamic creation of variables. Using ISFIELD and "dynamic fieldnames" is a more reliable technique.

Oleg Komarov
Oleg Komarov il 3 Giu 2011
Think if you had 20 fields in the struct, you would end up populating the workspace with 20 different variables which you will have eiter use by manual referencing or by using eval.
Both methods are nightmare, but you're welcome to abuse eval for some time. The problem comes later when you have to mantain your code.
  4 Commenti
Jeff
Jeff il 3 Giu 2011
Good points. I can create a list of variables needed rather than relying on fieldnames and add error handling for needed variables that don't exist. The function suggested on the link I posted below uses "assignin" within a for loop in a function so I believe that eliminates the concern for the assignment creating the iterator variable.
Walter Roberson
Walter Roberson il 3 Giu 2011
The problem isn't in creating the iterator variable: the problem would be that on the next iteration of the loop, the variable you _thought_ you copied from the structure would get overwritten.

Accedi per commentare.


Sean de Wolski
Sean de Wolski il 3 Giu 2011
doc struct2cell
?
  2 Commenti
Jeff
Jeff il 3 Giu 2011
That does well to get the values but it loses the names of the elements :-(
Sean de Wolski
Sean de Wolski il 3 Giu 2011
The values and their indeces should be all you need, per the FAQ link.

Accedi per commentare.

Categorie

Scopri di più su Structures in Help Center e File Exchange

Prodotti

Community Treasure Hunt

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

Start Hunting!

Translated by